tizen 2.3 release
[framework/multimedia/gst-plugins-base0.10.git] / gst / playback / gstdecodebin.c
1 /* GStreamer
2  * Copyright (C) <2004> Wim Taymans <wim.taymans@gmail.com>
3  * Copyright (C) 2011 Hewlett-Packard Development Company, L.P.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-decodebin
23  *
24  * #GstBin that auto-magically constructs a decoding pipeline using available
25  * decoders and demuxers via auto-plugging.
26  *
27  * When using decodebin in your application, connect a signal handler to
28  * #GstDecodeBin::new-decoded-pad and connect your sinks from within the
29  * callback function.
30  *
31  * <note>
32  * This element is deprecated and no longer supported. You should use the
33  * #uridecodebin or #decodebin2 element instead (or, even better: #playbin2).
34  * </note>
35  *
36  * Deprecated: use uridecodebin or decodebin2 instead.
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
42
43 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
44  * with newer GLib versions (>= 2.31.0) */
45 #define GLIB_DISABLE_DEPRECATION_WARNINGS
46
47 #include <gst/gst-i18n-plugin.h>
48
49 #include <string.h>
50 #include <gst/gst.h>
51 #include <gst/pbutils/pbutils.h>
52 #include "gst/glib-compat-private.h"
53
54 #include "gstplay-marshal.h"
55
56 /* generic templates */
57 static GstStaticPadTemplate decoder_bin_sink_template =
58 GST_STATIC_PAD_TEMPLATE ("sink",
59     GST_PAD_SINK,
60     GST_PAD_ALWAYS,
61     GST_STATIC_CAPS_ANY);
62
63 static GstStaticPadTemplate decoder_bin_src_template =
64 GST_STATIC_PAD_TEMPLATE ("src%d",
65     GST_PAD_SRC,
66     GST_PAD_SOMETIMES,
67     GST_STATIC_CAPS_ANY);
68
69 GST_DEBUG_CATEGORY_STATIC (gst_decode_bin_debug);
70 #define GST_CAT_DEFAULT gst_decode_bin_debug
71
72 #define GST_TYPE_DECODE_BIN             (gst_decode_bin_get_type())
73 #define GST_DECODE_BIN(obj)             (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DECODE_BIN,GstDecodeBin))
74 #define GST_DECODE_BIN_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_DECODE_BIN,GstDecodeBinClass))
75 #define GST_IS_DECODE_BIN(obj)          (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_DECODE_BIN))
76 #define GST_IS_DECODE_BIN_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_DECODE_BIN))
77
78 typedef struct _GstDecodeBin GstDecodeBin;
79 typedef struct _GstDecodeBinClass GstDecodeBinClass;
80
81 /**
82  * GstDecodeBin:
83  *
84  * Auto-plugging decoder element structure
85  */
86 struct _GstDecodeBin
87 {
88   GstBin bin;                   /* we extend GstBin */
89
90   GstElement *typefind;         /* this holds the typefind object */
91   GstElement *fakesink;
92
93   GList *dynamics;              /* list of dynamic connections */
94
95   GList *queues;                /* list of demuxer-decoder queues */
96
97   GList *probes;                /* list of PadProbeData */
98
99   GList *factories;             /* factories we can use for selecting elements */
100   gint numpads;
101   gint numwaiting;
102
103   gboolean have_type;
104   guint have_type_id;           /* signal id for the typefind element */
105
106   gboolean shutting_down;       /* stop pluggin if we're shutting down */
107
108   GType queue_type;             /* store the GType of queues, to aid in recognising them */
109
110   GMutex *cb_mutex;             /* Mutex for multi-threaded callbacks, such as removing the fakesink */
111 };
112
113 struct _GstDecodeBinClass
114 {
115   GstBinClass parent_class;
116
117   /* signal we fire when a new pad has been decoded into raw audio/video */
118   void (*new_decoded_pad) (GstElement * element, GstPad * pad, gboolean last);
119   /* signal we fire when a pad has been removed */
120   void (*removed_decoded_pad) (GstElement * element, GstPad * pad);
121   /* signal fired when we found a pad that we cannot decode */
122   void (*unknown_type) (GstElement * element, GstPad * pad, GstCaps * caps);
123 };
124
125 /* signals */
126 enum
127 {
128   SIGNAL_NEW_DECODED_PAD,
129   SIGNAL_REMOVED_DECODED_PAD,
130   SIGNAL_UNKNOWN_TYPE,
131   SIGNAL_REDIRECT,
132   LAST_SIGNAL
133 };
134
135 /* Properties */
136 enum
137 {
138   PROP_0,
139   PROP_SINK_CAPS,
140 };
141
142
143 typedef struct
144 {
145   GstPad *pad;
146   gulong sigid;
147   gboolean done;
148 } PadProbeData;
149
150 /* this structure is created for all dynamic pads that could get created
151  * at runtime */
152 typedef struct
153 {
154   GstDecodeBin *decode_bin;     /* pointer to ourself */
155
156   GstElement *element;          /* the element sending the signal */
157   gint np_sig_id;               /* signal id of new_pad */
158   gint nmp_sig_id;              /* signal id of no_more_pads */
159
160   GstPad *pad;                  /* the pad sending the signal */
161   gint caps_sig_id;             /* signal id of caps */
162 }
163 GstDynamic;
164
165 static void gst_decode_bin_class_init (GstDecodeBinClass * klass);
166 static void gst_decode_bin_init (GstDecodeBin * decode_bin);
167 static void gst_decode_bin_set_property (GObject * object, guint prop_id,
168     const GValue * value, GParamSpec * pspec);
169 static void gst_decode_bin_get_property (GObject * object, guint prop_id,
170     GValue * value, GParamSpec * pspec);
171 static void gst_decode_bin_dispose (GObject * object);
172 static void gst_decode_bin_finalize (GObject * object);
173
174 static GstStateChangeReturn gst_decode_bin_change_state (GstElement * element,
175     GstStateChange transition);
176
177 static gboolean add_fakesink (GstDecodeBin * decode_bin);
178 static void remove_fakesink (GstDecodeBin * decode_bin);
179
180 static void dynamic_free (GstDynamic * dyn);
181 static void free_dynamics (GstDecodeBin * decode_bin);
182 static void type_found (GstElement * typefind, guint probability,
183     GstCaps * caps, GstDecodeBin * decode_bin);
184 static GstElement *try_to_link_1 (GstDecodeBin * decode_bin,
185     GstElement * origelement, GstPad * pad, GList * factories);
186 static void close_link (GstElement * element, GstDecodeBin * decode_bin);
187 static void close_pad_link (GstElement * element, GstPad * pad,
188     GstCaps * caps, GstDecodeBin * decode_bin, gboolean more);
189 static void unlinked (GstPad * pad, GstPad * peerpad,
190     GstDecodeBin * decode_bin);
191 static void new_pad (GstElement * element, GstPad * pad, GstDynamic * dynamic);
192 static void no_more_pads (GstElement * element, GstDynamic * dynamic);
193 static void new_caps (GstPad * pad, GParamSpec * unused, GstDynamic * dynamic);
194
195 static void queue_filled_cb (GstElement * queue, GstDecodeBin * decode_bin);
196 static void queue_underrun_cb (GstElement * queue, GstDecodeBin * decode_bin);
197
198 static gboolean is_demuxer_element (GstElement * srcelement);
199
200 static GstElementClass *parent_class;
201 static guint gst_decode_bin_signals[LAST_SIGNAL] = { 0 };
202
203
204 static GType
205 gst_decode_bin_get_type (void)
206 {
207   static GType gst_decode_bin_type = 0;
208
209   if (!gst_decode_bin_type) {
210     static const GTypeInfo gst_decode_bin_info = {
211       sizeof (GstDecodeBinClass),
212       NULL,
213       NULL,
214       (GClassInitFunc) gst_decode_bin_class_init,
215       NULL,
216       NULL,
217       sizeof (GstDecodeBin),
218       0,
219       (GInstanceInitFunc) gst_decode_bin_init,
220       NULL
221     };
222
223     gst_decode_bin_type =
224         g_type_register_static (GST_TYPE_BIN, "GstDecodeBin",
225         &gst_decode_bin_info, 0);
226   }
227
228   return gst_decode_bin_type;
229 }
230
231 static void
232 gst_decode_bin_class_init (GstDecodeBinClass * klass)
233 {
234   GObjectClass *gobject_klass;
235   GstElementClass *gstelement_klass;
236
237   gobject_klass = (GObjectClass *) klass;
238   gstelement_klass = (GstElementClass *) klass;
239
240   parent_class = g_type_class_peek_parent (klass);
241
242   gobject_klass->set_property = gst_decode_bin_set_property;
243   gobject_klass->get_property = gst_decode_bin_get_property;
244   gobject_klass->dispose = gst_decode_bin_dispose;
245   gobject_klass->finalize = gst_decode_bin_finalize;
246
247   /**
248    * GstDecodeBin::new-decoded-pad:
249    * @bin: The decodebin
250    * @pad: The newly created pad
251    * @islast: #TRUE if this is the last pad to be added. Deprecated.
252    *
253    * This signal gets emitted as soon as a new pad of the same type as one of
254    * the valid 'raw' types is added.
255    */
256   gst_decode_bin_signals[SIGNAL_NEW_DECODED_PAD] =
257       g_signal_new ("new-decoded-pad", G_TYPE_FROM_CLASS (klass),
258       G_SIGNAL_RUN_LAST,
259       G_STRUCT_OFFSET (GstDecodeBinClass, new_decoded_pad), NULL, NULL,
260       gst_play_marshal_VOID__OBJECT_BOOLEAN, G_TYPE_NONE, 2, GST_TYPE_PAD,
261       G_TYPE_BOOLEAN);
262   /**
263    * GstDecodeBin::removed-decoded-pad:
264    * @bin: The decodebin
265    * @pad: The pad that was removed
266    *
267    * This signal is emitted when a 'final' caps pad has been removed.
268    */
269   gst_decode_bin_signals[SIGNAL_REMOVED_DECODED_PAD] =
270       g_signal_new ("removed-decoded-pad", G_TYPE_FROM_CLASS (klass),
271       G_SIGNAL_RUN_LAST,
272       G_STRUCT_OFFSET (GstDecodeBinClass, removed_decoded_pad), NULL, NULL,
273       gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_PAD);
274   /**
275    * GstDecodeBin::unknown-type:
276    * @bin: The decodebin
277    * @pad: The new pad containing caps that cannot be resolved to a 'final'
278    *       stream type.
279    * @caps: The #GstCaps of the pad that cannot be resolved.
280    *
281    * This signal is emitted when a pad for which there is no further possible
282    * decoding is added to the decodebin.
283    */
284   gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE] =
285       g_signal_new ("unknown-type", G_TYPE_FROM_CLASS (klass),
286       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, unknown_type),
287       NULL, NULL, gst_marshal_VOID__OBJECT_BOXED, G_TYPE_NONE, 2,
288       GST_TYPE_PAD, GST_TYPE_CAPS);
289
290   g_object_class_install_property (gobject_klass, PROP_SINK_CAPS,
291       g_param_spec_boxed ("sink-caps", "Sink Caps",
292           "The caps of the input data. (NULL = use typefind element)",
293           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
294
295   gst_element_class_add_static_pad_template (gstelement_klass,
296       &decoder_bin_sink_template);
297   gst_element_class_add_static_pad_template (gstelement_klass,
298       &decoder_bin_src_template);
299
300   gst_element_class_set_details_simple (gstelement_klass,
301       "Decoder Bin", "Generic/Bin/Decoder",
302       "Autoplug and decode to raw media",
303       "Wim Taymans <wim.taymans@gmail.com>");
304
305   gstelement_klass->change_state =
306       GST_DEBUG_FUNCPTR (gst_decode_bin_change_state);
307 }
308
309 /* check if the bin is dynamic.
310  *
311  * If there are no outstanding dynamic connections, the bin is
312  * considered to be non-dynamic.
313  */
314 static gboolean
315 gst_decode_bin_is_dynamic (GstDecodeBin * decode_bin)
316 {
317   return decode_bin->dynamics != NULL;
318 }
319
320 /* the filter function for selecting the elements we can use in
321  * autoplugging */
322 static gboolean
323 gst_decode_bin_factory_filter (GstPluginFeature * feature,
324     GstDecodeBin * decode_bin)
325 {
326   guint rank;
327   const gchar *klass;
328
329   /* we only care about element factories */
330   if (!GST_IS_ELEMENT_FACTORY (feature))
331     return FALSE;
332
333   klass = gst_element_factory_get_klass (GST_ELEMENT_FACTORY (feature));
334   /* only demuxers, decoders and parsers can play */
335   if (strstr (klass, "Demux") == NULL &&
336       strstr (klass, "Decoder") == NULL && strstr (klass, "Parse") == NULL &&
337       strstr (klass, "Depayloader") == NULL) {
338     return FALSE;
339   }
340
341   /* only select elements with autoplugging rank */
342   rank = gst_plugin_feature_get_rank (feature);
343   if (rank < GST_RANK_MARGINAL)
344     return FALSE;
345
346   return TRUE;
347 }
348
349 /* function used to sort element features */
350 static gint
351 compare_ranks (GstPluginFeature * f1, GstPluginFeature * f2)
352 {
353   gint diff;
354   const gchar *rname1, *rname2;
355
356   diff = gst_plugin_feature_get_rank (f2) - gst_plugin_feature_get_rank (f1);
357   if (diff != 0)
358     return diff;
359
360   rname1 = gst_plugin_feature_get_name (f1);
361   rname2 = gst_plugin_feature_get_name (f2);
362
363   diff = strcmp (rname2, rname1);
364
365   return diff;
366 }
367
368 static void
369 print_feature (GstPluginFeature * feature)
370 {
371   const gchar *rname;
372
373   rname = gst_plugin_feature_get_name (feature);
374
375   GST_DEBUG ("%s", rname);
376 }
377
378 static void
379 gst_decode_bin_init (GstDecodeBin * decode_bin)
380 {
381   GList *factories;
382
383   decode_bin->cb_mutex = g_mutex_new ();
384
385   /* first filter out the interesting element factories */
386   factories = gst_default_registry_feature_filter (
387       (GstPluginFeatureFilter) gst_decode_bin_factory_filter,
388       FALSE, decode_bin);
389
390   /* sort them according to their ranks */
391   decode_bin->factories = g_list_sort (factories, (GCompareFunc) compare_ranks);
392   /* do some debugging */
393   g_list_foreach (decode_bin->factories, (GFunc) print_feature, NULL);
394
395   /* we create the typefind element only once */
396   decode_bin->typefind = gst_element_factory_make ("typefind", "typefind");
397   if (!decode_bin->typefind) {
398     g_warning ("can't find typefind element, decodebin will not work");
399   } else {
400     GstPad *pad, *gpad;
401     GstPadTemplate *pad_tmpl;
402
403     /* add the typefind element */
404     if (!gst_bin_add (GST_BIN (decode_bin), decode_bin->typefind)) {
405       g_warning ("Could not add typefind element, decodebin will not work");
406       gst_object_unref (decode_bin->typefind);
407       decode_bin->typefind = NULL;
408     }
409
410     /* get the sinkpad */
411     pad = gst_element_get_static_pad (decode_bin->typefind, "sink");
412
413     /* get the pad template */
414     pad_tmpl = gst_static_pad_template_get (&decoder_bin_sink_template);
415
416     /* ghost the sink pad to ourself */
417     gpad = gst_ghost_pad_new_from_template ("sink", pad, pad_tmpl);
418     gst_pad_set_active (gpad, TRUE);
419     gst_element_add_pad (GST_ELEMENT (decode_bin), gpad);
420
421     gst_object_unref (pad_tmpl);
422     gst_object_unref (pad);
423
424     /* connect a signal to find out when the typefind element found
425      * a type */
426     decode_bin->have_type_id =
427         g_signal_connect (G_OBJECT (decode_bin->typefind), "have_type",
428         G_CALLBACK (type_found), decode_bin);
429   }
430   add_fakesink (decode_bin);
431
432   decode_bin->dynamics = NULL;
433   decode_bin->queues = NULL;
434   decode_bin->probes = NULL;
435 }
436
437 static void
438 gst_decode_bin_dispose (GObject * object)
439 {
440   GstDecodeBin *decode_bin;
441
442   decode_bin = GST_DECODE_BIN (object);
443
444   if (decode_bin->factories)
445     gst_plugin_feature_list_free (decode_bin->factories);
446   decode_bin->factories = NULL;
447
448   G_OBJECT_CLASS (parent_class)->dispose (object);
449
450   /* our parent dispose might trigger new signals when pads are unlinked
451    * etc. clean up the mess here. */
452   /* FIXME do proper cleanup when going to NULL */
453   free_dynamics (decode_bin);
454 }
455
456 static void
457 gst_decode_bin_set_sink_caps (GstDecodeBin * dbin, GstCaps * caps)
458 {
459   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
460
461   g_object_set (dbin->typefind, "force-caps", caps, NULL);
462 }
463
464 static GstCaps *
465 gst_decode_bin_get_sink_caps (GstDecodeBin * dbin)
466 {
467   GstCaps *caps;
468
469   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
470
471   g_object_get (dbin->typefind, "force-caps", &caps, NULL);
472
473   return caps;
474 }
475
476 static void
477 gst_decode_bin_set_property (GObject * object, guint prop_id,
478     const GValue * value, GParamSpec * pspec)
479 {
480   GstDecodeBin *dbin;
481
482   dbin = GST_DECODE_BIN (object);
483
484   switch (prop_id) {
485     case PROP_SINK_CAPS:
486       gst_decode_bin_set_sink_caps (dbin, g_value_get_boxed (value));
487       break;
488     default:
489       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
490       break;
491   }
492 }
493
494 static void
495 gst_decode_bin_get_property (GObject * object, guint prop_id,
496     GValue * value, GParamSpec * pspec)
497 {
498   GstDecodeBin *dbin;
499
500   dbin = GST_DECODE_BIN (object);
501   switch (prop_id) {
502     case PROP_SINK_CAPS:
503       g_value_take_boxed (value, gst_decode_bin_get_sink_caps (dbin));
504       break;
505     default:
506       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
507       break;
508   }
509 }
510
511 static void
512 gst_decode_bin_finalize (GObject * object)
513 {
514   GstDecodeBin *decode_bin = GST_DECODE_BIN (object);
515
516   g_mutex_free (decode_bin->cb_mutex);
517
518   G_OBJECT_CLASS (parent_class)->finalize (object);
519 }
520
521 struct DynFind
522 {
523   GstElement *elem;
524   GstPad *pad;
525 };
526
527 static gint
528 find_dynamic (GstDynamic * dyn, struct DynFind *info)
529 {
530   if (dyn->element == info->elem && dyn->pad == info->pad)
531     return 0;
532   return 1;
533 }
534
535 /* Add either an element (for dynamic pads/pad-added watching) or a
536  * pad (for delayed caps/notify::caps watching) to the dynamic list,
537  * taking care to ignore repeat entries so we don't end up handling a
538  * pad twice, for example */
539 static void
540 dynamic_add (GstElement * element, GstPad * pad, GstDecodeBin * decode_bin)
541 {
542   GstDynamic *dyn;
543   struct DynFind find_info;
544   GList *found;
545
546   g_return_if_fail (element != NULL);
547
548   /* do a search that this entry doesn't already exist */
549   find_info.elem = element;
550   find_info.pad = pad;
551   found = g_list_find_custom (decode_bin->dynamics, &find_info,
552       (GCompareFunc) find_dynamic);
553   if (found != NULL)
554     goto exit;
555
556   /* take refs */
557   dyn = g_new0 (GstDynamic, 1);
558   dyn->element = gst_object_ref (element);
559   dyn->decode_bin = gst_object_ref (decode_bin);
560   if (pad) {
561     dyn->pad = gst_object_ref (pad);
562     GST_DEBUG_OBJECT (decode_bin, "dynamic create for pad %" GST_PTR_FORMAT,
563         pad);
564     dyn->caps_sig_id = g_signal_connect (G_OBJECT (pad), "notify::caps",
565         G_CALLBACK (new_caps), dyn);
566   } else {
567     GST_DEBUG_OBJECT (decode_bin, "dynamic create for element %"
568         GST_PTR_FORMAT, element);
569     dyn->np_sig_id = g_signal_connect (G_OBJECT (element), "pad-added",
570         G_CALLBACK (new_pad), dyn);
571     dyn->nmp_sig_id = g_signal_connect (G_OBJECT (element), "no-more-pads",
572         G_CALLBACK (no_more_pads), dyn);
573   }
574
575   /* and add this element to the dynamic elements */
576   decode_bin->dynamics = g_list_prepend (decode_bin->dynamics, dyn);
577
578   return;
579 exit:
580   if (element) {
581     GST_DEBUG_OBJECT (decode_bin, "Dynamic element already added: %"
582         GST_PTR_FORMAT, element);
583   } else {
584     GST_DEBUG_OBJECT (decode_bin, "Dynamic pad already added: %"
585         GST_PTR_FORMAT, pad);
586   }
587 }
588
589 static void
590 dynamic_free (GstDynamic * dyn)
591 {
592   GST_DEBUG_OBJECT (dyn->decode_bin, "dynamic free");
593
594   /* disconnect signals */
595   if (dyn->np_sig_id)
596     g_signal_handler_disconnect (G_OBJECT (dyn->element), dyn->np_sig_id);
597   if (dyn->nmp_sig_id)
598     g_signal_handler_disconnect (G_OBJECT (dyn->element), dyn->nmp_sig_id);
599   if (dyn->caps_sig_id)
600     g_signal_handler_disconnect (G_OBJECT (dyn->pad), dyn->caps_sig_id);
601
602   if (dyn->pad)
603     gst_object_unref (dyn->pad);
604   dyn->pad = NULL;
605   if (dyn->element)
606     gst_object_unref (dyn->element);
607   dyn->element = NULL;
608
609   gst_object_unref (dyn->decode_bin);
610   dyn->decode_bin = NULL;
611
612   g_free (dyn);
613 }
614
615 static void
616 free_dynamics (GstDecodeBin * decode_bin)
617 {
618   GList *dyns;
619
620   for (dyns = decode_bin->dynamics; dyns; dyns = g_list_next (dyns)) {
621     GstDynamic *dynamic = (GstDynamic *) dyns->data;
622
623     dynamic_free (dynamic);
624   }
625   g_list_free (decode_bin->dynamics);
626   decode_bin->dynamics = NULL;
627 }
628
629 /* this function runs through the element factories and returns a list
630  * of all elements that are able to sink the given caps
631  */
632 static GList *
633 find_compatibles (GstDecodeBin * decode_bin, const GstCaps * caps)
634 {
635   GList *factories;
636   GList *to_try = NULL;
637
638   /* loop over all the factories */
639   for (factories = decode_bin->factories; factories;
640       factories = g_list_next (factories)) {
641     GstElementFactory *factory = GST_ELEMENT_FACTORY (factories->data);
642     const GList *templates;
643     GList *walk;
644
645     /* get the templates from the element factory */
646     templates = gst_element_factory_get_static_pad_templates (factory);
647     for (walk = (GList *) templates; walk; walk = g_list_next (walk)) {
648       GstStaticPadTemplate *templ = walk->data;
649
650       /* we only care about the sink templates */
651       if (templ->direction == GST_PAD_SINK) {
652         gboolean can_intersect;
653         GstCaps *tmpl_caps;
654
655         /* try to intersect the caps with the caps of the template */
656         tmpl_caps = gst_static_caps_get (&templ->static_caps);
657
658         can_intersect = gst_caps_can_intersect (caps, tmpl_caps);
659         gst_caps_unref (tmpl_caps);
660
661         /* check if the intersection is empty */
662         if (can_intersect) {
663           /* non empty intersection, we can use this element */
664           to_try = g_list_prepend (to_try, factory);
665           break;
666         }
667       }
668     }
669   }
670   to_try = g_list_reverse (to_try);
671
672   return to_try;
673 }
674
675 static gboolean
676 mimetype_is_raw (const gchar * mimetype)
677 {
678   return g_str_has_prefix (mimetype, "video/x-raw") ||
679       g_str_has_prefix (mimetype, "audio/x-raw") ||
680       g_str_has_prefix (mimetype, "text/plain") ||
681       g_str_has_prefix (mimetype, "text/x-pango-markup");
682 }
683
684 static void
685 free_pad_probes (GstDecodeBin * decode_bin)
686 {
687   GList *tmp;
688
689   /* Remove pad probes */
690   for (tmp = decode_bin->probes; tmp; tmp = g_list_next (tmp)) {
691     PadProbeData *data = (PadProbeData *) tmp->data;
692
693     gst_pad_remove_data_probe (data->pad, data->sigid);
694     g_free (data);
695   }
696   g_list_free (decode_bin->probes);
697   decode_bin->probes = NULL;
698 }
699
700 /* used when we need to remove a probe because the decoder we plugged failed
701  * to activate */
702 static void
703 free_pad_probe_for_element (GstDecodeBin * decode_bin, GstElement * element)
704 {
705   GList *l;
706
707   for (l = decode_bin->probes; l != NULL; l = g_list_next (l)) {
708     PadProbeData *data = (PadProbeData *) l->data;
709
710     if (GST_ELEMENT_CAST (GST_PAD_PARENT (data->pad)) == element) {
711       gst_pad_remove_data_probe (data->pad, data->sigid);
712       decode_bin->probes = g_list_delete_link (decode_bin->probes, l);
713       g_free (data);
714       return;
715     }
716   }
717 }
718
719 static gboolean
720 add_fakesink (GstDecodeBin * decode_bin)
721 {
722   if (decode_bin->fakesink != NULL)
723     return TRUE;
724
725   g_mutex_lock (decode_bin->cb_mutex);
726
727   decode_bin->fakesink = gst_element_factory_make ("fakesink", "fakesink");
728   if (!decode_bin->fakesink)
729     goto no_fakesink;
730
731   /* hacky, remove sink flag, we don't want our decodebin to become a sink
732    * just because we add a fakesink element to make us ASYNC */
733   GST_OBJECT_FLAG_UNSET (decode_bin->fakesink, GST_ELEMENT_IS_SINK);
734
735   /* takes ownership */
736   if (!gst_bin_add (GST_BIN (decode_bin), decode_bin->fakesink)) {
737     g_warning ("Could not add fakesink element, decodebin will not work");
738     gst_object_unref (decode_bin->fakesink);
739     decode_bin->fakesink = NULL;
740   }
741   g_mutex_unlock (decode_bin->cb_mutex);
742   return TRUE;
743
744   /* ERRORS */
745 no_fakesink:
746   {
747     g_warning ("can't find fakesink element, decodebin will not work");
748     g_mutex_unlock (decode_bin->cb_mutex);
749     return FALSE;
750   }
751 }
752
753 static void
754 remove_fakesink (GstDecodeBin * decode_bin)
755 {
756   gboolean removed_fakesink = FALSE;
757
758   if (decode_bin->fakesink == NULL)
759     return;
760
761   g_mutex_lock (decode_bin->cb_mutex);
762   if (decode_bin->fakesink) {
763     GST_DEBUG_OBJECT (decode_bin, "Removing fakesink and marking state dirty");
764
765     /* Lock the state to prevent it from changing state to non-NULL
766      * before it's removed */
767     gst_element_set_locked_state (decode_bin->fakesink, TRUE);
768     /* setting the state to NULL is never async */
769     gst_element_set_state (decode_bin->fakesink, GST_STATE_NULL);
770     gst_bin_remove (GST_BIN (decode_bin), decode_bin->fakesink);
771     decode_bin->fakesink = NULL;
772
773     removed_fakesink = TRUE;
774   }
775   g_mutex_unlock (decode_bin->cb_mutex);
776
777   if (removed_fakesink) {
778     free_pad_probes (decode_bin);
779   }
780 }
781
782 /* this should be implemented with _pad_block() */
783 static gboolean
784 pad_probe (GstPad * pad, GstMiniObject * data, GstDecodeBin * decode_bin)
785 {
786   GList *tmp;
787   gboolean alldone = TRUE;
788
789   for (tmp = decode_bin->probes; tmp; tmp = g_list_next (tmp)) {
790     PadProbeData *pdata = (PadProbeData *) tmp->data;
791
792     if (pdata->pad == pad) {
793       if (GST_IS_BUFFER (data)) {
794         if (!pdata->done)
795           decode_bin->numwaiting--;
796         pdata->done = TRUE;
797       } else if (GST_IS_EVENT (data) &&
798           ((GST_EVENT_TYPE (data) == GST_EVENT_EOS) ||
799               (GST_EVENT_TYPE (data) == GST_EVENT_TAG) ||
800               (GST_EVENT_TYPE (data) == GST_EVENT_FLUSH_START))) {
801         /* FIXME, what about NEWSEGMENT? really, use _pad_block()... */
802         if (!pdata->done)
803           decode_bin->numwaiting--;
804         pdata->done = TRUE;
805       }
806     }
807
808     if (!(pdata->done)) {
809       GST_LOG_OBJECT (decode_bin, "Pad probe on pad %" GST_PTR_FORMAT
810           " but pad %" GST_PTR_FORMAT " still needs data.", pad, pdata->pad);
811       alldone = FALSE;
812     }
813   }
814   if (alldone)
815     remove_fakesink (decode_bin);
816   return TRUE;
817 }
818
819 /* FIXME: this should be somehow merged with the queue code in
820  * try_to_link_1() to reduce code duplication */
821 static GstPad *
822 add_raw_queue (GstDecodeBin * decode_bin, GstPad * pad)
823 {
824   GstElement *queue = NULL;
825   GstPad *queuesinkpad = NULL, *queuesrcpad = NULL;
826
827   queue = gst_element_factory_make ("queue", NULL);
828   decode_bin->queue_type = G_OBJECT_TYPE (queue);
829
830   g_object_set (G_OBJECT (queue), "max-size-buffers", 0, NULL);
831   g_object_set (G_OBJECT (queue), "max-size-time", G_GINT64_CONSTANT (0), NULL);
832   g_object_set (G_OBJECT (queue), "max-size-bytes", 8192, NULL);
833   gst_bin_add (GST_BIN (decode_bin), queue);
834   gst_element_set_state (queue, GST_STATE_READY);
835   queuesinkpad = gst_element_get_static_pad (queue, "sink");
836   queuesrcpad = gst_element_get_static_pad (queue, "src");
837
838   if (gst_pad_link (pad, queuesinkpad) != GST_PAD_LINK_OK) {
839     GST_WARNING_OBJECT (decode_bin,
840         "Linking queue failed, trying without queue");
841     gst_element_set_state (queue, GST_STATE_NULL);
842     gst_object_unref (queuesrcpad);
843     gst_object_unref (queuesinkpad);
844     gst_bin_remove (GST_BIN (decode_bin), queue);
845     return gst_object_ref (pad);
846   }
847
848   decode_bin->queues = g_list_append (decode_bin->queues, queue);
849   g_signal_connect (G_OBJECT (queue),
850       "overrun", G_CALLBACK (queue_filled_cb), decode_bin);
851   g_signal_connect (G_OBJECT (queue),
852       "underrun", G_CALLBACK (queue_underrun_cb), decode_bin);
853
854   gst_element_set_state (queue, GST_STATE_PAUSED);
855   gst_object_unref (queuesinkpad);
856
857   return queuesrcpad;
858 }
859
860 /* given a pad and a caps from an element, find the list of elements
861  * that could connect to the pad
862  *
863  * If the pad has a raw format, this function will create a ghostpad
864  * for the pad onto the decodebin.
865  *
866  * If no compatible elements could be found, this function will signal
867  * the unknown_type signal.
868  */
869 static void
870 close_pad_link (GstElement * element, GstPad * pad, GstCaps * caps,
871     GstDecodeBin * decode_bin, gboolean more)
872 {
873   GstStructure *structure;
874   const gchar *mimetype;
875   gchar *padname;
876   gint diff;
877
878   padname = gst_pad_get_name (pad);
879   diff = strncmp (padname, "current_", 8);
880   g_free (padname);
881
882   /* hack.. ignore current pads */
883   if (!diff)
884     return;
885
886   /* the caps is empty, this means the pad has no type, we can only
887    * decide to fire the unknown_type signal. */
888   if (caps == NULL || gst_caps_is_empty (caps))
889     goto unknown_type;
890
891   /* the caps is any, this means the pad can be anything and
892    * we don't know yet */
893   if (gst_caps_is_any (caps))
894     goto dont_know_yet;
895
896   GST_LOG_OBJECT (element, "trying to close %" GST_PTR_FORMAT, caps);
897
898   /* FIXME, iterate over more structures? I guess it is possible that
899    * this pad has some encoded and some raw pads. This code will fail
900    * then if the first structure is not the raw type... */
901   structure = gst_caps_get_structure (caps, 0);
902   mimetype = gst_structure_get_name (structure);
903
904   /* first see if this is raw. If the type is raw, we can
905    * create a ghostpad for this pad. It's possible that the caps are not
906    * fixed. */
907   if (mimetype_is_raw (mimetype)) {
908     GstPadTemplate *tmpl;
909     gchar *padname;
910     GstPad *ghost;
911     PadProbeData *data;
912
913     /* If we're at a demuxer element but have raw data already
914      * we have to add a queue here. For non-raw data this is done
915      * in try_to_link_1() */
916     if (is_demuxer_element (element)) {
917       GST_DEBUG_OBJECT (decode_bin,
918           "Element %s is a demuxer, inserting a queue",
919           GST_OBJECT_NAME (element));
920
921       pad = add_raw_queue (decode_bin, pad);
922     }
923
924     /* make a unique name for this new pad */
925     padname = g_strdup_printf ("src%d", decode_bin->numpads);
926     decode_bin->numpads++;
927
928     /* make it a ghostpad */
929     tmpl = gst_static_pad_template_get (&decoder_bin_src_template);
930     ghost = gst_ghost_pad_new_from_template (padname, pad, tmpl);
931     gst_object_unref (tmpl);
932
933     gst_pad_set_active (ghost, TRUE);
934     gst_element_add_pad (GST_ELEMENT (decode_bin), ghost);
935
936     data = g_new0 (PadProbeData, 1);
937     data->pad = pad;
938     data->done = FALSE;
939
940     /* FIXME, use _pad_block() */
941     data->sigid = gst_pad_add_data_probe (pad, G_CALLBACK (pad_probe),
942         decode_bin);
943     decode_bin->numwaiting++;
944
945     decode_bin->probes = g_list_append (decode_bin->probes, data);
946
947     GST_LOG_OBJECT (element, "closed pad %s", padname);
948
949     /* our own signal with an extra flag that this is the only pad */
950     GST_DEBUG_OBJECT (decode_bin, "emitting new-decoded-pad");
951     g_signal_emit (G_OBJECT (decode_bin),
952         gst_decode_bin_signals[SIGNAL_NEW_DECODED_PAD], 0, ghost, !more);
953     GST_DEBUG_OBJECT (decode_bin, "emitted new-decoded-pad");
954
955     g_free (padname);
956
957     /* If we're at a demuxer element pad was set to a queue's
958      * srcpad and must be unref'd here */
959     if (is_demuxer_element (element))
960       gst_object_unref (pad);
961   } else {
962     GList *to_try;
963
964     /* if the caps has many types, we need to delay */
965     if (!gst_caps_is_fixed (caps))
966       goto many_types;
967
968     /* continue plugging, first find all compatible elements */
969     to_try = find_compatibles (decode_bin, caps);
970     if (to_try == NULL)
971       /* no compatible elements, we cannot go on */
972       goto unknown_type;
973
974     if (try_to_link_1 (decode_bin, element, pad, to_try) == NULL) {
975       g_list_free (to_try);
976       GST_LOG_OBJECT (pad, "none of the allegedly available elements usable");
977       goto unknown_type;
978     }
979
980     /* can free the list again now */
981     g_list_free (to_try);
982   }
983   return;
984
985   /* ERRORS */
986 unknown_type:
987   {
988     GST_LOG_OBJECT (pad, "unknown type found, fire signal");
989     g_signal_emit (G_OBJECT (decode_bin),
990         gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE], 0, pad, caps);
991
992     gst_element_post_message (GST_ELEMENT_CAST (decode_bin),
993         gst_missing_decoder_message_new (GST_ELEMENT_CAST (decode_bin), caps));
994
995     if (element == decode_bin->typefind) {
996       gchar *desc;
997
998       desc = gst_pb_utils_get_decoder_description (caps);
999       GST_ELEMENT_ERROR (decode_bin, STREAM, CODEC_NOT_FOUND,
1000           (_("A %s plugin is required to play this stream, but not installed."),
1001               desc),
1002           ("No decoder to handle media type '%s'",
1003               gst_structure_get_name (gst_caps_get_structure (caps, 0))));
1004       g_free (desc);
1005     }
1006
1007     return;
1008   }
1009 dont_know_yet:
1010   {
1011     GST_LOG_OBJECT (pad, "type is not known yet");
1012     goto setup_caps_delay;
1013   }
1014 many_types:
1015   {
1016     GST_LOG_OBJECT (pad, "many possible types");
1017     goto setup_caps_delay;
1018   }
1019 setup_caps_delay:
1020   {
1021     GST_LOG_OBJECT (pad, "setting up a delayed link");
1022     dynamic_add (element, pad, decode_bin);
1023     return;
1024   }
1025 }
1026
1027 /* Decide whether an element is a demuxer based on the
1028  * klass and number/type of src pad templates it has */
1029 static gboolean
1030 is_demuxer_element (GstElement * srcelement)
1031 {
1032   GstElementFactory *srcfactory;
1033   GstElementClass *elemclass;
1034   GList *walk;
1035   const gchar *klass;
1036   gint potential_src_pads = 0;
1037
1038   srcfactory = gst_element_get_factory (srcelement);
1039   klass = gst_element_factory_get_klass (srcfactory);
1040
1041   /* Can't be a demuxer unless it has Demux in the klass name */
1042   if (klass == NULL || !strstr (klass, "Demux"))
1043     return FALSE;
1044
1045   /* Walk the src pad templates and count how many the element
1046    * might produce */
1047   elemclass = GST_ELEMENT_GET_CLASS (srcelement);
1048
1049   walk = gst_element_class_get_pad_template_list (elemclass);
1050   while (walk != NULL) {
1051     GstPadTemplate *templ;
1052
1053     templ = (GstPadTemplate *) walk->data;
1054     if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SRC) {
1055       switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
1056         case GST_PAD_ALWAYS:
1057         case GST_PAD_SOMETIMES:
1058           if (strstr (GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "%"))
1059             potential_src_pads += 2;    /* Might make multiple pads */
1060           else
1061             potential_src_pads += 1;
1062           break;
1063         case GST_PAD_REQUEST:
1064           potential_src_pads += 2;
1065           break;
1066       }
1067     }
1068     walk = g_list_next (walk);
1069   }
1070
1071   if (potential_src_pads < 2)
1072     return FALSE;
1073
1074   return TRUE;
1075 }
1076
1077 /*
1078  * given a list of element factories, try to link one of the factories
1079  * to the given pad.
1080  *
1081  * The function returns the element that was successfully linked to the
1082  * pad.
1083  */
1084 static GstElement *
1085 try_to_link_1 (GstDecodeBin * decode_bin, GstElement * srcelement, GstPad * pad,
1086     GList * factories)
1087 {
1088   GList *walk;
1089   GstElement *result = NULL;
1090   gboolean isdemux = FALSE;
1091   GstPad *queuesinkpad = NULL, *queuesrcpad = NULL;
1092   GstElement *queue = NULL;
1093   GstPad *usedsrcpad = pad;
1094
1095   /* Check if the parent of the src pad is a demuxer */
1096   isdemux = is_demuxer_element (srcelement);
1097
1098   if (isdemux && factories != NULL) {
1099     GstPadLinkReturn dqlink;
1100
1101     /* Insert a queue between demuxer and decoder */
1102     GST_DEBUG_OBJECT (decode_bin,
1103         "Element %s is a demuxer, inserting a queue",
1104         GST_OBJECT_NAME (srcelement));
1105     queue = gst_element_factory_make ("queue", NULL);
1106     decode_bin->queue_type = G_OBJECT_TYPE (queue);
1107
1108     g_object_set (G_OBJECT (queue), "max-size-buffers", 0, NULL);
1109     g_object_set (G_OBJECT (queue), "max-size-time", G_GINT64_CONSTANT (0),
1110         NULL);
1111     g_object_set (G_OBJECT (queue), "max-size-bytes", 8192, NULL);
1112     gst_bin_add (GST_BIN (decode_bin), queue);
1113     gst_element_set_state (queue, GST_STATE_READY);
1114     queuesinkpad = gst_element_get_static_pad (queue, "sink");
1115     usedsrcpad = queuesrcpad = gst_element_get_static_pad (queue, "src");
1116
1117     dqlink = gst_pad_link (pad, queuesinkpad);
1118     g_return_val_if_fail (dqlink == GST_PAD_LINK_OK, NULL);
1119   }
1120
1121   /* loop over the factories */
1122   for (walk = factories; walk; walk = g_list_next (walk)) {
1123     GstElementFactory *factory = GST_ELEMENT_FACTORY (walk->data);
1124     GstElementFactory *src_factory;
1125     GstElement *element;
1126     GstPadLinkReturn ret;
1127     GstPad *sinkpad;
1128
1129     GST_DEBUG_OBJECT (decode_bin, "trying to link %s to %s",
1130         gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)),
1131         GST_OBJECT_NAME (srcelement));
1132
1133     /* don't plug the same parser twice, but allow multiple
1134      * instances of other elements (e.g. id3demux) in a row */
1135     src_factory = gst_element_get_factory (srcelement);
1136     if (src_factory == factory
1137         && gst_element_factory_list_is_type (factory,
1138             GST_ELEMENT_FACTORY_TYPE_PARSER)) {
1139       GST_DEBUG_OBJECT (decode_bin,
1140           "not inserting parser element %s twice in a row, skipping",
1141           GST_PLUGIN_FEATURE_NAME (factory));
1142       continue;
1143     }
1144
1145     /* make an element from the factory first */
1146     if ((element = gst_element_factory_create (factory, NULL)) == NULL) {
1147       /* hmm, strange. Like with all things in life, let's move on.. */
1148       GST_WARNING_OBJECT (decode_bin, "could not create an element from %s",
1149           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1150       continue;
1151     }
1152
1153     /* try to link the given pad to a sinkpad */
1154     /* FIXME, find the sinkpad by looping over the pads instead of
1155      * looking it up by name */
1156     if ((sinkpad = gst_element_get_static_pad (element, "sink")) == NULL) {
1157       /* if no pad is found we can't do anything */
1158       GST_WARNING_OBJECT (decode_bin, "could not find sinkpad in element");
1159       continue;
1160     }
1161
1162     /* now add the element to the bin first */
1163     GST_DEBUG_OBJECT (decode_bin, "adding %s", GST_OBJECT_NAME (element));
1164     gst_bin_add (GST_BIN (decode_bin), element);
1165
1166     /* set to READY first so it is ready, duh. */
1167     if (gst_element_set_state (element,
1168             GST_STATE_READY) == GST_STATE_CHANGE_FAILURE) {
1169       GST_WARNING_OBJECT (decode_bin, "Couldn't set %s to READY",
1170           GST_ELEMENT_NAME (element));
1171       /* get rid of the sinkpad */
1172       gst_object_unref (sinkpad);
1173       /* this element did not work, remove it again and continue trying
1174        * other elements, the element will be disposed. */
1175       /* FIXME: shouldn't we do this before adding it to the bin so that no
1176        * error messages get through to the app? (tpm) */
1177       gst_bin_remove (GST_BIN (decode_bin), element);
1178       continue;
1179     }
1180
1181     if ((ret = gst_pad_link (usedsrcpad, sinkpad)) != GST_PAD_LINK_OK) {
1182       GST_DEBUG_OBJECT (decode_bin, "link failed on pad %s:%s, reason %d",
1183           GST_DEBUG_PAD_NAME (pad), ret);
1184       /* get rid of the sinkpad */
1185       gst_object_unref (sinkpad);
1186       /* this element did not work, remove it again and continue trying
1187        * other elements, the element will be disposed. */
1188       gst_element_set_state (element, GST_STATE_NULL);
1189       gst_bin_remove (GST_BIN (decode_bin), element);
1190     } else {
1191       GST_DEBUG_OBJECT (decode_bin, "linked on pad %s:%s",
1192           GST_DEBUG_PAD_NAME (usedsrcpad));
1193
1194       /* configure the queue some more */
1195       if (queue != NULL) {
1196         decode_bin->queues = g_list_append (decode_bin->queues, queue);
1197         g_signal_connect (G_OBJECT (queue),
1198             "overrun", G_CALLBACK (queue_filled_cb), decode_bin);
1199         g_signal_connect (G_OBJECT (queue),
1200             "underrun", G_CALLBACK (queue_underrun_cb), decode_bin);
1201       }
1202
1203       /* The link worked, now figure out what it was that we connected */
1204
1205       /* make sure we catch unlink signals */
1206       g_signal_connect (G_OBJECT (pad), "unlinked",
1207           G_CALLBACK (unlinked), decode_bin);
1208
1209       /* now that we added the element we can try to continue autoplugging
1210        * on it until we have a raw type */
1211       close_link (element, decode_bin);
1212
1213       /* change the state of the element to that of the parent */
1214       if ((gst_element_set_state (element,
1215                   GST_STATE_PAUSED)) == GST_STATE_CHANGE_FAILURE) {
1216         GST_WARNING_OBJECT (decode_bin, "Couldn't set %s to PAUSED",
1217             GST_ELEMENT_NAME (element));
1218         /* close_link -> close_pad_link -> might have set up a pad probe */
1219         free_pad_probe_for_element (decode_bin, element);
1220         gst_element_set_state (element, GST_STATE_NULL);
1221         gst_bin_remove (GST_BIN (decode_bin), element);
1222         continue;
1223       }
1224
1225       result = element;
1226
1227       /* get rid of the sinkpad now */
1228       gst_object_unref (sinkpad);
1229
1230       /* Set the queue to paused and set the pointer to NULL so we don't
1231        * remove it below */
1232       if (queue != NULL) {
1233         gst_element_set_state (queue, GST_STATE_PAUSED);
1234         queue = NULL;
1235         gst_object_unref (queuesrcpad);
1236         gst_object_unref (queuesinkpad);
1237       }
1238
1239       /* and exit */
1240       goto done;
1241     }
1242   }
1243 done:
1244   if (queue != NULL) {
1245     /* We didn't successfully connect to the queue */
1246     gst_pad_unlink (pad, queuesinkpad);
1247     gst_element_set_state (queue, GST_STATE_NULL);
1248     gst_object_unref (queuesrcpad);
1249     gst_object_unref (queuesinkpad);
1250     gst_bin_remove (GST_BIN (decode_bin), queue);
1251   }
1252   return result;
1253 }
1254
1255 static GstPad *
1256 get_our_ghost_pad (GstDecodeBin * decode_bin, GstPad * pad)
1257 {
1258   GstIterator *pad_it = NULL;
1259   GstPad *db_pad = NULL;
1260   gboolean done = FALSE;
1261
1262   if (pad == NULL || !GST_PAD_IS_SRC (pad)) {
1263     GST_DEBUG_OBJECT (decode_bin, "pad NULL or not SRC pad");
1264     return NULL;
1265   }
1266
1267   /* our ghostpads are the sourcepads */
1268   pad_it = gst_element_iterate_src_pads (GST_ELEMENT (decode_bin));
1269   while (!done) {
1270     db_pad = NULL;
1271     switch (gst_iterator_next (pad_it, (gpointer) & db_pad)) {
1272       case GST_ITERATOR_OK:
1273         GST_DEBUG_OBJECT (decode_bin, "looking at pad %s:%s",
1274             GST_DEBUG_PAD_NAME (db_pad));
1275         if (GST_IS_GHOST_PAD (db_pad)) {
1276           GstPad *target_pad = NULL;
1277
1278           target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (db_pad));
1279           done = (target_pad == pad);
1280           if (target_pad)
1281             gst_object_unref (target_pad);
1282
1283           if (done) {
1284             /* Found our ghost pad */
1285             GST_DEBUG_OBJECT (decode_bin, "found ghostpad %s:%s for pad %s:%s",
1286                 GST_DEBUG_PAD_NAME (db_pad), GST_DEBUG_PAD_NAME (pad));
1287             break;
1288           }
1289         }
1290         /* Not the right one */
1291         gst_object_unref (db_pad);
1292         break;
1293       case GST_ITERATOR_RESYNC:
1294         gst_iterator_resync (pad_it);
1295         break;
1296       case GST_ITERATOR_ERROR:
1297         done = TRUE;
1298         break;
1299       case GST_ITERATOR_DONE:
1300         done = TRUE;
1301         break;
1302     }
1303   }
1304   gst_iterator_free (pad_it);
1305
1306   return db_pad;
1307 }
1308
1309 /* remove all downstream elements starting from the given pad.
1310  * Also make sure to remove the ghostpad we created for the raw
1311  * decoded stream.
1312  */
1313 static void
1314 remove_element_chain (GstDecodeBin * decode_bin, GstPad * pad)
1315 {
1316   GstIterator *iter;
1317   gboolean done = FALSE;
1318   gpointer item;
1319   GstElement *elem = GST_ELEMENT (GST_OBJECT_PARENT (pad));
1320
1321   while (GST_OBJECT_PARENT (elem) &&
1322       GST_OBJECT_PARENT (elem) != GST_OBJECT (decode_bin))
1323     elem = GST_ELEMENT (GST_OBJECT_PARENT (elem));
1324
1325   if (G_OBJECT_TYPE (elem) == decode_bin->queue_type) {
1326     GST_DEBUG_OBJECT (decode_bin,
1327         "Encountered demuxer output queue while removing element chain");
1328     decode_bin->queues = g_list_remove (decode_bin->queues, elem);
1329   }
1330
1331   GST_DEBUG_OBJECT (decode_bin, "%s:%s", GST_DEBUG_PAD_NAME (pad));
1332   iter = gst_pad_iterate_internal_links (pad);
1333   if (!iter)
1334     goto no_iter;
1335
1336   /* remove all elements linked to this pad up to the ghostpad
1337    * that we created for this stream */
1338   while (!done) {
1339     switch (gst_iterator_next (iter, &item)) {
1340       case GST_ITERATOR_OK:{
1341         GstPad *pad;
1342         GstPad *ghostpad;
1343         GstPad *peer;
1344
1345         pad = GST_PAD (item);
1346         GST_DEBUG_OBJECT (decode_bin, "inspecting internal pad %s:%s",
1347             GST_DEBUG_PAD_NAME (pad));
1348
1349         ghostpad = get_our_ghost_pad (decode_bin, pad);
1350         if (ghostpad) {
1351           GST_DEBUG_OBJECT (decode_bin, "found our ghost pad %s:%s for %s:%s",
1352               GST_DEBUG_PAD_NAME (ghostpad), GST_DEBUG_PAD_NAME (pad));
1353
1354           g_signal_emit (G_OBJECT (decode_bin),
1355               gst_decode_bin_signals[SIGNAL_REMOVED_DECODED_PAD], 0, ghostpad);
1356
1357           gst_element_remove_pad (GST_ELEMENT (decode_bin), ghostpad);
1358           gst_object_unref (ghostpad);
1359           continue;
1360         } else {
1361           GST_DEBUG_OBJECT (decode_bin, "not one of our ghostpads");
1362         }
1363
1364         peer = gst_pad_get_peer (pad);
1365         if (peer) {
1366           GstObject *parent = gst_pad_get_parent (peer);
1367
1368           GST_DEBUG_OBJECT (decode_bin,
1369               "internal pad %s:%s linked to pad %s:%s",
1370               GST_DEBUG_PAD_NAME (pad), GST_DEBUG_PAD_NAME (peer));
1371
1372           if (parent) {
1373             GstObject *grandparent = gst_object_get_parent (parent);
1374
1375             if (grandparent != NULL) {
1376               if (GST_ELEMENT (grandparent) != GST_ELEMENT (decode_bin)) {
1377                 GST_DEBUG_OBJECT (decode_bin, "dead end pad %s:%s parent %s",
1378                     GST_DEBUG_PAD_NAME (peer), GST_OBJECT_NAME (grandparent));
1379               } else {
1380                 GST_DEBUG_OBJECT (decode_bin,
1381                     "recursing element %s on pad %s:%s",
1382                     GST_ELEMENT_NAME (elem), GST_DEBUG_PAD_NAME (pad));
1383                 remove_element_chain (decode_bin, peer);
1384               }
1385               gst_object_unref (grandparent);
1386             }
1387             gst_object_unref (parent);
1388           }
1389           gst_object_unref (peer);
1390         }
1391         gst_object_unref (item);
1392       }
1393         break;
1394       case GST_ITERATOR_RESYNC:
1395         gst_iterator_resync (iter);
1396         break;
1397       case GST_ITERATOR_ERROR:
1398         GST_ERROR_OBJECT (pad, "Could not iterate over internally linked pads");
1399         done = TRUE;
1400         break;
1401       case GST_ITERATOR_DONE:
1402         done = TRUE;
1403         break;
1404     }
1405   }
1406   GST_DEBUG_OBJECT (decode_bin, "removing %s", GST_ELEMENT_NAME (elem));
1407
1408   gst_iterator_free (iter);
1409
1410 no_iter:
1411   gst_element_set_state (elem, GST_STATE_NULL);
1412   gst_bin_remove (GST_BIN (decode_bin), elem);
1413 }
1414
1415 /* there are @bytes bytes in @queue, enlarge it
1416  *
1417  * Returns: new max number of bytes in @queue
1418  */
1419 static guint
1420 queue_enlarge (GstElement * queue, guint bytes, GstDecodeBin * decode_bin)
1421 {
1422   /* Increase the queue size by 1Mbyte if it is over 1Mb, else double its current limit
1423    */
1424   if (bytes > 1024 * 1024)
1425     bytes += 1024 * 1024;
1426   else
1427     bytes *= 2;
1428
1429   GST_DEBUG_OBJECT (decode_bin,
1430       "increasing queue %s max-size-bytes to %d", GST_ELEMENT_NAME (queue),
1431       bytes);
1432   g_object_set (G_OBJECT (queue), "max-size-bytes", bytes, NULL);
1433
1434   return bytes;
1435 }
1436
1437 /* this callback is called when our queues fills up or are empty
1438  * We then check the status of all other queues to make sure we
1439  * never have an empty and full queue at the same time since that
1440  * would block dataflow. In the case of a filled queue, we make
1441  * it larger.
1442  */
1443 static void
1444 queue_underrun_cb (GstElement * queue, GstDecodeBin * decode_bin)
1445 {
1446   /* FIXME: we don't really do anything here for now. Ideally we should
1447    * see if some of the queues are filled and increase their values
1448    * in that case.
1449    * Note: be very careful with thread safety here as this underrun
1450    * signal is done from the streaming thread of queue srcpad which
1451    * is different from the pad_added (where we add the queue to the
1452    * list) and the overrun signals that are signalled from the
1453    * demuxer thread.
1454    */
1455   GST_DEBUG_OBJECT (decode_bin, "got underrun");
1456 }
1457
1458 /* Make sure we don't have a full queue and empty queue situation */
1459 static void
1460 queue_filled_cb (GstElement * queue, GstDecodeBin * decode_bin)
1461 {
1462   GList *tmp;
1463   gboolean increase = FALSE;
1464   guint bytes;
1465
1466   /* get current byte level from the queue that is filled */
1467   g_object_get (G_OBJECT (queue), "current-level-bytes", &bytes, NULL);
1468   GST_DEBUG_OBJECT (decode_bin, "One of the queues is full at %d bytes", bytes);
1469
1470   /* we do not buffer more than 20Mb */
1471   if (bytes > (20 * 1024 * 1024))
1472     goto too_large;
1473
1474   /* check all other queue to see if one is empty, in that case
1475    * we need to enlarge @queue */
1476   for (tmp = decode_bin->queues; tmp; tmp = g_list_next (tmp)) {
1477     GstElement *aqueue = GST_ELEMENT (tmp->data);
1478     guint levelbytes = 0;
1479
1480     if (aqueue != queue) {
1481       g_object_get (G_OBJECT (aqueue), "current-level-bytes", &levelbytes,
1482           NULL);
1483       if (levelbytes == 0) {
1484         /* yup, found an empty queue, we can stop the search and
1485          * need to enlarge the queue */
1486         increase = TRUE;
1487         break;
1488       }
1489     }
1490   }
1491
1492   if (increase) {
1493     /* enlarge @queue */
1494     queue_enlarge (queue, bytes, decode_bin);
1495   } else {
1496     GST_DEBUG_OBJECT (decode_bin,
1497         "Queue is full but other queues are not empty, not doing anything");
1498   }
1499   return;
1500
1501   /* errors */
1502 too_large:
1503   {
1504     GST_WARNING_OBJECT (decode_bin,
1505         "Queue is bigger than 20Mbytes, something else is going wrong");
1506     return;
1507   }
1508 }
1509
1510 /* This function will be called when a dynamic pad is created on an element.
1511  * We try to continue autoplugging on this new pad. */
1512 static void
1513 new_pad (GstElement * element, GstPad * pad, GstDynamic * dynamic)
1514 {
1515   GstDecodeBin *decode_bin = dynamic->decode_bin;
1516   GstCaps *caps;
1517   gboolean more;
1518
1519   GST_OBJECT_LOCK (decode_bin);
1520   if (decode_bin->shutting_down)
1521     goto shutting_down1;
1522   GST_OBJECT_UNLOCK (decode_bin);
1523
1524   GST_STATE_LOCK (decode_bin);
1525   if (decode_bin->shutting_down)
1526     goto shutting_down2;
1527
1528   /* see if any more pending dynamic connections exist */
1529   more = gst_decode_bin_is_dynamic (decode_bin);
1530
1531   caps = gst_pad_get_caps (pad);
1532   close_pad_link (element, pad, caps, decode_bin, more);
1533   if (caps)
1534     gst_caps_unref (caps);
1535   GST_STATE_UNLOCK (decode_bin);
1536
1537   return;
1538
1539 shutting_down1:
1540   {
1541     GST_DEBUG_OBJECT (decode_bin, "we are shutting down");
1542     GST_OBJECT_UNLOCK (decode_bin);
1543     return;
1544   }
1545 shutting_down2:
1546   {
1547     GST_DEBUG_OBJECT (decode_bin, "we are shutting down");
1548     GST_STATE_UNLOCK (decode_bin);
1549     return;
1550   }
1551 }
1552
1553 static void
1554 dynamic_remove (GstDynamic * dynamic)
1555 {
1556   GstDecodeBin *decode_bin = dynamic->decode_bin;
1557
1558   /* remove the dynamic from the list of dynamics */
1559   decode_bin->dynamics = g_list_remove (decode_bin->dynamics, dynamic);
1560   dynamic_free (dynamic);
1561
1562   /* if we have no more dynamic elements, we have no chance of creating
1563    * more pads, so we fire the no_more_pads signal */
1564   if (decode_bin->dynamics == NULL) {
1565     if (decode_bin->numwaiting == 0) {
1566       GST_DEBUG_OBJECT (decode_bin,
1567           "no more dynamic elements, removing fakesink");
1568       remove_fakesink (decode_bin);
1569     }
1570     GST_DEBUG_OBJECT (decode_bin,
1571         "no more dynamic elements, signaling no_more_pads");
1572     gst_element_no_more_pads (GST_ELEMENT (decode_bin));
1573   } else {
1574     GST_DEBUG_OBJECT (decode_bin, "we have more dynamic elements");
1575   }
1576 }
1577
1578 /* this signal is fired when an element signals the no_more_pads signal.
1579  * This means that the element will not generate more dynamic pads and
1580  * we can remove the element from the list of dynamic elements. When we
1581  * have no more dynamic elements in the pipeline, we can fire a no_more_pads
1582  * signal ourselves. */
1583 static void
1584 no_more_pads (GstElement * element, GstDynamic * dynamic)
1585 {
1586   GST_DEBUG_OBJECT (dynamic->decode_bin, "no more pads on element %s",
1587       GST_ELEMENT_NAME (element));
1588
1589   dynamic_remove (dynamic);
1590 }
1591
1592 static void
1593 new_caps (GstPad * pad, GParamSpec * unused, GstDynamic * dynamic)
1594 {
1595   GST_DEBUG_OBJECT (dynamic->decode_bin, "delayed link triggered");
1596
1597   new_pad (dynamic->element, pad, dynamic);
1598
1599   /* assume it worked and remove the dynamic */
1600   dynamic_remove (dynamic);
1601
1602   return;
1603 }
1604
1605 static gboolean
1606 is_our_kid (GstElement * e, GstDecodeBin * decode_bin)
1607 {
1608   gboolean ret;
1609   GstElement *parent;
1610
1611   parent = (GstElement *) gst_object_get_parent ((GstObject *) e);
1612   ret = (parent == (GstElement *) decode_bin);
1613
1614   if (parent)
1615     gst_object_unref ((GstObject *) parent);
1616
1617   return ret;
1618 }
1619
1620 static gboolean
1621 elem_is_dynamic (GstElement * element, GstDecodeBin * decode_bin)
1622 {
1623   GList *pads;
1624
1625   /* loop over all the padtemplates */
1626   for (pads = GST_ELEMENT_GET_CLASS (element)->padtemplates; pads;
1627       pads = g_list_next (pads)) {
1628     GstPadTemplate *templ = GST_PAD_TEMPLATE (pads->data);
1629     const gchar *templ_name;
1630
1631     /* we are only interested in source pads */
1632     if (GST_PAD_TEMPLATE_DIRECTION (templ) != GST_PAD_SRC)
1633       continue;
1634
1635     templ_name = GST_PAD_TEMPLATE_NAME_TEMPLATE (templ);
1636     GST_DEBUG_OBJECT (decode_bin, "got a source pad template %s", templ_name);
1637
1638     /* figure out what kind of pad this is */
1639     switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
1640       case GST_PAD_SOMETIMES:
1641       {
1642         /* try to get the pad to see if it is already created or
1643          * not */
1644         GstPad *pad = gst_element_get_static_pad (element, templ_name);
1645
1646         if (pad) {
1647           GST_DEBUG_OBJECT (decode_bin, "got the pad for sometimes template %s",
1648               templ_name);
1649           gst_object_unref (pad);
1650         } else {
1651           GST_DEBUG_OBJECT (decode_bin,
1652               "did not get the sometimes pad of template %s", templ_name);
1653           /* we have an element that will create dynamic pads */
1654           return TRUE;
1655         }
1656         break;
1657       }
1658       default:
1659         /* Don't care about ALWAYS or REQUEST pads */
1660         break;
1661     }
1662   }
1663   return FALSE;
1664 }
1665
1666 /* This function will be called when a pad is disconnected for some reason */
1667 static void
1668 unlinked (GstPad * pad, GstPad * peerpad, GstDecodeBin * decode_bin)
1669 {
1670   GstElement *element, *peer;
1671
1672   /* inactivate pad */
1673   gst_pad_set_active (pad, GST_ACTIVATE_NONE);
1674
1675   peer = gst_pad_get_parent_element (peerpad);
1676
1677   if (!is_our_kid (peer, decode_bin))
1678     goto exit;
1679
1680   GST_DEBUG_OBJECT (decode_bin, "pad %s:%s removal while alive - chained?",
1681       GST_DEBUG_PAD_NAME (pad));
1682
1683   /* remove all elements linked to the peerpad */
1684   remove_element_chain (decode_bin, peerpad);
1685
1686   /* Re-add as a dynamic element if needed, via close_link */
1687   element = gst_pad_get_parent_element (pad);
1688   if (element) {
1689     if (elem_is_dynamic (element, decode_bin))
1690       dynamic_add (element, NULL, decode_bin);
1691
1692     gst_object_unref (element);
1693   }
1694
1695 exit:
1696   gst_object_unref (peer);
1697 }
1698
1699 /* this function inspects the given element and tries to connect something
1700  * on the srcpads. If there are dynamic pads, it sets up a signal handler to
1701  * continue autoplugging when they become available */
1702 static void
1703 close_link (GstElement * element, GstDecodeBin * decode_bin)
1704 {
1705   GList *pads;
1706   gboolean dynamic = FALSE;
1707   GList *to_connect = NULL;
1708   gboolean more;
1709
1710   GST_DEBUG_OBJECT (decode_bin, "closing links with element %s",
1711       GST_ELEMENT_NAME (element));
1712
1713   /* loop over all the padtemplates */
1714   for (pads = GST_ELEMENT_GET_CLASS (element)->padtemplates; pads;
1715       pads = g_list_next (pads)) {
1716     GstPadTemplate *templ = GST_PAD_TEMPLATE (pads->data);
1717     const gchar *templ_name;
1718
1719     /* we are only interested in source pads */
1720     if (GST_PAD_TEMPLATE_DIRECTION (templ) != GST_PAD_SRC)
1721       continue;
1722
1723     templ_name = GST_PAD_TEMPLATE_NAME_TEMPLATE (templ);
1724     GST_DEBUG_OBJECT (decode_bin, "got a source pad template %s", templ_name);
1725
1726     /* figure out what kind of pad this is */
1727     switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
1728       case GST_PAD_ALWAYS:
1729       {
1730         /* get the pad that we need to autoplug */
1731         GstPad *pad = gst_element_get_static_pad (element, templ_name);
1732
1733         if (pad) {
1734           GST_DEBUG_OBJECT (decode_bin, "got the pad for always template %s",
1735               templ_name);
1736           /* here is the pad, we need to autoplug it */
1737           to_connect = g_list_prepend (to_connect, pad);
1738         } else {
1739           /* strange, pad is marked as always but it's not
1740            * there. Fix the element */
1741           GST_WARNING_OBJECT (decode_bin,
1742               "could not get the pad for always template %s", templ_name);
1743         }
1744         break;
1745       }
1746       case GST_PAD_SOMETIMES:
1747       {
1748         /* try to get the pad to see if it is already created or
1749          * not */
1750         GstPad *pad = gst_element_get_static_pad (element, templ_name);
1751
1752         if (pad) {
1753           GST_DEBUG_OBJECT (decode_bin, "got the pad for sometimes template %s",
1754               templ_name);
1755           /* the pad is created, we need to autoplug it */
1756           to_connect = g_list_prepend (to_connect, pad);
1757         } else {
1758           GST_DEBUG_OBJECT (decode_bin,
1759               "did not get the sometimes pad of template %s", templ_name);
1760           /* we have an element that will create dynamic pads */
1761           dynamic = TRUE;
1762         }
1763         break;
1764       }
1765       case GST_PAD_REQUEST:
1766         /* ignore request pads */
1767         GST_DEBUG_OBJECT (decode_bin, "ignoring request padtemplate %s",
1768             templ_name);
1769         break;
1770     }
1771   }
1772   if (dynamic) {
1773     GST_DEBUG_OBJECT (decode_bin, "got a dynamic element here");
1774     /* ok, this element has dynamic pads, set up the signal handlers to be
1775      * notified of them */
1776
1777     dynamic_add (element, NULL, decode_bin);
1778   }
1779
1780   /* Check if this is an element with more than 1 pad. If this element
1781    * has more than 1 pad, we need to be careful not to signal the
1782    * no_more_pads signal after connecting the first pad. */
1783   more = g_list_length (to_connect) > 1;
1784
1785   /* now loop over all the pads we need to connect */
1786   for (pads = to_connect; pads; pads = g_list_next (pads)) {
1787     GstPad *pad = GST_PAD_CAST (pads->data);
1788     GstCaps *caps;
1789
1790     /* we have more pads if we have more than 1 pad to connect or
1791      * dynamics. If we have only 1 pad and no dynamics, more will be
1792      * set to FALSE and the no-more-pads signal will be fired. Note
1793      * that this can change after the close_pad_link call. */
1794     more |= gst_decode_bin_is_dynamic (decode_bin);
1795
1796     GST_DEBUG_OBJECT (decode_bin, "closing pad link for %s",
1797         GST_OBJECT_NAME (pad));
1798
1799     /* continue autoplugging on the pads */
1800     caps = gst_pad_get_caps (pad);
1801     close_pad_link (element, pad, caps, decode_bin, more);
1802     if (caps)
1803       gst_caps_unref (caps);
1804
1805     gst_object_unref (pad);
1806   }
1807   g_list_free (to_connect);
1808 }
1809
1810 /* this is the signal handler for the typefind element have_type signal.
1811  * It tries to continue autoplugging on the typefind src pad */
1812 static void
1813 type_found (GstElement * typefind, guint probability, GstCaps * caps,
1814     GstDecodeBin * decode_bin)
1815 {
1816   gboolean dynamic;
1817   GstPad *pad;
1818
1819   GST_DEBUG_OBJECT (decode_bin, "typefind found caps %" GST_PTR_FORMAT, caps);
1820
1821   GST_OBJECT_LOCK (decode_bin);
1822   if (decode_bin->shutting_down)
1823     goto shutting_down;
1824   GST_OBJECT_UNLOCK (decode_bin);
1825
1826   GST_STATE_LOCK (decode_bin);
1827   if (decode_bin->shutting_down)
1828     goto exit;
1829
1830   /* don't need the typefind anymore if we already found a type, we're not going
1831    * to be able to do anything with it anyway except for generating errors */
1832   if (decode_bin->have_type)
1833     goto exit;
1834
1835   decode_bin->have_type = TRUE;
1836
1837   /* special-case text/plain: we only want to accept it as a raw type if it
1838    * comes from a subtitle parser element or a demuxer, but not if it is the
1839    * type of the entire stream, in which case we just want to error out */
1840   if (typefind == decode_bin->typefind &&
1841       gst_structure_has_name (gst_caps_get_structure (caps, 0), "text/plain")) {
1842     gst_element_no_more_pads (GST_ELEMENT (decode_bin));
1843     /* we can't handle this type of stream */
1844     GST_ELEMENT_ERROR (decode_bin, STREAM, WRONG_TYPE,
1845         (_("This appears to be a text file")),
1846         ("decodebin cannot decode plain text files"));
1847     goto exit;
1848   }
1849
1850   /* autoplug the new pad with the caps that the signal gave us. */
1851   pad = gst_element_get_static_pad (typefind, "src");
1852   close_pad_link (typefind, pad, caps, decode_bin, FALSE);
1853   gst_object_unref (pad);
1854
1855   dynamic = gst_decode_bin_is_dynamic (decode_bin);
1856   if (dynamic == FALSE) {
1857     GST_DEBUG_OBJECT (decode_bin, "we have no dynamic elements anymore");
1858     /* if we have no dynamic elements, we know that no new pads
1859      * will be created and we can signal out no_more_pads signal */
1860     gst_element_no_more_pads (GST_ELEMENT (decode_bin));
1861   } else {
1862     /* more dynamic elements exist that could create new pads */
1863     GST_DEBUG_OBJECT (decode_bin, "we have more dynamic elements");
1864   }
1865
1866 exit:
1867   GST_STATE_UNLOCK (decode_bin);
1868   return;
1869
1870 shutting_down:
1871   {
1872     GST_DEBUG_OBJECT (decode_bin, "we are shutting down");
1873     GST_OBJECT_UNLOCK (decode_bin);
1874     return;
1875   }
1876 }
1877
1878 static void
1879 disconnect_unlinked_signals (GstDecodeBin * decode_bin, GstElement * element)
1880 {
1881   GstIterator *pad_it = NULL;
1882   gboolean done = FALSE;
1883
1884   pad_it = gst_element_iterate_src_pads (element);
1885   while (!done) {
1886     GstPad *pad = NULL;
1887
1888     switch (gst_iterator_next (pad_it, (gpointer) & pad)) {
1889       case GST_ITERATOR_OK:
1890         g_signal_handlers_disconnect_by_func (pad, (gpointer) unlinked,
1891             decode_bin);
1892         gst_object_unref (pad);
1893         break;
1894       case GST_ITERATOR_RESYNC:
1895         gst_iterator_resync (pad_it);
1896         break;
1897       default:
1898         done = TRUE;
1899         break;
1900     }
1901   }
1902   gst_iterator_free (pad_it);
1903 }
1904
1905
1906 static void
1907 cleanup_decodebin (GstDecodeBin * decode_bin)
1908 {
1909   GstIterator *elem_it = NULL, *gpad_it = NULL;
1910   GstPad *typefind_pad = NULL;
1911   gboolean done = FALSE;
1912
1913   g_return_if_fail (GST_IS_DECODE_BIN (decode_bin));
1914
1915   GST_DEBUG_OBJECT (decode_bin, "cleaning up decodebin");
1916
1917   typefind_pad = gst_element_get_static_pad (decode_bin->typefind, "src");
1918   if (GST_IS_PAD (typefind_pad)) {
1919     g_signal_handlers_block_by_func (typefind_pad, (gpointer) unlinked,
1920         decode_bin);
1921   }
1922
1923   elem_it = gst_bin_iterate_elements (GST_BIN (decode_bin));
1924   while (!done) {
1925     GstElement *element = NULL;
1926
1927     switch (gst_iterator_next (elem_it, (gpointer) & element)) {
1928       case GST_ITERATOR_OK:
1929         if (element != decode_bin->typefind && element != decode_bin->fakesink) {
1930           GST_DEBUG_OBJECT (element, "removing autoplugged element");
1931           disconnect_unlinked_signals (decode_bin, element);
1932           gst_element_set_state (element, GST_STATE_NULL);
1933           gst_bin_remove (GST_BIN (decode_bin), element);
1934         }
1935         gst_object_unref (element);
1936         break;
1937       case GST_ITERATOR_RESYNC:
1938         gst_iterator_resync (elem_it);
1939         break;
1940       case GST_ITERATOR_ERROR:
1941         done = TRUE;
1942         break;
1943       case GST_ITERATOR_DONE:
1944         done = TRUE;
1945         break;
1946     }
1947   }
1948   gst_iterator_free (elem_it);
1949
1950   done = FALSE;
1951   gpad_it = gst_element_iterate_pads (GST_ELEMENT (decode_bin));
1952   while (!done) {
1953     GstPad *pad = NULL;
1954
1955     switch (gst_iterator_next (gpad_it, (gpointer) & pad)) {
1956       case GST_ITERATOR_OK:
1957         GST_DEBUG_OBJECT (pad, "inspecting pad %s:%s",
1958             GST_DEBUG_PAD_NAME (pad));
1959         if (GST_IS_GHOST_PAD (pad) && GST_PAD_IS_SRC (pad)) {
1960           GST_DEBUG_OBJECT (pad, "removing ghost pad");
1961           gst_element_remove_pad (GST_ELEMENT (decode_bin), pad);
1962         }
1963         gst_object_unref (pad);
1964         break;
1965       case GST_ITERATOR_RESYNC:
1966         gst_iterator_resync (gpad_it);
1967         break;
1968       case GST_ITERATOR_ERROR:
1969         done = TRUE;
1970         break;
1971       case GST_ITERATOR_DONE:
1972         done = TRUE;
1973         break;
1974     }
1975   }
1976   gst_iterator_free (gpad_it);
1977
1978   if (GST_IS_PAD (typefind_pad)) {
1979     g_signal_handlers_unblock_by_func (typefind_pad, (gpointer) unlinked,
1980         decode_bin);
1981     g_signal_handlers_disconnect_by_func (typefind_pad, (gpointer) unlinked,
1982         decode_bin);
1983     gst_object_unref (typefind_pad);
1984   }
1985 }
1986
1987 static GstStateChangeReturn
1988 gst_decode_bin_change_state (GstElement * element, GstStateChange transition)
1989 {
1990   GstStateChangeReturn ret;
1991   GstDecodeBin *decode_bin;
1992
1993   decode_bin = GST_DECODE_BIN (element);
1994
1995   switch (transition) {
1996     case GST_STATE_CHANGE_NULL_TO_READY:
1997       decode_bin->numpads = 0;
1998       decode_bin->numwaiting = 0;
1999       decode_bin->dynamics = NULL;
2000       if (decode_bin->typefind == NULL)
2001         goto missing_typefind;
2002       break;
2003     case GST_STATE_CHANGE_READY_TO_PAUSED:
2004       GST_OBJECT_LOCK (decode_bin);
2005       decode_bin->shutting_down = FALSE;
2006       decode_bin->have_type = FALSE;
2007       GST_OBJECT_UNLOCK (decode_bin);
2008
2009       if (!add_fakesink (decode_bin))
2010         goto missing_fakesink;
2011       break;
2012     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2013     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2014       break;
2015     case GST_STATE_CHANGE_PAUSED_TO_READY:
2016       GST_OBJECT_LOCK (decode_bin);
2017       decode_bin->shutting_down = TRUE;
2018       GST_OBJECT_UNLOCK (decode_bin);
2019       break;
2020     default:
2021       break;
2022   }
2023
2024   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2025   if (ret == GST_STATE_CHANGE_FAILURE)
2026     return ret;
2027
2028   switch (transition) {
2029     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2030       break;
2031     case GST_STATE_CHANGE_PAUSED_TO_READY:
2032     case GST_STATE_CHANGE_READY_TO_NULL:
2033       free_dynamics (decode_bin);
2034       free_pad_probes (decode_bin);
2035       cleanup_decodebin (decode_bin);
2036       break;
2037     default:
2038       break;
2039   }
2040
2041   return ret;
2042 /* ERRORS */
2043 missing_typefind:
2044   {
2045     gst_element_post_message (element,
2046         gst_missing_element_message_new (element, "typefind"));
2047     GST_ELEMENT_ERROR (element, CORE, MISSING_PLUGIN, (NULL), ("no typefind!"));
2048     return GST_STATE_CHANGE_FAILURE;
2049   }
2050 missing_fakesink:
2051   {
2052     gst_element_post_message (element,
2053         gst_missing_element_message_new (element, "fakesink"));
2054     GST_ELEMENT_ERROR (element, CORE, MISSING_PLUGIN, (NULL), ("no fakesink!"));
2055     return GST_STATE_CHANGE_FAILURE;
2056   }
2057 }
2058
2059 static gboolean
2060 plugin_init (GstPlugin * plugin)
2061 {
2062   GST_DEBUG_CATEGORY_INIT (gst_decode_bin_debug, "decodebin", 0, "decoder bin");
2063
2064 #ifdef ENABLE_NLS
2065   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
2066       LOCALEDIR);
2067   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
2068   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2069 #endif /* ENABLE_NLS */
2070
2071   return gst_element_register (plugin, "decodebin", GST_RANK_NONE,
2072       GST_TYPE_DECODE_BIN);
2073 }
2074
2075 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2076     GST_VERSION_MINOR,
2077     "decodebin",
2078     "decoder bin", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME,
2079     GST_PACKAGE_ORIGIN)