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