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