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