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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    future,
    mem::transmute,
    pin::Pin,
    task::{Context, Poll},
};

use futures_channel::mpsc::{self, UnboundedReceiver};
use futures_core::Stream;
use futures_util::{stream::FusedStream, StreamExt};
use glib::{
    ffi::{gboolean, gpointer},
    prelude::*,
    source::Priority,
    translate::*,
    ControlFlow,
};

use crate::{ffi, Bus, BusSyncReply, Message, MessageType};

unsafe extern "C" fn trampoline_watch<F: FnMut(&Bus, &Message) -> ControlFlow + Send + 'static>(
    bus: *mut ffi::GstBus,
    msg: *mut ffi::GstMessage,
    func: gpointer,
) -> gboolean {
    let func: &mut F = &mut *(func as *mut F);
    func(&from_glib_borrow(bus), &Message::from_glib_borrow(msg)).into_glib()
}

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

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

unsafe extern "C" fn trampoline_watch_local<F: FnMut(&Bus, &Message) -> ControlFlow + 'static>(
    bus: *mut ffi::GstBus,
    msg: *mut ffi::GstMessage,
    func: gpointer,
) -> gboolean {
    let func: &mut glib::thread_guard::ThreadGuard<F> =
        &mut *(func as *mut glib::thread_guard::ThreadGuard<F>);
    (func.get_mut())(&from_glib_borrow(bus), &Message::from_glib_borrow(msg)).into_glib()
}

unsafe extern "C" fn destroy_closure_watch_local<
    F: FnMut(&Bus, &Message) -> ControlFlow + 'static,
