Welcome to mirror list, hosted at ThFree Co, Russian Federation.

imp.rs « device_provider « src « ndi « net - github.com/sdroege/gst-plugin-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f67d1e55e3bee9724a7a7a5bbdc01dfb55637f43 (plain)
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
// SPDX-License-Identifier: MPL-2.0

use gst::prelude::*;
use gst::subclass::prelude::*;

use once_cell::sync::OnceCell;

use std::sync::atomic;
use std::sync::Mutex;
use std::thread;

use once_cell::sync::Lazy;

use crate::ndi;

static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
    gst::DebugCategory::new(
        "ndideviceprovider",
        gst::DebugColorFlags::empty(),
        Some("NewTek NDI Device Provider"),
    )
});

#[derive(Debug)]
pub struct DeviceProvider {
    thread: Mutex<Option<thread::JoinHandle<()>>>,
    current_devices: Mutex<Vec<super::Device>>,
    find: Mutex<Option<ndi::FindInstance>>,
    is_running: atomic::AtomicBool,
}

#[glib::object_subclass]
impl ObjectSubclass for DeviceProvider {
    const NAME: &'static str = "GstNdiDeviceProvider";
    type Type = super::DeviceProvider;
    type ParentType = gst::DeviceProvider;

    fn new() -> Self {
        Self {
            thread: Mutex::new(None),
            current_devices: Mutex::new(vec![]),
            find: Mutex::new(None),
            is_running: atomic::AtomicBool::new(false),
        }
    }
}

impl ObjectImpl for DeviceProvider {}

impl GstObjectImpl for DeviceProvider {}

impl DeviceProviderImpl for DeviceProvider {
    fn metadata() -> Option<&'static gst::subclass::DeviceProviderMetadata> {
        static METADATA: Lazy<gst::subclass::DeviceProviderMetadata> = Lazy::new(|| {
            gst::subclass::DeviceProviderMetadata::new("NewTek NDI Device Provider",
            "Source/Audio/Video/Network",
            "NewTek NDI Device Provider",
            "Ruben Gonzalez <rubenrua@teltek.es>, Daniel Vilar <daniel.peiteado@teltek.es>, Sebastian Dröge <sebastian@centricular.com>")
        });

        Some(&*METADATA)
    }

    fn probe(&self) -> Vec<gst::Device> {
        self.current_devices
            .lock()
            .unwrap()
            .iter()
            .map(|d| d.clone().upcast())
            .collect()
    }

    fn start(&self) -> Result<(), gst::LoggableError> {
        if let Err(err) = crate::ndi::load() {
            return Err(gst::loggable_error!(CAT, "{}", err));
        }

        let mut thread_guard = self.thread.lock().unwrap();
        if thread_guard.is_some() {
            gst::log!(CAT, imp: self, "Device provider already started");
            return Ok(());
        }

        self.is_running.store(true, atomic::Ordering::SeqCst);

        let imp_weak = self.downgrade();
        let mut first = true;
        *thread_guard = Some(thread::spawn(move || {
            {
                let imp = match imp_weak.upgrade() {
                    None => return,
                    Some(imp) => imp,
                };

                let mut find_guard = imp.find.lock().unwrap();
                if find_guard.is_some() {
                    gst::log!(CAT, imp: imp, "Already started");
                    return;
                }

                let find = match ndi::FindInstance::builder().build() {
                    None => {
                        gst::error!(CAT, imp: imp, "Failed to create Find instance");
                        return;
                    }
                    Some(find) => find,
                };
                *find_guard = Some(find);
            }

            loop {
                let imp = match imp_weak.upgrade() {
                    None => return,
                    Some(imp) => imp,
                };

                if !imp.is_running.load(atomic::Ordering::SeqCst) {
                    break;
                }

                imp.poll(first);
                first = false;
            }
        }));

        Ok(())
    }

    fn stop(&self) {
        if let Some(_thread) = self.thread.lock().unwrap().take() {
            self.is_running.store(false, atomic::Ordering::SeqCst);
            // Don't actually join because that might take a while
        }
    }
}

