Move dataurisrc element from -bad
[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 ((GQueue *) & 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       while (TRUE) {
3113         ret =
3114             gst_iterator_foreach (it, &reset_state, GINT_TO_POINTER (current));
3115         if (ret != GST_ITERATOR_RESYNC)
3116           break;
3117         gst_iterator_resync (it);
3118       }
3119       gst_iterator_free (it);
3120     }
3121     goto done;
3122   }
3123 }
3124
3125 /*
3126  * This function is a utility event handler for seek events.
3127  * It will send the event to all sinks or sources and appropriate
3128  * ghost pads depending on the event-direction.
3129  *
3130  * Applications are free to override this behaviour and
3131  * implement their own seek handler, but this will work for
3132  * pretty much all cases in practice.
3133  */
3134 static gboolean
3135 gst_bin_send_event (GstElement * element, GstEvent * event)
3136 {
3137   GstBin *bin = GST_BIN_CAST (element);
3138   GstIterator *iter;
3139   gboolean res = TRUE;
3140   gboolean done = FALSE;
3141   GValue data = { 0, };
3142
3143   if (GST_EVENT_IS_DOWNSTREAM (event)) {
3144     iter = gst_bin_iterate_sources (bin);
3145     GST_DEBUG_OBJECT (bin, "Sending %s event to src children",
3146         GST_EVENT_TYPE_NAME (event));
3147   } else {
3148     iter = gst_bin_iterate_sinks (bin);
3149     GST_DEBUG_OBJECT (bin, "Sending %s event to sink children",
3150         GST_EVENT_TYPE_NAME (event));
3151   }
3152
3153   while (!done) {
3154     switch (gst_iterator_next (iter, &data)) {
3155       case GST_ITERATOR_OK:
3156       {
3157         GstElement *child = g_value_get_object (&data);
3158
3159         gst_event_ref (event);
3160         res &= gst_element_send_event (child, event);
3161
3162         GST_LOG_OBJECT (child, "After handling %s event: %d",
3163             GST_EVENT_TYPE_NAME (event), res);
3164
3165         g_value_reset (&data);
3166         break;
3167       }
3168       case GST_ITERATOR_RESYNC:
3169         gst_iterator_resync (iter);
3170         res = TRUE;
3171         break;
3172       case GST_ITERATOR_DONE:
3173         done = TRUE;
3174         break;
3175       case GST_ITERATOR_ERROR:
3176         g_assert_not_reached ();
3177         break;
3178     }
3179   }
3180   g_value_unset (&data);
3181   gst_iterator_free (iter);
3182
3183   if (GST_EVENT_IS_DOWNSTREAM (event)) {
3184     iter = gst_element_iterate_sink_pads (GST_ELEMENT (bin));
3185     GST_DEBUG_OBJECT (bin, "Sending %s event to sink pads",
3186         GST_EVENT_TYPE_NAME (event));
3187   } else {
3188     iter = gst_element_iterate_src_pads (GST_ELEMENT (bin));
3189     GST_DEBUG_OBJECT (bin, "Sending %s event to src pads",
3190         GST_EVENT_TYPE_NAME (event));
3191   }
3192
3193   done = FALSE;
3194   while (!done) {
3195     switch (gst_iterator_next (iter, &data)) {
3196       case GST_ITERATOR_OK:
3197       {
3198         GstPad *pad = g_value_get_object (&data);
3199
3200         gst_event_ref (event);
3201         res &= gst_pad_send_event (pad, event);
3202         GST_LOG_OBJECT (pad, "After handling %s event: %d",
3203             GST_EVENT_TYPE_NAME (event), res);
3204         break;
3205       }
3206       case GST_ITERATOR_RESYNC:
3207         gst_iterator_resync (iter);
3208         res = TRUE;
3209         break;
3210       case GST_ITERATOR_DONE:
3211         done = TRUE;
3212         break;
3213       case GST_ITERATOR_ERROR:
3214         g_assert_not_reached ();
3215         break;
3216     }
3217   }
3218
3219   g_value_unset (&data);
3220   gst_iterator_free (iter);
3221   gst_event_unref (event);
3222
3223   return res;
3224 }
3225
3226 /* this is the function called by the threadpool. When async elements commit
3227  * their state, this function will attempt to bring the bin to the next state.
3228  */
3229 static void
3230 gst_bin_continue_func (GstBin * bin, BinContinueData * data)
3231 {
3232   GstState current, next, pending;
3233   GstStateChange transition;
3234
3235   pending = data->pending;
3236
3237   GST_DEBUG_OBJECT (bin, "waiting for state lock");
3238   GST_STATE_LOCK (bin);
3239
3240   GST_DEBUG_OBJECT (bin, "doing state continue");
3241   GST_OBJECT_LOCK (bin);
3242
3243   /* if a new state change happened after this thread was scheduled, we return
3244    * immediately. */
3245   if (data->cookie != GST_ELEMENT_CAST (bin)->state_cookie)
3246     goto interrupted;
3247
3248   current = GST_STATE (bin);
3249   next = GST_STATE_GET_NEXT (current, pending);
3250   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
3251
3252   GST_STATE_NEXT (bin) = next;
3253   GST_STATE_PENDING (bin) = pending;
3254   /* mark busy */
3255   GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3256   GST_OBJECT_UNLOCK (bin);
3257
3258   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3259       "continue state change %s to %s, final %s",
3260       gst_element_state_get_name (current),
3261       gst_element_state_get_name (next), gst_element_state_get_name (pending));
3262
3263   gst_element_change_state (GST_ELEMENT_CAST (bin), transition);
3264
3265   GST_STATE_UNLOCK (bin);
3266   GST_DEBUG_OBJECT (bin, "state continue done");
3267
3268   return;
3269
3270 interrupted:
3271   {
3272     GST_OBJECT_UNLOCK (bin);
3273     GST_STATE_UNLOCK (bin);
3274     GST_DEBUG_OBJECT (bin, "state continue aborted due to intervening change");
3275     return;
3276   }
3277 }
3278
3279 static GstBusSyncReply
3280 bin_bus_handler (GstBus * bus, GstMessage * message, GstBin * bin)
3281 {
3282   GstBinClass *bclass;
3283
3284   bclass = GST_BIN_GET_CLASS (bin);
3285   if (bclass->handle_message)
3286     bclass->handle_message (bin, message);
3287   else
3288     gst_message_unref (message);
3289
3290   return GST_BUS_DROP;
3291 }
3292
3293 static void
3294 free_bin_continue_data (BinContinueData * data)
3295 {
3296   g_slice_free (BinContinueData, data);
3297 }
3298
3299 static void
3300 bin_push_state_continue (GstBin * bin, BinContinueData * data)
3301 {
3302   GST_DEBUG_OBJECT (bin, "pushing continue on thread pool");
3303   gst_element_call_async (GST_ELEMENT_CAST (bin),
3304       (GstElementCallAsyncFunc) gst_bin_continue_func, data,
3305       (GDestroyNotify) free_bin_continue_data);
3306 }
3307
3308 /* an element started an async state change, if we were not busy with a state
3309  * change, we perform a lost state.
3310  * This function is called with the OBJECT lock.
3311  */
3312 static void
3313 bin_handle_async_start (GstBin * bin)
3314 {
3315   GstState old_state, new_state;
3316   gboolean toplevel;
3317   GstMessage *amessage = NULL;
3318
3319   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_FAILURE)
3320     goto had_error;
3321
3322   /* get our toplevel state */
3323   toplevel = BIN_IS_TOPLEVEL (bin);
3324
3325   /* prepare an ASYNC_START message, we always post the start message even if we
3326    * are busy with a state change or when we are NO_PREROLL. */
3327   if (!toplevel)
3328     /* non toplevel bin, prepare async-start for the parent */
3329     amessage = gst_message_new_async_start (GST_OBJECT_CAST (bin));
3330
3331   if (bin->polling || GST_STATE_PENDING (bin) != GST_STATE_VOID_PENDING)
3332     goto was_busy;
3333
3334   /* async starts are ignored when we are NO_PREROLL */
3335   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_NO_PREROLL)
3336     goto was_no_preroll;
3337
3338   old_state = GST_STATE (bin);
3339
3340   /* when we PLAYING we go back to PAUSED, when preroll happens, we go back to
3341    * PLAYING after optionally redistributing the base_time. */
3342   if (old_state > GST_STATE_PAUSED)
3343     new_state = GST_STATE_PAUSED;
3344   else
3345     new_state = old_state;
3346
3347   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
3348       "lost state of %s, new %s", gst_element_state_get_name (old_state),
3349       gst_element_state_get_name (new_state));
3350
3351   GST_STATE (bin) = new_state;
3352   GST_STATE_NEXT (bin) = new_state;
3353   GST_STATE_PENDING (bin) = new_state;
3354   GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3355   GST_OBJECT_UNLOCK (bin);
3356
3357   /* post message */
3358   _priv_gst_element_state_changed (GST_ELEMENT_CAST (bin), new_state, new_state,
3359       new_state);
3360
3361 post_start:
3362   if (amessage) {
3363     /* post our ASYNC_START. */
3364     GST_DEBUG_OBJECT (bin, "posting ASYNC_START to parent");
3365     gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
3366   }
3367   GST_OBJECT_LOCK (bin);
3368
3369   return;
3370
3371 had_error:
3372   {
3373     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "we had an error");
3374     return;
3375   }
3376 was_busy:
3377   {
3378     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "state change busy");
3379     GST_OBJECT_UNLOCK (bin);
3380     goto post_start;
3381   }
3382 was_no_preroll:
3383   {
3384     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "ignoring, we are NO_PREROLL");
3385     GST_OBJECT_UNLOCK (bin);
3386     goto post_start;
3387   }
3388 }
3389
3390 /* this function is called when there are no more async elements in the bin. We
3391  * post a state changed message and an ASYNC_DONE message.
3392  * This function is called with the OBJECT lock.
3393  */
3394 static void
3395 bin_handle_async_done (GstBin * bin, GstStateChangeReturn ret,
3396     gboolean flag_pending, GstClockTime running_time)
3397 {
3398   GstState current, pending, target;
3399   GstStateChangeReturn old_ret;
3400   GstState old_state, old_next;
3401   gboolean toplevel, state_changed = FALSE;
3402   GstMessage *amessage = NULL;
3403   BinContinueData *cont = NULL;
3404
3405   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_FAILURE)
3406     goto had_error;
3407
3408   pending = GST_STATE_PENDING (bin);
3409
3410   if (bin->polling)
3411     goto was_busy;
3412
3413   /* check if there is something to commit */
3414   if (pending == GST_STATE_VOID_PENDING)
3415     goto nothing_pending;
3416
3417   old_ret = GST_STATE_RETURN (bin);
3418   GST_STATE_RETURN (bin) = ret;
3419
3420   /* move to the next target state */
3421   target = GST_STATE_TARGET (bin);
3422   pending = GST_STATE_PENDING (bin) = target;
3423
3424   amessage = gst_message_new_async_done (GST_OBJECT_CAST (bin), running_time);
3425
3426   old_state = GST_STATE (bin);
3427   /* this is the state we should go to next */
3428   old_next = GST_STATE_NEXT (bin);
3429
3430   if (old_next != GST_STATE_PLAYING) {
3431     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3432         "committing state from %s to %s, old pending %s",
3433         gst_element_state_get_name (old_state),
3434         gst_element_state_get_name (old_next),
3435         gst_element_state_get_name (pending));
3436
3437     /* update current state */
3438     current = GST_STATE (bin) = old_next;
3439   } else {
3440     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3441         "setting state from %s to %s, pending %s",
3442         gst_element_state_get_name (old_state),
3443         gst_element_state_get_name (old_state),
3444         gst_element_state_get_name (pending));
3445     current = old_state;
3446   }
3447
3448   /* get our toplevel state */
3449   toplevel = BIN_IS_TOPLEVEL (bin);
3450
3451   /* see if we reached the final state. If we are not toplevel, we also have to
3452    * stop here, the parent will continue our state. */
3453   if ((pending == current) || !toplevel) {
3454     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3455         "completed state change, pending VOID");
3456
3457     /* mark VOID pending */
3458     pending = GST_STATE_VOID_PENDING;
3459     GST_STATE_PENDING (bin) = pending;
3460     GST_STATE_NEXT (bin) = GST_STATE_VOID_PENDING;
3461   } else {
3462     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3463         "continue state change, pending %s",
3464         gst_element_state_get_name (pending));
3465
3466     cont = g_slice_new (BinContinueData);
3467
3468     /* cookie to detect concurrent state change */
3469     cont->cookie = GST_ELEMENT_CAST (bin)->state_cookie;
3470     /* pending target state */
3471     cont->pending = pending;
3472     /* mark busy */
3473     GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3474     GST_STATE_NEXT (bin) = GST_STATE_GET_NEXT (old_state, pending);
3475   }
3476
3477   if (old_next != GST_STATE_PLAYING) {
3478     if (old_state != old_next || old_ret == GST_STATE_CHANGE_ASYNC) {
3479       state_changed = TRUE;
3480     }
3481   }
3482   GST_OBJECT_UNLOCK (bin);
3483
3484   if (state_changed) {
3485     _priv_gst_element_state_changed (GST_ELEMENT_CAST (bin), old_state,
3486         old_next, pending);
3487   }
3488   if (amessage) {
3489     /* post our combined ASYNC_DONE when all is ASYNC_DONE. */
3490     GST_DEBUG_OBJECT (bin, "posting ASYNC_DONE to parent");
3491     gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
3492   }
3493
3494   GST_OBJECT_LOCK (bin);
3495   if (cont) {
3496     /* toplevel, start continue state */
3497     GST_DEBUG_OBJECT (bin, "all async-done, starting state continue");
3498     bin_push_state_continue (bin, cont);
3499   } else {
3500     GST_DEBUG_OBJECT (bin, "state change complete");
3501     GST_STATE_BROADCAST (bin);
3502   }
3503   return;
3504
3505 had_error:
3506   {
3507     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "we had an error");
3508     return;
3509   }
3510 was_busy:
3511   {
3512     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "state change busy");
3513     /* if we were busy with a state change and we are requested to flag a
3514      * pending async done, we do so here */
3515     if (flag_pending)
3516       bin->priv->pending_async_done = TRUE;
3517     return;
3518   }
3519 nothing_pending:
3520   {
3521     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "nothing pending");
3522     return;
3523   }
3524 }
3525
3526 static void
3527 bin_do_eos (GstBin * bin)
3528 {
3529   guint32 seqnum = 0;
3530   gboolean eos;
3531
3532   GST_OBJECT_LOCK (bin);
3533   /* If all sinks are EOS, we're in PLAYING and no state change is pending
3534    * (or we're doing playing to playing and noone else will trigger posting
3535    * EOS for us) we forward the EOS message to the parent bin or application
3536    */
3537   eos = GST_STATE (bin) == GST_STATE_PLAYING
3538       && (GST_STATE_PENDING (bin) == GST_STATE_VOID_PENDING ||
3539       GST_STATE_PENDING (bin) == GST_STATE_PLAYING)
3540       && bin->priv->posted_playing && is_eos (bin, &seqnum);
3541   GST_OBJECT_UNLOCK (bin);
3542
3543   if (eos
3544       && g_atomic_int_compare_and_exchange (&bin->priv->posted_eos, FALSE,
3545           TRUE)) {
3546     GstMessage *tmessage;
3547
3548     /* Clear out any further messages, and reset posted_eos so we can
3549        detect any new EOS that happens (eg, after a seek). Since all
3550        sinks have now posted an EOS, there will be no further EOS events
3551        seen unless there is a new logical EOS */
3552     GST_OBJECT_LOCK (bin);
3553     bin_remove_messages (bin, NULL, GST_MESSAGE_EOS);
3554     bin->priv->posted_eos = FALSE;
3555     GST_OBJECT_UNLOCK (bin);
3556
3557     tmessage = gst_message_new_eos (GST_OBJECT_CAST (bin));
3558     gst_message_set_seqnum (tmessage, seqnum);
3559     GST_DEBUG_OBJECT (bin,
3560         "all sinks posted EOS, posting seqnum #%" G_GUINT32_FORMAT, seqnum);
3561     gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3562   } else {
3563     GST_LOG_OBJECT (bin, "Not forwarding EOS due to in progress state change, "
3564         " or already posted, or waiting for more EOS");
3565   }
3566 }
3567
3568 static void
3569 bin_do_stream_start (GstBin * bin)
3570 {
3571   guint32 seqnum = 0;
3572   gboolean stream_start;
3573   gboolean have_group_id = FALSE;
3574   guint group_id = 0;
3575
3576   GST_OBJECT_LOCK (bin);
3577   /* If all sinks are STREAM_START we forward the STREAM_START message
3578    * to the parent bin or application
3579    */
3580   stream_start = is_stream_start (bin, &seqnum, &have_group_id, &group_id);
3581   GST_OBJECT_UNLOCK (bin);
3582
3583   if (stream_start) {
3584     GstMessage *tmessage;
3585
3586     GST_OBJECT_LOCK (bin);
3587     bin_remove_messages (bin, NULL, GST_MESSAGE_STREAM_START);
3588     GST_OBJECT_UNLOCK (bin);
3589
3590     tmessage = gst_message_new_stream_start (GST_OBJECT_CAST (bin));
3591     gst_message_set_seqnum (tmessage, seqnum);
3592     if (have_group_id)
3593       gst_message_set_group_id (tmessage, group_id);
3594
3595     GST_DEBUG_OBJECT (bin,
3596         "all sinks posted STREAM_START, posting seqnum #%" G_GUINT32_FORMAT,
3597         seqnum);
3598     gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3599   }
3600 }
3601
3602 /* must be called without the object lock as it posts messages */
3603 static void
3604 bin_do_message_forward (GstBin * bin, GstMessage * message)
3605 {
3606   if (bin->priv->message_forward) {
3607     GstMessage *forwarded;
3608
3609     GST_DEBUG_OBJECT (bin, "pass %s message upward",
3610         GST_MESSAGE_TYPE_NAME (message));
3611
3612     /* we need to convert these messages to element messages so that our parent
3613      * bin can easily ignore them and so that the application can easily
3614      * distinguish between the internally forwarded and the real messages. */
3615     forwarded = gst_message_new_element (GST_OBJECT_CAST (bin),
3616         gst_structure_new ("GstBinForwarded",
3617             "message", GST_TYPE_MESSAGE, message, NULL));
3618
3619     gst_element_post_message (GST_ELEMENT_CAST (bin), forwarded);
3620   }
3621 }
3622
3623 static void
3624 gst_bin_update_context (GstBin * bin, GstContext * context)
3625 {
3626   GST_OBJECT_LOCK (bin);
3627   gst_bin_update_context_unlocked (bin, context);
3628   GST_OBJECT_UNLOCK (bin);
3629 }
3630
3631 static void
3632 gst_bin_update_context_unlocked (GstBin * bin, GstContext * context)
3633 {
3634   const gchar *context_type;
3635   GList *l, **contexts;
3636
3637   contexts = &GST_ELEMENT_CAST (bin)->contexts;
3638   context_type = gst_context_get_context_type (context);
3639
3640   GST_DEBUG_OBJECT (bin, "set context %p %" GST_PTR_FORMAT, context,
3641       gst_context_get_structure (context));
3642   for (l = *contexts; l; l = l->next) {
3643     GstContext *tmp = l->data;
3644     const gchar *tmp_type = gst_context_get_context_type (tmp);
3645
3646     /* Always store newest context but never replace
3647      * a persistent one by a non-persistent one */
3648     if (strcmp (context_type, tmp_type) == 0 &&
3649         (gst_context_is_persistent (context) ||
3650             !gst_context_is_persistent (tmp))) {
3651       gst_context_replace ((GstContext **) & l->data, context);
3652       break;
3653     }
3654   }
3655   /* Not found? Add */
3656   if (l == NULL) {
3657     *contexts = g_list_prepend (*contexts, gst_context_ref (context));
3658   }
3659 }
3660
3661 /* handle child messages:
3662  *
3663  * This method is called synchronously when a child posts a message on
3664  * the internal bus.
3665  *
3666  * GST_MESSAGE_EOS: This message is only posted by sinks
3667  *     in the PLAYING state. If all sinks posted the EOS message, post
3668  *     one upwards.
3669  *
3670  * GST_MESSAGE_STATE_DIRTY: Deprecated
3671  *
3672  * GST_MESSAGE_SEGMENT_START: just collect, never forward upwards. If an
3673  *     element posts segment_start twice, only the last message is kept.
3674  *
3675  * GST_MESSAGE_SEGMENT_DONE: replace SEGMENT_START message from same poster
3676  *     with the segment_done message. If there are no more segment_start
3677  *     messages, post segment_done message upwards.
3678  *
3679  * GST_MESSAGE_DURATION_CHANGED: clear any cached durations.
3680  *     Whenever someone performs a duration query on the bin, we store the
3681  *     result so we can answer it quicker the next time. Any element that
3682  *     changes its duration marks our cached values invalid.
3683  *     This message is also posted upwards. This is currently disabled
3684  *     because too many elements don't post DURATION_CHANGED messages when
3685  *     the duration changes.
3686  *
3687  * GST_MESSAGE_CLOCK_LOST: This message is posted by an element when it
3688  *     can no longer provide a clock. The default bin behaviour is to
3689  *     check if the lost clock was the one provided by the bin. If so and
3690  *     we are currently in the PLAYING state, we forward the message to
3691  *     our parent.
3692  *     This message is also generated when we remove a clock provider from
3693  *     a bin. If this message is received by the application, it should
3694  *     PAUSE the pipeline and set it back to PLAYING to force a new clock
3695  *     and a new base_time distribution.
3696  *
3697  * GST_MESSAGE_CLOCK_PROVIDE: This message is generated when an element
3698  *     can provide a clock. This mostly happens when we add a new clock
3699  *     provider to the bin. The default behaviour of the bin is to mark the
3700  *     currently selected clock as dirty, which will perform a clock
3701  *     recalculation the next time we are asked to provide a clock.
3702  *     This message is never sent to the application but is forwarded to
3703  *     the parent.
3704  *
3705  * GST_MESSAGE_ASYNC_START: Create an internal ELEMENT message that stores
3706  *     the state of the element and the fact that the element will need a
3707  *     new base_time. This message is not forwarded to the application.
3708  *
3709  * GST_MESSAGE_ASYNC_DONE: Find the internal ELEMENT message we kept for the
3710  *     element when it posted ASYNC_START. If all elements are done, post a
3711  *     ASYNC_DONE message to the parent.
3712  *
3713  * OTHER: post upwards.
3714  */
3715 static void
3716 gst_bin_handle_message_func (GstBin * bin, GstMessage * message)
3717 {
3718   GstObject *src;
3719   GstMessageType type;
3720   GstMessage *tmessage;
3721   guint32 seqnum;
3722
3723   src = GST_MESSAGE_SRC (message);
3724   type = GST_MESSAGE_TYPE (message);
3725
3726   GST_DEBUG_OBJECT (bin, "[msg %p] handling child %s message of type %s",
3727       message, src ? GST_ELEMENT_NAME (src) : "(NULL)",
3728       GST_MESSAGE_TYPE_NAME (message));
3729
3730   switch (type) {
3731     case GST_MESSAGE_ERROR:
3732     {
3733       GST_OBJECT_LOCK (bin);
3734       /* flag error */
3735       GST_DEBUG_OBJECT (bin, "got ERROR message, unlocking state change");
3736       GST_STATE_RETURN (bin) = GST_STATE_CHANGE_FAILURE;
3737       GST_STATE_BROADCAST (bin);
3738       GST_OBJECT_UNLOCK (bin);
3739
3740       goto forward;
3741     }
3742     case GST_MESSAGE_EOS:
3743     {
3744
3745       /* collect all eos messages from the children */
3746       bin_do_message_forward (bin, message);
3747       GST_OBJECT_LOCK (bin);
3748       /* ref message for future use  */
3749       bin_replace_message (bin, message, GST_MESSAGE_EOS);
3750       GST_OBJECT_UNLOCK (bin);
3751
3752       bin_do_eos (bin);
3753       break;
3754     }
3755     case GST_MESSAGE_STREAM_START:
3756     {
3757
3758       /* collect all stream_start messages from the children */
3759       GST_OBJECT_LOCK (bin);
3760       /* ref message for future use  */
3761       bin_replace_message (bin, message, GST_MESSAGE_STREAM_START);
3762       GST_OBJECT_UNLOCK (bin);
3763
3764       bin_do_stream_start (bin);
3765       break;
3766     }
3767     case GST_MESSAGE_STATE_DIRTY:
3768     {
3769       GST_WARNING_OBJECT (bin, "received deprecated STATE_DIRTY message");
3770
3771       /* free message */
3772       gst_message_unref (message);
3773       break;
3774     }
3775     case GST_MESSAGE_SEGMENT_START:{
3776       gboolean post = FALSE;
3777       GstFormat format;
3778       gint64 position;
3779
3780       gst_message_parse_segment_start (message, &format, &position);
3781       seqnum = gst_message_get_seqnum (message);
3782
3783       bin_do_message_forward (bin, message);
3784
3785       GST_OBJECT_LOCK (bin);
3786       /* if this is the first segment-start, post to parent but not to the
3787        * application */
3788       if (!find_message (bin, NULL, GST_MESSAGE_SEGMENT_START) &&
3789           (GST_OBJECT_PARENT (bin) != NULL)) {
3790         post = TRUE;
3791       }
3792       /* replace any previous segment_start message from this source
3793        * with the new segment start message */
3794       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
3795       GST_OBJECT_UNLOCK (bin);
3796       if (post) {
3797         tmessage = gst_message_new_segment_start (GST_OBJECT_CAST (bin),
3798             format, position);
3799         gst_message_set_seqnum (tmessage, seqnum);
3800
3801         /* post segment start with initial format and position. */
3802         GST_DEBUG_OBJECT (bin, "posting SEGMENT_START (%u) bus message: %p",
3803             seqnum, message);
3804         gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3805       }
3806       break;
3807     }
3808     case GST_MESSAGE_SEGMENT_DONE:
3809     {
3810       gboolean post = FALSE;
3811       GstFormat format;
3812       gint64 position;
3813
3814       gst_message_parse_segment_done (message, &format, &position);
3815       seqnum = gst_message_get_seqnum (message);
3816
3817       bin_do_message_forward (bin, message);
3818
3819       GST_OBJECT_LOCK (bin);
3820       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
3821       /* if there are no more segment_start messages, everybody posted
3822        * a segment_done and we can post one on the bus. */
3823
3824       /* we don't care who still has a pending segment start */
3825       if (!find_message (bin, NULL, GST_MESSAGE_SEGMENT_START)) {
3826         /* nothing found */
3827         post = TRUE;
3828         /* remove all old segment_done messages */
3829         bin_remove_messages (bin, NULL, GST_MESSAGE_SEGMENT_DONE);
3830       }
3831       GST_OBJECT_UNLOCK (bin);
3832       if (post) {
3833         tmessage = gst_message_new_segment_done (GST_OBJECT_CAST (bin),
3834             format, position);
3835         gst_message_set_seqnum (tmessage, seqnum);
3836
3837         /* post segment done with latest format and position. */
3838         GST_DEBUG_OBJECT (bin, "posting SEGMENT_DONE (%u) bus message: %p",
3839             seqnum, message);
3840         gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3841       }
3842       break;
3843     }
3844     case GST_MESSAGE_DURATION_CHANGED:
3845     {
3846       /* FIXME: remove all cached durations, next time somebody asks
3847        * for duration, we will recalculate. */
3848 #if 0
3849       GST_OBJECT_LOCK (bin);
3850       bin_remove_messages (bin, NULL, GST_MESSAGE_DURATION_CHANGED);
3851       GST_OBJECT_UNLOCK (bin);
3852 #endif
3853       goto forward;
3854     }
3855     case GST_MESSAGE_CLOCK_LOST:
3856     {
3857       GstClock **provided_clock_p;
3858       GstElement **clock_provider_p;
3859       gboolean playing, toplevel, provided, forward;
3860       GstClock *clock;
3861
3862       gst_message_parse_clock_lost (message, &clock);
3863
3864       GST_OBJECT_LOCK (bin);
3865       bin->clock_dirty = TRUE;
3866       /* if we lost the clock that we provided, post to parent but
3867        * only if we are not a top-level bin or PLAYING.
3868        * The reason for this is that applications should be able
3869        * to PAUSE/PLAY if they receive this message without worrying
3870        * about the state of the pipeline. */
3871       provided = (clock == bin->provided_clock);
3872       playing = (GST_STATE (bin) == GST_STATE_PLAYING);
3873       toplevel = GST_OBJECT_PARENT (bin) == NULL;
3874       forward = provided && (playing || !toplevel);
3875       if (provided) {
3876         GST_DEBUG_OBJECT (bin,
3877             "Lost clock %" GST_PTR_FORMAT " provided by %" GST_PTR_FORMAT,
3878             bin->provided_clock, bin->clock_provider);
3879         provided_clock_p = &bin->provided_clock;
3880         clock_provider_p = &bin->clock_provider;
3881         gst_object_replace ((GstObject **) provided_clock_p, NULL);
3882         gst_object_replace ((GstObject **) clock_provider_p, NULL);
3883       }
3884       GST_DEBUG_OBJECT (bin, "provided %d, playing %d, forward %d",
3885           provided, playing, forward);
3886       GST_OBJECT_UNLOCK (bin);
3887
3888       if (forward)
3889         goto forward;
3890
3891       /* free message */
3892       gst_message_unref (message);
3893       break;
3894     }
3895     case GST_MESSAGE_CLOCK_PROVIDE:
3896     {
3897       gboolean forward;
3898
3899       GST_OBJECT_LOCK (bin);
3900       bin->clock_dirty = TRUE;
3901       /* a new clock is available, post to parent but not
3902        * to the application */
3903       forward = GST_OBJECT_PARENT (bin) != NULL;
3904       GST_OBJECT_UNLOCK (bin);
3905
3906       if (forward)
3907         goto forward;
3908
3909       /* free message */
3910       gst_message_unref (message);
3911       break;
3912     }
3913     case GST_MESSAGE_ASYNC_START:
3914     {
3915       GstState target;
3916
3917       GST_DEBUG_OBJECT (bin, "ASYNC_START message %p, %s", message,
3918           src ? GST_OBJECT_NAME (src) : "(NULL)");
3919
3920       bin_do_message_forward (bin, message);
3921
3922       GST_OBJECT_LOCK (bin);
3923       /* we ignore the message if we are going to <= READY */
3924       if ((target = GST_STATE_TARGET (bin)) <= GST_STATE_READY)
3925         goto ignore_start_message;
3926
3927       /* takes ownership of the message */
3928       bin_replace_message (bin, message, GST_MESSAGE_ASYNC_START);
3929
3930       bin_handle_async_start (bin);
3931       GST_OBJECT_UNLOCK (bin);
3932       break;
3933
3934     ignore_start_message:
3935       {
3936         GST_DEBUG_OBJECT (bin, "ignoring message, target %s",
3937             gst_element_state_get_name (target));
3938         GST_OBJECT_UNLOCK (bin);
3939         gst_message_unref (message);
3940         break;
3941       }
3942     }
3943     case GST_MESSAGE_ASYNC_DONE:
3944     {
3945       GstClockTime running_time;
3946       GstState target;
3947
3948       GST_DEBUG_OBJECT (bin, "ASYNC_DONE message %p, %s", message,
3949           src ? GST_OBJECT_NAME (src) : "(NULL)");
3950
3951       gst_message_parse_async_done (message, &running_time);
3952
3953       bin_do_message_forward (bin, message);
3954
3955       GST_OBJECT_LOCK (bin);
3956       /* ignore messages if we are shutting down */
3957       if ((target = GST_STATE_TARGET (bin)) <= GST_STATE_READY)
3958         goto ignore_done_message;
3959
3960       bin_replace_message (bin, message, GST_MESSAGE_ASYNC_START);
3961       /* if there are no more ASYNC_START messages, everybody posted
3962        * a ASYNC_DONE and we can post one on the bus. When checking, we
3963        * don't care who still has a pending ASYNC_START */
3964       if (!find_message (bin, NULL, GST_MESSAGE_ASYNC_START)) {
3965         /* nothing found, remove all old ASYNC_DONE messages */
3966         bin_remove_messages (bin, NULL, GST_MESSAGE_ASYNC_DONE);
3967
3968         GST_DEBUG_OBJECT (bin, "async elements commited");
3969         /* when we get an async done message when a state change was busy, we
3970          * need to set the pending_done flag so that at the end of the state
3971          * change we can see if we need to verify pending async elements, hence
3972          * the TRUE argument here. */
3973         bin_handle_async_done (bin, GST_STATE_CHANGE_SUCCESS, TRUE,
3974             running_time);
3975       } else {
3976         GST_DEBUG_OBJECT (bin, "there are more async elements pending");
3977       }
3978       GST_OBJECT_UNLOCK (bin);
3979       break;
3980
3981     ignore_done_message:
3982       {
3983         GST_DEBUG_OBJECT (bin, "ignoring message, target %s",
3984             gst_element_state_get_name (target));
3985         GST_OBJECT_UNLOCK (bin);
3986         gst_message_unref (message);
3987         break;
3988       }
3989     }
3990     case GST_MESSAGE_STRUCTURE_CHANGE:
3991     {
3992       gboolean busy;
3993
3994       gst_message_parse_structure_change (message, NULL, NULL, &busy);
3995
3996       GST_OBJECT_LOCK (bin);
3997       if (busy) {
3998         /* while the pad is busy, avoid following it when doing state changes.
3999          * Don't update the cookie yet, we will do that after the structure
4000          * change finished and we are ready to inspect the new updated
4001          * structure. */
4002         bin_replace_message (bin, message, GST_MESSAGE_STRUCTURE_CHANGE);
4003         message = NULL;
4004       } else {
4005         /* a pad link/unlink ended, signal the state change iterator that we
4006          * need to resync by updating the structure_cookie. */
4007         bin_remove_messages (bin, GST_MESSAGE_SRC (message),
4008             GST_MESSAGE_STRUCTURE_CHANGE);
4009         if (!GST_BIN_IS_NO_RESYNC (bin))
4010           bin->priv->structure_cookie++;
4011       }
4012       GST_OBJECT_UNLOCK (bin);
4013
4014       if (message)
4015         gst_message_unref (message);
4016
4017       break;
4018     }
4019     case GST_MESSAGE_NEED_CONTEXT:{
4020       const gchar *context_type;
4021       GList *l, *contexts;
4022
4023       gst_message_parse_context_type (message, &context_type);
4024       GST_OBJECT_LOCK (bin);
4025       contexts = GST_ELEMENT_CAST (bin)->contexts;
4026       GST_LOG_OBJECT (bin, "got need-context message type: %s", context_type);
4027       for (l = contexts; l; l = l->next) {
4028         GstContext *tmp = l->data;
4029         const gchar *tmp_type = gst_context_get_context_type (tmp);
4030
4031         if (strcmp (context_type, tmp_type) == 0) {
4032           gst_element_set_context (GST_ELEMENT (src), l->data);
4033           break;
4034         }
4035       }
4036       GST_OBJECT_UNLOCK (bin);
4037
4038       /* Forward if we couldn't answer the message */
4039       if (l == NULL) {
4040         goto forward;
4041       } else {
4042         gst_message_unref (message);
4043       }
4044
4045       break;
4046     }
4047     case GST_MESSAGE_HAVE_CONTEXT:{
4048       GstContext *context;
4049
4050       gst_message_parse_have_context (message, &context);
4051       gst_bin_update_context (bin, context);
4052       gst_context_unref (context);
4053
4054       goto forward;
4055       break;
4056     }
4057     default:
4058       goto forward;
4059   }
4060   return;
4061
4062 forward:
4063   {
4064     /* Send all other messages upward */
4065     GST_DEBUG_OBJECT (bin, "posting message upward");
4066     gst_element_post_message (GST_ELEMENT_CAST (bin), message);
4067     return;
4068   }
4069 }
4070
4071 /* generic struct passed to all query fold methods */
4072 typedef struct
4073 {
4074   GstQuery *query;
4075   gint64 min;
4076   gint64 max;
4077   gboolean live;
4078 } QueryFold;
4079
4080 typedef void (*QueryInitFunction) (GstBin * bin, QueryFold * fold);
4081 typedef void (*QueryDoneFunction) (GstBin * bin, QueryFold * fold);
4082
4083 /* for duration/position we collect all durations/positions and take
4084  * the MAX of all valid results */
4085 static void
4086 bin_query_min_max_init (GstBin * bin, QueryFold * fold)
4087 {
4088   fold->min = 0;
4089   fold->max = -1;
4090   fold->live = FALSE;
4091 }
4092
4093 static gboolean
4094 bin_query_duration_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4095 {
4096   gboolean res = FALSE;
4097   GstObject *item = g_value_get_object (vitem);
4098   if (GST_IS_PAD (item))
4099     res = gst_pad_query (GST_PAD (item), fold->query);
4100   else
4101     res = gst_element_query (GST_ELEMENT (item), fold->query);
4102
4103   if (res) {
4104     gint64 duration;
4105
4106     g_value_set_boolean (ret, TRUE);
4107
4108     gst_query_parse_duration (fold->query, NULL, &duration);
4109
4110     GST_DEBUG_OBJECT (item, "got duration %" G_GINT64_FORMAT, duration);
4111
4112     if (duration == -1) {
4113       /* duration query succeeded, but duration is unknown */
4114       fold->max = -1;
4115       return FALSE;
4116     }
4117
4118     if (duration > fold->max)
4119       fold->max = duration;
4120   }
4121
4122   return TRUE;
4123 }
4124
4125 static void
4126 bin_query_duration_done (GstBin * bin, QueryFold * fold)
4127 {
4128   GstFormat format;
4129
4130   gst_query_parse_duration (fold->query, &format, NULL);
4131   /* store max in query result */
4132   gst_query_set_duration (fold->query, format, fold->max);
4133
4134   GST_DEBUG_OBJECT (bin, "max duration %" G_GINT64_FORMAT, fold->max);
4135
4136   /* FIXME: re-implement duration caching */
4137 #if 0
4138   /* and cache now */
4139   GST_OBJECT_LOCK (bin);
4140   bin->messages = g_list_prepend (bin->messages,
4141       gst_message_new_duration (GST_OBJECT_CAST (bin), format, fold->max));
4142   GST_OBJECT_UNLOCK (bin);
4143 #endif
4144 }
4145
4146 static gboolean
4147 bin_query_position_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4148 {
4149   gboolean res = FALSE;
4150   GstObject *item = g_value_get_object (vitem);
4151   if (GST_IS_PAD (item))
4152     res = gst_pad_query (GST_PAD (item), fold->query);
4153   else
4154     res = gst_element_query (GST_ELEMENT (item), fold->query);
4155
4156   if (res) {
4157     gint64 position;
4158
4159     g_value_set_boolean (ret, TRUE);
4160
4161     gst_query_parse_position (fold->query, NULL, &position);
4162
4163     GST_DEBUG_OBJECT (item, "got position %" G_GINT64_FORMAT, position);
4164
4165     if (position > fold->max)
4166       fold->max = position;
4167   }
4168
4169   return TRUE;
4170 }
4171
4172 static void
4173 bin_query_position_done (GstBin * bin, QueryFold * fold)
4174 {
4175   GstFormat format;
4176
4177   gst_query_parse_position (fold->query, &format, NULL);
4178   /* store max in query result */
4179   gst_query_set_position (fold->query, format, fold->max);
4180
4181   GST_DEBUG_OBJECT (bin, "max position %" G_GINT64_FORMAT, fold->max);
4182 }
4183
4184 static gboolean
4185 bin_query_latency_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4186 {
4187   gboolean res = FALSE;
4188   GstObject *item = g_value_get_object (vitem);
4189   if (GST_IS_PAD (item))
4190     res = gst_pad_query (GST_PAD (item), fold->query);
4191   else
4192     res = gst_element_query (GST_ELEMENT (item), fold->query);
4193   if (res) {
4194     GstClockTime min, max;
4195     gboolean live;
4196
4197     gst_query_parse_latency (fold->query, &live, &min, &max);
4198
4199     GST_DEBUG_OBJECT (item,
4200         "got latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
4201         ", live %d", GST_TIME_ARGS (min), GST_TIME_ARGS (max), live);
4202
4203     /* for the combined latency we collect the MAX of all min latencies and
4204      * the MIN of all max latencies */
4205     if (live) {
4206       if (min > fold->min)
4207         fold->min = min;
4208       if (fold->max == -1)
4209         fold->max = max;
4210       else if (max < fold->max)
4211         fold->max = max;
4212       if (!fold->live)
4213         fold->live = live;
4214     }
4215   } else {
4216     g_value_set_boolean (ret, FALSE);
4217     GST_DEBUG_OBJECT (item, "failed query");
4218   }
4219
4220   return TRUE;
4221 }
4222
4223 static void
4224 bin_query_latency_done (GstBin * bin, QueryFold * fold)
4225 {
4226   /* store max in query result */
4227   gst_query_set_latency (fold->query, fold->live, fold->min, fold->max);
4228
4229   GST_DEBUG_OBJECT (bin,
4230       "latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
4231       ", live %d", GST_TIME_ARGS (fold->min), GST_TIME_ARGS (fold->max),
4232       fold->live);
4233 }
4234
4235 /* generic fold, return first valid result */
4236 static gboolean
4237 bin_query_generic_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4238 {
4239   gboolean res = FALSE;
4240   GstObject *item = g_value_get_object (vitem);
4241   if (GST_IS_PAD (item))
4242     res = gst_pad_query (GST_PAD (item), fold->query);
4243   else
4244     res = gst_element_query (GST_ELEMENT (item), fold->query);
4245   if (res) {
4246     g_value_set_boolean (ret, TRUE);
4247     GST_DEBUG_OBJECT (item, "answered query %p", fold->query);
4248   }
4249
4250   /* and stop as soon as we have a valid result */
4251   return !res;
4252 }
4253
4254 /* Perform a query iteration for the given bin. The query is stored in
4255  * QueryFold and iter should be either a GstPad iterator or a
4256  * GstElement iterator. */
4257 static gboolean
4258 bin_iterate_fold (GstBin * bin, GstIterator * iter, QueryInitFunction fold_init,
4259     QueryDoneFunction fold_done, GstIteratorFoldFunction fold_func,
4260     QueryFold * fold_data, gboolean default_return)
4261 {
4262   gboolean res = default_return;
4263   GValue ret = { 0 };
4264   /* set the result of the query to FALSE initially */
4265   g_value_init (&ret, G_TYPE_BOOLEAN);
4266   g_value_set_boolean (&ret, res);
4267
4268   while (TRUE) {
4269     GstIteratorResult ires;
4270
4271     ires = gst_iterator_fold (iter, fold_func, &ret, fold_data);
4272
4273     switch (ires) {
4274       case GST_ITERATOR_RESYNC:
4275         gst_iterator_resync (iter);
4276         if (fold_init)
4277           fold_init (bin, fold_data);
4278         g_value_set_boolean (&ret, res);
4279         break;
4280       case GST_ITERATOR_OK:
4281       case GST_ITERATOR_DONE:
4282         res = g_value_get_boolean (&ret);
4283         if (fold_done != NULL && res)
4284           fold_done (bin, fold_data);
4285         goto done;
4286       default:
4287         res = FALSE;
4288         goto done;
4289     }
4290   }
4291 done:
4292   return res;
4293 }
4294
4295 static gboolean
4296 gst_bin_query (GstElement * element, GstQuery * query)
4297 {
4298   GstBin *bin = GST_BIN_CAST (element);
4299   GstIterator *iter;
4300   gboolean default_return = FALSE;
4301   gboolean res = FALSE;
4302   gboolean src_pads_query_result = FALSE;
4303   GstIteratorFoldFunction fold_func;
4304   QueryInitFunction fold_init = NULL;
4305   QueryDoneFunction fold_done = NULL;
4306   QueryFold fold_data;
4307
4308   switch (GST_QUERY_TYPE (query)) {
4309     case GST_QUERY_DURATION:
4310     {
4311       /* FIXME: implement duration caching in GstBin again */
4312 #if 0
4313       GList *cached;
4314       GstFormat qformat;
4315
4316       gst_query_parse_duration (query, &qformat, NULL);
4317
4318       /* find cached duration query */
4319       GST_OBJECT_LOCK (bin);
4320       for (cached = bin->messages; cached; cached = g_list_next (cached)) {
4321         GstMessage *message = (GstMessage *) cached->data;
4322
4323         if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_DURATION_CHANGED &&
4324             GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (bin)) {
4325           GstFormat format;
4326           gint64 duration;
4327
4328           gst_message_parse_duration (message, &format, &duration);
4329
4330           /* if cached same format, copy duration in query result */
4331           if (format == qformat) {
4332             GST_DEBUG_OBJECT (bin, "return cached duration %" G_GINT64_FORMAT,
4333                 duration);
4334             GST_OBJECT_UNLOCK (bin);
4335
4336             gst_query_set_duration (query, qformat, duration);
4337             res = TRUE;
4338             goto exit;
4339           }
4340         }
4341       }
4342       GST_OBJECT_UNLOCK (bin);
4343 #else
4344       GST_FIXME ("implement duration caching in GstBin again");
4345 #endif
4346       /* no cached value found, iterate and collect durations */
4347       fold_func = (GstIteratorFoldFunction) bin_query_duration_fold;
4348       fold_init = bin_query_min_max_init;
4349       fold_done = bin_query_duration_done;
4350       break;
4351     }
4352     case GST_QUERY_POSITION:
4353     {
4354       fold_func = (GstIteratorFoldFunction) bin_query_position_fold;
4355       fold_init = bin_query_min_max_init;
4356       fold_done = bin_query_position_done;
4357       break;
4358     }
4359     case GST_QUERY_LATENCY:
4360     {
4361       fold_func = (GstIteratorFoldFunction) bin_query_latency_fold;
4362       fold_init = bin_query_min_max_init;
4363       fold_done = bin_query_latency_done;
4364       default_return = TRUE;
4365       break;
4366     }
4367     default:
4368       fold_func = (GstIteratorFoldFunction) bin_query_generic_fold;
4369       break;
4370   }
4371
4372   fold_data.query = query;
4373
4374   iter = gst_bin_iterate_sinks (bin);
4375   GST_DEBUG_OBJECT (bin, "Sending query %p (type %s) to sink children",
4376       query, GST_QUERY_TYPE_NAME (query));
4377
4378   if (fold_init)
4379     fold_init (bin, &fold_data);
4380
4381   res =
4382       bin_iterate_fold (bin, iter, fold_init, fold_done, fold_func, &fold_data,
4383       default_return);
4384   gst_iterator_free (iter);
4385
4386   if (!res) {
4387     /* Query the source pads of the element */
4388     iter = gst_element_iterate_src_pads (element);
4389     src_pads_query_result =
4390         bin_iterate_fold (bin, iter, fold_init, fold_done, fold_func,
4391         &fold_data, default_return);
4392     gst_iterator_free (iter);
4393
4394     if (src_pads_query_result)
4395       res = TRUE;
4396   }
4397
4398   GST_DEBUG_OBJECT (bin, "query %p result %d", query, res);
4399
4400   return res;
4401 }
4402
4403 static void
4404 set_context (const GValue * item, gpointer user_data)
4405 {
4406   GstElement *element = g_value_get_object (item);
4407
4408   gst_element_set_context (element, user_data);
4409 }
4410
4411 static void
4412 gst_bin_set_context (GstElement * element, GstContext * context)
4413 {
4414   GstBin *bin;
4415   GstIterator *children;
4416
4417   g_return_if_fail (GST_IS_BIN (element));
4418
4419   bin = GST_BIN (element);
4420
4421   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
4422
4423   children = gst_bin_iterate_elements (bin);
4424   while (gst_iterator_foreach (children, set_context,
4425           context) == GST_ITERATOR_RESYNC)
4426     gst_iterator_resync (children);
4427   gst_iterator_free (children);
4428 }
4429
4430 static gint
4431 compare_name (const GValue * velement, const gchar * name)
4432 {
4433   gint eq;
4434   GstElement *element = g_value_get_object (velement);
4435
4436   GST_OBJECT_LOCK (element);
4437   eq = strcmp (GST_ELEMENT_NAME (element), name);
4438   GST_OBJECT_UNLOCK (element);
4439
4440   return eq;
4441 }
4442
4443 /**
4444  * gst_bin_get_by_name:
4445  * @bin: a #GstBin
4446  * @name: the element name to search for
4447  *
4448  * Gets the element with the given name from a bin. This
4449  * function recurses into child bins.
4450  *
4451  * Returns %NULL if no element with the given name is found in the bin.
4452  *
4453  * MT safe.  Caller owns returned reference.
4454  *
4455  * Returns: (transfer full) (nullable): the #GstElement with the given
4456  * name, or %NULL
4457  */
4458 GstElement *
4459 gst_bin_get_by_name (GstBin * bin, const gchar * name)
4460 {
4461   GstIterator *children;
4462   GValue result = { 0, };
4463   GstElement *element;
4464   gboolean found;
4465
4466   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4467
4468   GST_CAT_INFO (GST_CAT_PARENTAGE, "[%s]: looking up child element %s",
4469       GST_ELEMENT_NAME (bin), name);
4470
4471   children = gst_bin_iterate_recurse (bin);
4472   found = gst_iterator_find_custom (children,
4473       (GCompareFunc) compare_name, &result, (gpointer) name);
4474   gst_iterator_free (children);
4475
4476   if (found) {
4477     element = g_value_dup_object (&result);
4478     g_value_unset (&result);
4479   } else {
4480     element = NULL;
4481   }
4482
4483   return element;
4484 }
4485
4486 /**
4487  * gst_bin_get_by_name_recurse_up:
4488  * @bin: a #GstBin
4489  * @name: the element name to search for
4490  *
4491  * Gets the element with the given name from this bin. If the
4492  * element is not found, a recursion is performed on the parent bin.
4493  *
4494  * Returns %NULL if:
4495  * - no element with the given name is found in the bin
4496  *
4497  * MT safe.  Caller owns returned reference.
4498  *
4499  * Returns: (transfer full) (nullable): the #GstElement with the given
4500  * name, or %NULL
4501  */
4502 GstElement *
4503 gst_bin_get_by_name_recurse_up (GstBin * bin, const gchar * name)
4504 {
4505   GstElement *result;
4506
4507   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4508   g_return_val_if_fail (name != NULL, NULL);
4509
4510   result = gst_bin_get_by_name (bin, name);
4511
4512   if (!result) {
4513     GstObject *parent;
4514
4515     parent = gst_object_get_parent (GST_OBJECT_CAST (bin));
4516     if (parent) {
4517       if (GST_IS_BIN (parent)) {
4518         result = gst_bin_get_by_name_recurse_up (GST_BIN_CAST (parent), name);
4519       }
4520       gst_object_unref (parent);
4521     }
4522   }
4523
4524   return result;
4525 }
4526
4527 static gint
4528 compare_interface (const GValue * velement, GValue * interface)
4529 {
4530   GstElement *element = g_value_get_object (velement);
4531   GType interface_type = (GType) g_value_get_pointer (interface);
4532   gint ret;
4533
4534   if (G_TYPE_CHECK_INSTANCE_TYPE (element, interface_type)) {
4535     ret = 0;
4536   } else {
4537     ret = 1;
4538   }
4539   return ret;
4540 }
4541
4542 /**
4543  * gst_bin_get_by_interface:
4544  * @bin: a #GstBin
4545  * @iface: the #GType of an interface
4546  *
4547  * Looks for an element inside the bin that implements the given
4548  * interface. If such an element is found, it returns the element.
4549  * You can cast this element to the given interface afterwards.  If you want
4550  * all elements that implement the interface, use
4551  * gst_bin_iterate_all_by_interface(). This function recurses into child bins.
4552  *
4553  * MT safe.  Caller owns returned reference.
4554  *
4555  * Returns: (transfer full): A #GstElement inside the bin implementing the interface
4556  */
4557 GstElement *
4558 gst_bin_get_by_interface (GstBin * bin, GType iface)
4559 {
4560   GstIterator *children;
4561   GValue result = { 0, };
4562   GstElement *element;
4563   gboolean found;
4564   GValue viface = { 0, };
4565
4566   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4567   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface), NULL);
4568
4569   g_value_init (&viface, G_TYPE_POINTER);
4570   g_value_set_pointer (&viface, (gpointer) iface);
4571
4572   children = gst_bin_iterate_recurse (bin);
4573   found = gst_iterator_find_custom (children, (GCompareFunc) compare_interface,
4574       &result, &viface);
4575   gst_iterator_free (children);
4576
4577   if (found) {
4578     element = g_value_dup_object (&result);
4579     g_value_unset (&result);
4580   } else {
4581     element = NULL;
4582   }
4583   g_value_unset (&viface);
4584
4585   return element;
4586 }
4587
4588 /**
4589  * gst_bin_iterate_all_by_interface:
4590  * @bin: a #GstBin
4591  * @iface: the #GType of an interface
4592  *
4593  * Looks for all elements inside the bin that implements the given
4594  * interface. You can safely cast all returned elements to the given interface.
4595  * The function recurses inside child bins. The iterator will yield a series
4596  * of #GstElement that should be unreffed after use.
4597  *
4598  * MT safe.  Caller owns returned value.
4599  *
4600  * Returns: (transfer full) (nullable): a #GstIterator of #GstElement
4601  *     for all elements in the bin implementing the given interface,
4602  *     or %NULL
4603  */
4604 GstIterator *
4605 gst_bin_iterate_all_by_interface (GstBin * bin, GType iface)
4606 {
4607   GstIterator *children;
4608   GstIterator *result;
4609   GValue viface = { 0, };
4610
4611   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4612   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface), NULL);
4613
4614   g_value_init (&viface, G_TYPE_POINTER);
4615   g_value_set_pointer (&viface, (gpointer) iface);
4616
4617   children = gst_bin_iterate_recurse (bin);
4618   result = gst_iterator_filter (children, (GCompareFunc) compare_interface,
4619       &viface);
4620
4621   g_value_unset (&viface);
4622
4623   return result;
4624 }