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