gst/base/gstbasesink.c: Only error is an error.
[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  * SECTION:gstbin
27  * @short_description: Base class for elements that contain other elements
28  *
29  * GstBin is the simplest of the container elements, allowing elements to
30  * become children of itself.  Pads from the child elements can be ghosted to
31  * the bin, making the bin itself look transparently like any other element,
32  * allowing for deep nesting of predefined sub-pipelines.
33  *
34  * A new GstBin is created with gst_bin_new(). Use a #GstPipeline instead if you
35  * want to create a toplevel bin because a normal bin doesn't have a bus or
36  * handle clock distribution of its own.
37  * 
38  * After the bin has been created you will typically add elements to it with
39  * gst_bin_add(). You can remove elements with gst_bin_remove().
40  *
41  * An element can be retrieved from a bin with gst_bin_get_by_name(), using the
42  * elements name. gst_bin_get_by_name_recurse_up() is mainly used for internal
43  * purposes and will query the parent bins when the element is not found in the
44  * current bin.
45  * 
46  * An iterator of elements in a bin can be retrieved with 
47  * gst_bin_iterate_elements(). Various other iterators exist to retrieve the
48  * elements in a bin.
49  * 
50  * The "element_added" signal is fired whenever a new element is added to the
51  * bin. Likewise the "element_removed" signal is fired whenever an element is
52  * removed from the bin.
53  *
54  * gst_bin_unref() is used to destroy the bin. 
55  */
56
57 #include "gst_private.h"
58
59 #include "gstevent.h"
60 #include "gstbin.h"
61 #include "gstmarshal.h"
62 #include "gstxml.h"
63 #include "gstinfo.h"
64 #include "gsterror.h"
65
66 #include "gstindex.h"
67 #include "gstindexfactory.h"
68 #include "gstutils.h"
69 #include "gstchildproxy.h"
70
71 GST_DEBUG_CATEGORY_STATIC (bin_debug);
72 #define GST_CAT_DEFAULT bin_debug
73 #define GST_LOG_BIN_CONTENTS(bin, text) GST_LOG_OBJECT ((bin), \
74         text ": %d elements: %u PLAYING, %u PAUSED, %u READY, %u NULL, own state: %s", \
75         (bin)->numchildren, (guint) (bin)->child_states[3], \
76         (guint) (bin)->child_states[2], (bin)->child_states[1], \
77         (bin)->child_states[0], gst_element_state_get_name (GST_STATE (bin)))
78
79
80 static GstElementDetails gst_bin_details = GST_ELEMENT_DETAILS ("Generic bin",
81     "Generic/Bin",
82     "Simple container object",
83     "Erik Walthinsen <omega@cse.ogi.edu>," "Wim Taymans <wim@fluendo.com>");
84
85 GType _gst_bin_type = 0;
86
87 static void gst_bin_dispose (GObject * object);
88
89 static GstStateChangeReturn gst_bin_change_state (GstElement * element,
90     GstStateChange transition);
91 static GstStateChangeReturn gst_bin_get_state (GstElement * element,
92     GstState * state, GstState * pending, GTimeVal * timeout);
93
94 static gboolean gst_bin_add_func (GstBin * bin, GstElement * element);
95 static gboolean gst_bin_remove_func (GstBin * bin, GstElement * element);
96
97 #ifndef GST_DISABLE_INDEX
98 static void gst_bin_set_index_func (GstElement * element, GstIndex * index);
99 #endif
100 static GstClock *gst_bin_provide_clock_func (GstElement * element);
101 static void gst_bin_set_clock_func (GstElement * element, GstClock * clock);
102
103 static gboolean gst_bin_send_event (GstElement * element, GstEvent * event);
104 static GstBusSyncReply bin_bus_handler (GstBus * bus,
105     GstMessage * message, GstBin * bin);
106 static gboolean gst_bin_query (GstElement * element, GstQuery * query);
107
108 #ifndef GST_DISABLE_LOADSAVE
109 static xmlNodePtr gst_bin_save_thyself (GstObject * object, xmlNodePtr parent);
110 static void gst_bin_restore_thyself (GstObject * object, xmlNodePtr self);
111 #endif
112
113 static gint bin_element_is_sink (GstElement * child, GstBin * bin);
114
115 /* Bin signals and args */
116 enum
117 {
118   ELEMENT_ADDED,
119   ELEMENT_REMOVED,
120   LAST_SIGNAL
121 };
122
123 enum
124 {
125   ARG_0
126       /* FILL ME */
127 };
128
129 static void gst_bin_base_init (gpointer g_class);
130 static void gst_bin_class_init (GstBinClass * klass);
131 static void gst_bin_init (GstBin * bin);
132 static void gst_bin_child_proxy_init (gpointer g_iface, gpointer iface_data);
133
134 static GstElementClass *parent_class = NULL;
135 static guint gst_bin_signals[LAST_SIGNAL] = { 0 };
136
137 /**
138  * gst_bin_get_type:
139  *
140  * Returns: the type of #GstBin
141  */
142 GType
143 gst_bin_get_type (void)
144 {
145   if (!_gst_bin_type) {
146     static const GTypeInfo bin_info = {
147       sizeof (GstBinClass),
148       gst_bin_base_init,
149       NULL,
150       (GClassInitFunc) gst_bin_class_init,
151       NULL,
152       NULL,
153       sizeof (GstBin),
154       0,
155       (GInstanceInitFunc) gst_bin_init,
156       NULL
157     };
158     static const GInterfaceInfo child_proxy_info = {
159       gst_bin_child_proxy_init,
160       NULL,
161       NULL
162     };
163
164     _gst_bin_type =
165         g_type_register_static (GST_TYPE_ELEMENT, "GstBin", &bin_info, 0);
166
167     g_type_add_interface_static (_gst_bin_type, GST_TYPE_CHILD_PROXY,
168         &child_proxy_info);
169
170     GST_DEBUG_CATEGORY_INIT (bin_debug, "bin", GST_DEBUG_BOLD,
171         "debugging info for the 'bin' container element");
172   }
173   return _gst_bin_type;
174 }
175
176 static void
177 gst_bin_base_init (gpointer g_class)
178 {
179   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
180
181   gst_element_class_set_details (gstelement_class, &gst_bin_details);
182 }
183
184 static GstObject *
185 gst_bin_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
186     guint index)
187 {
188   return g_list_nth_data (GST_BIN (child_proxy)->children, index);
189 }
190
191 guint
192 gst_bin_child_proxy_get_children_count (GstChildProxy * child_proxy)
193 {
194   return GST_BIN (child_proxy)->numchildren;
195 }
196
197 static void
198 gst_bin_child_proxy_init (gpointer g_iface, gpointer iface_data)
199 {
200   GstChildProxyInterface *iface = g_iface;
201
202   iface->get_children_count = gst_bin_child_proxy_get_children_count;
203   iface->get_child_by_index = gst_bin_child_proxy_get_child_by_index;
204 }
205
206 static void
207 gst_bin_class_init (GstBinClass * klass)
208 {
209   GObjectClass *gobject_class;
210   GstObjectClass *gstobject_class;
211   GstElementClass *gstelement_class;
212
213   gobject_class = (GObjectClass *) klass;
214   gstobject_class = (GstObjectClass *) klass;
215   gstelement_class = (GstElementClass *) klass;
216
217   parent_class = g_type_class_peek_parent (klass);
218
219   /**
220    * GstBin::element-added:
221    * @bin: the object which emitted the signal.
222    * @element: the element that was added to the bin
223    *
224    * Will be emitted if a new element was removed/added to this bin.
225    */
226   gst_bin_signals[ELEMENT_ADDED] =
227       g_signal_new ("element-added", G_TYPE_FROM_CLASS (klass),
228       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstBinClass, element_added), NULL,
229       NULL, gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
230   /**
231    * GstBin::element-removed:
232    * @bin: the object which emitted the signal.
233    * @element: the element that was removed from the bin
234    *
235    * Will be emitted if an element was removed from this bin.
236    */
237   gst_bin_signals[ELEMENT_REMOVED] =
238       g_signal_new ("element-removed", G_TYPE_FROM_CLASS (klass),
239       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstBinClass, element_removed), NULL,
240       NULL, gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
241
242   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_bin_dispose);
243
244 #ifndef GST_DISABLE_LOADSAVE
245   gstobject_class->save_thyself = GST_DEBUG_FUNCPTR (gst_bin_save_thyself);
246   gstobject_class->restore_thyself =
247       GST_DEBUG_FUNCPTR (gst_bin_restore_thyself);
248 #endif
249
250   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_bin_change_state);
251   gstelement_class->get_state = GST_DEBUG_FUNCPTR (gst_bin_get_state);
252 #ifndef GST_DISABLE_INDEX
253   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_bin_set_index_func);
254 #endif
255   gstelement_class->provide_clock =
256       GST_DEBUG_FUNCPTR (gst_bin_provide_clock_func);
257   gstelement_class->set_clock = GST_DEBUG_FUNCPTR (gst_bin_set_clock_func);
258
259   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_bin_send_event);
260   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_bin_query);
261
262   klass->add_element = GST_DEBUG_FUNCPTR (gst_bin_add_func);
263   klass->remove_element = GST_DEBUG_FUNCPTR (gst_bin_remove_func);
264 }
265
266 static void
267 gst_bin_init (GstBin * bin)
268 {
269   GstBus *bus;
270
271   bin->numchildren = 0;
272   bin->children = NULL;
273   bin->children_cookie = 0;
274   bin->eosed = NULL;
275
276   /* Set up a bus for listening to child elements */
277   bus = g_object_new (gst_bus_get_type (), NULL);
278   bin->child_bus = bus;
279   gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bin_bus_handler, bin);
280 }
281
282 /**
283  * gst_bin_new:
284  * @name: name of new bin
285  *
286  * Create a new bin with given name.
287  *
288  * Returns: new bin
289  */
290 GstElement *
291 gst_bin_new (const gchar * name)
292 {
293   return gst_element_factory_make ("bin", name);
294 }
295
296 /* set the index on all elements in this bin
297  *
298  * MT safe
299  */
300 #ifndef GST_DISABLE_INDEX
301 static void
302 gst_bin_set_index_func (GstElement * element, GstIndex * index)
303 {
304   GstBin *bin;
305   GList *children;
306
307   bin = GST_BIN (element);
308
309   GST_LOCK (bin);
310   for (children = bin->children; children; children = g_list_next (children)) {
311     GstElement *child = GST_ELEMENT (children->data);
312
313     gst_element_set_index (child, index);
314   }
315   GST_UNLOCK (bin);
316 }
317 #endif
318
319 /* set the clock on all elements in this bin
320  *
321  * MT safe
322  */
323 static void
324 gst_bin_set_clock_func (GstElement * element, GstClock * clock)
325 {
326   GList *children;
327   GstBin *bin;
328
329   bin = GST_BIN (element);
330
331   GST_LOCK (bin);
332   for (children = bin->children; children; children = g_list_next (children)) {
333     GstElement *child = GST_ELEMENT (children->data);
334
335     gst_element_set_clock (child, clock);
336   }
337   GST_UNLOCK (bin);
338 }
339
340 /* get the clock for this bin by asking all of the children in this bin
341  *
342  * The ref of the returned clock in increased so unref after usage.
343  *
344  * MT safe
345  *
346  * FIXME, clock selection is not correct here.
347  */
348 static GstClock *
349 gst_bin_provide_clock_func (GstElement * element)
350 {
351   GstClock *result = NULL;
352   GstBin *bin;
353   GList *children;
354
355   bin = GST_BIN (element);
356
357   GST_LOCK (bin);
358   for (children = bin->children; children; children = g_list_next (children)) {
359     GstElement *child = GST_ELEMENT (children->data);
360
361     result = gst_element_provide_clock (child);
362     if (result)
363       break;
364   }
365   GST_UNLOCK (bin);
366
367   return result;
368 }
369
370 static gboolean
371 is_eos (GstBin * bin)
372 {
373   GstIterator *sinks;
374   gboolean result = TRUE;
375   gboolean done = FALSE;
376
377   sinks = gst_bin_iterate_sinks (bin);
378   while (!done) {
379     gpointer data;
380
381     switch (gst_iterator_next (sinks, &data)) {
382       case GST_ITERATOR_OK:
383       {
384         GstElement *element = GST_ELEMENT (data);
385         GList *eosed;
386         gchar *name;
387
388         name = gst_element_get_name (element);
389         eosed = g_list_find (bin->eosed, element);
390         if (!eosed) {
391           GST_DEBUG ("element %s did not post EOS yet", name);
392           result = FALSE;
393           done = TRUE;
394         } else {
395           GST_DEBUG ("element %s posted EOS", name);
396         }
397         g_free (name);
398         gst_object_unref (element);
399         break;
400       }
401       case GST_ITERATOR_RESYNC:
402         result = TRUE;
403         gst_iterator_resync (sinks);
404         break;
405       case GST_ITERATOR_DONE:
406         done = TRUE;
407         break;
408       default:
409         g_assert_not_reached ();
410         break;
411     }
412   }
413   gst_iterator_free (sinks);
414   return result;
415 }
416
417 static void
418 unlink_pads (GstPad * pad)
419 {
420   GstPad *peer;
421
422   if ((peer = gst_pad_get_peer (pad))) {
423     if (gst_pad_get_direction (pad) == GST_PAD_SRC)
424       gst_pad_unlink (pad, peer);
425     else
426       gst_pad_unlink (peer, pad);
427     gst_object_unref (peer);
428   }
429   gst_object_unref (pad);
430 }
431
432 /* add an element to this bin
433  *
434  * MT safe
435  */
436 static gboolean
437 gst_bin_add_func (GstBin * bin, GstElement * element)
438 {
439   gchar *elem_name;
440   GstIterator *it;
441
442   /* we obviously can't add ourself to ourself */
443   if (G_UNLIKELY (GST_ELEMENT_CAST (element) == GST_ELEMENT_CAST (bin)))
444     goto adding_itself;
445
446   /* get the element name to make sure it is unique in this bin. */
447   GST_LOCK (element);
448   elem_name = g_strdup (GST_ELEMENT_NAME (element));
449   GST_UNLOCK (element);
450
451   GST_LOCK (bin);
452
453   /* then check to see if the element's name is already taken in the bin,
454    * we can safely take the lock here. This check is probably bogus because
455    * you can safely change the element name after this check and before setting
456    * the object parent. The window is very small though... */
457   if (G_UNLIKELY (!gst_object_check_uniqueness (bin->children, elem_name)))
458     goto duplicate_name;
459
460   /* set the element's parent and add the element to the bin's list of children */
461   if (G_UNLIKELY (!gst_object_set_parent (GST_OBJECT_CAST (element),
462               GST_OBJECT_CAST (bin))))
463     goto had_parent;
464
465   /* if we add a sink we become a sink */
466   if (GST_FLAG_IS_SET (element, GST_ELEMENT_IS_SINK)) {
467     GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "element \"%s\" was sink",
468         elem_name);
469     GST_FLAG_SET (bin, GST_ELEMENT_IS_SINK);
470   }
471
472   bin->children = g_list_prepend (bin->children, element);
473   bin->numchildren++;
474   bin->children_cookie++;
475
476   /* distribute the bus */
477   gst_element_set_bus (element, bin->child_bus);
478
479   /* propagate the current base time and clock */
480   gst_element_set_base_time (element, GST_ELEMENT (bin)->base_time);
481   gst_element_set_clock (element, GST_ELEMENT_CLOCK (bin));
482
483   GST_UNLOCK (bin);
484
485   /* unlink all linked pads */
486   it = gst_element_iterate_pads (element);
487   gst_iterator_foreach (it, (GFunc) unlink_pads, element);
488   gst_iterator_free (it);
489
490   GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, bin, "added element \"%s\"",
491       elem_name);
492   g_free (elem_name);
493
494   g_signal_emit (G_OBJECT (bin), gst_bin_signals[ELEMENT_ADDED], 0, element);
495
496   return TRUE;
497
498   /* ERROR handling here */
499 adding_itself:
500   {
501     GST_LOCK (bin);
502     g_warning ("Cannot add bin %s to itself", GST_ELEMENT_NAME (bin));
503     GST_UNLOCK (bin);
504     return FALSE;
505   }
506 duplicate_name:
507   {
508     g_warning ("Name %s is not unique in bin %s, not adding",
509         elem_name, GST_ELEMENT_NAME (bin));
510     GST_UNLOCK (bin);
511     g_free (elem_name);
512     return FALSE;
513   }
514 had_parent:
515   {
516     g_warning ("Element %s already has parent", elem_name);
517     GST_UNLOCK (bin);
518     g_free (elem_name);
519     return FALSE;
520   }
521 }
522
523
524 /**
525  * gst_bin_add:
526  * @bin: #GstBin to add element to
527  * @element: #GstElement to add to bin
528  *
529  * Adds the given element to the bin.  Sets the element's parent, and thus
530  * takes ownership of the element. An element can only be added to one bin.
531  *
532  * If the element's pads are linked to other pads, the pads will be unlinked
533  * before the element is added to the bin.
534  *
535  * MT safe.
536  *
537  * Returns: TRUE if the element could be added, FALSE on wrong parameters or
538  * the bin does not want to accept the element.
539  */
540 gboolean
541 gst_bin_add (GstBin * bin, GstElement * element)
542 {
543   GstBinClass *bclass;
544   gboolean result;
545
546   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
547   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
548
549   bclass = GST_BIN_GET_CLASS (bin);
550
551   if (G_UNLIKELY (bclass->add_element == NULL))
552     goto no_function;
553
554   GST_CAT_DEBUG (GST_CAT_PARENTAGE, "adding element %s to bin %s",
555       GST_ELEMENT_NAME (element), GST_ELEMENT_NAME (bin));
556
557   result = bclass->add_element (bin, element);
558
559   return result;
560
561   /* ERROR handling */
562 no_function:
563   {
564     g_warning ("adding elements to bin %s is not supported",
565         GST_ELEMENT_NAME (bin));
566     return FALSE;
567   }
568 }
569
570 /* remove an element from the bin
571  *
572  * MT safe
573  */
574 static gboolean
575 gst_bin_remove_func (GstBin * bin, GstElement * element)
576 {
577   gchar *elem_name;
578   GstIterator *it;
579
580   GST_LOCK (element);
581   /* Check if the element is already being removed and immediately
582    * return */
583   if (G_UNLIKELY (GST_FLAG_IS_SET (element, GST_ELEMENT_UNPARENTING)))
584     goto already_removing;
585
586   GST_FLAG_SET (element, GST_ELEMENT_UNPARENTING);
587   /* grab element name so we can print it */
588   elem_name = g_strdup (GST_ELEMENT_NAME (element));
589   GST_UNLOCK (element);
590
591   /* unlink all linked pads */
592   it = gst_element_iterate_pads (element);
593   gst_iterator_foreach (it, (GFunc) unlink_pads, element);
594   gst_iterator_free (it);
595
596   GST_LOCK (bin);
597   /* the element must be in the bin's list of children */
598   if (G_UNLIKELY (g_list_find (bin->children, element) == NULL))
599     goto not_in_bin;
600
601   /* now remove the element from the list of elements */
602   bin->children = g_list_remove (bin->children, element);
603   bin->numchildren--;
604   bin->children_cookie++;
605
606   /* check if we removed a sink */
607   if (GST_FLAG_IS_SET (element, GST_ELEMENT_IS_SINK)) {
608     GList *other_sink;
609
610     /* check if we removed the last sink */
611     other_sink = g_list_find_custom (bin->children,
612         bin, (GCompareFunc) bin_element_is_sink);
613     if (!other_sink) {
614       /* yups, we're not a sink anymore */
615       GST_FLAG_UNSET (bin, GST_ELEMENT_IS_SINK);
616     }
617   }
618   GST_UNLOCK (bin);
619
620   GST_CAT_INFO_OBJECT (GST_CAT_PARENTAGE, bin, "removed child \"%s\"",
621       elem_name);
622   g_free (elem_name);
623
624   gst_element_set_bus (element, NULL);
625
626   /* unlock any waiters for the state change. It is possible that
627    * we are waiting for an ASYNC state change on this element. The
628    * element cannot be added to another bin yet as it is not yet
629    * unparented. */
630   GST_STATE_LOCK (element);
631   GST_STATE_BROADCAST (element);
632   GST_STATE_UNLOCK (element);
633
634   /* we ref here because after the _unparent() the element can be disposed
635    * and we still need it to reset the UNPARENTING flag and fire a signal. */
636   gst_object_ref (element);
637   gst_object_unparent (GST_OBJECT_CAST (element));
638
639   GST_LOCK (element);
640   GST_FLAG_UNSET (element, GST_ELEMENT_UNPARENTING);
641   GST_UNLOCK (element);
642
643   g_signal_emit (G_OBJECT (bin), gst_bin_signals[ELEMENT_REMOVED], 0, element);
644
645   /* element is really out of our control now */
646   gst_object_unref (element);
647
648   return TRUE;
649
650   /* ERROR handling */
651 not_in_bin:
652   {
653     g_warning ("Element %s is not in bin %s", elem_name,
654         GST_ELEMENT_NAME (bin));
655     GST_UNLOCK (bin);
656     g_free (elem_name);
657     return FALSE;
658   }
659 already_removing:
660   {
661     GST_UNLOCK (element);
662     return FALSE;
663   }
664 }
665
666 /**
667  * gst_bin_remove:
668  * @bin: #GstBin to remove element from
669  * @element: #GstElement to remove
670  *
671  * Remove the element from its associated bin, unparenting it as well.
672  * Unparenting the element means that the element will be dereferenced,
673  * so if the bin holds the only reference to the element, the element
674  * will be freed in the process of removing it from the bin.  If you
675  * want the element to still exist after removing, you need to call
676  * gst_object_ref() before removing it from the bin.
677  *
678  * If the element's pads are linked to other pads, the pads will be unlinked
679  * before the element is removed from the bin.
680  *
681  * MT safe.
682  *
683  * Returns: TRUE if the element could be removed, FALSE on wrong parameters or
684  * the bin does not want to remove the element.
685  */
686 gboolean
687 gst_bin_remove (GstBin * bin, GstElement * element)
688 {
689   GstBinClass *bclass;
690   gboolean result;
691
692   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
693   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
694
695   bclass = GST_BIN_GET_CLASS (bin);
696
697   if (G_UNLIKELY (bclass->remove_element == NULL))
698     goto no_function;
699
700   GST_CAT_DEBUG (GST_CAT_PARENTAGE, "removing element %s from bin %s",
701       GST_ELEMENT_NAME (element), GST_ELEMENT_NAME (bin));
702
703   result = bclass->remove_element (bin, element);
704
705   return result;
706
707   /* ERROR handling */
708 no_function:
709   {
710     g_warning ("removing elements from bin %s is not supported",
711         GST_ELEMENT_NAME (bin));
712     return FALSE;
713   }
714 }
715
716 static GstIteratorItem
717 iterate_child (GstIterator * it, GstElement * child)
718 {
719   gst_object_ref (child);
720   return GST_ITERATOR_ITEM_PASS;
721 }
722
723 /**
724  * gst_bin_iterate_elements:
725  * @bin: #Gstbin to iterate the elements of
726  *
727  * Get an iterator for the elements in this bin.
728  * Each element will have its refcount increased, so unref
729  * after use.
730  *
731  * MT safe.
732  *
733  * Returns: a #GstIterator of #GstElements. gst_iterator_free after
734  * use. returns NULL when passing bad parameters.
735  */
736 GstIterator *
737 gst_bin_iterate_elements (GstBin * bin)
738 {
739   GstIterator *result;
740
741   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
742
743   GST_LOCK (bin);
744   /* add ref because the iterator refs the bin. When the iterator
745    * is freed it will unref the bin again using the provided dispose
746    * function. */
747   gst_object_ref (bin);
748   result = gst_iterator_new_list (GST_GET_LOCK (bin),
749       &bin->children_cookie,
750       &bin->children,
751       bin,
752       (GstIteratorItemFunction) iterate_child,
753       (GstIteratorDisposeFunction) gst_object_unref);
754   GST_UNLOCK (bin);
755
756   return result;
757 }
758
759 static GstIteratorItem
760 iterate_child_recurse (GstIterator * it, GstElement * child)
761 {
762   gst_object_ref (child);
763   if (GST_IS_BIN (child)) {
764     GstIterator *other = gst_bin_iterate_recurse (GST_BIN (child));
765
766     gst_iterator_push (it, other);
767   }
768   return GST_ITERATOR_ITEM_PASS;
769 }
770
771 /**
772  * gst_bin_iterate_recurse:
773  * @bin: #Gstbin to iterate the elements of
774  *
775  * Get an iterator for the elements in this bin.
776  * Each element will have its refcount increased, so unref
777  * after use. This iterator recurses into GstBin children.
778  *
779  * MT safe.
780  *
781  * Returns: a #GstIterator of #GstElements. gst_iterator_free after
782  * use. returns NULL when passing bad parameters.
783  */
784 GstIterator *
785 gst_bin_iterate_recurse (GstBin * bin)
786 {
787   GstIterator *result;
788
789   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
790
791   GST_LOCK (bin);
792   /* add ref because the iterator refs the bin. When the iterator
793    * is freed it will unref the bin again using the provided dispose
794    * function. */
795   gst_object_ref (bin);
796   result = gst_iterator_new_list (GST_GET_LOCK (bin),
797       &bin->children_cookie,
798       &bin->children,
799       bin,
800       (GstIteratorItemFunction) iterate_child_recurse,
801       (GstIteratorDisposeFunction) gst_object_unref);
802   GST_UNLOCK (bin);
803
804   return result;
805 }
806
807 /* returns 0 when TRUE because this is a GCompareFunc */
808 /* MT safe */
809 static gint
810 bin_element_is_sink (GstElement * child, GstBin * bin)
811 {
812   gboolean is_sink;
813
814   /* we lock the child here for the remainder of the function to
815    * get its name safely. */
816   GST_LOCK (child);
817   is_sink = GST_FLAG_IS_SET (child, GST_ELEMENT_IS_SINK);
818
819   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, bin,
820       "child %s %s sink", GST_OBJECT_NAME (child), is_sink ? "is" : "is not");
821
822   GST_UNLOCK (child);
823   return is_sink ? 0 : 1;
824 }
825
826 static gint
827 sink_iterator_filter (GstElement * child, GstBin * bin)
828 {
829   if (bin_element_is_sink (child, bin) == 0) {
830     /* returns 0 because this is a GCompareFunc */
831     return 0;
832   } else {
833     /* child carries a ref from gst_bin_iterate_elements -- drop if not passing
834        through */
835     gst_object_unref ((GstObject *) child);
836     return 1;
837   }
838 }
839
840 /**
841  * gst_bin_iterate_sinks:
842  * @bin: #Gstbin to iterate on
843  *
844  * Get an iterator for the sink elements in this bin.
845  * Each element will have its refcount increased, so unref
846  * after use.
847  *
848  * The sink elements are those without any linked srcpads.
849  *
850  * MT safe.
851  *
852  * Returns: a #GstIterator of #GstElements. gst_iterator_free after use.
853  */
854 GstIterator *
855 gst_bin_iterate_sinks (GstBin * bin)
856 {
857   GstIterator *children;
858   GstIterator *result;
859
860   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
861
862   children = gst_bin_iterate_elements (bin);
863   result = gst_iterator_filter (children,
864       (GCompareFunc) sink_iterator_filter, bin);
865
866   return result;
867 }
868
869 /* 2 phases:
870  *  1) check state of all children with 0 timeout to find ERROR and
871  *     NO_PREROLL elements. return if found.
872  *  2) perform full blocking wait with requested timeout.
873  *
874  * 2) cannot be performed when 1) returns results as the sinks might
875  *    not be able to complete the state change making 2) block forever.
876  *
877  * MT safe
878  */
879 static GstStateChangeReturn
880 gst_bin_get_state (GstElement * element, GstState * state,
881     GstState * pending, GTimeVal * timeout)
882 {
883   GstBin *bin = GST_BIN (element);
884   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
885   GList *children;
886   guint32 children_cookie;
887   gboolean have_no_preroll;
888
889   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "getting state");
890
891   /* lock bin, no element can be added or removed between going into
892    * the quick scan and the blocking wait. */
893   GST_LOCK (bin);
894
895 restart:
896   have_no_preroll = FALSE;
897
898   /* first we need to poll with a non zero timeout to make sure we don't block
899    * on the sinks when we have NO_PREROLL elements. This is why we do
900    * a quick check if there are still NO_PREROLL elements. We also
901    * catch the error elements this way. */
902   {
903     GTimeVal tv;
904     gboolean have_async = FALSE;
905
906     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "checking for NO_PREROLL");
907     /* use 0 timeout so we don't block on the sinks */
908     GST_TIME_TO_TIMEVAL (0, tv);
909     children = bin->children;
910     children_cookie = bin->children_cookie;
911     while (children) {
912       GstElement *child = GST_ELEMENT_CAST (children->data);
913
914       gst_object_ref (child);
915       /* now we release the lock to enter a non blocking wait. We
916        * release the lock anyway since we can. */
917       GST_UNLOCK (bin);
918
919       ret = gst_element_get_state (child, NULL, NULL, &tv);
920
921       gst_object_unref (child);
922
923       /* now grab the lock to iterate to the next child */
924       GST_LOCK (bin);
925       if (G_UNLIKELY (children_cookie != bin->children_cookie)) {
926         /* child added/removed during state change, restart. We need
927          * to restart with the quick check as a no-preroll element could
928          * have been added here and we don't want to block on sinks then.*/
929         goto restart;
930       }
931
932       switch (ret) {
933           /* report FAILURE  immediatly */
934         case GST_STATE_CHANGE_FAILURE:
935           goto done;
936         case GST_STATE_CHANGE_NO_PREROLL:
937           /* we have to continue scanning as there might be
938            * ERRORS too */
939           have_no_preroll = TRUE;
940           break;
941         case GST_STATE_CHANGE_ASYNC:
942           have_async = TRUE;
943           break;
944         default:
945           break;
946       }
947       children = g_list_next (children);
948     }
949     /* if we get here, we have no FAILURES, check for any NO_PREROLL
950      * elements then. */
951     if (have_no_preroll) {
952       ret = GST_STATE_CHANGE_NO_PREROLL;
953       goto done;
954     }
955
956     /* if we get here, no NO_PREROLL elements are in the pipeline */
957     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "no NO_PREROLL elements");
958
959     /* if no ASYNC elements exist we don't even have to poll with a
960      * timeout again */
961     if (!have_async) {
962       ret = GST_STATE_CHANGE_SUCCESS;
963       goto done;
964     }
965   }
966
967   /* next we poll all children for their state to see if one of them
968    * is still busy with its state change. We did not release the bin lock
969    * yet so the elements are the same as the ones from the quick scan. */
970   children = bin->children;
971   children_cookie = bin->children_cookie;
972   while (children) {
973     GstElement *child = GST_ELEMENT_CAST (children->data);
974
975     gst_object_ref (child);
976     /* now we release the lock to enter the potentialy blocking wait */
977     GST_UNLOCK (bin);
978
979     /* ret is ASYNC if some child is still performing the state change
980      * ater the timeout. */
981     ret = gst_element_get_state (child, NULL, NULL, timeout);
982
983     gst_object_unref (child);
984
985     /* now grab the lock to iterate to the next child */
986     GST_LOCK (bin);
987     if (G_UNLIKELY (children_cookie != bin->children_cookie)) {
988       /* child added/removed during state change, restart. We need
989        * to restart with the quick check as a no-preroll element could
990        * have been added here and we don't want to block on sinks then.*/
991       goto restart;
992     }
993
994     switch (ret) {
995       case GST_STATE_CHANGE_SUCCESS:
996         break;
997       case GST_STATE_CHANGE_FAILURE:
998       case GST_STATE_CHANGE_NO_PREROLL:
999         /* report FAILURE and NO_PREROLL immediatly */
1000         goto done;
1001       case GST_STATE_CHANGE_ASYNC:
1002         goto done;
1003       default:
1004         g_assert_not_reached ();
1005     }
1006     children = g_list_next (children);
1007   }
1008   /* if we got here, all elements can do preroll */
1009   have_no_preroll = FALSE;
1010
1011 done:
1012   GST_UNLOCK (bin);
1013
1014   /* now we can take the state lock, it is possible that new elements
1015    * are added now and we still report the old state. No problem though as
1016    * the return is still consistent, the effect is as if the element was
1017    * added after this function completed. */
1018   GST_STATE_LOCK (bin);
1019   switch (ret) {
1020     case GST_STATE_CHANGE_SUCCESS:
1021       /* we can commit the state */
1022       gst_element_commit_state (element);
1023       break;
1024     case GST_STATE_CHANGE_FAILURE:
1025       /* some element failed, abort the state change */
1026       gst_element_abort_state (element);
1027       break;
1028     default:
1029       /* other cases are just passed along */
1030       break;
1031   }
1032
1033   /* and report the state if needed */
1034   if (state)
1035     *state = GST_STATE (element);
1036   if (pending)
1037     *pending = GST_STATE_PENDING (element);
1038
1039   GST_STATE_NO_PREROLL (element) = have_no_preroll;
1040
1041   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1042       "state current: %s, pending: %s, error: %d, no_preroll: %d, result: %d",
1043       gst_element_state_get_name (GST_STATE (element)),
1044       gst_element_state_get_name (GST_STATE_PENDING (element)),
1045       GST_STATE_ERROR (element), GST_STATE_NO_PREROLL (element), ret);
1046
1047   GST_STATE_UNLOCK (bin);
1048
1049   return ret;
1050 }
1051
1052 /***********************************************
1053  * Topologically sorted iterator 
1054  * see http://en.wikipedia.org/wiki/Topological_sorting
1055  *
1056  * For each element in the graph, an entry is kept in a HashTable
1057  * with its number of srcpad connections (degree). 
1058  * We then change state of all elements without dependencies 
1059  * (degree 0) and decrement the degree of all elements connected
1060  * on the sinkpads. When an element reaches degree 0, its state is
1061  * changed next.
1062  * When all elements are handled the algorithm stops.
1063  */
1064 typedef struct _GstBinSortIterator
1065 {
1066   GstIterator it;
1067   GQueue *queue;                /* elements queued for state change */
1068   GstBin *bin;                  /* bin we iterate */
1069   gint mode;                    /* adding or removing dependency */
1070   GstElement *best;             /* next element with least dependencies */
1071   gint best_deg;                /* best degree */
1072   GHashTable *hash;             /* has table with element dependencies */
1073 } GstBinSortIterator;
1074
1075 /* we add and subtract 1 to make sure we don't confuse NULL and 0 */
1076 #define HASH_SET_DEGREE(bit, elem, deg) \
1077     g_hash_table_replace (bit->hash, elem, GINT_TO_POINTER(deg+1))
1078 #define HASH_GET_DEGREE(bit, elem) \
1079     (GPOINTER_TO_INT(g_hash_table_lookup (bit->hash, elem))-1)
1080
1081 /* add element to queue of next elements in the iterator.
1082  * We push at the tail to give higher priority elements a
1083  * chance first */
1084 static void
1085 add_to_queue (GstBinSortIterator * bit, GstElement * element)
1086 {
1087   GST_DEBUG ("%s add to queue", GST_ELEMENT_NAME (element));
1088   gst_object_ref (element);
1089   g_queue_push_tail (bit->queue, element);
1090   HASH_SET_DEGREE (bit, element, -1);
1091 }
1092
1093 /* clear the queue, unref all objects as we took a ref when
1094  * we added them to the queue */
1095 static void
1096 clear_queue (GQueue * queue)
1097 {
1098   gpointer p;
1099
1100   while ((p = g_queue_pop_head (queue)))
1101     gst_object_unref (p);
1102 }
1103
1104 /* set all degrees to 0. Elements marked as a sink are
1105  * added to the queue immediatly. */
1106 static void
1107 reset_degree (GstElement * element, GstBinSortIterator * bit)
1108 {
1109   /* sinks are added right away */
1110   if (GST_FLAG_IS_SET (element, GST_ELEMENT_IS_SINK)) {
1111     add_to_queue (bit, element);
1112   } else {
1113     /* others are marked with 0 and handled when sinks are done */
1114     HASH_SET_DEGREE (bit, element, 0);
1115   }
1116 }
1117
1118 /* adjust the degree of all elements connected to the given
1119  * element. If an degree of an element drops to 0, it is
1120  * added to the queue of elements to schedule next.
1121  *
1122  * We have to make sure not to cross the bin boundary this element
1123  * belongs to.
1124  */
1125 static void
1126 update_degree (GstElement * element, GstBinSortIterator * bit)
1127 {
1128   gboolean linked = FALSE;
1129
1130   GST_LOCK (element);
1131   /* don't touch degree is element has no sourcepads */
1132   if (element->numsinkpads != 0) {
1133     /* loop over all sinkpads, decrement degree for all connected
1134      * elements in this bin */
1135     GList *pads;
1136
1137     for (pads = element->sinkpads; pads; pads = g_list_next (pads)) {
1138       GstPad *peer;
1139
1140       if ((peer = gst_pad_get_peer (GST_PAD_CAST (pads->data)))) {
1141         GstElement *peer_element;
1142
1143         if ((peer_element = gst_pad_get_parent_element (peer))) {
1144           GST_LOCK (peer_element);
1145           if (GST_OBJECT_CAST (peer_element)->parent ==
1146               GST_OBJECT_CAST (bit->bin)) {
1147             gint old_deg, new_deg;
1148
1149             old_deg = HASH_GET_DEGREE (bit, peer_element);
1150             new_deg = old_deg + bit->mode;
1151
1152             GST_DEBUG ("change element %s, degree %d->%d, linked to %s",
1153                 GST_ELEMENT_NAME (peer_element),
1154                 old_deg, new_deg, GST_ELEMENT_NAME (element));
1155
1156             /* update degree */
1157             if (new_deg == 0) {
1158               /* degree hit 0, add to queue */
1159               add_to_queue (bit, peer_element);
1160             } else {
1161               HASH_SET_DEGREE (bit, peer_element, new_deg);
1162             }
1163             linked = TRUE;
1164           }
1165           GST_UNLOCK (peer_element);
1166           gst_object_unref (peer_element);
1167         }
1168         gst_object_unref (peer);
1169       }
1170     }
1171   }
1172   if (!linked) {
1173     GST_DEBUG ("element %s not linked to anything", GST_ELEMENT_NAME (element));
1174   }
1175   GST_UNLOCK (element);
1176 }
1177
1178 /* find the next best element not handled yet. This is the one
1179  * with the lowest non-negative degree */
1180 static void
1181 find_element (GstElement * element, GstBinSortIterator * bit)
1182 {
1183   gint degree;
1184
1185   /* element is already handled */
1186   if ((degree = HASH_GET_DEGREE (bit, element)) < 0)
1187     return;
1188
1189   /* first element or element with smaller degree */
1190   if (bit->best == NULL || bit->best_deg > degree) {
1191     bit->best = element;
1192     bit->best_deg = degree;
1193   }
1194 }
1195
1196 /* get next element in iterator. the returned element has the
1197  * refcount increased */
1198 static GstIteratorResult
1199 gst_bin_sort_iterator_next (GstBinSortIterator * bit, gpointer * result)
1200 {
1201   /* empty queue, we have to find a next best element */
1202   if (g_queue_is_empty (bit->queue)) {
1203     bit->best = NULL;
1204     bit->best_deg = G_MAXINT;
1205     g_list_foreach (bit->bin->children, (GFunc) find_element, bit);
1206     if (bit->best) {
1207       if (bit->best_deg != 0) {
1208         /* we don't fail on this one yet */
1209         g_warning ("loop detected in the graph !!");
1210       }
1211       /* best unhandled element, schedule as next element */
1212       GST_DEBUG ("queue empty, next best: %s", GST_ELEMENT_NAME (bit->best));
1213       gst_object_ref (bit->best);
1214       HASH_SET_DEGREE (bit, bit->best, -1);
1215       *result = bit->best;
1216     } else {
1217       GST_DEBUG ("queue empty, elements exhausted");
1218       /* no more unhandled elements, we are done */
1219       return GST_ITERATOR_DONE;
1220     }
1221   } else {
1222     /* everything added to the queue got reffed */
1223     *result = g_queue_pop_head (bit->queue);
1224   }
1225
1226   GST_DEBUG ("queue head gives %s", GST_ELEMENT_NAME (*result));
1227   /* update degrees of linked elements */
1228   update_degree (GST_ELEMENT_CAST (*result), bit);
1229
1230   return GST_ITERATOR_OK;
1231 }
1232
1233 /* clear queues, recalculate the degrees and restart. */
1234 static void
1235 gst_bin_sort_iterator_resync (GstBinSortIterator * bit)
1236 {
1237   clear_queue (bit->queue);
1238   /* reset degrees */
1239   g_list_foreach (bit->bin->children, (GFunc) reset_degree, bit);
1240   /* calc degrees, incrementing */
1241   bit->mode = 1;
1242   g_list_foreach (bit->bin->children, (GFunc) update_degree, bit);
1243   /* for the rest of the function we decrement the degrees */
1244   bit->mode = -1;
1245 }
1246
1247 /* clear queues, unref bin and free iterator. */
1248 static void
1249 gst_bin_sort_iterator_free (GstBinSortIterator * bit)
1250 {
1251   clear_queue (bit->queue);
1252   g_queue_free (bit->queue);
1253   g_hash_table_destroy (bit->hash);
1254   gst_object_unref (bit->bin);
1255   g_free (bit);
1256 }
1257
1258 /**
1259  * gst_bin_iterate_sorted:
1260  * @bin: #Gstbin to iterate on
1261  *
1262  * Get an iterator for the elements in this bin in topologically
1263  * sorted order. This means that the elements are returned from
1264  * the most downstream elements (sinks) to the sources.
1265  *
1266  * This function is used internally to perform the state changes 
1267  * of the bin elements.
1268  *
1269  * Each element will have its refcount increased, so unref
1270  * after use.
1271  *
1272  * MT safe. 
1273  *
1274  * Returns: a #GstIterator of #GstElements. gst_iterator_free after use.
1275  */
1276 GstIterator *
1277 gst_bin_iterate_sorted (GstBin * bin)
1278 {
1279   GstBinSortIterator *result;
1280
1281   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1282
1283   GST_LOCK (bin);
1284   gst_object_ref (bin);
1285   /* we don't need a NextFunction because we ref the items in the _next
1286    * method already */
1287   result = (GstBinSortIterator *)
1288       gst_iterator_new (sizeof (GstBinSortIterator),
1289       GST_GET_LOCK (bin),
1290       &bin->children_cookie,
1291       (GstIteratorNextFunction) gst_bin_sort_iterator_next,
1292       (GstIteratorItemFunction) NULL,
1293       (GstIteratorResyncFunction) gst_bin_sort_iterator_resync,
1294       (GstIteratorFreeFunction) gst_bin_sort_iterator_free);
1295   result->queue = g_queue_new ();
1296   result->hash = g_hash_table_new (NULL, NULL);
1297   result->bin = bin;
1298   gst_bin_sort_iterator_resync (result);
1299   GST_UNLOCK (bin);
1300
1301   return (GstIterator *) result;
1302 }
1303
1304 static GstStateChangeReturn
1305 gst_bin_element_set_state (GstBin * bin, GstElement * element, GstState pending)
1306 {
1307   GstStateChangeReturn ret;
1308   gboolean locked;
1309
1310   /* peel off the locked flag */
1311   GST_LOCK (element);
1312   locked = GST_FLAG_IS_SET (element, GST_ELEMENT_LOCKED_STATE);
1313   GST_UNLOCK (element);
1314
1315   /* skip locked elements */
1316   if (G_UNLIKELY (locked)) {
1317     ret = GST_STATE_CHANGE_SUCCESS;
1318     goto done;
1319   }
1320
1321   /* change state */
1322   ret = gst_element_set_state (element, pending);
1323
1324 done:
1325   return ret;
1326 }
1327
1328 static GstStateChangeReturn
1329 gst_bin_change_state (GstElement * element, GstStateChange transition)
1330 {
1331   GstBin *bin;
1332   GstStateChangeReturn ret;
1333   GstState old_state, pending;
1334   gboolean have_async;
1335   gboolean have_no_preroll;
1336   GstClockTime base_time;
1337   GstIterator *it;
1338   gboolean done;
1339
1340   /* we don't need to take the STATE_LOCK, it is already taken */
1341   old_state = GST_STATE (element);
1342   pending = GST_STATE_PENDING (element);
1343
1344   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
1345       "changing state of children from %s to %s",
1346       gst_element_state_get_name (old_state),
1347       gst_element_state_get_name (pending));
1348
1349   if (pending == GST_STATE_VOID_PENDING)
1350     return GST_STATE_CHANGE_SUCCESS;
1351
1352   bin = GST_BIN_CAST (element);
1353
1354   /* Clear eosed element list on READY-> PAUSED */
1355   if (transition == GST_STATE_CHANGE_READY_TO_PAUSED) {
1356     g_list_free (bin->eosed);
1357     bin->eosed = NULL;
1358   }
1359
1360   /* iterate in state change order */
1361   it = gst_bin_iterate_sorted (bin);
1362
1363 restart:
1364   /* take base time */
1365   base_time = element->base_time;
1366
1367   have_async = FALSE;
1368   have_no_preroll = FALSE;
1369
1370   done = FALSE;
1371   while (!done) {
1372     gpointer data;
1373
1374     switch (gst_iterator_next (it, &data)) {
1375       case GST_ITERATOR_OK:
1376       {
1377         GstElement *element;
1378
1379         element = GST_ELEMENT_CAST (data);
1380
1381         /* set base time on element */
1382         gst_element_set_base_time (element, base_time);
1383
1384         /* set state now */
1385         ret = gst_bin_element_set_state (bin, element, pending);
1386
1387         switch (ret) {
1388           case GST_STATE_CHANGE_SUCCESS:
1389             GST_CAT_DEBUG (GST_CAT_STATES,
1390                 "child '%s' changed state to %d(%s) successfully",
1391                 GST_ELEMENT_NAME (element), pending,
1392                 gst_element_state_get_name (pending));
1393             break;
1394           case GST_STATE_CHANGE_ASYNC:
1395             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1396                 "child '%s' is changing state asynchronously",
1397                 GST_ELEMENT_NAME (element));
1398             have_async = TRUE;
1399             break;
1400           case GST_STATE_CHANGE_FAILURE:
1401             GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1402                 "child '%s' failed to go to state %d(%s)",
1403                 GST_ELEMENT_NAME (element),
1404                 pending, gst_element_state_get_name (pending));
1405             gst_object_unref (element);
1406             goto done;
1407           case GST_STATE_CHANGE_NO_PREROLL:
1408             GST_CAT_DEBUG (GST_CAT_STATES,
1409                 "child '%s' changed state to %d(%s) successfully without preroll",
1410                 GST_ELEMENT_NAME (element), pending,
1411                 gst_element_state_get_name (pending));
1412             have_no_preroll = TRUE;
1413             break;
1414           default:
1415             g_assert_not_reached ();
1416             break;
1417         }
1418         gst_object_unref (element);
1419         break;
1420       }
1421       case GST_ITERATOR_RESYNC:
1422         GST_CAT_DEBUG (GST_CAT_STATES, "iterator doing resync");
1423         gst_iterator_resync (it);
1424         goto restart;
1425         break;
1426       default:
1427       case GST_ITERATOR_DONE:
1428         GST_CAT_DEBUG (GST_CAT_STATES, "iterator done");
1429         done = TRUE;
1430         break;
1431     }
1432   }
1433
1434   if (have_no_preroll) {
1435     ret = GST_STATE_CHANGE_NO_PREROLL;
1436   } else if (have_async) {
1437     ret = GST_STATE_CHANGE_ASYNC;
1438   } else {
1439     ret = parent_class->change_state (element, transition);
1440   }
1441
1442 done:
1443   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
1444       "done changing bin's state from %s to %s, now in %s, ret %d",
1445       gst_element_state_get_name (old_state),
1446       gst_element_state_get_name (pending),
1447       gst_element_state_get_name (GST_STATE (element)), ret);
1448
1449   gst_iterator_free (it);
1450
1451   return ret;
1452 }
1453
1454 static void
1455 gst_bin_dispose (GObject * object)
1456 {
1457   GstBin *bin = GST_BIN (object);
1458
1459   GST_CAT_DEBUG_OBJECT (GST_CAT_REFCOUNTING, object, "dispose");
1460
1461   g_list_free (bin->eosed);
1462   bin->eosed = NULL;
1463   gst_object_unref (bin->child_bus);
1464   bin->child_bus = NULL;
1465
1466   while (bin->children) {
1467     gst_bin_remove (bin, GST_ELEMENT (bin->children->data));
1468   }
1469   if (G_UNLIKELY (bin->children != NULL)) {
1470     g_critical ("could not remove elements from bin %s",
1471         GST_STR_NULL (GST_OBJECT_NAME (object)));
1472   }
1473
1474   G_OBJECT_CLASS (parent_class)->dispose (object);
1475 }
1476
1477 /*
1478  * This function is a utility event handler for seek events.
1479  * It will send the event to all sinks.
1480  * Applications are free to override this behaviour and
1481  * implement their own seek handler, but this will work for
1482  * pretty much all cases in practice.
1483  */
1484 static gboolean
1485 gst_bin_send_event (GstElement * element, GstEvent * event)
1486 {
1487   GstBin *bin = GST_BIN (element);
1488   GstIterator *iter;
1489   gboolean res = TRUE;
1490   gboolean done = FALSE;
1491
1492   iter = gst_bin_iterate_sinks (bin);
1493   GST_DEBUG_OBJECT (bin, "Sending event to sink children");
1494
1495   while (!done) {
1496     gpointer data;
1497
1498     switch (gst_iterator_next (iter, &data)) {
1499       case GST_ITERATOR_OK:
1500       {
1501         GstElement *sink;
1502
1503         gst_event_ref (event);
1504         sink = GST_ELEMENT_CAST (data);
1505         res &= gst_element_send_event (sink, event);
1506         gst_object_unref (sink);
1507         break;
1508       }
1509       case GST_ITERATOR_RESYNC:
1510         gst_iterator_resync (iter);
1511         res = TRUE;
1512         break;
1513       default:
1514       case GST_ITERATOR_DONE:
1515         done = TRUE;
1516         break;
1517     }
1518   }
1519   gst_iterator_free (iter);
1520   gst_event_unref (event);
1521
1522   return res;
1523 }
1524
1525 static GstBusSyncReply
1526 bin_bus_handler (GstBus * bus, GstMessage * message, GstBin * bin)
1527 {
1528   GST_DEBUG_OBJECT (bin, "[msg %p] handling child message of type %s",
1529       message, gst_message_type_get_name (GST_MESSAGE_TYPE (message)));
1530
1531   switch (GST_MESSAGE_TYPE (message)) {
1532     case GST_MESSAGE_EOS:{
1533       GstObject *src = GST_MESSAGE_SRC (message);
1534
1535       if (src) {
1536         gchar *name;
1537
1538         name = gst_object_get_name (src);
1539         GST_DEBUG_OBJECT (bin, "got EOS message from %s", name);
1540         g_free (name);
1541
1542         /* collect all eos messages from the children */
1543         GST_LOCK (bin->child_bus);
1544         bin->eosed = g_list_prepend (bin->eosed, src);
1545         GST_UNLOCK (bin->child_bus);
1546
1547         /* if we are completely EOS, we forward an EOS message */
1548         if (is_eos (bin)) {
1549           GST_DEBUG_OBJECT (bin, "all sinks posted EOS");
1550           gst_element_post_message (GST_ELEMENT (bin),
1551               gst_message_new_eos (GST_OBJECT (bin)));
1552         }
1553       } else {
1554         GST_DEBUG_OBJECT (bin, "got EOS message from (NULL), not processing");
1555       }
1556
1557       /* we drop all EOS messages */
1558       gst_message_unref (message);
1559       break;
1560     }
1561     default:
1562       /* Send all other messages upward */
1563       GST_DEBUG_OBJECT (bin, "posting message upward");
1564       gst_element_post_message (GST_ELEMENT (bin), message);
1565       break;
1566   }
1567
1568   return GST_BUS_DROP;
1569 }
1570
1571 static gboolean
1572 gst_bin_query (GstElement * element, GstQuery * query)
1573 {
1574   GstBin *bin = GST_BIN (element);
1575   GstIterator *iter;
1576   gboolean res = FALSE, done = FALSE;
1577
1578   iter = gst_bin_iterate_sinks (bin);
1579   GST_DEBUG_OBJECT (bin, "Sending event to sink children");
1580
1581   while (!(res || done)) {
1582     gpointer data;
1583
1584     switch (gst_iterator_next (iter, &data)) {
1585       case GST_ITERATOR_OK:
1586       {
1587         GstElement *sink;
1588
1589         sink = GST_ELEMENT_CAST (data);
1590         res = gst_element_query (sink, query);
1591         gst_object_unref (sink);
1592         break;
1593       }
1594       case GST_ITERATOR_RESYNC:
1595         gst_iterator_resync (iter);
1596         break;
1597       default:
1598       case GST_ITERATOR_DONE:
1599         done = TRUE;
1600         break;
1601     }
1602   }
1603   gst_iterator_free (iter);
1604
1605   return res;
1606 }
1607
1608 static gint
1609 compare_name (GstElement * element, const gchar * name)
1610 {
1611   gint eq;
1612
1613   GST_LOCK (element);
1614   eq = strcmp (GST_ELEMENT_NAME (element), name);
1615   GST_UNLOCK (element);
1616
1617   if (eq != 0) {
1618     gst_object_unref (element);
1619   }
1620   return eq;
1621 }
1622
1623 /**
1624  * gst_bin_get_by_name:
1625  * @bin: #Gstbin to search
1626  * @name: the element name to search for
1627  *
1628  * Get the element with the given name from this bin. This
1629  * function recurses into subbins.
1630  *
1631  * MT safe.
1632  *
1633  * Returns: the element with the given name. Returns NULL if the
1634  * element is not found or when bad parameters were given. Unref after
1635  * use.
1636  */
1637 GstElement *
1638 gst_bin_get_by_name (GstBin * bin, const gchar * name)
1639 {
1640   GstIterator *children;
1641   GstIterator *result;
1642
1643   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1644
1645   GST_CAT_INFO (GST_CAT_PARENTAGE, "[%s]: looking up child element %s",
1646       GST_ELEMENT_NAME (bin), name);
1647
1648   children = gst_bin_iterate_recurse (bin);
1649   result = gst_iterator_find_custom (children,
1650       (GCompareFunc) compare_name, (gpointer) name);
1651   gst_iterator_free (children);
1652
1653   return GST_ELEMENT_CAST (result);
1654 }
1655
1656 /**
1657  * gst_bin_get_by_name_recurse_up:
1658  * @bin: #Gstbin to search
1659  * @name: the element name to search for
1660  *
1661  * MT safe.
1662  *
1663  * Get the element with the given name from this bin. If the
1664  * element is not found, a recursion is performed on the parent bin.
1665  *
1666  * Returns: the element with the given name or NULL when the element
1667  * was not found or bad parameters were given. Unref after use.
1668  */
1669 GstElement *
1670 gst_bin_get_by_name_recurse_up (GstBin * bin, const gchar * name)
1671 {
1672   GstElement *result;
1673
1674   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1675   g_return_val_if_fail (name != NULL, NULL);
1676
1677   result = gst_bin_get_by_name (bin, name);
1678
1679   if (!result) {
1680     GstObject *parent;
1681
1682     parent = gst_object_get_parent (GST_OBJECT_CAST (bin));
1683     if (parent) {
1684       if (GST_IS_BIN (parent)) {
1685         result = gst_bin_get_by_name_recurse_up (GST_BIN_CAST (parent), name);
1686       }
1687       gst_object_unref (parent);
1688     }
1689   }
1690
1691   return result;
1692 }
1693
1694 static gint
1695 compare_interface (GstElement * element, gpointer interface)
1696 {
1697   gint ret;
1698
1699   if (G_TYPE_CHECK_INSTANCE_TYPE (element, GPOINTER_TO_INT (interface))) {
1700     ret = 0;
1701   } else {
1702     /* we did not find the element, need to release the ref
1703      * added by the iterator */
1704     gst_object_unref (element);
1705     ret = 1;
1706   }
1707   return ret;
1708 }
1709
1710 /**
1711  * gst_bin_get_by_interface:
1712  * @bin: bin to find element in
1713  * @interface: interface to be implemented by interface
1714  *
1715  * Looks for the first element inside the bin that implements the given
1716  * interface. If such an element is found, it returns the element. You can
1717  * cast this element to the given interface afterwards.
1718  * If you want all elements that implement the interface, use
1719  * gst_bin_iterate_all_by_interface(). The function recurses inside bins.
1720  *
1721  * MT safe.
1722  *
1723  * Returns: An #GstElement inside the bin implementing the interface.
1724  *          Unref after use.
1725  */
1726 GstElement *
1727 gst_bin_get_by_interface (GstBin * bin, GType interface)
1728 {
1729   GstIterator *children;
1730   GstIterator *result;
1731
1732   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1733
1734   children = gst_bin_iterate_recurse (bin);
1735   result = gst_iterator_find_custom (children, (GCompareFunc) compare_interface,
1736       GINT_TO_POINTER (interface));
1737   gst_iterator_free (children);
1738
1739   return GST_ELEMENT_CAST (result);
1740 }
1741
1742 /**
1743  * gst_bin_iterate_all_by_interface:
1744  * @bin: bin to find elements in
1745  * @interface: interface to be implemented by interface
1746  *
1747  * Looks for all elements inside the bin that implements the given
1748  * interface. You can safely cast all returned elements to the given interface.
1749  * The function recurses bins inside bins. The iterator will return a series
1750  * of #GstElement that should be unreffed after use.
1751  *
1752  * MT safe.
1753  *
1754  * Returns: A #GstIterator for the elements inside the bin implementing the
1755  *          given interface.
1756  */
1757 GstIterator *
1758 gst_bin_iterate_all_by_interface (GstBin * bin, GType interface)
1759 {
1760   GstIterator *children;
1761   GstIterator *result;
1762
1763   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
1764
1765   children = gst_bin_iterate_recurse (bin);
1766   result = gst_iterator_filter (children, (GCompareFunc) compare_interface,
1767       GINT_TO_POINTER (interface));
1768
1769   return result;
1770 }
1771
1772 #ifndef GST_DISABLE_LOADSAVE
1773 static xmlNodePtr
1774 gst_bin_save_thyself (GstObject * object, xmlNodePtr parent)
1775 {
1776   GstBin *bin = GST_BIN (object);
1777   xmlNodePtr childlist, elementnode;
1778   GList *children;
1779   GstElement *child;
1780
1781   if (GST_OBJECT_CLASS (parent_class)->save_thyself)
1782     GST_OBJECT_CLASS (parent_class)->save_thyself (GST_OBJECT (bin), parent);
1783
1784   childlist = xmlNewChild (parent, NULL, (xmlChar *) "children", NULL);
1785
1786   GST_CAT_INFO (GST_CAT_XML, "[%s]: saving %d children",
1787       GST_ELEMENT_NAME (bin), bin->numchildren);
1788
1789   children = bin->children;
1790   while (children) {
1791     child = GST_ELEMENT (children->data);
1792     elementnode = xmlNewChild (childlist, NULL, (xmlChar *) "element", NULL);
1793     gst_object_save_thyself (GST_OBJECT (child), elementnode);
1794     children = g_list_next (children);
1795   }
1796   return childlist;
1797 }
1798
1799 static void
1800 gst_bin_restore_thyself (GstObject * object, xmlNodePtr self)
1801 {
1802   GstBin *bin = GST_BIN (object);
1803   xmlNodePtr field = self->xmlChildrenNode;
1804   xmlNodePtr childlist;
1805
1806   while (field) {
1807     if (!strcmp ((char *) field->name, "children")) {
1808       GST_CAT_INFO (GST_CAT_XML, "[%s]: loading children",
1809           GST_ELEMENT_NAME (object));
1810       childlist = field->xmlChildrenNode;
1811       while (childlist) {
1812         if (!strcmp ((char *) childlist->name, "element")) {
1813           GstElement *element =
1814               gst_xml_make_element (childlist, GST_OBJECT (bin));
1815
1816           /* it had to be parented to find the pads, now we ref and unparent so
1817            * we can add it to the bin */
1818           gst_object_ref (element);
1819           gst_object_unparent (GST_OBJECT (element));
1820
1821           gst_bin_add (bin, element);
1822         }
1823         childlist = childlist->next;
1824       }
1825     }
1826
1827     field = field->next;
1828   }
1829   if (GST_OBJECT_CLASS (parent_class)->restore_thyself)
1830     (GST_OBJECT_CLASS (parent_class)->restore_thyself) (object, self);
1831 }
1832 #endif /* GST_DISABLE_LOADSAVE */