tee: Check for the removed pad flag also in the slow pushing path
[platform/upstream/gstreamer.git] / gst / gstbus.c
1 /* GStreamer
2  * Copyright (C) 2004 Wim Taymans <wim@fluendo.com>
3  *
4  * gstbus.c: GstBus subsystem
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:gstbus
24  * @title: GstBus
25  * @short_description: Asynchronous message bus subsystem
26  * @see_also: #GstMessage, #GstElement
27  *
28  * The #GstBus is an object responsible for delivering #GstMessage packets in
29  * a first-in first-out way from the streaming threads (see #GstTask) to the
30  * application.
31  *
32  * Since the application typically only wants to deal with delivery of these
33  * messages from one thread, the GstBus will marshall the messages between
34  * different threads. This is important since the actual streaming of media
35  * is done in another thread than the application.
36  *
37  * The GstBus provides support for #GSource based notifications. This makes it
38  * possible to handle the delivery in the glib mainloop.
39  *
40  * The #GSource callback function gst_bus_async_signal_func() can be used to
41  * convert all bus messages into signal emissions.
42  *
43  * A message is posted on the bus with the gst_bus_post() method. With the
44  * gst_bus_peek() and gst_bus_pop() methods one can look at or retrieve a
45  * previously posted message.
46  *
47  * The bus can be polled with the gst_bus_poll() method. This methods blocks
48  * up to the specified timeout value until one of the specified messages types
49  * is posted on the bus. The application can then gst_bus_pop() the messages
50  * from the bus to handle them.
51  * Alternatively the application can register an asynchronous bus function
52  * using gst_bus_add_watch_full() or gst_bus_add_watch(). This function will
53  * install a #GSource in the default glib main loop and will deliver messages
54  * a short while after they have been posted. Note that the main loop should
55  * be running for the asynchronous callbacks.
56  *
57  * It is also possible to get messages from the bus without any thread
58  * marshalling with the gst_bus_set_sync_handler() method. This makes it
59  * possible to react to a message in the same thread that posted the
60  * message on the bus. This should only be used if the application is able
61  * to deal with messages from different threads.
62  *
63  * Every #GstPipeline has one bus.
64  *
65  * Note that a #GstPipeline will set its bus into flushing state when changing
66  * from READY to NULL state.
67  */
68
69 #include "gst_private.h"
70 #include <errno.h>
71 #ifdef HAVE_UNISTD_H
72 #  include <unistd.h>
73 #endif
74 #include <sys/types.h>
75
76 #include "gstatomicqueue.h"
77 #include "gstinfo.h"
78 #include "gstpoll.h"
79
80 #include "gstbus.h"
81 #include "glib-compat-private.h"
82
83 #ifdef G_OS_WIN32
84 #  ifndef EWOULDBLOCK
85 #  define EWOULDBLOCK EAGAIN    /* This is just to placate gcc */
86 #  endif
87 #endif /* G_OS_WIN32 */
88
89 #define GST_CAT_DEFAULT GST_CAT_BUS
90 /* bus signals */
91 enum
92 {
93   SYNC_MESSAGE,
94   ASYNC_MESSAGE,
95   /* add more above */
96   LAST_SIGNAL
97 };
98
99 #define DEFAULT_ENABLE_ASYNC (TRUE)
100
101 enum
102 {
103   PROP_0,
104   PROP_ENABLE_ASYNC
105 };
106
107 static void gst_bus_dispose (GObject * object);
108 static void gst_bus_finalize (GObject * object);
109
110 static guint gst_bus_signals[LAST_SIGNAL] = { 0 };
111
112 struct _GstBusPrivate
113 {
114   GstAtomicQueue *queue;
115   GMutex queue_lock;
116
117   GstBusSyncHandler sync_handler;
118   gpointer sync_handler_data;
119   GDestroyNotify sync_handler_notify;
120
121   guint num_signal_watchers;
122
123   guint num_sync_message_emitters;
124   GSource *signal_watch;
125
126   gboolean enable_async;
127   GstPoll *poll;
128   GPollFD pollfd;
129 };
130
131 #define gst_bus_parent_class parent_class
132 G_DEFINE_TYPE_WITH_PRIVATE (GstBus, gst_bus, GST_TYPE_OBJECT);
133
134 static void
135 gst_bus_set_property (GObject * object,
136     guint prop_id, const GValue * value, GParamSpec * pspec)
137 {
138   GstBus *bus = GST_BUS_CAST (object);
139
140   switch (prop_id) {
141     case PROP_ENABLE_ASYNC:
142       bus->priv->enable_async = g_value_get_boolean (value);
143       break;
144     default:
145       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
146       break;
147   }
148 }
149
150 static void
151 gst_bus_constructed (GObject * object)
152 {
153   GstBus *bus = GST_BUS_CAST (object);
154
155   if (bus->priv->enable_async) {
156     bus->priv->poll = gst_poll_new_timer ();
157     gst_poll_get_read_gpollfd (bus->priv->poll, &bus->priv->pollfd);
158   }
159
160   G_OBJECT_CLASS (gst_bus_parent_class)->constructed (object);
161 }
162
163 static void
164 gst_bus_class_init (GstBusClass * klass)
165 {
166   GObjectClass *gobject_class = (GObjectClass *) klass;
167
168   gobject_class->dispose = gst_bus_dispose;
169   gobject_class->finalize = gst_bus_finalize;
170   gobject_class->set_property = gst_bus_set_property;
171   gobject_class->constructed = gst_bus_constructed;
172
173   /**
174    * GstBus::enable-async:
175    *
176    * Enable async message delivery support for bus watches,
177    * gst_bus_pop() and similar API. Without this only the
178    * synchronous message handlers are called.
179    *
180    * This property is used to create the child element buses
181    * in #GstBin.
182    */
183   g_object_class_install_property (gobject_class, PROP_ENABLE_ASYNC,
184       g_param_spec_boolean ("enable-async", "Enable Async",
185           "Enable async message delivery for bus watches and gst_bus_pop()",
186           DEFAULT_ENABLE_ASYNC,
187           G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
188
189   /**
190    * GstBus::sync-message:
191    * @bus: the object which received the signal
192    * @message: the message that has been posted synchronously
193    *
194    * A message has been posted on the bus. This signal is emitted from the
195    * thread that posted the message so one has to be careful with locking.
196    *
197    * This signal will not be emitted by default, you have to call
198    * gst_bus_enable_sync_message_emission() before.
199    */
200   gst_bus_signals[SYNC_MESSAGE] =
201       g_signal_new ("sync-message", G_TYPE_FROM_CLASS (klass),
202       G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
203       G_STRUCT_OFFSET (GstBusClass, sync_message), NULL, NULL,
204       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_MESSAGE);
205
206   /**
207    * GstBus::message:
208    * @bus: the object which received the signal
209    * @message: the message that has been posted asynchronously
210    *
211    * A message has been posted on the bus. This signal is emitted from a
212    * GSource added to the mainloop. this signal will only be emitted when
213    * there is a mainloop running.
214    */
215   gst_bus_signals[ASYNC_MESSAGE] =
216       g_signal_new ("message", G_TYPE_FROM_CLASS (klass),
217       G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
218       G_STRUCT_OFFSET (GstBusClass, message), NULL, NULL,
219       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_MESSAGE);
220 }
221
222 static void
223 gst_bus_init (GstBus * bus)
224 {
225   bus->priv = gst_bus_get_instance_private (bus);
226   bus->priv->enable_async = DEFAULT_ENABLE_ASYNC;
227   g_mutex_init (&bus->priv->queue_lock);
228   bus->priv->queue = gst_atomic_queue_new (32);
229
230   GST_DEBUG_OBJECT (bus, "created");
231 }
232
233 static void
234 gst_bus_dispose (GObject * object)
235 {
236   GstBus *bus = GST_BUS (object);
237
238   if (bus->priv->queue) {
239     GstMessage *message;
240
241     g_mutex_lock (&bus->priv->queue_lock);
242     do {
243       message = gst_atomic_queue_pop (bus->priv->queue);
244       if (message)
245         gst_message_unref (message);
246     } while (message != NULL);
247     gst_atomic_queue_unref (bus->priv->queue);
248     bus->priv->queue = NULL;
249     g_mutex_unlock (&bus->priv->queue_lock);
250     g_mutex_clear (&bus->priv->queue_lock);
251
252     if (bus->priv->poll)
253       gst_poll_free (bus->priv->poll);
254     bus->priv->poll = NULL;
255   }
256
257   G_OBJECT_CLASS (parent_class)->dispose (object);
258 }
259
260 static void
261 gst_bus_finalize (GObject * object)
262 {
263   GstBus *bus = GST_BUS (object);
264
265   if (bus->priv->sync_handler_notify)
266     bus->priv->sync_handler_notify (bus->priv->sync_handler_data);
267
268   G_OBJECT_CLASS (parent_class)->finalize (object);
269 }
270
271 /**
272  * gst_bus_new:
273  *
274  * Creates a new #GstBus instance.
275  *
276  * Returns: (transfer full): a new #GstBus instance
277  */
278 GstBus *
279 gst_bus_new (void)
280 {
281   GstBus *result;
282
283   result = g_object_new (gst_bus_get_type (), NULL);
284   GST_DEBUG_OBJECT (result, "created new bus");
285
286   /* clear floating flag */
287   gst_object_ref_sink (result);
288
289   return result;
290 }
291
292 /**
293  * gst_bus_post:
294  * @bus: a #GstBus to post on
295  * @message: (transfer full): the #GstMessage to post
296  *
297  * Post a message on the given bus. Ownership of the message
298  * is taken by the bus.
299  *
300  * Returns: %TRUE if the message could be posted, %FALSE if the bus is flushing.
301  *
302  * MT safe.
303  */
304 gboolean
305 gst_bus_post (GstBus * bus, GstMessage * message)
306 {
307   GstBusSyncReply reply = GST_BUS_PASS;
308   GstBusSyncHandler handler;
309   gboolean emit_sync_message;
310   gpointer handler_data;
311
312   g_return_val_if_fail (GST_IS_BUS (bus), FALSE);
313   g_return_val_if_fail (GST_IS_MESSAGE (message), FALSE);
314
315   GST_DEBUG_OBJECT (bus, "[msg %p] posting on bus %" GST_PTR_FORMAT, message,
316       message);
317
318   /* check we didn't accidentally add a public flag that maps to same value */
319   g_assert (!GST_MINI_OBJECT_FLAG_IS_SET (message,
320           GST_MESSAGE_FLAG_ASYNC_DELIVERY));
321
322   GST_OBJECT_LOCK (bus);
323   /* check if the bus is flushing */
324   if (GST_OBJECT_FLAG_IS_SET (bus, GST_BUS_FLUSHING))
325     goto is_flushing;
326
327   handler = bus->priv->sync_handler;
328   handler_data = bus->priv->sync_handler_data;
329   emit_sync_message = bus->priv->num_sync_message_emitters > 0;
330   GST_OBJECT_UNLOCK (bus);
331
332   /* first call the sync handler if it is installed */
333   if (handler)
334     reply = handler (bus, message, handler_data);
335
336   /* emit sync-message if requested to do so via
337      gst_bus_enable_sync_message_emission. terrible but effective */
338   if (emit_sync_message && reply != GST_BUS_DROP
339       && handler != gst_bus_sync_signal_handler)
340     gst_bus_sync_signal_handler (bus, message, NULL);
341
342   /* If this is a bus without async message delivery
343    * always drop the message */
344   if (!bus->priv->poll)
345     reply = GST_BUS_DROP;
346
347   /* now see what we should do with the message */
348   switch (reply) {
349     case GST_BUS_DROP:
350       /* drop the message */
351       GST_DEBUG_OBJECT (bus, "[msg %p] dropped", message);
352       break;
353     case GST_BUS_PASS:
354       /* pass the message to the async queue, refcount passed in the queue */
355       GST_DEBUG_OBJECT (bus, "[msg %p] pushing on async queue", message);
356       gst_atomic_queue_push (bus->priv->queue, message);
357       gst_poll_write_control (bus->priv->poll);
358       GST_DEBUG_OBJECT (bus, "[msg %p] pushed on async queue", message);
359
360       break;
361     case GST_BUS_ASYNC:
362     {
363       /* async delivery, we need a mutex and a cond to block
364        * on */
365       GCond *cond = GST_MESSAGE_GET_COND (message);
366       GMutex *lock = GST_MESSAGE_GET_LOCK (message);
367
368       g_cond_init (cond);
369       g_mutex_init (lock);
370
371       GST_MINI_OBJECT_FLAG_SET (message, GST_MESSAGE_FLAG_ASYNC_DELIVERY);
372
373       GST_DEBUG_OBJECT (bus, "[msg %p] waiting for async delivery", message);
374
375       /* now we lock the message mutex, send the message to the async
376        * queue. When the message is handled by the app and destroyed,
377        * the cond will be signalled and we can continue */
378       g_mutex_lock (lock);
379
380       gst_atomic_queue_push (bus->priv->queue, message);
381       gst_poll_write_control (bus->priv->poll);
382
383       /* now block till the message is freed */
384       g_cond_wait (cond, lock);
385
386       /* we acquired a new ref from gst_message_dispose() so we can clean up */
387       g_mutex_unlock (lock);
388
389       GST_DEBUG_OBJECT (bus, "[msg %p] delivered asynchronously", message);
390
391       GST_MINI_OBJECT_FLAG_UNSET (message, GST_MESSAGE_FLAG_ASYNC_DELIVERY);
392
393       g_mutex_clear (lock);
394       g_cond_clear (cond);
395
396       gst_message_unref (message);
397       break;
398     }
399     default:
400       g_warning ("invalid return from bus sync handler");
401       break;
402   }
403   return TRUE;
404
405   /* ERRORS */
406 is_flushing:
407   {
408     GST_DEBUG_OBJECT (bus, "bus is flushing");
409     GST_OBJECT_UNLOCK (bus);
410     gst_message_unref (message);
411
412     return FALSE;
413   }
414 }
415
416 /**
417  * gst_bus_have_pending:
418  * @bus: a #GstBus to check
419  *
420  * Check if there are pending messages on the bus that
421  * should be handled.
422  *
423  * Returns: %TRUE if there are messages on the bus to be handled, %FALSE
424  * otherwise.
425  *
426  * MT safe.
427  */
428 gboolean
429 gst_bus_have_pending (GstBus * bus)
430 {
431   gboolean result;
432
433   g_return_val_if_fail (GST_IS_BUS (bus), FALSE);
434
435   /* see if there is a message on the bus */
436   result = gst_atomic_queue_length (bus->priv->queue) != 0;
437
438   return result;
439 }
440
441 /**
442  * gst_bus_set_flushing:
443  * @bus: a #GstBus
444  * @flushing: whether or not to flush the bus
445  *
446  * If @flushing, flush out and unref any messages queued in the bus. Releases
447  * references to the message origin objects. Will flush future messages until
448  * gst_bus_set_flushing() sets @flushing to %FALSE.
449  *
450  * MT safe.
451  */
452 void
453 gst_bus_set_flushing (GstBus * bus, gboolean flushing)
454 {
455   GstMessage *message;
456   GList *message_list = NULL;
457
458   g_return_if_fail (GST_IS_BUS (bus));
459
460   GST_OBJECT_LOCK (bus);
461
462   if (flushing) {
463     GST_OBJECT_FLAG_SET (bus, GST_BUS_FLUSHING);
464
465     GST_DEBUG_OBJECT (bus, "set bus flushing");
466
467     while ((message = gst_bus_pop (bus)))
468       message_list = g_list_prepend (message_list, message);
469   } else {
470     GST_DEBUG_OBJECT (bus, "unset bus flushing");
471     GST_OBJECT_FLAG_UNSET (bus, GST_BUS_FLUSHING);
472   }
473
474   GST_OBJECT_UNLOCK (bus);
475
476   g_list_free_full (message_list, (GDestroyNotify) gst_message_unref);
477 }
478
479 /**
480  * gst_bus_timed_pop_filtered:
481  * @bus: a #GstBus to pop from
482  * @timeout: a timeout in nanoseconds, or GST_CLOCK_TIME_NONE to wait forever
483  * @types: message types to take into account, GST_MESSAGE_ANY for any type
484  *
485  * Get a message from the bus whose type matches the message type mask @types,
486  * waiting up to the specified timeout (and discarding any messages that do not
487  * match the mask provided).
488  *
489  * If @timeout is 0, this function behaves like gst_bus_pop_filtered(). If
490  * @timeout is #GST_CLOCK_TIME_NONE, this function will block forever until a
491  * matching message was posted on the bus.
492  *
493  * Returns: (transfer full) (nullable): a #GstMessage matching the
494  *     filter in @types, or %NULL if no matching message was found on
495  *     the bus until the timeout expired. The message is taken from
496  *     the bus and needs to be unreffed with gst_message_unref() after
497  *     usage.
498  *
499  * MT safe.
500  */
501 GstMessage *
502 gst_bus_timed_pop_filtered (GstBus * bus, GstClockTime timeout,
503     GstMessageType types)
504 {
505   GstMessage *message;
506   GTimeVal now, then;
507   gboolean first_round = TRUE;
508   GstClockTime elapsed = 0;
509
510   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
511   g_return_val_if_fail (types != 0, NULL);
512   g_return_val_if_fail (timeout == 0 || bus->priv->poll != NULL, NULL);
513
514   g_mutex_lock (&bus->priv->queue_lock);
515
516   while (TRUE) {
517     gint ret;
518
519     GST_LOG_OBJECT (bus, "have %d messages",
520         gst_atomic_queue_length (bus->priv->queue));
521
522     while ((message = gst_atomic_queue_pop (bus->priv->queue))) {
523       if (bus->priv->poll) {
524         while (!gst_poll_read_control (bus->priv->poll)) {
525           if (errno == EWOULDBLOCK) {
526             /* Retry, this can happen if pushing to the queue has finished,
527              * popping here succeeded but writing control did not finish
528              * before we got to this line. */
529             /* Give other threads the chance to do something */
530             g_thread_yield ();
531             continue;
532           } else {
533             /* This is a real error and means that either the bus is in an
534              * inconsistent state, or the GstPoll is invalid. GstPoll already
535              * prints a critical warning about this, no need to do that again
536              * ourselves */
537             break;
538           }
539         }
540       }
541
542       GST_DEBUG_OBJECT (bus, "got message %p, %s from %s, type mask is %u",
543           message, GST_MESSAGE_TYPE_NAME (message),
544           GST_MESSAGE_SRC_NAME (message), (guint) types);
545       if ((GST_MESSAGE_TYPE (message) & types) != 0) {
546         /* Extra check to ensure extended types don't get matched unless
547          * asked for */
548         if ((!GST_MESSAGE_TYPE_IS_EXTENDED (message))
549             || (types & GST_MESSAGE_EXTENDED)) {
550           /* exit the loop, we have a message */
551           goto beach;
552         }
553       }
554
555       GST_DEBUG_OBJECT (bus, "discarding message, does not match mask");
556       gst_message_unref (message);
557       message = NULL;
558     }
559
560     /* no need to wait, exit loop */
561     if (timeout == 0)
562       break;
563
564     else if (timeout != GST_CLOCK_TIME_NONE) {
565       if (first_round) {
566         g_get_current_time (&then);
567         first_round = FALSE;
568       } else {
569         g_get_current_time (&now);
570
571         elapsed = GST_TIMEVAL_TO_TIME (now) - GST_TIMEVAL_TO_TIME (then);
572
573         if (elapsed > timeout)
574           break;
575       }
576     }
577
578     /* only here in timeout case */
579     g_assert (bus->priv->poll);
580     g_mutex_unlock (&bus->priv->queue_lock);
581     ret = gst_poll_wait (bus->priv->poll, timeout - elapsed);
582     g_mutex_lock (&bus->priv->queue_lock);
583
584     if (ret == 0) {
585       GST_INFO_OBJECT (bus, "timed out, breaking loop");
586       break;
587     } else {
588       GST_INFO_OBJECT (bus, "we got woken up, recheck for message");
589     }
590   }
591
592 beach:
593
594   g_mutex_unlock (&bus->priv->queue_lock);
595
596   return message;
597 }
598
599
600 /**
601  * gst_bus_timed_pop:
602  * @bus: a #GstBus to pop
603  * @timeout: a timeout
604  *
605  * Get a message from the bus, waiting up to the specified timeout.
606  *
607  * If @timeout is 0, this function behaves like gst_bus_pop(). If @timeout is
608  * #GST_CLOCK_TIME_NONE, this function will block forever until a message was
609  * posted on the bus.
610  *
611  * Returns: (transfer full) (nullable): the #GstMessage that is on the
612  *     bus after the specified timeout or %NULL if the bus is empty
613  *     after the timeout expired.  The message is taken from the bus
614  *     and needs to be unreffed with gst_message_unref() after usage.
615  *
616  * MT safe.
617  */
618 GstMessage *
619 gst_bus_timed_pop (GstBus * bus, GstClockTime timeout)
620 {
621   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
622
623   return gst_bus_timed_pop_filtered (bus, timeout, GST_MESSAGE_ANY);
624 }
625
626 /**
627  * gst_bus_pop_filtered:
628  * @bus: a #GstBus to pop
629  * @types: message types to take into account
630  *
631  * Get a message matching @type from the bus.  Will discard all messages on
632  * the bus that do not match @type and that have been posted before the first
633  * message that does match @type.  If there is no message matching @type on
634  * the bus, all messages will be discarded. It is not possible to use message
635  * enums beyond #GST_MESSAGE_EXTENDED in the @events mask.
636  *
637  * Returns: (transfer full) (nullable): the next #GstMessage matching
638  *     @type that is on the bus, or %NULL if the bus is empty or there
639  *     is no message matching @type. The message is taken from the bus
640  *     and needs to be unreffed with gst_message_unref() after usage.
641  *
642  * MT safe.
643  */
644 GstMessage *
645 gst_bus_pop_filtered (GstBus * bus, GstMessageType types)
646 {
647   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
648   g_return_val_if_fail (types != 0, NULL);
649
650   return gst_bus_timed_pop_filtered (bus, 0, types);
651 }
652
653 /**
654  * gst_bus_pop:
655  * @bus: a #GstBus to pop
656  *
657  * Get a message from the bus.
658  *
659  * Returns: (transfer full) (nullable): the #GstMessage that is on the
660  *     bus, or %NULL if the bus is empty. The message is taken from
661  *     the bus and needs to be unreffed with gst_message_unref() after
662  *     usage.
663  *
664  * MT safe.
665  */
666 GstMessage *
667 gst_bus_pop (GstBus * bus)
668 {
669   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
670
671   return gst_bus_timed_pop_filtered (bus, 0, GST_MESSAGE_ANY);
672 }
673
674 /**
675  * gst_bus_peek:
676  * @bus: a #GstBus
677  *
678  * Peek the message on the top of the bus' queue. The message will remain
679  * on the bus' message queue. A reference is returned, and needs to be unreffed
680  * by the caller.
681  *
682  * Returns: (transfer full) (nullable): the #GstMessage that is on the
683  *     bus, or %NULL if the bus is empty.
684  *
685  * MT safe.
686  */
687 GstMessage *
688 gst_bus_peek (GstBus * bus)
689 {
690   GstMessage *message;
691
692   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
693
694   g_mutex_lock (&bus->priv->queue_lock);
695   message = gst_atomic_queue_peek (bus->priv->queue);
696   if (message)
697     gst_message_ref (message);
698   g_mutex_unlock (&bus->priv->queue_lock);
699
700   GST_DEBUG_OBJECT (bus, "peek on bus, got message %p", message);
701
702   return message;
703 }
704
705 /**
706  * gst_bus_set_sync_handler:
707  * @bus: a #GstBus to install the handler on
708  * @func: (allow-none): The handler function to install
709  * @user_data: User data that will be sent to the handler function.
710  * @notify: called when @user_data becomes unused
711  *
712  * Sets the synchronous handler on the bus. The function will be called
713  * every time a new message is posted on the bus. Note that the function
714  * will be called in the same thread context as the posting object. This
715  * function is usually only called by the creator of the bus. Applications
716  * should handle messages asynchronously using the gst_bus watch and poll
717  * functions.
718  *
719  * You cannot replace an existing sync_handler. You can pass %NULL to this
720  * function, which will clear the existing handler.
721  */
722 void
723 gst_bus_set_sync_handler (GstBus * bus, GstBusSyncHandler func,
724     gpointer user_data, GDestroyNotify notify)
725 {
726   GDestroyNotify old_notify;
727
728   g_return_if_fail (GST_IS_BUS (bus));
729
730   GST_OBJECT_LOCK (bus);
731   /* Assert if the user attempts to replace an existing sync_handler,
732    * other than to clear it */
733   if (func != NULL && bus->priv->sync_handler != NULL)
734     goto no_replace;
735
736   if ((old_notify = bus->priv->sync_handler_notify)) {
737     gpointer old_data = bus->priv->sync_handler_data;
738
739     bus->priv->sync_handler_data = NULL;
740     bus->priv->sync_handler_notify = NULL;
741     GST_OBJECT_UNLOCK (bus);
742
743     old_notify (old_data);
744
745     GST_OBJECT_LOCK (bus);
746   }
747   bus->priv->sync_handler = func;
748   bus->priv->sync_handler_data = user_data;
749   bus->priv->sync_handler_notify = notify;
750   GST_OBJECT_UNLOCK (bus);
751
752   return;
753
754 no_replace:
755   {
756     GST_OBJECT_UNLOCK (bus);
757     g_warning ("cannot replace existing sync handler");
758     return;
759   }
760 }
761
762 /**
763  * gst_bus_get_pollfd:
764  * @bus: A #GstBus
765  * @fd: (out): A GPollFD to fill
766  *
767  * Gets the file descriptor from the bus which can be used to get notified about
768  * messages being available with functions like g_poll(), and allows integration
769  * into other event loops based on file descriptors.
770  * Whenever a message is available, the POLLIN / %G_IO_IN event is set.
771  *
772  * Warning: NEVER read or write anything to the returned fd but only use it
773  * for getting notifications via g_poll() or similar and then use the normal
774  * GstBus API, e.g. gst_bus_pop().
775  *
776  * Since: 1.14
777  */
778 void
779 gst_bus_get_pollfd (GstBus * bus, GPollFD * fd)
780 {
781   g_return_if_fail (GST_IS_BUS (bus));
782   g_return_if_fail (bus->priv->poll != NULL);
783
784   *fd = bus->priv->pollfd;
785 }
786
787 /* GSource for the bus
788  */
789 typedef struct
790 {
791   GSource source;
792   GstBus *bus;
793 } GstBusSource;
794
795 static gboolean
796 gst_bus_source_prepare (GSource * source, gint * timeout)
797 {
798   *timeout = -1;
799   return FALSE;
800 }
801
802 static gboolean
803 gst_bus_source_check (GSource * source)
804 {
805   GstBusSource *bsrc = (GstBusSource *) source;
806
807   return bsrc->bus->priv->pollfd.revents & (G_IO_IN | G_IO_HUP | G_IO_ERR);
808 }
809
810 static gboolean
811 gst_bus_source_dispatch (GSource * source, GSourceFunc callback,
812     gpointer user_data)
813 {
814   GstBusFunc handler = (GstBusFunc) callback;
815   GstBusSource *bsource = (GstBusSource *) source;
816   GstMessage *message;
817   gboolean keep;
818   GstBus *bus;
819
820   g_return_val_if_fail (bsource != NULL, FALSE);
821
822   bus = bsource->bus;
823
824   g_return_val_if_fail (GST_IS_BUS (bus), FALSE);
825
826   message = gst_bus_pop (bus);
827
828   /* The message queue might be empty if some other thread or callback set
829    * the bus to flushing between check/prepare and dispatch */
830   if (G_UNLIKELY (message == NULL))
831     return TRUE;
832
833   if (!handler)
834     goto no_handler;
835
836   GST_DEBUG_OBJECT (bus, "source %p calling dispatch with %" GST_PTR_FORMAT,
837       source, message);
838
839   keep = handler (bus, message, user_data);
840   gst_message_unref (message);
841
842   GST_DEBUG_OBJECT (bus, "source %p handler returns %d", source, keep);
843
844   return keep;
845
846 no_handler:
847   {
848     g_warning ("GstBus watch dispatched without callback\n"
849         "You must call g_source_set_callback().");
850     gst_message_unref (message);
851     return FALSE;
852   }
853 }
854
855 static void
856 gst_bus_source_finalize (GSource * source)
857 {
858   GstBusSource *bsource = (GstBusSource *) source;
859   GstBus *bus;
860
861   bus = bsource->bus;
862
863   GST_DEBUG_OBJECT (bus, "finalize source %p", source);
864
865   GST_OBJECT_LOCK (bus);
866   if (bus->priv->signal_watch == source)
867     bus->priv->signal_watch = NULL;
868   GST_OBJECT_UNLOCK (bus);
869
870   gst_object_unref (bsource->bus);
871   bsource->bus = NULL;
872 }
873
874 static GSourceFuncs gst_bus_source_funcs = {
875   gst_bus_source_prepare,
876   gst_bus_source_check,
877   gst_bus_source_dispatch,
878   gst_bus_source_finalize
879 };
880
881 /**
882  * gst_bus_create_watch:
883  * @bus: a #GstBus to create the watch for
884  *
885  * Create watch for this bus. The GSource will be dispatched whenever
886  * a message is on the bus. After the GSource is dispatched, the
887  * message is popped off the bus and unreffed.
888  *
889  * Returns: (transfer full) (nullable): a #GSource that can be added to a mainloop.
890  */
891 GSource *
892 gst_bus_create_watch (GstBus * bus)
893 {
894   GstBusSource *source;
895
896   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
897   g_return_val_if_fail (bus->priv->poll != NULL, NULL);
898
899   source = (GstBusSource *) g_source_new (&gst_bus_source_funcs,
900       sizeof (GstBusSource));
901
902   g_source_set_name ((GSource *) source, "GStreamer message bus watch");
903
904   source->bus = gst_object_ref (bus);
905   g_source_add_poll ((GSource *) source, &bus->priv->pollfd);
906
907   return (GSource *) source;
908 }
909
910 /* must be called with the bus OBJECT LOCK */
911 static guint
912 gst_bus_add_watch_full_unlocked (GstBus * bus, gint priority,
913     GstBusFunc func, gpointer user_data, GDestroyNotify notify)
914 {
915   GMainContext *ctx;
916   guint id;
917   GSource *source;
918
919   if (bus->priv->signal_watch) {
920     GST_ERROR_OBJECT (bus,
921         "Tried to add new watch while one was already there");
922     return 0;
923   }
924
925   source = gst_bus_create_watch (bus);
926   if (!source) {
927     g_critical ("Creating bus watch failed");
928     return 0;
929   }
930
931   if (priority != G_PRIORITY_DEFAULT)
932     g_source_set_priority (source, priority);
933
934   g_source_set_callback (source, (GSourceFunc) func, user_data, notify);
935
936   ctx = g_main_context_get_thread_default ();
937   id = g_source_attach (source, ctx);
938   g_source_unref (source);
939
940   if (id) {
941     bus->priv->signal_watch = source;
942   }
943
944   GST_DEBUG_OBJECT (bus, "New source %p with id %u", source, id);
945   return id;
946 }
947
948 /**
949  * gst_bus_add_watch_full: (rename-to gst_bus_add_watch)
950  * @bus: a #GstBus to create the watch for.
951  * @priority: The priority of the watch.
952  * @func: A function to call when a message is received.
953  * @user_data: user data passed to @func.
954  * @notify: the function to call when the source is removed.
955  *
956  * Adds a bus watch to the default main context with the given @priority (e.g.
957  * %G_PRIORITY_DEFAULT). It is also possible to use a non-default  main
958  * context set up using g_main_context_push_thread_default() (before
959  * one had to create a bus watch source and attach it to the desired main
960  * context 'manually').
961  *
962  * This function is used to receive asynchronous messages in the main loop.
963  * There can only be a single bus watch per bus, you must remove it before you
964  * can set a new one.
965  *
966  * The bus watch will only work if a GLib main loop is being run.
967  *
968  * When @func is called, the message belongs to the caller; if you want to
969  * keep a copy of it, call gst_message_ref() before leaving @func.
970  *
971  * The watch can be removed using gst_bus_remove_watch() or by returning %FALSE
972  * from @func. If the watch was added to the default main context it is also
973  * possible to remove the watch using g_source_remove().
974  *
975  * The bus watch will take its own reference to the @bus, so it is safe to unref
976  * @bus using gst_object_unref() after setting the bus watch.
977  *
978  * MT safe.
979  *
980  * Returns: The event source id or 0 if @bus already got an event source.
981  */
982 guint
983 gst_bus_add_watch_full (GstBus * bus, gint priority,
984     GstBusFunc func, gpointer user_data, GDestroyNotify notify)
985 {
986   guint id;
987
988   g_return_val_if_fail (GST_IS_BUS (bus), 0);
989
990   GST_OBJECT_LOCK (bus);
991   id = gst_bus_add_watch_full_unlocked (bus, priority, func, user_data, notify);
992   GST_OBJECT_UNLOCK (bus);
993
994   return id;
995 }
996
997 /**
998  * gst_bus_add_watch: (skip)
999  * @bus: a #GstBus to create the watch for
1000  * @func: A function to call when a message is received.
1001  * @user_data: user data passed to @func.
1002  *
1003  * Adds a bus watch to the default main context with the default priority
1004  * (%G_PRIORITY_DEFAULT). It is also possible to use a non-default main
1005  * context set up using g_main_context_push_thread_default() (before
1006  * one had to create a bus watch source and attach it to the desired main
1007  * context 'manually').
1008  *
1009  * This function is used to receive asynchronous messages in the main loop.
1010  * There can only be a single bus watch per bus, you must remove it before you
1011  * can set a new one.
1012  *
1013  * The bus watch will only work if a GLib main loop is being run.
1014  *
1015  * The watch can be removed using gst_bus_remove_watch() or by returning %FALSE
1016  * from @func. If the watch was added to the default main context it is also
1017  * possible to remove the watch using g_source_remove().
1018  *
1019  * The bus watch will take its own reference to the @bus, so it is safe to unref
1020  * @bus using gst_object_unref() after setting the bus watch.
1021  *
1022  * MT safe.
1023  *
1024  * Returns: The event source id or 0 if @bus already got an event source.
1025  */
1026 guint
1027 gst_bus_add_watch (GstBus * bus, GstBusFunc func, gpointer user_data)
1028 {
1029   return gst_bus_add_watch_full (bus, G_PRIORITY_DEFAULT, func,
1030       user_data, NULL);
1031 }
1032
1033 /**
1034  * gst_bus_remove_watch:
1035  * @bus: a #GstBus to remove the watch from.
1036  *
1037  * Removes an installed bus watch from @bus.
1038  *
1039  * Returns: %TRUE on success or %FALSE if @bus has no event source.
1040  *
1041  * Since: 1.6
1042  *
1043  */
1044 gboolean
1045 gst_bus_remove_watch (GstBus * bus)
1046 {
1047   GSource *source;
1048
1049   g_return_val_if_fail (GST_IS_BUS (bus), FALSE);
1050
1051   GST_OBJECT_LOCK (bus);
1052
1053   if (bus->priv->signal_watch == NULL) {
1054     GST_ERROR_OBJECT (bus, "no bus watch was present");
1055     goto error;
1056   }
1057
1058   if (bus->priv->num_signal_watchers > 0) {
1059     GST_ERROR_OBJECT (bus,
1060         "trying to remove signal watch with gst_bus_remove_watch()");
1061     goto error;
1062   }
1063
1064   source =
1065       bus->priv->signal_watch ? g_source_ref (bus->priv->signal_watch) : NULL;
1066
1067   GST_OBJECT_UNLOCK (bus);
1068
1069   if (source) {
1070     g_source_destroy (source);
1071     g_source_unref (source);
1072   }
1073
1074   return TRUE;
1075
1076 error:
1077   GST_OBJECT_UNLOCK (bus);
1078
1079   return FALSE;
1080 }
1081
1082 typedef struct
1083 {
1084   GMainLoop *loop;
1085   guint timeout_id;
1086   gboolean source_running;
1087   GstMessageType events;
1088   GstMessage *message;
1089 } GstBusPollData;
1090
1091 static void
1092 poll_func (GstBus * bus, GstMessage * message, GstBusPollData * poll_data)
1093 {
1094   GstMessageType type;
1095
1096   if (!g_main_loop_is_running (poll_data->loop)) {
1097     GST_DEBUG ("mainloop %p not running", poll_data->loop);
1098     return;
1099   }
1100
1101   type = GST_MESSAGE_TYPE (message);
1102
1103   if (type & poll_data->events) {
1104     g_assert (poll_data->message == NULL);
1105     /* keep ref to message */
1106     poll_data->message = gst_message_ref (message);
1107     GST_DEBUG ("mainloop %p quit", poll_data->loop);
1108     g_main_loop_quit (poll_data->loop);
1109   } else {
1110     GST_DEBUG ("type %08x does not match %08x", type, poll_data->events);
1111   }
1112 }
1113
1114 static gboolean
1115 poll_timeout (GstBusPollData * poll_data)
1116 {
1117   GST_DEBUG ("mainloop %p quit", poll_data->loop);
1118   g_main_loop_quit (poll_data->loop);
1119
1120   /* we don't remove the GSource as this would free our poll_data,
1121    * which we still need */
1122   return TRUE;
1123 }
1124
1125 static void
1126 poll_destroy (GstBusPollData * poll_data, gpointer unused)
1127 {
1128   poll_data->source_running = FALSE;
1129   if (!poll_data->timeout_id) {
1130     g_main_loop_unref (poll_data->loop);
1131     g_slice_free (GstBusPollData, poll_data);
1132   }
1133 }
1134
1135 static void
1136 poll_destroy_timeout (GstBusPollData * poll_data)
1137 {
1138   poll_data->timeout_id = 0;
1139   if (!poll_data->source_running) {
1140     g_main_loop_unref (poll_data->loop);
1141     g_slice_free (GstBusPollData, poll_data);
1142   }
1143 }
1144
1145 /**
1146  * gst_bus_poll:
1147  * @bus: a #GstBus
1148  * @events: a mask of #GstMessageType, representing the set of message types to
1149  * poll for (note special handling of extended message types below)
1150  * @timeout: the poll timeout, as a #GstClockTime, or #GST_CLOCK_TIME_NONE to poll
1151  * indefinitely.
1152  *
1153  * Poll the bus for messages. Will block while waiting for messages to come.
1154  * You can specify a maximum time to poll with the @timeout parameter. If
1155  * @timeout is negative, this function will block indefinitely.
1156  *
1157  * All messages not in @events will be popped off the bus and will be ignored.
1158  * It is not possible to use message enums beyond #GST_MESSAGE_EXTENDED in the
1159  * @events mask
1160  *
1161  * Because poll is implemented using the "message" signal enabled by
1162  * gst_bus_add_signal_watch(), calling gst_bus_poll() will cause the "message"
1163  * signal to be emitted for every message that poll sees. Thus a "message"
1164  * signal handler will see the same messages that this function sees -- neither
1165  * will steal messages from the other.
1166  *
1167  * This function will run a main loop from the default main context when
1168  * polling.
1169  *
1170  * You should never use this function, since it is pure evil. This is
1171  * especially true for GUI applications based on Gtk+ or Qt, but also for any
1172  * other non-trivial application that uses the GLib main loop. As this function
1173  * runs a GLib main loop, any callback attached to the default GLib main
1174  * context may be invoked. This could be timeouts, GUI events, I/O events etc.;
1175  * even if gst_bus_poll() is called with a 0 timeout. Any of these callbacks
1176  * may do things you do not expect, e.g. destroy the main application window or
1177  * some other resource; change other application state; display a dialog and
1178  * run another main loop until the user clicks it away. In short, using this
1179  * function may add a lot of complexity to your code through unexpected
1180  * re-entrancy and unexpected changes to your application's state.
1181  *
1182  * For 0 timeouts use gst_bus_pop_filtered() instead of this function; for
1183  * other short timeouts use gst_bus_timed_pop_filtered(); everything else is
1184  * better handled by setting up an asynchronous bus watch and doing things
1185  * from there.
1186  *
1187  * Returns: (transfer full) (nullable): the message that was received,
1188  *     or %NULL if the poll timed out. The message is taken from the
1189  *     bus and needs to be unreffed with gst_message_unref() after
1190  *     usage.
1191  */
1192 GstMessage *
1193 gst_bus_poll (GstBus * bus, GstMessageType events, GstClockTime timeout)
1194 {
1195   GstBusPollData *poll_data;
1196   GstMessage *ret;
1197   gulong id;
1198
1199   g_return_val_if_fail (GST_IS_BUS (bus), NULL);
1200
1201   poll_data = g_slice_new (GstBusPollData);
1202   poll_data->source_running = TRUE;
1203   poll_data->loop = g_main_loop_new (NULL, FALSE);
1204   poll_data->events = events;
1205   poll_data->message = NULL;
1206
1207   if (timeout != GST_CLOCK_TIME_NONE)
1208     poll_data->timeout_id = g_timeout_add_full (G_PRIORITY_DEFAULT_IDLE,
1209         timeout / GST_MSECOND, (GSourceFunc) poll_timeout, poll_data,
1210         (GDestroyNotify) poll_destroy_timeout);
1211   else
1212     poll_data->timeout_id = 0;
1213
1214   id = g_signal_connect_data (bus, "message", G_CALLBACK (poll_func), poll_data,
1215       (GClosureNotify) poll_destroy, 0);
1216
1217   /* these can be nested, so it's ok */
1218   gst_bus_add_signal_watch (bus);
1219
1220   GST_DEBUG ("running mainloop %p", poll_data->loop);
1221   g_main_loop_run (poll_data->loop);
1222   GST_DEBUG ("mainloop stopped %p", poll_data->loop);
1223
1224   gst_bus_remove_signal_watch (bus);
1225
1226   /* holds a ref */
1227   ret = poll_data->message;
1228
1229   if (poll_data->timeout_id)
1230     g_source_remove (poll_data->timeout_id);
1231
1232   /* poll_data will be freed now */
1233   g_signal_handler_disconnect (bus, id);
1234
1235   GST_DEBUG_OBJECT (bus, "finished poll with message %p", ret);
1236
1237   return ret;
1238 }
1239
1240 /**
1241  * gst_bus_async_signal_func:
1242  * @bus: a #GstBus
1243  * @message: the #GstMessage received
1244  * @data: user data
1245  *
1246  * A helper #GstBusFunc that can be used to convert all asynchronous messages
1247  * into signals.
1248  *
1249  * Returns: %TRUE
1250  */
1251 gboolean
1252 gst_bus_async_signal_func (GstBus * bus, GstMessage * message, gpointer data)
1253 {
1254   GQuark detail = 0;
1255
1256   g_return_val_if_fail (GST_IS_BUS (bus), TRUE);
1257   g_return_val_if_fail (message != NULL, TRUE);
1258
1259   detail = gst_message_type_to_quark (GST_MESSAGE_TYPE (message));
1260
1261   g_signal_emit (bus, gst_bus_signals[ASYNC_MESSAGE], detail, message);
1262
1263   /* we never remove this source based on signal emission return values */
1264   return TRUE;
1265 }
1266
1267 /**
1268  * gst_bus_sync_signal_handler:
1269  * @bus: a #GstBus
1270  * @message: the #GstMessage received
1271  * @data: user data
1272  *
1273  * A helper GstBusSyncHandler that can be used to convert all synchronous
1274  * messages into signals.
1275  *
1276  * Returns: GST_BUS_PASS
1277  */
1278 GstBusSyncReply
1279 gst_bus_sync_signal_handler (GstBus * bus, GstMessage * message, gpointer data)
1280 {
1281   GQuark detail = 0;
1282
1283   g_return_val_if_fail (GST_IS_BUS (bus), GST_BUS_DROP);
1284   g_return_val_if_fail (message != NULL, GST_BUS_DROP);
1285
1286   detail = gst_message_type_to_quark (GST_MESSAGE_TYPE (message));
1287
1288   g_signal_emit (bus, gst_bus_signals[SYNC_MESSAGE], detail, message);
1289
1290   return GST_BUS_PASS;
1291 }
1292
1293 /**
1294  * gst_bus_enable_sync_message_emission:
1295  * @bus: a #GstBus on which you want to receive the "sync-message" signal
1296  *
1297  * Instructs GStreamer to emit the "sync-message" signal after running the bus's
1298  * sync handler. This function is here so that code can ensure that they can
1299  * synchronously receive messages without having to affect what the bin's sync
1300  * handler is.
1301  *
1302  * This function may be called multiple times. To clean up, the caller is
1303  * responsible for calling gst_bus_disable_sync_message_emission() as many times
1304  * as this function is called.
1305  *
1306  * While this function looks similar to gst_bus_add_signal_watch(), it is not
1307  * exactly the same -- this function enables <emphasis>synchronous</emphasis> emission of
1308  * signals when messages arrive; gst_bus_add_signal_watch() adds an idle callback
1309  * to pop messages off the bus <emphasis>asynchronously</emphasis>. The sync-message signal
1310  * comes from the thread of whatever object posted the message; the "message"
1311  * signal is marshalled to the main thread via the main loop.
1312  *
1313  * MT safe.
1314  */
1315 void
1316 gst_bus_enable_sync_message_emission (GstBus * bus)
1317 {
1318   g_return_if_fail (GST_IS_BUS (bus));
1319
1320   GST_OBJECT_LOCK (bus);
1321   bus->priv->num_sync_message_emitters++;
1322   GST_OBJECT_UNLOCK (bus);
1323 }
1324
1325 /**
1326  * gst_bus_disable_sync_message_emission:
1327  * @bus: a #GstBus on which you previously called
1328  * gst_bus_enable_sync_message_emission()
1329  *
1330  * Instructs GStreamer to stop emitting the "sync-message" signal for this bus.
1331  * See gst_bus_enable_sync_message_emission() for more information.
1332  *
1333  * In the event that multiple pieces of code have called
1334  * gst_bus_enable_sync_message_emission(), the sync-message emissions will only
1335  * be stopped after all calls to gst_bus_enable_sync_message_emission() were
1336  * "cancelled" by calling this function. In this way the semantics are exactly
1337  * the same as gst_object_ref() that which calls enable should also call
1338  * disable.
1339  *
1340  * MT safe.
1341  */
1342 void
1343 gst_bus_disable_sync_message_emission (GstBus * bus)
1344 {
1345   g_return_if_fail (GST_IS_BUS (bus));
1346   g_return_if_fail (bus->priv->num_sync_message_emitters > 0);
1347
1348   GST_OBJECT_LOCK (bus);
1349   bus->priv->num_sync_message_emitters--;
1350   GST_OBJECT_UNLOCK (bus);
1351 }
1352
1353 /**
1354  * gst_bus_add_signal_watch_full:
1355  * @bus: a #GstBus on which you want to receive the "message" signal
1356  * @priority: The priority of the watch.
1357  *
1358  * Adds a bus signal watch to the default main context with the given @priority
1359  * (e.g. %G_PRIORITY_DEFAULT). It is also possible to use a non-default main
1360  * context set up using g_main_context_push_thread_default()
1361  * (before one had to create a bus watch source and attach it to the desired
1362  * main context 'manually').
1363  *
1364  * After calling this statement, the bus will emit the "message" signal for each
1365  * message posted on the bus when the main loop is running.
1366  *
1367  * This function may be called multiple times. To clean up, the caller is
1368  * responsible for calling gst_bus_remove_signal_watch() as many times as this
1369  * function is called.
1370  *
1371  * There can only be a single bus watch per bus, you must remove any signal
1372  * watch before you can set another type of watch.
1373  *
1374  * MT safe.
1375  */
1376 void
1377 gst_bus_add_signal_watch_full (GstBus * bus, gint priority)
1378 {
1379   g_return_if_fail (GST_IS_BUS (bus));
1380
1381   /* I know the callees don't take this lock, so go ahead and abuse it */
1382   GST_OBJECT_LOCK (bus);
1383
1384   if (bus->priv->num_signal_watchers > 0)
1385     goto done;
1386
1387   /* this should not fail because the counter above takes care of it */
1388   g_assert (!bus->priv->signal_watch);
1389
1390   gst_bus_add_watch_full_unlocked (bus, priority, gst_bus_async_signal_func,
1391       NULL, NULL);
1392
1393   if (G_UNLIKELY (!bus->priv->signal_watch))
1394     goto add_failed;
1395
1396 done:
1397
1398   bus->priv->num_signal_watchers++;
1399
1400   GST_OBJECT_UNLOCK (bus);
1401   return;
1402
1403   /* ERRORS */
1404 add_failed:
1405   {
1406     g_critical ("Could not add signal watch to bus %s", GST_OBJECT_NAME (bus));
1407     GST_OBJECT_UNLOCK (bus);
1408     return;
1409   }
1410 }
1411
1412 /**
1413  * gst_bus_add_signal_watch:
1414  * @bus: a #GstBus on which you want to receive the "message" signal
1415  *
1416  * Adds a bus signal watch to the default main context with the default priority
1417  * (%G_PRIORITY_DEFAULT). It is also possible to use a non-default
1418  * main context set up using g_main_context_push_thread_default() (before
1419  * one had to create a bus watch source and attach it to the desired main
1420  * context 'manually').
1421  *
1422  * After calling this statement, the bus will emit the "message" signal for each
1423  * message posted on the bus.
1424  *
1425  * This function may be called multiple times. To clean up, the caller is
1426  * responsible for calling gst_bus_remove_signal_watch() as many times as this
1427  * function is called.
1428  *
1429  * MT safe.
1430  */
1431 void
1432 gst_bus_add_signal_watch (GstBus * bus)
1433 {
1434   gst_bus_add_signal_watch_full (bus, G_PRIORITY_DEFAULT);
1435 }
1436
1437 /**
1438  * gst_bus_remove_signal_watch:
1439  * @bus: a #GstBus you previously added a signal watch to
1440  *
1441  * Removes a signal watch previously added with gst_bus_add_signal_watch().
1442  *
1443  * MT safe.
1444  */
1445 void
1446 gst_bus_remove_signal_watch (GstBus * bus)
1447 {
1448   GSource *source = NULL;
1449
1450   g_return_if_fail (GST_IS_BUS (bus));
1451
1452   /* I know the callees don't take this lock, so go ahead and abuse it */
1453   GST_OBJECT_LOCK (bus);
1454
1455   if (bus->priv->num_signal_watchers == 0)
1456     goto error;
1457
1458   bus->priv->num_signal_watchers--;
1459
1460   if (bus->priv->num_signal_watchers > 0)
1461     goto done;
1462
1463   GST_DEBUG_OBJECT (bus, "removing signal watch %u",
1464       g_source_get_id (bus->priv->signal_watch));
1465
1466   source =
1467       bus->priv->signal_watch ? g_source_ref (bus->priv->signal_watch) : NULL;
1468
1469 done:
1470   GST_OBJECT_UNLOCK (bus);
1471
1472   if (source) {
1473     g_source_destroy (source);
1474     g_source_unref (source);
1475   }
1476
1477   return;
1478
1479   /* ERRORS */
1480 error:
1481   {
1482     g_critical ("Bus %s has no signal watches attached", GST_OBJECT_NAME (bus));
1483     GST_OBJECT_UNLOCK (bus);
1484     return;
1485   }
1486 }