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