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