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