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
// Copyright (C) 2017 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use futures_channel::mpsc::{self, UnboundedReceiver};
use futures_core::Stream;
use futures_util::{future, StreamExt};
use glib;
use glib::prelude::*;
use glib::source::{Continue, Priority, SourceId};
use glib::translate::*;
use glib_sys;
use glib_sys::{gboolean, gpointer};
use gst_sys;
use std::cell::RefCell;
use std::mem::transmute;
use std::pin::Pin;
use std::task::{Context, Poll};

use Bus;
use BusSyncReply;
use Message;
use MessageType;

unsafe extern "C" fn trampoline_watch<F: FnMut(&Bus, &Message) -> Continue + 'static>(
    bus: *mut gst_sys::GstBus,
    msg: *mut gst_sys::GstMessage,
    func: gpointer,
) -> gboolean {
    let func: &RefCell<F> = &*(func as *const RefCell<F>);
    (&mut *func.borrow_mut())(&from_glib_borrow(bus), &Message::from_glib_borrow(msg)).to_glib()
}

unsafe extern "C" fn destroy_closure_watch<F: FnMut(&Bus, &Message) -> Continue + 'static>(
    ptr: gpointer,
) {
    Box::<RefCell<F>>::from_raw(ptr as *mut _);
}

fn into_raw_watch<F: FnMut(&Bus, &Message) -> Continue + 'static>(func: F) -> gpointer {
    #[allow(clippy::type_complexity)]
    let func: Box<RefCell<F>> = Box::new(RefCell::new(func));
    Box::into_raw(func) as gpointer
}

unsafe extern "C" fn trampoline_sync<
    F: Fn(&Bus, &Message) -> BusSyncReply + Send + Sync + 'static,
>(
    bus: *mut gst_sys::GstBus,
    msg: *mut gst_sys::GstMessage,
    func: gpointer,
) -> gst_sys::GstBusSyncReply {
    let f: &F = &*(func as *const F);
    let res = f(&from_glib_borrow(bus), &Message::from_glib_borrow(msg)).to_glib();

    if res == gst_sys::GST_BUS_DROP {
        gst_sys::gst_mini_object_unref(msg as *mut _);
    }

    res
}

unsafe extern "C" fn destroy_closure_sync<
    F: Fn(&Bus, &Message) -> BusSyncReply + Send + Sync + 'static,
>(
    ptr: gpointer,
) {
    Box::<F>::from_raw(ptr as *mut _);
}

fn into_raw_sync<F: Fn(&Bus, &Message) -> BusSyncReply + Send + Sync + 'static>(
    func: F,
) -> gpointer {
    let func: Box<F> = Box::new(func);
    Box::into_raw(func) as gpointer
}

impl Bus {
    /// Adds a bus signal watch to the default main context with the given `priority`
    /// (e.g. `G_PRIORITY_DEFAULT`). It is also possible to use a non-default main
    /// context set up using `glib::MainContext::push_thread_default`
    /// (before one had to create a bus watch source and attach it to the desired
    /// main context 'manually').
    ///
    /// After calling this statement, the bus will emit the "message" signal for each
    /// message posted on the bus when the main loop is running.
    ///
    /// This function may be called multiple times. To clean up, the caller is
    /// responsible for calling `Bus::remove_signal_watch` as many times as this
    /// function is called.
    ///
    /// There can only be a single bus watch per bus, you must remove any signal
    /// watch before you can set another type of watch.
    ///
    /// MT safe.
    /// ## `priority`
    /// The priority of the watch.
    pub fn add_signal_watch_full(&self, priority: Priority) {
        unsafe {
            gst_sys::gst_bus_add_signal_watch_full(self.to_glib_none().0, priority.to_glib());
        }
    }

    /// Create watch for this bus. The GSource will be dispatched whenever
    /// a message is on the bus. After the GSource is dispatched, the
    /// message is popped off the bus and unreffed.
    ///
    /// # Returns
    ///
    /// a `glib::Source` that can be added to a mainloop.
    pub fn create_watch<F>(&self, name: Option<&str>, priority: Priority, func: F) -> glib::Source
    where
        F: FnMut(&Bus, &Message) -> Continue + Send + 'static,
    {
        skip_assert_initialized!();
        unsafe {
            let source = gst_sys::gst_bus_create_watch(self.to_glib_none().0);
            glib_sys::g_source_set_callback(
                source,
                Some(transmute::<
                    _,
                    unsafe extern "C" fn(glib_sys::gpointer) -> i32,
                >(trampoline_watch::<F> as *const ())),
                into_raw_watch(func),
                Some(destroy_closure_watch::<F>),
            );
            glib_sys::g_source_set_priority(source, priority.to_glib());

            if let Some(name) = name {
                glib_sys::g_source_set_name(source, name.to_glib_none().0);
            }

            from_glib_full(source)
        }
    }

