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