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