bin: Also don't *unset* element flags if they're in the suppressed flags
[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 gst_bin_sort_iterator_copy (const GstBinSortIterator * it,
2139     GstBinSortIterator * copy)
2140 {
2141   GHashTableIter iter;
2142   gpointer key, value;
2143
2144   copy->queue = it->queue;
2145   g_queue_foreach (&copy->queue, (GFunc) gst_object_ref, NULL);
2146
2147   copy->bin = gst_object_ref (it->bin);
2148   if (it->best)
2149     copy->best = gst_object_ref (it->best);
2150
2151   copy->hash = g_hash_table_new (NULL, NULL);
2152   g_hash_table_iter_init (&iter, it->hash);
2153   while (g_hash_table_iter_next (&iter, &key, &value))
2154     g_hash_table_insert (copy->hash, key, value);
2155 }
2156
2157 /* we add and subtract 1 to make sure we don't confuse NULL and 0 */
2158 #define HASH_SET_DEGREE(bit, elem, deg) \
2159     g_hash_table_replace (bit->hash, elem, GINT_TO_POINTER(deg+1))
2160 #define HASH_GET_DEGREE(bit, elem) \
2161     (GPOINTER_TO_INT(g_hash_table_lookup (bit->hash, elem))-1)
2162
2163 /* add element to queue of next elements in the iterator.
2164  * We push at the tail to give higher priority elements a
2165  * chance first */
2166 static void
2167 add_to_queue (GstBinSortIterator * bit, GstElement * element)
2168 {
2169   GST_DEBUG_OBJECT (bit->bin, "adding '%s' to queue",
2170       GST_ELEMENT_NAME (element));
2171   gst_object_ref (element);
2172   g_queue_push_tail (&bit->queue, element);
2173   HASH_SET_DEGREE (bit, element, -1);
2174 }
2175
2176 static void
2177 remove_from_queue (GstBinSortIterator * bit, GstElement * element)
2178 {
2179   GList *find;
2180
2181   if ((find = g_queue_find (&bit->queue, element))) {
2182     GST_DEBUG_OBJECT (bit->bin, "removing '%s' from queue",
2183         GST_ELEMENT_NAME (element));
2184
2185     g_queue_delete_link (&bit->queue, find);
2186     gst_object_unref (element);
2187   } else {
2188     GST_DEBUG_OBJECT (bit->bin, "unable to remove '%s' from queue",
2189         GST_ELEMENT_NAME (element));
2190   }
2191 }
2192
2193 /* clear the queue, unref all objects as we took a ref when
2194  * we added them to the queue */
2195 static void
2196 clear_queue (GQueue * queue)
2197 {
2198   gpointer p;
2199
2200   while ((p = g_queue_pop_head (queue)))
2201     gst_object_unref (p);
2202 }
2203
2204 /* set all degrees to 0. Elements marked as a sink are
2205  * added to the queue immediately. Since we only look at the SINK flag of the
2206  * element, it is possible that we add non-sinks to the queue. These will be
2207  * removed from the queue again when we can prove that it provides data for some
2208  * other element. */
2209 static void
2210 reset_degree (GstElement * element, GstBinSortIterator * bit)
2211 {
2212   gboolean is_sink;
2213
2214   /* sinks are added right away */
2215   GST_OBJECT_LOCK (element);
2216   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_FLAG_SINK);
2217   GST_OBJECT_UNLOCK (element);
2218
2219   if (is_sink) {
2220     add_to_queue (bit, element);
2221   } else {
2222     /* others are marked with 0 and handled when sinks are done */
2223     HASH_SET_DEGREE (bit, element, 0);
2224   }
2225 }
2226
2227 /* adjust the degree of all elements connected to the given
2228  * element. If a degree of an element drops to 0, it is
2229  * added to the queue of elements to schedule next.
2230  *
2231  * We have to make sure not to cross the bin boundary this element
2232  * belongs to.
2233  */
2234 static void
2235 update_degree (GstElement * element, GstBinSortIterator * bit)
2236 {
2237   gboolean linked = FALSE;
2238
2239   GST_OBJECT_LOCK (element);
2240   /* don't touch degree if element has no sinkpads */
2241   if (element->numsinkpads != 0) {
2242     /* loop over all sinkpads, decrement degree for all connected
2243      * elements in this bin */
2244     GList *pads;
2245
2246     for (pads = element->sinkpads; pads; pads = g_list_next (pads)) {
2247       GstPad *pad, *peer;
2248
2249       pad = GST_PAD_CAST (pads->data);
2250
2251       /* we're iterating over the sinkpads, check if it's busy in a link/unlink */
2252       if (G_UNLIKELY (find_message (bit->bin, GST_OBJECT_CAST (pad),
2253                   GST_MESSAGE_STRUCTURE_CHANGE))) {
2254         /* mark the iterator as dirty because we won't be updating the degree
2255          * of the peer parent now. This would result in the 'loop detected'
2256          * later on because the peer parent element could become the best next
2257          * element with a degree > 0. We will simply continue our state
2258          * changes and we'll eventually resync when the unlink completed and
2259          * the iterator cookie is updated. */
2260         bit->dirty = TRUE;
2261         continue;
2262       }
2263
2264       if ((peer = gst_pad_get_peer (pad))) {
2265         GstElement *peer_element;
2266
2267         if ((peer_element = gst_pad_get_parent_element (peer))) {
2268           GST_OBJECT_LOCK (peer_element);
2269           /* check that we don't go outside of this bin */
2270           if (GST_OBJECT_CAST (peer_element)->parent ==
2271               GST_OBJECT_CAST (bit->bin)) {
2272             gint old_deg, new_deg;
2273
2274             old_deg = HASH_GET_DEGREE (bit, peer_element);
2275
2276             /* check to see if we added an element as sink that was not really a
2277              * sink because it was connected to some other element. */
2278             if (old_deg == -1) {
2279               remove_from_queue (bit, peer_element);
2280               old_deg = 0;
2281             }
2282             new_deg = old_deg + bit->mode;
2283
2284             GST_DEBUG_OBJECT (bit->bin,
2285                 "change element %s, degree %d->%d, linked to %s",
2286                 GST_ELEMENT_NAME (peer_element), old_deg, new_deg,
2287                 GST_ELEMENT_NAME (element));
2288
2289             /* update degree, it is possible that an element was in 0 and
2290              * reaches -1 here. This would mean that the element had no sinkpads
2291              * but became linked while the state change was happening. We will
2292              * resync on this with the structure change message. */
2293             if (new_deg == 0) {
2294               /* degree hit 0, add to queue */
2295               add_to_queue (bit, peer_element);
2296             } else {
2297               HASH_SET_DEGREE (bit, peer_element, new_deg);
2298             }
2299             linked = TRUE;
2300           }
2301           GST_OBJECT_UNLOCK (peer_element);
2302           gst_object_unref (peer_element);
2303         }
2304         gst_object_unref (peer);
2305       }
2306     }
2307   }
2308   if (!linked) {
2309     GST_DEBUG_OBJECT (bit->bin, "element %s not linked on any sinkpads",
2310         GST_ELEMENT_NAME (element));
2311   }
2312   GST_OBJECT_UNLOCK (element);
2313 }
2314
2315 /* find the next best element not handled yet. This is the one
2316  * with the lowest non-negative degree */
2317 static void
2318 find_element (GstElement * element, GstBinSortIterator * bit)
2319 {
2320   gint degree;
2321
2322   /* element is already handled */
2323   if ((degree = HASH_GET_DEGREE (bit, element)) < 0)
2324     return;
2325
2326   /* first element or element with smaller degree */
2327   if (bit->best == NULL || bit->best_deg > degree) {
2328     bit->best = element;
2329     bit->best_deg = degree;
2330   }
2331 }
2332
2333 /* get next element in iterator. */
2334 static GstIteratorResult
2335 gst_bin_sort_iterator_next (GstBinSortIterator * bit, GValue * result)
2336 {
2337   GstElement *best;
2338   GstBin *bin = bit->bin;
2339
2340   /* empty queue, we have to find a next best element */
2341   if (g_queue_is_empty (&bit->queue)) {
2342     bit->best = NULL;
2343     bit->best_deg = G_MAXINT;
2344     g_list_foreach (bin->children, (GFunc) find_element, bit);
2345     if ((best = bit->best)) {
2346       /* when we detected an unlink, don't warn because our degrees might be
2347        * screwed up. We will resync later */
2348       if (bit->best_deg != 0 && !bit->dirty) {
2349         /* we don't fail on this one yet */
2350         GST_WARNING_OBJECT (bin, "loop dected in graph");
2351         g_warning ("loop detected in the graph of bin '%s'!!",
2352             GST_ELEMENT_NAME (bin));
2353       }
2354       /* best unhandled element, schedule as next element */
2355       GST_DEBUG_OBJECT (bin, "queue empty, next best: %s",
2356           GST_ELEMENT_NAME (best));
2357       HASH_SET_DEGREE (bit, best, -1);
2358       g_value_set_object (result, best);
2359     } else {
2360       GST_DEBUG_OBJECT (bin, "queue empty, elements exhausted");
2361       /* no more unhandled elements, we are done */
2362       return GST_ITERATOR_DONE;
2363     }
2364   } else {
2365     /* everything added to the queue got reffed */
2366     best = g_queue_pop_head (&bit->queue);
2367     g_value_set_object (result, best);
2368     gst_object_unref (best);
2369   }
2370
2371   GST_DEBUG_OBJECT (bin, "queue head gives %s", GST_ELEMENT_NAME (best));
2372   /* update degrees of linked elements */
2373   update_degree (best, bit);
2374
2375   return GST_ITERATOR_OK;
2376 }
2377
2378 /* clear queues, recalculate the degrees and restart. */
2379 static void
2380 gst_bin_sort_iterator_resync (GstBinSortIterator * bit)
2381 {
2382   GstBin *bin = bit->bin;
2383
2384   GST_DEBUG_OBJECT (bin, "resync");
2385   bit->dirty = FALSE;
2386   clear_queue (&bit->queue);
2387   /* reset degrees */
2388   g_list_foreach (bin->children, (GFunc) reset_degree, bit);
2389   /* calc degrees, incrementing */
2390   bit->mode = 1;
2391   g_list_foreach (bin->children, (GFunc) update_degree, bit);
2392   /* for the rest of the function we decrement the degrees */
2393   bit->mode = -1;
2394 }
2395
2396 /* clear queues, unref bin and free iterator. */
2397 static void
2398 gst_bin_sort_iterator_free (GstBinSortIterator * bit)
2399 {
2400   GstBin *bin = bit->bin;
2401
2402   GST_DEBUG_OBJECT (bin, "free");
2403   clear_queue (&bit->queue);
2404   g_hash_table_destroy (bit->hash);
2405   gst_object_unref (bin);
2406 }
2407
2408 /* should be called with the bin LOCK held */
2409 static GstIterator *
2410 gst_bin_sort_iterator_new (GstBin * bin)
2411 {
2412   GstBinSortIterator *result;
2413
2414   /* we don't need an ItemFunction because we ref the items in the _next
2415    * method already */
2416   result = (GstBinSortIterator *)
2417       gst_iterator_new (sizeof (GstBinSortIterator),
2418       GST_TYPE_ELEMENT,
2419       GST_OBJECT_GET_LOCK (bin),
2420       &bin->priv->structure_cookie,
2421       (GstIteratorCopyFunction) gst_bin_sort_iterator_copy,
2422       (GstIteratorNextFunction) gst_bin_sort_iterator_next,
2423       (GstIteratorItemFunction) NULL,
2424       (GstIteratorResyncFunction) gst_bin_sort_iterator_resync,
2425       (GstIteratorFreeFunction) gst_bin_sort_iterator_free);
2426   g_queue_init (&result->queue);
2427   result->hash = g_hash_table_new (NULL, NULL);
2428   gst_object_ref (bin);
2429   result->bin = bin;
2430   gst_bin_sort_iterator_resync (result);
2431
2432   return (GstIterator *) result;
2433 }
2434
2435 /**
2436  * gst_bin_iterate_sorted:
2437  * @bin: a #GstBin
2438  *
2439  * Gets an iterator for the elements in this bin in topologically
2440  * sorted order. This means that the elements are returned from
2441  * the most downstream elements (sinks) to the sources.
2442  *
2443  * This function is used internally to perform the state changes
2444  * of the bin elements and for clock selection.
2445  *
2446  * MT safe.  Caller owns returned value.
2447  *
2448  * Returns: (transfer full) (nullable): a #GstIterator of #GstElement,
2449  * or %NULL
2450  */
2451 GstIterator *
2452 gst_bin_iterate_sorted (GstBin * bin)
2453 {
2454   GstIterator *result;
2455
2456   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
2457
2458   GST_OBJECT_LOCK (bin);
2459   result = gst_bin_sort_iterator_new (bin);
2460   GST_OBJECT_UNLOCK (bin);
2461
2462   return result;
2463 }
2464
2465 static GstStateChangeReturn
2466 gst_bin_element_set_state (GstBin * bin, GstElement * element,
2467     GstClockTime base_time, GstClockTime start_time, GstState current,
2468     GstState next)
2469 {
2470   GstStateChangeReturn ret;
2471   GstState child_current, child_pending;
2472   gboolean locked;
2473   GList *found;
2474
2475   GST_STATE_LOCK (element);
2476
2477   GST_OBJECT_LOCK (element);
2478   /* set base_time and start time on child */
2479   GST_ELEMENT_START_TIME (element) = start_time;
2480   element->base_time = base_time;
2481   /* peel off the locked flag */
2482   locked = GST_ELEMENT_IS_LOCKED_STATE (element);
2483   /* Get the previous set_state result to preserve NO_PREROLL and ASYNC */
2484   ret = GST_STATE_RETURN (element);
2485   child_current = GST_STATE (element);
2486   child_pending = GST_STATE_PENDING (element);
2487   GST_OBJECT_UNLOCK (element);
2488
2489   /* skip locked elements */
2490   if (G_UNLIKELY (locked))
2491     goto locked;
2492
2493   /* if the element was no preroll, just start changing the state regardless
2494    * if it had async elements (in the case of a bin) because they won't preroll
2495    * anyway. */
2496   if (G_UNLIKELY (ret == GST_STATE_CHANGE_NO_PREROLL)) {
2497     GST_DEBUG_OBJECT (element, "element is NO_PREROLL, ignore async elements");
2498     goto no_preroll;
2499   }
2500
2501   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2502       "current %s pending %s, desired next %s",
2503       gst_element_state_get_name (child_current),
2504       gst_element_state_get_name (child_pending),
2505       gst_element_state_get_name (next));
2506
2507   /* always recurse into bins so that we can set the base time */
2508   if (GST_IS_BIN (element))
2509     goto do_state;
2510
2511   /* Try not to change the state of elements that are already in the state we're
2512    * going to */
2513   if (child_current == next && child_pending == GST_STATE_VOID_PENDING) {
2514     /* child is already at the requested state, return previous return. Note that
2515      * if the child has a pending state to next, we will still call the
2516      * set_state function */
2517     goto unneeded;
2518   } else if (next > current) {
2519     /* upward state change */
2520     if (child_pending == GST_STATE_VOID_PENDING) {
2521       /* .. and the child is not busy doing anything */
2522       if (child_current > next) {
2523         /* .. and is already past the requested state, assume it got there
2524          * without error */
2525         ret = GST_STATE_CHANGE_SUCCESS;
2526         goto unneeded;
2527       }
2528     } else if (child_pending > child_current) {
2529       /* .. and the child is busy going upwards */
2530       if (child_current >= next) {
2531         /* .. and is already past the requested state, assume it got there
2532          * without error */
2533         ret = GST_STATE_CHANGE_SUCCESS;
2534         goto unneeded;
2535       }
2536     } else {
2537       /* .. and the child is busy going downwards */
2538       if (child_current > next) {
2539         /* .. and is already past the requested state, assume it got there
2540          * without error */
2541         ret = GST_STATE_CHANGE_SUCCESS;
2542         goto unneeded;
2543       }
2544     }
2545   } else if (next < current) {
2546     /* downward state change */
2547     if (child_pending == GST_STATE_VOID_PENDING) {
2548       /* .. and the child is not busy doing anything */
2549       if (child_current < next) {
2550         /* .. and is already past the requested state, assume it got there
2551          * without error */
2552         ret = GST_STATE_CHANGE_SUCCESS;
2553         goto unneeded;
2554       }
2555     } else if (child_pending < child_current) {
2556       /* .. and the child is busy going downwards */
2557       if (child_current <= next) {
2558         /* .. and is already past the requested state, assume it got there
2559          * without error */
2560         ret = GST_STATE_CHANGE_SUCCESS;
2561         goto unneeded;
2562       }
2563     } else {
2564       /* .. and the child is busy going upwards */
2565       if (child_current < next) {
2566         /* .. and is already past the requested state, assume it got there
2567          * without error */
2568         ret = GST_STATE_CHANGE_SUCCESS;
2569         goto unneeded;
2570       }
2571     }
2572   }
2573
2574 do_state:
2575   GST_OBJECT_LOCK (bin);
2576   /* the element was busy with an upwards async state change, we must wait for
2577    * an ASYNC_DONE message before we attemp to change the state. */
2578   if ((found =
2579           find_message (bin, GST_OBJECT_CAST (element),
2580               GST_MESSAGE_ASYNC_START))) {
2581 #ifndef GST_DISABLE_GST_DEBUG
2582     GstMessage *message = GST_MESSAGE_CAST (found->data);
2583
2584     GST_DEBUG_OBJECT (element, "element message %p, %s async busy",
2585         message, GST_ELEMENT_NAME (GST_MESSAGE_SRC (message)));
2586 #endif
2587     /* only wait for upward state changes */
2588     if (next > current) {
2589       /* We found an async element check if we can force its state to change or
2590        * if we have to wait for it to preroll. */
2591       goto was_busy;
2592     }
2593   }
2594   GST_OBJECT_UNLOCK (bin);
2595
2596 no_preroll:
2597   GST_DEBUG_OBJECT (bin,
2598       "setting element %s to %s, base_time %" GST_TIME_FORMAT,
2599       GST_ELEMENT_NAME (element), gst_element_state_get_name (next),
2600       GST_TIME_ARGS (base_time));
2601
2602   /* change state */
2603   ret = gst_element_set_state (element, next);
2604
2605   GST_STATE_UNLOCK (element);
2606
2607   return ret;
2608
2609 locked:
2610   {
2611     GST_DEBUG_OBJECT (element,
2612         "element is locked, return previous return %s",
2613         gst_element_state_change_return_get_name (ret));
2614     GST_STATE_UNLOCK (element);
2615     return ret;
2616   }
2617 unneeded:
2618   {
2619     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2620         "skipping transition from %s to  %s",
2621         gst_element_state_get_name (child_current),
2622         gst_element_state_get_name (next));
2623     GST_STATE_UNLOCK (element);
2624     return ret;
2625   }
2626 was_busy:
2627   {
2628     GST_DEBUG_OBJECT (element, "element was busy, delaying state change");
2629     GST_OBJECT_UNLOCK (bin);
2630     GST_STATE_UNLOCK (element);
2631     return GST_STATE_CHANGE_ASYNC;
2632   }
2633 }
2634
2635 /* gst_iterator_fold functions for pads_activate
2636  * Stop the iterator if activating one pad failed, but only if that pad
2637  * has not been removed from the element. */
2638 static gboolean
2639 activate_pads (const GValue * vpad, GValue * ret, gboolean * active)
2640 {
2641   GstPad *pad = g_value_get_object (vpad);
2642   gboolean cont = TRUE;
2643
2644   if (!gst_pad_set_active (pad, *active)) {
2645     if (GST_PAD_PARENT (pad) != NULL) {
2646       cont = FALSE;
2647       g_value_set_boolean (ret, FALSE);
2648     }
2649   }
2650
2651   return cont;
2652 }
2653
2654 /* returns false on error or early cutout of the fold, true if all
2655  * pads in @iter were (de)activated successfully. */
2656 static gboolean
2657 iterator_activate_fold_with_resync (GstIterator * iter, gpointer user_data)
2658 {
2659   GstIteratorResult ires;
2660   GValue ret = { 0 };
2661
2662   /* no need to unset this later, it's just a boolean */
2663   g_value_init (&ret, G_TYPE_BOOLEAN);
2664   g_value_set_boolean (&ret, TRUE);
2665
2666   while (1) {
2667     ires = gst_iterator_fold (iter, (GstIteratorFoldFunction) activate_pads,
2668         &ret, user_data);
2669     switch (ires) {
2670       case GST_ITERATOR_RESYNC:
2671         /* need to reset the result again */
2672         g_value_set_boolean (&ret, TRUE);
2673         gst_iterator_resync (iter);
2674         break;
2675       case GST_ITERATOR_DONE:
2676         /* all pads iterated, return collected value */
2677         goto done;
2678       default:
2679         /* iterator returned _ERROR or premature end with _OK,
2680          * mark an error and exit */
2681         g_value_set_boolean (&ret, FALSE);
2682         goto done;
2683     }
2684   }
2685 done:
2686   /* return collected value */
2687   return g_value_get_boolean (&ret);
2688 }
2689
2690 /* is called with STATE_LOCK
2691  */
2692 static gboolean
2693 gst_bin_src_pads_activate (GstBin * bin, gboolean active)
2694 {
2695   GstIterator *iter;
2696   gboolean fold_ok;
2697
2698   GST_DEBUG_OBJECT (bin, "%s pads", active ? "activate" : "deactivate");
2699
2700   iter = gst_element_iterate_src_pads ((GstElement *) bin);
2701   fold_ok = iterator_activate_fold_with_resync (iter, &active);
2702   gst_iterator_free (iter);
2703   if (G_UNLIKELY (!fold_ok))
2704     goto failed;
2705
2706   GST_DEBUG_OBJECT (bin, "pad %sactivation successful", active ? "" : "de");
2707
2708   return TRUE;
2709
2710   /* ERRORS */
2711 failed:
2712   {
2713     GST_DEBUG_OBJECT (bin, "pad %sactivation failed", active ? "" : "de");
2714     return FALSE;
2715   }
2716 }
2717
2718 /**
2719  * gst_bin_recalculate_latency:
2720  * @bin: a #GstBin
2721  *
2722  * Query @bin for the current latency using and reconfigures this latency to all the
2723  * elements with a LATENCY event.
2724  *
2725  * This method is typically called on the pipeline when a #GST_MESSAGE_LATENCY
2726  * is posted on the bus.
2727  *
2728  * This function simply emits the 'do-latency' signal so any custom latency
2729  * calculations will be performed.
2730  *
2731  * Returns: %TRUE if the latency could be queried and reconfigured.
2732  */
2733 gboolean
2734 gst_bin_recalculate_latency (GstBin * bin)
2735 {
2736   gboolean res;
2737
2738   g_signal_emit (bin, gst_bin_signals[DO_LATENCY], 0, &res);
2739   GST_DEBUG_OBJECT (bin, "latency returned %d", res);
2740
2741   return res;
2742 }
2743
2744 static gboolean
2745 gst_bin_do_latency_func (GstBin * bin)
2746 {
2747   GstQuery *query;
2748   GstElement *element;
2749   GstClockTime min_latency, max_latency;
2750   gboolean res;
2751
2752   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
2753
2754   element = GST_ELEMENT_CAST (bin);
2755
2756   GST_DEBUG_OBJECT (element, "querying latency");
2757
2758   query = gst_query_new_latency ();
2759   if ((res = gst_element_query (element, query))) {
2760     gboolean live;
2761
2762     gst_query_parse_latency (query, &live, &min_latency, &max_latency);
2763
2764     GST_DEBUG_OBJECT (element,
2765         "got min latency %" GST_TIME_FORMAT ", max latency %"
2766         GST_TIME_FORMAT ", live %d", GST_TIME_ARGS (min_latency),
2767         GST_TIME_ARGS (max_latency), live);
2768
2769     if (max_latency < min_latency) {
2770       /* this is an impossible situation, some parts of the pipeline might not
2771        * work correctly. We post a warning for now. */
2772       GST_ELEMENT_WARNING (element, CORE, CLOCK, (NULL),
2773           ("Impossible to configure latency: max %" GST_TIME_FORMAT " < min %"
2774               GST_TIME_FORMAT ". Add queues or other buffering elements.",
2775               GST_TIME_ARGS (max_latency), GST_TIME_ARGS (min_latency)));
2776     }
2777
2778     /* configure latency on elements */
2779     res = gst_element_send_event (element, gst_event_new_latency (min_latency));
2780     if (res) {
2781       GST_INFO_OBJECT (element, "configured latency of %" GST_TIME_FORMAT,
2782           GST_TIME_ARGS (min_latency));
2783     } else {
2784       GST_WARNING_OBJECT (element,
2785           "did not really configure latency of %" GST_TIME_FORMAT,
2786           GST_TIME_ARGS (min_latency));
2787     }
2788   } else {
2789     /* this is not a real problem, we just don't configure any latency. */
2790     GST_WARNING_OBJECT (element, "failed to query latency");
2791   }
2792   gst_query_unref (query);
2793
2794   return res;
2795 }
2796
2797 static gboolean
2798 gst_bin_post_message (GstElement * element, GstMessage * msg)
2799 {
2800   GstElementClass *pklass = (GstElementClass *) parent_class;
2801   gboolean ret;
2802
2803   ret = pklass->post_message (element, gst_message_ref (msg));
2804
2805   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_STATE_CHANGED &&
2806       GST_MESSAGE_SRC (msg) == GST_OBJECT_CAST (element)) {
2807     GstState newstate, pending;
2808
2809     gst_message_parse_state_changed (msg, NULL, &newstate, &pending);
2810     if (newstate == GST_STATE_PLAYING && pending == GST_STATE_VOID_PENDING) {
2811       GST_BIN_CAST (element)->priv->posted_playing = TRUE;
2812       bin_do_eos (GST_BIN_CAST (element));
2813     } else {
2814       GST_BIN_CAST (element)->priv->posted_playing = FALSE;
2815     }
2816   }
2817
2818   gst_message_unref (msg);
2819
2820   return ret;
2821 }
2822
2823 static void
2824 reset_state (const GValue * data, gpointer user_data)
2825 {
2826   GstElement *e = g_value_get_object (data);
2827   GstState state = GPOINTER_TO_INT (user_data);
2828
2829   if (gst_element_set_state (e, state) == GST_STATE_CHANGE_FAILURE)
2830     GST_WARNING_OBJECT (e, "Failed to switch back down to %s",
2831         gst_element_state_get_name (state));
2832 }
2833
2834 static GstStateChangeReturn
2835 gst_bin_change_state_func (GstElement * element, GstStateChange transition)
2836 {
2837   GstBin *bin;
2838   GstStateChangeReturn ret;
2839   GstState current, next;
2840   gboolean have_async;
2841   gboolean have_no_preroll;
2842   GstClockTime base_time, start_time;
2843   GstIterator *it;
2844   gboolean done;
2845   GValue data = { 0, };
2846
2847   /* we don't need to take the STATE_LOCK, it is already taken */
2848   current = (GstState) GST_STATE_TRANSITION_CURRENT (transition);
2849   next = (GstState) GST_STATE_TRANSITION_NEXT (transition);
2850
2851   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2852       "changing state of children from %s to %s",
2853       gst_element_state_get_name (current), gst_element_state_get_name (next));
2854
2855   bin = GST_BIN_CAST (element);
2856
2857   switch (next) {
2858     case GST_STATE_PLAYING:
2859     {
2860       gboolean toplevel, asynchandling;
2861
2862       GST_OBJECT_LOCK (bin);
2863       toplevel = BIN_IS_TOPLEVEL (bin);
2864       asynchandling = bin->priv->asynchandling;
2865       GST_OBJECT_UNLOCK (bin);
2866
2867       if (toplevel)
2868         gst_bin_recalculate_latency (bin);
2869       if (asynchandling)
2870         gst_element_post_message (element,
2871             gst_message_new_latency (GST_OBJECT_CAST (element)));
2872       break;
2873     }
2874     case GST_STATE_PAUSED:
2875       /* Clear EOS list on next PAUSED */
2876       GST_OBJECT_LOCK (bin);
2877       GST_DEBUG_OBJECT (element, "clearing EOS elements");
2878       bin_remove_messages (bin, NULL, GST_MESSAGE_EOS);
2879       bin->priv->posted_eos = FALSE;
2880       if (current == GST_STATE_READY)
2881         bin_remove_messages (bin, NULL, GST_MESSAGE_STREAM_START);
2882       GST_OBJECT_UNLOCK (bin);
2883       if (current == GST_STATE_READY)
2884         if (!(gst_bin_src_pads_activate (bin, TRUE)))
2885           goto activate_failure;
2886       break;
2887     case GST_STATE_READY:
2888       /* Clear message list on next READY */
2889       GST_OBJECT_LOCK (bin);
2890       GST_DEBUG_OBJECT (element, "clearing all cached messages");
2891       bin_remove_messages (bin, NULL, GST_MESSAGE_ANY);
2892       GST_OBJECT_UNLOCK (bin);
2893       /* We might not have reached PAUSED yet due to async errors,
2894        * make sure to always deactivate the pads nonetheless */
2895       if (!(gst_bin_src_pads_activate (bin, FALSE)))
2896         goto activate_failure;
2897       break;
2898     case GST_STATE_NULL:
2899       /* Clear message list on next NULL */
2900       GST_OBJECT_LOCK (bin);
2901       GST_DEBUG_OBJECT (element, "clearing all cached messages");
2902       bin_remove_messages (bin, NULL, GST_MESSAGE_ANY);
2903       GST_OBJECT_UNLOCK (bin);
2904       if (current == GST_STATE_READY) {
2905         if (!(gst_bin_src_pads_activate (bin, FALSE)))
2906           goto activate_failure;
2907       }
2908       break;
2909     default:
2910       break;
2911   }
2912
2913   /* this flag is used to make the async state changes return immediately. We
2914    * don't want them to interfere with this state change */
2915   GST_OBJECT_LOCK (bin);
2916   bin->polling = TRUE;
2917   GST_OBJECT_UNLOCK (bin);
2918
2919   /* iterate in state change order */
2920   it = gst_bin_iterate_sorted (bin);
2921
2922   /* mark if we've seen an ASYNC element in the bin when we did a state change.
2923    * Note how we don't reset this value when a resync happens, the reason being
2924    * that the async element posted ASYNC_START and we want to post ASYNC_DONE
2925    * even after a resync when the async element is gone */
2926   have_async = FALSE;
2927
2928 restart:
2929   /* take base_time */
2930   base_time = gst_element_get_base_time (element);
2931   start_time = gst_element_get_start_time (element);
2932
2933   have_no_preroll = FALSE;
2934
2935   done = FALSE;
2936   while (!done) {
2937     switch (gst_iterator_next (it, &data)) {
2938       case GST_ITERATOR_OK:
2939       {
2940         GstElement *child;
2941
2942         child = g_value_get_object (&data);
2943
2944         /* set state and base_time now */
2945         ret = gst_bin_element_set_state (bin, child, base_time, start_time,
2946             current, next);
2947
2948         switch (ret) {
2949           case GST_STATE_CHANGE_SUCCESS:
2950             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2951                 "child '%s' changed state to %d(%s) successfully",
2952                 GST_ELEMENT_NAME (child), next,
2953                 gst_element_state_get_name (next));
2954             break;
2955           case GST_STATE_CHANGE_ASYNC:
2956           {
2957             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2958                 "child '%s' is changing state asynchronously to %s",
2959                 GST_ELEMENT_NAME (child), gst_element_state_get_name (next));
2960             have_async = TRUE;
2961             break;
2962           }
2963           case GST_STATE_CHANGE_FAILURE:{
2964             GstObject *parent;
2965
2966             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2967                 "child '%s' failed to go to state %d(%s)",
2968                 GST_ELEMENT_NAME (child),
2969                 next, gst_element_state_get_name (next));
2970
2971             /* Only fail if the child is still inside
2972              * this bin. It might've been removed already
2973              * because of the error by the bin subclass
2974              * to ignore the error.  */
2975             parent = gst_object_get_parent (GST_OBJECT_CAST (child));
2976             if (parent == GST_OBJECT_CAST (element)) {
2977               /* element is still in bin, really error now */
2978               gst_object_unref (parent);
2979               goto undo;
2980             }
2981             /* child removed from bin, let the resync code redo the state
2982              * change */
2983             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2984                 "child '%s' was removed from the bin",
2985                 GST_ELEMENT_NAME (child));
2986
2987             if (parent)
2988               gst_object_unref (parent);
2989
2990             break;
2991           }
2992           case GST_STATE_CHANGE_NO_PREROLL:
2993             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2994                 "child '%s' changed state to %d(%s) successfully without preroll",
2995                 GST_ELEMENT_NAME (child), next,
2996                 gst_element_state_get_name (next));
2997             have_no_preroll = TRUE;
2998             break;
2999           default:
3000             g_assert_not_reached ();
3001             break;
3002         }
3003         g_value_reset (&data);
3004         break;
3005       }
3006       case GST_ITERATOR_RESYNC:
3007         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "iterator doing resync");
3008         gst_iterator_resync (it);
3009         goto restart;
3010       default:
3011       case GST_ITERATOR_DONE:
3012         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "iterator done");
3013         done = TRUE;
3014         break;
3015     }
3016   }
3017
3018   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3019   if (G_UNLIKELY (ret == GST_STATE_CHANGE_FAILURE))
3020     goto done;
3021
3022   if (have_no_preroll) {
3023     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
3024         "we have NO_PREROLL elements %s -> NO_PREROLL",
3025         gst_element_state_change_return_get_name (ret));
3026     ret = GST_STATE_CHANGE_NO_PREROLL;
3027   } else if (have_async) {
3028     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
3029         "we have ASYNC elements %s -> ASYNC",
3030         gst_element_state_change_return_get_name (ret));
3031     ret = GST_STATE_CHANGE_ASYNC;
3032   }
3033
3034 done:
3035   g_value_unset (&data);
3036   gst_iterator_free (it);
3037
3038   GST_OBJECT_LOCK (bin);
3039   bin->polling = FALSE;
3040   /* it's possible that we did not get ASYNC from the children while the bin is
3041    * simulating ASYNC behaviour by posting an ASYNC_DONE message on the bus with
3042    * itself as the source. In that case we still want to check if the state
3043    * change completed. */
3044   if (ret != GST_STATE_CHANGE_ASYNC && !bin->priv->pending_async_done) {
3045     /* no element returned ASYNC and there are no pending async_done messages,
3046      * we can just complete. */
3047     GST_DEBUG_OBJECT (bin, "no async elements");
3048     goto state_end;
3049   }
3050   /* when we get here an ASYNC element was found */
3051   if (GST_STATE_TARGET (bin) <= GST_STATE_READY) {
3052     /* we ignore ASYNC state changes when we go to READY or NULL */
3053     GST_DEBUG_OBJECT (bin, "target state %s <= READY",
3054         gst_element_state_get_name (GST_STATE_TARGET (bin)));
3055     goto state_end;
3056   }
3057
3058   GST_DEBUG_OBJECT (bin, "check async elements");
3059   /* check if all elements managed to commit their state already */
3060   if (!find_message (bin, NULL, GST_MESSAGE_ASYNC_START)) {
3061     /* nothing found, remove all old ASYNC_DONE messages. This can happen when
3062      * all the elements commited their state while we were doing the state
3063      * change. We will still return ASYNC for consistency but we commit the
3064      * state already so that a _get_state() will return immediately. */
3065     bin_remove_messages (bin, NULL, GST_MESSAGE_ASYNC_DONE);
3066
3067     GST_DEBUG_OBJECT (bin, "async elements commited");
3068     bin_handle_async_done (bin, GST_STATE_CHANGE_SUCCESS, FALSE,
3069         GST_CLOCK_TIME_NONE);
3070   }
3071
3072 state_end:
3073   bin->priv->pending_async_done = FALSE;
3074   GST_OBJECT_UNLOCK (bin);
3075
3076   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
3077       "done changing bin's state from %s to %s, now in %s, ret %s",
3078       gst_element_state_get_name (current),
3079       gst_element_state_get_name (next),
3080       gst_element_state_get_name (GST_STATE (element)),
3081       gst_element_state_change_return_get_name (ret));
3082
3083   return ret;
3084
3085   /* ERRORS */
3086 activate_failure:
3087   {
3088     GST_CAT_WARNING_OBJECT (GST_CAT_STATES, element,
3089         "failure (de)activating src pads");
3090     return GST_STATE_CHANGE_FAILURE;
3091   }
3092
3093 undo:
3094   {
3095     if (current < next) {
3096       GstIterator *it = gst_bin_iterate_sorted (GST_BIN (element));
3097       GstIteratorResult ret;
3098
3099       GST_DEBUG_OBJECT (element,
3100           "Bin failed to change state, switching children back to %s",
3101           gst_element_state_get_name (current));
3102       do {
3103         ret =
3104             gst_iterator_foreach (it, &reset_state, GINT_TO_POINTER (current));
3105       } while (ret == GST_ITERATOR_RESYNC);
3106       gst_iterator_free (it);
3107     }
3108     goto done;
3109   }
3110 }
3111
3112 /*
3113  * This function is a utility event handler for seek events.
3114  * It will send the event to all sinks or sources and appropriate
3115  * ghost pads depending on the event-direction.
3116  *
3117  * Applications are free to override this behaviour and
3118  * implement their own seek handler, but this will work for
3119  * pretty much all cases in practice.
3120  */
3121 static gboolean
3122 gst_bin_send_event (GstElement * element, GstEvent * event)
3123 {
3124   GstBin *bin = GST_BIN_CAST (element);
3125   GstIterator *iter;
3126   gboolean res = TRUE;
3127   gboolean done = FALSE;
3128   GValue data = { 0, };
3129
3130   if (GST_EVENT_IS_DOWNSTREAM (event)) {
3131     iter = gst_bin_iterate_sources (bin);
3132     GST_DEBUG_OBJECT (bin, "Sending %s event to src children",
3133         GST_EVENT_TYPE_NAME (event));
3134   } else {
3135     iter = gst_bin_iterate_sinks (bin);
3136     GST_DEBUG_OBJECT (bin, "Sending %s event to sink children",
3137         GST_EVENT_TYPE_NAME (event));
3138   }
3139
3140   while (!done) {
3141     switch (gst_iterator_next (iter, &data)) {
3142       case GST_ITERATOR_OK:
3143       {
3144         GstElement *child = g_value_get_object (&data);
3145
3146         gst_event_ref (event);
3147         res &= gst_element_send_event (child, event);
3148
3149         GST_LOG_OBJECT (child, "After handling %s event: %d",
3150             GST_EVENT_TYPE_NAME (event), res);
3151
3152         g_value_reset (&data);
3153         break;
3154       }
3155       case GST_ITERATOR_RESYNC:
3156         gst_iterator_resync (iter);
3157         res = TRUE;
3158         break;
3159       case GST_ITERATOR_DONE:
3160         done = TRUE;
3161         break;
3162       case GST_ITERATOR_ERROR:
3163         g_assert_not_reached ();
3164         break;
3165     }
3166   }
3167   g_value_unset (&data);
3168   gst_iterator_free (iter);
3169
3170   if (GST_EVENT_IS_DOWNSTREAM (event)) {
3171     iter = gst_element_iterate_sink_pads (GST_ELEMENT (bin));
3172     GST_DEBUG_OBJECT (bin, "Sending %s event to sink pads",
3173         GST_EVENT_TYPE_NAME (event));
3174   } else {
3175     iter = gst_element_iterate_src_pads (GST_ELEMENT (bin));
3176     GST_DEBUG_OBJECT (bin, "Sending %s event to src pads",
3177         GST_EVENT_TYPE_NAME (event));
3178   }
3179
3180   done = FALSE;
3181   while (!done) {
3182     switch (gst_iterator_next (iter, &data)) {
3183       case GST_ITERATOR_OK:
3184       {
3185         GstPad *pad = g_value_get_object (&data);
3186
3187         gst_event_ref (event);
3188         res &= gst_pad_send_event (pad, event);
3189         GST_LOG_OBJECT (pad, "After handling %s event: %d",
3190             GST_EVENT_TYPE_NAME (event), res);
3191         break;
3192       }
3193       case GST_ITERATOR_RESYNC:
3194         gst_iterator_resync (iter);
3195         res = TRUE;
3196         break;
3197       case GST_ITERATOR_DONE:
3198         done = TRUE;
3199         break;
3200       case GST_ITERATOR_ERROR:
3201         g_assert_not_reached ();
3202         break;
3203     }
3204   }
3205
3206   g_value_unset (&data);
3207   gst_iterator_free (iter);
3208   gst_event_unref (event);
3209
3210   return res;
3211 }
3212
3213 /* this is the function called by the threadpool. When async elements commit
3214  * their state, this function will attempt to bring the bin to the next state.
3215  */
3216 static void
3217 gst_bin_continue_func (GstBin * bin, BinContinueData * data)
3218 {
3219   GstState current, next, pending;
3220   GstStateChange transition;
3221
3222   pending = data->pending;
3223
3224   GST_DEBUG_OBJECT (bin, "waiting for state lock");
3225   GST_STATE_LOCK (bin);
3226
3227   GST_DEBUG_OBJECT (bin, "doing state continue");
3228   GST_OBJECT_LOCK (bin);
3229
3230   /* if a new state change happened after this thread was scheduled, we return
3231    * immediately. */
3232   if (data->cookie != GST_ELEMENT_CAST (bin)->state_cookie)
3233     goto interrupted;
3234
3235   current = GST_STATE (bin);
3236   next = GST_STATE_GET_NEXT (current, pending);
3237   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
3238
3239   GST_STATE_NEXT (bin) = next;
3240   GST_STATE_PENDING (bin) = pending;
3241   /* mark busy */
3242   GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3243   GST_OBJECT_UNLOCK (bin);
3244
3245   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3246       "continue state change %s to %s, final %s",
3247       gst_element_state_get_name (current),
3248       gst_element_state_get_name (next), gst_element_state_get_name (pending));
3249
3250   gst_element_change_state (GST_ELEMENT_CAST (bin), transition);
3251
3252   GST_STATE_UNLOCK (bin);
3253   GST_DEBUG_OBJECT (bin, "state continue done");
3254
3255   return;
3256
3257 interrupted:
3258   {
3259     GST_OBJECT_UNLOCK (bin);
3260     GST_STATE_UNLOCK (bin);
3261     GST_DEBUG_OBJECT (bin, "state continue aborted due to intervening change");
3262     return;
3263   }
3264 }
3265
3266 static GstBusSyncReply
3267 bin_bus_handler (GstBus * bus, GstMessage * message, GstBin * bin)
3268 {
3269   GstBinClass *bclass;
3270
3271   bclass = GST_BIN_GET_CLASS (bin);
3272   if (bclass->handle_message)
3273     bclass->handle_message (bin, message);
3274   else
3275     gst_message_unref (message);
3276
3277   return GST_BUS_DROP;
3278 }
3279
3280 static void
3281 free_bin_continue_data (BinContinueData * data)
3282 {
3283   g_slice_free (BinContinueData, data);
3284 }
3285
3286 static void
3287 bin_push_state_continue (GstBin * bin, BinContinueData * data)
3288 {
3289   GST_DEBUG_OBJECT (bin, "pushing continue on thread pool");
3290   gst_element_call_async (GST_ELEMENT_CAST (bin),
3291       (GstElementCallAsyncFunc) gst_bin_continue_func, data,
3292       (GDestroyNotify) free_bin_continue_data);
3293 }
3294
3295 /* an element started an async state change, if we were not busy with a state
3296  * change, we perform a lost state.
3297  * This function is called with the OBJECT lock.
3298  */
3299 static void
3300 bin_handle_async_start (GstBin * bin)
3301 {
3302   GstState old_state, new_state;
3303   gboolean toplevel;
3304   GstMessage *amessage = NULL;
3305
3306   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_FAILURE)
3307     goto had_error;
3308
3309   /* get our toplevel state */
3310   toplevel = BIN_IS_TOPLEVEL (bin);
3311
3312   /* prepare an ASYNC_START message, we always post the start message even if we
3313    * are busy with a state change or when we are NO_PREROLL. */
3314   if (!toplevel)
3315     /* non toplevel bin, prepare async-start for the parent */
3316     amessage = gst_message_new_async_start (GST_OBJECT_CAST (bin));
3317
3318   if (bin->polling || GST_STATE_PENDING (bin) != GST_STATE_VOID_PENDING)
3319     goto was_busy;
3320
3321   /* async starts are ignored when we are NO_PREROLL */
3322   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_NO_PREROLL)
3323     goto was_no_preroll;
3324
3325   old_state = GST_STATE (bin);
3326
3327   /* when we PLAYING we go back to PAUSED, when preroll happens, we go back to
3328    * PLAYING after optionally redistributing the base_time. */
3329   if (old_state > GST_STATE_PAUSED)
3330     new_state = GST_STATE_PAUSED;
3331   else
3332     new_state = old_state;
3333
3334   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
3335       "lost state of %s, new %s", gst_element_state_get_name (old_state),
3336       gst_element_state_get_name (new_state));
3337
3338   GST_STATE (bin) = new_state;
3339   GST_STATE_NEXT (bin) = new_state;
3340   GST_STATE_PENDING (bin) = new_state;
3341   GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3342   GST_OBJECT_UNLOCK (bin);
3343
3344   /* post message */
3345   _priv_gst_element_state_changed (GST_ELEMENT_CAST (bin), new_state, new_state,
3346       new_state);
3347
3348 post_start:
3349   if (amessage) {
3350     /* post our ASYNC_START. */
3351     GST_DEBUG_OBJECT (bin, "posting ASYNC_START to parent");
3352     gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
3353   }
3354   GST_OBJECT_LOCK (bin);
3355
3356   return;
3357
3358 had_error:
3359   {
3360     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "we had an error");
3361     return;
3362   }
3363 was_busy:
3364   {
3365     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "state change busy");
3366     GST_OBJECT_UNLOCK (bin);
3367     goto post_start;
3368   }
3369 was_no_preroll:
3370   {
3371     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "ignoring, we are NO_PREROLL");
3372     GST_OBJECT_UNLOCK (bin);
3373     goto post_start;
3374   }
3375 }
3376
3377 /* this function is called when there are no more async elements in the bin. We
3378  * post a state changed message and an ASYNC_DONE message.
3379  * This function is called with the OBJECT lock.
3380  */
3381 static void
3382 bin_handle_async_done (GstBin * bin, GstStateChangeReturn ret,
3383     gboolean flag_pending, GstClockTime running_time)
3384 {
3385   GstState current, pending, target;
3386   GstStateChangeReturn old_ret;
3387   GstState old_state, old_next;
3388   gboolean toplevel, state_changed = FALSE;
3389   GstMessage *amessage = NULL;
3390   BinContinueData *cont = NULL;
3391
3392   if (GST_STATE_RETURN (bin) == GST_STATE_CHANGE_FAILURE)
3393     goto had_error;
3394
3395   pending = GST_STATE_PENDING (bin);
3396
3397   if (bin->polling)
3398     goto was_busy;
3399
3400   /* check if there is something to commit */
3401   if (pending == GST_STATE_VOID_PENDING)
3402     goto nothing_pending;
3403
3404   old_ret = GST_STATE_RETURN (bin);
3405   GST_STATE_RETURN (bin) = ret;
3406
3407   /* move to the next target state */
3408   target = GST_STATE_TARGET (bin);
3409   pending = GST_STATE_PENDING (bin) = target;
3410
3411   amessage = gst_message_new_async_done (GST_OBJECT_CAST (bin), running_time);
3412
3413   old_state = GST_STATE (bin);
3414   /* this is the state we should go to next */
3415   old_next = GST_STATE_NEXT (bin);
3416
3417   if (old_next != GST_STATE_PLAYING) {
3418     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3419         "committing state from %s to %s, old pending %s",
3420         gst_element_state_get_name (old_state),
3421         gst_element_state_get_name (old_next),
3422         gst_element_state_get_name (pending));
3423
3424     /* update current state */
3425     current = GST_STATE (bin) = old_next;
3426   } else {
3427     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3428         "setting state from %s to %s, pending %s",
3429         gst_element_state_get_name (old_state),
3430         gst_element_state_get_name (old_state),
3431         gst_element_state_get_name (pending));
3432     current = old_state;
3433   }
3434
3435   /* get our toplevel state */
3436   toplevel = BIN_IS_TOPLEVEL (bin);
3437
3438   /* see if we reached the final state. If we are not toplevel, we also have to
3439    * stop here, the parent will continue our state. */
3440   if ((pending == current) || !toplevel) {
3441     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3442         "completed state change, pending VOID");
3443
3444     /* mark VOID pending */
3445     pending = GST_STATE_VOID_PENDING;
3446     GST_STATE_PENDING (bin) = pending;
3447     GST_STATE_NEXT (bin) = GST_STATE_VOID_PENDING;
3448   } else {
3449     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
3450         "continue state change, pending %s",
3451         gst_element_state_get_name (pending));
3452
3453     cont = g_slice_new (BinContinueData);
3454
3455     /* cookie to detect concurrent state change */
3456     cont->cookie = GST_ELEMENT_CAST (bin)->state_cookie;
3457     /* pending target state */
3458     cont->pending = pending;
3459     /* mark busy */
3460     GST_STATE_RETURN (bin) = GST_STATE_CHANGE_ASYNC;
3461     GST_STATE_NEXT (bin) = GST_STATE_GET_NEXT (old_state, pending);
3462   }
3463
3464   if (old_next != GST_STATE_PLAYING) {
3465     if (old_state != old_next || old_ret == GST_STATE_CHANGE_ASYNC) {
3466       state_changed = TRUE;
3467     }
3468   }
3469   GST_OBJECT_UNLOCK (bin);
3470
3471   if (state_changed) {
3472     _priv_gst_element_state_changed (GST_ELEMENT_CAST (bin), old_state,
3473         old_next, pending);
3474   }
3475   if (amessage) {
3476     /* post our combined ASYNC_DONE when all is ASYNC_DONE. */
3477     GST_DEBUG_OBJECT (bin, "posting ASYNC_DONE to parent");
3478     gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
3479   }
3480
3481   GST_OBJECT_LOCK (bin);
3482   if (cont) {
3483     /* toplevel, start continue state */
3484     GST_DEBUG_OBJECT (bin, "all async-done, starting state continue");
3485     bin_push_state_continue (bin, cont);
3486   } else {
3487     GST_DEBUG_OBJECT (bin, "state change complete");
3488     GST_STATE_BROADCAST (bin);
3489   }
3490   return;
3491
3492 had_error:
3493   {
3494     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "we had an error");
3495     return;
3496   }
3497 was_busy:
3498   {
3499     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin, "state change busy");
3500     /* if we were busy with a state change and we are requested to flag a
3501      * pending async done, we do so here */
3502     if (flag_pending)
3503       bin->priv->pending_async_done = TRUE;
3504     return;
3505   }
3506 nothing_pending:
3507   {
3508     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "nothing pending");
3509     return;
3510   }
3511 }
3512
3513 static void
3514 bin_do_eos (GstBin * bin)
3515 {
3516   guint32 seqnum = 0;
3517   gboolean eos;
3518
3519   GST_OBJECT_LOCK (bin);
3520   /* If all sinks are EOS, we're in PLAYING and no state change is pending
3521    * (or we're doing playing to playing and noone else will trigger posting
3522    * EOS for us) we forward the EOS message to the parent bin or application
3523    */
3524   eos = GST_STATE (bin) == GST_STATE_PLAYING
3525       && (GST_STATE_PENDING (bin) == GST_STATE_VOID_PENDING ||
3526       GST_STATE_PENDING (bin) == GST_STATE_PLAYING)
3527       && bin->priv->posted_playing && is_eos (bin, &seqnum);
3528   GST_OBJECT_UNLOCK (bin);
3529
3530   if (eos
3531       && g_atomic_int_compare_and_exchange (&bin->priv->posted_eos, FALSE,
3532           TRUE)) {
3533     GstMessage *tmessage;
3534
3535     /* Clear out any further messages, and reset posted_eos so we can
3536        detect any new EOS that happens (eg, after a seek). Since all
3537        sinks have now posted an EOS, there will be no further EOS events
3538        seen unless there is a new logical EOS */
3539     GST_OBJECT_LOCK (bin);
3540     bin_remove_messages (bin, NULL, GST_MESSAGE_EOS);
3541     bin->priv->posted_eos = FALSE;
3542     GST_OBJECT_UNLOCK (bin);
3543
3544     tmessage = gst_message_new_eos (GST_OBJECT_CAST (bin));
3545     gst_message_set_seqnum (tmessage, seqnum);
3546     GST_DEBUG_OBJECT (bin,
3547         "all sinks posted EOS, posting seqnum #%" G_GUINT32_FORMAT, seqnum);
3548     gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3549   } else {
3550     GST_LOG_OBJECT (bin, "Not forwarding EOS due to in progress state change, "
3551         " or already posted, or waiting for more EOS");
3552   }
3553 }
3554
3555 static void
3556 bin_do_stream_start (GstBin * bin)
3557 {
3558   guint32 seqnum = 0;
3559   gboolean stream_start;
3560   gboolean have_group_id = FALSE;
3561   guint group_id = 0;
3562
3563   GST_OBJECT_LOCK (bin);
3564   /* If all sinks are STREAM_START we forward the STREAM_START message
3565    * to the parent bin or application
3566    */
3567   stream_start = is_stream_start (bin, &seqnum, &have_group_id, &group_id);
3568   GST_OBJECT_UNLOCK (bin);
3569
3570   if (stream_start) {
3571     GstMessage *tmessage;
3572
3573     GST_OBJECT_LOCK (bin);
3574     bin_remove_messages (bin, NULL, GST_MESSAGE_STREAM_START);
3575     GST_OBJECT_UNLOCK (bin);
3576
3577     tmessage = gst_message_new_stream_start (GST_OBJECT_CAST (bin));
3578     gst_message_set_seqnum (tmessage, seqnum);
3579     if (have_group_id)
3580       gst_message_set_group_id (tmessage, group_id);
3581
3582     GST_DEBUG_OBJECT (bin,
3583         "all sinks posted STREAM_START, posting seqnum #%" G_GUINT32_FORMAT,
3584         seqnum);
3585     gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3586   }
3587 }
3588
3589 /* must be called without the object lock as it posts messages */
3590 static void
3591 bin_do_message_forward (GstBin * bin, GstMessage * message)
3592 {
3593   if (bin->priv->message_forward) {
3594     GstMessage *forwarded;
3595
3596     GST_DEBUG_OBJECT (bin, "pass %s message upward",
3597         GST_MESSAGE_TYPE_NAME (message));
3598
3599     /* we need to convert these messages to element messages so that our parent
3600      * bin can easily ignore them and so that the application can easily
3601      * distinguish between the internally forwarded and the real messages. */
3602     forwarded = gst_message_new_element (GST_OBJECT_CAST (bin),
3603         gst_structure_new ("GstBinForwarded",
3604             "message", GST_TYPE_MESSAGE, message, NULL));
3605
3606     gst_element_post_message (GST_ELEMENT_CAST (bin), forwarded);
3607   }
3608 }
3609
3610 static void
3611 gst_bin_update_context (GstBin * bin, GstContext * context)
3612 {
3613   GST_OBJECT_LOCK (bin);
3614   gst_bin_update_context_unlocked (bin, context);
3615   GST_OBJECT_UNLOCK (bin);
3616 }
3617
3618 static void
3619 gst_bin_update_context_unlocked (GstBin * bin, GstContext * context)
3620 {
3621   const gchar *context_type;
3622   GList *l, **contexts;
3623
3624   contexts = &GST_ELEMENT_CAST (bin)->contexts;
3625   context_type = gst_context_get_context_type (context);
3626
3627   GST_DEBUG_OBJECT (bin, "set context %p %" GST_PTR_FORMAT, context,
3628       gst_context_get_structure (context));
3629   for (l = *contexts; l; l = l->next) {
3630     GstContext *tmp = l->data;
3631     const gchar *tmp_type = gst_context_get_context_type (tmp);
3632
3633     /* Always store newest context but never replace
3634      * a persistent one by a non-persistent one */
3635     if (strcmp (context_type, tmp_type) == 0 &&
3636         (gst_context_is_persistent (context) ||
3637             !gst_context_is_persistent (tmp))) {
3638       gst_context_replace ((GstContext **) & l->data, context);
3639       break;
3640     }
3641   }
3642   /* Not found? Add */
3643   if (l == NULL) {
3644     *contexts = g_list_prepend (*contexts, gst_context_ref (context));
3645   }
3646 }
3647
3648 /* handle child messages:
3649  *
3650  * This method is called synchronously when a child posts a message on
3651  * the internal bus.
3652  *
3653  * GST_MESSAGE_EOS: This message is only posted by sinks
3654  *     in the PLAYING state. If all sinks posted the EOS message, post
3655  *     one upwards.
3656  *
3657  * GST_MESSAGE_STATE_DIRTY: Deprecated
3658  *
3659  * GST_MESSAGE_SEGMENT_START: just collect, never forward upwards. If an
3660  *     element posts segment_start twice, only the last message is kept.
3661  *
3662  * GST_MESSAGE_SEGMENT_DONE: replace SEGMENT_START message from same poster
3663  *     with the segment_done message. If there are no more segment_start
3664  *     messages, post segment_done message upwards.
3665  *
3666  * GST_MESSAGE_DURATION_CHANGED: clear any cached durations.
3667  *     Whenever someone performs a duration query on the bin, we store the
3668  *     result so we can answer it quicker the next time. Any element that
3669  *     changes its duration marks our cached values invalid.
3670  *     This message is also posted upwards. This is currently disabled
3671  *     because too many elements don't post DURATION_CHANGED messages when
3672  *     the duration changes.
3673  *
3674  * GST_MESSAGE_CLOCK_LOST: This message is posted by an element when it
3675  *     can no longer provide a clock. The default bin behaviour is to
3676  *     check if the lost clock was the one provided by the bin. If so and
3677  *     we are currently in the PLAYING state, we forward the message to
3678  *     our parent.
3679  *     This message is also generated when we remove a clock provider from
3680  *     a bin. If this message is received by the application, it should
3681  *     PAUSE the pipeline and set it back to PLAYING to force a new clock
3682  *     and a new base_time distribution.
3683  *
3684  * GST_MESSAGE_CLOCK_PROVIDE: This message is generated when an element
3685  *     can provide a clock. This mostly happens when we add a new clock
3686  *     provider to the bin. The default behaviour of the bin is to mark the
3687  *     currently selected clock as dirty, which will perform a clock
3688  *     recalculation the next time we are asked to provide a clock.
3689  *     This message is never sent to the application but is forwarded to
3690  *     the parent.
3691  *
3692  * GST_MESSAGE_ASYNC_START: Create an internal ELEMENT message that stores
3693  *     the state of the element and the fact that the element will need a
3694  *     new base_time. This message is not forwarded to the application.
3695  *
3696  * GST_MESSAGE_ASYNC_DONE: Find the internal ELEMENT message we kept for the
3697  *     element when it posted ASYNC_START. If all elements are done, post a
3698  *     ASYNC_DONE message to the parent.
3699  *
3700  * OTHER: post upwards.
3701  */
3702 static void
3703 gst_bin_handle_message_func (GstBin * bin, GstMessage * message)
3704 {
3705   GstObject *src;
3706   GstMessageType type;
3707   GstMessage *tmessage;
3708   guint32 seqnum;
3709
3710   src = GST_MESSAGE_SRC (message);
3711   type = GST_MESSAGE_TYPE (message);
3712
3713   GST_DEBUG_OBJECT (bin, "[msg %p] handling child %s message of type %s",
3714       message, src ? GST_ELEMENT_NAME (src) : "(NULL)",
3715       GST_MESSAGE_TYPE_NAME (message));
3716
3717   switch (type) {
3718     case GST_MESSAGE_ERROR:
3719     {
3720       GST_OBJECT_LOCK (bin);
3721       /* flag error */
3722       GST_DEBUG_OBJECT (bin, "got ERROR message, unlocking state change");
3723       GST_STATE_RETURN (bin) = GST_STATE_CHANGE_FAILURE;
3724       GST_STATE_BROADCAST (bin);
3725       GST_OBJECT_UNLOCK (bin);
3726
3727       goto forward;
3728     }
3729     case GST_MESSAGE_EOS:
3730     {
3731
3732       /* collect all eos messages from the children */
3733       bin_do_message_forward (bin, message);
3734       GST_OBJECT_LOCK (bin);
3735       /* ref message for future use  */
3736       bin_replace_message (bin, message, GST_MESSAGE_EOS);
3737       GST_OBJECT_UNLOCK (bin);
3738
3739       bin_do_eos (bin);
3740       break;
3741     }
3742     case GST_MESSAGE_STREAM_START:
3743     {
3744
3745       /* collect all stream_start messages from the children */
3746       GST_OBJECT_LOCK (bin);
3747       /* ref message for future use  */
3748       bin_replace_message (bin, message, GST_MESSAGE_STREAM_START);
3749       GST_OBJECT_UNLOCK (bin);
3750
3751       bin_do_stream_start (bin);
3752       break;
3753     }
3754     case GST_MESSAGE_STATE_DIRTY:
3755     {
3756       GST_WARNING_OBJECT (bin, "received deprecated STATE_DIRTY message");
3757
3758       /* free message */
3759       gst_message_unref (message);
3760       break;
3761     }
3762     case GST_MESSAGE_SEGMENT_START:{
3763       gboolean post = FALSE;
3764       GstFormat format;
3765       gint64 position;
3766
3767       gst_message_parse_segment_start (message, &format, &position);
3768       seqnum = gst_message_get_seqnum (message);
3769
3770       bin_do_message_forward (bin, message);
3771
3772       GST_OBJECT_LOCK (bin);
3773       /* if this is the first segment-start, post to parent but not to the
3774        * application */
3775       if (!find_message (bin, NULL, GST_MESSAGE_SEGMENT_START) &&
3776           (GST_OBJECT_PARENT (bin) != NULL)) {
3777         post = TRUE;
3778       }
3779       /* replace any previous segment_start message from this source
3780        * with the new segment start message */
3781       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
3782       GST_OBJECT_UNLOCK (bin);
3783       if (post) {
3784         tmessage = gst_message_new_segment_start (GST_OBJECT_CAST (bin),
3785             format, position);
3786         gst_message_set_seqnum (tmessage, seqnum);
3787
3788         /* post segment start with initial format and position. */
3789         GST_DEBUG_OBJECT (bin, "posting SEGMENT_START (%u) bus message: %p",
3790             seqnum, message);
3791         gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3792       }
3793       break;
3794     }
3795     case GST_MESSAGE_SEGMENT_DONE:
3796     {
3797       gboolean post = FALSE;
3798       GstFormat format;
3799       gint64 position;
3800
3801       gst_message_parse_segment_done (message, &format, &position);
3802       seqnum = gst_message_get_seqnum (message);
3803
3804       bin_do_message_forward (bin, message);
3805
3806       GST_OBJECT_LOCK (bin);
3807       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
3808       /* if there are no more segment_start messages, everybody posted
3809        * a segment_done and we can post one on the bus. */
3810
3811       /* we don't care who still has a pending segment start */
3812       if (!find_message (bin, NULL, GST_MESSAGE_SEGMENT_START)) {
3813         /* nothing found */
3814         post = TRUE;
3815         /* remove all old segment_done messages */
3816         bin_remove_messages (bin, NULL, GST_MESSAGE_SEGMENT_DONE);
3817       }
3818       GST_OBJECT_UNLOCK (bin);
3819       if (post) {
3820         tmessage = gst_message_new_segment_done (GST_OBJECT_CAST (bin),
3821             format, position);
3822         gst_message_set_seqnum (tmessage, seqnum);
3823
3824         /* post segment done with latest format and position. */
3825         GST_DEBUG_OBJECT (bin, "posting SEGMENT_DONE (%u) bus message: %p",
3826             seqnum, message);
3827         gst_element_post_message (GST_ELEMENT_CAST (bin), tmessage);
3828       }
3829       break;
3830     }
3831     case GST_MESSAGE_DURATION_CHANGED:
3832     {
3833       /* FIXME: remove all cached durations, next time somebody asks
3834        * for duration, we will recalculate. */
3835 #if 0
3836       GST_OBJECT_LOCK (bin);
3837       bin_remove_messages (bin, NULL, GST_MESSAGE_DURATION_CHANGED);
3838       GST_OBJECT_UNLOCK (bin);
3839 #endif
3840       goto forward;
3841     }
3842     case GST_MESSAGE_CLOCK_LOST:
3843     {
3844       GstClock **provided_clock_p;
3845       GstElement **clock_provider_p;
3846       gboolean playing, toplevel, provided, forward;
3847       GstClock *clock;
3848
3849       gst_message_parse_clock_lost (message, &clock);
3850
3851       GST_OBJECT_LOCK (bin);
3852       bin->clock_dirty = TRUE;
3853       /* if we lost the clock that we provided, post to parent but
3854        * only if we are not a top-level bin or PLAYING.
3855        * The reason for this is that applications should be able
3856        * to PAUSE/PLAY if they receive this message without worrying
3857        * about the state of the pipeline. */
3858       provided = (clock == bin->provided_clock);
3859       playing = (GST_STATE (bin) == GST_STATE_PLAYING);
3860       toplevel = GST_OBJECT_PARENT (bin) == NULL;
3861       forward = provided && (playing || !toplevel);
3862       if (provided) {
3863         GST_DEBUG_OBJECT (bin,
3864             "Lost clock %" GST_PTR_FORMAT " provided by %" GST_PTR_FORMAT,
3865             bin->provided_clock, bin->clock_provider);
3866         provided_clock_p = &bin->provided_clock;
3867         clock_provider_p = &bin->clock_provider;
3868         gst_object_replace ((GstObject **) provided_clock_p, NULL);
3869         gst_object_replace ((GstObject **) clock_provider_p, NULL);
3870       }
3871       GST_DEBUG_OBJECT (bin, "provided %d, playing %d, forward %d",
3872           provided, playing, forward);
3873       GST_OBJECT_UNLOCK (bin);
3874
3875       if (forward)
3876         goto forward;
3877
3878       /* free message */
3879       gst_message_unref (message);
3880       break;
3881     }
3882     case GST_MESSAGE_CLOCK_PROVIDE:
3883     {
3884       gboolean forward;
3885
3886       GST_OBJECT_LOCK (bin);
3887       bin->clock_dirty = TRUE;
3888       /* a new clock is available, post to parent but not
3889        * to the application */
3890       forward = GST_OBJECT_PARENT (bin) != NULL;
3891       GST_OBJECT_UNLOCK (bin);
3892
3893       if (forward)
3894         goto forward;
3895
3896       /* free message */
3897       gst_message_unref (message);
3898       break;
3899     }
3900     case GST_MESSAGE_ASYNC_START:
3901     {
3902       GstState target;
3903
3904       GST_DEBUG_OBJECT (bin, "ASYNC_START message %p, %s", message,
3905           src ? GST_OBJECT_NAME (src) : "(NULL)");
3906
3907       bin_do_message_forward (bin, message);
3908
3909       GST_OBJECT_LOCK (bin);
3910       /* we ignore the message if we are going to <= READY */
3911       if ((target = GST_STATE_TARGET (bin)) <= GST_STATE_READY)
3912         goto ignore_start_message;
3913
3914       /* takes ownership of the message */
3915       bin_replace_message (bin, message, GST_MESSAGE_ASYNC_START);
3916
3917       bin_handle_async_start (bin);
3918       GST_OBJECT_UNLOCK (bin);
3919       break;
3920
3921     ignore_start_message:
3922       {
3923         GST_DEBUG_OBJECT (bin, "ignoring message, target %s",
3924             gst_element_state_get_name (target));
3925         GST_OBJECT_UNLOCK (bin);
3926         gst_message_unref (message);
3927         break;
3928       }
3929     }
3930     case GST_MESSAGE_ASYNC_DONE:
3931     {
3932       GstClockTime running_time;
3933       GstState target;
3934
3935       GST_DEBUG_OBJECT (bin, "ASYNC_DONE message %p, %s", message,
3936           src ? GST_OBJECT_NAME (src) : "(NULL)");
3937
3938       gst_message_parse_async_done (message, &running_time);
3939
3940       bin_do_message_forward (bin, message);
3941
3942       GST_OBJECT_LOCK (bin);
3943       /* ignore messages if we are shutting down */
3944       if ((target = GST_STATE_TARGET (bin)) <= GST_STATE_READY)
3945         goto ignore_done_message;
3946
3947       bin_replace_message (bin, message, GST_MESSAGE_ASYNC_START);
3948       /* if there are no more ASYNC_START messages, everybody posted
3949        * a ASYNC_DONE and we can post one on the bus. When checking, we
3950        * don't care who still has a pending ASYNC_START */
3951       if (!find_message (bin, NULL, GST_MESSAGE_ASYNC_START)) {
3952         /* nothing found, remove all old ASYNC_DONE messages */
3953         bin_remove_messages (bin, NULL, GST_MESSAGE_ASYNC_DONE);
3954
3955         GST_DEBUG_OBJECT (bin, "async elements commited");
3956         /* when we get an async done message when a state change was busy, we
3957          * need to set the pending_done flag so that at the end of the state
3958          * change we can see if we need to verify pending async elements, hence
3959          * the TRUE argument here. */
3960         bin_handle_async_done (bin, GST_STATE_CHANGE_SUCCESS, TRUE,
3961             running_time);
3962       } else {
3963         GST_DEBUG_OBJECT (bin, "there are more async elements pending");
3964       }
3965       GST_OBJECT_UNLOCK (bin);
3966       break;
3967
3968     ignore_done_message:
3969       {
3970         GST_DEBUG_OBJECT (bin, "ignoring message, target %s",
3971             gst_element_state_get_name (target));
3972         GST_OBJECT_UNLOCK (bin);
3973         gst_message_unref (message);
3974         break;
3975       }
3976     }
3977     case GST_MESSAGE_STRUCTURE_CHANGE:
3978     {
3979       gboolean busy;
3980
3981       gst_message_parse_structure_change (message, NULL, NULL, &busy);
3982
3983       GST_OBJECT_LOCK (bin);
3984       if (busy) {
3985         /* while the pad is busy, avoid following it when doing state changes.
3986          * Don't update the cookie yet, we will do that after the structure
3987          * change finished and we are ready to inspect the new updated
3988          * structure. */
3989         bin_replace_message (bin, message, GST_MESSAGE_STRUCTURE_CHANGE);
3990         message = NULL;
3991       } else {
3992         /* a pad link/unlink ended, signal the state change iterator that we
3993          * need to resync by updating the structure_cookie. */
3994         bin_remove_messages (bin, GST_MESSAGE_SRC (message),
3995             GST_MESSAGE_STRUCTURE_CHANGE);
3996         if (!GST_BIN_IS_NO_RESYNC (bin))
3997           bin->priv->structure_cookie++;
3998       }
3999       GST_OBJECT_UNLOCK (bin);
4000
4001       if (message)
4002         gst_message_unref (message);
4003
4004       break;
4005     }
4006     case GST_MESSAGE_NEED_CONTEXT:{
4007       const gchar *context_type;
4008       GList *l, *contexts;
4009
4010       gst_message_parse_context_type (message, &context_type);
4011       GST_OBJECT_LOCK (bin);
4012       contexts = GST_ELEMENT_CAST (bin)->contexts;
4013       GST_LOG_OBJECT (bin, "got need-context message type: %s", context_type);
4014       for (l = contexts; l; l = l->next) {
4015         GstContext *tmp = l->data;
4016         const gchar *tmp_type = gst_context_get_context_type (tmp);
4017
4018         if (strcmp (context_type, tmp_type) == 0) {
4019           gst_element_set_context (GST_ELEMENT (src), l->data);
4020           break;
4021         }
4022       }
4023       GST_OBJECT_UNLOCK (bin);
4024
4025       /* Forward if we couldn't answer the message */
4026       if (l == NULL) {
4027         goto forward;
4028       } else {
4029         gst_message_unref (message);
4030       }
4031
4032       break;
4033     }
4034     case GST_MESSAGE_HAVE_CONTEXT:{
4035       GstContext *context;
4036
4037       gst_message_parse_have_context (message, &context);
4038       gst_bin_update_context (bin, context);
4039       gst_context_unref (context);
4040
4041       goto forward;
4042       break;
4043     }
4044     default:
4045       goto forward;
4046   }
4047   return;
4048
4049 forward:
4050   {
4051     /* Send all other messages upward */
4052     GST_DEBUG_OBJECT (bin, "posting message upward");
4053     gst_element_post_message (GST_ELEMENT_CAST (bin), message);
4054     return;
4055   }
4056 }
4057
4058 /* generic struct passed to all query fold methods */
4059 typedef struct
4060 {
4061   GstQuery *query;
4062   gint64 min;
4063   gint64 max;
4064   gboolean live;
4065 } QueryFold;
4066
4067 typedef void (*QueryInitFunction) (GstBin * bin, QueryFold * fold);
4068 typedef void (*QueryDoneFunction) (GstBin * bin, QueryFold * fold);
4069
4070 /* for duration/position we collect all durations/positions and take
4071  * the MAX of all valid results */
4072 static void
4073 bin_query_min_max_init (GstBin * bin, QueryFold * fold)
4074 {
4075   fold->min = 0;
4076   fold->max = -1;
4077   fold->live = FALSE;
4078 }
4079
4080 static gboolean
4081 bin_query_duration_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4082 {
4083   gboolean res = FALSE;
4084   GstObject *item = g_value_get_object (vitem);
4085   if (GST_IS_PAD (item))
4086     res = gst_pad_query (GST_PAD (item), fold->query);
4087   else
4088     res = gst_element_query (GST_ELEMENT (item), fold->query);
4089
4090   if (res) {
4091     gint64 duration;
4092
4093     g_value_set_boolean (ret, TRUE);
4094
4095     gst_query_parse_duration (fold->query, NULL, &duration);
4096
4097     GST_DEBUG_OBJECT (item, "got duration %" G_GINT64_FORMAT, duration);
4098
4099     if (duration == -1) {
4100       /* duration query succeeded, but duration is unknown */
4101       fold->max = -1;
4102       return FALSE;
4103     }
4104
4105     if (duration > fold->max)
4106       fold->max = duration;
4107   }
4108
4109   return TRUE;
4110 }
4111
4112 static void
4113 bin_query_duration_done (GstBin * bin, QueryFold * fold)
4114 {
4115   GstFormat format;
4116
4117   gst_query_parse_duration (fold->query, &format, NULL);
4118   /* store max in query result */
4119   gst_query_set_duration (fold->query, format, fold->max);
4120
4121   GST_DEBUG_OBJECT (bin, "max duration %" G_GINT64_FORMAT, fold->max);
4122
4123   /* FIXME: re-implement duration caching */
4124 #if 0
4125   /* and cache now */
4126   GST_OBJECT_LOCK (bin);
4127   bin->messages = g_list_prepend (bin->messages,
4128       gst_message_new_duration (GST_OBJECT_CAST (bin), format, fold->max));
4129   GST_OBJECT_UNLOCK (bin);
4130 #endif
4131 }
4132
4133 static gboolean
4134 bin_query_position_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4135 {
4136   gboolean res = FALSE;
4137   GstObject *item = g_value_get_object (vitem);
4138   if (GST_IS_PAD (item))
4139     res = gst_pad_query (GST_PAD (item), fold->query);
4140   else
4141     res = gst_element_query (GST_ELEMENT (item), fold->query);
4142
4143   if (res) {
4144     gint64 position;
4145
4146     g_value_set_boolean (ret, TRUE);
4147
4148     gst_query_parse_position (fold->query, NULL, &position);
4149
4150     GST_DEBUG_OBJECT (item, "got position %" G_GINT64_FORMAT, position);
4151
4152     if (position > fold->max)
4153       fold->max = position;
4154   }
4155
4156   return TRUE;
4157 }
4158
4159 static void
4160 bin_query_position_done (GstBin * bin, QueryFold * fold)
4161 {
4162   GstFormat format;
4163
4164   gst_query_parse_position (fold->query, &format, NULL);
4165   /* store max in query result */
4166   gst_query_set_position (fold->query, format, fold->max);
4167
4168   GST_DEBUG_OBJECT (bin, "max position %" G_GINT64_FORMAT, fold->max);
4169 }
4170
4171 static gboolean
4172 bin_query_latency_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4173 {
4174   gboolean res = FALSE;
4175   GstObject *item = g_value_get_object (vitem);
4176   if (GST_IS_PAD (item))
4177     res = gst_pad_query (GST_PAD (item), fold->query);
4178   else
4179     res = gst_element_query (GST_ELEMENT (item), fold->query);
4180   if (res) {
4181     GstClockTime min, max;
4182     gboolean live;
4183
4184     gst_query_parse_latency (fold->query, &live, &min, &max);
4185
4186     GST_DEBUG_OBJECT (item,
4187         "got latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
4188         ", live %d", GST_TIME_ARGS (min), GST_TIME_ARGS (max), live);
4189
4190     /* for the combined latency we collect the MAX of all min latencies and
4191      * the MIN of all max latencies */
4192     if (live) {
4193       if (min > fold->min)
4194         fold->min = min;
4195       if (fold->max == -1)
4196         fold->max = max;
4197       else if (max < fold->max)
4198         fold->max = max;
4199       if (!fold->live)
4200         fold->live = live;
4201     }
4202   } else {
4203     g_value_set_boolean (ret, FALSE);
4204     GST_DEBUG_OBJECT (item, "failed query");
4205   }
4206
4207   return TRUE;
4208 }
4209
4210 static void
4211 bin_query_latency_done (GstBin * bin, QueryFold * fold)
4212 {
4213   /* store max in query result */
4214   gst_query_set_latency (fold->query, fold->live, fold->min, fold->max);
4215
4216   GST_DEBUG_OBJECT (bin,
4217       "latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
4218       ", live %d", GST_TIME_ARGS (fold->min), GST_TIME_ARGS (fold->max),
4219       fold->live);
4220 }
4221
4222 /* generic fold, return first valid result */
4223 static gboolean
4224 bin_query_generic_fold (const GValue * vitem, GValue * ret, QueryFold * fold)
4225 {
4226   gboolean res = FALSE;
4227   GstObject *item = g_value_get_object (vitem);
4228   if (GST_IS_PAD (item))
4229     res = gst_pad_query (GST_PAD (item), fold->query);
4230   else
4231     res = gst_element_query (GST_ELEMENT (item), fold->query);
4232   if (res) {
4233     g_value_set_boolean (ret, TRUE);
4234     GST_DEBUG_OBJECT (item, "answered query %p", fold->query);
4235   }
4236
4237   /* and stop as soon as we have a valid result */
4238   return !res;
4239 }
4240
4241 /* Perform a query iteration for the given bin. The query is stored in
4242  * QueryFold and iter should be either a GstPad iterator or a
4243  * GstElement iterator. */
4244 static gboolean
4245 bin_iterate_fold (GstBin * bin, GstIterator * iter, QueryInitFunction fold_init,
4246     QueryDoneFunction fold_done, GstIteratorFoldFunction fold_func,
4247     QueryFold * fold_data, gboolean default_return)
4248 {
4249   gboolean res = default_return;
4250   GValue ret = { 0 };
4251   /* set the result of the query to FALSE initially */
4252   g_value_init (&ret, G_TYPE_BOOLEAN);
4253   g_value_set_boolean (&ret, res);
4254
4255   while (TRUE) {
4256     GstIteratorResult ires;
4257
4258     ires = gst_iterator_fold (iter, fold_func, &ret, fold_data);
4259
4260     switch (ires) {
4261       case GST_ITERATOR_RESYNC:
4262         gst_iterator_resync (iter);
4263         if (fold_init)
4264           fold_init (bin, fold_data);
4265         g_value_set_boolean (&ret, res);
4266         break;
4267       case GST_ITERATOR_OK:
4268       case GST_ITERATOR_DONE:
4269         res = g_value_get_boolean (&ret);
4270         if (fold_done != NULL && res)
4271           fold_done (bin, fold_data);
4272         goto done;
4273       default:
4274         res = FALSE;
4275         goto done;
4276     }
4277   }
4278 done:
4279   return res;
4280 }
4281
4282 static gboolean
4283 gst_bin_query (GstElement * element, GstQuery * query)
4284 {
4285   GstBin *bin = GST_BIN_CAST (element);
4286   GstIterator *iter;
4287   gboolean default_return = FALSE;
4288   gboolean res = FALSE;
4289   gboolean src_pads_query_result = FALSE;
4290   GstIteratorFoldFunction fold_func;
4291   QueryInitFunction fold_init = NULL;
4292   QueryDoneFunction fold_done = NULL;
4293   QueryFold fold_data;
4294
4295   switch (GST_QUERY_TYPE (query)) {
4296     case GST_QUERY_DURATION:
4297     {
4298       /* FIXME: implement duration caching in GstBin again */
4299 #if 0
4300       GList *cached;
4301       GstFormat qformat;
4302
4303       gst_query_parse_duration (query, &qformat, NULL);
4304
4305       /* find cached duration query */
4306       GST_OBJECT_LOCK (bin);
4307       for (cached = bin->messages; cached; cached = g_list_next (cached)) {
4308         GstMessage *message = (GstMessage *) cached->data;
4309
4310         if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_DURATION_CHANGED &&
4311             GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (bin)) {
4312           GstFormat format;
4313           gint64 duration;
4314
4315           gst_message_parse_duration (message, &format, &duration);
4316
4317           /* if cached same format, copy duration in query result */
4318           if (format == qformat) {
4319             GST_DEBUG_OBJECT (bin, "return cached duration %" G_GINT64_FORMAT,
4320                 duration);
4321             GST_OBJECT_UNLOCK (bin);
4322
4323             gst_query_set_duration (query, qformat, duration);
4324             res = TRUE;
4325             goto exit;
4326           }
4327         }
4328       }
4329       GST_OBJECT_UNLOCK (bin);
4330 #else
4331       GST_FIXME ("implement duration caching in GstBin again");
4332 #endif
4333       /* no cached value found, iterate and collect durations */
4334       fold_func = (GstIteratorFoldFunction) bin_query_duration_fold;
4335       fold_init = bin_query_min_max_init;
4336       fold_done = bin_query_duration_done;
4337       break;
4338     }
4339     case GST_QUERY_POSITION:
4340     {
4341       fold_func = (GstIteratorFoldFunction) bin_query_position_fold;
4342       fold_init = bin_query_min_max_init;
4343       fold_done = bin_query_position_done;
4344       break;
4345     }
4346     case GST_QUERY_LATENCY:
4347     {
4348       fold_func = (GstIteratorFoldFunction) bin_query_latency_fold;
4349       fold_init = bin_query_min_max_init;
4350       fold_done = bin_query_latency_done;
4351       default_return = TRUE;
4352       break;
4353     }
4354     default:
4355       fold_func = (GstIteratorFoldFunction) bin_query_generic_fold;
4356       break;
4357   }
4358
4359   fold_data.query = query;
4360
4361   iter = gst_bin_iterate_sinks (bin);
4362   GST_DEBUG_OBJECT (bin, "Sending query %p (type %s) to sink children",
4363       query, GST_QUERY_TYPE_NAME (query));
4364
4365   if (fold_init)
4366     fold_init (bin, &fold_data);
4367
4368   res =
4369       bin_iterate_fold (bin, iter, fold_init, fold_done, fold_func, &fold_data,
4370       default_return);
4371   gst_iterator_free (iter);
4372
4373   if (!res) {
4374     /* Query the source pads of the element */
4375     iter = gst_element_iterate_src_pads (element);
4376     src_pads_query_result =
4377         bin_iterate_fold (bin, iter, fold_init, fold_done, fold_func,
4378         &fold_data, default_return);
4379     gst_iterator_free (iter);
4380
4381     if (src_pads_query_result)
4382       res = TRUE;
4383   }
4384
4385   GST_DEBUG_OBJECT (bin, "query %p result %d", query, res);
4386
4387   return res;
4388 }
4389
4390 static void
4391 set_context (const GValue * item, gpointer user_data)
4392 {
4393   GstElement *element = g_value_get_object (item);
4394
4395   gst_element_set_context (element, user_data);
4396 }
4397
4398 static void
4399 gst_bin_set_context (GstElement * element, GstContext * context)
4400 {
4401   GstBin *bin;
4402   GstIterator *children;
4403
4404   g_return_if_fail (GST_IS_BIN (element));
4405
4406   bin = GST_BIN (element);
4407
4408   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
4409
4410   children = gst_bin_iterate_elements (bin);
4411   while (gst_iterator_foreach (children, set_context,
4412           context) == GST_ITERATOR_RESYNC)
4413     gst_iterator_resync (children);
4414   gst_iterator_free (children);
4415 }
4416
4417 static gint
4418 compare_name (const GValue * velement, const gchar * name)
4419 {
4420   gint eq;
4421   GstElement *element = g_value_get_object (velement);
4422
4423   GST_OBJECT_LOCK (element);
4424   eq = strcmp (GST_ELEMENT_NAME (element), name);
4425   GST_OBJECT_UNLOCK (element);
4426
4427   return eq;
4428 }
4429
4430 /**
4431  * gst_bin_get_by_name:
4432  * @bin: a #GstBin
4433  * @name: the element name to search for
4434  *
4435  * Gets the element with the given name from a bin. This
4436  * function recurses into child bins.
4437  *
4438  * Returns %NULL if no element with the given name is found in the bin.
4439  *
4440  * MT safe.  Caller owns returned reference.
4441  *
4442  * Returns: (transfer full) (nullable): the #GstElement with the given
4443  * name, or %NULL
4444  */
4445 GstElement *
4446 gst_bin_get_by_name (GstBin * bin, const gchar * name)
4447 {
4448   GstIterator *children;
4449   GValue result = { 0, };
4450   GstElement *element;
4451   gboolean found;
4452
4453   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4454
4455   GST_CAT_INFO (GST_CAT_PARENTAGE, "[%s]: looking up child element %s",
4456       GST_ELEMENT_NAME (bin), name);
4457
4458   children = gst_bin_iterate_recurse (bin);
4459   found = gst_iterator_find_custom (children,
4460       (GCompareFunc) compare_name, &result, (gpointer) name);
4461   gst_iterator_free (children);
4462
4463   if (found) {
4464     element = g_value_dup_object (&result);
4465     g_value_unset (&result);
4466   } else {
4467     element = NULL;
4468   }
4469
4470   return element;
4471 }
4472
4473 /**
4474  * gst_bin_get_by_name_recurse_up:
4475  * @bin: a #GstBin
4476  * @name: the element name to search for
4477  *
4478  * Gets the element with the given name from this bin. If the
4479  * element is not found, a recursion is performed on the parent bin.
4480  *
4481  * Returns %NULL if:
4482  * - no element with the given name is found in the bin
4483  *
4484  * MT safe.  Caller owns returned reference.
4485  *
4486  * Returns: (transfer full) (nullable): the #GstElement with the given
4487  * name, or %NULL
4488  */
4489 GstElement *
4490 gst_bin_get_by_name_recurse_up (GstBin * bin, const gchar * name)
4491 {
4492   GstElement *result;
4493
4494   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4495   g_return_val_if_fail (name != NULL, NULL);
4496
4497   result = gst_bin_get_by_name (bin, name);
4498
4499   if (!result) {
4500     GstObject *parent;
4501
4502     parent = gst_object_get_parent (GST_OBJECT_CAST (bin));
4503     if (parent) {
4504       if (GST_IS_BIN (parent)) {
4505         result = gst_bin_get_by_name_recurse_up (GST_BIN_CAST (parent), name);
4506       }
4507       gst_object_unref (parent);
4508     }
4509   }
4510
4511   return result;
4512 }
4513
4514 static gint
4515 compare_interface (const GValue * velement, GValue * interface)
4516 {
4517   GstElement *element = g_value_get_object (velement);
4518   GType interface_type = (GType) g_value_get_pointer (interface);
4519   gint ret;
4520
4521   if (G_TYPE_CHECK_INSTANCE_TYPE (element, interface_type)) {
4522     ret = 0;
4523   } else {
4524     ret = 1;
4525   }
4526   return ret;
4527 }
4528
4529 /**
4530  * gst_bin_get_by_interface:
4531  * @bin: a #GstBin
4532  * @iface: the #GType of an interface
4533  *
4534  * Looks for an element inside the bin that implements the given
4535  * interface. If such an element is found, it returns the element.
4536  * You can cast this element to the given interface afterwards.  If you want
4537  * all elements that implement the interface, use
4538  * gst_bin_iterate_all_by_interface(). This function recurses into child bins.
4539  *
4540  * MT safe.  Caller owns returned reference.
4541  *
4542  * Returns: (transfer full): A #GstElement inside the bin implementing the interface
4543  */
4544 GstElement *
4545 gst_bin_get_by_interface (GstBin * bin, GType iface)
4546 {
4547   GstIterator *children;
4548   GValue result = { 0, };
4549   GstElement *element;
4550   gboolean found;
4551   GValue viface = { 0, };
4552
4553   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4554   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface), NULL);
4555
4556   g_value_init (&viface, G_TYPE_POINTER);
4557   g_value_set_pointer (&viface, (gpointer) iface);
4558
4559   children = gst_bin_iterate_recurse (bin);
4560   found = gst_iterator_find_custom (children, (GCompareFunc) compare_interface,
4561       &result, &viface);
4562   gst_iterator_free (children);
4563
4564   if (found) {
4565     element = g_value_dup_object (&result);
4566     g_value_unset (&result);
4567   } else {
4568     element = NULL;
4569   }
4570   g_value_unset (&viface);
4571
4572   return element;
4573 }
4574
4575 /**
4576  * gst_bin_iterate_all_by_interface:
4577  * @bin: a #GstBin
4578  * @iface: the #GType of an interface
4579  *
4580  * Looks for all elements inside the bin that implements the given
4581  * interface. You can safely cast all returned elements to the given interface.
4582  * The function recurses inside child bins. The iterator will yield a series
4583  * of #GstElement that should be unreffed after use.
4584  *
4585  * MT safe.  Caller owns returned value.
4586  *
4587  * Returns: (transfer full) (nullable): a #GstIterator of #GstElement
4588  *     for all elements in the bin implementing the given interface,
4589  *     or %NULL
4590  */
4591 GstIterator *
4592 gst_bin_iterate_all_by_interface (GstBin * bin, GType iface)
4593 {
4594   GstIterator *children;
4595   GstIterator *result;
4596   GValue viface = { 0, };
4597
4598   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
4599   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface), NULL);
4600
4601   g_value_init (&viface, G_TYPE_POINTER);
4602   g_value_set_pointer (&viface, (gpointer) iface);
4603
4604   children = gst_bin_iterate_recurse (bin);
4605   result = gst_iterator_filter (children, (GCompareFunc) compare_interface,
4606       &viface);
4607
4608   g_value_unset (&viface);
4609
4610   return result;
4611 }