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