    /// Adds a bus watch to the default main context with the default priority
    /// (`G_PRIORITY_DEFAULT`). It is also possible to use a non-default main
    /// context set up using `glib::MainContext::push_thread_default` (before
    /// one had to create a bus watch source and attach it to the desired main
    /// context 'manually').
    ///
    /// This function is used to receive asynchronous messages in the main loop.
    /// There can only be a single bus watch per bus, you must remove it before you
    /// can set a new one.
    ///
    /// The bus watch will only work if a GLib main loop is being run.
    ///
    /// The watch can be removed using `Bus::remove_watch` or by returning `false`
    /// from `func`. If the watch was added to the default main context it is also
    /// possible to remove the watch using `glib::Source::remove`.
    ///
    /// The bus watch will take its own reference to the `self`, so it is safe to unref
    /// `self` using `GstObjectExt::unref` after setting the bus watch.
    ///
    /// MT safe.
    /// ## `func`
    /// A function to call when a message is received.
    /// ## `user_data`
    /// user data passed to `func`.
    ///
    /// # Returns
    ///
    /// The event source id or 0 if `self` already got an event source.
    pub fn add_watch<F>(&self, func: F) -> Result<SourceId, glib::BoolError>
    where
        F: FnMut(&Bus, &Message) -> Continue + Send + 'static,
    {
        unsafe {
            let res = gst_sys::gst_bus_add_watch_full(
                self.to_glib_none().0,
                glib_sys::G_PRIORITY_DEFAULT,
                Some(trampoline_watch::<F>),
                into_raw_watch(func),
                Some(destroy_closure_watch::<F>),
            );

            if res == 0 {
                Err(glib_bool_error!("Bus already has a watch"))
            } else {
                Ok(from_glib(res))
            }
        }
    }

    pub fn add_watch_local<F>(&self, func: F) -> Result<SourceId, glib::BoolError>
    where
        F: FnMut(&Bus, &Message) -> Continue + 'static,
    {
        unsafe {
            assert!(glib::MainContext::ref_thread_default().is_owner());

            let res = gst_sys::gst_bus_add_watch_full(
                self.to_glib_none().0,
                glib_sys::G_PRIORITY_DEFAULT,
                Some(trampoline_watch::<F>),
                into_raw_watch(func),
                Some(destroy_closure_watch::<F>),
            );

            if res == 0 {
                Err(glib_bool_error!("Bus already has a watch"))
            } else {
                Ok(from_glib(res))
            }
        }
    }

    /// Sets the synchronous handler on the bus. The function will be called
    /// every time a new message is posted on the bus. Note that the function
    /// will be called in the same thread context as the posting object. This
    /// function is usually only called by the creator of the bus. Applications
    /// should handle messages asynchronously using the gst_bus watch and poll
    /// functions.
    ///
    /// Before 1.16.3 it was not possible to replace an existing handler and
    /// clearing an existing handler with `None` was not thread-safe.
    /// ## `func`
    /// The handler function to install
    /// ## `user_data`
    /// User data that will be sent to the handler function.
    /// ## `notify`
    /// called when `user_data` becomes unused
    pub fn set_sync_handler<F>(&self, func: F)
    where
        F: Fn(&Bus, &Message) -> BusSyncReply + Send + Sync + 'static,
    {
        use once_cell::sync::Lazy;
        static SET_ONCE_QUARK: Lazy<glib::Quark> =
            Lazy::new(|| glib::Quark::from_string("gstreamer-rs-sync-handler"));

        unsafe {
            let bus = self.to_glib_none().0;

            // This is not thread-safe before 1.16.3, see
            // https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/merge_requests/416
            if ::version() < (1, 16, 3, 0) {
                if !gobject_sys::g_object_get_qdata(bus as *mut _, SET_ONCE_QUARK.to_glib())
                    .is_null()
                {
                    panic!("Bus sync handler can only be set once");
                }

                gobject_sys::g_object_set_qdata(
                    bus as *mut _,
                    SET_ONCE_QUARK.to_glib(),
                    1 as *mut _,
                );
            }

            gst_sys::gst_bus_set_sync_handler(
                bus,
                Some(trampoline_sync::<F>),
                into_raw_sync(func),
                Some(destroy_closure_sync::<F>),
            )
        }
    }

    pub fn unset_sync_handler(&self) {
        // This is not thread-safe before 1.16.3, see
        // https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/merge_requests/416
        if ::version() < (1, 16, 3, 0) {
            return;
        }

        unsafe {
            use std::ptr;

            gst_sys::gst_bus_set_sync_handler(self.to_glib_none().0, None, ptr::null_mut(), None)
        }
    }

    pub fn iter(&self) -> Iter {
        self.iter_timed(0.into())
    }

    pub fn iter_timed(&self, timeout: ::ClockTime) -> Iter {
        Iter { bus: self, timeout }
    }

