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