9f8c1bdb2ef0463e1658c9808b27bf1da2325964
[platform/upstream/gstreamer.git] / gst / gstbin.c
1 /* GStreamer
2  *
3  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
4  *                    2004 Wim Taymans <wim@fluendo.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., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  *
23  * MT safe.
24  */
25
26 /**
27  * SECTION:gstbin
28  * @short_description: Base class and element that can contain other elements
29  *
30  * #GstBin is an element that can contain other #GstElement, allowing them to be
31  * managed as a group.
32  * Pads from the child elements can be ghosted to the bin, see #GstGhostPad.
33  * This makes the bin look like any other elements and enables creation of
34  * higher-level abstraction elements.
35  *
36  * A new #GstBin is created with gst_bin_new(). Use a #GstPipeline instead if you
37  * want to create a toplevel bin because a normal bin doesn't have a bus or
38  * handle clock distribution of its own.
39  *
40  * After the bin has been created you will typically add elements to it with
41  * gst_bin_add(). You can remove elements with gst_bin_remove().
42  *
43  * An element can be retrieved from a bin with gst_bin_get_by_name(), using the
44  * elements name. gst_bin_get_by_name_recurse_up() is mainly used for internal
45  * purposes and will query the parent bins when the element is not found in the
46  * current bin.
47  *
48  * An iterator of elements in a bin can be retrieved with
49  * gst_bin_iterate_elements(). Various other iterators exist to retrieve the
50  * elements in a bin.
51  *
52  * gst_object_unref() is used to drop your reference to the bin.
53  *
54  * The <link linkend="GstBin-element-added">element-added</link> signal is
55  * fired whenever a new element is added to the bin. Likewise the <link
56  * linkend="GstBin-element-removed">element-removed</link> signal is fired
57  * whenever an element is removed from the bin.
58  *
59  * <refsect2><title>Notes</title>
60  * <para>
61  * A #GstBin internally intercepts every #GstMessage posted by its children and
62  * implements the following default behaviour for each of them:
63  * <variablelist>
64  *   <varlistentry>
65  *     <term>GST_MESSAGE_EOS</term>
66  *     <listitem><para>This message is only posted by sinks in the PLAYING
67  *     state. If all sinks posted the EOS message, this bin will post and EOS
68  *     message upwards.</para></listitem>
69  *   </varlistentry>
70  *   <varlistentry>
71  *     <term>GST_MESSAGE_SEGMENT_START</term>
72  *     <listitem><para>just collected and never forwarded upwards.
73  *     The messages are used to decide when all elements have completed playback
74  *     of their segment.</para></listitem>
75  *   </varlistentry>
76  *   <varlistentry>
77  *     <term>GST_MESSAGE_SEGMENT_DONE</term>
78  *     <listitem><para> Is posted by #GstBin when all elements that posted
79  *     a SEGMENT_START have posted a SEGMENT_DONE.</para></listitem>
80  *   </varlistentry>
81  *   <varlistentry>
82  *     <term>GST_MESSAGE_DURATION</term>
83  *     <listitem><para> Is posted by an element that detected a change
84  *     in the stream duration. The default bin behaviour is to clear any
85  *     cached duration values so that the next duration query will perform
86  *     a full duration recalculation. The duration change is posted to the
87  *     application so that it can refetch the new duration with a duration
88  *     query.
89  *     </para></listitem>
90  *   </varlistentry>
91  *   <varlistentry>
92  *     <term>GST_MESSAGE_CLOCK_LOST</term>
93  *     <listitem><para> This message is posted by an element when it
94  *     can no longer provide a clock. The default bin behaviour is to
95  *     check if the lost clock was the one provided by the bin. If so and
96  *     the bin is currently in the PLAYING state, the message is forwarded to
97  *     the bin parent.
98  *     This message is also generated when a clock provider is removed from
99  *     the bin. If this message is received by the application, it should
100  *     PAUSE the pipeline and set it back to PLAYING to force a new clock
101  *     distribution.
102  *     </para></listitem>
103  *   </varlistentry>
104  *   <varlistentry>
105  *     <term>GST_MESSAGE_CLOCK_PROVIDE</term>
106  *     <listitem><para> This message is generated when an element
107  *     can provide a clock. This mostly happens when a new clock 
108  *     provider is added to the bin. The default behaviour of the bin is to 
109  *     mark the currently selected clock as dirty, which will perform a clock
110  *     recalculation the next time the bin is asked to provide a clock.
111  *     This message is never sent tot the application but is forwarded to
112  *     the parent of the bin.
113  *     </para></listitem>
114  *   </varlistentry>
115  *   <varlistentry>
116  *     <term>OTHERS</term>
117  *     <listitem><para> posted upwards.</para></listitem>
118  *   </varlistentry>
119  * </variablelist>
120  *
121  *
122  * A #GstBin implements the following default behaviour for answering to a
123  * #GstQuery:
124  * <variablelist>
125  *   <varlistentry>
126  *     <term>GST_QUERY_DURATION</term>
127  *     <listitem><para>If the query has been asked before with the same format
128  *     and the bin is a toplevel bin (ie. has no parent),
129  *     use the cached previous value. If no previous value was cached, the
130  *     query is sent to all sink elements in the bin and the MAXIMUM of all
131  *     values is returned. If the bin is a toplevel bin the value is cached. 
132  *     If no sinks are available in the bin, the query fails.
133  *     </para></listitem>
134  *   </varlistentry>
135  *   <varlistentry>
136  *     <term>OTHERS</term>
137  *     <listitem><para>the query is forwarded to all sink elements, the result
138  *     of the first sink that answers the query successfully is returned. If no
139  *     sink is in the bin, the query fails.</para></listitem>
140  *   </varlistentry>
141  * </variablelist>
142  *
143  * A #GstBin will by default forward any event sent to it to all sink elements.
144  * If all the sinks return TRUE, the bin will also return TRUE, else FALSE is
145  * returned. If no sinks are in the bin, the event handler will return TRUE.
146  *
147  * </para>
148  * </refsect2>
149  *
150  * Last reviewed on 2006-04-28 (0.10.6)
151  */
152
153 #include "gst_private.h"
154
155 #include "gstevent.h"
156 #include "gstbin.h"
157 #include "gstmarshal.h"
158 #include "gstxml.h"
159 #include "gstinfo.h"
160 #include "gsterror.h"
161
162 #include "gstindex.h"
163 #include "gstindexfactory.h"
164 #include "gstutils.h"
165 #include "gstchildproxy.h"
166
167 GST_DEBUG_CATEGORY_STATIC (bin_debug);
168 #define GST_CAT_DEFAULT bin_debug
169
170 static const GstElementDetails gst_bin_details =
171 GST_ELEMENT_DETAILS ("Generic bin",
172     "Generic/Bin",
173     "Simple container object",
174     "Erik Walthinsen <omega@cse.ogi.edu>," "Wim Taymans <wim@fluendo.com>");
175
176 static void gst_bin_dispose (GObject * object);
177
178 static void gst_bin_recalc_state (GstBin * bin, gboolean force);
179 static GstStateChangeReturn gst_bin_change_state_func (GstElement * element,
180     GstStateChange transition);
181 static GstStateChangeReturn gst_bin_get_state_func (GstElement * element,
182     GstState * state, GstState * pending, GstClockTime timeout);
183
184 static gboolean gst_bin_add_func (GstBin * bin, GstElement * element);
185 static gboolean gst_bin_remove_func (GstBin * bin, GstElement * element);
186
187 #ifndef GST_DISABLE_INDEX
188 static void gst_bin_set_index_func (GstElement * element, GstIndex * index);
189 #endif
190 static GstClock *gst_bin_provide_clock_func (GstElement * element);
191 static gboolean gst_bin_set_clock_func (GstElement * element, GstClock * clock);
192
193 static void gst_bin_handle_message_func (GstBin * bin, GstMessage * message);
194 static gboolean gst_bin_send_event (GstElement * element, GstEvent * event);
195 static GstBusSyncReply bin_bus_handler (GstBus * bus,
196     GstMessage * message, GstBin * bin);
197 static gboolean gst_bin_query (GstElement * element, GstQuery * query);
198
199 #ifndef GST_DISABLE_LOADSAVE
200 static xmlNodePtr gst_bin_save_thyself (GstObject * object, xmlNodePtr parent);
201 static void gst_bin_restore_thyself (GstObject * object, xmlNodePtr self);
202 #endif
203
204 static void bin_remove_messages (GstBin * bin, GstObject * src,
205     GstMessageType types);
206 static void gst_bin_recalc_func (GstBin * child, gpointer data);
207 static gint bin_element_is_sink (GstElement * child, GstBin * bin);
208 static gint bin_element_is_src (GstElement * child, GstBin * bin);
209
210 static GstIterator *gst_bin_sort_iterator_new (GstBin * bin);
211
212 /* Bin signals and properties */
213 enum
214 {
215   ELEMENT_ADDED,
216   ELEMENT_REMOVED,
217   LAST_SIGNAL
218 };
219
220 enum
221 {
222   PROP_0
223       /* FILL ME */
224 };
225
226 static void gst_bin_base_init (gpointer g_class);
227 static void gst_bin_class_init (GstBinClass * klass);
228 static void gst_bin_init (GstBin * bin);
229 static void gst_bin_child_proxy_init (gpointer g_iface, gpointer iface_data);
230
231 static GstElementClass *parent_class = NULL;
232 static guint gst_bin_signals[LAST_SIGNAL] = { 0 };
233
234 /**
235  * gst_bin_get_type:
236  *
237  * Returns: the type of #GstBin
238  */
239 GType
240 gst_bin_get_type (void)
241 {
242   static GType gst_bin_type = 0;
243
244   if (G_UNLIKELY (gst_bin_type == 0)) {
245     static const GTypeInfo bin_info = {
246       sizeof (GstBinClass),
247       gst_bin_base_init,
248       NULL,
249       (GClassInitFunc) gst_bin_class_init,
250       NULL,
251       NULL,
252       sizeof (GstBin),
253       0,
254       (GInstanceInitFunc) gst_bin_init,
255       NULL
256     };
257     static const GInterfaceInfo child_proxy_info = {
258       gst_bin_child_proxy_init,
259       NULL,
260       NULL
261     };
262
263     gst_bin_type =
264         g_type_register_static (GST_TYPE_ELEMENT, "GstBin", &bin_info, 0);
265
266     g_type_add_interface_static (gst_bin_type, GST_TYPE_CHILD_PROXY,
267         &child_proxy_info);
268
269     GST_DEBUG_CATEGORY_INIT (bin_debug, "bin", GST_DEBUG_BOLD,
270         "debugging info for the 'bin' container element");
271   }
272   return gst_bin_type;
273 }
274
275 static void
276 gst_bin_base_init (gpointer g_class)
277 {
278   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
279
280   gst_element_class_set_details (gstelement_class, &gst_bin_details);
281 }
282
283 static GstObject *
284 gst_bin_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
285     guint index)
286 {
287   GstObject *res;
288   GstBin *bin;
289
290   bin = GST_BIN_CAST (child_proxy);
291
292   GST_OBJECT_LOCK (bin);
293   if ((res = g_list_nth_data (bin->children, index)))
294     gst_object_ref (res);
295   GST_OBJECT_UNLOCK (bin);
296
297   return res;
298 }
299
300 guint
301 gst_bin_child_proxy_get_children_count (GstChildProxy * child_proxy)
302 {
303   guint num;
304   GstBin *bin;
305
306   bin = GST_BIN_CAST (child_proxy);
307
308   GST_OBJECT_LOCK (bin);
309   num = bin->numchildren;
310   GST_OBJECT_UNLOCK (bin);
311
312   return num;
313 }
314
315 static void
316 gst_bin_child_proxy_init (gpointer g_iface, gpointer iface_data)
317 {
318   GstChildProxyInterface *iface = g_iface;
319
320   iface->get_children_count = gst_bin_child_proxy_get_children_count;
321   iface->get_child_by_index = gst_bin_child_proxy_get_child_by_index;
322 }
323
324 static void
325 gst_bin_class_init (GstBinClass * klass)
326 {
327   GObjectClass *gobject_class;
328   GstObjectClass *gstobject_class;
329   GstElementClass *gstelement_class;
330   GError *err;
331
332   gobject_class = (GObjectClass *) klass;
333   gstobject_class = (GstObjectClass *) klass;
334   gstelement_class = (GstElementClass *) klass;
335
336   parent_class = g_type_class_peek_parent (klass);
337
338   /**
339    * GstBin::element-added:
340    * @bin: the #GstBin
341    * @element: the #GstElement that was added to the bin
342    *
343    * Will be emitted after the element was added to the bin.
344    */
345   gst_bin_signals[ELEMENT_ADDED] =
346       g_signal_new ("element-added", G_TYPE_FROM_CLASS (klass),
347       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstBinClass, element_added), NULL,
348       NULL, gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
349   /**
350    * GstBin::element-removed:
351    * @bin: the #GstBin
352    * @element: the #GstElement that was removed from the bin
353    *
354    * Will be emitted after the element was removed from the bin.
355    */
356   gst_bin_signals[ELEMENT_REMOVED] =
357       g_signal_new ("element-removed", G_TYPE_FROM_CLASS (klass),
358       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstBinClass, element_removed), NULL,
359       NULL, gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
360
361   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_bin_dispose);
362
363 #ifndef GST_DISABLE_LOADSAVE
364   gstobject_class->save_thyself = GST_DEBUG_FUNCPTR (gst_bin_save_thyself);
365   gstobject_class->restore_thyself =
366       GST_DEBUG_FUNCPTR (gst_bin_restore_thyself);
367 #endif
368
369   gstelement_class->change_state =
370       GST_DEBUG_FUNCPTR (gst_bin_change_state_func);
371   gstelement_class->get_state = GST_DEBUG_FUNCPTR (gst_bin_get_state_func);
372 #ifndef GST_DISABLE_INDEX
373   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_bin_set_index_func);
374 #endif
375   gstelement_class->provide_clock =
376       GST_DEBUG_FUNCPTR (gst_bin_provide_clock_func);
377   gstelement_class->set_clock = GST_DEBUG_FUNCPTR (gst_bin_set_clock_func);
378
379   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_bin_send_event);
380   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_bin_query);
381
382   klass->add_element = GST_DEBUG_FUNCPTR (gst_bin_add_func);
383   klass->remove_element = GST_DEBUG_FUNCPTR (gst_bin_remove_func);
384   klass->handle_message = GST_DEBUG_FUNCPTR (gst_bin_handle_message_func);
385
386   GST_DEBUG ("creating bin thread pool");
387   err = NULL;
388   klass->pool =
389       g_thread_pool_new ((GFunc) gst_bin_recalc_func, NULL, -1, FALSE, &err);
390   if (err != NULL) {
391     g_critical ("could alloc threadpool %s", err->message);
392   }
393 }
394
395 static void
396 gst_bin_init (GstBin * bin)
397 {
398   GstBus *bus;
399
400   bin->numchildren = 0;
401   bin->children = NULL;
402   bin->children_cookie = 0;
403   bin->messages = NULL;
404   bin->polling = FALSE;
405   bin->state_dirty = FALSE;
406   bin->provided_clock = NULL;
407   bin->clock_dirty = FALSE;
408
409   /* Set up a bus for listening to child elements */
410   bus = gst_bus_new ();
411   bin->child_bus = bus;
412   GST_DEBUG_OBJECT (bin, "using bus %" GST_PTR_FORMAT " to listen to children",
413       bus);
414   gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bin_bus_handler, bin);
415 }
416
417 static void
418 gst_bin_dispose (GObject * object)
419 {
420   GstBin *bin = GST_BIN (object);
421   GstBus **child_bus_p = &bin->child_bus;
422   GstClock **provided_clock_p = &bin->provided_clock;
423   GstElement **clock_provider_p = &bin->clock_provider;
424
425   GST_CAT_DEBUG_OBJECT (GST_CAT_REFCOUNTING, object, "dispose");
426
427   bin_remove_messages (bin, NULL, GST_MESSAGE_ANY);
428
429   gst_object_replace ((GstObject **) child_bus_p, NULL);
430   gst_object_replace ((GstObject **) provided_clock_p, NULL);
431   gst_object_replace ((GstObject **) clock_provider_p, NULL);
432
433   while (bin->children) {
434     gst_bin_remove (bin, GST_ELEMENT_CAST (bin->children->data));
435   }
436   if (G_UNLIKELY (bin->children != NULL)) {
437     g_critical ("could not remove elements from bin %s",
438         GST_STR_NULL (GST_OBJECT_NAME (object)));
439   }
440
441   G_OBJECT_CLASS (parent_class)->dispose (object);
442 }
443
444 /**
445  * gst_bin_new:
446  * @name: the name of the new bin
447  *
448  * Creates a new bin with the given name.
449  *
450  * Returns: a new #GstBin
451  */
452 GstElement *
453 gst_bin_new (const gchar * name)
454 {
455   return gst_element_factory_make ("bin", name);
456 }
457
458 /* set the index on all elements in this bin
459  *
460  * MT safe
461  */
462 #ifndef GST_DISABLE_INDEX
463 static void
464 gst_bin_set_index_func (GstElement * element, GstIndex * index)
465 {
466   GstBin *bin;
467   GList *children;
468
469   bin = GST_BIN (element);
470
471   GST_OBJECT_LOCK (bin);
472   for (children = bin->children; children; children = g_list_next (children)) {
473     GstElement *child = GST_ELEMENT (children->data);
474
475     gst_element_set_index (child, index);
476   }
477   GST_OBJECT_UNLOCK (bin);
478 }
479 #endif
480
481 /* set the clock on all elements in this bin
482  *
483  * MT safe
484  */
485 static gboolean
486 gst_bin_set_clock_func (GstElement * element, GstClock * clock)
487 {
488   GList *children;
489   GstBin *bin;
490   gboolean res = TRUE;
491
492   bin = GST_BIN (element);
493
494   GST_OBJECT_LOCK (bin);
495   if (element->clock != clock) {
496     for (children = bin->children; children; children = g_list_next (children)) {
497       GstElement *child = GST_ELEMENT (children->data);
498
499       res &= gst_element_set_clock (child, clock);
500     }
501   }
502   GST_OBJECT_UNLOCK (bin);
503
504   return res;
505 }
506
507 /* get the clock for this bin by asking all of the children in this bin
508  *
509  * The ref of the returned clock in increased so unref after usage.
510  *
511  * We loop the elements in state order and pick the last clock we can 
512  * get. This makes sure we get a clock from the source.
513  *
514  * MT safe
515  */
516 static GstClock *
517 gst_bin_provide_clock_func (GstElement * element)
518 {
519   GstClock *result = NULL;
520   GstElement *provider = NULL;
521   GstBin *bin;
522   GstIterator *it;
523   gpointer val;
524   GstClock **provided_clock_p;
525   GstElement **clock_provider_p;
526
527   bin = GST_BIN (element);
528
529   GST_OBJECT_LOCK (bin);
530   if (!bin->clock_dirty)
531     goto not_dirty;
532
533   GST_DEBUG_OBJECT (bin, "finding new clock");
534
535   it = gst_bin_sort_iterator_new (bin);
536
537   while (it->next (it, &val) == GST_ITERATOR_OK) {
538     GstElement *child = GST_ELEMENT_CAST (val);
539     GstClock *clock;
540
541     clock = gst_element_provide_clock (child);
542     if (clock) {
543       GST_DEBUG_OBJECT (bin, "found candidate clock %p by element %s",
544           clock, GST_ELEMENT_NAME (child));
545       if (result) {
546         gst_object_unref (result);
547         gst_object_unref (provider);
548       }
549       result = clock;
550       provider = child;
551     } else {
552       gst_object_unref (child);
553     }
554   }
555
556   provided_clock_p = &bin->provided_clock;
557   clock_provider_p = &bin->clock_provider;
558   gst_object_replace ((GstObject **) provided_clock_p, (GstObject *) result);
559   gst_object_replace ((GstObject **) clock_provider_p, (GstObject *) provider);
560   bin->clock_dirty = FALSE;
561   GST_DEBUG_OBJECT (bin,
562       "provided new clock %" GST_PTR_FORMAT " by provider %" GST_PTR_FORMAT,
563       result, provider);
564   /* Provider is not being returned to caller, just the result */
565   if (provider)
566     gst_object_unref (provider);
567   GST_OBJECT_UNLOCK (bin);
568
569   gst_iterator_free (it);
570
571   return result;
572
573 not_dirty:
574   {
575     if ((result = bin->provided_clock))
576       gst_object_ref (result);
577     GST_DEBUG_OBJECT (bin, "returning old clock %p", result);
578     GST_OBJECT_UNLOCK (bin);
579
580     return result;
581   }
582 }
583
584 /*
585  * functions for manipulating cached messages
586  */
587 typedef struct
588 {
589   GstObject *src;
590   GstMessageType types;
591 } MessageFind;
592
593 /* check if a message is of given src and type */
594 static gint
595 message_check (GstMessage * message, MessageFind * target)
596 {
597   gboolean eq = TRUE;
598
599   if (target->src)
600     eq &= GST_MESSAGE_SRC (message) == target->src;
601   if (target->types)
602     eq &= (GST_MESSAGE_TYPE (message) & target->types) != 0;
603
604   return (eq ? 0 : 1);
605 }
606
607 /* with LOCK, returns TRUE if message had a valid SRC, takes ref on
608  * the message. 
609  *
610  * A message that is cached and has the same SRC and type is replaced
611  * by the given message.
612  */
613 static gboolean
614 bin_replace_message (GstBin * bin, GstMessage * message, GstMessageType types)
615 {
616   GList *previous;
617   GstObject *src;
618   gboolean res = TRUE;
619   const gchar *name;
620
621   name = GST_MESSAGE_TYPE_NAME (message);
622
623   if ((src = GST_MESSAGE_SRC (message))) {
624     MessageFind find;
625
626     find.src = src;
627     find.types = types;
628
629     /* first find the previous message posted by this element */
630     previous = g_list_find_custom (bin->messages, &find,
631         (GCompareFunc) message_check);
632     if (previous) {
633       /* if we found a previous message, replace it */
634       gst_message_unref (previous->data);
635       previous->data = message;
636
637       GST_DEBUG_OBJECT (bin, "replace old message %s from %s",
638           name, GST_ELEMENT_NAME (src));
639     } else {
640       /* keep new message */
641       bin->messages = g_list_prepend (bin->messages, message);
642
643       GST_DEBUG_OBJECT (bin, "got new message %s from %s",
644           name, GST_ELEMENT_NAME (src));
645     }
646   } else {
647     GST_DEBUG_OBJECT (bin, "got message %s from (NULL), not processing", name);
648     res = FALSE;
649     gst_message_unref (message);
650   }
651   return res;
652 }
653
654 /* with LOCK. Remove all messages of given types */
655 static void
656 bin_remove_messages (GstBin * bin, GstObject * src, GstMessageType types)
657 {
658   MessageFind find;
659   GList *walk, *next;
660
661   find.src = src;
662   find.types = types;
663
664   for (walk = bin->messages; walk; walk = next) {
665     GstMessage *message = (GstMessage *) walk->data;
666
667     next = g_list_next (walk);
668
669     if (message_check (message, &find) == 0) {
670       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (message),
671           "deleting message of types %d", types);
672       bin->messages = g_list_delete_link (bin->messages, walk);
673       gst_message_unref (message);
674     } else {
675       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (message),
676           "not deleting message of type %d", GST_MESSAGE_TYPE (message));
677     }
678   }
679 }
680
681
682 /* Check if the bin is EOS. We do this by scanning all sinks and
683  * checking if they posted an EOS message.
684  *
685  * call with bin LOCK */
686 static gboolean
687 is_eos (GstBin * bin)
688 {
689   gboolean result;
690   GList *walk;
691
692   result = TRUE;
693   for (walk = bin->children; walk; walk = g_list_next (walk)) {
694     GstElement *element;
695
696     element = GST_ELEMENT_CAST (walk->data);
697     if (bin_element_is_sink (element, bin) == 0) {
698       MessageFind find;
699
700       /* check if element posted EOS */
701       find.src = GST_OBJECT_CAST (element);
702       find.types = GST_MESSAGE_EOS;
703
704       if (g_list_find_custom (bin->messages, &find,
705               (GCompareFunc) message_check)) {
706         GST_DEBUG ("element posted EOS");
707       } else {
708         GST_DEBUG ("element did not post EOS yet");
709         result = FALSE;
710         break;
711       }
712     }
713   }
714   return result;
715 }
716
717 static void
718 unlink_pads (GstPad * pad)
719 {
720   GstPad *peer;
721
722   if ((peer = gst_pad_get_peer (pad))) {
723     if (gst_pad_get_direction (pad) == GST_PAD_SRC)
724       gst_pad_unlink (pad, peer);
725     else
726       gst_pad_unlink (peer, pad);
727     gst_object_unref (peer);
728   }
729   gst_object_unref (pad);
730 }
731
732 /* vmethod that adds an element to a bin
733  *
734  * MT safe
735  */
736 static gboolean
737 gst_bin_add_func (GstBin * bin, GstElement * element)
738 {
739   gchar *elem_name;
740   GstIterator *it;
741   gboolean is_sink;
742   GstMessage *clock_message = NULL;
743
744   /* we obviously can't add ourself to ourself */
745   if (G_UNLIKELY (GST_ELEMENT_CAST (element) == GST_ELEMENT_CAST (bin)))
746     goto adding_itself;
747
748   /* get the element name to make sure it is unique in this bin. */
749   GST_OBJECT_LOCK (element);
750   elem_name = g_strdup (GST_ELEMENT_NAME (element));
751   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_IS_SINK);
752   GST_OBJECT_UNLOCK (element);
753
754   GST_OBJECT_LOCK (bin);
755
756   /* then check to see if the element's name is already taken in the bin,
757    * we can safely take the lock here. This check is probably bogus because
758    * you can safely change the element name after this check and before setting
759    * the object parent. The window is very small though... */
760   if (G_UNLIKELY (!gst_object_check_uniqueness (bin->children, elem_name)))
761     goto duplicate_name;
762
763   /* set the element's parent and add the element to the bin's list of children */
764   if (G_UNLIKELY (!gst_object_set_parent (GST_OBJECT_CAST (element),
765               GST_OBJECT_CAST (bin))))
766     goto had_parent;
767
768   /* if we add a sink we become a sink */
769   if (is_sink) {
770     GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "element \"%s\" was sink",
771         elem_name);
772     GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_IS_SINK);
773   }
774   if (gst_element_provides_clock (element)) {
775     GST_DEBUG_OBJECT (bin, "element \"%s\" can provide a clock", elem_name);
776     bin->clock_dirty = TRUE;
777     clock_message =
778         gst_message_new_clock_provide (GST_OBJECT_CAST (bin), NULL, TRUE);
779   }
780
781   bin->children = g_list_prepend (bin->children, element);
782   bin->numchildren++;
783   bin->children_cookie++;
784
785   /* distribute the bus */
786   gst_element_set_bus (element, bin->child_bus);
787
788   /* propagate the current base time and clock */
789   gst_element_set_base_time (element, GST_ELEMENT (bin)->base_time);
790   /* it's possible that the element did not accept the clock but
791    * that is not important right now. When the pipeline goes to PLAYING,
792    * a new clock will be selected */
793   gst_element_set_clock (element, GST_ELEMENT_CLOCK (bin));
794   bin->state_dirty = TRUE;
795   GST_OBJECT_UNLOCK (bin);
796
797   if (clock_message) {
798     gst_element_post_message (GST_ELEMENT_CAST (bin), clock_message);
799   }
800
801   /* unlink all linked pads */
802   it = gst_element_iterate_pads (element);
803   gst_iterator_foreach (it, (GFunc) unlink_pads, element);
804   gst_iterator_free (it);
805
806   GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "added element \"%s\"",
807       elem_name);
808   g_free (elem_name);
809
810   g_signal_emit (G_OBJECT (bin), gst_bin_signals[ELEMENT_ADDED], 0, element);
811
812   return TRUE;
813
814   /* ERROR handling here */
815 adding_itself:
816   {
817     GST_OBJECT_LOCK (bin);
818     g_warning ("Cannot add bin %s to itself", GST_ELEMENT_NAME (bin));
819     GST_OBJECT_UNLOCK (bin);
820     return FALSE;
821   }
822 duplicate_name:
823   {
824     g_warning ("Name %s is not unique in bin %s, not adding",
825         elem_name, GST_ELEMENT_NAME (bin));
826     GST_OBJECT_UNLOCK (bin);
827     g_free (elem_name);
828     return FALSE;
829   }
830 had_parent:
831   {
832     g_warning ("Element %s already has parent", elem_name);
833     GST_OBJECT_UNLOCK (bin);
834     g_free (elem_name);
835     return FALSE;
836   }
837 }
838
839
840 /**
841  * gst_bin_add:
842  * @bin: a #GstBin
843  * @element: the #GstElement to add
844  *
845  * Adds the given element to the bin.  Sets the element's parent, and thus
846  * takes ownership of the element. An element can only be added to one bin.
847  *
848  * If the element's pads are linked to other pads, the pads will be unlinked
849  * before the element is added to the bin.
850  *
851  * MT safe.
852  *
853  * Returns: TRUE if the element could be added, FALSE if
854  * the bin does not want to accept the element.
855  */
856 gboolean
857 gst_bin_add (GstBin * bin, GstElement * element)
858 {
859   GstBinClass *bclass;
860   gboolean result;
861
862   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
863   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
864
865   bclass = GST_BIN_GET_CLASS (bin);
866
867   if (G_UNLIKELY (bclass->add_element == NULL))
868     goto no_function;
869
870   GST_CAT_DEBUG (GST_CAT_PARENTAGE, "adding element %s to bin %s",
871       GST_ELEMENT_NAME (element), GST_ELEMENT_NAME (bin));
872
873   result = bclass->add_element (bin, element);
874
875   return result;
876
877   /* ERROR handling */
878 no_function:
879   {
880     g_warning ("adding elements to bin %s is not supported",
881         GST_ELEMENT_NAME (bin));
882     return FALSE;
883   }
884 }
885
886 /* remove an element from the bin
887  *
888  * MT safe
889  */
890 static gboolean
891 gst_bin_remove_func (GstBin * bin, GstElement * element)
892 {
893   gchar *elem_name;
894   GstIterator *it;
895   gboolean is_sink;
896   GstMessage *clock_message = NULL;
897
898   GST_OBJECT_LOCK (element);
899   /* Check if the element is already being removed and immediately
900    * return */
901   if (G_UNLIKELY (GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_UNPARENTING)))
902     goto already_removing;
903
904   GST_OBJECT_FLAG_SET (element, GST_ELEMENT_UNPARENTING);
905   /* grab element name so we can print it */
906   elem_name = g_strdup (GST_ELEMENT_NAME (element));
907   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_IS_SINK);
908   GST_OBJECT_UNLOCK (element);
909
910   /* unlink all linked pads */
911   it = gst_element_iterate_pads (element);
912   gst_iterator_foreach (it, (GFunc) unlink_pads, element);
913   gst_iterator_free (it);
914
915   GST_OBJECT_LOCK (bin);
916   /* the element must be in the bin's list of children */
917   if (G_UNLIKELY (g_list_find (bin->children, element) == NULL))
918     goto not_in_bin;
919
920   /* now remove the element from the list of elements */
921   bin->children = g_list_remove (bin->children, element);
922   bin->numchildren--;
923   bin->children_cookie++;
924
925   /* check if we removed a sink */
926   if (is_sink) {
927     GList *other_sink;
928
929     /* check if we removed the last sink */
930     other_sink = g_list_find_custom (bin->children,
931         bin, (GCompareFunc) bin_element_is_sink);
932     if (!other_sink) {
933       /* yups, we're not a sink anymore */
934       GST_OBJECT_FLAG_UNSET (bin, GST_ELEMENT_IS_SINK);
935     }
936   }
937
938   /* if the clock provider for this element is removed, we lost
939    * the clock as well, we need to inform the parent of this
940    * so that it can select a new clock */
941   if (bin->clock_provider == element) {
942     GST_DEBUG_OBJECT (bin, "element \"%s\" provided the clock", elem_name);
943     bin->clock_dirty = TRUE;
944     clock_message =
945         gst_message_new_clock_lost (GST_OBJECT_CAST (bin), bin->provided_clock);
946   }
947
948   bin->state_dirty = TRUE;
949   GST_OBJECT_UNLOCK (bin);
950
951   if (clock_message) {
952     gst_element_post_message (GST_ELEMENT_CAST (bin), clock_message);
953   }
954
955   GST_CAT_INFO_OBJECT (GST_CAT_PARENTAGE, bin, "removed child \"%s\"",
956       elem_name);
957   g_free (elem_name);
958
959   gst_element_set_bus (element, NULL);
960
961   /* Clear the clock we provided to the element */
962   gst_element_set_clock (element, NULL);
963
964   /* we ref here because after the _unparent() the element can be disposed
965    * and we still need it to reset the UNPARENTING flag and fire a signal. */
966   gst_object_ref (element);
967   gst_object_unparent (GST_OBJECT_CAST (element));
968
969   GST_OBJECT_LOCK (element);
970   GST_OBJECT_FLAG_UNSET (element, GST_ELEMENT_UNPARENTING);
971   GST_OBJECT_UNLOCK (element);
972
973   g_signal_emit (G_OBJECT (bin), gst_bin_signals[ELEMENT_REMOVED], 0, element);
974
975   /* element is really out of our control now */
976   gst_object_unref (element);
977
978   return TRUE;
979
980   /* ERROR handling */
981 not_in_bin:
982   {
983     g_warning ("Element %s is not in bin %s", elem_name,
984         GST_ELEMENT_NAME (bin));
985     GST_OBJECT_UNLOCK (bin);
986     g_free (elem_name);
987     return FALSE;
988   }
989 already_removing:
990   {
991     GST_OBJECT_UNLOCK (element);
992     return FALSE;
993   }
994 }
995
996 /**
997  * gst_bin_remove:
998  * @bin: a #GstBin
999  * @element: the #GstElement to remove
1000  *
1001  * Removes the element from the bin, unparenting it as well.
1002  * Unparenting the element means that the element will be dereferenced,
1003  * so if the bin holds the only reference to the element, the element
1004  * will be freed in the process of removing it from the bin.  If you
1005  * want the element to still exist after removing, you need to call
1006  * gst_object_ref() before removing it from the bin.
1007  *
1008  * If the element's pads are linked to other pads, the pads will be unlinked
1009  * before the element is removed from the bin.
1010  *
1011  * MT safe.
1012  *
1013  * Returns: TRUE if the element could be removed, FALSE if
1014  * the bin does not want to remove the element.
1015  */
1016 gboolean
1017 gst_bin_remove (GstBin * bin, GstElement * element)
1018 {
1019   GstBinClass *bclass;
1020   gboolean result;
1021
1022   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
1023   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1024
1025   bclass = GST_BIN_GET_CLASS (bin);
1026
1027   if (G_UNLIKELY (bclass->remove_element == NULL))
1028     goto no_function;
1029
1030   GST_CAT_DEBUG (GST_CAT_PARENTAGE, "removing element %s from bin %s",
1031       GST_ELEMENT_NAME (element), GST_ELEMENT_NAME (bin));
1032
1033   result = bclass->remove_element (bin, element);
1034
1035   return result;
1036
1037   /* ERROR handling */
1038 no_function:
1039   {
1040     g_warning ("removing elements from bin %s is not supported",
1041         GST_ELEMENT_NAME (bin));
1042     return FALSE;
1043   }
1044 }
1045
1046 static GstIteratorItem
1047 iterate_child (GstIterator * it, GstElement * child)
1048 {
1049   gst_object_ref (child);
1050   return GST_ITERATOR_ITEM_PASS;
1051 }
1052
1053 /**
1054  * gst_bin_iterate_elements:
1055  * @bin: a #GstBin
1056  *
1057  * Gets an iterator for the elements in this bin.
1058  *
1059  * Each element yielded by the iterator will have its refcount increased, so
1060  * unref after use.
1061  *
1062  * MT safe.  Caller owns returned value.
1063  *
1064  * Returns: a #GstIterator of #GstElement, or NULL
1065  */
1066 GstIterator *
1067 gst_bin_iterate_elements (GstBin * bin)
1068 {
1069   GstIterator *result;
1070
1071   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1072
1073   GST_OBJECT_LOCK (bin);
1074   /* add ref because the iterator refs the bin. When the iterator
1075    * is freed it will unref the bin again using the provided dispose
1076    * function. */
1077   gst_object_ref (bin);
1078   result = gst_iterator_new_list (GST_TYPE_ELEMENT,
1079       GST_OBJECT_GET_LOCK (bin),
1080       &bin->children_cookie,
1081       &bin->children,
1082       bin,
1083       (GstIteratorItemFunction) iterate_child,
1084       (GstIteratorDisposeFunction) gst_object_unref);
1085   GST_OBJECT_UNLOCK (bin);
1086
1087   return result;
1088 }
1089
1090 static GstIteratorItem
1091 iterate_child_recurse (GstIterator * it, GstElement * child)
1092 {
1093   gst_object_ref (child);
1094   if (GST_IS_BIN (child)) {
1095     GstIterator *other = gst_bin_iterate_recurse (GST_BIN (child));
1096
1097     gst_iterator_push (it, other);
1098   }
1099   return GST_ITERATOR_ITEM_PASS;
1100 }
1101
1102 /**
1103  * gst_bin_iterate_recurse:
1104  * @bin: a #GstBin
1105  *
1106  * Gets an iterator for the elements in this bin.
1107  * This iterator recurses into GstBin children.
1108  *
1109  * Each element yielded by the iterator will have its refcount increased, so
1110  * unref after use.
1111  *
1112  * MT safe.  Caller owns returned value.
1113  *
1114  * Returns: a #GstIterator of #GstElement, or NULL
1115  */
1116 GstIterator *
1117 gst_bin_iterate_recurse (GstBin * bin)
1118 {
1119   GstIterator *result;
1120
1121   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1122
1123   GST_OBJECT_LOCK (bin);
1124   /* add ref because the iterator refs the bin. When the iterator
1125    * is freed it will unref the bin again using the provided dispose
1126    * function. */
1127   gst_object_ref (bin);
1128   result = gst_iterator_new_list (GST_TYPE_ELEMENT,
1129       GST_OBJECT_GET_LOCK (bin),
1130       &bin->children_cookie,
1131       &bin->children,
1132       bin,
1133       (GstIteratorItemFunction) iterate_child_recurse,
1134       (GstIteratorDisposeFunction) gst_object_unref);
1135   GST_OBJECT_UNLOCK (bin);
1136
1137   return result;
1138 }
1139
1140 /* returns 0 when TRUE because this is a GCompareFunc */
1141 /* MT safe */
1142 static gint
1143 bin_element_is_sink (GstElement * child, GstBin * bin)
1144 {
1145   gboolean is_sink;
1146
1147   /* we lock the child here for the remainder of the function to
1148    * get its name and flag safely. */
1149   GST_OBJECT_LOCK (child);
1150   is_sink = GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_IS_SINK);
1151
1152   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
1153       "child %s %s sink", GST_OBJECT_NAME (child), is_sink ? "is" : "is not");
1154
1155   GST_OBJECT_UNLOCK (child);
1156   return is_sink ? 0 : 1;
1157 }
1158
1159 static gint
1160 sink_iterator_filter (GstElement * child, GstBin * bin)
1161 {
1162   if (bin_element_is_sink (child, bin) == 0) {
1163     /* returns 0 because this is a GCompareFunc */
1164     return 0;
1165   } else {
1166     /* child carries a ref from gst_bin_iterate_elements -- drop if not passing
1167        through */
1168     gst_object_unref (child);
1169     return 1;
1170   }
1171 }
1172
1173 /**
1174  * gst_bin_iterate_sinks:
1175  * @bin: a #GstBin
1176  *
1177  * Gets an iterator for all elements in the bin that have the
1178  * #GST_ELEMENT_IS_SINK flag set.
1179  *
1180  * Each element yielded by the iterator will have its refcount increased, so
1181  * unref after use.
1182  *
1183  * MT safe.  Caller owns returned value.
1184  *
1185  * Returns: a #GstIterator of #GstElement, or NULL
1186  */
1187 GstIterator *
1188 gst_bin_iterate_sinks (GstBin * bin)
1189 {
1190   GstIterator *children;
1191   GstIterator *result;
1192
1193   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1194
1195   children = gst_bin_iterate_elements (bin);
1196   result = gst_iterator_filter (children,
1197       (GCompareFunc) sink_iterator_filter, bin);
1198
1199   return result;
1200 }
1201
1202 /* returns 0 when TRUE because this is a GCompareFunc */
1203 /* MT safe */
1204 static gint
1205 bin_element_is_src (GstElement * child, GstBin * bin)
1206 {
1207   gboolean is_src = FALSE;
1208
1209   /* we lock the child here for the remainder of the function to
1210    * get its name and flag safely. */
1211   GST_OBJECT_LOCK (child);
1212   if (!GST_OBJECT_FLAG_IS_SET (child, GST_ELEMENT_IS_SINK) &&
1213       !child->numsinkpads) {
1214     is_src = TRUE;
1215   }
1216
1217   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
1218       "child %s %s src", GST_OBJECT_NAME (child), is_src ? "is" : "is not");
1219
1220   GST_OBJECT_UNLOCK (child);
1221   return is_src ? 0 : 1;
1222 }
1223
1224 static gint
1225 src_iterator_filter (GstElement * child, GstBin * bin)
1226 {
1227   if (bin_element_is_src (child, bin) == 0) {
1228     /* returns 0 because this is a GCompareFunc */
1229     return 0;
1230   } else {
1231     /* child carries a ref from gst_bin_iterate_elements -- drop if not passing
1232        through */
1233     gst_object_unref (child);
1234     return 1;
1235   }
1236 }
1237
1238 /**
1239  * gst_bin_iterate_sources:
1240  * @bin: a #GstBin
1241  *
1242  * Gets an iterator for all elements in the bin that have the
1243  * #GST_ELEMENT_IS_SRC flag set.
1244  *
1245  * Each element yielded by the iterator will have its refcount increased, so
1246  * unref after use.
1247  *
1248  * MT safe.  Caller owns returned value.
1249  *
1250  * Returns: a #GstIterator of #GstElement, or NULL
1251  */
1252 GstIterator *
1253 gst_bin_iterate_sources (GstBin * bin)
1254 {
1255   GstIterator *children;
1256   GstIterator *result;
1257
1258   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1259
1260   children = gst_bin_iterate_elements (bin);
1261   result = gst_iterator_filter (children,
1262       (GCompareFunc) src_iterator_filter, bin);
1263
1264   return result;
1265 }
1266
1267 /*
1268  * MT safe
1269  */
1270 static GstStateChangeReturn
1271 gst_bin_get_state_func (GstElement * element, GstState * state,
1272     GstState * pending, GstClockTime timeout)
1273 {
1274   GstBin *bin = GST_BIN (element);
1275   GstStateChangeReturn ret;
1276
1277   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "getting state");
1278
1279   /* do a non forced recalculation of the state */
1280   gst_bin_recalc_state (bin, FALSE);
1281
1282   ret = parent_class->get_state (element, state, pending, timeout);
1283
1284   return ret;
1285 }
1286
1287 static void
1288 gst_bin_recalc_state (GstBin * bin, gboolean force)
1289 {
1290   GstStateChangeReturn ret;
1291   GList *children;
1292   guint32 children_cookie;
1293   guint32 state_cookie;
1294   gboolean have_no_preroll;
1295   gboolean have_async;
1296
1297   ret = GST_STATE_CHANGE_SUCCESS;
1298
1299   /* lock bin, no element can be added or removed while we have this lock */
1300   GST_OBJECT_LOCK (bin);
1301   /* forced recalc, make state dirty again */
1302   if (force)
1303     bin->state_dirty = TRUE;
1304
1305   /* no point in scanning if nothing changed and it's no forced recalc */
1306   if (!bin->state_dirty)
1307     goto not_dirty;
1308
1309   /* no point in having two scans run concurrently */
1310   if (bin->polling)
1311     goto was_polling;
1312
1313   bin->polling = TRUE;
1314   state_cookie = GST_ELEMENT_CAST (bin)->state_cookie;
1315
1316   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "recalc state");
1317
1318 restart:
1319   /* when we leave this function, the state must not be dirty, whenever
1320    * we are scanning and the state becomes dirty again, we restart. */
1321   bin->state_dirty = FALSE;
1322
1323   have_no_preroll = FALSE;
1324   have_async = FALSE;
1325
1326   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "checking element states");
1327
1328   /* scan all element states with a zero timeout so we don't block on
1329    * anything */
1330   children = bin->children;
1331   children_cookie = bin->children_cookie;
1332   while (children) {
1333     GstElement *child = GST_ELEMENT_CAST (children->data);
1334
1335     gst_object_ref (child);
1336     /* now we release the lock to enter a non blocking wait. We
1337      * release the lock anyway since we can. */
1338     GST_OBJECT_UNLOCK (bin);
1339
1340     ret = gst_element_get_state (child, NULL, NULL, 0);
1341
1342     gst_object_unref (child);
1343
1344     /* now grab the lock to iterate to the next child */
1345     GST_OBJECT_LOCK (bin);
1346     if (G_UNLIKELY (children_cookie != bin->children_cookie)) {
1347       /* child added/removed during state change, restart. We need
1348        * to restart with the quick check as a no-preroll element could
1349        * have been added here and we don't want to block on sinks then.*/
1350       GST_DEBUG_OBJECT (bin, "children added or removed, restarting recalc");
1351       goto restart;
1352     }
1353     if (state_cookie != GST_ELEMENT_CAST (bin)->state_cookie) {
1354       GST_DEBUG_OBJECT (bin, "concurrent state change");
1355       goto concurrent_state;
1356     }
1357     if (bin->state_dirty) {
1358       GST_DEBUG_OBJECT (bin, "state dirty again, restarting recalc");
1359       goto restart;
1360     }
1361
1362     switch (ret) {
1363       case GST_STATE_CHANGE_FAILURE:
1364         /* report FAILURE  immediatly */
1365         goto done;
1366       case GST_STATE_CHANGE_NO_PREROLL:
1367         /* we have to continue scanning as there might be
1368          * ERRORS too */
1369         have_no_preroll = TRUE;
1370         break;
1371       case GST_STATE_CHANGE_ASYNC:
1372         /* we have to continue scanning as there might be
1373          * ERRORS too */
1374         have_async = TRUE;
1375         break;
1376       default:
1377         break;
1378     }
1379     children = g_list_next (children);
1380   }
1381   /* if we get here, we have no FAILURES */
1382
1383   /* if we have NO_PREROLL, return that */
1384   if (have_no_preroll) {
1385     ret = GST_STATE_CHANGE_NO_PREROLL;
1386   }
1387   /* else return ASYNC if async elements where found. */
1388   else if (have_async) {
1389     ret = GST_STATE_CHANGE_ASYNC;
1390   }
1391
1392 done:
1393   bin->polling = FALSE;
1394   GST_OBJECT_UNLOCK (bin);
1395
1396   /* now we can take the state lock, it is possible that new elements
1397    * are added now and we still report the old state. No problem though as
1398    * the return is still consistent, the effect is as if the element was
1399    * added after this function completed. */
1400   switch (ret) {
1401     case GST_STATE_CHANGE_SUCCESS:
1402     case GST_STATE_CHANGE_NO_PREROLL:
1403       ret = gst_element_continue_state (GST_ELEMENT_CAST (bin), ret);
1404       break;
1405     case GST_STATE_CHANGE_ASYNC:
1406       gst_element_lost_state (GST_ELEMENT_CAST (bin));
1407       break;
1408     case GST_STATE_CHANGE_FAILURE:
1409       gst_element_abort_state (GST_ELEMENT_CAST (bin));
1410       break;
1411     default:
1412       goto unknown_state;
1413   }
1414
1415   GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "bin RETURN is now %d", ret);
1416
1417   return;
1418
1419 not_dirty:
1420   {
1421     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "not dirty");
1422     GST_OBJECT_UNLOCK (bin);
1423     return;
1424   }
1425 was_polling:
1426   {
1427     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "was polling");
1428     GST_OBJECT_UNLOCK (bin);
1429     return;
1430   }
1431 concurrent_state:
1432   {
1433     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin, "concurrent_state");
1434     bin->polling = FALSE;
1435     GST_OBJECT_UNLOCK (bin);
1436     return;
1437   }
1438 unknown_state:
1439   {
1440     /* somebody added a GST_STATE_ and forgot to do stuff here ! */
1441     GST_CAT_INFO_OBJECT (GST_CAT_STATES, bin,
1442         "unknown return value %d from a state change function", ret);
1443     g_critical ("unknown return value %d from a state change function", ret);
1444     GST_STATE_RETURN (bin) = GST_STATE_CHANGE_FAILURE;
1445     GST_STATE_UNLOCK (bin);
1446     return;
1447   }
1448 }
1449
1450 /***********************************************
1451  * Topologically sorted iterator
1452  * see http://en.wikipedia.org/wiki/Topological_sorting
1453  *
1454  * For each element in the graph, an entry is kept in a HashTable
1455  * with its number of srcpad connections (degree).
1456  * We then change state of all elements without dependencies
1457  * (degree 0) and decrement the degree of all elements connected
1458  * on the sinkpads. When an element reaches degree 0, its state is
1459  * changed next.
1460  * When all elements are handled the algorithm stops.
1461  */
1462 typedef struct _GstBinSortIterator
1463 {
1464   GstIterator it;
1465   GQueue *queue;                /* elements queued for state change */
1466   GstBin *bin;                  /* bin we iterate */
1467   gint mode;                    /* adding or removing dependency */
1468   GstElement *best;             /* next element with least dependencies */
1469   gint best_deg;                /* best degree */
1470   GHashTable *hash;             /* hashtable with element dependencies */
1471 } GstBinSortIterator;
1472
1473 /* we add and subtract 1 to make sure we don't confuse NULL and 0 */
1474 #define HASH_SET_DEGREE(bit, elem, deg) \
1475     g_hash_table_replace (bit->hash, elem, GINT_TO_POINTER(deg+1))
1476 #define HASH_GET_DEGREE(bit, elem) \
1477     (GPOINTER_TO_INT(g_hash_table_lookup (bit->hash, elem))-1)
1478
1479 /* add element to queue of next elements in the iterator.
1480  * We push at the tail to give higher priority elements a
1481  * chance first */
1482 static void
1483 add_to_queue (GstBinSortIterator * bit, GstElement * element)
1484 {
1485   GST_DEBUG_OBJECT (bit->bin, "%s add to queue", GST_ELEMENT_NAME (element));
1486   gst_object_ref (element);
1487   g_queue_push_tail (bit->queue, element);
1488   HASH_SET_DEGREE (bit, element, -1);
1489 }
1490
1491 /* clear the queue, unref all objects as we took a ref when
1492  * we added them to the queue */
1493 static void
1494 clear_queue (GQueue * queue)
1495 {
1496   gpointer p;
1497
1498   while ((p = g_queue_pop_head (queue)))
1499     gst_object_unref (p);
1500 }
1501
1502 /* set all degrees to 0. Elements marked as a sink are
1503  * added to the queue immediatly. */
1504 static void
1505 reset_degree (GstElement * element, GstBinSortIterator * bit)
1506 {
1507   gboolean is_sink;
1508
1509   /* sinks are added right away */
1510   GST_OBJECT_LOCK (element);
1511   is_sink = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_IS_SINK);
1512   GST_OBJECT_UNLOCK (element);
1513
1514   if (is_sink) {
1515     add_to_queue (bit, element);
1516   } else {
1517     /* others are marked with 0 and handled when sinks are done */
1518     HASH_SET_DEGREE (bit, element, 0);
1519   }
1520 }
1521
1522 /* adjust the degree of all elements connected to the given
1523  * element. If an degree of an element drops to 0, it is
1524  * added to the queue of elements to schedule next.
1525  *
1526  * We have to make sure not to cross the bin boundary this element
1527  * belongs to.
1528  */
1529 static void
1530 update_degree (GstElement * element, GstBinSortIterator * bit)
1531 {
1532   gboolean linked = FALSE;
1533
1534   GST_OBJECT_LOCK (element);
1535   /* don't touch degree if element has no sourcepads */
1536   if (element->numsinkpads != 0) {
1537     /* loop over all sinkpads, decrement degree for all connected
1538      * elements in this bin */
1539     GList *pads;
1540
1541     for (pads = element->sinkpads; pads; pads = g_list_next (pads)) {
1542       GstPad *peer;
1543
1544       if ((peer = gst_pad_get_peer (GST_PAD_CAST (pads->data)))) {
1545         GstElement *peer_element;
1546
1547         if ((peer_element = gst_pad_get_parent_element (peer))) {
1548           GST_OBJECT_LOCK (peer_element);
1549           /* check that we don't go outside of this bin */
1550           if (GST_OBJECT_CAST (peer_element)->parent ==
1551               GST_OBJECT_CAST (bit->bin)) {
1552             gint old_deg, new_deg;
1553
1554             old_deg = HASH_GET_DEGREE (bit, peer_element);
1555             new_deg = old_deg + bit->mode;
1556
1557             GST_DEBUG_OBJECT (bit->bin,
1558                 "change element %s, degree %d->%d, linked to %s",
1559                 GST_ELEMENT_NAME (peer_element), old_deg, new_deg,
1560                 GST_ELEMENT_NAME (element));
1561
1562             /* update degree */
1563             if (new_deg == 0) {
1564               /* degree hit 0, add to queue */
1565               add_to_queue (bit, peer_element);
1566             } else {
1567               HASH_SET_DEGREE (bit, peer_element, new_deg);
1568             }
1569             linked = TRUE;
1570           }
1571           GST_OBJECT_UNLOCK (peer_element);
1572           gst_object_unref (peer_element);
1573         }
1574         gst_object_unref (peer);
1575       }
1576     }
1577   }
1578   if (!linked) {
1579     GST_DEBUG_OBJECT (bit->bin, "element %s not linked on any sinkpads",
1580         GST_ELEMENT_NAME (element));
1581   }
1582   GST_OBJECT_UNLOCK (element);
1583 }
1584
1585 /* find the next best element not handled yet. This is the one
1586  * with the lowest non-negative degree */
1587 static void
1588 find_element (GstElement * element, GstBinSortIterator * bit)
1589 {
1590   gint degree;
1591
1592   /* element is already handled */
1593   if ((degree = HASH_GET_DEGREE (bit, element)) < 0)
1594     return;
1595
1596   /* first element or element with smaller degree */
1597   if (bit->best == NULL || bit->best_deg > degree) {
1598     bit->best = element;
1599     bit->best_deg = degree;
1600   }
1601 }
1602
1603 /* get next element in iterator. the returned element has the
1604  * refcount increased */
1605 static GstIteratorResult
1606 gst_bin_sort_iterator_next (GstBinSortIterator * bit, gpointer * result)
1607 {
1608   GstBin *bin = bit->bin;
1609
1610   /* empty queue, we have to find a next best element */
1611   if (g_queue_is_empty (bit->queue)) {
1612     GstElement *best;
1613
1614     bit->best = NULL;
1615     bit->best_deg = G_MAXINT;
1616     g_list_foreach (bin->children, (GFunc) find_element, bit);
1617     if ((best = bit->best)) {
1618       if (bit->best_deg != 0) {
1619         /* we don't fail on this one yet */
1620         g_warning ("loop detected in the graph !!");
1621       }
1622       /* best unhandled element, schedule as next element */
1623       GST_DEBUG_OBJECT (bin, "queue empty, next best: %s",
1624           GST_ELEMENT_NAME (best));
1625       gst_object_ref (best);
1626       HASH_SET_DEGREE (bit, best, -1);
1627       *result = best;
1628     } else {
1629       GST_DEBUG_OBJECT (bin, "queue empty, elements exhausted");
1630       /* no more unhandled elements, we are done */
1631       return GST_ITERATOR_DONE;
1632     }
1633   } else {
1634     /* everything added to the queue got reffed */
1635     *result = g_queue_pop_head (bit->queue);
1636   }
1637
1638   GST_DEBUG_OBJECT (bin, "queue head gives %s", GST_ELEMENT_NAME (*result));
1639   /* update degrees of linked elements */
1640   update_degree (GST_ELEMENT_CAST (*result), bit);
1641
1642   return GST_ITERATOR_OK;
1643 }
1644
1645 /* clear queues, recalculate the degrees and restart. */
1646 static void
1647 gst_bin_sort_iterator_resync (GstBinSortIterator * bit)
1648 {
1649   GstBin *bin = bit->bin;
1650
1651   GST_DEBUG_OBJECT (bin, "resync");
1652   clear_queue (bit->queue);
1653   /* reset degrees */
1654   g_list_foreach (bin->children, (GFunc) reset_degree, bit);
1655   /* calc degrees, incrementing */
1656   bit->mode = 1;
1657   g_list_foreach (bin->children, (GFunc) update_degree, bit);
1658   /* for the rest of the function we decrement the degrees */
1659   bit->mode = -1;
1660 }
1661
1662 /* clear queues, unref bin and free iterator. */
1663 static void
1664 gst_bin_sort_iterator_free (GstBinSortIterator * bit)
1665 {
1666   GstBin *bin = bit->bin;
1667
1668   GST_DEBUG_OBJECT (bin, "free");
1669   clear_queue (bit->queue);
1670   g_queue_free (bit->queue);
1671   g_hash_table_destroy (bit->hash);
1672   gst_object_unref (bin);
1673   g_free (bit);
1674 }
1675
1676 /* should be called with the bin LOCK held */
1677 static GstIterator *
1678 gst_bin_sort_iterator_new (GstBin * bin)
1679 {
1680   GstBinSortIterator *result;
1681
1682   /* we don't need an ItemFunction because we ref the items in the _next
1683    * method already */
1684   result = (GstBinSortIterator *)
1685       gst_iterator_new (sizeof (GstBinSortIterator),
1686       GST_TYPE_ELEMENT,
1687       GST_OBJECT_GET_LOCK (bin),
1688       &bin->children_cookie,
1689       (GstIteratorNextFunction) gst_bin_sort_iterator_next,
1690       (GstIteratorItemFunction) NULL,
1691       (GstIteratorResyncFunction) gst_bin_sort_iterator_resync,
1692       (GstIteratorFreeFunction) gst_bin_sort_iterator_free);
1693   result->queue = g_queue_new ();
1694   result->hash = g_hash_table_new (NULL, NULL);
1695   gst_object_ref (bin);
1696   result->bin = bin;
1697   gst_bin_sort_iterator_resync (result);
1698
1699   return (GstIterator *) result;
1700 }
1701
1702 /**
1703  * gst_bin_iterate_sorted:
1704  * @bin: a #GstBin
1705  *
1706  * Gets an iterator for the elements in this bin in topologically
1707  * sorted order. This means that the elements are returned from
1708  * the most downstream elements (sinks) to the sources.
1709  *
1710  * This function is used internally to perform the state changes
1711  * of the bin elements.
1712  *
1713  * Each element yielded by the iterator will have its refcount increased, so
1714  * unref after use.
1715  *
1716  * MT safe.  Caller owns returned value.
1717  *
1718  * Returns: a #GstIterator of #GstElement, or NULL
1719  */
1720 GstIterator *
1721 gst_bin_iterate_sorted (GstBin * bin)
1722 {
1723   GstIterator *result;
1724
1725   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1726
1727   GST_OBJECT_LOCK (bin);
1728   result = gst_bin_sort_iterator_new (bin);
1729   GST_OBJECT_UNLOCK (bin);
1730
1731   return result;
1732 }
1733
1734 static GstStateChangeReturn
1735 gst_bin_element_set_state (GstBin * bin, GstElement * element, GstState pending)
1736 {
1737   GstStateChangeReturn ret;
1738   gboolean locked;
1739
1740   /* peel off the locked flag */
1741   GST_OBJECT_LOCK (element);
1742   locked = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_LOCKED_STATE);
1743   GST_OBJECT_UNLOCK (element);
1744
1745   /* skip locked elements */
1746   if (G_UNLIKELY (locked)) {
1747     GST_DEBUG_OBJECT (element,
1748         "element is locked, pretending state change succeeded");
1749     ret = GST_STATE_CHANGE_SUCCESS;
1750     goto done;
1751   }
1752
1753   /* change state */
1754   ret = gst_element_set_state (element, pending);
1755
1756 done:
1757   return ret;
1758 }
1759
1760 static GstStateChangeReturn
1761 gst_bin_change_state_func (GstElement * element, GstStateChange transition)
1762 {
1763   GstBin *bin;
1764   GstStateChangeReturn ret;
1765   GstState current, next;
1766   gboolean have_async;
1767   gboolean have_no_preroll;
1768   GstClockTime base_time;
1769   GstIterator *it;
1770   gboolean done;
1771
1772   /* we don't need to take the STATE_LOCK, it is already taken */
1773   current = GST_STATE_TRANSITION_CURRENT (transition);
1774   next = GST_STATE_TRANSITION_NEXT (transition);
1775
1776   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
1777       "changing state of children from %s to %s",
1778       gst_element_state_get_name (current), gst_element_state_get_name (next));
1779
1780   bin = GST_BIN_CAST (element);
1781
1782   switch (next) {
1783     case GST_STATE_PAUSED:
1784       /* Clear EOS list on next PAUSED */
1785       GST_OBJECT_LOCK (bin);
1786       GST_DEBUG_OBJECT (element, "clearing EOS elements");
1787       bin_remove_messages (bin, NULL, GST_MESSAGE_EOS);
1788       GST_OBJECT_UNLOCK (bin);
1789       break;
1790     case GST_STATE_READY:
1791       /* Clear message list on next READY */
1792       GST_OBJECT_LOCK (bin);
1793       GST_DEBUG_OBJECT (element, "clearing all cached messages");
1794       bin_remove_messages (bin, NULL, GST_MESSAGE_ANY);
1795       GST_OBJECT_UNLOCK (bin);
1796       break;
1797     default:
1798       break;
1799   }
1800
1801   /* iterate in state change order */
1802   it = gst_bin_iterate_sorted (bin);
1803
1804 restart:
1805   /* take base time */
1806   base_time = gst_element_get_base_time (element);
1807
1808   have_async = FALSE;
1809   have_no_preroll = FALSE;
1810
1811   done = FALSE;
1812   while (!done) {
1813     gpointer data;
1814
1815     switch (gst_iterator_next (it, &data)) {
1816       case GST_ITERATOR_OK:
1817       {
1818         GstElement *child;
1819
1820         child = GST_ELEMENT_CAST (data);
1821
1822         /* set base time on child */
1823         gst_element_set_base_time (child, base_time);
1824
1825         /* set state now */
1826         ret = gst_bin_element_set_state (bin, child, next);
1827
1828         switch (ret) {
1829           case GST_STATE_CHANGE_SUCCESS:
1830             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1831                 "child '%s' changed state to %d(%s) successfully",
1832                 GST_ELEMENT_NAME (child), next,
1833                 gst_element_state_get_name (next));
1834             break;
1835           case GST_STATE_CHANGE_ASYNC:
1836             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1837                 "child '%s' is changing state asynchronously",
1838                 GST_ELEMENT_NAME (child));
1839             have_async = TRUE;
1840             break;
1841           case GST_STATE_CHANGE_FAILURE:
1842             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1843                 "child '%s' failed to go to state %d(%s)",
1844                 GST_ELEMENT_NAME (child),
1845                 next, gst_element_state_get_name (next));
1846             gst_object_unref (child);
1847             goto done;
1848           case GST_STATE_CHANGE_NO_PREROLL:
1849             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1850                 "child '%s' changed state to %d(%s) successfully without preroll",
1851                 GST_ELEMENT_NAME (child), next,
1852                 gst_element_state_get_name (next));
1853             have_no_preroll = TRUE;
1854             break;
1855           default:
1856             g_assert_not_reached ();
1857             break;
1858         }
1859         gst_object_unref (child);
1860         break;
1861       }
1862       case GST_ITERATOR_RESYNC:
1863         GST_CAT_DEBUG (GST_CAT_STATES, "iterator doing resync");
1864         gst_iterator_resync (it);
1865         goto restart;
1866         break;
1867       default:
1868       case GST_ITERATOR_DONE:
1869         GST_CAT_DEBUG (GST_CAT_STATES, "iterator done");
1870         done = TRUE;
1871         break;
1872     }
1873   }
1874
1875   ret = parent_class->change_state (element, transition);
1876   if (ret == GST_STATE_CHANGE_FAILURE)
1877     goto done;
1878
1879   if (have_no_preroll) {
1880     ret = GST_STATE_CHANGE_NO_PREROLL;
1881   } else if (have_async) {
1882     ret = GST_STATE_CHANGE_ASYNC;
1883   }
1884
1885 done:
1886   gst_iterator_free (it);
1887
1888   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
1889       "done changing bin's state from %s to %s, now in %s, ret %d",
1890       gst_element_state_get_name (current),
1891       gst_element_state_get_name (next),
1892       gst_element_state_get_name (GST_STATE (element)), ret);
1893
1894   return ret;
1895 }
1896
1897 /*
1898  * This function is a utility event handler for seek events.
1899  * It will send the event to all sinks or sources depending on the
1900  * event-direction.
1901  *
1902  * Applications are free to override this behaviour and
1903  * implement their own seek handler, but this will work for
1904  * pretty much all cases in practice.
1905  */
1906 static gboolean
1907 gst_bin_send_event (GstElement * element, GstEvent * event)
1908 {
1909   GstBin *bin = GST_BIN (element);
1910   GstIterator *iter;
1911   gboolean res = TRUE;
1912   gboolean done = FALSE;
1913
1914   if (GST_EVENT_IS_DOWNSTREAM (event)) {
1915     iter = gst_bin_iterate_sources (bin);
1916     GST_DEBUG_OBJECT (bin, "Sending %s event to src children",
1917         GST_EVENT_TYPE_NAME (event));
1918   } else {
1919     iter = gst_bin_iterate_sinks (bin);
1920     GST_DEBUG_OBJECT (bin, "Sending %s event to sink children",
1921         GST_EVENT_TYPE_NAME (event));
1922   }
1923
1924   while (!done) {
1925     gpointer data;
1926
1927     switch (gst_iterator_next (iter, &data)) {
1928       case GST_ITERATOR_OK:
1929       {
1930         GstElement *child;
1931
1932         gst_event_ref (event);
1933         child = GST_ELEMENT_CAST (data);
1934         res &= gst_element_send_event (child, event);
1935         gst_object_unref (child);
1936         break;
1937       }
1938       case GST_ITERATOR_RESYNC:
1939         gst_iterator_resync (iter);
1940         res = TRUE;
1941         break;
1942       case GST_ITERATOR_DONE:
1943         done = TRUE;
1944         break;
1945       case GST_ITERATOR_ERROR:
1946         g_assert_not_reached ();
1947         break;
1948     }
1949   }
1950   gst_iterator_free (iter);
1951   gst_event_unref (event);
1952
1953   return res;
1954 }
1955
1956 static void
1957 gst_bin_recalc_func (GstBin * bin, gpointer data)
1958 {
1959   GST_DEBUG_OBJECT (bin, "doing state recalc");
1960   GST_STATE_LOCK (bin);
1961   gst_bin_recalc_state (bin, FALSE);
1962   GST_STATE_UNLOCK (bin);
1963   GST_DEBUG_OBJECT (bin, "state recalc done");
1964   gst_object_unref (bin);
1965 }
1966
1967 static GstBusSyncReply
1968 bin_bus_handler (GstBus * bus, GstMessage * message, GstBin * bin)
1969 {
1970
1971   GstBinClass *bclass;
1972
1973   bclass = GST_BIN_GET_CLASS (bin);
1974   if (bclass->handle_message)
1975     bclass->handle_message (bin, message);
1976   else
1977     gst_message_unref (message);
1978
1979   return GST_BUS_DROP;
1980 }
1981
1982 /* handle child messages:
1983  *
1984  * GST_MESSAGE_EOS: This message is only posted by sinks
1985  *     in the PLAYING state. If all sinks posted the EOS message, post
1986  *     one upwards.
1987  *
1988  * GST_MESSAGE_STATE_DIRTY: if we are the toplevel bin we do a state
1989  *     recalc. If we are not toplevel (we have a parent) we just post
1990  *     the message upwards.
1991  *
1992  * GST_MESSAGE_SEGMENT_START: just collect, never forward upwards. If an
1993  *     element posts segment_start twice, only the last message is kept.
1994  *
1995  * GST_MESSAGE_SEGMENT_DONE: replace SEGMENT_START message from same poster
1996  *     with the segment_done message. If there are no more segment_start
1997  *     messages, post segment_done message upwards.
1998  *
1999  * GST_MESSAGE_DURATION: remove all previously cached duration messages.
2000  *     Whenever someone performs a duration query on the bin, we store the
2001  *     result so we can answer it quicker the next time. Any element that
2002  *     changes its duration marks our cached values invalid.
2003  *     This message is also posted upwards.
2004  *
2005  * GST_MESSAGE_CLOCK_LOST: This message is posted by an element when it
2006  *     can no longer provide a clock. The default bin behaviour is to
2007  *     check if the lost clock was the one provided by the bin. If so and
2008  *     we are currently in the PLAYING state, we forward the message to 
2009  *     our parent.
2010  *     This message is also generated when we remove a clock provider from
2011  *     a bin. If this message is received by the application, it should
2012  *     PAUSE the pipeline and set it back to PLAYING to force a new clock
2013  *     distribution.
2014  *
2015  * GST_MESSAGE_CLOCK_PROVIDE: This message is generated when an element
2016  *     can provide a clock. This mostly happens when we add a new clock
2017  *     provider to the bin. The default behaviour of the bin is to mark the
2018  *     currently selected clock as dirty, which will perform a clock
2019  *     recalculation the next time we are asked to provide a clock.
2020  *     This message is never sent tot the application but is forwarded to
2021  *     the parent.
2022  *
2023  * OTHER: post upwards.
2024  */
2025 static void
2026 gst_bin_handle_message_func (GstBin * bin, GstMessage * message)
2027 {
2028   GST_DEBUG_OBJECT (bin, "[msg %p] handling child message of type %s",
2029       message, GST_MESSAGE_TYPE_NAME (message));
2030
2031   switch (GST_MESSAGE_TYPE (message)) {
2032     case GST_MESSAGE_EOS:
2033     {
2034       gboolean eos;
2035
2036       /* collect all eos messages from the children */
2037       GST_OBJECT_LOCK (bin);
2038       bin_replace_message (bin, message, GST_MESSAGE_EOS);
2039       eos = is_eos (bin);
2040       GST_OBJECT_UNLOCK (bin);
2041
2042       /* if we are completely EOS, we forward an EOS message */
2043       if (eos) {
2044         GST_DEBUG_OBJECT (bin, "all sinks posted EOS");
2045         gst_element_post_message (GST_ELEMENT_CAST (bin),
2046             gst_message_new_eos (GST_OBJECT_CAST (bin)));
2047       }
2048       break;
2049     }
2050     case GST_MESSAGE_STATE_DIRTY:
2051     {
2052       GstObject *src;
2053       GstBinClass *klass;
2054
2055       src = GST_MESSAGE_SRC (message);
2056
2057       GST_DEBUG_OBJECT (bin, "%s gave state dirty", GST_ELEMENT_NAME (src));
2058
2059       /* mark the bin dirty */
2060       GST_OBJECT_LOCK (bin);
2061       GST_DEBUG_OBJECT (bin, "marking dirty");
2062       bin->state_dirty = TRUE;
2063
2064       if (GST_OBJECT_PARENT (bin))
2065         goto not_toplevel;
2066
2067       /* free message */
2068       gst_message_unref (message);
2069
2070       klass = GST_BIN_GET_CLASS (bin);
2071       if (!bin->polling) {
2072         GST_DEBUG_OBJECT (bin, "pushing recalc on thread pool");
2073         gst_object_ref (bin);
2074         g_thread_pool_push (klass->pool, bin, NULL);
2075       } else {
2076         GST_DEBUG_OBJECT (bin,
2077             "state recalc already in progress, not pushing new recalc");
2078       }
2079       GST_OBJECT_UNLOCK (bin);
2080       break;
2081
2082       /* non toplevel bins just forward the message and don't start
2083        * a recalc themselves */
2084     not_toplevel:
2085       {
2086         GST_OBJECT_UNLOCK (bin);
2087         GST_DEBUG_OBJECT (bin, "not toplevel, forwarding");
2088         goto forward;
2089       }
2090     }
2091     case GST_MESSAGE_SEGMENT_START:
2092       GST_OBJECT_LOCK (bin);
2093       /* replace any previous segment_start message from this source 
2094        * with the new segment start message */
2095       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
2096       GST_OBJECT_UNLOCK (bin);
2097       break;
2098     case GST_MESSAGE_SEGMENT_DONE:
2099     {
2100       MessageFind find;
2101       gboolean post = FALSE;
2102       GstFormat format;
2103       gint64 position;
2104
2105       gst_message_parse_segment_done (message, &format, &position);
2106
2107       GST_OBJECT_LOCK (bin);
2108       bin_replace_message (bin, message, GST_MESSAGE_SEGMENT_START);
2109       /* if there are no more segment_start messages, everybody posted
2110        * a segment_done and we can post one on the bus. */
2111
2112       /* we don't care who still has a pending segment start */
2113       find.src = NULL;
2114       find.types = GST_MESSAGE_SEGMENT_START;
2115
2116       if (!g_list_find_custom (bin->messages, &find,
2117               (GCompareFunc) message_check)) {
2118         /* nothing found */
2119         post = TRUE;
2120         /* remove all old segment_done messages */
2121         bin_remove_messages (bin, NULL, GST_MESSAGE_SEGMENT_DONE);
2122       }
2123       GST_OBJECT_UNLOCK (bin);
2124       if (post) {
2125         /* post segment done with latest format and position. */
2126         gst_element_post_message (GST_ELEMENT_CAST (bin),
2127             gst_message_new_segment_done (GST_OBJECT_CAST (bin),
2128                 format, position));
2129       }
2130       break;
2131     }
2132     case GST_MESSAGE_DURATION:
2133     {
2134       /* remove all cached duration messages, next time somebody asks
2135        * for duration, we will recalculate. */
2136       GST_OBJECT_LOCK (bin);
2137       bin_remove_messages (bin, NULL, GST_MESSAGE_DURATION);
2138       GST_OBJECT_UNLOCK (bin);
2139       goto forward;
2140     }
2141     case GST_MESSAGE_CLOCK_LOST:
2142     {
2143       GstClock **provided_clock_p;
2144       GstElement **clock_provider_p;
2145       gboolean playing, provided, forward;
2146       GstClock *clock;
2147
2148       gst_message_parse_clock_lost (message, &clock);
2149
2150       GST_OBJECT_LOCK (bin);
2151       bin->clock_dirty = TRUE;
2152       /* if we lost the clock that we provided, post to parent but 
2153        * only if we are PLAYING. */
2154       provided = (clock == bin->provided_clock);
2155       playing = (GST_STATE (bin) == GST_STATE_PLAYING);
2156       forward = playing & provided;
2157       if (provided) {
2158         GST_DEBUG_OBJECT (bin,
2159             "Lost clock %" GST_PTR_FORMAT " provided by %" GST_PTR_FORMAT,
2160             bin->provided_clock, bin->clock_provider);
2161         provided_clock_p = &bin->provided_clock;
2162         clock_provider_p = &bin->clock_provider;
2163         gst_object_replace ((GstObject **) provided_clock_p, NULL);
2164         gst_object_replace ((GstObject **) clock_provider_p, NULL);
2165       }
2166       GST_DEBUG_OBJECT (bin, "provided %d, playing %d, forward %d",
2167           provided, playing, forward);
2168       GST_OBJECT_UNLOCK (bin);
2169
2170       if (forward)
2171         goto forward;
2172
2173       /* free message */
2174       gst_message_unref (message);
2175       break;
2176     }
2177     case GST_MESSAGE_CLOCK_PROVIDE:
2178     {
2179       gboolean forward;
2180
2181       GST_OBJECT_LOCK (bin);
2182       bin->clock_dirty = TRUE;
2183       /* a new clock is available, post to parent but not
2184        * to the application */
2185       forward = GST_OBJECT_PARENT (bin) != NULL;
2186       GST_OBJECT_UNLOCK (bin);
2187
2188       if (forward)
2189         goto forward;
2190
2191       /* free message */
2192       gst_message_unref (message);
2193       break;
2194     }
2195     default:
2196       goto forward;
2197   }
2198   return;
2199
2200 forward:
2201   {
2202     /* Send all other messages upward */
2203     GST_DEBUG_OBJECT (bin, "posting message upward");
2204     gst_element_post_message (GST_ELEMENT_CAST (bin), message);
2205     return;
2206   }
2207 }
2208
2209 /* generic struct passed to all query fold methods */
2210 typedef struct
2211 {
2212   GstQuery *query;
2213   gint64 max;
2214 } QueryFold;
2215
2216 typedef void (*QueryInitFunction) (GstBin * bin, QueryFold * fold);
2217 typedef void (*QueryDoneFunction) (GstBin * bin, QueryFold * fold);
2218
2219 /* for duration/position we collect all durations/positions and take 
2220  * the MAX of all valid results */
2221 static void
2222 bin_query_max_init (GstBin * bin, QueryFold * fold)
2223 {
2224   fold->max = -1;
2225 }
2226
2227 static gboolean
2228 bin_query_duration_fold (GstElement * item, GValue * ret, QueryFold * fold)
2229 {
2230   if (gst_element_query (item, fold->query)) {
2231     gint64 duration;
2232
2233     g_value_set_boolean (ret, TRUE);
2234
2235     gst_query_parse_duration (fold->query, NULL, &duration);
2236
2237     GST_DEBUG_OBJECT (item, "got duration %" G_GINT64_FORMAT, duration);
2238
2239     if (duration > fold->max)
2240       fold->max = duration;
2241   }
2242
2243   gst_object_unref (item);
2244   return TRUE;
2245 }
2246 static void
2247 bin_query_duration_done (GstBin * bin, QueryFold * fold)
2248 {
2249   GstFormat format;
2250
2251   gst_query_parse_duration (fold->query, &format, NULL);
2252   /* store max in query result */
2253   gst_query_set_duration (fold->query, format, fold->max);
2254
2255   GST_DEBUG_OBJECT (bin, "max duration %" G_GINT64_FORMAT, fold->max);
2256
2257 #if 0
2258   /* and cache now */
2259   GST_OBJECT_LOCK (bin);
2260   bin->messages = g_list_prepend (bin->messages,
2261       gst_message_new_duration (GST_OBJECT_CAST (bin), format, fold->max));
2262   GST_OBJECT_UNLOCK (bin);
2263 #endif
2264 }
2265
2266 static gboolean
2267 bin_query_position_fold (GstElement * item, GValue * ret, QueryFold * fold)
2268 {
2269   if (gst_element_query (item, fold->query)) {
2270     gint64 position;
2271
2272     g_value_set_boolean (ret, TRUE);
2273
2274     gst_query_parse_position (fold->query, NULL, &position);
2275
2276     GST_DEBUG_OBJECT (item, "got position %" G_GINT64_FORMAT, position);
2277
2278     if (position > fold->max)
2279       fold->max = position;
2280   }
2281
2282   gst_object_unref (item);
2283   return TRUE;
2284 }
2285 static void
2286 bin_query_position_done (GstBin * bin, QueryFold * fold)
2287 {
2288   GstFormat format;
2289
2290   gst_query_parse_position (fold->query, &format, NULL);
2291   /* store max in query result */
2292   gst_query_set_position (fold->query, format, fold->max);
2293
2294   GST_DEBUG_OBJECT (bin, "max position %" G_GINT64_FORMAT, fold->max);
2295 }
2296
2297 /* generic fold, return first valid result */
2298 static gboolean
2299 bin_query_generic_fold (GstElement * item, GValue * ret, QueryFold * fold)
2300 {
2301   gboolean res;
2302
2303   if ((res = gst_element_query (item, fold->query))) {
2304     g_value_set_boolean (ret, TRUE);
2305     GST_DEBUG_OBJECT (item, "answered query %p", fold->query);
2306   }
2307
2308   gst_object_unref (item);
2309
2310   /* and stop as soon as we have a valid result */
2311   return !res;
2312 }
2313
2314 static gboolean
2315 gst_bin_query (GstElement * element, GstQuery * query)
2316 {
2317   GstBin *bin = GST_BIN (element);
2318   GstIterator *iter;
2319   gboolean res = FALSE;
2320   GstIteratorFoldFunction fold_func;
2321   QueryInitFunction fold_init = NULL;
2322   QueryDoneFunction fold_done = NULL;
2323   QueryFold fold_data;
2324   GValue ret = { 0 };
2325
2326   switch (GST_QUERY_TYPE (query)) {
2327     case GST_QUERY_DURATION:
2328     {
2329 #if 0
2330       GList *cached;
2331       GstFormat qformat;
2332
2333       gst_query_parse_duration (query, &qformat, NULL);
2334
2335       /* find cached duration query */
2336       GST_OBJECT_LOCK (bin);
2337       for (cached = bin->messages; cached; cached = g_list_next (cached)) {
2338         GstMessage *message = (GstMessage *) cached->data;
2339
2340         if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_DURATION &&
2341             GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (bin)) {
2342           GstFormat format;
2343           gint64 duration;
2344
2345           gst_message_parse_duration (message, &format, &duration);
2346
2347           /* if cached same format, copy duration in query result */
2348           if (format == qformat) {
2349             GST_DEBUG_OBJECT (bin, "return cached duration %" G_GINT64_FORMAT,
2350                 duration);
2351             GST_OBJECT_UNLOCK (bin);
2352
2353             gst_query_set_duration (query, qformat, duration);
2354             res = TRUE;
2355             goto exit;
2356           }
2357         }
2358       }
2359       GST_OBJECT_UNLOCK (bin);
2360 #endif
2361       fold_func = (GstIteratorFoldFunction) bin_query_duration_fold;
2362       fold_init = bin_query_max_init;
2363       fold_done = bin_query_duration_done;
2364       break;
2365     }
2366     case GST_QUERY_POSITION:
2367     {
2368       fold_func = (GstIteratorFoldFunction) bin_query_position_fold;
2369       fold_init = bin_query_max_init;
2370       fold_done = bin_query_position_done;
2371       break;
2372     }
2373     default:
2374       fold_func = (GstIteratorFoldFunction) bin_query_generic_fold;
2375       break;
2376   }
2377
2378   fold_data.query = query;
2379
2380   g_value_init (&ret, G_TYPE_BOOLEAN);
2381   g_value_set_boolean (&ret, FALSE);
2382
2383   iter = gst_bin_iterate_sinks (bin);
2384   GST_DEBUG_OBJECT (bin, "Sending query %p (type %d) to sink children",
2385       query, GST_QUERY_TYPE (query));
2386
2387   if (fold_init)
2388     fold_init (bin, &fold_data);
2389
2390   while (TRUE) {
2391     GstIteratorResult ires;
2392
2393     ires = gst_iterator_fold (iter, fold_func, &ret, &fold_data);
2394
2395     switch (ires) {
2396       case GST_ITERATOR_RESYNC:
2397         gst_iterator_resync (iter);
2398         if (fold_init)
2399           fold_init (bin, &fold_data);
2400         g_value_set_boolean (&ret, FALSE);
2401         break;
2402       case GST_ITERATOR_OK:
2403       case GST_ITERATOR_DONE:
2404         res = g_value_get_boolean (&ret);
2405         if (fold_done != NULL && res)
2406           fold_done (bin, &fold_data);
2407         goto done;
2408       default:
2409         res = FALSE;
2410         goto done;
2411     }
2412   }
2413 done:
2414   gst_iterator_free (iter);
2415
2416 /* exit: */
2417   GST_DEBUG_OBJECT (bin, "query %p result %d", query, res);
2418
2419   return res;
2420 }
2421
2422 static gint
2423 compare_name (GstElement * element, const gchar * name)
2424 {
2425   gint eq;
2426
2427   GST_OBJECT_LOCK (element);
2428   eq = strcmp (GST_ELEMENT_NAME (element), name);
2429   GST_OBJECT_UNLOCK (element);
2430
2431   if (eq != 0) {
2432     gst_object_unref (element);
2433   }
2434   return eq;
2435 }
2436
2437 /**
2438  * gst_bin_get_by_name:
2439  * @bin: a #GstBin
2440  * @name: the element name to search for
2441  *
2442  * Gets the element with the given name from a bin. This
2443  * function recurses into child bins.
2444  *
2445  * Returns NULL if no element with the given name is found in the bin.
2446  *
2447  * MT safe.  Caller owns returned reference.
2448  *
2449  * Returns: the #GstElement with the given name, or NULL
2450  */
2451 GstElement *
2452 gst_bin_get_by_name (GstBin * bin, const gchar * name)
2453 {
2454   GstIterator *children;
2455   GstIterator *result;
2456
2457   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
2458
2459   GST_CAT_INFO (GST_CAT_PARENTAGE, "[%s]: looking up child element %s",
2460       GST_ELEMENT_NAME (bin), name);
2461
2462   children = gst_bin_iterate_recurse (bin);
2463   result = gst_iterator_find_custom (children,
2464       (GCompareFunc) compare_name, (gpointer) name);
2465   gst_iterator_free (children);
2466
2467   return GST_ELEMENT_CAST (result);
2468 }
2469
2470 /**
2471  * gst_bin_get_by_name_recurse_up:
2472  * @bin: a #GstBin
2473  * @name: the element name to search for
2474  *
2475  * Gets the element with the given name from this bin. If the
2476  * element is not found, a recursion is performed on the parent bin.
2477  *
2478  * Returns NULL if:
2479  * - no element with the given name is found in the bin
2480  *
2481  * MT safe.  Caller owns returned reference.
2482  *
2483  * Returns: the #GstElement with the given name, or NULL
2484  */
2485 GstElement *
2486 gst_bin_get_by_name_recurse_up (GstBin * bin, const gchar * name)
2487 {
2488   GstElement *result;
2489
2490   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
2491   g_return_val_if_fail (name != NULL, NULL);
2492
2493   result = gst_bin_get_by_name (bin, name);
2494
2495   if (!result) {
2496     GstObject *parent;
2497
2498     parent = gst_object_get_parent (GST_OBJECT_CAST (bin));
2499     if (parent) {
2500       if (GST_IS_BIN (parent)) {
2501         result = gst_bin_get_by_name_recurse_up (GST_BIN_CAST (parent), name);
2502       }
2503       gst_object_unref (parent);
2504     }
2505   }
2506
2507   return result;
2508 }
2509
2510 static gint
2511 compare_interface (GstElement * element, gpointer interface)
2512 {
2513   gint ret;
2514
2515   if (G_TYPE_CHECK_INSTANCE_TYPE (element, GPOINTER_TO_INT (interface))) {
2516     ret = 0;
2517   } else {
2518     /* we did not find the element, need to release the ref
2519      * added by the iterator */
2520     gst_object_unref (element);
2521     ret = 1;
2522   }
2523   return ret;
2524 }
2525
2526 /**
2527  * gst_bin_get_by_interface:
2528  * @bin: a #GstBin
2529  * @interface: the #GType of an interface
2530  *
2531  * Looks for an element inside the bin that implements the given
2532  * interface. If such an element is found, it returns the element.
2533  * You can cast this element to the given interface afterwards.  If you want
2534  * all elements that implement the interface, use
2535  * gst_bin_iterate_all_by_interface(). This function recurses into child bins.
2536  *
2537  * MT safe.  Caller owns returned reference.
2538  *
2539  * Returns: A #GstElement inside the bin implementing the interface
2540  */
2541 GstElement *
2542 gst_bin_get_by_interface (GstBin * bin, GType interface)
2543 {
2544   GstIterator *children;
2545   GstIterator *result;
2546
2547   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
2548
2549   children = gst_bin_iterate_recurse (bin);
2550   result = gst_iterator_find_custom (children, (GCompareFunc) compare_interface,
2551       GINT_TO_POINTER (interface));
2552   gst_iterator_free (children);
2553
2554   return GST_ELEMENT_CAST (result);
2555 }
2556
2557 /**
2558  * gst_bin_iterate_all_by_interface:
2559  * @bin: a #GstBin
2560  * @interface: the #GType of an interface
2561  *
2562  * Looks for all elements inside the bin that implements the given
2563  * interface. You can safely cast all returned elements to the given interface.
2564  * The function recurses inside child bins. The iterator will yield a series
2565  * of #GstElement that should be unreffed after use.
2566  *
2567  * Each element yielded by the iterator will have its refcount increased, so
2568  * unref after use.
2569  *
2570  * MT safe.  Caller owns returned value.
2571  *
2572  * Returns: a #GstIterator of #GstElement for all elements in the bin
2573  *          implementing the given interface, or NULL
2574  */
2575 GstIterator *
2576 gst_bin_iterate_all_by_interface (GstBin * bin, GType interface)
2577 {
2578   GstIterator *children;
2579   GstIterator *result;
2580
2581   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
2582
2583   children = gst_bin_iterate_recurse (bin);
2584   result = gst_iterator_filter (children, (GCompareFunc) compare_interface,
2585       GINT_TO_POINTER (interface));
2586
2587   return result;
2588 }
2589
2590 #ifndef GST_DISABLE_LOADSAVE
2591 static xmlNodePtr
2592 gst_bin_save_thyself (GstObject * object, xmlNodePtr parent)
2593 {
2594   GstBin *bin = GST_BIN (object);
2595   xmlNodePtr childlist, elementnode;
2596   GList *children;
2597   GstElement *child;
2598
2599   if (GST_OBJECT_CLASS (parent_class)->save_thyself)
2600     GST_OBJECT_CLASS (parent_class)->save_thyself (GST_OBJECT (bin), parent);
2601
2602   childlist = xmlNewChild (parent, NULL, (xmlChar *) "children", NULL);
2603
2604   GST_CAT_INFO (GST_CAT_XML, "[%s]: saving %d children",
2605       GST_ELEMENT_NAME (bin), bin->numchildren);
2606
2607   children = bin->children;
2608   while (children) {
2609     child = GST_ELEMENT (children->data);
2610     elementnode = xmlNewChild (childlist, NULL, (xmlChar *) "element", NULL);
2611     gst_object_save_thyself (GST_OBJECT (child), elementnode);
2612     children = g_list_next (children);
2613   }
2614   return childlist;
2615 }
2616
2617 static void
2618 gst_bin_restore_thyself (GstObject * object, xmlNodePtr self)
2619 {
2620   GstBin *bin = GST_BIN (object);
2621   xmlNodePtr field = self->xmlChildrenNode;
2622   xmlNodePtr childlist;
2623
2624   while (field) {
2625     if (!strcmp ((char *) field->name, "children")) {
2626       GST_CAT_INFO (GST_CAT_XML, "[%s]: loading children",
2627           GST_ELEMENT_NAME (object));
2628       childlist = field->xmlChildrenNode;
2629       while (childlist) {
2630         if (!strcmp ((char *) childlist->name, "element")) {
2631           GstElement *element =
2632               gst_xml_make_element (childlist, GST_OBJECT (bin));
2633
2634           /* it had to be parented to find the pads, now we ref and unparent so
2635            * we can add it to the bin */
2636           gst_object_ref (element);
2637           gst_object_unparent (GST_OBJECT (element));
2638
2639           gst_bin_add (bin, element);
2640         }
2641         childlist = childlist->next;
2642       }
2643     }
2644
2645     field = field->next;
2646   }
2647   if (GST_OBJECT_CLASS (parent_class)->restore_thyself)
2648     (GST_OBJECT_CLASS (parent_class)->restore_thyself) (object, self);
2649 }
2650 #endif /* GST_DISABLE_LOADSAVE */