    pub fn iter_filtered<'a>(
        &'a self,
        msg_types: &'a [MessageType],
    ) -> impl Iterator<Item = Message> + 'a {
        self.iter_timed_filtered(0.into(), msg_types)
    }

    pub fn iter_timed_filtered<'a>(
        &'a self,
        timeout: ::ClockTime,
        msg_types: &'a [MessageType],
    ) -> impl Iterator<Item = Message> + 'a {
        self.iter_timed(timeout)
            .filter(move |msg| msg_types.contains(&msg.get_type()))
    }

    /// Get a message from the bus whose type matches the message type mask `types`,
    /// waiting up to the specified timeout (and discarding any messages that do not
    /// match the mask provided).
    ///
    /// If `timeout` is 0, this function behaves like `Bus::pop_filtered`. If
    /// `timeout` is `GST_CLOCK_TIME_NONE`, this function will block forever until a
    /// matching message was posted on the bus.
    /// ## `timeout`
    /// a timeout in nanoseconds, or GST_CLOCK_TIME_NONE to wait forever
    /// ## `types`
    /// message types to take into account, GST_MESSAGE_ANY for any type
    ///
    /// # Returns
    ///
    /// a `Message` matching the
    ///  filter in `types`, or `None` if no matching message was found on
    ///  the bus until the timeout expired. The message is taken from
    ///  the bus and needs to be unreffed with `Message::unref` after
    ///  usage.
    ///
    /// MT safe.
    pub fn timed_pop_filtered(
        &self,
        timeout: ::ClockTime,
        msg_types: &[MessageType],
    ) -> Option<Message> {
        loop {
            let msg = self.timed_pop(timeout)?;
            if msg_types.contains(&msg.get_type()) {
                return Some(msg);
            }
        }
    }

    /// Get a message matching `type_` from the bus. Will discard all messages on
    /// the bus that do not match `type_` and that have been posted before the first
    /// message that does match `type_`. If there is no message matching `type_` on
    /// the bus, all messages will be discarded. It is not possible to use message
    /// enums beyond `MessageType::Extended` in the `events` mask.
    /// ## `types`
    /// message types to take into account
    ///
    /// # Returns
    ///
    /// the next `Message` matching
    ///  `type_` that is on the bus, or `None` if the bus is empty or there
    ///  is no message matching `type_`. The message is taken from the bus
    ///  and needs to be unreffed with `Message::unref` after usage.
    ///
    /// MT safe.
    pub fn pop_filtered(&self, msg_types: &[MessageType]) -> Option<Message> {
        loop {
            let msg = self.pop()?;
            if msg_types.contains(&msg.get_type()) {
                return Some(msg);
            }
        }
    }

    pub fn stream(&self) -> BusStream {
        BusStream::new(self)
    }

    pub fn stream_filtered<'a>(
        &self,
        message_types: &'a [MessageType],
    ) -> impl Stream<Item = Message> + Unpin + Send + 'a {
        self.stream().filter(move |message| {
            let message_type = message.get_type();

            future::ready(message_types.contains(&message_type))
        })
    }
}

#[derive(Debug)]
pub struct Iter<'a> {
    bus: &'a Bus,
    timeout: ::ClockTime,
}

impl<'a> Iterator for Iter<'a> {
    type Item = Message;

    fn next(&mut self) -> Option<Message> {
        self.bus.timed_pop(self.timeout)
    }
}

#[derive(Debug)]
pub struct BusStream {
    bus: glib::WeakRef<Bus>,
    receiver: UnboundedReceiver<Message>,
}

impl BusStream {
    fn new(bus: &Bus) -> Self {
        skip_assert_initialized!();

        let (sender, receiver) = mpsc::unbounded();

        bus.set_sync_handler(move |_, message| {
            let _ = sender.unbounded_send(message.to_owned());

            BusSyncReply::Drop
        });

        Self {
            bus: bus.downgrade(),
            receiver,
        }
    }
}

impl Drop for BusStream {
    fn drop(&mut self) {
        if let Some(bus) = self.bus.upgrade() {
            bus.unset_sync_handler();
        }
    }
}

impl Stream for BusStream {
    type Item = Message;

    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Self::Item>> {
        self.receiver.poll_next_unpin(context)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[test]
    fn test_sync_handler() {
        ::init().unwrap();

        let bus = Bus::new();
        let msgs = Arc::new(Mutex::new(Vec::new()));
        let msgs_clone = msgs.clone();
        bus.set_sync_handler(move |_, msg| {
            msgs_clone.lock().unwrap().push(msg.clone());
            BusSyncReply::Pass
        });

        bus.post(&::message::Eos::new()).unwrap();

        let msgs = msgs.lock().unwrap();
        assert_eq!(msgs.len(), 1);
        match msgs[0].view() {
            ::MessageView::Eos(_) => (),
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_bus_stream() {
        ::init().unwrap();

        let bus = Bus::new();
        let bus_stream = bus.stream();

        let eos_message = ::message::Eos::new();
        bus.post(&eos_message).unwrap();

        let bus_future = bus_stream.into_future();
        let (message, _) = futures_executor::block_on(bus_future);

        match message.unwrap().view() {
            ::MessageView::Eos(_) => (),
            _ => unreachable!(),
        }
    }
}