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

use std::borrow::Cow;

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

use super::prelude::*;
use crate::{ffi, Device, DeviceProvider, LoggableError};

#[derive(Debug, Clone)]
pub struct DeviceProviderMetadata {
    long_name: Cow<'static, str>,
    classification: Cow<'static, str>,
    description: Cow<'static, str>,
    author: Cow<'static, str>,
    additional: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>,
}

impl DeviceProviderMetadata {
    pub fn new(long_name: &str, classification: &str, description: &str, author: &str) -> Self {
        Self {
            long_name: Cow::Owned(long_name.into()),
            classification: Cow::Owned(classification.into()),
            description: Cow::Owned(description.into()),
            author: Cow::Owned(author.into()),
            additional: Cow::Borrowed(&[]),
        }
    }

    pub fn with_additional(
        long_name: &str,
        classification: &str,
        description: &str,
        author: &str,
        additional: &[(&str, &str)],
    ) -> Self {
        Self {
            long_name: Cow::Owned(long_name.into()),
            classification: Cow::Owned(classification.into()),
            description: Cow::Owned(description.into()),
            author: Cow::Owned(author.into()),
            additional: additional
                .iter()
                .copied()
                .map(|(key, value)| (Cow::Owned(key.into()), Cow::Owned(value.into())))
                .collect(),
        }
    }

    pub const fn with_cow(
        long_name: Cow<'static, str>,
        classification: Cow<'static, str>,
        description: Cow<'static, str>,
        author: Cow<'static, str>,
        additional: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>,
    ) -> Self {
        Self {
            long_name,
            classification,
            description,
            author,
            additional,
        }
    }
}

pub trait DeviceProviderImpl: DeviceProviderImplExt + GstObjectImpl + Send + Sync {
    fn metadata() -> Option<&'static DeviceProviderMetadata> {
        None
    }

    /// Returns a list of devices that are currently available.
    ///  This should never block. The devices should not have a parent and should
    ///  be floating.
    fn probe(&self) -> Vec<Device> {
        self.parent_probe()
    }

    /// Starts providering the devices. This will cause `GST_MESSAGE_DEVICE_ADDED`
    /// and `GST_MESSAGE_DEVICE_REMOVED` messages to be posted on the provider's bus
    /// when devices are added or removed from the system.
    ///
    /// Since the [`DeviceProvider`][crate::DeviceProvider] is a singleton,
    /// [`DeviceProviderExt::start()`][crate::prelude::DeviceProviderExt::start()] may already have been called by another
    /// user of the object, [`DeviceProviderExt::stop()`][crate::prelude::DeviceProviderExt::stop()] needs to be called the same
    /// number of times.
    ///
    /// After this function has been called, [`DeviceProviderExtManual::devices()`][crate::prelude::DeviceProviderExtManual::devices()] will
    /// return the same objects that have been received from the
    /// `GST_MESSAGE_DEVICE_ADDED` messages and will no longer probe.
    ///
    /// # Returns
    ///
    /// [`true`] if the device providering could be started
    fn start(&self) -> Result<(), LoggableError> {
        self.parent_start()
    }

    /// Decreases the use-count by one. If the use count reaches zero, this
    /// [`DeviceProvider`][crate::DeviceProvider] will stop providering the devices. This needs to be
    /// called the same number of times that [`DeviceProviderExt::start()`][crate::prelude::DeviceProviderExt::start()] was called.
    fn stop(&self) {
        self.parent_stop()
    }
}

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

pub trait DeviceProviderImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_probe(&self) -> Vec<Device> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstDeviceProviderClass;
            if let Some(f) = (*parent_class).probe {
                FromGlibPtrContainer::from_glib_full(f(self
                    .obj()
                    .unsafe_cast_ref::<DeviceProvider>()
                    .to_glib_none()
                    .0))
            } else {
                Vec::new()
            }
        }
    }

    fn parent_start(&self) -> Result<(), LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstDeviceProviderClass;
            let f = (*parent_class).start.ok_or_else(|| {
                loggable_error!(crate::CAT_RUST, "Parent function `start` is not defined")
            })?;
            result_from_gboolean!(
                f(self
                    .obj()
                    .unsafe_cast_ref::<DeviceProvider>()
                    .to_glib_none()
                    .0),
                crate::CAT_RUST,
                "Failed to start the device provider using the parent function"
            )
        }
    }

    fn parent_stop(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstDeviceProviderClass;
            if let Some(f) = (*parent_class).stop {
                f(self
                    .obj()
                    .unsafe_cast_ref::<DeviceProvider>()
                    .to_glib_none()
                    .0);
            }
        }
    }
}

impl<T: DeviceProviderImpl> DeviceProviderImplExt for T {}

unsafe impl<T: DeviceProviderImpl> IsSubclassable<T> for DeviceProvider {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.probe = Some(device_provider_probe::<T>);
        klass.start = Some(device_provider_start::<T>);
        klass.stop = Some(device_provider_stop::<T>);

        unsafe {
            if let Some(metadata) = T::metadata() {
                ffi::gst_device_provider_class_set_metadata(
                    klass,
                    metadata.long_name.to_glib_none().0,
                    metadata.classification.to_glib_none().0,
                    metadata.description.to_glib_none().0,
                    metadata.author.to_glib_none().0,
                );

                for (key, value) in metadata.additional.iter() {
                    ffi::gst_device_provider_class_add_metadata(
                        klass,
                        key.to_glib_none().0,
                        value.to_glib_none().0,
                    );
                }
            }
        }
    }
}

unsafe extern "C" fn device_provider_probe<T: DeviceProviderImpl>(
    ptr: *mut ffi::GstDeviceProvider,
) -> *mut glib::ffi::GList {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.probe().to_glib_full()
}

unsafe extern "C" fn device_provider_start<T: DeviceProviderImpl>(
    ptr: *mut ffi::GstDeviceProvider,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    match imp.start() {
        Ok(()) => true,
        Err(err) => {
            err.log_with_imp(imp);
            false
        }
    }
    .into_glib()
}

unsafe extern "C" fn device_provider_stop<T: DeviceProviderImpl>(ptr: *mut ffi::GstDeviceProvider) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.stop();
}