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