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