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