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