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