impl DeviceProvider {
    fn poll(&self, first: bool) {
        let mut find_guard = self.find.lock().unwrap();
        let find = match *find_guard {
            None => return,
            Some(ref mut find) => find,
        };

        if !find.wait_for_sources(if first { 1000 } else { 5000 }) {
            gst::trace!(CAT, imp: self, "No new sources found");
            return;
        }

        let sources = find.get_current_sources();
        let mut sources = sources.iter().map(|s| s.to_owned()).collect::<Vec<_>>();

        let mut current_devices_guard = self.current_devices.lock().unwrap();
        let mut expired_devices = vec![];
        let mut remaining_sources = vec![];

        // First check for each device we previously knew if it's still available
        for old_device in &*current_devices_guard {
            let old_device_imp = old_device.imp();
            let old_source = old_device_imp.source.get().unwrap();

            if !sources.contains(old_source) {
                gst::log!(CAT, imp: self, "Source {:?} disappeared", old_source);
                expired_devices.push(old_device.clone());
            } else {
                // Otherwise remember that we had it before already and don't have to announce it
                // again. After the loop we're going to remove these all from the sources vec.
                remaining_sources.push(old_source.to_owned());
            }
        }

        for remaining_source in remaining_sources {
            sources.retain(|s| s != &remaining_source);
        }

        // Remove all expired devices from the list of cached devices
        current_devices_guard.retain(|d| !expired_devices.contains(d));
        // And also notify the device provider of them having disappeared
        for old_device in expired_devices {
            self.obj().device_remove(&old_device);
        }

        // Now go through all new devices and announce them
        for source in sources {
            gst::log!(CAT, imp: self, "Source {:?} appeared", source);
            let device = super::Device::new(&source);
            self.obj().device_add(&device);
            current_devices_guard.push(device);
        }
    }
}

#[derive(Debug)]
pub struct Device {
    source: OnceCell<ndi::Source<'static>>,
}

#[glib::object_subclass]
impl ObjectSubclass for Device {
    const NAME: &'static str = "GstNdiDevice";
    type Type = super::Device;
    type ParentType = gst::Device;

    fn new() -> Self {
        Self {
            source: OnceCell::new(),
        }
    }
}

impl ObjectImpl for Device {}

impl GstObjectImpl for Device {}

impl DeviceImpl for Device {
    fn create_element(&self, name: Option<&str>) -> Result<gst::Element, gst::LoggableError> {
        let source_info = self.source.get().unwrap();
        let element = glib::Object::with_type(
            crate::ndisrc::NdiSrc::static_type(),
            &[
                ("name", &name),
                ("ndi-name", &source_info.ndi_name()),
                ("url-address", &source_info.url_address()),
            ],
        )
        .dynamic_cast::<gst::Element>()
        .unwrap();

        Ok(element)
    }
}

impl super::Device {
    fn new(source: &ndi::Source<'_>) -> super::Device {
        let display_name = source.ndi_name();
        let device_class = "Source/Audio/Video/Network";

        let element_class =
            glib::Class::<gst::Element>::from_type(crate::ndisrc::NdiSrc::static_type()).unwrap();
        let templ = element_class.pad_template("src").unwrap();
        let caps = templ.caps();

        // Put the url-address into the extra properties
        let extra_properties = gst::Structure::builder("properties")
            .field("ndi-name", &source.ndi_name())
            .field("url-address", &source.url_address())
            .build();

        let device = glib::Object::new::<super::Device>(&[
            ("caps", &caps),
            ("display-name", &display_name),
            ("device-class", &device_class),
            ("properties", &extra_properties),
        ]);

        let imp = device.imp();
        imp.source.set(source.to_owned()).unwrap();

        device
    }
}