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