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