discoverer: Wait until an update/filler newsegment event or buffer for subtitle streams
[platform/upstream/gstreamer.git] / gst-libs / gst / pbutils / gstdiscoverer.c
1 /* GStreamer
2  * Copyright (C) 2009 Edward Hervey <edward.hervey@collabora.co.uk>
3  *               2009 Nokia Corporation
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:gstdiscoverer
23  * @short_description: Utility for discovering information on URIs.
24  *
25  * The #GstDiscoverer is a utility object which allows to get as much
26  * information as possible from one or many URIs.
27  *
28  * It provides two APIs, allowing usage in blocking or non-blocking mode.
29  *
30  * The blocking mode just requires calling gst_discoverer_discover_uri()
31  * with the URI one wishes to discover.
32  *
33  * The non-blocking mode requires a running #GMainLoop in the default
34  * #GMainContext, where one connects to the various signals, appends the
35  * URIs to be processed (through gst_discoverer_discover_uri_async()) and then
36  * asks for the discovery to begin (through gst_discoverer_start()).
37  *
38  * All the information is returned in a #GstDiscovererInfo structure.
39  *
40  * Since: 0.10.31
41  */
42
43 #ifdef HAVE_CONFIG_H
44 #include "config.h"
45 #endif
46
47 #include <gst/video/video.h>
48
49 #include "pbutils.h"
50 #include "pbutils-marshal.h"
51 #include "pbutils-private.h"
52
53 #include "gst/glib-compat-private.h"
54
55 GST_DEBUG_CATEGORY_STATIC (discoverer_debug);
56 #define GST_CAT_DEFAULT discoverer_debug
57
58 static GQuark _CAPS_QUARK;
59 static GQuark _TAGS_QUARK;
60 static GQuark _MISSING_PLUGIN_QUARK;
61 static GQuark _STREAM_TOPOLOGY_QUARK;
62 static GQuark _TOPOLOGY_PAD_QUARK;
63
64
65 typedef struct
66 {
67   GstDiscoverer *dc;
68   GstPad *pad;
69   GstElement *queue;
70   GstElement *sink;
71   GstTagList *tags;
72 } PrivateStream;
73
74 typedef struct
75 {
76   GstPad *pad;
77   gulong id;
78 } PadWithId;
79
80 struct _GstDiscovererPrivate
81 {
82   gboolean async;
83
84   /* allowed time to discover each uri in nanoseconds */
85   GstClockTime timeout;
86
87   /* list of pending URI to process (current excluded) */
88   GList *pending_uris;
89
90   GMutex *lock;
91
92   /* TRUE if processing a URI */
93   gboolean processing;
94
95   /* TRUE if discoverer has been started */
96   gboolean running;
97
98   /* TRUE if ASYNC_DONE has been received (need to check for subtitle tags) */
99   gboolean async_done;
100
101   /* current items */
102   GstDiscovererInfo *current_info;
103   GError *current_error;
104   GstStructure *current_topology;
105
106   /* List of private streams */
107   GList *streams;
108
109   /* List of these sinks and their handler IDs (to remove the probe) */
110   GList *pending_subtitle_pads;
111
112   /* Global elements */
113   GstBin *pipeline;
114   GstElement *uridecodebin;
115   GstBus *bus;
116
117   GType decodebin_type;
118
119   /* Custom main context variables */
120   GMainContext *ctx;
121   guint sourceid;
122   guint timeoutid;
123
124   /* reusable queries */
125   GstQuery *seeking_query;
126
127   /* Handler ids for various callbacks */
128   gulong pad_added_id;
129   gulong pad_remove_id;
130   gulong element_added_id;
131   gulong bus_cb_id;
132 };
133
134 #define DISCO_LOCK(dc) g_mutex_lock (dc->priv->lock);
135 #define DISCO_UNLOCK(dc) g_mutex_unlock (dc->priv->lock);
136
137 static void
138 _do_init (void)
139 {
140   GST_DEBUG_CATEGORY_INIT (discoverer_debug, "discoverer", 0, "Discoverer");
141
142   _CAPS_QUARK = g_quark_from_static_string ("caps");
143   _TAGS_QUARK = g_quark_from_static_string ("tags");
144   _MISSING_PLUGIN_QUARK = g_quark_from_static_string ("missing-plugin");
145   _STREAM_TOPOLOGY_QUARK = g_quark_from_static_string ("stream-topology");
146   _TOPOLOGY_PAD_QUARK = g_quark_from_static_string ("pad");
147 };
148
149 G_DEFINE_TYPE_EXTENDED (GstDiscoverer, gst_discoverer, G_TYPE_OBJECT, 0,
150     _do_init ());
151
152 enum
153 {
154   SIGNAL_FINISHED,
155   SIGNAL_STARTING,
156   SIGNAL_DISCOVERED,
157   LAST_SIGNAL
158 };
159
160 #define DEFAULT_PROP_TIMEOUT 15 * GST_SECOND
161
162 enum
163 {
164   PROP_0,
165   PROP_TIMEOUT
166 };
167
168 static guint gst_discoverer_signals[LAST_SIGNAL] = { 0 };
169
170 static void gst_discoverer_set_timeout (GstDiscoverer * dc,
171     GstClockTime timeout);
172 static gboolean async_timeout_cb (GstDiscoverer * dc);
173
174 static void discoverer_bus_cb (GstBus * bus, GstMessage * msg,
175     GstDiscoverer * dc);
176 static void uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad,
177     GstDiscoverer * dc);
178 static void uridecodebin_pad_removed_cb (GstElement * uridecodebin,
179     GstPad * pad, GstDiscoverer * dc);
180
181 static void gst_discoverer_dispose (GObject * dc);
182 static void gst_discoverer_set_property (GObject * object, guint prop_id,
183     const GValue * value, GParamSpec * pspec);
184 static void gst_discoverer_get_property (GObject * object, guint prop_id,
185     GValue * value, GParamSpec * pspec);
186
187 static void
188 gst_discoverer_class_init (GstDiscovererClass * klass)
189 {
190   GObjectClass *gobject_class = (GObjectClass *) klass;
191
192   gobject_class->dispose = gst_discoverer_dispose;
193
194   gobject_class->set_property = gst_discoverer_set_property;
195   gobject_class->get_property = gst_discoverer_get_property;
196
197   g_type_class_add_private (klass, sizeof (GstDiscovererPrivate));
198
199   /* properties */
200   /**
201    * GstDiscoverer:timeout
202    *
203    * The duration (in nanoseconds) after which the discovery of an individual
204    * URI will timeout.
205    *
206    * If the discovery of a URI times out, the %GST_DISCOVERER_TIMEOUT will be
207    * set on the result flags.
208    */
209   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
210       g_param_spec_uint64 ("timeout", "timeout", "Timeout",
211           GST_SECOND, 3600 * GST_SECOND, DEFAULT_PROP_TIMEOUT,
212           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
213
214   /* signals */
215   /**
216    * GstDiscoverer::finished:
217    * @discoverer: the #GstDiscoverer
218    *
219    * Will be emitted when all pending URIs have been processed.
220    */
221   gst_discoverer_signals[SIGNAL_FINISHED] =
222       g_signal_new ("finished", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
223       G_STRUCT_OFFSET (GstDiscovererClass, finished),
224       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
225
226   /**
227    * GstDiscoverer::starting:
228    * @discoverer: the #GstDiscoverer
229    *
230    * Will be emitted when the discover starts analyzing the pending URIs
231    */
232   gst_discoverer_signals[SIGNAL_STARTING] =
233       g_signal_new ("starting", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
234       G_STRUCT_OFFSET (GstDiscovererClass, starting),
235       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
236
237   /**
238    * GstDiscoverer::discovered:
239    * @discoverer: the #GstDiscoverer
240    * @info: the results #GstDiscovererInfo
241    * @error: (type GLib.Error): #GError, which will be non-NULL if an error
242    *                            occurred during discovery
243    *
244    * Will be emitted when all information on a URI could be discovered.
245    */
246   gst_discoverer_signals[SIGNAL_DISCOVERED] =
247       g_signal_new ("discovered", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
248       G_STRUCT_OFFSET (GstDiscovererClass, discovered),
249       NULL, NULL, pbutils_marshal_VOID__POINTER_BOXED,
250       G_TYPE_NONE, 2, GST_TYPE_DISCOVERER_INFO,
251       G_TYPE_ERROR | G_SIGNAL_TYPE_STATIC_SCOPE);
252 }
253
254 static void
255 uridecodebin_element_added_cb (GstElement * uridecodebin,
256     GstElement * child, GstDiscoverer * dc)
257 {
258   GST_DEBUG ("New element added to uridecodebin : %s",
259       GST_ELEMENT_NAME (child));
260
261   if (G_OBJECT_TYPE (child) == dc->priv->decodebin_type) {
262     g_object_set (child, "post-stream-topology", TRUE, NULL);
263   }
264 }
265
266 static void
267 gst_discoverer_init (GstDiscoverer * dc)
268 {
269   GstElement *tmp;
270   GstFormat format = GST_FORMAT_TIME;
271
272   dc->priv = G_TYPE_INSTANCE_GET_PRIVATE (dc, GST_TYPE_DISCOVERER,
273       GstDiscovererPrivate);
274
275   dc->priv->timeout = DEFAULT_PROP_TIMEOUT;
276   dc->priv->async = FALSE;
277   dc->priv->async_done = FALSE;
278
279   dc->priv->lock = g_mutex_new ();
280
281   dc->priv->pending_subtitle_pads = NULL;
282
283   GST_LOG ("Creating pipeline");
284   dc->priv->pipeline = (GstBin *) gst_pipeline_new ("Discoverer");
285   GST_LOG_OBJECT (dc, "Creating uridecodebin");
286   dc->priv->uridecodebin =
287       gst_element_factory_make ("uridecodebin", "discoverer-uri");
288   if (G_UNLIKELY (dc->priv->uridecodebin == NULL)) {
289     GST_ERROR ("Can't create uridecodebin");
290     return;
291   }
292   GST_LOG_OBJECT (dc, "Adding uridecodebin to pipeline");
293   gst_bin_add (dc->priv->pipeline, dc->priv->uridecodebin);
294
295   dc->priv->pad_added_id =
296       g_signal_connect_object (dc->priv->uridecodebin, "pad-added",
297       G_CALLBACK (uridecodebin_pad_added_cb), dc, 0);
298   dc->priv->pad_remove_id =
299       g_signal_connect_object (dc->priv->uridecodebin, "pad-removed",
300       G_CALLBACK (uridecodebin_pad_removed_cb), dc, 0);
301
302   GST_LOG_OBJECT (dc, "Getting pipeline bus");
303   dc->priv->bus = gst_pipeline_get_bus ((GstPipeline *) dc->priv->pipeline);
304
305   dc->priv->bus_cb_id =
306       g_signal_connect_object (dc->priv->bus, "message",
307       G_CALLBACK (discoverer_bus_cb), dc, 0);
308
309   GST_DEBUG_OBJECT (dc, "Done initializing Discoverer");
310
311   /* This is ugly. We get the GType of decodebin so we can quickly detect
312    * when a decodebin is added to uridecodebin so we can set the
313    * post-stream-topology setting to TRUE */
314   dc->priv->element_added_id =
315       g_signal_connect_object (dc->priv->uridecodebin, "element-added",
316       G_CALLBACK (uridecodebin_element_added_cb), dc, 0);
317   tmp = gst_element_factory_make ("decodebin", NULL);
318   dc->priv->decodebin_type = G_OBJECT_TYPE (tmp);
319   gst_object_unref (tmp);
320
321   /* create queries */
322   dc->priv->seeking_query = gst_query_new_seeking (format);
323 }
324
325 static void
326 discoverer_reset (GstDiscoverer * dc)
327 {
328   GST_DEBUG_OBJECT (dc, "Resetting");
329
330   if (dc->priv->pending_uris) {
331     g_list_foreach (dc->priv->pending_uris, (GFunc) g_free, NULL);
332     g_list_free (dc->priv->pending_uris);
333     dc->priv->pending_uris = NULL;
334   }
335
336   if (dc->priv->pipeline)
337     gst_element_set_state ((GstElement *) dc->priv->pipeline, GST_STATE_NULL);
338 }
339
340 #define DISCONNECT_SIGNAL(o,i) G_STMT_START{           \
341   if ((i) && g_signal_handler_is_connected ((o), (i))) \
342     g_signal_handler_disconnect ((o), (i));            \
343   (i) = 0;                                             \
344 }G_STMT_END
345
346 static void
347 gst_discoverer_dispose (GObject * obj)
348 {
349   GstDiscoverer *dc = (GstDiscoverer *) obj;
350
351   GST_DEBUG_OBJECT (dc, "Disposing");
352
353   discoverer_reset (dc);
354
355   if (G_LIKELY (dc->priv->pipeline)) {
356     /* Workaround for bug #118536 */
357     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->pad_added_id);
358     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->pad_remove_id);
359     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->element_added_id);
360     DISCONNECT_SIGNAL (dc->priv->bus, dc->priv->bus_cb_id);
361
362     /* pipeline was set to NULL in _reset */
363     gst_object_unref (dc->priv->pipeline);
364     gst_object_unref (dc->priv->bus);
365
366     dc->priv->pipeline = NULL;
367     dc->priv->uridecodebin = NULL;
368     dc->priv->bus = NULL;
369   }
370
371   gst_discoverer_stop (dc);
372
373   if (dc->priv->lock) {
374     g_mutex_free (dc->priv->lock);
375     dc->priv->lock = NULL;
376   }
377
378   if (dc->priv->seeking_query) {
379     gst_query_unref (dc->priv->seeking_query);
380     dc->priv->seeking_query = NULL;
381   }
382
383   G_OBJECT_CLASS (gst_discoverer_parent_class)->dispose (obj);
384 }
385
386 static void
387 gst_discoverer_set_property (GObject * object, guint prop_id,
388     const GValue * value, GParamSpec * pspec)
389 {
390   GstDiscoverer *dc = (GstDiscoverer *) object;
391
392   switch (prop_id) {
393     case PROP_TIMEOUT:
394       gst_discoverer_set_timeout (dc, g_value_get_uint64 (value));
395       break;
396     default:
397       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
398       break;
399   }
400 }
401
402 static void
403 gst_discoverer_get_property (GObject * object, guint prop_id,
404     GValue * value, GParamSpec * pspec)
405 {
406   GstDiscoverer *dc = (GstDiscoverer *) object;
407
408   switch (prop_id) {
409     case PROP_TIMEOUT:
410       DISCO_LOCK (dc);
411       g_value_set_uint64 (value, dc->priv->timeout);
412       DISCO_UNLOCK (dc);
413       break;
414     default:
415       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
416       break;
417   }
418 }
419
420 static void
421 gst_discoverer_set_timeout (GstDiscoverer * dc, GstClockTime timeout)
422 {
423   GST_DEBUG_OBJECT (dc, "timeout : %" GST_TIME_FORMAT, GST_TIME_ARGS (timeout));
424
425   /* FIXME : update current pending timeout if we're running */
426   DISCO_LOCK (dc);
427   dc->priv->timeout = timeout;
428   DISCO_UNLOCK (dc);
429 }
430
431 static GstPadProbeReturn
432 _event_probe (GstPad * pad, GstPadProbeInfo * info, PrivateStream * ps)
433 {
434   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
435
436   if (GST_EVENT_TYPE (event) == GST_EVENT_TAG) {
437     GstTagList *tl = NULL, *tmp;
438
439     gst_event_parse_tag (event, &tl);
440     GST_DEBUG_OBJECT (pad, "tags %" GST_PTR_FORMAT, tl);
441     DISCO_LOCK (ps->dc);
442     /* If preroll is complete, drop these tags - the collected information is
443      * possibly already being processed and adding more tags would be racy */
444     if (G_LIKELY (ps->dc->priv->processing)) {
445       GST_DEBUG_OBJECT (pad, "private stream %p old tags %" GST_PTR_FORMAT, ps,
446           ps->tags);
447       tmp = gst_tag_list_merge (ps->tags, tl, GST_TAG_MERGE_APPEND);
448       if (ps->tags)
449         gst_tag_list_free (ps->tags);
450       ps->tags = tmp;
451       GST_DEBUG_OBJECT (pad, "private stream %p new tags %" GST_PTR_FORMAT, ps,
452           tmp);
453     } else
454       GST_DEBUG_OBJECT (pad, "Dropping tags since preroll is done");
455     DISCO_UNLOCK (ps->dc);
456   }
457
458   return GST_PAD_PROBE_OK;
459 }
460
461 static GstStaticCaps subtitle_caps = GST_STATIC_CAPS ("text/plain; "
462     "text/x-pango-markup; subpicture/x-pgs; subpicture/x-dvb; "
463     "application/x-subtitle-unknown; application/x-ssa; application/x-ass; "
464     "subtitle/x-kate; application/x-kate; video/x-dvd-subpicture");
465
466 static gboolean
467 is_subtitle_caps (const GstCaps * caps)
468 {
469   GstCaps *subs_caps;
470   gboolean ret;
471
472   subs_caps = gst_static_caps_get (&subtitle_caps);
473   ret = gst_caps_can_intersect (caps, subs_caps);
474   gst_caps_unref (subs_caps);
475
476   return ret;
477 }
478
479 static void
480 free_pad_id (PadWithId * d)
481 {
482
483   gst_pad_remove_data_probe (d->pad, d->id);
484   gst_object_unref (d->pad);
485   g_slice_free (PadWithId, d);
486
487 }
488
489 static void
490 got_subtitle_data (GstPad * pad, GstMiniObject * obj, GstDiscoverer * dc)
491 {
492
493   GList *item = NULL;
494   gboolean update;
495   gboolean is_event;
496
497   is_event = GST_IS_EVENT (obj);
498
499   if (!(GST_IS_BUFFER (obj) || (is_event
500               && GST_EVENT_TYPE ((GstEvent *) obj) == GST_EVENT_NEWSEGMENT)))
501     return;
502
503   if (is_event) {
504     gst_event_parse_new_segment ((GstEvent *) obj, &update, NULL, NULL, NULL,
505         NULL, NULL);
506     if (!update)
507       return;
508   }
509
510   DISCO_LOCK (dc);
511   for (item = dc->priv->pending_subtitle_pads; item; item = item->next) {
512     PadWithId *pad_id = (PadWithId *) item->data;
513     if (pad_id->pad == pad) {
514       dc->priv->pending_subtitle_pads =
515           g_list_remove_link (dc->priv->pending_subtitle_pads, item);
516       free_pad_id (pad_id);
517       break;
518     }
519   }
520
521   if (dc->priv->pending_subtitle_pads == NULL) {
522     GstMessage *msg = gst_message_new_application (NULL,
523         gst_structure_empty_new ("DiscovererDone"));
524     gst_element_post_message ((GstElement *) dc->priv->pipeline, msg);
525   }
526   DISCO_UNLOCK (dc);
527
528 }
529
530 static void
531 uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad,
532     GstDiscoverer * dc)
533 {
534   PrivateStream *ps;
535   GstPad *sinkpad = NULL;
536   GstCaps *caps;
537
538   GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
539
540   ps = g_slice_new0 (PrivateStream);
541
542   ps->dc = dc;
543   ps->pad = pad;
544   ps->queue = gst_element_factory_make ("queue", NULL);
545   ps->sink = gst_element_factory_make ("fakesink", NULL);
546
547   if (G_UNLIKELY (ps->queue == NULL || ps->sink == NULL))
548     goto error;
549
550   g_object_set (ps->sink, "silent", TRUE, NULL);
551   g_object_set (ps->queue, "max-size-buffers", 1, "silent", TRUE, NULL);
552
553   caps = gst_pad_query_caps (pad, NULL);
554
555   sinkpad = gst_element_get_static_pad (ps->queue, "sink");
556   if (sinkpad == NULL)
557     goto error;
558
559   if (is_subtitle_caps (caps)) {
560     /* Subtitle streams are sparse and may not provide any information - don't
561      * wait for data to preroll */
562     PadWithId *pad_id;
563     pad_id = g_slice_new0 (PadWithId);
564     pad_id->pad = GST_PAD_CAST (gst_object_ref (sinkpad));
565     pad_id->id =
566         gst_pad_add_data_probe (sinkpad, (GCallback) got_subtitle_data, dc);
567     g_object_set (ps->sink, "async", FALSE, NULL);
568     DISCO_LOCK (dc);
569     dc->priv->pending_subtitle_pads =
570         g_list_prepend (dc->priv->pending_subtitle_pads, pad_id);
571     DISCO_UNLOCK (dc);
572   }
573
574   gst_caps_unref (caps);
575
576   gst_bin_add_many (dc->priv->pipeline, ps->queue, ps->sink, NULL);
577
578   if (!gst_element_link_pads_full (ps->queue, "src", ps->sink, "sink",
579           GST_PAD_LINK_CHECK_NOTHING))
580     goto error;
581   if (!gst_element_sync_state_with_parent (ps->sink))
582     goto error;
583   if (!gst_element_sync_state_with_parent (ps->queue))
584     goto error;
585
586   if (gst_pad_link_full (pad, sinkpad,
587           GST_PAD_LINK_CHECK_NOTHING) != GST_PAD_LINK_OK)
588     goto error;
589   gst_object_unref (sinkpad);
590
591   /* Add an event probe */
592   gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
593       (GstPadProbeCallback) _event_probe, ps, NULL);
594
595   DISCO_LOCK (dc);
596   dc->priv->streams = g_list_append (dc->priv->streams, ps);
597   DISCO_UNLOCK (dc);
598
599   GST_DEBUG_OBJECT (dc, "Done handling pad");
600
601   return;
602
603 error:
604   GST_ERROR_OBJECT (dc, "Error while handling pad");
605   if (sinkpad)
606     gst_object_unref (sinkpad);
607   if (ps->queue)
608     gst_object_unref (ps->queue);
609   if (ps->sink)
610     gst_object_unref (ps->sink);
611   g_slice_free (PrivateStream, ps);
612   return;
613 }
614
615 static void
616 uridecodebin_pad_removed_cb (GstElement * uridecodebin, GstPad * pad,
617     GstDiscoverer * dc)
618 {
619   GList *tmp;
620   PrivateStream *ps;
621   GstPad *sinkpad;
622
623   GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
624
625   /* Find the PrivateStream */
626   DISCO_LOCK (dc);
627   for (tmp = dc->priv->streams; tmp; tmp = tmp->next) {
628     ps = (PrivateStream *) tmp->data;
629     if (ps->pad == pad)
630       break;
631   }
632
633   if (tmp == NULL) {
634     DISCO_UNLOCK (dc);
635     GST_DEBUG ("The removed pad wasn't controlled by us !");
636     return;
637   }
638
639   dc->priv->streams = g_list_delete_link (dc->priv->streams, tmp);
640   DISCO_UNLOCK (dc);
641
642   gst_element_set_state (ps->sink, GST_STATE_NULL);
643   gst_element_set_state (ps->queue, GST_STATE_NULL);
644   gst_element_unlink (ps->queue, ps->sink);
645
646   sinkpad = gst_element_get_static_pad (ps->queue, "sink");
647   gst_pad_unlink (pad, sinkpad);
648   gst_object_unref (sinkpad);
649
650   /* references removed here */
651   gst_bin_remove_many (dc->priv->pipeline, ps->sink, ps->queue, NULL);
652
653   if (ps->tags) {
654     gst_tag_list_free (ps->tags);
655   }
656
657   g_slice_free (PrivateStream, ps);
658
659   GST_DEBUG ("Done handling pad");
660 }
661
662 static GstStructure *
663 collect_stream_information (GstDiscoverer * dc, PrivateStream * ps, guint idx)
664 {
665   GstCaps *caps;
666   GstStructure *st;
667   gchar *stname;
668
669   stname = g_strdup_printf ("stream-%02d", idx);
670   st = gst_structure_new_empty (stname);
671   g_free (stname);
672
673   /* Get caps */
674   caps = gst_pad_get_current_caps (ps->pad);
675   if (!caps) {
676     GST_WARNING ("Couldn't get negotiated caps from %s:%s",
677         GST_DEBUG_PAD_NAME (ps->pad));
678     caps = gst_pad_query_caps (ps->pad, NULL);
679   }
680   if (caps) {
681     GST_DEBUG ("Got caps %" GST_PTR_FORMAT, caps);
682     gst_structure_id_set (st, _CAPS_QUARK, GST_TYPE_CAPS, caps, NULL);
683
684     gst_caps_unref (caps);
685   }
686   if (ps->tags)
687     gst_structure_id_set (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, ps->tags, NULL);
688
689   return st;
690 }
691
692 /* takes ownership of new_tags, may replace *taglist with a new one */
693 static void
694 gst_discoverer_merge_and_replace_tags (GstTagList ** taglist,
695     GstTagList * new_tags)
696 {
697   if (new_tags == NULL)
698     return;
699
700   if (*taglist == NULL) {
701     *taglist = new_tags;
702     return;
703   }
704
705   gst_tag_list_insert (*taglist, new_tags, GST_TAG_MERGE_REPLACE);
706   gst_tag_list_free (new_tags);
707 }
708
709 /* Parses a set of caps and tags in st and populates a GstDiscovererStreamInfo
710  * structure (parent, if !NULL, otherwise it allocates one)
711  */
712 static GstDiscovererStreamInfo *
713 collect_information (GstDiscoverer * dc, const GstStructure * st,
714     GstDiscovererStreamInfo * parent)
715 {
716   GstCaps *caps;
717   GstStructure *caps_st;
718   GstTagList *tags_st;
719   const gchar *name;
720   int tmp;
721   guint utmp;
722
723   if (!st || !gst_structure_id_has_field (st, _CAPS_QUARK)) {
724     GST_WARNING ("Couldn't find caps !");
725     if (parent)
726       return gst_discoverer_stream_info_ref (parent);
727     else
728       return (GstDiscovererStreamInfo *)
729           g_object_new (GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
730   }
731
732   gst_structure_id_get (st, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL);
733   caps_st = gst_caps_get_structure (caps, 0);
734   name = gst_structure_get_name (caps_st);
735
736   if (g_str_has_prefix (name, "audio/")) {
737     GstDiscovererAudioInfo *info;
738
739     if (parent)
740       info = (GstDiscovererAudioInfo *) gst_discoverer_stream_info_ref (parent);
741     else {
742       info = (GstDiscovererAudioInfo *)
743           g_object_new (GST_TYPE_DISCOVERER_AUDIO_INFO, NULL);
744       info->parent.caps = gst_caps_ref (caps);
745     }
746
747     if (gst_structure_get_int (caps_st, "rate", &tmp))
748       info->sample_rate = (guint) tmp;
749
750     if (gst_structure_get_int (caps_st, "channels", &tmp))
751       info->channels = (guint) tmp;
752
753     if (gst_structure_get_int (caps_st, "depth", &tmp))
754       info->depth = (guint) tmp;
755
756     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
757       gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st, NULL);
758       if (gst_tag_list_get_uint (tags_st, GST_TAG_BITRATE, &utmp) ||
759           gst_tag_list_get_uint (tags_st, GST_TAG_NOMINAL_BITRATE, &utmp))
760         info->bitrate = utmp;
761
762       if (gst_tag_list_get_uint (tags_st, GST_TAG_MAXIMUM_BITRATE, &utmp))
763         info->max_bitrate = utmp;
764
765       /* FIXME: Is it worth it to remove the tags we've parsed? */
766       gst_discoverer_merge_and_replace_tags (&info->parent.tags, tags_st);
767     }
768
769     if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) {
770       gchar *language;
771       if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags,
772               GST_TAG_LANGUAGE_CODE, &language)) {
773         info->language = language;
774       }
775     }
776
777     gst_caps_unref (caps);
778     return (GstDiscovererStreamInfo *) info;
779
780   } else if (g_str_has_prefix (name, "video/") ||
781       g_str_has_prefix (name, "image/")) {
782     GstDiscovererVideoInfo *info;
783     GstVideoInfo vinfo;
784
785     if (parent)
786       info = (GstDiscovererVideoInfo *) gst_discoverer_stream_info_ref (parent);
787     else {
788       info = (GstDiscovererVideoInfo *)
789           g_object_new (GST_TYPE_DISCOVERER_VIDEO_INFO, NULL);
790       info->parent.caps = gst_caps_ref (caps);
791     }
792
793     /* FIXME : gst_video_info_from_caps only works with raw caps,
794      * wouldn't we want to get all the info below for non-raw caps ? 
795      */
796     if (g_str_has_prefix (name, "video/x-raw") &&
797         gst_video_info_from_caps (&vinfo, caps)) {
798       info->width = (guint) vinfo.width;
799       info->height = (guint) vinfo.height;
800
801       info->depth = (guint) 0;
802
803       info->par_num = vinfo.par_n;
804       info->par_denom = vinfo.par_d;
805
806       info->framerate_num = vinfo.fps_n;
807       info->framerate_denom = vinfo.fps_d;
808
809       info->interlaced =
810           vinfo.interlace_mode != GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
811     }
812
813     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
814       gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st, NULL);
815       if (gst_tag_list_get_uint (tags_st, GST_TAG_BITRATE, &utmp) ||
816           gst_tag_list_get_uint (tags_st, GST_TAG_NOMINAL_BITRATE, &utmp))
817         info->bitrate = utmp;
818
819       if (gst_tag_list_get_uint (tags_st, GST_TAG_MAXIMUM_BITRATE, &utmp))
820         info->max_bitrate = utmp;
821
822       /* FIXME: Is it worth it to remove the tags we've parsed? */
823       gst_discoverer_merge_and_replace_tags (&info->parent.tags,
824           (GstTagList *) tags_st);
825     }
826
827     gst_caps_unref (caps);
828     return (GstDiscovererStreamInfo *) info;
829
830   } else if (is_subtitle_caps (caps)) {
831     GstDiscovererSubtitleInfo *info;
832
833     if (parent)
834       info =
835           (GstDiscovererSubtitleInfo *) gst_discoverer_stream_info_ref (parent);
836     else {
837       info = (GstDiscovererSubtitleInfo *)
838           g_object_new (GST_TYPE_DISCOVERER_SUBTITLE_INFO, NULL);
839       info->parent.caps = gst_caps_ref (caps);
840     }
841
842     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
843       const gchar *language;
844
845       gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st, NULL);
846
847       language = gst_structure_get_string (caps_st, GST_TAG_LANGUAGE_CODE);
848       if (language)
849         info->language = g_strdup (language);
850
851       /* FIXME: Is it worth it to remove the tags we've parsed? */
852       gst_discoverer_merge_and_replace_tags (&info->parent.tags, tags_st);
853     }
854
855     if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) {
856       gchar *language;
857       if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags,
858               GST_TAG_LANGUAGE_CODE, &language)) {
859         info->language = language;
860       }
861     }
862
863     gst_caps_unref (caps);
864     return (GstDiscovererStreamInfo *) info;
865
866   } else {
867     /* None of the above - populate what information we can */
868     GstDiscovererStreamInfo *info;
869
870     if (parent)
871       info = gst_discoverer_stream_info_ref (parent);
872     else {
873       info = (GstDiscovererStreamInfo *)
874           g_object_new (GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
875       info->caps = gst_caps_ref (caps);
876     }
877
878     if (gst_structure_id_get (st, _TAGS_QUARK,
879             GST_TYPE_TAG_LIST, &tags_st, NULL)) {
880       gst_discoverer_merge_and_replace_tags (&info->tags, tags_st);
881     }
882
883     gst_caps_unref (caps);
884     return info;
885   }
886
887 }
888
889 static GstStructure *
890 find_stream_for_node (GstDiscoverer * dc, const GstStructure * topology)
891 {
892   GstPad *pad;
893   GstPad *target_pad = NULL;
894   GstStructure *st = NULL;
895   PrivateStream *ps;
896   guint i;
897   GList *tmp;
898
899   if (!gst_structure_id_has_field (topology, _TOPOLOGY_PAD_QUARK)) {
900     GST_DEBUG ("Could not find pad for node %" GST_PTR_FORMAT "\n", topology);
901     return NULL;
902   }
903
904   gst_structure_id_get (topology, _TOPOLOGY_PAD_QUARK,
905       GST_TYPE_PAD, &pad, NULL);
906
907   if (!dc->priv->streams) {
908     gst_object_unref (pad);
909     return NULL;
910   }
911
912   for (i = 0, tmp = dc->priv->streams; tmp; tmp = tmp->next, i++) {
913     ps = (PrivateStream *) tmp->data;
914
915     target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ps->pad));
916     gst_object_unref (target_pad);
917
918     if (target_pad == pad)
919       break;
920   }
921
922   if (tmp)
923     st = collect_stream_information (dc, ps, i);
924
925   gst_object_unref (pad);
926
927   return st;
928 }
929
930 static gboolean
931 child_is_raw_stream (const GstCaps * parent, const GstCaps * child)
932 {
933   const GstStructure *st1, *st2;
934   const gchar *name1, *name2;
935
936   st1 = gst_caps_get_structure (parent, 0);
937   name1 = gst_structure_get_name (st1);
938   st2 = gst_caps_get_structure (child, 0);
939   name2 = gst_structure_get_name (st2);
940
941   if ((g_str_has_prefix (name1, "audio/") &&
942           g_str_has_prefix (name2, "audio/x-raw")) ||
943       ((g_str_has_prefix (name1, "video/") ||
944               g_str_has_prefix (name1, "image/")) &&
945           g_str_has_prefix (name2, "video/x-raw"))) {
946     /* child is the "raw" sub-stream corresponding to parent */
947     return TRUE;
948   }
949
950   if (is_subtitle_caps (parent))
951     return TRUE;
952
953   return FALSE;
954 }
955
956 /* If a parent is non-NULL, collected stream information will be appended to it
957  * (and where the information exists, it will be overriden)
958  */
959 static GstDiscovererStreamInfo *
960 parse_stream_topology (GstDiscoverer * dc, const GstStructure * topology,
961     GstDiscovererStreamInfo * parent)
962 {
963   GstDiscovererStreamInfo *res = NULL;
964   GstCaps *caps = NULL;
965   const GValue *nval = NULL;
966
967   GST_DEBUG ("parsing: %" GST_PTR_FORMAT, topology);
968
969   nval = gst_structure_get_value (topology, "next");
970
971   if (nval == NULL || GST_VALUE_HOLDS_STRUCTURE (nval)) {
972     GstStructure *st = find_stream_for_node (dc, topology);
973     gboolean add_to_list = TRUE;
974
975     if (st) {
976       res = collect_information (dc, st, parent);
977       gst_structure_free (st);
978     } else {
979       /* Didn't find a stream structure, so let's just use the caps we have */
980       res = collect_information (dc, topology, parent);
981     }
982
983     if (nval == NULL) {
984       /* FIXME : aggregate with information from main streams */
985       GST_DEBUG ("Coudn't find 'next' ! might be the last entry");
986     } else {
987       GstCaps *caps;
988       const GstStructure *st;
989
990       st = gst_value_get_structure (nval);
991
992       GST_DEBUG ("next is a structure %" GST_PTR_FORMAT, st);
993
994       if (!parent)
995         parent = res;
996
997       if (gst_structure_id_get (st, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL)) {
998         if (gst_caps_can_intersect (parent->caps, caps)) {
999           /* We sometimes get an extra sub-stream from the parser. If this is
1000            * the case, we just replace the parent caps with this stream's caps
1001            * since they might contain more information */
1002           gst_caps_replace (&parent->caps, caps);
1003
1004           parse_stream_topology (dc, st, parent);
1005           add_to_list = FALSE;
1006         } else if (child_is_raw_stream (parent->caps, caps)) {
1007           /* This is the "raw" stream corresponding to the parent. This
1008            * contains more information than the parent, tags etc. */
1009           parse_stream_topology (dc, st, parent);
1010           add_to_list = FALSE;
1011         } else {
1012           GstDiscovererStreamInfo *next = parse_stream_topology (dc, st, NULL);
1013           res->next = next;
1014           next->previous = res;
1015         }
1016         gst_caps_unref (caps);
1017       }
1018     }
1019
1020     if (add_to_list) {
1021       dc->priv->current_info->stream_list =
1022           g_list_append (dc->priv->current_info->stream_list, res);
1023     } else {
1024       gst_discoverer_stream_info_unref (res);
1025     }
1026
1027   } else if (GST_VALUE_HOLDS_LIST (nval)) {
1028     guint i, len;
1029     GstDiscovererContainerInfo *cont;
1030     GstTagList *tags;
1031
1032     if (!gst_structure_id_get (topology, _CAPS_QUARK,
1033             GST_TYPE_CAPS, &caps, NULL))
1034       GST_WARNING ("Couldn't find caps !");
1035
1036     len = gst_value_list_get_size (nval);
1037     GST_DEBUG ("next is a list of %d entries", len);
1038
1039     cont = (GstDiscovererContainerInfo *)
1040         g_object_new (GST_TYPE_DISCOVERER_CONTAINER_INFO, NULL);
1041     cont->parent.caps = caps;
1042     res = (GstDiscovererStreamInfo *) cont;
1043
1044     if (gst_structure_id_has_field (topology, _TAGS_QUARK)) {
1045       GstTagList *tmp;
1046
1047       gst_structure_id_get (topology, _TAGS_QUARK,
1048           GST_TYPE_TAG_LIST, &tags, NULL);
1049
1050       GST_DEBUG ("Merge tags %" GST_PTR_FORMAT, tags);
1051
1052       tmp =
1053           gst_tag_list_merge (cont->parent.tags, (GstTagList *) tags,
1054           GST_TAG_MERGE_APPEND);
1055       gst_tag_list_free (tags);
1056       if (cont->parent.tags)
1057         gst_tag_list_free (cont->parent.tags);
1058       cont->parent.tags = tmp;
1059       GST_DEBUG ("Container info tags %" GST_PTR_FORMAT, tmp);
1060     }
1061
1062     for (i = 0; i < len; i++) {
1063       const GValue *subv = gst_value_list_get_value (nval, i);
1064       const GstStructure *subst = gst_value_get_structure (subv);
1065       GstDiscovererStreamInfo *substream;
1066
1067       GST_DEBUG ("%d %" GST_PTR_FORMAT, i, subst);
1068
1069       substream = parse_stream_topology (dc, subst, NULL);
1070
1071       substream->previous = res;
1072       cont->streams =
1073           g_list_append (cont->streams,
1074           gst_discoverer_stream_info_ref (substream));
1075     }
1076   }
1077
1078   return res;
1079 }
1080
1081 /* Called when pipeline is pre-rolled */
1082 static void
1083 discoverer_collect (GstDiscoverer * dc)
1084 {
1085   GST_DEBUG ("Collecting information");
1086
1087   /* Stop the timeout handler if present */
1088   if (dc->priv->timeoutid) {
1089     g_source_remove (dc->priv->timeoutid);
1090     dc->priv->timeoutid = 0;
1091   }
1092
1093   if (dc->priv->streams) {
1094     /* FIXME : Make this querying optional */
1095     if (TRUE) {
1096       GstElement *pipeline = (GstElement *) dc->priv->pipeline;
1097       gint64 dur;
1098
1099       GST_DEBUG ("Attempting to query duration");
1100
1101       if (gst_element_query_duration (pipeline, GST_FORMAT_TIME, &dur)) {
1102         GST_DEBUG ("Got duration %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
1103         dc->priv->current_info->duration = (guint64) dur;
1104       } else {
1105         GstStateChangeReturn sret;
1106
1107         /* Some parsers may not even return a rough estimate right away, e.g.
1108          * because they've only processed a single frame so far, so if we
1109          * didn't get a duration the first time, spin a bit and try again.
1110          * Ugly, but still better than making parsers or other elements return
1111          * completely bogus values. We need some API extensions to solve this
1112          * better. */
1113         GST_INFO ("No duration yet, try a bit harder..");
1114         sret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
1115         if (sret != GST_STATE_CHANGE_FAILURE) {
1116           int i;
1117
1118           for (i = 0; i < 2; ++i) {
1119             g_usleep (G_USEC_PER_SEC / 20);
1120             if (gst_element_query_duration (pipeline, GST_FORMAT_TIME, &dur)
1121                 && dur > 0) {
1122               GST_DEBUG ("Got duration %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
1123               dc->priv->current_info->duration = (guint64) dur;
1124               break;
1125             }
1126           }
1127           gst_element_set_state (pipeline, GST_STATE_PAUSED);
1128         }
1129       }
1130
1131       if (dc->priv->seeking_query) {
1132         if (gst_element_query (pipeline, dc->priv->seeking_query)) {
1133           GstFormat format;
1134           gboolean seekable;
1135
1136           gst_query_parse_seeking (dc->priv->seeking_query, &format,
1137               &seekable, NULL, NULL);
1138           if (format == GST_FORMAT_TIME) {
1139             GST_DEBUG ("Got seekable %d", seekable);
1140             dc->priv->current_info->seekable = seekable;
1141           }
1142         }
1143       }
1144     }
1145
1146     if (dc->priv->current_topology)
1147       dc->priv->current_info->stream_info = parse_stream_topology (dc,
1148           dc->priv->current_topology, NULL);
1149
1150     /*
1151      * Images need some special handling. They do not have a duration, have
1152      * caps named image/<foo> (th exception being MJPEG video which is also
1153      * type image/jpeg), and should consist of precisely one stream (actually
1154      * initially there are 2, the image and raw stream, but we squash these
1155      * while parsing the stream topology). At some point, if we find that these
1156      * conditions are not sufficient, we can count the number of decoders and
1157      * parsers in the chain, and if there's more than one decoder, or any
1158      * parser at all, we should not mark this as an image.
1159      */
1160     if (dc->priv->current_info->duration == 0 &&
1161         dc->priv->current_info->stream_info != NULL &&
1162         dc->priv->current_info->stream_info->next == NULL) {
1163       GstStructure *st =
1164           gst_caps_get_structure (dc->priv->current_info->stream_info->caps, 0);
1165
1166       if (g_str_has_prefix (gst_structure_get_name (st), "image/"))
1167         ((GstDiscovererVideoInfo *) dc->priv->current_info->
1168             stream_info)->is_image = TRUE;
1169     }
1170   }
1171
1172   if (dc->priv->async) {
1173     GST_DEBUG ("Emitting 'discoverered'");
1174     g_signal_emit (dc, gst_discoverer_signals[SIGNAL_DISCOVERED], 0,
1175         dc->priv->current_info, dc->priv->current_error);
1176     /* Clients get a copy of current_info since it is a boxed type */
1177     gst_discoverer_info_unref (dc->priv->current_info);
1178   }
1179 }
1180
1181 static void
1182 get_async_cb (gpointer cb_data, GSource * source, GSourceFunc * func,
1183     gpointer * data)
1184 {
1185   *func = (GSourceFunc) async_timeout_cb;
1186   *data = cb_data;
1187 }
1188
1189 /* Wrapper since GSourceCallbackFuncs don't expect a return value from ref() */
1190 static void
1191 _void_g_object_ref (gpointer object)
1192 {
1193   g_object_ref (G_OBJECT (object));
1194 }
1195
1196 static void
1197 handle_current_async (GstDiscoverer * dc)
1198 {
1199   GSource *source;
1200   static GSourceCallbackFuncs cb_funcs = {
1201     _void_g_object_ref,
1202     g_object_unref,
1203     get_async_cb,
1204   };
1205
1206   /* Attach a timeout to the main context */
1207   source = g_timeout_source_new (dc->priv->timeout / GST_MSECOND);
1208   g_source_set_callback_indirect (source, g_object_ref (dc), &cb_funcs);
1209   dc->priv->timeoutid = g_source_attach (source, dc->priv->ctx);
1210   g_source_unref (source);
1211 }
1212
1213
1214 /* Returns TRUE if processing should stop */
1215 static gboolean
1216 handle_message (GstDiscoverer * dc, GstMessage * msg)
1217 {
1218   gboolean done = FALSE;
1219
1220   GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "got a %s message",
1221       GST_MESSAGE_TYPE_NAME (msg));
1222
1223   switch (GST_MESSAGE_TYPE (msg)) {
1224     case GST_MESSAGE_ERROR:{
1225       GError *gerr;
1226       gchar *debug;
1227
1228       gst_message_parse_error (msg, &gerr, &debug);
1229       GST_WARNING_OBJECT (GST_MESSAGE_SRC (msg),
1230           "Got an error [debug:%s], [message:%s]", debug, gerr->message);
1231       dc->priv->current_error = gerr;
1232       g_free (debug);
1233
1234       /* We need to stop */
1235       done = TRUE;
1236
1237       /* Don't override missing plugin result code for missing plugin errors */
1238       if (dc->priv->current_info->result != GST_DISCOVERER_MISSING_PLUGINS ||
1239           (!g_error_matches (gerr, GST_CORE_ERROR,
1240                   GST_CORE_ERROR_MISSING_PLUGIN) &&
1241               !g_error_matches (gerr, GST_STREAM_ERROR,
1242                   GST_STREAM_ERROR_CODEC_NOT_FOUND))) {
1243         GST_DEBUG ("Setting result to ERROR");
1244         dc->priv->current_info->result = GST_DISCOVERER_ERROR;
1245       }
1246     }
1247       break;
1248
1249     case GST_MESSAGE_EOS:
1250       GST_DEBUG ("Got EOS !");
1251       done = TRUE;
1252       break;
1253
1254     case GST_MESSAGE_APPLICATION:{
1255       const gchar *name;
1256       gboolean async_done;
1257       name = gst_structure_get_name (gst_message_get_structure (msg));
1258       /* Maybe ASYNC_DONE is received & we're just waiting for subtitle tags */
1259       DISCO_LOCK (dc);
1260       async_done = dc->priv->async_done;
1261       DISCO_UNLOCK (dc);
1262       if (g_str_equal (name, "DiscovererDone") && async_done)
1263         return TRUE;
1264       break;
1265     }
1266
1267     case GST_MESSAGE_ASYNC_DONE:
1268       if (GST_MESSAGE_SRC (msg) == (GstObject *) dc->priv->pipeline) {
1269         GST_DEBUG ("Finished changing state asynchronously");
1270         DISCO_LOCK (dc);
1271         if (dc->priv->pending_subtitle_pads == NULL) {
1272           done = TRUE;
1273         } else {
1274           /* Remember that ASYNC_DONE has been received, wait for subtitles */
1275           dc->priv->async_done = TRUE;
1276         }
1277         DISCO_UNLOCK (dc);
1278
1279       }
1280       break;
1281
1282     case GST_MESSAGE_ELEMENT:
1283     {
1284       GQuark sttype;
1285       const GstStructure *structure;
1286
1287       structure = gst_message_get_structure (msg);
1288       sttype = gst_structure_get_name_id (structure);
1289       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg),
1290           "structure %" GST_PTR_FORMAT, structure);
1291       if (sttype == _MISSING_PLUGIN_QUARK) {
1292         GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg),
1293             "Setting result to MISSING_PLUGINS");
1294         dc->priv->current_info->result = GST_DISCOVERER_MISSING_PLUGINS;
1295         if (dc->priv->current_info->misc)
1296           gst_structure_free (dc->priv->current_info->misc);
1297         dc->priv->current_info->misc = gst_structure_copy (structure);
1298       } else if (sttype == _STREAM_TOPOLOGY_QUARK) {
1299         if (dc->priv->current_topology)
1300           gst_structure_free (dc->priv->current_topology);
1301         dc->priv->current_topology = gst_structure_copy (structure);
1302       }
1303     }
1304       break;
1305
1306     case GST_MESSAGE_TAG:
1307     {
1308       GstTagList *tl, *tmp;
1309
1310       gst_message_parse_tag (msg, &tl);
1311       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Got tags %" GST_PTR_FORMAT, tl);
1312       /* Merge with current tags */
1313       tmp =
1314           gst_tag_list_merge (dc->priv->current_info->tags, tl,
1315           GST_TAG_MERGE_APPEND);
1316       gst_tag_list_free (tl);
1317       if (dc->priv->current_info->tags)
1318         gst_tag_list_free (dc->priv->current_info->tags);
1319       dc->priv->current_info->tags = tmp;
1320       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Current info %p, tags %"
1321           GST_PTR_FORMAT, dc->priv->current_info, tmp);
1322     }
1323       break;
1324
1325     default:
1326       break;
1327   }
1328
1329   return done;
1330 }
1331
1332 static void
1333 handle_current_sync (GstDiscoverer * dc)
1334 {
1335   GTimer *timer;
1336   gdouble deadline = ((gdouble) dc->priv->timeout) / GST_SECOND;
1337   GstMessage *msg;
1338   gboolean done = FALSE;
1339
1340   timer = g_timer_new ();
1341   g_timer_start (timer);
1342
1343   do {
1344     /* poll bus with timeout */
1345     /* FIXME : make the timeout more fine-tuned */
1346     if ((msg = gst_bus_timed_pop (dc->priv->bus, GST_SECOND / 2))) {
1347       done = handle_message (dc, msg);
1348       gst_message_unref (msg);
1349     }
1350   } while (!done && (g_timer_elapsed (timer, NULL) < deadline));
1351
1352   /* return result */
1353   if (!done) {
1354     GST_DEBUG ("we timed out! Setting result to TIMEOUT");
1355     dc->priv->current_info->result = GST_DISCOVERER_TIMEOUT;
1356   }
1357
1358   GST_DEBUG ("Done");
1359
1360   g_timer_stop (timer);
1361   g_timer_destroy (timer);
1362 }
1363
1364 static void
1365 _setup_locked (GstDiscoverer * dc)
1366 {
1367   GstStateChangeReturn ret;
1368
1369   GST_DEBUG ("Setting up");
1370
1371   /* Pop URI off the pending URI list */
1372   dc->priv->current_info =
1373       (GstDiscovererInfo *) g_object_new (GST_TYPE_DISCOVERER_INFO, NULL);
1374   dc->priv->current_info->uri = (gchar *) dc->priv->pending_uris->data;
1375   dc->priv->pending_uris =
1376       g_list_delete_link (dc->priv->pending_uris, dc->priv->pending_uris);
1377
1378   /* set uri on uridecodebin */
1379   g_object_set (dc->priv->uridecodebin, "uri", dc->priv->current_info->uri,
1380       NULL);
1381
1382   GST_DEBUG ("Current is now %s", dc->priv->current_info->uri);
1383
1384   dc->priv->processing = TRUE;
1385
1386   /* set pipeline to PAUSED */
1387   DISCO_UNLOCK (dc);
1388   GST_DEBUG ("Setting pipeline to PAUSED");
1389   ret =
1390       gst_element_set_state ((GstElement *) dc->priv->pipeline,
1391       GST_STATE_PAUSED);
1392   DISCO_LOCK (dc);
1393
1394   GST_DEBUG_OBJECT (dc, "Pipeline going to PAUSED : %s",
1395       gst_element_state_change_return_get_name (ret));
1396 }
1397
1398 static void
1399 discoverer_cleanup (GstDiscoverer * dc)
1400 {
1401   GST_DEBUG ("Cleaning up");
1402
1403   gst_bus_set_flushing (dc->priv->bus, TRUE);
1404   gst_element_set_state ((GstElement *) dc->priv->pipeline, GST_STATE_READY);
1405   gst_bus_set_flushing (dc->priv->bus, FALSE);
1406
1407   DISCO_LOCK (dc);
1408   if (dc->priv->current_error)
1409     g_error_free (dc->priv->current_error);
1410   dc->priv->current_error = NULL;
1411   if (dc->priv->current_topology) {
1412     gst_structure_free (dc->priv->current_topology);
1413     dc->priv->current_topology = NULL;
1414   }
1415
1416   dc->priv->current_info = NULL;
1417
1418   g_list_foreach (dc->priv->pending_subtitle_pads, (GFunc) free_pad_id, NULL);
1419   g_list_free (dc->priv->pending_subtitle_pads);
1420   dc->priv->pending_subtitle_pads = NULL;
1421   dc->priv->async_done = FALSE;
1422
1423   /* Try popping the next uri */
1424   if (dc->priv->async) {
1425     if (dc->priv->pending_uris != NULL) {
1426       _setup_locked (dc);
1427       DISCO_UNLOCK (dc);
1428       /* Start timeout */
1429       handle_current_async (dc);
1430     } else {
1431       /* We're done ! */
1432       DISCO_UNLOCK (dc);
1433       g_signal_emit (dc, gst_discoverer_signals[SIGNAL_FINISHED], 0);
1434     }
1435   } else
1436     DISCO_UNLOCK (dc);
1437
1438   GST_DEBUG ("out");
1439 }
1440
1441 static void
1442 discoverer_bus_cb (GstBus * bus, GstMessage * msg, GstDiscoverer * dc)
1443 {
1444   if (dc->priv->processing) {
1445     if (handle_message (dc, msg)) {
1446       GST_DEBUG ("Stopping asynchronously");
1447       /* Serialise with _event_probe() */
1448       DISCO_LOCK (dc);
1449       dc->priv->processing = FALSE;
1450       DISCO_UNLOCK (dc);
1451       discoverer_collect (dc);
1452       discoverer_cleanup (dc);
1453     }
1454   }
1455 }
1456
1457 static gboolean
1458 async_timeout_cb (GstDiscoverer * dc)
1459 {
1460   if (!g_source_is_destroyed (g_main_current_source ())) {
1461     dc->priv->timeoutid = 0;
1462     GST_DEBUG ("Setting result to TIMEOUT");
1463     dc->priv->current_info->result = GST_DISCOVERER_TIMEOUT;
1464     dc->priv->processing = FALSE;
1465     discoverer_collect (dc);
1466     discoverer_cleanup (dc);
1467   }
1468   return FALSE;
1469 }
1470
1471 /* If there is a pending URI, it will pop it from the list of pending
1472  * URIs and start the discovery on it.
1473  *
1474  * Returns GST_DISCOVERER_OK if the next URI was popped and is processing,
1475  * else a error flag.
1476  */
1477 static GstDiscovererResult
1478 start_discovering (GstDiscoverer * dc)
1479 {
1480   GstDiscovererResult res = GST_DISCOVERER_OK;
1481
1482   GST_DEBUG ("Starting");
1483
1484   DISCO_LOCK (dc);
1485   if (dc->priv->pending_uris == NULL) {
1486     GST_WARNING ("No URI to process");
1487     res = GST_DISCOVERER_URI_INVALID;
1488     DISCO_UNLOCK (dc);
1489     goto beach;
1490   }
1491
1492   if (dc->priv->current_info != NULL) {
1493     GST_WARNING ("Already processing a file");
1494     res = GST_DISCOVERER_BUSY;
1495     DISCO_UNLOCK (dc);
1496     goto beach;
1497   }
1498
1499   g_signal_emit (dc, gst_discoverer_signals[SIGNAL_STARTING], 0);
1500
1501   _setup_locked (dc);
1502
1503   DISCO_UNLOCK (dc);
1504
1505   if (dc->priv->async)
1506     handle_current_async (dc);
1507   else
1508     handle_current_sync (dc);
1509
1510 beach:
1511   return res;
1512 }
1513
1514
1515 /**
1516  * gst_discoverer_start:
1517  * @discoverer: A #GstDiscoverer
1518  *
1519  * Allow asynchronous discovering of URIs to take place.
1520  * A #GMainLoop must be available for #GstDiscoverer to properly work in
1521  * asynchronous mode.
1522  *
1523  * Since: 0.10.31
1524  */
1525 void
1526 gst_discoverer_start (GstDiscoverer * discoverer)
1527 {
1528   GSource *source;
1529   GMainContext *ctx = NULL;
1530
1531   GST_DEBUG_OBJECT (discoverer, "Starting...");
1532
1533   if (discoverer->priv->async) {
1534     GST_DEBUG_OBJECT (discoverer, "We were already started");
1535     return;
1536   }
1537
1538   discoverer->priv->async = TRUE;
1539   discoverer->priv->running = TRUE;
1540
1541   ctx = g_main_context_get_thread_default ();
1542
1543   /* Connect to bus signals */
1544   if (ctx == NULL)
1545     ctx = g_main_context_default ();
1546
1547   source = gst_bus_create_watch (discoverer->priv->bus);
1548   g_source_set_callback (source, (GSourceFunc) gst_bus_async_signal_func,
1549       NULL, NULL);
1550   discoverer->priv->sourceid = g_source_attach (source, ctx);
1551   g_source_unref (source);
1552   discoverer->priv->ctx = g_main_context_ref (ctx);
1553
1554   start_discovering (discoverer);
1555   GST_DEBUG_OBJECT (discoverer, "Started");
1556 }
1557
1558 /**
1559  * gst_discoverer_stop:
1560  * @discoverer: A #GstDiscoverer
1561  *
1562  * Stop the discovery of any pending URIs and clears the list of
1563  * pending URIS (if any).
1564  *
1565  * Since: 0.10.31
1566  */
1567 void
1568 gst_discoverer_stop (GstDiscoverer * discoverer)
1569 {
1570   GST_DEBUG_OBJECT (discoverer, "Stopping...");
1571
1572   if (!discoverer->priv->async) {
1573     GST_DEBUG_OBJECT (discoverer,
1574         "We were already stopped, or running synchronously");
1575     return;
1576   }
1577
1578   DISCO_LOCK (discoverer);
1579   if (discoverer->priv->processing) {
1580     /* We prevent any further processing by setting the bus to
1581      * flushing and setting the pipeline to READY.
1582      * _reset() will take care of the rest of the cleanup */
1583     if (discoverer->priv->bus)
1584       gst_bus_set_flushing (discoverer->priv->bus, TRUE);
1585     if (discoverer->priv->pipeline)
1586       gst_element_set_state ((GstElement *) discoverer->priv->pipeline,
1587           GST_STATE_READY);
1588   }
1589   discoverer->priv->running = FALSE;
1590   DISCO_UNLOCK (discoverer);
1591
1592   /* Remove timeout handler */
1593   if (discoverer->priv->timeoutid) {
1594     g_source_remove (discoverer->priv->timeoutid);
1595     discoverer->priv->timeoutid = 0;
1596   }
1597   /* Remove signal watch */
1598   if (discoverer->priv->sourceid) {
1599     g_source_remove (discoverer->priv->sourceid);
1600     discoverer->priv->sourceid = 0;
1601   }
1602   /* Unref main context */
1603   if (discoverer->priv->ctx) {
1604     g_main_context_unref (discoverer->priv->ctx);
1605     discoverer->priv->ctx = NULL;
1606   }
1607   discoverer_reset (discoverer);
1608
1609   discoverer->priv->async = FALSE;
1610
1611   GST_DEBUG_OBJECT (discoverer, "Stopped");
1612 }
1613
1614 /**
1615  * gst_discoverer_discover_uri_async:
1616  * @discoverer: A #GstDiscoverer
1617  * @uri: the URI to add.
1618  *
1619  * Appends the given @uri to the list of URIs to discoverer. The actual
1620  * discovery of the @uri will only take place if gst_discoverer_start() has
1621  * been called.
1622  *
1623  * A copy of @uri will be made internally, so the caller can safely g_free()
1624  * afterwards.
1625  *
1626  * Returns: %TRUE if the @uri was successfully appended to the list of pending
1627  * uris, else %FALSE
1628  *
1629  * Since: 0.10.31
1630  */
1631 gboolean
1632 gst_discoverer_discover_uri_async (GstDiscoverer * discoverer,
1633     const gchar * uri)
1634 {
1635   gboolean can_run;
1636
1637   GST_DEBUG_OBJECT (discoverer, "uri : %s", uri);
1638
1639   DISCO_LOCK (discoverer);
1640   can_run = (discoverer->priv->pending_uris == NULL);
1641   discoverer->priv->pending_uris =
1642       g_list_append (discoverer->priv->pending_uris, g_strdup (uri));
1643   DISCO_UNLOCK (discoverer);
1644
1645   if (can_run)
1646     start_discovering (discoverer);
1647
1648   return TRUE;
1649 }
1650
1651
1652 /* Synchronous mode */
1653 /**
1654  * gst_discoverer_discover_uri:
1655  * @discoverer: A #GstDiscoverer
1656  * @uri: The URI to run on.
1657  * @err: (out) (allow-none): If an error occurred, this field will be filled in.
1658  *
1659  * Synchronously discovers the given @uri.
1660  *
1661  * A copy of @uri will be made internally, so the caller can safely g_free()
1662  * afterwards.
1663  *
1664  * Returns: (transfer full): the result of the scanning. Can be %NULL if an
1665  * error occurred.
1666  *
1667  * Since: 0.10.31
1668  */
1669 GstDiscovererInfo *
1670 gst_discoverer_discover_uri (GstDiscoverer * discoverer, const gchar * uri,
1671     GError ** err)
1672 {
1673   GstDiscovererResult res = 0;
1674   GstDiscovererInfo *info;
1675
1676   GST_DEBUG_OBJECT (discoverer, "uri:%s", uri);
1677
1678   DISCO_LOCK (discoverer);
1679   if (G_UNLIKELY (discoverer->priv->current_info)) {
1680     DISCO_UNLOCK (discoverer);
1681     GST_WARNING_OBJECT (discoverer, "Already handling a uri");
1682     return NULL;
1683   }
1684
1685   discoverer->priv->pending_uris =
1686       g_list_append (discoverer->priv->pending_uris, g_strdup (uri));
1687   DISCO_UNLOCK (discoverer);
1688
1689   res = start_discovering (discoverer);
1690   discoverer_collect (discoverer);
1691
1692   /* Get results */
1693   if (err) {
1694     if (discoverer->priv->current_error)
1695       *err = g_error_copy (discoverer->priv->current_error);
1696     else
1697       *err = NULL;
1698   }
1699   if (res != GST_DISCOVERER_OK) {
1700     GST_DEBUG ("Setting result to %d (was %d)", res,
1701         discoverer->priv->current_info->result);
1702     discoverer->priv->current_info->result = res;
1703   }
1704   info = discoverer->priv->current_info;
1705
1706   discoverer_cleanup (discoverer);
1707
1708   return info;
1709 }
1710
1711 /**
1712  * gst_discoverer_new:
1713  * @timeout: timeout per file, in nanoseconds. Allowed are values between
1714  *     one second (#GST_SECOND) and one hour (3600 * #GST_SECOND)
1715  * @err: a pointer to a #GError. can be %NULL
1716  *
1717  * Creates a new #GstDiscoverer with the provided timeout.
1718  *
1719  * Returns: (transfer full): The new #GstDiscoverer.
1720  * If an error occurred when creating the discoverer, @err will be set
1721  * accordingly and %NULL will be returned. If @err is set, the caller must
1722  * free it when no longer needed using g_error_free().
1723  *
1724  * Since: 0.10.31
1725  */
1726 GstDiscoverer *
1727 gst_discoverer_new (GstClockTime timeout, GError ** err)
1728 {
1729   GstDiscoverer *res;
1730
1731   res = g_object_new (GST_TYPE_DISCOVERER, "timeout", timeout, NULL);
1732   if (res->priv->uridecodebin == NULL) {
1733     if (err)
1734       *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN,
1735           "Couldn't create 'uridecodebin' element");
1736     gst_object_unref (res);
1737     res = NULL;
1738   }
1739   return res;
1740 }