Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gstreamer.git] / gst / gstbin.c
1 /* GStreamer
2  *
3  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
4  *                    2004 Wim Taymans <wim.taymans@gmail.com>
5  *
6  * gstbin.c: GstBin container object and support code
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  *
23  * MT safe.
24  */
25
26 /**
27  * SECTION:gstbin
28  * @short_description: Base class and element that can contain other elements
29  *
30  * #GstBin is an element that can contain other #GstElement, allowing them to be
31  * managed as a group.
32  * Pads from the child elements can be ghosted to the bin, see #GstGhostPad.
33  * This makes the bin look like any other elements and enables creation of
34  * higher-level abstraction elements.
35  *
36  * A new #GstBin is created with gst_bin_new(). Use a #GstPipeline instead if you
37  * want to create a toplevel bin because a normal bin doesn't have a bus or
38  * handle clock distribution of its own.
39  *
40  * After the bin has been created you will typically add elements to it with
41  * gst_bin_add(). You can remove elements with gst_bin_remove().
42  *
43  * An element can be retrieved from a bin with gst_bin_get_by_name(), using the
44  * elements name. gst_bin_get_by_name_recurse_up() is mainly used for internal
45  * purposes and will query the parent bins when the element is not found in the
46  * current bin.
47  *
48  * An iterator of elements in a bin can be retrieved with
49  * gst_bin_iterate_elements(). Various other iterators exist to retrieve the
50  * elements in a bin.
51  *
52  * gst_object_unref() is used to drop your reference to the bin.
53  *
54  * The #GstBin::element-added signal is fired whenever a new element is added to
55  * the bin. Likewise the #GstBin::element-removed signal is fired whenever an
56  * element is removed from the bin.
57  *
58  * <refsect2><title>Notes</title>
59  * <para>
60  * A #GstBin internally intercepts every #GstMessage posted by its children and
61  * implements the following default behaviour for each of them:
62  * <variablelist>
63  *   <varlistentry>
64  *     <term>GST_MESSAGE_EOS</term>
65  *     <listitem><para>This message is only posted by sinks in the PLAYING
66  *     state. If all sinks posted the EOS message, this bin will post and EOS
67  *     message upwards.</para></listitem>
68  *   </varlistentry>
69  *   <varlistentry>
70  *     <term>GST_MESSAGE_SEGMENT_START</term>
71  *     <listitem><para>just collected and never forwarded upwards.
72  *     The messages are used to decide when all elements have completed playback
73  *     of their segment.</para></listitem>
74  *   </varlistentry>
75  *   <varlistentry>
76  *     <term>GST_MESSAGE_SEGMENT_DONE</term>
77  *     <listitem><para> Is posted by #GstBin when all elements that posted
78  *     a SEGMENT_START have posted a SEGMENT_DONE.</para></listitem>
79  *   </varlistentry>
80  *   <varlistentry>
81  *     <term>GST_MESSAGE_DURATION</term>
82  *     <listitem><para> Is posted by an element that detected a change
83  *     in the stream duration. The default bin behaviour is to clear any
84  *     cached duration values so that the next duration query will perform
85  *     a full duration recalculation. The duration change is posted to the
86  *     application so that it can refetch the new duration with a duration
87  *     query. Note that these messages can be posted before the bin is
88  *     prerolled, in which case the duration query might fail.
89  *     </para></listitem>
90  *   </varlistentry>
91  *   <varlistentry>
92  *     <term>GST_MESSAGE_CLOCK_LOST</term>
93  *     <listitem><para> This message is posted by an element when it
94  *     can no longer provide a clock. The default bin behaviour is to
95  *     check if the lost clock was the one provided by the bin. If so and
96  *     the bin is currently in the PLAYING state, the message is forwarded to
97  *     the bin parent.
98  *     This message is also generated when a clock provider is removed from
99  *     the bin. If this message is received by the application, it should
100  *     PAUSE the pipeline and set it back to PLAYING to force a new clock
101  *     distribution.
102  *     </para></listitem>
103  *   </varlistentry>
104  *   <varlistentry>
105  *     <term>GST_MESSAGE_CLOCK_PROVIDE</term>
106  *     <listitem><para> This message is generated when an element
107  *     can provide a clock. This mostly happens when a new clock
108  *     provider is added to the bin. The default behaviour of the bin is to
109  *     mark the currently selected clock as dirty, which will perform a clock
110  *     recalculation the next time the bin is asked to provide a clock.
111  *     This message is never sent tot the application but is forwarded to
112  *     the parent of the bin.
113  *     </para></listitem>
114  *   </varlistentry>
115  *   <varlistentry>
116  *     <term>OTHERS</term>
117  *     <listitem><para> posted upwards.</para></listitem>
118  *   </varlistentry>
119  * </variablelist>
120  *
121  *
122  * A #GstBin implements the following default behaviour for answering to a
123  * #GstQuery:
124  * <variablelist>
125  *   <varlistentry>
126  *     <term>GST_QUERY_DURATION</term>
127  *     <listitem><para>If the query has been asked before with the same format
128  *     and the bin is a toplevel bin (ie. has no parent),
129  *     use the cached previous value. If no previous value was cached, the
130  *     query is sent to all sink elements in the bin and the MAXIMUM of all
131  *     values is returned. If the bin is a toplevel bin the value is cached.
132  *     If no sinks are available in the bin, the query fails.
133  *     </para></listitem>
134  *   </varlistentry>
135  *   <varlistentry>
136  *     <term>GST_QUERY_POSITION</term>
137  *     <listitem><para>The query is sent to all sink elements in the bin and the
138  *     MAXIMUM of all values is returned. If no sinks are available in the bin,
139  *     the query fails.
140  *     </para></listitem>
141  *   </varlistentry>
142  *   <varlistentry>
143  *     <term>OTHERS</term>
144  *     <listitem><para>the query is forwarded to all sink elements, the result
145  *     of the first sink that answers the query successfully is returned. If no
146  *     sink is in the bin, the query fails.</para></listitem>
147  *   </varlistentry>
148  * </variablelist>
149  *
150  * A #GstBin will by default forward any event sent to it to all sink elements.
151  * If all the sinks return TRUE, the bin will also return TRUE, else FALSE is
152  * returned. If no sinks are in the bin, the event handler will return TRUE.
153  *
154  * </para>
155  * </refsect2>
156  *
157  * Last reviewed on 2006-04-28 (0.10.6)
158  */
159
160 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
161  * with newer GLib versions (>= 2.31.0) */
162 #define GLIB_DISABLE_DEPRECATION_WARNINGS
163 #include "gst_private.h"
164
165 #include "gstevent.h"
166 #include "gstbin.h"
167 #include "gstmarshal.h"
168 #include "gstinfo.h"
169 #include "gsterror.h"
170
171 #include "gstutils.h"
172 #include "gstchildproxy.h"
173
174 /* latency is by default enabled now.
175  * live-preroll and no-live-preroll in the environment var GST_COMPAT
176  * to enables or disable it respectively.
177  */
178 static gboolean enable_latency = TRUE;
179
180 GST_DEBUG_CATEGORY_STATIC (bin_debug);
181 #define GST_CAT_DEFAULT bin_debug
182
183 /* a bin is toplevel if it has no parent or when it is configured to behave like
184  * a toplevel bin */
185 #define BIN_IS_TOPLEVEL(bin) ((GST_OBJECT_PARENT (bin) == NULL) || bin->priv->asynchandling)
186
187 #define GST_BIN_GET_PRIVATE(obj)  \
188    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BIN, GstBinPrivate))
189
190 struct _GstBinPrivate
191 {
192   gboolean asynchandling;
193   /* if we get an ASYNC_DONE message from ourselves, this means that the
194    * subclass will simulate ASYNC behaviour without having ASYNC children. When
195    * such an ASYNC_DONE message is posted while we are doing a state change, we
196    * have to process the message after finishing the state change even when no
197    * child returned GST_STATE_CHANGE_ASYNC. */
198   gboolean pending_async_done;
199
200   guint32 structure_cookie;
201
202 #if 0
203   /* cached index */
204   GstIndex *index;
205 #endif
206
207   /* forward messages from our children */
208   gboolean message_forward;
209
210   gboolean posted_eos;
211 };
212
213 typedef struct
214 {
215   GstBin *bin;
216   guint32 cookie;
217   GstState pending;
218 } BinContinueData;
219
220 static void gst_bin_dispose (GObject * object);
221
222 static void gst_bin_set_property (GObject * object, guint prop_id,
223     const GValue * value, GParamSpec * pspec);
224 static void gst_bin_get_property (GObject * object, guint prop_id,
225     GValue * value, GParamSpec * pspec);
226
227 static GstStateChangeReturn gst_bin_change_state_func (GstElement * element,
228     GstStateChange transition);
229 static void gst_bin_state_changed (GstElement * element, GstState oldstate,
230     GstState newstate, GstState pending);
231 static GstStateChangeReturn gst_bin_get_state_func (GstElement * element,
232     GstState * state, GstState * pending, GstClockTime timeout);
233 static void bin_handle_async_done (GstBin * bin, GstStateChangeReturn ret,
234     gboolean flag_pending, gboolean reset_time);
235 static void bin_handle_async_start (GstBin * bin);
236 static void bin_push_state_continue (BinContinueData * data);
237 static void bin_do_eos (GstBin * bin);
238
239 static gboolean gst_bin_add_func (GstBin * bin, GstElement * element);
240 static gboolean gst_bin_remove_func (GstBin * bin, GstElement * element);
241
242 #if 0
243 static void gst_bin_set_index_func (GstElement * element, GstIndex * index);
244 static GstIndex *gst_bin_get_index_func (GstElement * element);
245 #endif
246
247 static GstClock *gst_bin_provide_clock_func (GstElement * element);
248 static gboolean gst_bin_set_clock_func (GstElement * element, GstClock * clock);
249
250 static void gst_bin_handle_message_func (GstBin * bin, GstMessage * message);
251 static gboolean gst_bin_send_event (GstElement * element, GstEvent * event);
252 static GstBusSyncReply bin_bus_handler (GstBus * bus,
253     GstMessage * message, GstBin * bin);
254 static gboolean gst_bin_query (GstElement * element, GstQuery * query);
255
256 static gboolean gst_bin_do_latency_func (GstBin * bin);
257
258 static void bin_remove_messages (GstBin * bin, GstObject * src,
259     GstMessageType types);
260 static void gst_bin_continue_func (BinContinueData * data);
261 static gint bin_element_is_sink (GstElement * child, GstBin * bin);
262 static gint bin_element_is_src (GstElement * child, GstBin * bin);
263
264 static GstIterator *gst_bin_sort_iterator_new (GstBin * bin);
265
266 /* Bin signals and properties */
267 enum
268 {
269   ELEMENT_ADDED,
270   ELEMENT_REMOVED,
271   DO_LATENCY,
272   LAST_SIGNAL
273 };
274
275 #define DEFAULT_ASYNC_HANDLING  FALSE
276 #define DEFAULT_MESSAGE_FORWARD FALSE
277
278 enum
279 {
280   PROP_0,
281   PROP_ASYNC_HANDLING,
282   PROP_MESSAGE_FORWARD,
283   PROP_LAST
284 };
285
286 static void gst_bin_child_proxy_init (gpointer g_iface, gpointer iface_data);
287
288 static guint gst_bin_signals[LAST_SIGNAL] = { 0 };
289
290 #define _do_init \
291 { \
292   const gchar *compat; \
293   static const GInterfaceInfo iface_info = { \
294     gst_bin_child_proxy_init, \
295     NULL, \
296     NULL}; \
297   \
298   g_type_add_interface_static (g_define_type_id, GST_TYPE_CHILD_PROXY, &iface_info); \
299   \
300   GST_DEBUG_CATEGORY_INIT (bin_debug, "bin", GST_DEBUG_BOLD, \
301       "debugging info for the 'bin' container element"); \
302   \
303   /* compatibility stuff */ \
304   compat = g_getenv ("GST_COMPAT"); \
305   if (compat != NULL) { \
306     if (strstr (compat, "no-live-preroll")) \
307       enable_latency = FALSE; \
308     else if (strstr (compat, "live-preroll")) \
309       enable_latency = TRUE; \
310   } \
311 }
312
313 #define gst_bin_parent_class parent_class
314 G_DEFINE_TYPE_WITH_CODE (GstBin, gst_bin, GST_TYPE_ELEMENT, _do_init);
315
316 static GstObject *
317 gst_bin_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
318     guint index)
319 {
320   GstObject *res;
321   GstBin *bin;
322
323   bin = GST_BIN_CAST (child_proxy);
324
325   GST_OBJECT_LOCK (bin);
326   if ((res = g_list_nth_data (bin->children, index)))
327     gst_object_ref (res);
328   GST_OBJECT_UNLOCK (bin);
329
330   return res;
331 }
332
333 static guint
334 gst_bin_child_proxy_get_children_count (GstChildProxy * child_proxy)
335 {
336   guint num;
337   GstBin *bin;
338
339   bin = GST_BIN_CAST (child_proxy);
340
341   GST_OBJECT_LOCK (bin);
342   num = bin->numchildren;
343   GST_OBJECT_UNLOCK (bin);
344
345   return num;
346 }
347
348 static void
349 gst_bin_child_proxy_init (gpointer g_iface, gpointer iface_data)
350 {
351   GstChildProxyInterface *iface = g_iface;
352
353   iface->get_children_count = gst_bin_child_proxy_get_children_count;
354   iface->get_child_by_index = gst_bin_child_proxy_get_child_by_index;
355 }
356
357 static gboolean
358 _gst_boolean_accumulator (GSignalInvocationHint * ihint,
359     GValue * return_accu, const GValue * handler_return, gpointer dummy)
360 {
361   gboolean myboolean;
362
363   myboolean = g_value_get_boolean (handler_return);
364   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
365     g_value_set_boolean (return_accu, myboolean);
366
367   GST_DEBUG ("invocation %d, %d", ihint->run_type, myboolean);
368
369   /* stop emission */
370   return FALSE;
371 }
372
373 static void
374 gst_bin_class_init (GstBinClass * klass)
375 {
376   GObjectClass *gobject_class;
377   GstElementClass *gstelement_class;
378   GError *err;
379
380   gobject_class = (GObjectClass *) klass;
381   gstelement_class = (GstElementClass *) klass;
382
383   g_type_class_add_private (klass, sizeof (GstBinPrivate));
384
385   gobject_class->set_property = gst_bin_set_property;
386   gobject_class->get_property = gst_bin_get_property;
387
388   /**
389    * GstBin:async-handling
390    *
391    * If set to #TRUE, the bin will handle asynchronous state changes.
392    * This should be used only if the bin subclass is modifying the state
393    * of its children on its own.
394    *
395    * Since: 0.10.13
396    */
397   g_object_class_install_property (gobject_class, PROP_ASYNC_HANDLING,
398       g_param_spec_boolean ("async-handling", "Async Handling",
399           "The bin will handle Asynchronous state changes",
400           DEFAULT_ASYNC_HANDLING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
401
402   /**
403    * GstBin::element-added:
404    * @bin: the #GstBin
405    * @element: the #GstElement that was added to the bin
406    *
407    * Will be emitted after the element was added to the bin.
408    */
409   gst_bin_signals[ELEMENT_ADDED] =
410       g_signal_new ("element-added", G_TYPE_FROM_CLASS (klass),
411       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstBinClass, element_added), NULL,
412       NULL, gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
413   /**
414    * GstBin::element-removed:
415    * @bin: the #GstBin
416    * @element: the #GstElement that was removed from the bin
417    *
418    * Will be emitted after the element was removed from the bin.
419    */
420   gst_bin_signals[ELEMENT_REMOVED] =
421       g_signal_new ("element-removed", G_TYPE_FROM_CLASS (klass),
422       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstBinClass, element_removed), NULL,
423       NULL, gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
424   /**
425    * GstBin::do-latency:
426    * @bin: the #GstBin
427    *
428    * Will be emitted when the bin needs to perform latency calculations. This
429    * signal is only emited for toplevel bins or when async-handling is
430    * enabled.
431    *
432    * Only one signal handler is invoked. If no signals are connected, the
433    * default handler is invoked, which will query and distribute the lowest
434    * possible latency to all sinks.
435    *
436    * Connect to this signal if the default latency calculations are not
437    * sufficient, like when you need different latencies for different sinks in
438    * the same pipeline.
439    *
440    * Since: 0.10.22
441    */
442   gst_bin_signals[DO_LATENCY] =
443       g_signal_new ("do-latency", G_TYPE_FROM_CLASS (klass),
444       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstBinClass, do_latency),
445       _gst_boolean_accumulator, NULL, gst_marshal_BOOLEAN__VOID,
446       G_TYPE_BOOLEAN, 0, G_TYPE_NONE);
447
448   /**
449    * GstBin:message-forward
450    *
451    * Forward all children messages, even those that would normally be filtered by
452    * the bin. This can be interesting when one wants to be notified of the EOS
453    * state of individual elements, for example.
454    *
455    * The messages are converted to an ELEMENT message with the bin as the
456    * source. The structure of the message is named 'GstBinForwarded' and contains
457    * a field named 'message' of type GST_TYPE_MESSAGE that contains the original
458    * forwarded message.
459    *
460    * Since: 0.10.31
461    */
462   g_object_class_install_property (gobject_class, PROP_MESSAGE_FORWARD,
463       g_param_spec_boolean ("message-forward", "Message Forward",
464           "Forwards all children messages",
465           DEFAULT_MESSAGE_FORWARD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
466
467   gobject_class->dispose = gst_bin_dispose;
468
469   gst_element_class_set_metadata (gstelement_class, "Generic bin",
470       "Generic/Bin",
471       "Simple container object",
472       "Erik Walthinsen <omega@cse.ogi.edu>,"
473       "Wim Taymans <wim.taymans@gmail.com>");
474
475   gstelement_class->change_state =
476       GST_DEBUG_FUNCPTR (gst_bin_change_state_func);
477   gstelement_class->state_changed = GST_DEBUG_FUNCPTR (gst_bin_state_changed);
478   gstelement_class->get_state = GST_DEBUG_FUNCPTR (gst_bin_get_state_func);
479 #if 0
480   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_bin_get_index_func);
481   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_bin_set_index_func);
482 #endif
483   gstelement_class->provide_clock =
484       GST_DEBUG_FUNCPTR (gst_bin_provide_clock_func);
485   gstelement_class->set_clock = GST_DEBUG_FUNCPTR (gst_bin_set_clock_func);
486
487   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_bin_send_event);
488   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_bin_query);
489
490   klass->add_element = GST_DEBUG_FUNCPTR (gst_bin_add_func);
491   klass->remove_element = GST_DEBUG_FUNCPTR (gst_bin_remove_func);
492   klass->handle_message = GST_DEBUG_FUNCPTR (gst_bin_handle_message_func);
493
494   klass->do_latency = GST_DEBUG_FUNCPTR (gst_bin_do_latency_func);
495
496   GST_DEBUG ("creating bin thread pool");
497   err = NULL;
498   klass->pool =
499       g_thread_pool_new ((GFunc) gst_bin_continue_func, NULL, -1, FALSE, &err);
500   if (err != NULL) {
501     g_critical ("could alloc threadpool %s", err->message);
502   }
503 }
504
505 static void
506 gst_bin_init (GstBin * bin)
507 {
508   GstBus *bus;
509
510   bin->numchildren = 0;
511   bin->children = NULL;
512   bin->children_cookie = 0;
513   bin->messages = NULL;
514   bin->provided_clock = NULL;
515   bin->clock_dirty = FALSE;
516
517   /* Set up a bus for listening to child elements */
518   bus = g_object_new (GST_TYPE_BUS, "enable-async", FALSE, NULL);
519   bin->child_bus = bus;
520   GST_DEBUG_OBJECT (bin, "using bus %" GST_PTR_FORMAT " to listen to children",
521       bus);
522   gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bin_bus_handler, bin);
523
524   bin->priv = GST_BIN_GET_PRIVATE (bin);
525   bin->priv->asynchandling = DEFAULT_ASYNC_HANDLING;
526   bin->priv->structure_cookie = 0;
527   bin->priv->message_forward = DEFAULT_MESSAGE_FORWARD;
528 }
529
530 static void
531 gst_bin_dispose (GObject * object)
532 {
533   GstBin *bin = GST_BIN_CAST (object);
534   GstBus **child_bus_p = &bin->child_bus;
535   GstClock **provided_clock_p = &bin->provided_clock;
536   GstElement **clock_provider_p = &bin->clock_provider;
537
538   GST_CAT_DEBUG_OBJECT (GST_CAT_REFCOUNTING, object, "dispose");
539
540   GST_OBJECT_LOCK (object);
541   gst_object_replace ((GstObject **) child_bus_p, NULL);
542   gst_object_replace ((GstObject **) provided_clock_p, NULL);
543   gst_object_replace ((GstObject **) clock_provider_p, NULL);
544   bin_remove_messages (bin, NULL, GST_MESSAGE_ANY);
545   GST_OBJECT_UNLOCK (object);
546
547   while (bin->children) {
548     gst_bin_remove (bin, GST_ELEMENT_CAST (bin->children->data));
549   }
550   if (G_UNLIKELY (bin->children != NULL)) {
551     g_critical ("could not remove elements from bin '%s'",
552         GST_STR_NULL (GST_OBJECT_NAME (object)));
553   }
554
555   G_OBJECT_CLASS (parent_class)->dispose (object);
556 }
557
558 /**
559  * gst_bin_new:
560  * @name: the name of the new bin
561  *
562  * Creates a new bin with the given name.
563  *
564  * Returns: (transfer full): a new #GstBin
565  */
566 GstElement *
567 gst_bin_new (const gchar * name)
568 {
569   return gst_element_factory_make ("bin", name);
570 }
571
572 static void
573 gst_bin_set_property (GObject * object, guint prop_id,
574     const GValue * value, GParamSpec * pspec)
575 {
576   GstBin *gstbin;
577
578   gstbin = GST_BIN_CAST (object);
579
580   switch (prop_id) {
581     case PROP_ASYNC_HANDLING:
582       GST_OBJECT_LOCK (gstbin);
583       gstbin->priv->asynchandling = g_value_get_boolean (value);
584       GST_OBJECT_UNLOCK (gstbin);
585       break;
586     case PROP_MESSAGE_FORWARD:
587       GST_OBJECT_LOCK (gstbin);
588       gstbin->priv->message_forward = g_value_get_boolean (value);
589       GST_OBJECT_UNLOCK (gstbin);
590       break;
591     default:
592       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
593       break;
594   }
595 }
596
597 static void
598 gst_bin_get_property (GObject * object, guint prop_id,
599     GValue * value, GParamSpec * pspec)
600 {
601   GstBin *gstbin;
602
603   gstbin = GST_BIN_CAST (object);
604
605   switch (prop_id) {
606     case PROP_ASYNC_HANDLING:
607       GST_OBJECT_LOCK (gstbin);
608       g_value_set_boolean (value, gstbin->priv->asynchandling);
609       GST_OBJECT_UNLOCK (gstbin);
610       break;
611     case PROP_MESSAGE_FORWARD:
612       GST_OBJECT_LOCK (gstbin);
613       g_value_set_boolean (value, gstbin->priv->message_forward);
614       GST_OBJECT_UNLOCK (gstbin);
615       break;
616     default:
617       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
618       break;
619   }
620 }
621
622 #if 0
623 /* return the cached index */
624 static GstIndex *
625 gst_bin_get_index_func (GstElement * element)
626 {
627   GstBin *bin;
628   GstIndex *result;
629
630   bin = GST_BIN_CAST (element);
631
632   GST_OBJECT_LOCK (bin);
633   if ((result = bin->priv->index))
634     gst_object_ref (result);
635   GST_OBJECT_UNLOCK (bin);
636
637   return result;
638 }
639
640 /* set the index on all elements in this bin
641  *
642  * MT safe
643  */
644 static void
645 gst_bin_set_index_func (GstElement * element, GstIndex * index)
646 {
647   GstBin *bin;
648   gboolean done;
649   GstIterator *it;
650   GstIndex *old;
651   GValue data = { 0, };
652
653   bin = GST_BIN_CAST (element);
654
655   GST_OBJECT_LOCK (bin);
656   old = bin->priv->index;
657   if (G_UNLIKELY (old == index))
658     goto was_set;
659   if (index)
660     gst_object_ref (index);
661   bin->priv->index = index;
662   GST_OBJECT_UNLOCK (bin);
663
664   if (old)
665     gst_object_unref (old);
666
667   it = gst_bin_iterate_elements (bin);
668
669   /* set the index on all elements in the bin */
670   done = FALSE;
671   while (!done) {
672     switch (gst_iterator_next (it, &data)) {
673       case GST_ITERATOR_OK:
674       {
675         GstElement *child = g_value_get_object (&data);
676
677         GST_DEBUG_OBJECT (bin, "setting index on '%s'",
678             GST_ELEMENT_NAME (child));
679         gst_element_set_index (child, index);
680
681         g_value_reset (&data);
682         break;
683       }
684       case GST_ITERATOR_RESYNC:
685         GST_DEBUG_OBJECT (bin, "iterator doing resync");
686         gst_iterator_resync (it);
687         break;
688       default:
689       case GST_ITERATOR_DONE:
690         GST_DEBUG_OBJECT (bin, "iterator done");
691         done = TRUE;
692         break;
693     }
694   }
695   g_value_unset (&data);
696   gst_iterator_free (it);
697   return;
698
699 was_set:
700   {
701     GST_DEBUG_OBJECT (bin, "index was already set");
702     GST_OBJECT_UNLOCK (bin);
703     return;
704   }
705 }
706 #endif
707
708 /* set the clock on all elements in this bin
709  *
710  * MT safe
711  */
712 static gboolean
713 gst_bin_set_clock_func (GstElement * element, GstClock * clock)
714 {
715   GstBin *bin;
716   gboolean done;
717   GstIterator *it;
718   gboolean res = TRUE;
719   GValue data = { 0, };
720
721   bin = GST_BIN_CAST (element);
722
723   it = gst_bin_iterate_elements (bin);
724
725   done = FALSE;
726   while (!done) {
727     switch (gst_iterator_next (it, &data)) {
728       case GST_ITERATOR_OK:
729       {
730         GstElement *child = g_value_get_object (&data);
731
732         res &= gst_element_set_clock (child, clock);
733
734         g_value_reset (&data);
735         break;
736       }
737       case GST_ITERATOR_RESYNC:
738         GST_DEBUG_OBJECT (bin, "iterator doing resync");
739         gst_iterator_resync (it);
740         res = TRUE;
741         break;
742       default:
743       case GST_ITERATOR_DONE:
744         GST_DEBUG_OBJECT (bin, "iterator done");
745         done = TRUE;
746         break;
747     }
748   }
749   g_value_unset (&data);
750   gst_iterator_free (it);
751
752   if (res)
753     res = GST_ELEMENT_CLASS (parent_class)->set_clock (element, clock);
754
755   return res;
756 }
757
758 /* get the clock for this bin by asking all of the children in this bin
759  *
760  * The ref of the returned clock in increased so unref after usage.
761  *
762  * We loop the elements in state order and pick the last clock we can
763  * get. This makes sure we get a clock from the source.
764  *
765  * MT safe
766  */
767 static GstClock *
768 gst_bin_provide_clock_func (GstElement * element)
769 {
770   GstClock *result = NULL;
771   GstElement *provider = NULL;
772   GstBin *bin;
773   GstIterator *it;
774   gboolean done;
775   GValue val = { 0, };
776   GstClock **provided_clock_p;
777   GstElement **clock_provider_p;
778
779   bin = GST_BIN_CAST (element);
780
781   GST_OBJECT_LOCK (bin);
782   if (!bin->clock_dirty)
783     goto not_dirty;
784
785   GST_DEBUG_OBJECT (bin, "finding new clock");
786
787   it = gst_bin_sort_iterator_new (bin);
788   GST_OBJECT_UNLOCK (bin);
789
790   done = FALSE;
791   while (!done) {
792     switch (gst_iterator_next (it, &val)) {
793       case GST_ITERATOR_OK:
794       {
795         GstElement *child = g_value_get_object (&val);
796         GstClock *clock;
797
798         clock = gst_element_provide_clock (child);
799         if (clock) {
800           GST_DEBUG_OBJECT (bin, "found candidate clock %p by element %s",
801               clock, GST_ELEMENT_NAME (child));
802           if (result) {
803             gst_object_unref (result);
804             gst_object_unref (provider);
805           }
806           result = clock;
807           provider = gst_object_ref (child);
808         }
809
810         g_value_reset (&val);
811         break;
812       }
813       case GST_ITERATOR_RESYNC:
814         gst_iterator_resync (it);
815         break;
816       default:
817       case GST_ITERATOR_DONE:
818         done = TRUE;
819         break;
820     }
821   }
822   g_value_unset (&val);
823   gst_iterator_free (it);
824
825   GST_OBJECT_LOCK (bin);
826   if (!bin->clock_dirty) {
827     if (provider)
828       gst_object_unref (provider);
829     if (result)
830       gst_object_unref (result);
831     result = NULL;
832
833     goto not_dirty;
834   }
835
836   provided_clock_p = &bin->provided_clock;
837   clock_provider_p = &bin->clock_provider;
838   gst_object_replace ((GstObject **) provided_clock_p, (GstObject *) result);
839   gst_object_replace ((GstObject **) clock_provider_p, (GstObject *) provider);
840   bin->clock_dirty = FALSE;
841   GST_DEBUG_OBJECT (bin,
842       "provided new clock %" GST_PTR_FORMAT " by provider %" GST_PTR_FORMAT,
843       result, provider);
844   /* Provider is not being returned to caller, just the result */
845   if (provider)
846     gst_object_unref (provider);
847   GST_OBJECT_UNLOCK (bin);
848
849   return result;
850
851 not_dirty:
852   {
853     if ((result = bin->provided_clock))
854       gst_object_ref (result);
855     GST_DEBUG_OBJECT (bin, "returning old clock %p", result);
856     GST_OBJECT_UNLOCK (bin);
857
858     return result;
859   }
860 }
861
862 /*
863  * functions for manipulating cached messages
864  */
865 typedef struct
866 {
867   GstObject *src;
868   GstMessageType types;
869 } MessageFind;
870
871 /* check if a message is of given src and type */
872 static gint
873 message_check (GstMessage * message, MessageFind * target)
874 {
875   gboolean eq = TRUE;
876
877   if (target->src)
878     eq &= GST_MESSAGE_SRC (message) == target->src;
879   if (target->types)
880     eq &= (GST_MESSAGE_TYPE (message) & target->types) != 0;
881   GST_LOG ("looking at message %p: %d", message, eq);
882
883   return (eq ? 0 : 1);
884 }
885
886 static GList *
887 find_message (GstBin * bin, GstObject * src, GstMessageType types)
888 {
889   GList *result;
890   MessageFind find;
891
892   find.src = src;
893   find.types = types;
894
895   result = g_list_find_custom (bin->messages, &find,
896       (GCompareFunc) message_check);
897
898   if (result) {
899     GST_DEBUG_OBJECT (bin, "we found a message %p from %s matching types %08x",
900         result->data, GST_OBJECT_NAME (GST_MESSAGE_CAST (result->data)->src),
901         types);
902   } else {
903     GST_DEBUG_OBJECT (bin, "no message found matching types %08x", types);
904 #ifndef GST_DISABLE_GST_DEBUG
905     {
906       guint i;
907
908       for (i = 0; i < 32; i++)
909         if (types & (1 << i))
910           GST_DEBUG_OBJECT (bin, "  %s", gst_message_type_get_name (1 << i));
911     }
912 #endif
913   }
914
915   return result;
916 }
917
918 /* with LOCK, returns TRUE if message had a valid SRC, takes ownership of
919  * the message.
920  *
921  * A message that is cached and has the same SRC and type is replaced
922  * by the given message.
923  */
924 static gboolean
925 bin_replace_message (GstBin * bin, GstMessage * message, GstMessageType types)
926 {
927   GList *previous;
928   GstObject *src;
929   gboolean res = TRUE;
930
931   if ((src = GST_MESSAGE_SRC (message))) {
932     /* first find the previous message posted by this element */
933     if ((previous = find_message (bin, src, types))) {
934       GstMessage *previous_msg;
935
936       /* if we found a previous message, replace it */
937       previous_msg = previous->data;
938       previous->data = message;
939
940       GST_DEBUG_OBJECT (bin, "replace old message %s from %s with %s message",
941           GST_MESSAGE_TYPE_NAME (previous_msg), GST_ELEMENT_NAME (src),
942           GST_MESSAGE_TYPE_NAME (message));
943
944       gst_message_unref (previous_msg);
945     } else {
946       /* keep new message */
947       bin->messages = g_list_prepend (bin->messages, message);
948
949       GST_DEBUG_OBJECT (bin, "got new message %p, %s from %s",
950           message, GST_MESSAGE_TYPE_NAME (message), GST_ELEMENT_NAME (src));
951     }
952   } else {
953     GST_DEBUG_OBJECT (bin, "got message %s from (NULL), not processing",
954         GST_MESSAGE_TYPE_NAME (message));
955     res = FALSE;
956     gst_message_unref (message);
957   }
958   return res;
959 }
960
961 /* with LOCK. Remove all messages of given types */
962 static void
963 bin_remove_messages (GstBin * bin, GstObject * src, GstMessageType types)
964 {
965   MessageFind find;
966   GList *walk, *next;
967
968   find.src = src;
969   find.types = types;
970
971   for (walk = bin->messages; walk; walk = next) {
972     GstMessage *message = (GstMessage *) walk->data;
973
974     next = g_list_next (walk);
975
976     if (message_check (message, &find) == 0) {
977       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (message),
978           "deleting message %p of types 0x%08x", message, types);
979       bin->messages = g_list_delete_link (bin->messages, walk);
980       gst_message_unref (message);
981     } else {
982       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (message),
983           "not deleting message %p of type 0x%08x", message,
984           GST_MESSAGE_TYPE (message));
985     }
986   }
987 }
988
989
990 /* Check if the bin is EOS. We do this by scanning all sinks and
991  * checking if they posted an EOS message.
992  *
993  * call with bin LOCK */
994 static gboolean
995 is_eos (GstBin * bin, guint32 * seqnum)
996 {
997   gboolean result;
998   gint n_eos = 0;
999   GList *walk, *msgs;
1000
1001   result = TRUE;
1002   for (walk = bin->children; walk; walk = g_list_next (walk)) {
1003     GstElement *element;
1004
1005     element = GST_ELEMENT_CAST (walk->data);
1006     if (bin_element_is_sink (element, bin) == 0) {
1007       /* check if element posted EOS */
1008       if ((msgs =
1009               find_message (bin, GST_OBJECT_CAST (element), GST_MESSAGE_EOS))) {
1010         GST_DEBUG ("sink '%s' posted EOS", GST_ELEMENT_NAME (element));
1011         *seqnum = gst_message_get_seqnum (GST_MESSAGE_CAST (msgs->data));
1012         n_eos++;
1013       } else {
1014         GST_DEBUG ("sink '%s' did not post EOS yet",
1015             GST_ELEMENT_NAME (element));
1016         result = FALSE;
1017         break;
1018       }
1019     }
1020   }
1021   /* FIXME: Some tests (e.g. elements/capsfilter) use
1022    * pipelines with a dangling sinkpad but no sink element.
1023    * These tests assume that no EOS message is ever
1024    * posted on the bus so let's keep that behaviour.
1025    * In valid pipelines this doesn't make a difference.
1026    */
1027   return result && n_eos > 0;
1028 }
1029
1030 static void
1031 unlink_pads (const GValue * item, gpointer user_data)
1032 {
1033   GstPad *pad;
1034   GstPad *peer;
1035
1036   pad = g_value_get_object (item);
1037
1038   if ((peer = gst_pad_get_peer (pad))) {
1039     if (gst_pad_get_direction (pad) == GST_PAD_SRC)
1040       gst_pad_unlink (pad, peer);
1041     else
1042       gst_pad_unlink (peer, pad);
1043     gst_object_unref (peer);
1044   }
1045 }
1046
1047 /* vmethod that adds an element to a bin
1048  *
1049  * MT safe
1050  */
1051 static gboolean
1052 gst_bin_add_func (GstBin * bin, GstElement * element)
1053 {
1054   gchar *elem_name;
1055   GstIterator *it;
1056   gboolean is_sink, is_source, provides_clock, requires_clock;
1057   GstMessage *clock_message = NULL, *async_message = NULL;
1058   GstStateChangeReturn ret;
1059
1060   GST_DEBUG_OBJECT (bin, "element :%s", GST_ELEMENT_NAME (element));
1061
1062   /* we obviously can't add ourself to ourself */
1063   if (G_UNLIKELY (GST_ELEMENT_CAST (element) == GST_ELEMENT_CAST (bin)))
1064     goto adding_itself;
1065
1066   /* get the element name to make sure it is unique in this bin. */
1067   GST_OBJECT_LOCK (element);
1068   elem_name = g_strdup (GST_ELEMENT_NAME (element));
1069   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_SINK);
1070   is_source = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_SOURCE);
1071   provides_clock =
1072       GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1073   requires_clock =
1074       GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_REQUIRE_CLOCK);
1075   GST_OBJECT_UNLOCK (element);
1076
1077   GST_OBJECT_LOCK (bin);
1078
1079   /* then check to see if the element's name is already taken in the bin,
1080    * we can safely take the lock here. This check is probably bogus because
1081    * you can safely change the element name after this check and before setting
1082    * the object parent. The window is very small though... */
1083   if (G_UNLIKELY (!gst_object_check_uniqueness (bin->children, elem_name)))
1084     goto duplicate_name;
1085
1086   /* set the element's parent and add the element to the bin's list of children */
1087   if (G_UNLIKELY (!gst_object_set_parent (GST_OBJECT_CAST (element),
1088               GST_OBJECT_CAST (bin))))
1089     goto had_parent;
1090
1091   /* if we add a sink we become a sink */
1092   if (is_sink) {
1093     GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "element \"%s\" was sink",
1094         elem_name);
1095     GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_FLAG_SINK);
1096   }
1097   if (is_source) {
1098     GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "element \"%s\" was source",
1099         elem_name);
1100     GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_FLAG_SOURCE);
1101   }
1102   if (provides_clock) {
1103     GST_DEBUG_OBJECT (bin, "element \"%s\" can provide a clock", elem_name);
1104     clock_message =
1105         gst_message_new_clock_provide (GST_OBJECT_CAST (element), NULL, TRUE);
1106     GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1107   }
1108   if (requires_clock) {
1109     GST_DEBUG_OBJECT (bin, "element \"%s\" requires a clock", elem_name);
1110     GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_FLAG_REQUIRE_CLOCK);
1111   }
1112
1113   bin->children = g_list_prepend (bin->children, element);
1114   bin->numchildren++;
1115   bin->children_cookie++;
1116   bin->priv->structure_cookie++;
1117
1118   /* distribute the bus */
1119   gst_element_set_bus (element, bin->child_bus);
1120
1121   /* propagate the current base_time, start_time and clock */
1122   gst_element_set_base_time (element, GST_ELEMENT_CAST (bin)->base_time);
1123   gst_element_set_start_time (element, GST_ELEMENT_START_TIME (bin));
1124   /* it's possible that the element did not accept the clock but
1125    * that is not important right now. When the pipeline goes to PLAYING,
1126    * a new clock will be selected */
1127   gst_element_set_clock (element, GST_ELEMENT_CLOCK (bin));
1128
1129 #if 0
1130   /* set the cached index on the children */
1131   if (bin->priv->index)
1132     gst_element_set_index (element, bin->priv->index);
1133 #endif
1134
1135   ret = GST_STATE_RETURN (bin);
1136   /* no need to update the state if we are in error */
1137   if (ret == GST_STATE_CHANGE_FAILURE)
1138     goto no_state_recalc;
1139
1140   /* update the bin state, the new element could have been an ASYNC or
1141    * NO_PREROLL element */
1142   ret = GST_STATE_RETURN (element);
1143   GST_DEBUG_OBJECT (bin, "added %s element",
1144       gst_element_state_change_return_get_name (ret));
1145
1146   switch (ret) {
1147     case GST_STATE_CHANGE_ASYNC:
1148     {
1149       /* create message to track this aync element when it posts an async-done
1150        * message */
1151       async_message = gst_message_new_async_start (GST_OBJECT_CAST (element));
1152       break;
1153     }
1154     case GST_STATE_CHANGE_NO_PREROLL:
1155       /* ignore all async elements we might have and commit our state */
1156       bin_handle_async_done (bin, ret, FALSE, FALSE);
1157       break;
1158     case GST_STATE_CHANGE_FAILURE:
1159       break;
1160     default:
1161       break;
1162   }
1163
1164 no_state_recalc:
1165   GST_OBJECT_UNLOCK (bin);
1166
1167   /* post the messages on the bus of the element so that the bin can handle
1168    * them */
1169   if (clock_message)
1170     gst_element_post_message (GST_ELEMENT_CAST (element), clock_message);
1171
1172   if (async_message)
1173     gst_element_post_message (GST_ELEMENT_CAST (element), async_message);
1174
1175   /* unlink all linked pads */
1176   it = gst_element_iterate_pads (element);
1177   gst_iterator_foreach (it, (GstIteratorForeachFunction) unlink_pads, NULL);
1178   gst_iterator_free (it);
1179
1180   GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "added element \"%s\"",
1181       elem_name);
1182   g_free (elem_name);
1183
1184   g_signal_emit (bin, gst_bin_signals[ELEMENT_ADDED], 0, element);
1185   gst_child_proxy_child_added ((GstObject *) bin, (GstObject *) element);
1186
1187   return TRUE;
1188
1189   /* ERROR handling here */
1190 adding_itself:
1191   {
1192     GST_OBJECT_LOCK (bin);
1193     g_warning ("Cannot add bin '%s' to itself", GST_ELEMENT_NAME (bin));
1194     GST_OBJECT_UNLOCK (bin);
1195     return FALSE;
1196   }
1197 duplicate_name:
1198   {
1199     g_warning ("Name '%s' is not unique in bin '%s', not adding",
1200         elem_name, GST_ELEMENT_NAME (bin));
1201     GST_OBJECT_UNLOCK (bin);
1202     g_free (elem_name);
1203     return FALSE;
1204   }
1205 had_parent:
1206   {
1207     g_warning ("Element '%s' already has parent", elem_name);
1208     GST_OBJECT_UNLOCK (bin);
1209     g_free (elem_name);
1210     return FALSE;
1211   }
1212 }
1213
1214 /**
1215  * gst_bin_add:
1216  * @bin: a #GstBin
1217  * @element: (transfer full): the #GstElement to add
1218  *
1219  * Adds the given element to the bin.  Sets the element's parent, and thus
1220  * takes ownership of the element. An element can only be added to one bin.
1221  *
1222  * If the element's pads are linked to other pads, the pads will be unlinked
1223  * before the element is added to the bin.
1224  *
1225  * <note>
1226  * When you add an element to an already-running pipeline, you will have to
1227  * take care to set the state of the newly-added element to the desired
1228  * state (usually PLAYING or PAUSED, same you set the pipeline to originally)
1229  * with gst_element_set_state(), or use gst_element_sync_state_with_parent().
1230  * The bin or pipeline will not take care of this for you.
1231  * </note>
1232  *
1233  * MT safe.
1234  *
1235  * Returns: TRUE if the element could be added, FALSE if
1236  * the bin does not want to accept the element.
1237  */
1238 gboolean
1239 gst_bin_add (GstBin * bin, GstElement * element)
1240 {
1241   GstBinClass *bclass;
1242   gboolean result;
1243
1244   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
1245   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1246
1247   bclass = GST_BIN_GET_CLASS (bin);
1248
1249   if (G_UNLIKELY (bclass->add_element == NULL))
1250     goto no_function;
1251
1252   GST_CAT_DEBUG (GST_CAT_PARENTAGE, "adding element %s to bin %s",
1253       GST_STR_NULL (GST_ELEMENT_NAME (element)),
1254       GST_STR_NULL (GST_ELEMENT_NAME (bin)));
1255
1256   result = bclass->add_element (bin, element);
1257
1258   return result;
1259
1260   /* ERROR handling */
1261 no_function:
1262   {
1263     g_warning ("adding elements to bin '%s' is not supported",
1264         GST_ELEMENT_NAME (bin));
1265     return FALSE;
1266   }
1267 }
1268
1269 /* remove an element from the bin
1270  *
1271  * MT safe
1272  */
1273 static gboolean
1274 gst_bin_remove_func (GstBin * bin, GstElement * element)
1275 {
1276   gchar *elem_name;
1277   GstIterator *it;
1278   gboolean is_sink, is_source, provides_clock, requires_clock;
1279   gboolean othersink, othersource, otherprovider, otherrequirer, found;
1280   GstMessage *clock_message = NULL;
1281   GstClock **provided_clock_p;
1282   GstElement **clock_provider_p;
1283   GList *walk, *next;
1284   gboolean other_async, this_async, have_no_preroll;
1285   GstStateChangeReturn ret;
1286
1287   GST_DEBUG_OBJECT (bin, "element :%s", GST_ELEMENT_NAME (element));
1288
1289   GST_OBJECT_LOCK (element);
1290   /* Check if the element is already being removed and immediately
1291    * return */
1292   if (G_UNLIKELY (GST_OBJECT_FLAG_IS_SET (element,
1293               GST_ELEMENT_FLAG_UNPARENTING)))
1294     goto already_removing;
1295
1296   GST_OBJECT_FLAG_SET (element, GST_ELEMENT_FLAG_UNPARENTING);
1297   /* grab element name so we can print it */
1298   elem_name = g_strdup (GST_ELEMENT_NAME (element));
1299   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_SINK);
1300   is_source = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_SOURCE);
1301   provides_clock =
1302       GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1303   requires_clock =
1304       GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_REQUIRE_CLOCK);
1305   GST_OBJECT_UNLOCK (element);
1306
1307   /* unlink all linked pads */
1308   it = gst_element_iterate_pads (element);
1309   gst_iterator_foreach (it, (GstIteratorForeachFunction) unlink_pads, NULL);
1310   gst_iterator_free (it);
1311
1312   GST_OBJECT_LOCK (bin);
1313   found = FALSE;
1314   othersink = FALSE;
1315   othersource = FALSE;
1316   otherprovider = FALSE;
1317   otherrequirer = FALSE;
1318   have_no_preroll = FALSE;
1319   /* iterate the elements, we collect which ones are async and no_preroll. We
1320    * also remove the element when we find it. */
1321   for (walk = bin->children; walk; walk = next) {
1322     GstElement *child = GST_ELEMENT_CAST (walk->data);
1323
1324     next = g_list_next (walk);
1325
1326     if (child == element) {
1327       found = TRUE;
1328       /* remove the element */
1329       bin->children = g_list_delete_link (bin->children, walk);
1330     } else {
1331       gboolean child_sink, child_source, child_provider, child_requirer;
1332
1333       GST_OBJECT_LOCK (child);
1334       child_sink = GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_FLAG_SINK);
1335       child_source = GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_FLAG_SOURCE);
1336       child_provider =
1337           GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1338       child_requirer =
1339           GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_FLAG_REQUIRE_CLOCK);
1340       /* when we remove a sink, check if there are other sinks. */
1341       if (is_sink && !othersink && child_sink)
1342         othersink = TRUE;
1343       if (is_source && !othersource && child_source)
1344         othersource = TRUE;
1345       if (provides_clock && !otherprovider && child_provider)
1346         otherprovider = TRUE;
1347       if (requires_clock && !otherrequirer && child_requirer)
1348         otherrequirer = TRUE;
1349       /* check if we have NO_PREROLL children */
1350       if (GST_STATE_RETURN (child) == GST_STATE_CHANGE_NO_PREROLL)
1351         have_no_preroll = TRUE;
1352       GST_OBJECT_UNLOCK (child);
1353     }
1354   }
1355
1356   /* the element must have been in the bin's list of children */
1357   if (G_UNLIKELY (!found))
1358     goto not_in_bin;
1359
1360   /* we now removed the element from the list of elements, increment the cookie
1361    * so that others can detect a change in the children list. */
1362   bin->numchildren--;
1363   bin->children_cookie++;
1364   bin->priv->structure_cookie++;
1365
1366   if (is_sink && !othersink) {
1367     /* we're not a sink anymore */
1368     GST_DEBUG_OBJECT (bin, "we removed the last sink");
1369     GST_OBJECT_FLAG_UNSET (bin, GST_ELEMENT_FLAG_SINK);
1370   }
1371   if (is_source && !othersource) {
1372     /* we're not a source anymore */
1373     GST_DEBUG_OBJECT (bin, "we removed the last source");
1374     GST_OBJECT_FLAG_UNSET (bin, GST_ELEMENT_FLAG_SOURCE);
1375   }
1376   if (provides_clock && !otherprovider) {
1377     /* we're not a clock provider anymore */
1378     GST_DEBUG_OBJECT (bin, "we removed the last clock provider");
1379     GST_OBJECT_FLAG_UNSET (bin, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1380   }
1381   if (requires_clock && !otherrequirer) {
1382     /* we're not a clock requirer anymore */
1383     GST_DEBUG_OBJECT (bin, "we removed the last clock requirer");
1384     GST_OBJECT_FLAG_UNSET (bin, GST_ELEMENT_FLAG_REQUIRE_CLOCK);
1385   }
1386
1387   /* if the clock provider for this element is removed, we lost
1388    * the clock as well, we need to inform the parent of this
1389    * so that it can select a new clock */
1390   if (bin->clock_provider == element) {
1391     GST_DEBUG_OBJECT (bin, "element \"%s\" provided the clock", elem_name);
1392     bin->clock_dirty = TRUE;
1393     clock_message =
1394         gst_message_new_clock_lost (GST_OBJECT_CAST (bin), bin->provided_clock);
1395     provided_clock_p = &bin->provided_clock;
1396     clock_provider_p = &bin->clock_provider;
1397     gst_object_replace ((GstObject **) provided_clock_p, NULL);
1398     gst_object_replace ((GstObject **) clock_provider_p, NULL);
1399   }
1400
1401   /* remove messages for the element, if there was a pending ASYNC_START
1402    * message we must see if removing the element caused the bin to lose its
1403    * async state. */
1404   this_async = FALSE;
1405   other_async = FALSE;
1406   for (walk = bin->messages; walk; walk = next) {
1407     GstMessage *message = (GstMessage *) walk->data;
1408     GstElement *src = GST_ELEMENT_CAST (GST_MESSAGE_SRC (message));
1409     gboolean remove;
1410
1411     next = g_list_next (walk);
1412     remove = FALSE;
1413
1414     switch (GST_MESSAGE_TYPE (message)) {
1415       case GST_MESSAGE_ASYNC_START:
1416         if (src == element)
1417           this_async = TRUE;
1418         else
1419           other_async = TRUE;
1420
1421         GST_DEBUG_OBJECT (src, "looking at message %p", message);
1422         break;
1423       case GST_MESSAGE_STRUCTURE_CHANGE:
1424       {
1425         GstElement *owner;
1426
1427         GST_DEBUG_OBJECT (src, "looking at structure change message %p",
1428             message);
1429         /* it's unlikely that this message is still in the list of messages
1430          * because this would mean that a link/unlink is busy in another thread
1431          * while we remove the element. We still have to remove the message
1432          * because we might not receive the done message anymore when the element
1433          * is removed from the bin. */
1434         gst_message_parse_structure_change (message, NULL, &owner, NULL);
1435         if (owner == element)
1436           remove = TRUE;
1437         break;
1438       }
1439       default:
1440         break;
1441     }
1442     if (src == element)
1443       remove = TRUE;
1444
1445     if (remove) {
1446       /* delete all message types */
1447       GST_DEBUG_OBJECT (src, "deleting message %p of element \"%s\"",
1448           message, elem_name);
1449       bin->messages = g_list_delete_link (bin->messages, walk);
1450       gst_message_unref (message);
1451     }
1452   }
1453
1454   /* get last return */
1455   ret = GST_STATE_RETURN (bin);
1456
1457   /* no need to update the state if we are in error */
1458   if (ret == GST_STATE_CHANGE_FAILURE)
1459     goto no_state_recalc;
1460
1461   if (!other_async && this_async) {
1462     /* all other elements were not async and we removed the async one,
1463      * handle the async-done case because we are not async anymore now. */
1464     GST_DEBUG_OBJECT (bin,
1465         "we removed the last async element, have no_preroll %d",
1466         have_no_preroll);
1467
1468     /* the current state return of the bin depends on if there are no_preroll
1469      * elements in the pipeline or not */
1470     if (have_no_preroll)
1471       ret = GST_STATE_CHANGE_NO_PREROLL;
1472     else
1473       ret = GST_STATE_CHANGE_SUCCESS;
1474
1475     bin_handle_async_done (bin, ret, FALSE, FALSE);
1476   } else {
1477     GST_DEBUG_OBJECT (bin,
1478         "recalc state preroll: %d, other async: %d, this async %d",
1479         have_no_preroll, other_async, this_async);
1480
1481     if (have_no_preroll) {
1482       ret = GST_STATE_CHANGE_NO_PREROLL;
1483     } else if (other_async) {
1484       /* there are other async elements and we were not doing an async state
1485        * change, change our pending state and go async */
1486       if (GST_STATE_PENDING (bin) == GST_STATE_VOID_PENDING) {
1487         GST_STATE_NEXT (bin) = GST_STATE (bin);
1488         GST_STATE_PENDING (bin) = GST_STATE (bin);
1489       }
1490       ret = GST_STATE_CHANGE_ASYNC;
1491     }
1492     GST_STATE_RETURN (bin) = ret;
1493   }
1494 no_state_recalc:
1495   GST_OBJECT_UNLOCK (bin);
1496
1497   if (clock_message)
1498     gst_element_post_message (GST_ELEMENT_CAST (bin), clock_message);
1499
1500   GST_CAT_INFO_OBJECT (GST_CAT_PARENTAGE, bin, "removed child \"%s\"",
1501       elem_name);
1502   g_free (elem_name);
1503
1504   gst_element_set_bus (element, NULL);
1505
1506   /* Clear the clock we provided to the element */
1507   gst_element_set_clock (element, NULL);
1508
1509   /* we ref here because after the _unparent() the element can be disposed
1510    * and we still need it to reset the UNPARENTING flag and fire a signal. */
1511   gst_object_ref (element);
1512   gst_object_unparent (GST_OBJECT_CAST (element));
1513
1514   GST_OBJECT_LOCK (element);
1515   GST_OBJECT_FLAG_UNSET (element, GST_ELEMENT_FLAG_UNPARENTING);
1516   GST_OBJECT_UNLOCK (element);
1517
1518   g_signal_emit (bin, gst_bin_signals[ELEMENT_REMOVED], 0, element);
1519   gst_child_proxy_child_removed ((GstObject *) bin, (GstObject *) element);
1520
1521   /* element is really out of our control now */
1522   gst_object_unref (element);
1523
1524   return TRUE;
1525
1526   /* ERROR handling */
1527 not_in_bin:
1528   {
1529     g_warning ("Element '%s' is not in bin '%s'", elem_name,
1530         GST_ELEMENT_NAME (bin));
1531     GST_OBJECT_UNLOCK (bin);
1532     g_free (elem_name);
1533     return FALSE;
1534   }
1535 already_removing:
1536   {
1537     GST_CAT_INFO_OBJECT (GST_CAT_PARENTAGE, bin, "already removing child");
1538     GST_OBJECT_UNLOCK (element);
1539     return FALSE;
1540   }
1541 }
1542
1543 /**
1544  * gst_bin_remove:
1545  * @bin: a #GstBin
1546  * @element: (transfer none): the #GstElement to remove
1547  *
1548  * Removes the element from the bin, unparenting it as well.
1549  * Unparenting the element means that the element will be dereferenced,
1550  * so if the bin holds the only reference to the element, the element
1551  * will be freed in the process of removing it from the bin.  If you
1552  * want the element to still exist after removing, you need to call
1553  * gst_object_ref() before removing it from the bin.
1554  *
1555  * If the element's pads are linked to other pads, the pads will be unlinked
1556  * before the element is removed from the bin.
1557  *
1558  * MT safe.
1559  *
1560  * Returns: TRUE if the element could be removed, FALSE if
1561  * the bin does not want to remove the element.
1562  */
1563 gboolean
1564 gst_bin_remove (GstBin * bin, GstElement * element)
1565 {
1566   GstBinClass *bclass;
1567   gboolean result;
1568
1569   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
1570   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1571
1572   bclass = GST_BIN_GET_CLASS (bin);
1573
1574   if (G_UNLIKELY (bclass->remove_element == NULL))
1575     goto no_function;
1576
1577   GST_CAT_DEBUG (GST_CAT_PARENTAGE, "removing element %s from bin %s",
1578       GST_ELEMENT_NAME (element), GST_ELEMENT_NAME (bin));
1579
1580   result = bclass->remove_element (bin, element);
1581
1582   return result;
1583
1584   /* ERROR handling */
1585 no_function:
1586   {
1587     g_warning ("removing elements from bin '%s' is not supported",
1588         GST_ELEMENT_NAME (bin));
1589     return FALSE;
1590   }
1591 }
1592
1593 /**
1594  * gst_bin_iterate_elements:
1595  * @bin: a #GstBin
1596  *
1597  * Gets an iterator for the elements in this bin.
1598  *
1599  * Each element yielded by the iterator will have its refcount increased, so
1600  * unref after use.
1601  *
1602  * MT safe.  Caller owns returned value.
1603  *
1604  * Returns: (transfer full): a #GstIterator of #GstElement, or NULL
1605  */
1606 GstIterator *
1607 gst_bin_iterate_elements (GstBin * bin)
1608 {
1609   GstIterator *result;
1610
1611   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1612
1613   GST_OBJECT_LOCK (bin);
1614   result = gst_iterator_new_list (GST_TYPE_ELEMENT,
1615       GST_OBJECT_GET_LOCK (bin),
1616       &bin->children_cookie, &bin->children, (GObject *) bin, NULL);
1617   GST_OBJECT_UNLOCK (bin);
1618
1619   return result;
1620 }
1621
1622 static GstIteratorItem
1623 iterate_child_recurse (GstIterator * it, const GValue * item)
1624 {
1625   GstElement *child = g_value_get_object (item);
1626
1627   if (GST_IS_BIN (child)) {
1628     GstIterator *other = gst_bin_iterate_recurse (GST_BIN_CAST (child));
1629
1630     gst_iterator_push (it, other);
1631   }
1632   return GST_ITERATOR_ITEM_PASS;
1633 }
1634
1635 /**
1636  * gst_bin_iterate_recurse:
1637  * @bin: a #GstBin
1638  *
1639  * Gets an iterator for the elements in this bin.
1640  * This iterator recurses into GstBin children.
1641  *
1642  * Each element yielded by the iterator will have its refcount increased, so
1643  * unref after use.
1644  *
1645  * MT safe.  Caller owns returned value.
1646  *
1647  * Returns: (transfer full): a #GstIterator of #GstElement, or NULL
1648  */
1649 GstIterator *
1650 gst_bin_iterate_recurse (GstBin * bin)
1651 {
1652   GstIterator *result;
1653
1654   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1655
1656   GST_OBJECT_LOCK (bin);
1657   result = gst_iterator_new_list (GST_TYPE_ELEMENT,
1658       GST_OBJECT_GET_LOCK (bin),
1659       &bin->children_cookie,
1660       &bin->children,
1661       (GObject *) bin, (GstIteratorItemFunction) iterate_child_recurse);
1662   GST_OBJECT_UNLOCK (bin);
1663
1664   return result;
1665 }
1666
1667 /* returns 0 when TRUE because this is a GCompareFunc */
1668 /* MT safe */
1669 static gint
1670 bin_element_is_sink (GstElement * child, GstBin * bin)
1671 {
1672   gboolean is_sink;
1673
1674   /* we lock the child here for the remainder of the function to
1675    * get its name and flag safely. */
1676   GST_OBJECT_LOCK (child);
1677   is_sink = GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_FLAG_SINK);
1678
1679   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
1680       "child %s %s sink", GST_OBJECT_NAME (child), is_sink ? "is" : "is not");
1681
1682   GST_OBJECT_UNLOCK (child);
1683   return is_sink ? 0 : 1;
1684 }
1685
1686 static gint
1687 sink_iterator_filter (const GValue * vchild, GValue * vbin)
1688 {
1689   GstBin *bin = g_value_get_object (vbin);
1690   GstElement *child = g_value_get_object (vchild);
1691
1692   return (bin_element_is_sink (child, bin));
1693 }
1694
1695 /**
1696  * gst_bin_iterate_sinks:
1697  * @bin: a #GstBin
1698  *
1699  * Gets an iterator for all elements in the bin that have the
1700  * #GST_ELEMENT_FLAG_SINK flag set.
1701  *
1702  * Each element yielded by the iterator will have its refcount increased, so
1703  * unref after use.
1704  *
1705  * MT safe.  Caller owns returned value.
1706  *
1707  * Returns: (transfer full): a #GstIterator of #GstElement, or NULL
1708  */
1709 GstIterator *
1710 gst_bin_iterate_sinks (GstBin * bin)
1711 {
1712   GstIterator *children;
1713   GstIterator *result;
1714   GValue vbin = { 0, };
1715
1716   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1717
1718   g_value_init (&vbin, GST_TYPE_BIN);
1719   g_value_set_object (&vbin, bin);
1720
1721   children = gst_bin_iterate_elements (bin);
1722   result = gst_iterator_filter (children,
1723       (GCompareFunc) sink_iterator_filter, &vbin);
1724
1725   g_value_unset (&vbin);
1726
1727   return result;
1728 }
1729
1730 /* returns 0 when TRUE because this is a GCompareFunc */
1731 /* MT safe */
1732 static gint
1733 bin_element_is_src (GstElement * child, GstBin * bin)
1734 {
1735   gboolean is_src;
1736
1737   /* we lock the child here for the remainder of the function to
1738    * get its name and other info safely. */
1739   GST_OBJECT_LOCK (child);
1740   is_src = GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_FLAG_SOURCE);
1741
1742   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
1743       "child %s %s src", GST_OBJECT_NAME (child), is_src ? "is" : "is not");
1744
1745   GST_OBJECT_UNLOCK (child);
1746   return is_src ? 0 : 1;
1747 }
1748
1749 static gint
1750 src_iterator_filter (const GValue * vchild, GValue * vbin)
1751 {
1752   GstBin *bin = g_value_get_object (vbin);
1753   GstElement *child = g_value_get_object (vchild);
1754
1755   return (bin_element_is_src (child, bin));
1756 }
1757
1758 /**
1759  * gst_bin_iterate_sources:
1760  * @bin: a #GstBin
1761  *
1762  * Gets an iterator for all elements in the bin that have the
1763  * #GST_ELEMENT_FLAG_SOURCE flag set.
1764  *
1765  * Each element yielded by the iterator will have its refcount increased, so
1766  * unref after use.
1767  *
1768  * MT safe.  Caller owns returned value.
1769  *
1770  * Returns: (transfer full): a #GstIterator of #GstElement, or NULL
1771  */
1772 GstIterator *
1773 gst_bin_iterate_sources (GstBin * bin)
1774 {
1775   GstIterator *children;
1776   GstIterator *result;
1777   GValue vbin = { 0, };
1778
1779   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1780
1781   g_value_init (&vbin, GST_TYPE_BIN);
1782   g_value_set_object (&vbin, bin);
1783
1784   children = gst_bin_iterate_elements (bin);
1785   result = gst_iterator_filter (children,
1786       (GCompareFunc) src_iterator_filter, &vbin);
1787
1788   g_value_unset (&vbin);
1789
1790   return result;
1791 }
1792
1793 /*
1794  * MT safe
1795  */
1796 static GstStateChangeReturn
1797 gst_bin_get_state_func (GstElement * element, GstState * state,
1798     GstState * pending, GstClockTime timeout)
1799 {
1800   GstStateChangeReturn ret;
1801
1802   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "getting state");
1803
1804   ret =
1805       GST_ELEMENT_CLASS (parent_class)->get_state (element, state, pending,
1806       timeout);
1807
1808   return ret;
1809 }
1810
1811 /***********************************************
1812  * Topologically sorted iterator
1813  * see http://en.wikipedia.org/wiki/Topological_sorting
1814  *
1815  * For each element in the graph, an entry is kept in a HashTable
1816  * with its number of srcpad connections (degree).
1817  * We then change state of all elements without dependencies
1818  * (degree 0) and decrement the degree of all elements connected
1819  * on the sinkpads. When an element reaches degree 0, its state is
1820  * changed next.
1821  * When all elements are handled the algorithm stops.
1822  */
1823 typedef struct _GstBinSortIterator
1824 {
1825   GstIterator it;
1826   GQueue queue;                 /* elements queued for state change */
1827   GstBin *bin;                  /* bin we iterate */
1828   gint mode;                    /* adding or removing dependency */
1829   GstElement *best;             /* next element with least dependencies */
1830   gint best_deg;                /* best degree */
1831   GHashTable *hash;             /* hashtable with element dependencies */
1832   gboolean dirty;               /* we detected structure change */
1833 } GstBinSortIterator;
1834
1835 static void
1836 gst_bin_sort_iterator_copy (const GstBinSortIterator * it,
1837     GstBinSortIterator * copy)
1838 {
1839   GHashTableIter iter;
1840   gpointer key, value;
1841
1842   copy->queue = it->queue;
1843   g_queue_foreach (&copy->queue, (GFunc) gst_object_ref, NULL);
1844
1845   copy->bin = gst_object_ref (it->bin);
1846   if (it->best)
1847     copy->best = gst_object_ref (it->best);
1848
1849   copy->hash = g_hash_table_new (NULL, NULL);
1850   g_hash_table_iter_init (&iter, it->hash);
1851   while (g_hash_table_iter_next (&iter, &key, &value))
1852     g_hash_table_insert (copy->hash, key, value);
1853 }
1854
1855 /* we add and subtract 1 to make sure we don't confuse NULL and 0 */
1856 #define HASH_SET_DEGREE(bit, elem, deg) \
1857     g_hash_table_replace (bit->hash, elem, GINT_TO_POINTER(deg+1))
1858 #define HASH_GET_DEGREE(bit, elem) \
1859     (GPOINTER_TO_INT(g_hash_table_lookup (bit->hash, elem))-1)
1860
1861 /* add element to queue of next elements in the iterator.
1862  * We push at the tail to give higher priority elements a
1863  * chance first */
1864 static void
1865 add_to_queue (GstBinSortIterator * bit, GstElement * element)
1866 {
1867   GST_DEBUG_OBJECT (bit->bin, "adding '%s' to queue",
1868       GST_ELEMENT_NAME (element));
1869   gst_object_ref (element);
1870   g_queue_push_tail (&bit->queue, element);
1871   HASH_SET_DEGREE (bit, element, -1);
1872 }
1873
1874 static void
1875 remove_from_queue (GstBinSortIterator * bit, GstElement * element)
1876 {
1877   GList *find;
1878
1879   if ((find = g_queue_find (&bit->queue, element))) {
1880     GST_DEBUG_OBJECT (bit->bin, "removing '%s' from queue",
1881         GST_ELEMENT_NAME (element));
1882
1883     g_queue_delete_link (&bit->queue, find);
1884     gst_object_unref (element);
1885   } else {
1886     GST_DEBUG_OBJECT (bit->bin, "unable to remove '%s' from queue",
1887         GST_ELEMENT_NAME (element));
1888   }
1889 }
1890
1891 /* clear the queue, unref all objects as we took a ref when
1892  * we added them to the queue */
1893 static void
1894 clear_queue (GQueue * queue)
1895 {
1896   gpointer p;
1897
1898   while ((p = g_queue_pop_head (queue)))
1899     gst_object_unref (p);
1900 }
1901
1902 /* set all degrees to 0. Elements marked as a sink are
1903  * added to the queue immediately. Since we only look at the SINK flag of the
1904  * element, it is possible that we add non-sinks to the queue. These will be
1905  * removed from the queue again when we can prove that it provides data for some
1906  * other element. */
1907 static void
1908 reset_degree (GstElement * element, GstBinSortIterator * bit)
1909 {
1910   gboolean is_sink;
1911
1912   /* sinks are added right away */
1913   GST_OBJECT_LOCK (element);
1914   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_SINK);
1915   GST_OBJECT_UNLOCK (element);
1916
1917   if (is_sink) {
1918     add_to_queue (bit, element);
1919   } else {
1920     /* others are marked with 0 and handled when sinks are done */
1921     HASH_SET_DEGREE (bit, element, 0);
1922   }
1923 }
1924
1925 /* adjust the degree of all elements connected to the given
1926  * element. If a degree of an element drops to 0, it is
1927  * added to the queue of elements to schedule next.
1928  *
1929  * We have to make sure not to cross the bin boundary this element
1930  * belongs to.
1931  */
1932 static void
1933 update_degree (GstElement * element, GstBinSortIterator * bit)
1934 {
1935   gboolean linked = FALSE;
1936
1937   GST_OBJECT_LOCK (element);
1938   /* don't touch degree if element has no sinkpads */
1939   if (element->numsinkpads != 0) {
1940     /* loop over all sinkpads, decrement degree for all connected
1941      * elements in this bin */
1942     GList *pads;
1943
1944     for (pads = element->sinkpads; pads; pads = g_list_next (pads)) {
1945       GstPad *pad, *peer;
1946
1947       pad = GST_PAD_CAST (pads->data);
1948
1949       /* we're iterating over the sinkpads, check if it's busy in a link/unlink */
1950       if (G_UNLIKELY (find_message (bit->bin, GST_OBJECT_CAST (pad),
1951                   GST_MESSAGE_STRUCTURE_CHANGE))) {
1952         /* mark the iterator as dirty because we won't be updating the degree
1953          * of the peer parent now. This would result in the 'loop detected'
1954          * later on because the peer parent element could become the best next
1955          * element with a degree > 0. We will simply continue our state
1956          * changes and we'll eventually resync when the unlink completed and
1957          * the iterator cookie is updated. */
1958         bit->dirty = TRUE;
1959         continue;
1960       }
1961
1962       if ((peer = gst_pad_get_peer (pad))) {
1963         GstElement *peer_element;
1964
1965         if ((peer_element = gst_pad_get_parent_element (peer))) {
1966           GST_OBJECT_LOCK (peer_element);
1967           /* check that we don't go outside of this bin */
1968           if (GST_OBJECT_CAST (peer_element)->parent ==
1969               GST_OBJECT_CAST (bit->bin)) {
1970             gint old_deg, new_deg;
1971
1972             old_deg = HASH_GET_DEGREE (bit, peer_element);
1973
1974             /* check to see if we added an element as sink that was not really a
1975              * sink because it was connected to some other element. */
1976             if (old_deg == -1) {
1977               remove_from_queue (bit, peer_element);
1978               old_deg = 0;
1979             }
1980             new_deg = old_deg + bit->mode;
1981
1982             GST_DEBUG_OBJECT (bit->bin,
1983                 "change element %s, degree %d->%d, linked to %s",
1984                 GST_ELEMENT_NAME (peer_element), old_deg, new_deg,
1985                 GST_ELEMENT_NAME (element));
1986
1987             /* update degree, it is possible that an element was in 0 and
1988              * reaches -1 here. This would mean that the element had no sinkpads
1989              * but became linked while the state change was happening. We will
1990              * resync on this with the structure change message. */
1991             if (new_deg == 0) {
1992               /* degree hit 0, add to queue */
1993               add_to_queue (bit, peer_element);
1994             } else {
1995               HASH_SET_DEGREE (bit, peer_element, new_deg);
1996             }
1997             linked = TRUE;
1998           }
1999           GST_OBJECT_UNLOCK (peer_element);
2000           gst_object_unref (peer_element);
2001         }
2002         gst_object_unref (peer);
2003       }
2004     }
2005   }
2006   if (!linked) {
2007     GST_DEBUG_OBJECT (bit->bin, "element %s not linked on any sinkpads",
2008         GST_ELEMENT_NAME (element));
2009   }
2010   GST_OBJECT_UNLOCK (element);
2011 }
2012
2013 /* find the next best element not handled yet. This is the one
2014  * with the lowest non-negative degree */
2015 static void
2016 find_element (GstElement * element, GstBinSortIterator * bit)
2017 {
2018   gint degree;
2019
2020   /* element is already handled */
2021   if ((degree = HASH_GET_DEGREE (bit, element)) < 0)
2022     return;
2023
2024   /* first element or element with smaller degree */
2025   if (bit->best == NULL || bit->best_deg > degree) {
2026     bit->best = element;
2027     bit->best_deg = degree;
2028   }
2029 }
2030
2031 /* get next element in iterator. the returned element has the
2032  * refcount increased */
2033 static GstIteratorResult
2034 gst_bin_sort_iterator_next (GstBinSortIterator * bit, GValue * result)
2035 {
2036   GstElement *best;
2037   GstBin *bin = bit->bin;
2038
2039   /* empty queue, we have to find a next best element */
2040   if (g_queue_is_empty (&bit->queue)) {
2041     bit->best = NULL;
2042     bit->best_deg = G_MAXINT;
2043     g_list_foreach (bin->children, (GFunc) find_element, bit);
2044     if ((best = bit->best)) {
2045       /* when we detected an unlink, don't warn because our degrees might be
2046        * screwed up. We will resync later */
2047       if (bit->best_deg != 0 && !bit->dirty) {
2048         /* we don't fail on this one yet */
2049         GST_WARNING_OBJECT (bin, "loop dected in graph");
2050         g_warning ("loop detected in the graph of bin '%s'!!",
2051             GST_ELEMENT_NAME (bin));
2052       }
2053       /* best unhandled element, schedule as next element */
2054       GST_DEBUG_OBJECT (bin, "queue empty, next best: %s",
2055           GST_ELEMENT_NAME (best));
2056       HASH_SET_DEGREE (bit, best, -1);
2057       g_value_set_object (result, best);
2058     } else {
2059       GST_DEBUG_OBJECT (bin, "queue empty, elements exhausted");
2060       /* no more unhandled elements, we are done */
2061       return GST_ITERATOR_DONE;
2062     }
2063   } else {
2064     /* everything added to the queue got reffed */
2065     best = g_queue_pop_head (&bit->queue);
2066     g_value_set_object (result, best);
2067     gst_object_unref (best);
2068   }
2069
2070   GST_DEBUG_OBJECT (bin, "queue head gives %s", GST_ELEMENT_NAME (best));
2071   /* update degrees of linked elements */
2072   update_degree (best, bit);
2073
2074   return GST_ITERATOR_OK;
2075 }
2076
2077 /* clear queues, recalculate the degrees and restart. */
2078 static void
2079 gst_bin_sort_iterator_resync (GstBinSortIterator * bit)
2080 {
2081   GstBin *bin = bit->bin;
2082
2083   GST_DEBUG_OBJECT (bin, "resync");
2084   bit->dirty = FALSE;
2085   clear_queue (&bit->queue);
2086   /* reset degrees */
2087   g_list_foreach (bin->children, (GFunc) reset_degree, bit);
2088   /* calc degrees, incrementing */
2089   bit->mode = 1;
2090   g_list_foreach (bin->children, (GFunc) update_degree, bit);
2091   /* for the rest of the function we decrement the degrees */
2092   bit->mode = -1;
2093 }
2094
2095 /* clear queues, unref bin and free iterator. */
2096 static void
2097 gst_bin_sort_iterator_free (GstBinSortIterator * bit)
2098 {
2099   GstBin *bin = bit->bin;
2100
2101   GST_DEBUG_OBJECT (bin, "free");
2102   clear_queue (&bit->queue);
2103   g_hash_table_destroy (bit->hash);
2104   gst_object_unref (bin);
2105 }
2106
2107 /* should be called with the bin LOCK held */
2108 static GstIterator *
2109 gst_bin_sort_iterator_new (GstBin * bin)
2110 {
2111   GstBinSortIterator *result;
2112
2113   /* we don't need an ItemFunction because we ref the items in the _next
2114    * method already */
2115   result = (GstBinSortIterator *)
2116       gst_iterator_new (sizeof (GstBinSortIterator),
2117       GST_TYPE_ELEMENT,
2118       GST_OBJECT_GET_LOCK (bin),
2119       &bin->priv->structure_cookie,
2120       (GstIteratorCopyFunction) gst_bin_sort_iterator_copy,
2121       (GstIteratorNextFunction) gst_bin_sort_iterator_next,
2122       (GstIteratorItemFunction) NULL,
2123       (GstIteratorResyncFunction) gst_bin_sort_iterator_resync,
2124       (GstIteratorFreeFunction) gst_bin_sort_iterator_free);
2125   g_queue_init (&result->queue);
2126   result->hash = g_hash_table_new (NULL, NULL);
2127   gst_object_ref (bin);
2128   result->bin = bin;
2129   gst_bin_sort_iterator_resync (result);
2130
2131   return (GstIterator *) result;
2132 }
2133
2134 /**
2135  * gst_bin_iterate_sorted:
2136  * @bin: a #GstBin
2137  *
2138  * Gets an iterator for the elements in this bin in topologically
2139  * sorted order. This means that the elements are returned from
2140  * the most downstream elements (sinks) to the sources.
2141  *
2142  * This function is used internally to perform the state changes
2143  * of the bin elements and for clock selection.
2144  *
2145  * Each element yielded by the iterator will have its refcount increased, so
2146  * unref after use.
2147  *
2148  * MT safe.  Caller owns returned value.
2149  *
2150  * Returns: (transfer full): a #GstIterator of #GstElement, or NULL
2151  */
2152 GstIterator *
2153 gst_bin_iterate_sorted (GstBin * bin)
2154 {
2155   GstIterator *result;
2156
2157   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
2158
2159   GST_OBJECT_LOCK (bin);
2160   result = gst_bin_sort_iterator_new (bin);
2161   GST_OBJECT_UNLOCK (bin);
2162
2163   return result;
2164 }
2165
2166 static GstStateChangeReturn
2167 gst_bin_element_set_state (GstBin * bin, GstElement * element,
2168     GstClockTime base_time, GstClockTime start_time, GstState current,
2169     GstState next)
2170 {
2171   GstStateChangeReturn ret;
2172   GstState pending, child_current, child_pending;
2173   gboolean locked;
2174   GList *found;
2175
2176   GST_STATE_LOCK (element);
2177
2178   GST_OBJECT_LOCK (element);
2179   /* set base_time and start time on child */
2180   GST_ELEMENT_START_TIME (element) = start_time;
2181   element->base_time = base_time;
2182   /* peel off the locked flag */
2183   locked = GST_ELEMENT_IS_LOCKED_STATE (element);
2184   /* Get the previous set_state result to preserve NO_PREROLL and ASYNC */
2185   ret = GST_STATE_RETURN (element);
2186   child_current = GST_STATE (element);
2187   child_pending = GST_STATE_PENDING (element);
2188   GST_OBJECT_UNLOCK (element);
2189
2190   /* skip locked elements */
2191   if (G_UNLIKELY (locked))
2192     goto locked;
2193
2194   /* if the element was no preroll, just start changing the state regardless
2195    * if it had async elements (in the case of a bin) because they won't preroll
2196    * anyway. */
2197   if (G_UNLIKELY (ret == GST_STATE_CHANGE_NO_PREROLL)) {
2198     GST_DEBUG_OBJECT (element, "element is NO_PREROLL, ignore async elements");
2199     goto no_preroll;
2200   }
2201
2202   GST_OBJECT_LOCK (bin);
2203   pending = GST_STATE_PENDING (bin);
2204
2205   /* Try not to change the state of elements that are already in the state we're
2206    * going to */
2207   if (!(next == GST_STATE_PLAYING || child_pending != GST_STATE_VOID_PENDING ||
2208           (child_pending == GST_STATE_VOID_PENDING &&
2209               ((pending > child_current && next > child_current) ||
2210                   (pending < child_current && next < child_current)))))
2211     goto unneeded;
2212
2213   /* the element was busy with an upwards async state change, we must wait for
2214    * an ASYNC_DONE message before we attemp to change the state. */
2215   if ((found =
2216           find_message (bin, GST_OBJECT_CAST (element),
2217               GST_MESSAGE_ASYNC_START))) {
2218 #ifndef GST_DISABLE_GST_DEBUG
2219     GstMessage *message = GST_MESSAGE_CAST (found->data);
2220
2221     GST_DEBUG_OBJECT (element, "element message %p, %s async busy",
2222         message, GST_ELEMENT_NAME (GST_MESSAGE_SRC (message)));
2223 #endif
2224     /* only wait for upward state changes */
2225     if (next > current) {
2226       /* We found an async element check if we can force its state to change or
2227        * if we have to wait for it to preroll. */
2228       if (G_UNLIKELY (!enable_latency)) {
2229         g_warning ("Future versions of GStreamer will wait for element \"%s\"\n"
2230             "\tto preroll in order to perform correct latency calculations.\n"
2231             "\tPlease verify that the application continues to work correctly by\n"
2232             "\tsetting the environment variable GST_COMPAT to a value containing\n"
2233             "\tthe string 'live-preroll'.", GST_ELEMENT_NAME (element));
2234         goto no_latency;
2235       }
2236       goto was_busy;
2237     }
2238   }
2239 no_latency:
2240   GST_OBJECT_UNLOCK (bin);
2241
2242 no_preroll:
2243   GST_DEBUG_OBJECT (bin,
2244       "setting element %s to %s, base_time %" GST_TIME_FORMAT,
2245       GST_ELEMENT_NAME (element), gst_element_state_get_name (next),
2246       GST_TIME_ARGS (base_time));
2247
2248   /* change state */
2249   ret = gst_element_set_state (element, next);
2250
2251   GST_STATE_UNLOCK (element);
2252
2253   return ret;
2254
2255 locked:
2256   {
2257     GST_DEBUG_OBJECT (element,
2258         "element is locked, return previous return %s",
2259         gst_element_state_change_return_get_name (ret));
2260     GST_STATE_UNLOCK (element);
2261     return ret;
2262   }
2263 was_busy:
2264   {
2265     GST_DEBUG_OBJECT (element, "element was busy, delaying state change");
2266     GST_OBJECT_UNLOCK (bin);
2267     GST_STATE_UNLOCK (element);
2268     return GST_STATE_CHANGE_ASYNC;
2269   }
2270 unneeded:
2271   {
2272     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2273         "skipping transition from %s to  %s, since bin pending"
2274         " is %s : last change state return follows",
2275         gst_element_state_get_name (child_current),
2276         gst_element_state_get_name (next),
2277         gst_element_state_get_name (pending));
2278     GST_OBJECT_UNLOCK (bin);
2279     GST_STATE_UNLOCK (element);
2280     return ret;
2281   }
2282 }
2283
2284 /* gst_iterator_fold functions for pads_activate
2285  * Stop the iterator if activating one pad failed. */
2286 static gboolean
2287 activate_pads (const GValue * vpad, GValue * ret, gboolean * active)
2288 {
2289   GstPad *pad = g_value_get_object (vpad);
2290   gboolean cont = TRUE;
2291
2292   if (!(cont = gst_pad_set_active (pad, *active)))
2293     g_value_set_boolean (ret, FALSE);
2294
2295   return cont;
2296 }
2297
2298 /* returns false on error or early cutout of the fold, true if all
2299  * pads in @iter were (de)activated successfully. */
2300 static gboolean
2301 iterator_activate_fold_with_resync (GstIterator * iter, gpointer user_data)
2302 {
2303   GstIteratorResult ires;
2304   GValue ret = { 0 };
2305
2306   /* no need to unset this later, it's just a boolean */
2307   g_value_init (&ret, G_TYPE_BOOLEAN);
2308   g_value_set_boolean (&ret, TRUE);
2309
2310   while (1) {
2311     ires = gst_iterator_fold (iter, (GstIteratorFoldFunction) activate_pads,
2312         &ret, user_data);
2313     switch (ires) {
2314       case GST_ITERATOR_RESYNC:
2315         /* need to reset the result again */
2316         g_value_set_boolean (&ret, TRUE);
2317         gst_iterator_resync (iter);
2318         break;
2319       case GST_ITERATOR_DONE:
2320         /* all pads iterated, return collected value */
2321         goto done;
2322       default:
2323         /* iterator returned _ERROR or premature end with _OK,
2324          * mark an error and exit */
2325         g_value_set_boolean (&ret, FALSE);
2326         goto done;
2327     }
2328   }
2329 done:
2330   /* return collected value */
2331   return g_value_get_boolean (&ret);
2332 }
2333
2334 /* is called with STATE_LOCK
2335  */
2336 static gboolean
2337 gst_bin_src_pads_activate (GstBin * bin, gboolean active)
2338 {
2339   GstIterator *iter;
2340   gboolean fold_ok;
2341
2342   GST_DEBUG_OBJECT (bin, "src_pads_activate with active %d", active);
2343
2344   iter = gst_element_iterate_src_pads ((GstElement *) bin);
2345   fold_ok = iterator_activate_fold_with_resync (iter, &active);
2346   gst_iterator_free (iter);
2347   if (G_UNLIKELY (!fold_ok))
2348     goto failed;
2349
2350   GST_DEBUG_OBJECT (bin, "pads_activate successful");
2351
2352   return TRUE;
2353
2354   /* ERRORS */
2355 failed:
2356   {
2357     GST_DEBUG_OBJECT (bin, "source pads_activate failed");
2358     return FALSE;
2359   }
2360 }
2361
2362 /**
2363  * gst_bin_recalculate_latency:
2364  * @bin: a #GstBin
2365  *
2366  * Query @bin for the current latency using and reconfigures this latency to all the
2367  * elements with a LATENCY event.
2368  *
2369  * This method is typically called on the pipeline when a #GST_MESSAGE_LATENCY
2370  * is posted on the bus.
2371  *
2372  * This function simply emits the 'do-latency' signal so any custom latency
2373  * calculations will be performed.
2374  *
2375  * Returns: %TRUE if the latency could be queried and reconfigured.
2376  *
2377  * Since: 0.10.22.
2378  */
2379 gboolean
2380 gst_bin_recalculate_latency (GstBin * bin)
2381 {
2382   gboolean res;
2383
2384   g_signal_emit (bin, gst_bin_signals[DO_LATENCY], 0, &res);
2385   GST_DEBUG_OBJECT (bin, "latency returned %d", res);
2386
2387   return res;
2388 }
2389
2390 static gboolean
2391 gst_bin_do_latency_func (GstBin * bin)
2392 {
2393   GstQuery *query;
2394   GstElement *element;
2395   GstClockTime min_latency, max_latency;
2396   gboolean res;
2397
2398   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
2399
2400   element = GST_ELEMENT_CAST (bin);
2401
2402   GST_DEBUG_OBJECT (element, "querying latency");
2403
2404   query = gst_query_new_latency ();
2405   if ((res = gst_element_query (element, query))) {
2406     gboolean live;
2407
2408     gst_query_parse_latency (query, &live, &min_latency, &max_latency);
2409
2410     GST_DEBUG_OBJECT (element,
2411         "got min latency %" GST_TIME_FORMAT ", max latency %"
2412         GST_TIME_FORMAT ", live %d", GST_TIME_ARGS (min_latency),
2413         GST_TIME_ARGS (max_latency), live);
2414
2415     if (max_latency < min_latency) {
2416       /* this is an impossible situation, some parts of the pipeline might not
2417        * work correctly. We post a warning for now. */
2418       GST_ELEMENT_WARNING (element, CORE, CLOCK, (NULL),
2419           ("Impossible to configure latency: max %" GST_TIME_FORMAT " < min %"
2420               GST_TIME_FORMAT ". Add queues or other buffering elements.",
2421               GST_TIME_ARGS (max_latency), GST_TIME_ARGS (min_latency)));
2422     }
2423
2424     /* configure latency on elements */
2425     res = gst_element_send_event (element, gst_event_new_latency (min_latency));
2426     if (res) {
2427       GST_INFO_OBJECT (element, "configured latency of %" GST_TIME_FORMAT,
2428           GST_TIME_ARGS (min_latency));
2429     } else {
2430       GST_WARNING_OBJECT (element,
2431           "did not really configure latency of %" GST_TIME_FORMAT,
2432           GST_TIME_ARGS (min_latency));
2433     }
2434   } else {
2435     /* this is not a real problem, we just don't configure any latency. */
2436     GST_WARNING_OBJECT (element, "failed to query latency");
2437   }
2438   gst_query_unref (query);
2439
2440   return res;
2441 }
2442
2443 static void
2444 gst_bin_state_changed (GstElement * element, GstState oldstate,
2445     GstState newstate, GstState pending)
2446 {
2447   GstElementClass *pklass = (GstElementClass *) parent_class;
2448
2449   if (newstate == GST_STATE_PLAYING && pending == GST_STATE_VOID_PENDING)
2450     bin_do_eos (GST_BIN_CAST (element));
2451
2452   if (pklass->state_changed)
2453     pklass->state_changed (element, oldstate, newstate, pending);
2454 }
2455
2456 static GstStateChangeReturn
2457 gst_bin_change_state_func (GstElement * element, GstStateChange transition)
2458 {
2459   GstBin *bin;
2460   GstStateChangeReturn ret;
2461   GstState current, next;
2462   gboolean have_async;
2463   gboolean have_no_preroll;
2464   GstClockTime base_time, start_time;
2465   GstIterator *it;
2466   gboolean done;
2467   GValue data = { 0, };
2468
2469   /* we don't need to take the STATE_LOCK, it is already taken */
2470   current = (GstState) GST_STATE_TRANSITION_CURRENT (transition);
2471   next = (GstState) GST_STATE_TRANSITION_NEXT (transition);
2472
2473   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2474       "changing state of children from %s to %s",
2475       gst_element_state_get_name (current), gst_element_state_get_name (next));
2476
2477   bin = GST_BIN_CAST (element);
2478
2479   switch (next) {
2480     case GST_STATE_PLAYING:
2481     {
2482       gboolean toplevel;
2483
2484       GST_OBJECT_LOCK (bin);
2485       toplevel = BIN_IS_TOPLEVEL (bin);
2486       GST_OBJECT_UNLOCK (bin);
2487
2488       if (toplevel)
2489         gst_bin_recalculate_latency (bin);
2490       break;
2491     }
2492     case GST_STATE_PAUSED:
2493       /* Clear EOS list on next PAUSED */
2494       GST_OBJECT_LOCK (bin);
2495       GST_DEBUG_OBJECT (element, "clearing EOS elements");
2496       bin_remove_messages (bin, NULL, GST_MESSAGE_EOS);
2497       bin->priv->posted_eos = FALSE;
2498       GST_OBJECT_UNLOCK (bin);
2499       if (current == GST_STATE_READY)
2500         if (!(gst_bin_src_pads_activate (bin, TRUE)))
2501           goto activate_failure;
2502       break;
2503     case GST_STATE_READY:
2504       /* Clear message list on next READY */
2505       GST_OBJECT_LOCK (bin);
2506       GST_DEBUG_OBJECT (element, "clearing all cached messages");
2507       bin_remove_messages (bin, NULL, GST_MESSAGE_ANY);
2508       GST_OBJECT_UNLOCK (bin);
2509       if (current == GST_STATE_PAUSED)
2510         if (!(gst_bin_src_pads_activate (bin, FALSE)))
2511           goto activate_failure;
2512       break;
2513     case GST_STATE_NULL:
2514       if (current == GST_STATE_READY)
2515         if (!(gst_bin_src_pads_activate (bin, FALSE)))
2516           goto activate_failure;
2517       break;
2518     default:
2519       break;
2520   }
2521
2522   /* this flag is used to make the async state changes return immediately. We
2523    * don't want them to interfere with this state change */
2524   GST_OBJECT_LOCK (bin);
2525   bin->polling = TRUE;
2526   GST_OBJECT_UNLOCK (bin);
2527
2528   /* iterate in state change order */
2529   it = gst_bin_iterate_sorted (bin);
2530
2531   /* mark if we've seen an ASYNC element in the bin when we did a state change.
2532    * Note how we don't reset this value when a resync happens, the reason being
2533    * that the async element posted ASYNC_START and we want to post ASYNC_DONE
2534    * even after a resync when the async element is gone */
2535   have_async = FALSE;
2536
2537 restart:
2538   /* take base_time */
2539   base_time = gst_element_get_base_time (element);
2540   start_time = gst_element_get_start_time (element);
2541
2542   have_no_preroll = FALSE;
2543
2544   done = FALSE;
2545   while (!done) {
2546     switch (gst_iterator_next (it, &data)) {
2547       case GST_ITERATOR_OK:
2548       {
2549         GstElement *child;
2550
2551         child = g_value_get_object (&data);
2552
2553         /* set state and base_time now */
2554         ret = gst_bin_element_set_state (bin, child, base_time, start_time,
2555             current, next);
2556
2557         switch (ret) {
2558           case GST_STATE_CHANGE_SUCCESS:
2559             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2560                 "child '%s' changed state to %d(%s) successfully",
2561                 GST_ELEMENT_NAME (child), next,
2562                 gst_element_state_get_name (next));
2563             break;
2564           case GST_STATE_CHANGE_ASYNC:
2565           {
2566             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2567                 "child '%s' is changing state asynchronously to %s",
2568                 GST_ELEMENT_NAME (child), gst_element_state_get_name (next));
2569             have_async = TRUE;
2570             break;
2571           }
2572           case GST_STATE_CHANGE_FAILURE:{
2573             GstObject *parent;
2574
2575             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2576                 "child '%s' failed to go to state %d(%s)",
2577                 GST_ELEMENT_NAME (child),
2578                 next, gst_element_state_get_name (next));
2579
2580             /* Only fail if the child is still inside
2581              * this bin. It might've been removed already
2582              * because of the error by the bin subclass
2583              * to ignore the error.  */
2584             parent = gst_object_get_parent (GST_OBJECT_CAST (child));
2585             if (parent == GST_OBJECT_CAST (element)) {
2586               /* element is still in bin, really error now */
2587               gst_object_unref (parent);
2588               goto done;
2589             }
2590             /* child removed from bin, let the resync code redo the state
2591              * change */
2592             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2593                 "child '%s' was removed from the bin",
2594                 GST_ELEMENT_NAME (child));
2595
2596             if (parent)
2597               gst_object_unref (parent);
2598
2599             break;
2600           }
2601           case GST_STATE_CHANGE_NO_PREROLL:
2602             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2603                 "child '%s' changed state to %d(%s) successfully without preroll",
2604                 GST_ELEMENT_NAME (child), next,
2605                 gst_element_state_get_name (next));
2606             have_no_preroll = TRUE;
2607             break;
2608           default:
2609             g_assert_not_reached ();
2610             break;
2611         }
2612         g_value_reset (&data);
2613         break;
2614       }
2615       case GST_ITERATOR_RESYNC:
2616         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "iterator doing resync");
2617         gst_iterator_resync (it);
2618         goto restart;
2619       default:
2620       case GST_ITERATOR_DONE:
2621         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "iterator done");
2622         done = TRUE;
2623         break;
2624     }
2625   }
2626
2627   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2628   if (G_UNLIKELY (ret == GST_STATE_CHANGE_FAILURE))
2629     goto done;
2630
2631   if (have_no_preroll) {
2632     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
2633         "we have NO_PREROLL elements %s -> NO_PREROLL",
2634         gst_element_state_change_return_get_name (ret));
2635     ret = GST_STATE_CHANGE_NO_PREROLL;
2636   } else if (have_async) {
2637     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
2638         "we have ASYNC elements %s -> ASYNC",
2639         gst_element_state_change_return_get_name (ret));
2640     ret = GST_STATE_CHANGE_ASYNC;
2641   }
2642
2643 done:
2644   g_value_unset (&data);
2645   gst_iterator_free (it);
2646
2647   GST_OBJECT_LOCK (bin);
2648   bin->polling = FALSE;
2649   /* it's possible that we did not get ASYNC from the children while the bin is
2650    * simulating ASYNC behaviour by posting an ASYNC_DONE message on the bus with
2651    * itself as the source. In that case we still want to check if the state
2652    * change completed. */
2653   if (ret != GST_STATE_CHANGE_ASYNC && !bin->priv->pending_async_done) {
2654     /* no element returned ASYNC and there are no pending async_done messages,
2655      * we can just complete. */
2656     GST_DEBUG_OBJECT (bin, "no async elements");
2657     goto state_end;
2658   }
2659   /* when we get here an ASYNC element was found */
2660   if (GST_STATE_TARGET (bin) <= GST_STATE_READY) {
2661     /* we ignore ASYNC state changes when we go to READY or NULL */
2662     GST_DEBUG_OBJECT (bin, "target state %s <= READY",
2663         gst_element_state_get_name (GST_STATE_TARGET (bin)));
2664     goto state_end;
2665   }
2666
2667   GST_DEBUG_OBJECT (bin, "check async elements");
2668   /* check if all elements managed to commit their state already */
2669   if (!find_message (bin, NULL, GST_MESSAGE_ASYNC_START)) {
2670     /* nothing found, remove all old ASYNC_DONE messages. This can happen when
2671      * all the elements commited their state while we were doing the state
2672      * change. We will still return ASYNC for consistency but we commit the
2673      * state already so that a _get_state() will return immediately. */
2674     bin_remove_messages (bin, NULL, GST_MESSAGE_ASYNC_DONE);
2675
2676     GST_DEBUG_OBJECT (bin, "async elements commited");
2677     bin_handle_async_done (bin, GST_STATE_CHANGE_SUCCESS, FALSE, FALSE);
2678   }
2679
2680 state_end:
2681   bin->priv->pending_async_done = FALSE;
2682   GST_OBJECT_UNLOCK (bin);
2683
2684   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2685       "done changing bin's state from %s to %s, now in %s, ret %s",
2686       gst_element_state_get_name (current),
2687       gst_element_state_get_name (next),
2688       gst_element_state_get_name (GST_STATE (element)),
2689       gst_element_state_change_return_get_name (ret));
2690
2691   return ret;
2692
2693   /* ERRORS */
2694 activate_failure:
2695   {
2696     GST_CAT_WARNING_OBJECT (GST_CAT_STATES, element,
2697         "failure (de)activating src pads");
2698     return GST_STATE_CHANGE_FAILURE;
2699   }
2700 }
2701
2702 /*
2703  * This function is a utility event handler for seek events.
2704  * It will send the event to all sinks or sources depending on the
2705  * event-direction.
2706  *
2707  * Applications are free to override this behaviour and
2708  * implement their own seek handler, but this will work for
2709  * pretty much all cases in practice.
2710  */
2711 static gboolean
2712 gst_bin_send_event (GstElement * element, GstEvent * event)
2713 {
2714   GstBin *bin = GST_BIN_CAST (element);
2715   GstIterator *iter;
2716   gboolean res = TRUE;
2717   gboolean done = FALSE;
2718   GValue data = { 0, };
2719
2720   if (GST_EVENT_IS_DOWNSTREAM (event)) {
2721     iter = gst_bin_iterate_sources (bin);
2722     GST_DEBUG_OBJECT (bin, "Sending %s event to src children",
2723         GST_EVENT_TYPE_NAME (event));
2724   } else {
2725     iter = gst_bin_iterate_sinks (bin);
2726     GST_DEBUG_OBJECT (bin, "Sending %s event to sink children",
2727         GST_EVENT_TYPE_NAME (event));
2728   }
2729
2730   while (!done) {
2731     switch (gst_iterator_next (iter, &data)) {
2732       case GST_ITERATOR_OK:
2733       {
2734         GstElement *child = g_value_get_object (&data);;
2735
2736         gst_event_ref (event);
2737         res &= gst_element_send_event (child, event);
2738         GST_LOG_OBJECT (child, "After handling %s event: %d",
2739             GST_EVENT_TYPE_NAME (event), res);
2740         break;
2741       }
2742       case GST_ITERATOR_RESYNC:
2743         gst_iterator_resync (iter);
2744         res = TRUE;
2745         break;
2746       case GST_ITERATOR_DONE:
2747         done = TRUE;
2748         break;
2749       case GST_ITERATOR_ERROR:
2750         g_assert_not_reached ();
2751         break;
2752     }
2753   }
2754   g_value_unset (&data);
2755   gst_iterator_free (iter);
2756   gst_event_unref (event);
2757
2758   return res;
2759 }
2760
2761 /* this is the function called by the threadpool. When async elements commit
2762  * their state, this function will attempt to bring the bin to the next state.
2763  */
2764 static void
2765 gst_bin_continue_func (BinContinueData * data)
2766 {
2767   GstBin *bin;
2768   GstState current, next, pending;
2769   GstStateChange transition;
2770
2771   bin = data->bin;
2772   pending = data->pending;
2773
2774   GST_DEBUG_OBJECT (bin, "waiting for state lock");
2775   GST_STATE_LOCK (bin);
2776
2777   GST_DEBUG_OBJECT (bin, "doing state continue");
2778   GST_OBJECT_LOCK (bin);
2779
2780   /* if a new state change happened after this thread was scheduled, we return
2781    * immediately. */
2782   if (data->cookie != GST_ELEMENT_CAST (bin)->state_cookie)
2783     goto interrupted;
2784
2785   current = GST_STATE (bin);
2786   next = GST_STATE_GET_NEXT (current, pending);
2787   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
2788
2789   GST_STATE_NEXT (bin) = next;
2790   GST_STATE_PENDING (bin) = pending;
2791   /* mark busy */
2792   GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
2793   GST_OBJECT_UNLOCK (bin);
2794
2795   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
2796       "continue state change %s to %s, final %s",
2797       gst_element_state_get_name (current),
2798       gst_element_state_get_name (next), gst_element_state_get_name (pending));
2799
2800   gst_element_change_state (GST_ELEMENT_CAST (bin), transition);
2801
2802   GST_STATE_UNLOCK (bin);
2803   GST_DEBUG_OBJECT (bin, "state continue done");
2804
2805   gst_object_unref (bin);
2806   g_slice_free (BinContinueData, data);
2807   return;
2808
2809 interrupted:
2810   {
2811     GST_OBJECT_UNLOCK (bin);
2812     GST_STATE_UNLOCK (bin);
2813     GST_DEBUG_OBJECT (bin, "state continue aborted due to intervening change");
2814     gst_object_unref (bin);
2815     g_slice_free (BinContinueData, data);
2816     return;
2817   }
2818 }
2819
2820 static GstBusSyncReply
2821 bin_bus_handler (GstBus * bus, GstMessage * message, GstBin * bin)
2822 {
2823   GstBinClass *bclass;
2824
2825   bclass = GST_BIN_GET_CLASS (bin);
2826   if (bclass->handle_message)
2827     bclass->handle_message (bin, message);
2828   else
2829     gst_message_unref (message);
2830
2831   return GST_BUS_DROP;
2832 }
2833
2834 static void
2835 bin_push_state_continue (BinContinueData * data)
2836 {
2837   GstBinClass *klass;
2838   GstBin *bin;
2839
2840   /* ref was taken */
2841   bin = data->bin;
2842   klass = GST_BIN_GET_CLASS (bin);
2843
2844   GST_DEBUG_OBJECT (bin, "pushing continue on thread pool");
2845   g_thread_pool_push (klass->pool, data, NULL);
2846 }
2847
2848 /* an element started an async state change, if we were not busy with a state
2849  * change, we perform a lost state.
2850  * This function is called with the OBJECT lock.
2851  */
2852 static void
2853 bin_handle_async_start (GstBin * bin)
2854 {
2855   GstState old_state, new_state;
2856   gboolean toplevel;
2857   GstMessage *amessage = NULL;
2858
2859   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_FAILURE)
2860     goto had_error;
2861
2862   /* get our toplevel state */
2863   toplevel = BIN_IS_TOPLEVEL (bin);
2864
2865   /* prepare an ASYNC_START message, we always post the start message even if we
2866    * are busy with a state change or when we are NO_PREROLL. */
2867   if (!toplevel)
2868     /* non toplevel bin, prepare async-start for the parent */
2869     amessage = gst_message_new_async_start (GST_OBJECT_CAST (bin));
2870
2871   if (bin->polling || GST_STATE_PENDING (bin) != GST_STATE_VOID_PENDING)
2872     goto was_busy;
2873
2874   /* async starts are ignored when we are NO_PREROLL */
2875   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_NO_PREROLL)
2876     goto was_no_preroll;
2877
2878   old_state = GST_STATE (bin);
2879
2880   /* when we PLAYING we go back to PAUSED, when preroll happens, we go back to
2881    * PLAYING after optionally redistributing the base_time. */
2882   if (old_state > GST_STATE_PAUSED)
2883     new_state = GST_STATE_PAUSED;
2884   else
2885     new_state = old_state;
2886
2887   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
2888       "lost state of %s, new %s", gst_element_state_get_name (old_state),
2889       gst_element_state_get_name (new_state));
2890
2891   GST_STATE (bin) = new_state;
2892   GST_STATE_NEXT (bin) = new_state;
2893   GST_STATE_PENDING (bin) = new_state;
2894   GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
2895   GST_OBJECT_UNLOCK (bin);
2896
2897   /* post message */
2898   _priv_gst_element_state_changed (GST_ELEMENT_CAST (bin), new_state, new_state,
2899       new_state);
2900
2901 post_start:
2902   if (amessage) {
2903     /* post our ASYNC_START. */
2904     GST_DEBUG_OBJECT (bin, "posting ASYNC_START to parent");
2905     gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
2906   }
2907   GST_OBJECT_LOCK (bin);
2908
2909   return;
2910
2911 had_error:
2912   {
2913     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "we had an error");
2914     return;
2915   }
2916 was_busy:
2917   {
2918     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "state change busy");
2919     GST_OBJECT_UNLOCK (bin);
2920     goto post_start;
2921   }
2922 was_no_preroll:
2923   {
2924     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "ignoring, we are NO_PREROLL");
2925     GST_OBJECT_UNLOCK (bin);
2926     goto post_start;
2927   }
2928 }
2929
2930 /* this function is called when there are no more async elements in the bin. We
2931  * post a state changed message and an ASYNC_DONE message.
2932  * This function is called with the OBJECT lock.
2933  */
2934 static void
2935 bin_handle_async_done (GstBin * bin, GstStateChangeReturn ret,
2936     gboolean flag_pending, gboolean reset_time)
2937 {
2938   GstState current, pending, target;
2939   GstStateChangeReturn old_ret;
2940   GstState old_state, old_next;
2941   gboolean toplevel, state_changed = FALSE;
2942   GstMessage *amessage = NULL;
2943   BinContinueData *cont = NULL;
2944
2945   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_FAILURE)
2946     goto had_error;
2947
2948   pending = GST_STATE_PENDING (bin);
2949
2950   if (bin->polling)
2951     goto was_busy;
2952
2953   /* check if there is something to commit */
2954   if (pending == GST_STATE_VOID_PENDING)
2955     goto nothing_pending;
2956
2957   old_ret = GST_STATE_RETURN (bin);
2958   GST_STATE_RETURN (bin) = ret;
2959
2960   /* move to the next target state */
2961   target = GST_STATE_TARGET (bin);
2962   pending = GST_STATE_PENDING (bin) = target;
2963
2964   amessage = gst_message_new_async_done (GST_OBJECT_CAST (bin), reset_time);
2965
2966   old_state = GST_STATE (bin);
2967   /* this is the state we should go to next */
2968   old_next = GST_STATE_NEXT (bin);
2969
2970   if (old_next != GST_STATE_PLAYING) {
2971     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
2972         "committing state from %s to %s, old pending %s",
2973         gst_element_state_get_name (old_state),
2974         gst_element_state_get_name (old_next),
2975         gst_element_state_get_name (pending));
2976
2977     /* update current state */
2978     current = GST_STATE (bin) = old_next;
2979   } else {
2980     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
2981         "setting state from %s to %s, pending %s",
2982         gst_element_state_get_name (old_state),
2983         gst_element_state_get_name (old_state),
2984         gst_element_state_get_name (pending));
2985     current = old_state;
2986   }
2987
2988   /* get our toplevel state */
2989   toplevel = BIN_IS_TOPLEVEL (bin);
2990
2991   /* see if we reached the final state. If we are not toplevel, we also have to
2992    * stop here, the parent will continue our state. */
2993   if ((pending == current) || !toplevel) {
2994     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
2995         "completed state change, pending VOID");
2996
2997     /* mark VOID pending */
2998     pending = GST_STATE_VOID_PENDING;
2999     GST_STATE_PENDING (bin) = pending;
3000     GST_STATE_NEXT (bin) = GST_STATE_VOID_PENDING;
3001   } else {
3002     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3003         "continue state change, pending %s",
3004         gst_element_state_get_name (pending));
3005
3006     cont = g_slice_new (BinContinueData);
3007
3008     /* ref to the bin */
3009     cont->bin = gst_object_ref (bin);
3010     /* cookie to detect concurrent state change */
3011     cont->cookie = GST_ELEMENT_CAST (bin)->state_cookie;
3012     /* pending target state */
3013     cont->pending = pending;
3014     /* mark busy */
3015     GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3016     GST_STATE_NEXT (bin) = GST_STATE_GET_NEXT (old_state, pending);
3017   }
3018
3019   if (old_next != GST_STATE_PLAYING) {
3020     if (old_state != old_next || old_ret == GST_STATE_CHANGE_ASYNC) {
3021       state_changed = TRUE;
3022     }
3023   }
3024   GST_OBJECT_UNLOCK (bin);
3025
3026   if (state_changed) {
3027     _priv_gst_element_state_changed (GST_ELEMENT_CAST (bin), old_state,
3028         old_next, pending);
3029   }
3030   if (amessage) {
3031     /* post our combined ASYNC_DONE when all is ASYNC_DONE. */
3032     GST_DEBUG_OBJECT (bin, "posting ASYNC_DONE to parent");
3033     gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
3034   }
3035
3036   GST_OBJECT_LOCK (bin);
3037   if (cont) {
3038     /* toplevel, start continue state */
3039     GST_DEBUG_OBJECT (bin, "all async-done, starting state continue");
3040     bin_push_state_continue (cont);
3041   } else {
3042     GST_DEBUG_OBJECT (bin, "state change complete");
3043     GST_STATE_BROADCAST (bin);
3044   }
3045   return;
3046
3047 had_error:
3048   {
3049     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "we had an error");
3050     return;
3051   }
3052 was_busy:
3053   {
3054     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "state change busy");
3055     /* if we were busy with a state change and we are requested to flag a
3056      * pending async done, we do so here */
3057     if (flag_pending)
3058       bin->priv->pending_async_done = TRUE;
3059     return;
3060   }
3061 nothing_pending:
3062   {
3063     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "nothing pending");
3064     return;
3065   }
3066 }
3067
3068 static void
3069 bin_do_eos (GstBin * bin)
3070 {
3071   guint32 seqnum = 0;
3072   gboolean eos;
3073
3074   GST_OBJECT_LOCK (bin);
3075   /* If all sinks are EOS, we're in PLAYING and no state change is pending
3076    * we forward the EOS message to the parent bin or application
3077    */
3078   eos = GST_STATE (bin) == GST_STATE_PLAYING
3079       && GST_STATE_PENDING (bin) == GST_STATE_VOID_PENDING
3080       && is_eos (bin, &seqnum);
3081   GST_OBJECT_UNLOCK (bin);
3082
3083   if (eos
3084       && g_atomic_int_compare_and_exchange (&bin->priv->posted_eos, FALSE,
3085           TRUE)) {
3086     GstMessage *tmessage;
3087     tmessage = gst_message_new_eos (GST_OBJECT_CAST (bin));
3088     gst_message_set_seqnum (tmessage, seqnum);
3089     GST_DEBUG_OBJECT (bin,
3090         "all sinks posted EOS, posting seqnum #%" G_GUINT32_FORMAT, seqnum);
3091     gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3092   }
3093 }
3094
3095 /* must be called with the object lock. This function releases the lock to post
3096  * the message. */
3097 static void
3098 bin_do_message_forward (GstBin * bin, GstMessage * message)
3099 {
3100   if (bin->priv->message_forward) {
3101     GstMessage *forwarded;
3102
3103     GST_DEBUG_OBJECT (bin, "pass %s message upward",
3104         GST_MESSAGE_TYPE_NAME (message));
3105     GST_OBJECT_UNLOCK (bin);
3106
3107     /* we need to convert these messages to element messages so that our parent
3108      * bin can easily ignore them and so that the application can easily
3109      * distinguish between the internally forwarded and the real messages. */
3110     forwarded = gst_message_new_element (GST_OBJECT_CAST (bin),
3111         gst_structure_new ("GstBinForwarded",
3112             "message", GST_TYPE_MESSAGE, message, NULL));
3113
3114     gst_element_post_message (GST_ELEMENT_CAST (bin), forwarded);
3115
3116     GST_OBJECT_LOCK (bin);
3117   }
3118 }
3119
3120 /* handle child messages:
3121  *
3122  * This method is called synchronously when a child posts a message on
3123  * the internal bus.
3124  *
3125  * GST_MESSAGE_EOS: This message is only posted by sinks
3126  *     in the PLAYING state. If all sinks posted the EOS message, post
3127  *     one upwards.
3128  *
3129  * GST_MESSAGE_STATE_DIRTY: Deprecated
3130  *
3131  * GST_MESSAGE_SEGMENT_START: just collect, never forward upwards. If an
3132  *     element posts segment_start twice, only the last message is kept.
3133  *
3134  * GST_MESSAGE_SEGMENT_DONE: replace SEGMENT_START message from same poster
3135  *     with the segment_done message. If there are no more segment_start
3136  *     messages, post segment_done message upwards.
3137  *
3138  * GST_MESSAGE_DURATION: remove all previously cached duration messages.
3139  *     Whenever someone performs a duration query on the bin, we store the
3140  *     result so we can answer it quicker the next time. Any element that
3141  *     changes its duration marks our cached values invalid.
3142  *     This message is also posted upwards. This is currently disabled
3143  *     because too many elements don't post DURATION messages when the
3144  *     duration changes.
3145  *
3146  * GST_MESSAGE_CLOCK_LOST: This message is posted by an element when it
3147  *     can no longer provide a clock. The default bin behaviour is to
3148  *     check if the lost clock was the one provided by the bin. If so and
3149  *     we are currently in the PLAYING state, we forward the message to
3150  *     our parent.
3151  *     This message is also generated when we remove a clock provider from
3152  *     a bin. If this message is received by the application, it should
3153  *     PAUSE the pipeline and set it back to PLAYING to force a new clock
3154  *     and a new base_time distribution.
3155  *
3156  * GST_MESSAGE_CLOCK_PROVIDE: This message is generated when an element
3157  *     can provide a clock. This mostly happens when we add a new clock
3158  *     provider to the bin. The default behaviour of the bin is to mark the
3159  *     currently selected clock as dirty, which will perform a clock
3160  *     recalculation the next time we are asked to provide a clock.
3161  *     This message is never sent to the application but is forwarded to
3162  *     the parent.
3163  *
3164  * GST_MESSAGE_ASYNC_START: Create an internal ELEMENT message that stores
3165  *     the state of the element and the fact that the element will need a
3166  *     new base_time. This message is not forwarded to the application.
3167  *
3168  * GST_MESSAGE_ASYNC_DONE: Find the internal ELEMENT message we kept for the
3169  *     element when it posted ASYNC_START. If all elements are done, post a
3170  *     ASYNC_DONE message to the parent.
3171  *
3172  * OTHER: post upwards.
3173  */
3174 static void
3175 gst_bin_handle_message_func (GstBin * bin, GstMessage * message)
3176 {
3177   GstObject *src;
3178   GstMessageType type;
3179   GstMessage *tmessage;
3180   guint32 seqnum;
3181
3182   src = GST_MESSAGE_SRC (message);
3183   type = GST_MESSAGE_TYPE (message);
3184
3185   GST_DEBUG_OBJECT (bin, "[msg %p] handling child %s message of type %s",
3186       message, src ? GST_ELEMENT_NAME (src) : "(NULL)",
3187       GST_MESSAGE_TYPE_NAME (message));
3188
3189   switch (type) {
3190     case GST_MESSAGE_ERROR:
3191     {
3192       GST_OBJECT_LOCK (bin);
3193       /* flag error */
3194       GST_DEBUG_OBJECT (bin, "got ERROR message, unlocking state change");
3195       GST_STATE_RETURN (bin) = GST_STATE_CHANGE_FAILURE;
3196       GST_STATE_BROADCAST (bin);
3197       GST_OBJECT_UNLOCK (bin);
3198
3199       goto forward;
3200     }
3201     case GST_MESSAGE_EOS:
3202     {
3203
3204       /* collect all eos messages from the children */
3205       GST_OBJECT_LOCK (bin);
3206       bin_do_message_forward (bin, message);
3207       /* ref message for future use  */
3208       bin_replace_message (bin, message, GST_MESSAGE_EOS);
3209       GST_OBJECT_UNLOCK (bin);
3210
3211       bin_do_eos (bin);
3212       break;
3213     }
3214     case GST_MESSAGE_STATE_DIRTY:
3215     {
3216       GST_WARNING_OBJECT (bin, "received deprecated STATE_DIRTY message");
3217
3218       /* free message */
3219       gst_message_unref (message);
3220       break;
3221     }
3222     case GST_MESSAGE_SEGMENT_START:{
3223       gboolean post = FALSE;
3224       GstFormat format;
3225       gint64 position;
3226
3227       gst_message_parse_segment_start (message, &format, &position);
3228       seqnum = gst_message_get_seqnum (message);
3229
3230       GST_OBJECT_LOCK (bin);
3231       bin_do_message_forward (bin, message);
3232       /* if this is the first segment-start, post to parent but not to the
3233        * application */
3234       if (!find_message (bin, NULL, GST_MESSAGE_SEGMENT_START) &&
3235           (GST_OBJECT_PARENT (bin) != NULL)) {
3236         post = TRUE;
3237       }
3238       /* replace any previous segment_start message from this source
3239        * with the new segment start message */
3240       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
3241       GST_OBJECT_UNLOCK (bin);
3242       if (post) {
3243         tmessage = gst_message_new_segment_start (GST_OBJECT_CAST (bin),
3244             format, position);
3245         gst_message_set_seqnum (tmessage, seqnum);
3246
3247         /* post segment start with initial format and position. */
3248         GST_DEBUG_OBJECT (bin, "posting SEGMENT_START (%u) bus message: %p",
3249             seqnum, message);
3250         gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3251       }
3252       break;
3253     }
3254     case GST_MESSAGE_SEGMENT_DONE:
3255     {
3256       gboolean post = FALSE;
3257       GstFormat format;
3258       gint64 position;
3259
3260       gst_message_parse_segment_done (message, &format, &position);
3261       seqnum = gst_message_get_seqnum (message);
3262
3263       GST_OBJECT_LOCK (bin);
3264       bin_do_message_forward (bin, message);
3265       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
3266       /* if there are no more segment_start messages, everybody posted
3267        * a segment_done and we can post one on the bus. */
3268
3269       /* we don't care who still has a pending segment start */
3270       if (!find_message (bin, NULL, GST_MESSAGE_SEGMENT_START)) {
3271         /* nothing found */
3272         post = TRUE;
3273         /* remove all old segment_done messages */
3274         bin_remove_messages (bin, NULL, GST_MESSAGE_SEGMENT_DONE);
3275       }
3276       GST_OBJECT_UNLOCK (bin);
3277       if (post) {
3278         tmessage = gst_message_new_segment_done (GST_OBJECT_CAST (bin),
3279             format, position);
3280         gst_message_set_seqnum (tmessage, seqnum);
3281
3282         /* post segment done with latest format and position. */
3283         GST_DEBUG_OBJECT (bin, "posting SEGMENT_DONE (%u) bus message: %p",
3284             seqnum, message);
3285         gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3286       }
3287       break;
3288     }
3289     case GST_MESSAGE_DURATION:
3290     {
3291       /* remove all cached duration messages, next time somebody asks
3292        * for duration, we will recalculate. */
3293       GST_OBJECT_LOCK (bin);
3294       bin_remove_messages (bin, NULL, GST_MESSAGE_DURATION);
3295       GST_OBJECT_UNLOCK (bin);
3296       goto forward;
3297     }
3298     case GST_MESSAGE_CLOCK_LOST:
3299     {
3300       GstClock **provided_clock_p;
3301       GstElement **clock_provider_p;
3302       gboolean playing, provided, forward;
3303       GstClock *clock;
3304
3305       gst_message_parse_clock_lost (message, &clock);
3306
3307       GST_OBJECT_LOCK (bin);
3308       bin->clock_dirty = TRUE;
3309       /* if we lost the clock that we provided, post to parent but
3310        * only if we are PLAYING. */
3311       provided = (clock == bin->provided_clock);
3312       playing = (GST_STATE (bin) == GST_STATE_PLAYING);
3313       forward = playing & provided;
3314       if (provided) {
3315         GST_DEBUG_OBJECT (bin,
3316             "Lost clock %" GST_PTR_FORMAT " provided by %" GST_PTR_FORMAT,
3317             bin->provided_clock, bin->clock_provider);
3318         provided_clock_p = &bin->provided_clock;
3319         clock_provider_p = &bin->clock_provider;
3320         gst_object_replace ((GstObject **) provided_clock_p, NULL);
3321         gst_object_replace ((GstObject **) clock_provider_p, NULL);
3322       }
3323       GST_DEBUG_OBJECT (bin, "provided %d, playing %d, forward %d",
3324           provided, playing, forward);
3325       GST_OBJECT_UNLOCK (bin);
3326
3327       if (forward)
3328         goto forward;
3329
3330       /* free message */
3331       gst_message_unref (message);
3332       break;
3333     }
3334     case GST_MESSAGE_CLOCK_PROVIDE:
3335     {
3336       gboolean forward;
3337
3338       GST_OBJECT_LOCK (bin);
3339       bin->clock_dirty = TRUE;
3340       /* a new clock is available, post to parent but not
3341        * to the application */
3342       forward = GST_OBJECT_PARENT (bin) != NULL;
3343       GST_OBJECT_UNLOCK (bin);
3344
3345       if (forward)
3346         goto forward;
3347
3348       /* free message */
3349       gst_message_unref (message);
3350       break;
3351     }
3352     case GST_MESSAGE_ASYNC_START:
3353     {
3354       GstState target;
3355
3356       GST_DEBUG_OBJECT (bin, "ASYNC_START message %p, %s", message,
3357           src ? GST_OBJECT_NAME (src) : "(NULL)");
3358
3359       GST_OBJECT_LOCK (bin);
3360       bin_do_message_forward (bin, message);
3361
3362       /* we ignore the message if we are going to <= READY */
3363       if ((target = GST_STATE_TARGET (bin)) <= GST_STATE_READY)
3364         goto ignore_start_message;
3365
3366       /* takes ownership of the message */
3367       bin_replace_message (bin, message, GST_MESSAGE_ASYNC_START);
3368
3369       bin_handle_async_start (bin);
3370       GST_OBJECT_UNLOCK (bin);
3371       break;
3372
3373     ignore_start_message:
3374       {
3375         GST_DEBUG_OBJECT (bin, "ignoring message, target %s",
3376             gst_element_state_get_name (target));
3377         GST_OBJECT_UNLOCK (bin);
3378         gst_message_unref (message);
3379         break;
3380       }
3381     }
3382     case GST_MESSAGE_ASYNC_DONE:
3383     {
3384       gboolean reset_time;
3385       GstState target;
3386
3387       GST_DEBUG_OBJECT (bin, "ASYNC_DONE message %p, %s", message,
3388           src ? GST_OBJECT_NAME (src) : "(NULL)");
3389
3390       gst_message_parse_async_done (message, &reset_time);
3391
3392       GST_OBJECT_LOCK (bin);
3393       bin_do_message_forward (bin, message);
3394
3395       /* ignore messages if we are shutting down */
3396       if ((target = GST_STATE_TARGET (bin)) <= GST_STATE_READY)
3397         goto ignore_done_message;
3398
3399       bin_replace_message (bin, message, GST_MESSAGE_ASYNC_START);
3400       /* if there are no more ASYNC_START messages, everybody posted
3401        * a ASYNC_DONE and we can post one on the bus. When checking, we
3402        * don't care who still has a pending ASYNC_START */
3403       if (!find_message (bin, NULL, GST_MESSAGE_ASYNC_START)) {
3404         /* nothing found, remove all old ASYNC_DONE messages */
3405         bin_remove_messages (bin, NULL, GST_MESSAGE_ASYNC_DONE);
3406
3407         GST_DEBUG_OBJECT (bin, "async elements commited");
3408         /* when we get an async done message when a state change was busy, we
3409          * need to set the pending_done flag so that at the end of the state
3410          * change we can see if we need to verify pending async elements, hence
3411          * the TRUE argument here. */
3412         bin_handle_async_done (bin, GST_STATE_CHANGE_SUCCESS, TRUE, reset_time);
3413       } else {
3414         GST_DEBUG_OBJECT (bin, "there are more async elements pending");
3415       }
3416       GST_OBJECT_UNLOCK (bin);
3417       break;
3418
3419     ignore_done_message:
3420       {
3421         GST_DEBUG_OBJECT (bin, "ignoring message, target %s",
3422             gst_element_state_get_name (target));
3423         GST_OBJECT_UNLOCK (bin);
3424         gst_message_unref (message);
3425         break;
3426       }
3427     }
3428     case GST_MESSAGE_STRUCTURE_CHANGE:
3429     {
3430       gboolean busy;
3431
3432       gst_message_parse_structure_change (message, NULL, NULL, &busy);
3433
3434       GST_OBJECT_LOCK (bin);
3435       if (busy) {
3436         /* while the pad is busy, avoid following it when doing state changes.
3437          * Don't update the cookie yet, we will do that after the structure
3438          * change finished and we are ready to inspect the new updated
3439          * structure. */
3440         bin_replace_message (bin, message, GST_MESSAGE_STRUCTURE_CHANGE);
3441         message = NULL;
3442       } else {
3443         /* a pad link/unlink ended, signal the state change iterator that we
3444          * need to resync by updating the structure_cookie. */
3445         bin_remove_messages (bin, GST_MESSAGE_SRC (message),
3446             GST_MESSAGE_STRUCTURE_CHANGE);
3447         bin->priv->structure_cookie++;
3448       }
3449       GST_OBJECT_UNLOCK (bin);
3450
3451       if (message)
3452         gst_message_unref (message);
3453
3454       break;
3455     }
3456     default:
3457       goto forward;
3458   }
3459   return;
3460
3461 forward:
3462   {
3463     /* Send all other messages upward */
3464     GST_DEBUG_OBJECT (bin, "posting message upward");
3465     gst_element_post_message (GST_ELEMENT_CAST (bin), message);
3466     return;
3467   }
3468 }
3469
3470 /* generic struct passed to all query fold methods */
3471 typedef struct
3472 {
3473   GstQuery *query;
3474   gint64 min;
3475   gint64 max;
3476   gboolean live;
3477 } QueryFold;
3478
3479 typedef void (*QueryInitFunction) (GstBin * bin, QueryFold * fold);
3480 typedef void (*QueryDoneFunction) (GstBin * bin, QueryFold * fold);
3481
3482 /* for duration/position we collect all durations/positions and take
3483  * the MAX of all valid results */
3484 static void
3485 bin_query_min_max_init (GstBin * bin, QueryFold * fold)
3486 {
3487   fold->min = 0;
3488   fold->max = -1;
3489   fold->live = FALSE;
3490 }
3491
3492 static gboolean
3493 bin_query_duration_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
3494 {
3495   GstElement *item = g_value_get_object (vitem);
3496
3497   if (gst_element_query (item, fold->query)) {
3498     gint64 duration;
3499
3500     g_value_set_boolean (ret, TRUE);
3501
3502     gst_query_parse_duration (fold->query, NULL, &duration);
3503
3504     GST_DEBUG_OBJECT (item, "got duration %" G_GINT64_FORMAT, duration);
3505
3506     if (duration > fold->max)
3507       fold->max = duration;
3508   }
3509
3510   return TRUE;
3511 }
3512
3513 static void
3514 bin_query_duration_done (GstBin * bin, QueryFold * fold)
3515 {
3516   GstFormat format;
3517
3518   gst_query_parse_duration (fold->query, &format, NULL);
3519   /* store max in query result */
3520   gst_query_set_duration (fold->query, format, fold->max);
3521
3522   GST_DEBUG_OBJECT (bin, "max duration %" G_GINT64_FORMAT, fold->max);
3523
3524   /* and cache now */
3525   GST_OBJECT_LOCK (bin);
3526   bin->messages = g_list_prepend (bin->messages,
3527       gst_message_new_duration (GST_OBJECT_CAST (bin), format, fold->max));
3528   GST_OBJECT_UNLOCK (bin);
3529 }
3530
3531 static gboolean
3532 bin_query_position_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
3533 {
3534   GstElement *item = g_value_get_object (vitem);
3535
3536   if (gst_element_query (item, fold->query)) {
3537     gint64 position;
3538
3539     g_value_set_boolean (ret, TRUE);
3540
3541     gst_query_parse_position (fold->query, NULL, &position);
3542
3543     GST_DEBUG_OBJECT (item, "got position %" G_GINT64_FORMAT, position);
3544
3545     if (position > fold->max)
3546       fold->max = position;
3547   }
3548
3549   return TRUE;
3550 }
3551
3552 static void
3553 bin_query_position_done (GstBin * bin, QueryFold * fold)
3554 {
3555   GstFormat format;
3556
3557   gst_query_parse_position (fold->query, &format, NULL);
3558   /* store max in query result */
3559   gst_query_set_position (fold->query, format, fold->max);
3560
3561   GST_DEBUG_OBJECT (bin, "max position %" G_GINT64_FORMAT, fold->max);
3562 }
3563
3564 static gboolean
3565 bin_query_latency_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
3566 {
3567   GstElement *item = g_value_get_object (vitem);
3568
3569   if (gst_element_query (item, fold->query)) {
3570     GstClockTime min, max;
3571     gboolean live;
3572
3573     gst_query_parse_latency (fold->query, &live, &min, &max);
3574
3575     GST_DEBUG_OBJECT (item,
3576         "got latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
3577         ", live %d", GST_TIME_ARGS (min), GST_TIME_ARGS (max), live);
3578
3579     /* for the combined latency we collect the MAX of all min latencies and
3580      * the MIN of all max latencies */
3581     if (live) {
3582       if (min > fold->min)
3583         fold->min = min;
3584       if (fold->max == -1)
3585         fold->max = max;
3586       else if (max < fold->max)
3587         fold->max = max;
3588       if (fold->live == FALSE)
3589         fold->live = live;
3590     }
3591   } else {
3592     g_value_set_boolean (ret, FALSE);
3593     GST_DEBUG_OBJECT (item, "failed query");
3594   }
3595
3596   return TRUE;
3597 }
3598
3599 static void
3600 bin_query_latency_done (GstBin * bin, QueryFold * fold)
3601 {
3602   /* store max in query result */
3603   gst_query_set_latency (fold->query, fold->live, fold->min, fold->max);
3604
3605   GST_DEBUG_OBJECT (bin,
3606       "latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
3607       ", live %d", GST_TIME_ARGS (fold->min), GST_TIME_ARGS (fold->max),
3608       fold->live);
3609 }
3610
3611 /* generic fold, return first valid result */
3612 static gboolean
3613 bin_query_generic_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
3614 {
3615   GstElement *item = g_value_get_object (vitem);
3616   gboolean res;
3617
3618   if ((res = gst_element_query (item, fold->query))) {
3619     g_value_set_boolean (ret, TRUE);
3620     GST_DEBUG_OBJECT (item, "answered query %p", fold->query);
3621   }
3622
3623   /* and stop as soon as we have a valid result */
3624   return !res;
3625 }
3626
3627 static gboolean
3628 gst_bin_query (GstElement * element, GstQuery * query)
3629 {
3630   GstBin *bin = GST_BIN_CAST (element);
3631   GstIterator *iter;
3632   gboolean res = FALSE;
3633   GstIteratorFoldFunction fold_func;
3634   QueryInitFunction fold_init = NULL;
3635   QueryDoneFunction fold_done = NULL;
3636   QueryFold fold_data;
3637   GValue ret = { 0 };
3638
3639   switch (GST_QUERY_TYPE (query)) {
3640     case GST_QUERY_DURATION:
3641     {
3642       GList *cached;
3643       GstFormat qformat;
3644
3645       gst_query_parse_duration (query, &qformat, NULL);
3646
3647       /* find cached duration query */
3648       GST_OBJECT_LOCK (bin);
3649       for (cached = bin->messages; cached; cached = g_list_next (cached)) {
3650         GstMessage *message = (GstMessage *) cached->data;
3651
3652         if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_DURATION &&
3653             GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (bin)) {
3654           GstFormat format;
3655           gint64 duration;
3656
3657           gst_message_parse_duration (message, &format, &duration);
3658
3659           /* if cached same format, copy duration in query result */
3660           if (format == qformat) {
3661             GST_DEBUG_OBJECT (bin, "return cached duration %" G_GINT64_FORMAT,
3662                 duration);
3663             GST_OBJECT_UNLOCK (bin);
3664
3665             gst_query_set_duration (query, qformat, duration);
3666             res = TRUE;
3667             goto exit;
3668           }
3669         }
3670       }
3671       GST_OBJECT_UNLOCK (bin);
3672       /* no cached value found, iterate and collect durations */
3673       fold_func = (GstIteratorFoldFunction) bin_query_duration_fold;
3674       fold_init = bin_query_min_max_init;
3675       fold_done = bin_query_duration_done;
3676       break;
3677     }
3678     case GST_QUERY_POSITION:
3679     {
3680       fold_func = (GstIteratorFoldFunction) bin_query_position_fold;
3681       fold_init = bin_query_min_max_init;
3682       fold_done = bin_query_position_done;
3683       break;
3684     }
3685     case GST_QUERY_LATENCY:
3686     {
3687       fold_func = (GstIteratorFoldFunction) bin_query_latency_fold;
3688       fold_init = bin_query_min_max_init;
3689       fold_done = bin_query_latency_done;
3690       res = TRUE;
3691       break;
3692     }
3693     default:
3694       fold_func = (GstIteratorFoldFunction) bin_query_generic_fold;
3695       break;
3696   }
3697
3698   fold_data.query = query;
3699
3700   /* set the result of the query to FALSE initially */
3701   g_value_init (&ret, G_TYPE_BOOLEAN);
3702   g_value_set_boolean (&ret, res);
3703
3704   iter = gst_bin_iterate_sinks (bin);
3705   GST_DEBUG_OBJECT (bin, "Sending query %p (type %s) to sink children",
3706       query, GST_QUERY_TYPE_NAME (query));
3707
3708   if (fold_init)
3709     fold_init (bin, &fold_data);
3710
3711   while (TRUE) {
3712     GstIteratorResult ires;
3713
3714     ires = gst_iterator_fold (iter, fold_func, &ret, &fold_data);
3715
3716     switch (ires) {
3717       case GST_ITERATOR_RESYNC:
3718         gst_iterator_resync (iter);
3719         if (fold_init)
3720           fold_init (bin, &fold_data);
3721         g_value_set_boolean (&ret, res);
3722         break;
3723       case GST_ITERATOR_OK:
3724       case GST_ITERATOR_DONE:
3725         res = g_value_get_boolean (&ret);
3726         if (fold_done != NULL && res)
3727           fold_done (bin, &fold_data);
3728         goto done;
3729       default:
3730         res = FALSE;
3731         goto done;
3732     }
3733   }
3734 done:
3735   gst_iterator_free (iter);
3736
3737 exit:
3738   GST_DEBUG_OBJECT (bin, "query %p result %d", query, res);
3739
3740   return res;
3741 }
3742
3743 static gint
3744 compare_name (const GValue * velement, const gchar * name)
3745 {
3746   gint eq;
3747   GstElement *element = g_value_get_object (velement);
3748
3749   GST_OBJECT_LOCK (element);
3750   eq = strcmp (GST_ELEMENT_NAME (element), name);
3751   GST_OBJECT_UNLOCK (element);
3752
3753   return eq;
3754 }
3755
3756 /**
3757  * gst_bin_get_by_name:
3758  * @bin: a #GstBin
3759  * @name: the element name to search for
3760  *
3761  * Gets the element with the given name from a bin. This
3762  * function recurses into child bins.
3763  *
3764  * Returns NULL if no element with the given name is found in the bin.
3765  *
3766  * MT safe.  Caller owns returned reference.
3767  *
3768  * Returns: (transfer full): the #GstElement with the given name, or NULL
3769  */
3770 GstElement *
3771 gst_bin_get_by_name (GstBin * bin, const gchar * name)
3772 {
3773   GstIterator *children;
3774   GValue result = { 0, };
3775   GstElement *element;
3776   gboolean found;
3777
3778   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3779
3780   GST_CAT_INFO (GST_CAT_PARENTAGE, "[%s]: looking up child element %s",
3781       GST_ELEMENT_NAME (bin), name);
3782
3783   children = gst_bin_iterate_recurse (bin);
3784   found = gst_iterator_find_custom (children,
3785       (GCompareFunc) compare_name, &result, (gpointer) name);
3786   gst_iterator_free (children);
3787
3788   if (found) {
3789     element = g_value_dup_object (&result);
3790     g_value_unset (&result);
3791   } else {
3792     element = NULL;
3793   }
3794
3795   return element;
3796 }
3797
3798 /**
3799  * gst_bin_get_by_name_recurse_up:
3800  * @bin: a #GstBin
3801  * @name: the element name to search for
3802  *
3803  * Gets the element with the given name from this bin. If the
3804  * element is not found, a recursion is performed on the parent bin.
3805  *
3806  * Returns NULL if:
3807  * - no element with the given name is found in the bin
3808  *
3809  * MT safe.  Caller owns returned reference.
3810  *
3811  * Returns: (transfer full): the #GstElement with the given name, or NULL
3812  */
3813 GstElement *
3814 gst_bin_get_by_name_recurse_up (GstBin * bin, const gchar * name)
3815 {
3816   GstElement *result;
3817
3818   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3819   g_return_val_if_fail (name != NULL, NULL);
3820
3821   result = gst_bin_get_by_name (bin, name);
3822
3823   if (!result) {
3824     GstObject *parent;
3825
3826     parent = gst_object_get_parent (GST_OBJECT_CAST (bin));
3827     if (parent) {
3828       if (GST_IS_BIN (parent)) {
3829         result = gst_bin_get_by_name_recurse_up (GST_BIN_CAST (parent), name);
3830       }
3831       gst_object_unref (parent);
3832     }
3833   }
3834
3835   return result;
3836 }
3837
3838 static gint
3839 compare_interface (const GValue * velement, GValue * interface)
3840 {
3841   GstElement *element = g_value_get_object (velement);
3842   GType interface_type = (GType) g_value_get_pointer (interface);
3843   gint ret;
3844
3845   if (G_TYPE_CHECK_INSTANCE_TYPE (element, interface_type)) {
3846     ret = 0;
3847   } else {
3848     ret = 1;
3849   }
3850   return ret;
3851 }
3852
3853 /**
3854  * gst_bin_get_by_interface:
3855  * @bin: a #GstBin
3856  * @iface: the #GType of an interface
3857  *
3858  * Looks for an element inside the bin that implements the given
3859  * interface. If such an element is found, it returns the element.
3860  * You can cast this element to the given interface afterwards.  If you want
3861  * all elements that implement the interface, use
3862  * gst_bin_iterate_all_by_interface(). This function recurses into child bins.
3863  *
3864  * MT safe.  Caller owns returned reference.
3865  *
3866  * Returns: (transfer full): A #GstElement inside the bin implementing the interface
3867  */
3868 GstElement *
3869 gst_bin_get_by_interface (GstBin * bin, GType iface)
3870 {
3871   GstIterator *children;
3872   GValue result = { 0, };
3873   GstElement *element;
3874   gboolean found;
3875   GValue viface = { 0, };
3876
3877   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3878   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface), NULL);
3879
3880   g_value_init (&viface, G_TYPE_POINTER);
3881   g_value_set_pointer (&viface, (gpointer) iface);
3882
3883   children = gst_bin_iterate_recurse (bin);
3884   found = gst_iterator_find_custom (children, (GCompareFunc) compare_interface,
3885       &result, &viface);
3886   gst_iterator_free (children);
3887
3888   if (found) {
3889     element = g_value_dup_object (&result);
3890     g_value_unset (&result);
3891   } else {
3892     element = NULL;
3893   }
3894   g_value_unset (&viface);
3895
3896   return element;
3897 }
3898
3899 /**
3900  * gst_bin_iterate_all_by_interface:
3901  * @bin: a #GstBin
3902  * @iface: the #GType of an interface
3903  *
3904  * Looks for all elements inside the bin that implements the given
3905  * interface. You can safely cast all returned elements to the given interface.
3906  * The function recurses inside child bins. The iterator will yield a series
3907  * of #GstElement that should be unreffed after use.
3908  *
3909  * Each element yielded by the iterator will have its refcount increased, so
3910  * unref after use.
3911  *
3912  * MT safe.  Caller owns returned value.
3913  *
3914  * Returns: (transfer full): a #GstIterator of #GstElement for all elements
3915  *          in the bin implementing the given interface, or NULL
3916  */
3917 GstIterator *
3918 gst_bin_iterate_all_by_interface (GstBin * bin, GType iface)
3919 {
3920   GstIterator *children;
3921   GstIterator *result;
3922   GValue viface = { 0, };
3923
3924   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3925   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface), NULL);
3926
3927   g_value_init (&viface, G_TYPE_POINTER);
3928   g_value_set_pointer (&viface, (gpointer) iface);
3929
3930   children = gst_bin_iterate_recurse (bin);
3931   result = gst_iterator_filter (children, (GCompareFunc) compare_interface,
3932       &viface);
3933
3934   g_value_unset (&viface);
3935
3936   return result;
3937 }