>(
    ptr: gpointer,
) {
    let _ = Box::<glib::thread_guard::ThreadGuard<F>>::from_raw(ptr as *mut _);
}

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

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

    if res == ffi::GST_BUS_DROP {
        ffi::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,
) {
    let _ = 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()`][crate::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 `GMainLoop` is running.
    ///
    /// This function may be called multiple times. To clean up, the caller is
    /// responsible for calling [`remove_signal_watch()`][Self::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.
    /// ## `priority`
    /// The priority of the watch.
    #[doc(alias = "gst_bus_add_signal_watch")]
    #[doc(alias = "gst_bus_add_signal_watch_full")]
    pub fn add_signal_watch_full(&self, priority: Priority) {
        unsafe {
            ffi::gst_bus_add_signal_watch_full(self.to_glib_none().0, priority.into_glib());
        }
    }

    /// Create watch for this bus. The [`glib::Source`][crate::glib::Source] will be dispatched whenever
    /// a message is on the bus. After the GSource is dispatched, the
    /// message is popped off the bus and unreffed.
    ///
    /// As with other watches, there can only be one watch on the bus, including
    /// any signal watch added with `gst_bus_add_signal_watch`.
    ///
    /// # Returns
    ///
    /// a [`glib::Source`][crate::glib::Source] that can be added to a `GMainLoop`.
    #[doc(alias = "gst_bus_create_watch")]
    pub fn create_watch<F>(&self, name: Option<&str>, priority: Priority, func: F) -> glib::Source
    where
        F: FnMut(&Bus, &Message) -> ControlFlow + Send + 'static,
    {
        skip_assert_initialized!();
        unsafe {
            let source = ffi::gst_bus_create_watch(self.to_glib_none().0);
            glib::ffi::g_source_set_callback(
                source,
                Some(transmute::<
                    *const (),
                    unsafe extern "C" fn(glib::ffi::gpointer) -> i32,
                >(trampoline_watch::<F> as *const ())),
                into_raw_watch(func),
                Some(destroy_closure_watch::<F>),
            );
            glib::ffi::g_source_set_priority(source, priority.into_glib());

            if let Some(name) = name {
                glib::ffi::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()`][crate::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 `GMainLoop` is being run.
    ///
    /// The watch can be removed using [`remove_watch()`][Self::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()`][crate::glib::Source::remove()].
    ///
    /// The bus watch will take its own reference to the `self`, so it is safe to unref
    /// `self` using `gst_object_unref()` after setting the bus watch.
    /// ## `func`
    /// A function to call when a message is received.
    ///
    /// # Returns
    ///
    /// The event source id or 0 if `self` already got an event source.
    #[doc(alias = "gst_bus_add_watch")]
    #[doc(alias = "gst_bus_add_watch_full")]
    pub fn add_watch<F>(&self, func: F) -> Result<BusWatchGuard, glib::BoolError>
    where
        F: FnMut(&Bus, &Message) -> ControlFlow + Send + 'static,
    {
        unsafe {
            let res = ffi::gst_bus_add_watch_full(
                self.to_glib_none().0,
                glib::ffi::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(BusWatchGuard { bus: self.clone() })
            }
        }
    }

    #[doc(alias = "gst_bus_add_watch")]
    #[doc(alias = "gst_bus_add_watch_full")]
    pub fn add_watch_local<F>(&self, func: F) -> Result<BusWatchGuard, glib::BoolError>
    where
        F: FnMut(&Bus, &Message) -> ControlFlow + 'static,
    {
        unsafe {
            let ctx = glib::MainContext::ref_thread_default();
            let _acquire = ctx
                .acquire()
                .expect("thread default main context already acquired by another thread");

            let res = ffi::gst_bus_add_watch_full(
                self.to_glib_none().0,
                glib::ffi::G_PRIORITY_DEFAULT,
                Some(trampoline_watch_local::<F>),
                into_raw_watch_local(func),
                Some(destroy_closure_watch_local::<F>),
            );

            if res == 0 {
                Err(glib::bool_error!("Bus already has a watch"))
            } else {
                Ok(BusWatchGuard { bus: self.clone() })
            }
        }
    }

    /// 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
    /// ## `notify`
    /// called when `user_data` becomes unused
    #[doc(alias = "gst_bus_set_sync_handler")]
    pub fn set_sync_handler<F>(&self, func: F)
    where
        F: Fn(&Bus, &Message) -> BusSyncReply + Send + Sync + 'static,
    {
        unsafe {
            let bus = self.to_glib_none().0;

            #[cfg(not(feature = "v1_18"))]
            {
                static SET_ONCE_QUARK: std::sync::OnceLock<glib::Quark> =
                    std::sync::OnceLock::new();

                let set_once_quark = SET_ONCE_QUARK
                    .get_or_init(|| glib::Quark::from_str("gstreamer-rs-sync-handler"));

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

                    glib::gobject_ffi::g_object_set_qdata(
                        bus as *mut _,
                        set_once_quark.into_glib(),
                        1 as *mut _,
                    );
                }
            }

            ffi::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) {
        #[cfg(not(feature = "v1_18"))]
        {
            // This is not thread-safe before 1.16.3, see
            // https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/merge_requests/416
            if crate::version() < (1, 16, 3, 0) {
                return;
            }
        }

        unsafe {
            use std::ptr;

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

    #[doc(alias = "gst_bus_pop")]
    pub fn iter(&self) -> Iter {
        self.iter_timed(Some(crate::ClockTime::ZERO))
    }

    #[doc(alias = "gst_bus_timed_pop")]
    pub fn iter_timed(&self, timeout: impl Into<Option<crate::ClockTime>>) -> Iter {
        Iter {
            bus: self,
            timeout: timeout.into(),
        }
    }

    #[doc(alias = "gst_bus_pop_filtered")]
    pub fn iter_filtered<'a>(
        &'a self,
        msg_types: &'a [MessageType],
    ) -> impl Iterator<Item = Message> + 'a {
        self.iter_timed_filtered(Some(crate::ClockTime::ZERO), msg_types)
    }

    #[doc(alias = "gst_bus_timed_pop_filtered")]
    pub fn iter_timed_filtered<'a>(
        &'a self,
        timeout: impl Into<Option<crate::ClockTime>>,
        msg_types: &'a [MessageType],
    ) -> impl Iterator<Item = Message> + 'a {
        self.iter_timed(timeout)
            .filter(move |msg| msg_types.contains(&msg.type_()))
    }

    /// Gets 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 [`pop_filtered()`][Self::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`][crate::Message] matching the
    ///  filter in `types`, or [`None`] if no matching message was found on
    ///  the bus until the timeout expired.
    #[doc(alias = "gst_bus_timed_pop_filtered")]
    pub fn timed_pop_filtered(
        &self,
        timeout: impl Into<Option<crate::ClockTime>> + Clone,
        msg_types: &[MessageType],
    ) -> Option<Message> {
        loop {
            let msg = self.timed_pop(timeout.clone())?;
            if msg_types.contains(&msg.type_()) {
                return Some(msg);
            }
        }
    }

    /// Gets 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 `GST_MESSAGE_EXTENDED` in the `events` mask.
    /// ## `types`
    /// message types to take into account
    ///
    /// # Returns
    ///
    /// the next [`Message`][crate::Message] matching
    ///  `type_` that is on the bus, or [`None`] if the bus is empty or there
    ///  is no message matching `type_`.
    #[doc(alias = "gst_bus_pop_filtered")]
    pub fn pop_filtered(&self, msg_types: &[MessageType]) -> Option<Message> {
        loop {
            let msg = self.pop()?;
            if msg_types.contains(&msg.type_()) {
                return Some(msg);
            }
        }
    }

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

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

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

#[derive(Debug)]
pub struct Iter<'a> {
    bus: &'a Bus,
    timeout: Option<crate::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 |bus, message| {
            // First pop all messages that might've been previously queued before creating
            // the bus stream.
            while let Some(message) = bus.pop() {
                let _ = sender.unbounded_send(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)
    }
}

impl FusedStream for BusStream {
    fn is_terminated(&self) -> bool {
        self.receiver.is_terminated()
    }
}

// rustdoc-stripper-ignore-next
/// Manages ownership of the bus watch added to a bus with [`Bus::add_watch`] or [`Bus::add_watch_local`]
///
/// When dropped the bus watch is removed from the bus.
#[derive(Debug)]
#[must_use = "if unused the bus watch will immediately be removed"]
pub struct BusWatchGuard {
    bus: Bus,
}

impl Drop for BusWatchGuard {
    fn drop(&mut self) {
        let _ = self.bus.remove_watch();
    }
}

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

    use super::*;

    #[test]
    fn test_sync_handler() {
        crate::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(crate::message::Eos::new()).unwrap();

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

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

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

        let eos_message = crate::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() {
            crate::MessageView::Eos(_) => (),
            _ => unreachable!(),
        }
    }
}