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