pbutils: Add/fix various annotations
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / 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  * @title: GstDiscoverer
24  * @short_description: Utility for discovering information on URIs.
25  *
26  * The #GstDiscoverer is a utility object which allows to get as much
27  * information as possible from one or many URIs.
28  *
29  * It provides two APIs, allowing usage in blocking or non-blocking mode.
30  *
31  * The blocking mode just requires calling gst_discoverer_discover_uri()
32  * with the URI one wishes to discover.
33  *
34  * The non-blocking mode requires a running #GMainLoop iterating a
35  * #GMainContext, where one connects to the various signals, appends the
36  * URIs to be processed (through gst_discoverer_discover_uri_async()) and then
37  * asks for the discovery to begin (through gst_discoverer_start()).
38  * By default this will use the GLib default main context unless you have
39  * set a custom context using g_main_context_push_thread_default().
40  *
41  * All the information is returned in a #GstDiscovererInfo structure.
42  */
43
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif
47
48 #include <gst/video/video.h>
49 #include <gst/audio/audio.h>
50
51 #include <string.h>
52
53 #include "pbutils.h"
54 #include "pbutils-private.h"
55
56 /* For g_stat () */
57 #include <glib/gstdio.h>
58
59 GST_DEBUG_CATEGORY_STATIC (discoverer_debug);
60 #define GST_CAT_DEFAULT discoverer_debug
61 #define CACHE_DIRNAME "discoverer"
62
63 static GQuark _CAPS_QUARK;
64 static GQuark _TAGS_QUARK;
65 static GQuark _ELEMENT_SRCPAD_QUARK;
66 static GQuark _TOC_QUARK;
67 static GQuark _STREAM_ID_QUARK;
68 static GQuark _MISSING_PLUGIN_QUARK;
69 static GQuark _STREAM_TOPOLOGY_QUARK;
70 static GQuark _TOPOLOGY_PAD_QUARK;
71
72
73 typedef struct
74 {
75   GstDiscoverer *dc;
76   GstPad *pad;
77   GstElement *queue;
78   GstElement *sink;
79   GstTagList *tags;
80   GstToc *toc;
81   gchar *stream_id;
82   gulong probe_id;
83 } PrivateStream;
84
85 struct _GstDiscovererPrivate
86 {
87   gboolean async;
88
89   /* allowed time to discover each uri in nanoseconds */
90   GstClockTime timeout;
91
92   /* list of pending URI to process (current excluded) */
93   GList *pending_uris;
94
95   GMutex lock;
96   /* TRUE if cleaning up discoverer */
97   gboolean cleanup;
98
99   /* TRUE if processing a URI */
100   gboolean processing;
101
102   /* TRUE if discoverer has been started */
103   gboolean running;
104
105   /* current items */
106   GstDiscovererInfo *current_info;
107   GError *current_error;
108   GstStructure *current_topology;
109
110   GstTagList *all_tags;
111   GstTagList *global_tags;
112
113   /* List of private streams */
114   GList *streams;
115
116   /* List of these sinks and their handler IDs (to remove the probe) */
117   guint pending_subtitle_pads;
118
119   /* Whether we received no_more_pads */
120   gboolean no_more_pads;
121
122   GstState target_state;
123   GstState current_state;
124
125   /* Global elements */
126   GstBin *pipeline;
127   GstElement *uridecodebin;
128   GstBus *bus;
129
130   /* Custom main context variables */
131   GMainContext *ctx;
132   GSource *bus_source;
133   GSource *timeout_source;
134
135   /* reusable queries */
136   GstQuery *seeking_query;
137
138   /* Handler ids for various callbacks */
139   gulong pad_added_id;
140   gulong pad_remove_id;
141   gulong no_more_pads_id;
142   gulong source_chg_id;
143   gulong bus_cb_id;
144
145   gboolean use_cache;
146 };
147
148 #define DISCO_LOCK(dc) g_mutex_lock (&dc->priv->lock);
149 #define DISCO_UNLOCK(dc) g_mutex_unlock (&dc->priv->lock);
150
151 static void
152 _do_init (void)
153 {
154   GST_DEBUG_CATEGORY_INIT (discoverer_debug, "discoverer", 0, "Discoverer");
155
156   _CAPS_QUARK = g_quark_from_static_string ("caps");
157   _ELEMENT_SRCPAD_QUARK = g_quark_from_static_string ("element-srcpad");
158   _TAGS_QUARK = g_quark_from_static_string ("tags");
159   _TOC_QUARK = g_quark_from_static_string ("toc");
160   _STREAM_ID_QUARK = g_quark_from_static_string ("stream-id");
161   _MISSING_PLUGIN_QUARK = g_quark_from_static_string ("missing-plugin");
162   _STREAM_TOPOLOGY_QUARK = g_quark_from_static_string ("stream-topology");
163   _TOPOLOGY_PAD_QUARK = g_quark_from_static_string ("pad");
164 };
165
166 G_DEFINE_TYPE_EXTENDED (GstDiscoverer, gst_discoverer, G_TYPE_OBJECT, 0,
167     G_ADD_PRIVATE (GstDiscoverer) _do_init ());
168
169 enum
170 {
171   SIGNAL_FINISHED,
172   SIGNAL_STARTING,
173   SIGNAL_DISCOVERED,
174   SIGNAL_SOURCE_SETUP,
175   LAST_SIGNAL
176 };
177
178 #define DEFAULT_PROP_TIMEOUT 15 * GST_SECOND
179 #define DEFAULT_PROP_USE_CACHE FALSE
180
181 enum
182 {
183   PROP_0,
184   PROP_TIMEOUT,
185   PROP_USE_CACHE
186 };
187
188 static guint gst_discoverer_signals[LAST_SIGNAL] = { 0 };
189
190 static void gst_discoverer_set_timeout (GstDiscoverer * dc,
191     GstClockTime timeout);
192 static gboolean async_timeout_cb (GstDiscoverer * dc);
193
194 static void discoverer_bus_cb (GstBus * bus, GstMessage * msg,
195     GstDiscoverer * dc);
196 static void uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad,
197     GstDiscoverer * dc);
198 static void uridecodebin_pad_removed_cb (GstElement * uridecodebin,
199     GstPad * pad, GstDiscoverer * dc);
200 static void uridecodebin_no_more_pads_cb (GstElement * uridecodebin,
201     GstDiscoverer * dc);
202 static void uridecodebin_source_changed_cb (GstElement * uridecodebin,
203     GParamSpec * pspec, GstDiscoverer * dc);
204
205 static void gst_discoverer_dispose (GObject * dc);
206 static void gst_discoverer_finalize (GObject * dc);
207 static void gst_discoverer_set_property (GObject * object, guint prop_id,
208     const GValue * value, GParamSpec * pspec);
209 static void gst_discoverer_get_property (GObject * object, guint prop_id,
210     GValue * value, GParamSpec * pspec);
211 static gboolean _setup_locked (GstDiscoverer * dc);
212 static void handle_current_async (GstDiscoverer * dc);
213 static gboolean emit_discovererd_and_next (GstDiscoverer * dc);
214 static GVariant *gst_discoverer_info_to_variant_recurse (GstDiscovererStreamInfo
215     * sinfo, GstDiscovererSerializeFlags flags);
216 static GstDiscovererStreamInfo *_parse_discovery (GVariant * variant,
217     GstDiscovererInfo * info);
218
219 static void
220 gst_discoverer_class_init (GstDiscovererClass * klass)
221 {
222   GObjectClass *gobject_class = (GObjectClass *) klass;
223
224   gobject_class->dispose = gst_discoverer_dispose;
225   gobject_class->finalize = gst_discoverer_finalize;
226
227   gobject_class->set_property = gst_discoverer_set_property;
228   gobject_class->get_property = gst_discoverer_get_property;
229
230
231   /* properties */
232   /**
233    * GstDiscoverer:timeout:
234    *
235    * The duration (in nanoseconds) after which the discovery of an individual
236    * URI will timeout.
237    *
238    * If the discovery of a URI times out, the %GST_DISCOVERER_TIMEOUT will be
239    * set on the result flags.
240    */
241   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
242       g_param_spec_uint64 ("timeout", "timeout", "Timeout",
243           GST_SECOND, 3600 * GST_SECOND, DEFAULT_PROP_TIMEOUT,
244           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
245
246   /**
247    * GstDiscoverer::use-cache:
248    *
249    * Whether to use a serialized version of the discoverer info from our
250    * own cache if accessible. This allows the discovery to be much faster
251    * as when using this option, we do not need to create a #GstPipeline
252    * and run it, but instead, just reload the #GstDiscovererInfo in its
253    * serialized form.
254    *
255    * The cache files are saved in `$XDG_CACHE_DIR/gstreamer-1.0/discoverer/`.
256    *
257    * Since: 1.16
258    */
259   g_object_class_install_property (gobject_class, PROP_USE_CACHE,
260       g_param_spec_boolean ("use-cache", "use cache", "Use cache",
261           DEFAULT_PROP_USE_CACHE,
262           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
263
264   /* signals */
265   /**
266    * GstDiscoverer::finished:
267    * @discoverer: the #GstDiscoverer
268    *
269    * Will be emitted in async mode when all pending URIs have been processed.
270    */
271   gst_discoverer_signals[SIGNAL_FINISHED] =
272       g_signal_new ("finished", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
273       G_STRUCT_OFFSET (GstDiscovererClass, finished), NULL, NULL, NULL,
274       G_TYPE_NONE, 0, G_TYPE_NONE);
275
276   /**
277    * GstDiscoverer::starting:
278    * @discoverer: the #GstDiscoverer
279    *
280    * Will be emitted when the discover starts analyzing the pending URIs
281    */
282   gst_discoverer_signals[SIGNAL_STARTING] =
283       g_signal_new ("starting", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
284       G_STRUCT_OFFSET (GstDiscovererClass, starting), NULL, NULL, NULL,
285       G_TYPE_NONE, 0, G_TYPE_NONE);
286
287   /**
288    * GstDiscoverer::discovered:
289    * @discoverer: the #GstDiscoverer
290    * @info: the results #GstDiscovererInfo
291    * @error: (allow-none) (type GLib.Error): #GError, which will be non-NULL
292    *                                         if an error occurred during
293    *                                         discovery. You must not free
294    *                                         this #GError, it will be freed by
295    *                                         the discoverer.
296    *
297    * Will be emitted in async mode when all information on a URI could be
298    * discovered, or an error occurred.
299    *
300    * When an error occurs, @info might still contain some partial information,
301    * depending on the circumstances of the error.
302    */
303   gst_discoverer_signals[SIGNAL_DISCOVERED] =
304       g_signal_new ("discovered", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
305       G_STRUCT_OFFSET (GstDiscovererClass, discovered), NULL, NULL, NULL,
306       G_TYPE_NONE, 2, GST_TYPE_DISCOVERER_INFO,
307       G_TYPE_ERROR | G_SIGNAL_TYPE_STATIC_SCOPE);
308
309   /**
310    * GstDiscoverer::source-setup:
311    * @discoverer: the #GstDiscoverer
312    * @source: source element
313    *
314    * This signal is emitted after the source element has been created for, so
315    * the URI being discovered, so it can be configured by setting additional
316    * properties (e.g. set a proxy server for an http source, or set the device
317    * and read speed for an audio cd source).
318    *
319    * This signal is usually emitted from the context of a GStreamer streaming
320    * thread.
321    */
322   gst_discoverer_signals[SIGNAL_SOURCE_SETUP] =
323       g_signal_new ("source-setup", G_TYPE_FROM_CLASS (klass),
324       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDiscovererClass, source_setup),
325       NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
326 }
327
328 static void
329 gst_discoverer_init (GstDiscoverer * dc)
330 {
331   GstFormat format = GST_FORMAT_TIME;
332
333   dc->priv = gst_discoverer_get_instance_private (dc);
334
335   dc->priv->timeout = DEFAULT_PROP_TIMEOUT;
336   dc->priv->use_cache = DEFAULT_PROP_USE_CACHE;
337   dc->priv->async = FALSE;
338
339   g_mutex_init (&dc->priv->lock);
340
341   dc->priv->pending_subtitle_pads = 0;
342
343   dc->priv->current_state = GST_STATE_NULL;
344   dc->priv->target_state = GST_STATE_NULL;
345   dc->priv->no_more_pads = FALSE;
346
347   dc->priv->all_tags = NULL;
348   dc->priv->global_tags = NULL;
349
350   GST_LOG ("Creating pipeline");
351   dc->priv->pipeline = (GstBin *) gst_pipeline_new ("Discoverer");
352   GST_LOG_OBJECT (dc, "Creating uridecodebin");
353   dc->priv->uridecodebin =
354       gst_element_factory_make ("uridecodebin", "discoverer-uri");
355   if (G_UNLIKELY (dc->priv->uridecodebin == NULL)) {
356     GST_ERROR ("Can't create uridecodebin");
357     return;
358   }
359
360   g_object_set (dc->priv->uridecodebin, "post-stream-topology", TRUE, NULL);
361
362   GST_LOG_OBJECT (dc, "Adding uridecodebin to pipeline");
363   gst_bin_add (dc->priv->pipeline, dc->priv->uridecodebin);
364
365   dc->priv->pad_added_id =
366       g_signal_connect_object (dc->priv->uridecodebin, "pad-added",
367       G_CALLBACK (uridecodebin_pad_added_cb), dc, 0);
368   dc->priv->pad_remove_id =
369       g_signal_connect_object (dc->priv->uridecodebin, "pad-removed",
370       G_CALLBACK (uridecodebin_pad_removed_cb), dc, 0);
371   dc->priv->no_more_pads_id =
372       g_signal_connect_object (dc->priv->uridecodebin, "no-more-pads",
373       G_CALLBACK (uridecodebin_no_more_pads_cb), dc, 0);
374   dc->priv->source_chg_id =
375       g_signal_connect_object (dc->priv->uridecodebin, "notify::source",
376       G_CALLBACK (uridecodebin_source_changed_cb), dc, 0);
377
378   GST_LOG_OBJECT (dc, "Getting pipeline bus");
379   dc->priv->bus = gst_pipeline_get_bus ((GstPipeline *) dc->priv->pipeline);
380
381   dc->priv->bus_cb_id =
382       g_signal_connect_object (dc->priv->bus, "message",
383       G_CALLBACK (discoverer_bus_cb), dc, 0);
384
385   GST_DEBUG_OBJECT (dc, "Done initializing Discoverer");
386
387   /* create queries */
388   dc->priv->seeking_query = gst_query_new_seeking (format);
389 }
390
391 static void
392 discoverer_reset (GstDiscoverer * dc)
393 {
394   GST_DEBUG_OBJECT (dc, "Resetting");
395
396   if (dc->priv->pending_uris) {
397     g_list_foreach (dc->priv->pending_uris, (GFunc) g_free, NULL);
398     g_list_free (dc->priv->pending_uris);
399     dc->priv->pending_uris = NULL;
400   }
401
402   if (dc->priv->pipeline)
403     gst_element_set_state ((GstElement *) dc->priv->pipeline, GST_STATE_NULL);
404 }
405
406 #define DISCONNECT_SIGNAL(o,i) G_STMT_START{           \
407   if ((i) && g_signal_handler_is_connected ((o), (i))) \
408     g_signal_handler_disconnect ((o), (i));            \
409   (i) = 0;                                             \
410 }G_STMT_END
411
412 static void
413 gst_discoverer_dispose (GObject * obj)
414 {
415   GstDiscoverer *dc = (GstDiscoverer *) obj;
416
417   GST_DEBUG_OBJECT (dc, "Disposing");
418
419   discoverer_reset (dc);
420
421   if (G_LIKELY (dc->priv->pipeline)) {
422     /* Workaround for bug #118536 */
423     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->pad_added_id);
424     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->pad_remove_id);
425     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->no_more_pads_id);
426     DISCONNECT_SIGNAL (dc->priv->uridecodebin, dc->priv->source_chg_id);
427     DISCONNECT_SIGNAL (dc->priv->bus, dc->priv->bus_cb_id);
428
429     /* pipeline was set to NULL in _reset */
430     gst_object_unref (dc->priv->pipeline);
431     if (dc->priv->bus)
432       gst_object_unref (dc->priv->bus);
433
434     dc->priv->pipeline = NULL;
435     dc->priv->uridecodebin = NULL;
436     dc->priv->bus = NULL;
437   }
438
439   gst_discoverer_stop (dc);
440
441   if (dc->priv->seeking_query) {
442     gst_query_unref (dc->priv->seeking_query);
443     dc->priv->seeking_query = NULL;
444   }
445
446   G_OBJECT_CLASS (gst_discoverer_parent_class)->dispose (obj);
447 }
448
449 static void
450 gst_discoverer_finalize (GObject * obj)
451 {
452   GstDiscoverer *dc = (GstDiscoverer *) obj;
453
454   g_mutex_clear (&dc->priv->lock);
455
456   G_OBJECT_CLASS (gst_discoverer_parent_class)->finalize (obj);
457 }
458
459 static void
460 gst_discoverer_set_property (GObject * object, guint prop_id,
461     const GValue * value, GParamSpec * pspec)
462 {
463   GstDiscoverer *dc = (GstDiscoverer *) object;
464
465   switch (prop_id) {
466     case PROP_TIMEOUT:
467       gst_discoverer_set_timeout (dc, g_value_get_uint64 (value));
468       break;
469     case PROP_USE_CACHE:
470       DISCO_LOCK (dc);
471       dc->priv->use_cache = g_value_get_boolean (value);
472       DISCO_UNLOCK (dc);
473       break;
474     default:
475       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
476       break;
477   }
478 }
479
480 static void
481 gst_discoverer_get_property (GObject * object, guint prop_id,
482     GValue * value, GParamSpec * pspec)
483 {
484   GstDiscoverer *dc = (GstDiscoverer *) object;
485
486   switch (prop_id) {
487     case PROP_TIMEOUT:
488       DISCO_LOCK (dc);
489       g_value_set_uint64 (value, dc->priv->timeout);
490       DISCO_UNLOCK (dc);
491       break;
492     case PROP_USE_CACHE:
493       DISCO_LOCK (dc);
494       g_value_set_boolean (value, dc->priv->use_cache);
495       DISCO_UNLOCK (dc);
496       break;
497     default:
498       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
499       break;
500   }
501 }
502
503 static void
504 gst_discoverer_set_timeout (GstDiscoverer * dc, GstClockTime timeout)
505 {
506   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (timeout));
507
508   GST_DEBUG_OBJECT (dc, "timeout : %" GST_TIME_FORMAT, GST_TIME_ARGS (timeout));
509
510   /* FIXME : update current pending timeout if we're running */
511   DISCO_LOCK (dc);
512   dc->priv->timeout = timeout;
513   DISCO_UNLOCK (dc);
514 }
515
516 static GstPadProbeReturn
517 _event_probe (GstPad * pad, GstPadProbeInfo * info, PrivateStream * ps)
518 {
519   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
520
521   switch (GST_EVENT_TYPE (event)) {
522     case GST_EVENT_TOC:{
523       GstToc *tmp;
524
525       gst_event_parse_toc (event, &tmp, NULL);
526       GST_DEBUG_OBJECT (pad, "toc %" GST_PTR_FORMAT, tmp);
527       DISCO_LOCK (ps->dc);
528       ps->toc = tmp;
529       if (G_LIKELY (ps->dc->priv->processing)) {
530         GST_DEBUG_OBJECT (pad, "private stream %p toc %" GST_PTR_FORMAT, ps,
531             tmp);
532       } else
533         GST_DEBUG_OBJECT (pad, "Dropping toc since preroll is done");
534       DISCO_UNLOCK (ps->dc);
535       break;
536     }
537     case GST_EVENT_STREAM_START:{
538       const gchar *stream_id;
539
540       gst_event_parse_stream_start (event, &stream_id);
541
542       g_free (ps->stream_id);
543       ps->stream_id = stream_id ? g_strdup (stream_id) : NULL;
544       break;
545     }
546     default:
547       break;
548   }
549
550   return GST_PAD_PROBE_OK;
551 }
552
553 static GstStaticCaps subtitle_caps =
554     GST_STATIC_CAPS
555     ("application/x-ssa; application/x-ass; application/x-kate");
556
557 static gboolean
558 is_subtitle_caps (const GstCaps * caps)
559 {
560   GstCaps *subs_caps;
561   GstStructure *s;
562   const gchar *name;
563   gboolean ret;
564
565   s = gst_caps_get_structure (caps, 0);
566   if (!s)
567     return FALSE;
568
569   name = gst_structure_get_name (s);
570   if (g_str_has_prefix (name, "text/") ||
571       g_str_has_prefix (name, "subpicture/") ||
572       g_str_has_prefix (name, "subtitle/") ||
573       g_str_has_prefix (name, "closedcaption/") ||
574       g_str_has_prefix (name, "application/x-subtitle"))
575     return TRUE;
576
577   subs_caps = gst_static_caps_get (&subtitle_caps);
578   ret = gst_caps_can_intersect (caps, subs_caps);
579   gst_caps_unref (subs_caps);
580
581   return ret;
582 }
583
584 static GstPadProbeReturn
585 got_subtitle_data (GstPad * pad, GstPadProbeInfo * info, GstDiscoverer * dc)
586 {
587   GstMessage *msg;
588
589   if (!(GST_IS_BUFFER (info->data) || (GST_IS_EVENT (info->data)
590               && (GST_EVENT_TYPE ((GstEvent *) info->data) == GST_EVENT_GAP
591                   || GST_EVENT_TYPE ((GstEvent *) info->data) ==
592                   GST_EVENT_EOS))))
593     return GST_PAD_PROBE_OK;
594
595
596   DISCO_LOCK (dc);
597
598   dc->priv->pending_subtitle_pads--;
599
600   msg = gst_message_new_application (NULL,
601       gst_structure_new_empty ("DiscovererDone"));
602   gst_element_post_message ((GstElement *) dc->priv->pipeline, msg);
603
604   DISCO_UNLOCK (dc);
605
606   return GST_PAD_PROBE_REMOVE;
607
608 }
609
610 static void
611 uridecodebin_source_changed_cb (GstElement * uridecodebin,
612     GParamSpec * pspec, GstDiscoverer * dc)
613 {
614   GstElement *src;
615   /* get a handle to the source */
616   g_object_get (uridecodebin, pspec->name, &src, NULL);
617
618   GST_DEBUG_OBJECT (dc, "got a new source %p", src);
619
620   g_signal_emit (dc, gst_discoverer_signals[SIGNAL_SOURCE_SETUP], 0, src);
621   gst_object_unref (src);
622 }
623
624 static void
625 uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad,
626     GstDiscoverer * dc)
627 {
628   PrivateStream *ps;
629   GstPad *sinkpad = NULL;
630   GstCaps *caps;
631   gchar *padname;
632   gchar *tmpname;
633
634   GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
635
636   DISCO_LOCK (dc);
637   if (dc->priv->cleanup) {
638     GST_WARNING_OBJECT (dc, "Cleanup, not adding pad");
639     DISCO_UNLOCK (dc);
640     return;
641   }
642   if (dc->priv->current_error) {
643     GST_WARNING_OBJECT (dc, "Ongoing error, not adding more pads");
644     DISCO_UNLOCK (dc);
645     return;
646   }
647   ps = g_slice_new0 (PrivateStream);
648
649   ps->dc = dc;
650   ps->pad = pad;
651   padname = gst_pad_get_name (pad);
652   tmpname = g_strdup_printf ("discoverer-queue-%s", padname);
653   ps->queue = gst_element_factory_make ("queue", tmpname);
654   g_free (tmpname);
655   tmpname = g_strdup_printf ("discoverer-sink-%s", padname);
656   ps->sink = gst_element_factory_make ("fakesink", tmpname);
657   g_free (tmpname);
658   g_free (padname);
659
660   if (G_UNLIKELY (ps->queue == NULL || ps->sink == NULL))
661     goto error;
662
663   g_object_set (ps->sink, "silent", TRUE, NULL);
664   g_object_set (ps->queue, "max-size-buffers", 1, "silent", TRUE, NULL);
665
666   sinkpad = gst_element_get_static_pad (ps->queue, "sink");
667   if (sinkpad == NULL)
668     goto error;
669
670   caps = gst_pad_get_current_caps (pad);
671   if (!caps) {
672     GST_WARNING ("Couldn't get negotiated caps from %s:%s",
673         GST_DEBUG_PAD_NAME (pad));
674     caps = gst_pad_query_caps (pad, NULL);
675   }
676
677   if (caps && !gst_caps_is_empty (caps) && !gst_caps_is_any (caps)
678       && is_subtitle_caps (caps)) {
679     /* Subtitle streams are sparse and may not provide any information - don't
680      * wait for data to preroll */
681     ps->probe_id =
682         gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM,
683         (GstPadProbeCallback) got_subtitle_data, dc, NULL);
684     g_object_set (ps->sink, "async", FALSE, NULL);
685     dc->priv->pending_subtitle_pads++;
686   }
687
688   if (caps)
689     gst_caps_unref (caps);
690
691   gst_bin_add_many (dc->priv->pipeline, ps->queue, ps->sink, NULL);
692
693   if (!gst_element_link_pads_full (ps->queue, "src", ps->sink, "sink",
694           GST_PAD_LINK_CHECK_NOTHING))
695     goto error;
696   if (!gst_element_sync_state_with_parent (ps->sink))
697     goto error;
698   if (!gst_element_sync_state_with_parent (ps->queue))
699     goto error;
700
701   if (gst_pad_link_full (pad, sinkpad,
702           GST_PAD_LINK_CHECK_NOTHING) != GST_PAD_LINK_OK)
703     goto error;
704   gst_object_unref (sinkpad);
705
706   /* Add an event probe */
707   gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
708       (GstPadProbeCallback) _event_probe, ps, NULL);
709
710   dc->priv->streams = g_list_append (dc->priv->streams, ps);
711   DISCO_UNLOCK (dc);
712
713   GST_DEBUG_OBJECT (dc, "Done handling pad");
714
715   return;
716
717 error:
718   GST_ERROR_OBJECT (dc, "Error while handling pad");
719   if (sinkpad)
720     gst_object_unref (sinkpad);
721   if (ps->queue)
722     gst_object_unref (ps->queue);
723   if (ps->sink)
724     gst_object_unref (ps->sink);
725   g_slice_free (PrivateStream, ps);
726   DISCO_UNLOCK (dc);
727   return;
728 }
729
730 static void
731 uridecodebin_no_more_pads_cb (GstElement * uridecodebin, GstDiscoverer * dc)
732 {
733   GstMessage *msg = gst_message_new_application (NULL,
734       gst_structure_new_empty ("DiscovererDone"));
735
736   DISCO_LOCK (dc);
737   dc->priv->no_more_pads = TRUE;
738   gst_element_post_message ((GstElement *) dc->priv->pipeline, msg);
739   DISCO_UNLOCK (dc);
740 }
741
742 static void
743 uridecodebin_pad_removed_cb (GstElement * uridecodebin, GstPad * pad,
744     GstDiscoverer * dc)
745 {
746   GList *tmp;
747   PrivateStream *ps;
748   GstPad *sinkpad;
749
750   GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
751
752   /* Find the PrivateStream */
753   DISCO_LOCK (dc);
754   for (tmp = dc->priv->streams; tmp; tmp = tmp->next) {
755     ps = (PrivateStream *) tmp->data;
756     if (ps->pad == pad)
757       break;
758   }
759
760   if (tmp == NULL) {
761     DISCO_UNLOCK (dc);
762     GST_DEBUG ("The removed pad wasn't controlled by us !");
763     return;
764   }
765
766   if (ps->probe_id)
767     gst_pad_remove_probe (pad, ps->probe_id);
768
769   dc->priv->streams = g_list_delete_link (dc->priv->streams, tmp);
770
771   gst_element_set_state (ps->sink, GST_STATE_NULL);
772   gst_element_set_state (ps->queue, GST_STATE_NULL);
773   gst_element_unlink (ps->queue, ps->sink);
774
775   sinkpad = gst_element_get_static_pad (ps->queue, "sink");
776   gst_pad_unlink (pad, sinkpad);
777   gst_object_unref (sinkpad);
778
779   /* references removed here */
780   gst_bin_remove_many (dc->priv->pipeline, ps->sink, ps->queue, NULL);
781
782   DISCO_UNLOCK (dc);
783   if (ps->tags) {
784     gst_tag_list_unref (ps->tags);
785   }
786   if (ps->toc) {
787     gst_toc_unref (ps->toc);
788   }
789   g_free (ps->stream_id);
790
791   g_slice_free (PrivateStream, ps);
792
793   GST_DEBUG ("Done handling pad");
794 }
795
796 static GstStructure *
797 collect_stream_information (GstDiscoverer * dc, PrivateStream * ps, guint idx)
798 {
799   GstCaps *caps;
800   GstStructure *st;
801   gchar *stname;
802
803   stname = g_strdup_printf ("stream-%02d", idx);
804   st = gst_structure_new_empty (stname);
805   g_free (stname);
806
807   /* Get caps */
808   caps = gst_pad_get_current_caps (ps->pad);
809   if (!caps) {
810     GST_WARNING ("Couldn't get negotiated caps from %s:%s",
811         GST_DEBUG_PAD_NAME (ps->pad));
812     caps = gst_pad_query_caps (ps->pad, NULL);
813   }
814   if (caps) {
815     GST_DEBUG ("stream-%02d, got caps %" GST_PTR_FORMAT, idx, caps);
816     gst_structure_id_set (st, _CAPS_QUARK, GST_TYPE_CAPS, caps, NULL);
817     gst_caps_unref (caps);
818   }
819   if (ps->tags)
820     gst_structure_id_set (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, ps->tags, NULL);
821   if (ps->toc)
822     gst_structure_id_set (st, _TOC_QUARK, GST_TYPE_TOC, ps->toc, NULL);
823   if (ps->stream_id)
824     gst_structure_id_set (st, _STREAM_ID_QUARK, G_TYPE_STRING, ps->stream_id,
825         NULL);
826
827   return st;
828 }
829
830 /* takes ownership of new_tags, may replace *taglist with a new one */
831 static void
832 gst_discoverer_merge_and_replace_tags (GstTagList ** taglist,
833     GstTagList * new_tags)
834 {
835   if (new_tags == NULL)
836     return;
837
838   if (*taglist == NULL) {
839     *taglist = new_tags;
840     return;
841   }
842
843   gst_tag_list_insert (*taglist, new_tags, GST_TAG_MERGE_REPLACE);
844   gst_tag_list_unref (new_tags);
845 }
846
847 static void
848 collect_common_information (GstDiscovererStreamInfo * info,
849     const GstStructure * st)
850 {
851   if (gst_structure_id_has_field (st, _TOC_QUARK)) {
852     gst_structure_id_get (st, _TOC_QUARK, GST_TYPE_TOC, &info->toc, NULL);
853   }
854
855   if (gst_structure_id_has_field (st, _STREAM_ID_QUARK)) {
856     gst_structure_id_get (st, _STREAM_ID_QUARK, G_TYPE_STRING, &info->stream_id,
857         NULL);
858   }
859 }
860
861 static GstDiscovererStreamInfo *
862 make_info (GstDiscovererStreamInfo * parent, GType type, GstCaps * caps)
863 {
864   GstDiscovererStreamInfo *info;
865
866   if (parent)
867     info = gst_discoverer_stream_info_ref (parent);
868   else {
869     info = g_object_new (type, NULL);
870     if (caps)
871       info->caps = gst_caps_ref (caps);
872   }
873   return info;
874 }
875
876 /* Parses a set of caps and tags in st and populates a GstDiscovererStreamInfo
877  * structure (parent, if !NULL, otherwise it allocates one)
878  */
879 static GstDiscovererStreamInfo *
880 collect_information (GstDiscoverer * dc, const GstStructure * st,
881     GstDiscovererStreamInfo * parent)
882 {
883   GstPad *srcpad;
884   GstCaps *caps = NULL;
885   GstStructure *caps_st;
886   GstTagList *tags_st;
887   const gchar *name;
888   gint tmp, tmp2;
889   guint utmp;
890
891   if (!st || (!gst_structure_id_has_field (st, _CAPS_QUARK)
892           && !gst_structure_id_has_field (st, _ELEMENT_SRCPAD_QUARK))) {
893     GST_WARNING ("Couldn't find caps !");
894     return make_info (parent, GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
895   }
896
897   if (gst_structure_id_get (st, _ELEMENT_SRCPAD_QUARK, GST_TYPE_PAD, &srcpad,
898           NULL)) {
899     caps = gst_pad_get_current_caps (srcpad);
900     gst_object_unref (srcpad);
901   }
902   if (!caps) {
903     gst_structure_id_get (st, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL);
904   }
905
906   if (!caps || gst_caps_is_empty (caps) || gst_caps_is_any (caps)) {
907     GST_WARNING ("Couldn't find caps !");
908     if (caps)
909       gst_caps_unref (caps);
910     return make_info (parent, GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
911   }
912
913   caps_st = gst_caps_get_structure (caps, 0);
914   name = gst_structure_get_name (caps_st);
915
916   if (g_str_has_prefix (name, "audio/")) {
917     GstDiscovererAudioInfo *info;
918     const gchar *format_str;
919     guint64 channel_mask;
920
921     info = (GstDiscovererAudioInfo *) make_info (parent,
922         GST_TYPE_DISCOVERER_AUDIO_INFO, caps);
923
924     if (gst_structure_get_int (caps_st, "rate", &tmp))
925       info->sample_rate = (guint) tmp;
926
927     if (gst_structure_get_int (caps_st, "channels", &tmp))
928       info->channels = (guint) tmp;
929
930     if (gst_structure_get (caps_st, "channel-mask", GST_TYPE_BITMASK,
931             &channel_mask, NULL)) {
932       info->channel_mask = channel_mask;
933     } else if (info->channels) {
934       info->channel_mask = gst_audio_channel_get_fallback_mask (info->channels);
935     }
936
937     /* FIXME: we only want to extract depth if raw audio is what's in the
938      * container (i.e. not if there is a decoder involved) */
939     format_str = gst_structure_get_string (caps_st, "format");
940     if (format_str != NULL) {
941       const GstAudioFormatInfo *finfo;
942       GstAudioFormat format;
943
944       format = gst_audio_format_from_string (format_str);
945       finfo = gst_audio_format_get_info (format);
946       if (finfo)
947         info->depth = GST_AUDIO_FORMAT_INFO_DEPTH (finfo);
948     }
949
950     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
951       gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st, NULL);
952       if (gst_tag_list_get_uint (tags_st, GST_TAG_BITRATE, &utmp) ||
953           gst_tag_list_get_uint (tags_st, GST_TAG_NOMINAL_BITRATE, &utmp))
954         info->bitrate = utmp;
955
956       if (gst_tag_list_get_uint (tags_st, GST_TAG_MAXIMUM_BITRATE, &utmp))
957         info->max_bitrate = utmp;
958
959       /* FIXME: Is it worth it to remove the tags we've parsed? */
960       gst_discoverer_merge_and_replace_tags (&info->parent.tags, tags_st);
961     }
962
963     collect_common_information (&info->parent, st);
964
965     if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) {
966       gchar *language;
967       if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags,
968               GST_TAG_LANGUAGE_CODE, &language)) {
969         info->language = language;
970       }
971     }
972
973     gst_caps_unref (caps);
974     return (GstDiscovererStreamInfo *) info;
975
976   } else if (g_str_has_prefix (name, "video/") ||
977       g_str_has_prefix (name, "image/")) {
978     GstDiscovererVideoInfo *info;
979     const gchar *caps_str;
980
981     info = (GstDiscovererVideoInfo *) make_info (parent,
982         GST_TYPE_DISCOVERER_VIDEO_INFO, caps);
983
984     if (gst_structure_get_int (caps_st, "width", &tmp))
985       info->width = (guint) tmp;
986     if (gst_structure_get_int (caps_st, "height", &tmp))
987       info->height = (guint) tmp;
988
989     if (gst_structure_get_fraction (caps_st, "framerate", &tmp, &tmp2)) {
990       info->framerate_num = (guint) tmp;
991       info->framerate_denom = (guint) tmp2;
992     } else {
993       info->framerate_num = 0;
994       info->framerate_denom = 1;
995     }
996
997     if (gst_structure_get_fraction (caps_st, "pixel-aspect-ratio", &tmp, &tmp2)) {
998       info->par_num = (guint) tmp;
999       info->par_denom = (guint) tmp2;
1000     } else {
1001       info->par_num = 1;
1002       info->par_denom = 1;
1003     }
1004
1005     /* FIXME: we only want to extract depth if raw video is what's in the
1006      * container (i.e. not if there is a decoder involved) */
1007     caps_str = gst_structure_get_string (caps_st, "format");
1008     if (caps_str != NULL) {
1009       const GstVideoFormatInfo *finfo;
1010       GstVideoFormat format;
1011
1012       format = gst_video_format_from_string (caps_str);
1013       finfo = gst_video_format_get_info (format);
1014       if (finfo)
1015         info->depth = finfo->bits * finfo->n_components;
1016     }
1017
1018     caps_str = gst_structure_get_string (caps_st, "interlace-mode");
1019     if (!caps_str || strcmp (caps_str, "progressive") == 0)
1020       info->interlaced = FALSE;
1021     else
1022       info->interlaced = TRUE;
1023
1024     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
1025       gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st, NULL);
1026       if (gst_tag_list_get_uint (tags_st, GST_TAG_BITRATE, &utmp) ||
1027           gst_tag_list_get_uint (tags_st, GST_TAG_NOMINAL_BITRATE, &utmp))
1028         info->bitrate = utmp;
1029
1030       if (gst_tag_list_get_uint (tags_st, GST_TAG_MAXIMUM_BITRATE, &utmp))
1031         info->max_bitrate = utmp;
1032
1033       /* FIXME: Is it worth it to remove the tags we've parsed? */
1034       gst_discoverer_merge_and_replace_tags (&info->parent.tags, tags_st);
1035     }
1036
1037     collect_common_information (&info->parent, st);
1038
1039     gst_caps_unref (caps);
1040     return (GstDiscovererStreamInfo *) info;
1041
1042   } else if (is_subtitle_caps (caps)) {
1043     GstDiscovererSubtitleInfo *info;
1044
1045     info = (GstDiscovererSubtitleInfo *) make_info (parent,
1046         GST_TYPE_DISCOVERER_SUBTITLE_INFO, caps);
1047
1048     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
1049       const gchar *language;
1050
1051       gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st, NULL);
1052
1053       language = gst_structure_get_string (caps_st, GST_TAG_LANGUAGE_CODE);
1054       if (language)
1055         info->language = g_strdup (language);
1056
1057       /* FIXME: Is it worth it to remove the tags we've parsed? */
1058       gst_discoverer_merge_and_replace_tags (&info->parent.tags, tags_st);
1059     }
1060
1061     collect_common_information (&info->parent, st);
1062
1063     if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) {
1064       gchar *language;
1065       if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags,
1066               GST_TAG_LANGUAGE_CODE, &language)) {
1067         info->language = language;
1068       }
1069     }
1070
1071     gst_caps_unref (caps);
1072     return (GstDiscovererStreamInfo *) info;
1073
1074   } else {
1075     /* None of the above - populate what information we can */
1076     GstDiscovererStreamInfo *info;
1077
1078     info = make_info (parent, GST_TYPE_DISCOVERER_STREAM_INFO, caps);
1079
1080     if (gst_structure_id_get (st, _TAGS_QUARK, GST_TYPE_TAG_LIST, &tags_st,
1081             NULL)) {
1082       gst_discoverer_merge_and_replace_tags (&info->tags, tags_st);
1083     }
1084
1085     collect_common_information (info, st);
1086
1087     gst_caps_unref (caps);
1088     return info;
1089   }
1090
1091 }
1092
1093 static GstStructure *
1094 find_stream_for_node (GstDiscoverer * dc, const GstStructure * topology)
1095 {
1096   GstPad *pad;
1097   GstPad *target_pad = NULL;
1098   GstStructure *st = NULL;
1099   PrivateStream *ps;
1100   guint i;
1101   GList *tmp;
1102
1103   if (!dc->priv->streams) {
1104     return NULL;
1105   }
1106
1107   if (!gst_structure_id_has_field (topology, _TOPOLOGY_PAD_QUARK)) {
1108     GST_DEBUG ("Could not find pad for node %" GST_PTR_FORMAT, topology);
1109     return NULL;
1110   }
1111
1112   gst_structure_id_get (topology, _TOPOLOGY_PAD_QUARK,
1113       GST_TYPE_PAD, &pad, NULL);
1114
1115   for (i = 0, tmp = dc->priv->streams; tmp; tmp = tmp->next, i++) {
1116     ps = (PrivateStream *) tmp->data;
1117
1118     target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ps->pad));
1119     if (target_pad == NULL)
1120       continue;
1121     gst_object_unref (target_pad);
1122
1123     if (target_pad == pad)
1124       break;
1125   }
1126
1127   if (tmp)
1128     st = collect_stream_information (dc, ps, i);
1129
1130   gst_object_unref (pad);
1131
1132   return st;
1133 }
1134
1135 /* this can fail due to {framed,parsed}={TRUE,FALSE} differences, thus we filter
1136  * the parent */
1137 static gboolean
1138 child_is_same_stream (const GstCaps * _parent, const GstCaps * child)
1139 {
1140   GstCaps *parent;
1141   gboolean res;
1142
1143   if (_parent == child)
1144     return TRUE;
1145   if (!_parent)
1146     return FALSE;
1147   if (!child)
1148     return FALSE;
1149
1150   parent = copy_and_clean_caps (_parent);
1151   res = gst_caps_can_intersect (parent, child);
1152   gst_caps_unref (parent);
1153   return res;
1154 }
1155
1156
1157 static gboolean
1158 child_is_raw_stream (const GstCaps * parent, const GstCaps * child)
1159 {
1160   const GstStructure *st1, *st2;
1161   const gchar *name1, *name2;
1162
1163   if (parent == child)
1164     return TRUE;
1165   if (!parent)
1166     return FALSE;
1167   if (!child)
1168     return FALSE;
1169
1170   st1 = gst_caps_get_structure (parent, 0);
1171   name1 = gst_structure_get_name (st1);
1172   st2 = gst_caps_get_structure (child, 0);
1173   name2 = gst_structure_get_name (st2);
1174
1175   if ((g_str_has_prefix (name1, "audio/") &&
1176           g_str_has_prefix (name2, "audio/x-raw")) ||
1177       ((g_str_has_prefix (name1, "video/") ||
1178               g_str_has_prefix (name1, "image/")) &&
1179           g_str_has_prefix (name2, "video/x-raw"))) {
1180     /* child is the "raw" sub-stream corresponding to parent */
1181     return TRUE;
1182   }
1183
1184   if (is_subtitle_caps (parent))
1185     return TRUE;
1186
1187   return FALSE;
1188 }
1189
1190 /* If a parent is non-NULL, collected stream information will be appended to it
1191  * (and where the information exists, it will be overridden)
1192  */
1193 static GstDiscovererStreamInfo *
1194 parse_stream_topology (GstDiscoverer * dc, const GstStructure * topology,
1195     GstDiscovererStreamInfo * parent)
1196 {
1197   GstDiscovererStreamInfo *res = NULL;
1198   GstCaps *caps = NULL;
1199   const GValue *nval = NULL;
1200
1201   GST_DEBUG ("parsing: %" GST_PTR_FORMAT, topology);
1202
1203   nval = gst_structure_get_value (topology, "next");
1204
1205   if (nval == NULL || GST_VALUE_HOLDS_STRUCTURE (nval)) {
1206     GstStructure *st = find_stream_for_node (dc, topology);
1207     gboolean add_to_list = TRUE;
1208
1209     if (st) {
1210       res = collect_information (dc, st, parent);
1211       gst_structure_free (st);
1212     } else {
1213       /* Didn't find a stream structure, so let's just use the caps we have */
1214       res = collect_information (dc, topology, parent);
1215     }
1216
1217     if (nval == NULL) {
1218       /* FIXME : aggregate with information from main streams */
1219       GST_DEBUG ("Couldn't find 'next' ! might be the last entry");
1220     } else {
1221       GstPad *srcpad;
1222
1223       st = (GstStructure *) gst_value_get_structure (nval);
1224
1225       GST_DEBUG ("next is a structure %" GST_PTR_FORMAT, st);
1226
1227       if (!parent)
1228         parent = res;
1229
1230       if (gst_structure_id_get (st, _ELEMENT_SRCPAD_QUARK, GST_TYPE_PAD,
1231               &srcpad, NULL)) {
1232         caps = gst_pad_get_current_caps (srcpad);
1233         gst_object_unref (srcpad);
1234       }
1235       if (!caps) {
1236         gst_structure_id_get (st, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL);
1237       }
1238
1239       if (caps) {
1240         if (child_is_same_stream (parent->caps, caps)) {
1241           /* We sometimes get an extra sub-stream from the parser. If this is
1242            * the case, we just replace the parent caps with this stream's caps
1243            * since they might contain more information */
1244           gst_caps_replace (&parent->caps, caps);
1245
1246           parse_stream_topology (dc, st, parent);
1247           add_to_list = FALSE;
1248         } else if (child_is_raw_stream (parent->caps, caps)) {
1249           /* This is the "raw" stream corresponding to the parent. This
1250            * contains more information than the parent, tags etc. */
1251           parse_stream_topology (dc, st, parent);
1252           add_to_list = FALSE;
1253         } else {
1254           GstDiscovererStreamInfo *next = parse_stream_topology (dc, st, NULL);
1255           res->next = next;
1256           next->previous = res;
1257         }
1258         gst_caps_unref (caps);
1259       }
1260     }
1261
1262     if (add_to_list) {
1263       res->stream_number = dc->priv->current_info->stream_count++;
1264       dc->priv->current_info->stream_list =
1265           g_list_append (dc->priv->current_info->stream_list, res);
1266     } else {
1267       gst_discoverer_stream_info_unref (res);
1268     }
1269
1270   } else if (GST_VALUE_HOLDS_LIST (nval)) {
1271     guint i, len;
1272     GstDiscovererContainerInfo *cont;
1273     GstPad *srcpad;
1274
1275     if (gst_structure_id_get (topology, _ELEMENT_SRCPAD_QUARK, GST_TYPE_PAD,
1276             &srcpad, NULL)) {
1277       caps = gst_pad_get_current_caps (srcpad);
1278       gst_object_unref (srcpad);
1279     }
1280     if (!caps) {
1281       gst_structure_id_get (topology, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL);
1282     }
1283
1284     if (!caps)
1285       GST_WARNING ("Couldn't find caps !");
1286
1287     len = gst_value_list_get_size (nval);
1288     GST_DEBUG ("next is a list of %d entries", len);
1289
1290     cont = (GstDiscovererContainerInfo *)
1291         g_object_new (GST_TYPE_DISCOVERER_CONTAINER_INFO, NULL);
1292     cont->parent.caps = caps;
1293     if (dc->priv->global_tags)
1294       cont->tags = gst_tag_list_ref (dc->priv->global_tags);
1295     res = (GstDiscovererStreamInfo *) cont;
1296
1297     for (i = 0; i < len; i++) {
1298       const GValue *subv = gst_value_list_get_value (nval, i);
1299       const GstStructure *subst = gst_value_get_structure (subv);
1300       GstDiscovererStreamInfo *substream;
1301
1302       GST_DEBUG ("%d %" GST_PTR_FORMAT, i, subst);
1303
1304       substream = parse_stream_topology (dc, subst, NULL);
1305
1306       substream->previous = res;
1307       cont->streams =
1308           g_list_append (cont->streams,
1309           gst_discoverer_stream_info_ref (substream));
1310     }
1311   }
1312
1313   return res;
1314 }
1315
1316 /* Required DISCO_LOCK to be taken, and will release it */
1317 static void
1318 setup_next_uri_locked (GstDiscoverer * dc)
1319 {
1320   if (dc->priv->pending_uris != NULL) {
1321     gboolean ready = _setup_locked (dc);
1322     DISCO_UNLOCK (dc);
1323
1324     if (!ready) {
1325       /* Start timeout */
1326       handle_current_async (dc);
1327     } else {
1328       g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
1329           (GSourceFunc) emit_discovererd_and_next, gst_object_ref (dc),
1330           gst_object_unref);
1331     }
1332   } else {
1333     /* We're done ! */
1334     DISCO_UNLOCK (dc);
1335     g_signal_emit (dc, gst_discoverer_signals[SIGNAL_FINISHED], 0);
1336   }
1337 }
1338
1339 static GstDiscovererInfo *
1340 _ensure_info_tags (GstDiscoverer * dc)
1341 {
1342   GstDiscovererInfo *info = dc->priv->current_info;
1343
1344   if (dc->priv->all_tags)
1345     info->tags = dc->priv->all_tags;
1346   dc->priv->all_tags = NULL;
1347   return info;
1348 }
1349
1350 static void
1351 emit_discovererd (GstDiscoverer * dc)
1352 {
1353   GstDiscovererInfo *info = _ensure_info_tags (dc);
1354   GST_DEBUG_OBJECT (dc, "Emitting 'discoverered' %s", info->uri);
1355   g_signal_emit (dc, gst_discoverer_signals[SIGNAL_DISCOVERED], 0,
1356       info, dc->priv->current_error);
1357   /* Clients get a copy of current_info since it is a boxed type */
1358   gst_discoverer_info_unref (dc->priv->current_info);
1359   dc->priv->current_info = NULL;
1360 }
1361
1362 static gboolean
1363 emit_discovererd_and_next (GstDiscoverer * dc)
1364 {
1365   emit_discovererd (dc);
1366
1367   DISCO_LOCK (dc);
1368   setup_next_uri_locked (dc);
1369
1370   return G_SOURCE_REMOVE;
1371 }
1372
1373 /* Called when pipeline is pre-rolled */
1374 static void
1375 discoverer_collect (GstDiscoverer * dc)
1376 {
1377   GST_DEBUG ("Collecting information");
1378
1379   /* Stop the timeout handler if present */
1380   if (dc->priv->timeout_source) {
1381     g_source_destroy (dc->priv->timeout_source);
1382     g_source_unref (dc->priv->timeout_source);
1383     dc->priv->timeout_source = NULL;
1384   }
1385
1386   if (dc->priv->use_cache && dc->priv->current_info
1387       && dc->priv->current_info->from_cache) {
1388     GST_DEBUG_OBJECT (dc,
1389         "Nothing to collect as the info was built from" " the cache");
1390     return;
1391   }
1392
1393   if (dc->priv->streams) {
1394     /* FIXME : Make this querying optional */
1395     if (TRUE) {
1396       GstElement *pipeline = (GstElement *) dc->priv->pipeline;
1397       gint64 dur;
1398
1399       GST_DEBUG ("Attempting to query duration");
1400
1401       if (gst_element_query_duration (pipeline, GST_FORMAT_TIME, &dur)) {
1402         GST_DEBUG ("Got duration %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
1403         dc->priv->current_info->duration = (guint64) dur;
1404       } else if (dc->priv->current_info->result != GST_DISCOVERER_ERROR) {
1405         GstStateChangeReturn sret;
1406         /* Note: We don't switch to PLAYING if we previously saw an ERROR since
1407          * the state of various element isn't guaranteed anymore */
1408
1409         /* Some parsers may not even return a rough estimate right away, e.g.
1410          * because they've only processed a single frame so far, so if we
1411          * didn't get a duration the first time, spin a bit and try again.
1412          * Ugly, but still better than making parsers or other elements return
1413          * completely bogus values. We need some API extensions to solve this
1414          * better. */
1415         GST_INFO ("No duration yet, try a bit harder..");
1416         /* Make sure we don't add/remove elements while switching to PLAYING itself */
1417         DISCO_LOCK (dc);
1418         sret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
1419         DISCO_UNLOCK (dc);
1420         if (sret != GST_STATE_CHANGE_FAILURE) {
1421           int i;
1422
1423           for (i = 0; i < 2; ++i) {
1424             g_usleep (G_USEC_PER_SEC / 20);
1425             if (gst_element_query_duration (pipeline, GST_FORMAT_TIME, &dur)
1426                 && dur > 0) {
1427               GST_DEBUG ("Got duration %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
1428               dc->priv->current_info->duration = (guint64) dur;
1429               break;
1430             }
1431           }
1432           gst_element_set_state (pipeline, GST_STATE_PAUSED);
1433         }
1434       }
1435
1436       if (dc->priv->seeking_query) {
1437         if (gst_element_query (pipeline, dc->priv->seeking_query)) {
1438           GstFormat format;
1439           gboolean seekable;
1440
1441           gst_query_parse_seeking (dc->priv->seeking_query, &format,
1442               &seekable, NULL, NULL);
1443           if (format == GST_FORMAT_TIME) {
1444             GST_DEBUG ("Got seekable %d", seekable);
1445             dc->priv->current_info->seekable = seekable;
1446           }
1447         }
1448       }
1449     }
1450
1451     if (dc->priv->target_state == GST_STATE_PAUSED)
1452       dc->priv->current_info->live = FALSE;
1453     else
1454       dc->priv->current_info->live = TRUE;
1455
1456     if (dc->priv->current_topology) {
1457       dc->priv->current_info->stream_count = 1;
1458       dc->priv->current_info->stream_info = parse_stream_topology (dc,
1459           dc->priv->current_topology, NULL);
1460       if (dc->priv->current_info->stream_info)
1461         dc->priv->current_info->stream_info->stream_number = 0;
1462     }
1463
1464     /*
1465      * Images need some special handling. They do not have a duration, have
1466      * caps named image/<foo> (th exception being MJPEG video which is also
1467      * type image/jpeg), and should consist of precisely one stream (actually
1468      * initially there are 2, the image and raw stream, but we squash these
1469      * while parsing the stream topology). At some point, if we find that these
1470      * conditions are not sufficient, we can count the number of decoders and
1471      * parsers in the chain, and if there's more than one decoder, or any
1472      * parser at all, we should not mark this as an image.
1473      */
1474     if (dc->priv->current_info->duration == 0 &&
1475         dc->priv->current_info->stream_info != NULL &&
1476         dc->priv->current_info->stream_info->next == NULL) {
1477       GstDiscovererStreamInfo *stream_info;
1478       GstStructure *st;
1479
1480       stream_info = dc->priv->current_info->stream_info;
1481       st = gst_caps_get_structure (stream_info->caps, 0);
1482
1483       if (g_str_has_prefix (gst_structure_get_name (st), "image/"))
1484         ((GstDiscovererVideoInfo *) stream_info)->is_image = TRUE;
1485     }
1486   }
1487
1488   if (dc->priv->use_cache && dc->priv->current_info->cachefile &&
1489       dc->priv->current_info->result == GST_DISCOVERER_OK) {
1490     GVariant *variant = gst_discoverer_info_to_variant (dc->priv->current_info,
1491         GST_DISCOVERER_SERIALIZE_ALL);
1492
1493     g_file_set_contents (dc->priv->current_info->cachefile,
1494         g_variant_get_data (variant), g_variant_get_size (variant), NULL);
1495     g_variant_unref (variant);
1496   }
1497
1498   if (dc->priv->async)
1499     emit_discovererd (dc);
1500 }
1501
1502 static void
1503 get_async_cb (gpointer cb_data, GSource * source, GSourceFunc * func,
1504     gpointer * data)
1505 {
1506   *func = (GSourceFunc) async_timeout_cb;
1507   *data = cb_data;
1508 }
1509
1510 /* Wrapper since GSourceCallbackFuncs don't expect a return value from ref() */
1511 static void
1512 _void_g_object_ref (gpointer object)
1513 {
1514   g_object_ref (G_OBJECT (object));
1515 }
1516
1517 static void
1518 handle_current_async (GstDiscoverer * dc)
1519 {
1520   GSource *source;
1521   static GSourceCallbackFuncs cb_funcs = {
1522     _void_g_object_ref,
1523     g_object_unref,
1524     get_async_cb,
1525   };
1526
1527   /* Attach a timeout to the main context */
1528   source = g_timeout_source_new (dc->priv->timeout / GST_MSECOND);
1529   g_source_set_callback_indirect (source, g_object_ref (dc), &cb_funcs);
1530   g_source_attach (source, dc->priv->ctx);
1531   dc->priv->timeout_source = source;
1532 }
1533
1534
1535 /* Returns TRUE if processing should stop */
1536 static gboolean
1537 handle_message (GstDiscoverer * dc, GstMessage * msg)
1538 {
1539   gboolean done = FALSE;
1540   const gchar *dump_name = NULL;
1541
1542   GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "got a %s message",
1543       GST_MESSAGE_TYPE_NAME (msg));
1544
1545   switch (GST_MESSAGE_TYPE (msg)) {
1546     case GST_MESSAGE_ERROR:{
1547       GError *gerr;
1548       gchar *debug;
1549
1550       gst_message_parse_error (msg, &gerr, &debug);
1551       GST_WARNING_OBJECT (GST_MESSAGE_SRC (msg),
1552           "Got an error [debug:%s], [message:%s]", debug, gerr->message);
1553       dc->priv->current_error = gerr;
1554       g_free (debug);
1555
1556       /* We need to stop */
1557       done = TRUE;
1558       dump_name = "gst-discoverer-error";
1559
1560       /* Don't override missing plugin result code for missing plugin errors */
1561       if (dc->priv->current_info->result != GST_DISCOVERER_MISSING_PLUGINS ||
1562           (!g_error_matches (gerr, GST_CORE_ERROR,
1563                   GST_CORE_ERROR_MISSING_PLUGIN) &&
1564               !g_error_matches (gerr, GST_STREAM_ERROR,
1565                   GST_STREAM_ERROR_CODEC_NOT_FOUND))) {
1566         GST_DEBUG ("Setting result to ERROR");
1567         dc->priv->current_info->result = GST_DISCOVERER_ERROR;
1568       }
1569     }
1570       break;
1571
1572     case GST_MESSAGE_WARNING:{
1573       GError *err;
1574       gchar *debug = NULL;
1575
1576       gst_message_parse_warning (msg, &err, &debug);
1577       GST_WARNING_OBJECT (GST_MESSAGE_SRC (msg),
1578           "Got a warning [debug:%s], [message:%s]", debug, err->message);
1579       g_clear_error (&err);
1580       g_free (debug);
1581       dump_name = "gst-discoverer-warning";
1582       break;
1583     }
1584
1585     case GST_MESSAGE_EOS:
1586       GST_DEBUG ("Got EOS !");
1587       done = TRUE;
1588       dump_name = "gst-discoverer-eos";
1589       break;
1590
1591     case GST_MESSAGE_APPLICATION:{
1592       const gchar *name =
1593           gst_structure_get_name (gst_message_get_structure (msg));
1594
1595       if (g_strcmp0 (name, "DiscovererDone"))
1596         break;
1597
1598       /* Maybe we already reached the target state, and all we're waiting for
1599        * is either the subtitle tags or no_more_pads
1600        */
1601       DISCO_LOCK (dc);
1602       if (dc->priv->pending_subtitle_pads == 0)
1603         done = dc->priv->no_more_pads
1604             && dc->priv->target_state == dc->priv->current_state;
1605       DISCO_UNLOCK (dc);
1606
1607       if (done)
1608         dump_name = "gst-discoverer-application-message";
1609     }
1610       break;
1611
1612     case GST_MESSAGE_STATE_CHANGED:{
1613       GstState old, new, pending;
1614
1615       gst_message_parse_state_changed (msg, &old, &new, &pending);
1616       if (GST_MESSAGE_SRC (msg) == (GstObject *) dc->priv->pipeline) {
1617         DISCO_LOCK (dc);
1618         dc->priv->current_state = new;
1619
1620         if (dc->priv->pending_subtitle_pads == 0)
1621           done = dc->priv->no_more_pads
1622               && dc->priv->target_state == dc->priv->current_state;
1623         /* Else we should get unblocked in GST_MESSAGE_APPLICATION */
1624
1625         DISCO_UNLOCK (dc);
1626       }
1627
1628       if (done)
1629         dump_name = "gst-discoverer-target-state";
1630     }
1631       break;
1632
1633     case GST_MESSAGE_ELEMENT:
1634     {
1635       GQuark sttype;
1636       const GstStructure *structure;
1637
1638       structure = gst_message_get_structure (msg);
1639       sttype = gst_structure_get_name_id (structure);
1640       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg),
1641           "structure %" GST_PTR_FORMAT, structure);
1642       if (sttype == _MISSING_PLUGIN_QUARK) {
1643         GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg),
1644             "Setting result to MISSING_PLUGINS");
1645         dc->priv->current_info->result = GST_DISCOVERER_MISSING_PLUGINS;
1646         /* FIXME 2.0 Remove completely the ->misc
1647          * Keep the old behaviour for now.
1648          */
1649         if (dc->priv->current_info->misc)
1650           gst_structure_free (dc->priv->current_info->misc);
1651         dc->priv->current_info->misc = gst_structure_copy (structure);
1652         g_ptr_array_add (dc->priv->current_info->missing_elements_details,
1653             gst_missing_plugin_message_get_installer_detail (msg));
1654       } else if (sttype == _STREAM_TOPOLOGY_QUARK) {
1655         if (dc->priv->current_topology)
1656           gst_structure_free (dc->priv->current_topology);
1657         dc->priv->current_topology = gst_structure_copy (structure);
1658       }
1659     }
1660       break;
1661
1662     case GST_MESSAGE_TAG:
1663     {
1664       GstTagList *tl, *tmp = NULL;
1665       GstTagScope scope;
1666
1667       gst_message_parse_tag (msg, &tl);
1668       scope = gst_tag_list_get_scope (tl);
1669       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Got tags %" GST_PTR_FORMAT, tl);
1670
1671       tmp = gst_tag_list_merge (dc->priv->all_tags, tl, GST_TAG_MERGE_APPEND);
1672       if (dc->priv->all_tags)
1673         gst_tag_list_unref (dc->priv->all_tags);
1674       dc->priv->all_tags = tmp;
1675
1676       if (scope == GST_TAG_SCOPE_STREAM) {
1677         for (GList * curr = dc->priv->streams; curr; curr = curr->next) {
1678           PrivateStream *ps = (PrivateStream *) curr->data;
1679           if (GST_MESSAGE_SRC (msg) == GST_OBJECT_CAST (ps->sink)) {
1680             tmp = gst_tag_list_merge (ps->tags, tl, GST_TAG_MERGE_APPEND);
1681             if (ps->tags)
1682               gst_tag_list_unref (ps->tags);
1683             ps->tags = tmp;
1684             GST_DEBUG_OBJECT (ps->pad, "tags %" GST_PTR_FORMAT, ps->tags);
1685             break;
1686           }
1687         }
1688       } else {
1689         tmp =
1690             gst_tag_list_merge (dc->priv->global_tags, tl,
1691             GST_TAG_MERGE_APPEND);
1692         if (dc->priv->global_tags)
1693           gst_tag_list_unref (dc->priv->global_tags);
1694         dc->priv->global_tags = tmp;
1695       }
1696       gst_tag_list_unref (tl);
1697     }
1698       break;
1699     case GST_MESSAGE_TOC:
1700     {
1701       GstToc *tmp;
1702
1703       gst_message_parse_toc (msg, &tmp, NULL);
1704       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Got toc %" GST_PTR_FORMAT, tmp);
1705       if (dc->priv->current_info->toc)
1706         gst_toc_unref (dc->priv->current_info->toc);
1707       dc->priv->current_info->toc = tmp;        /* transfer ownership */
1708       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Current info %p, toc %"
1709           GST_PTR_FORMAT, dc->priv->current_info, tmp);
1710     }
1711       break;
1712
1713     default:
1714       break;
1715   }
1716
1717   if (dump_name != NULL) {
1718     /* dump graph when done or for warnings */
1719     GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (dc->priv->pipeline),
1720         GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
1721   }
1722   return done;
1723 }
1724
1725 static void
1726 handle_current_sync (GstDiscoverer * dc)
1727 {
1728   GTimer *timer;
1729   gdouble deadline = ((gdouble) dc->priv->timeout) / GST_SECOND;
1730   GstMessage *msg;
1731   gboolean done = FALSE;
1732
1733   timer = g_timer_new ();
1734   g_timer_start (timer);
1735
1736   do {
1737     /* poll bus with timeout */
1738     /* FIXME : make the timeout more fine-tuned */
1739     if ((msg = gst_bus_timed_pop (dc->priv->bus, GST_SECOND / 2))) {
1740       done = handle_message (dc, msg);
1741       gst_message_unref (msg);
1742     }
1743   } while (!done && (g_timer_elapsed (timer, NULL) < deadline));
1744
1745   /* return result */
1746   if (!done) {
1747     GST_DEBUG ("we timed out! Setting result to TIMEOUT");
1748     dc->priv->current_info->result = GST_DISCOVERER_TIMEOUT;
1749   }
1750
1751   DISCO_LOCK (dc);
1752   dc->priv->processing = FALSE;
1753   DISCO_UNLOCK (dc);
1754
1755
1756   GST_DEBUG ("Done");
1757
1758   g_timer_stop (timer);
1759   g_timer_destroy (timer);
1760 }
1761
1762 static gchar *
1763 _serialized_info_get_path (GstDiscoverer * dc, gchar * uri)
1764 {
1765   GChecksum *cs = NULL;
1766   GStatBuf file_status;
1767   gchar *location = NULL, *res = NULL, *cache_dir = NULL, *tmp = NULL,
1768       *protocol = gst_uri_get_protocol (uri), hash_dirname[3] = "00";
1769   const gchar *checksum;
1770
1771   if (g_ascii_strcasecmp (protocol, "file") != 0) {
1772     GST_DEBUG_OBJECT (dc, "Can not work with serialized DiscovererInfo"
1773         " on non local files - protocol: %s", protocol);
1774
1775     goto done;
1776   }
1777
1778   location = gst_uri_get_location (uri);
1779   if (g_stat (location, &file_status) < 0) {
1780     GST_DEBUG_OBJECT (dc, "Could not get stat for file: %s", location);
1781
1782     goto done;
1783   }
1784
1785   tmp = g_strdup_printf ("%s-%" G_GSIZE_FORMAT "-%" G_GINT64_FORMAT,
1786       location, (gsize) file_status.st_size, (gint64) file_status.st_mtime);
1787   cs = g_checksum_new (G_CHECKSUM_SHA1);
1788   g_checksum_update (cs, (const guchar *) tmp, strlen (tmp));
1789   checksum = g_checksum_get_string (cs);
1790
1791   hash_dirname[0] = checksum[0];
1792   hash_dirname[1] = checksum[1];
1793   cache_dir =
1794       g_build_filename (g_get_user_cache_dir (), "gstreamer-" GST_API_VERSION,
1795       CACHE_DIRNAME, hash_dirname, NULL);
1796   g_mkdir_with_parents (cache_dir, 0777);
1797
1798   res = g_build_filename (cache_dir, &checksum[2], NULL);
1799
1800 done:
1801   g_checksum_free (cs);
1802   g_free (cache_dir);
1803   g_free (location);
1804   g_free (tmp);
1805   g_free (protocol);
1806
1807   return res;
1808 }
1809
1810 static GstDiscovererInfo *
1811 _get_info_from_cachefile (GstDiscoverer * dc, gchar * cachefile)
1812 {
1813   gchar *data;
1814   gsize length;
1815
1816   if (g_file_get_contents (cachefile, &data, &length, NULL)) {
1817     GstDiscovererInfo *info = NULL;
1818     GVariant *variant =
1819         g_variant_new_from_data (G_VARIANT_TYPE ("v"), data, length,
1820         TRUE, NULL, NULL);
1821
1822     info = gst_discoverer_info_from_variant (variant);
1823     g_variant_unref (variant);
1824
1825     if (info) {
1826       info->cachefile = cachefile;
1827       info->from_cache = (gpointer) 0x01;
1828     }
1829
1830     GST_INFO_OBJECT (dc, "Got info from cache: %p", info);
1831     g_free (data);
1832
1833     return info;
1834   }
1835
1836   return NULL;
1837 }
1838
1839 static gboolean
1840 _setup_locked (GstDiscoverer * dc)
1841 {
1842   GstStateChangeReturn ret;
1843   gchar *uri = (gchar *) dc->priv->pending_uris->data;
1844   gchar *cachefile = NULL;
1845
1846   dc->priv->pending_uris =
1847       g_list_delete_link (dc->priv->pending_uris, dc->priv->pending_uris);
1848
1849   if (dc->priv->use_cache) {
1850     cachefile = _serialized_info_get_path (dc, uri);
1851     if (cachefile)
1852       dc->priv->current_info = _get_info_from_cachefile (dc, cachefile);
1853
1854     if (dc->priv->current_info) {
1855       /* Make sure the URI is exactly what the user passed in */
1856       g_free (dc->priv->current_info->uri);
1857       dc->priv->current_info->uri = uri;
1858
1859       dc->priv->current_info->cachefile = cachefile;
1860       dc->priv->processing = FALSE;
1861       dc->priv->target_state = GST_STATE_NULL;
1862
1863       return TRUE;
1864     }
1865   }
1866
1867   GST_DEBUG ("Setting up");
1868
1869   /* Pop URI off the pending URI list */
1870   dc->priv->current_info =
1871       (GstDiscovererInfo *) g_object_new (GST_TYPE_DISCOVERER_INFO, NULL);
1872   dc->priv->current_info->cachefile = cachefile;
1873   dc->priv->current_info->uri = uri;
1874
1875   /* set uri on uridecodebin */
1876   g_object_set (dc->priv->uridecodebin, "uri", dc->priv->current_info->uri,
1877       NULL);
1878
1879   GST_DEBUG ("Current is now %s", dc->priv->current_info->uri);
1880
1881   dc->priv->processing = TRUE;
1882
1883   dc->priv->target_state = GST_STATE_PAUSED;
1884
1885   /* set pipeline to PAUSED */
1886   DISCO_UNLOCK (dc);
1887   GST_DEBUG ("Setting pipeline to PAUSED");
1888   ret =
1889       gst_element_set_state ((GstElement *) dc->priv->pipeline,
1890       dc->priv->target_state);
1891
1892   if (ret == GST_STATE_CHANGE_NO_PREROLL) {
1893     GST_DEBUG ("Source is live, switching to PLAYING");
1894     dc->priv->target_state = GST_STATE_PLAYING;
1895     ret =
1896         gst_element_set_state ((GstElement *) dc->priv->pipeline,
1897         dc->priv->target_state);
1898   }
1899   DISCO_LOCK (dc);
1900
1901
1902   GST_DEBUG_OBJECT (dc, "Pipeline going to PAUSED : %s",
1903       gst_element_state_change_return_get_name (ret));
1904
1905   return FALSE;
1906 }
1907
1908 static void
1909 discoverer_cleanup (GstDiscoverer * dc)
1910 {
1911   GST_DEBUG ("Cleaning up");
1912
1913   DISCO_LOCK (dc);
1914   dc->priv->cleanup = TRUE;
1915   DISCO_UNLOCK (dc);
1916
1917   gst_bus_set_flushing (dc->priv->bus, TRUE);
1918
1919   DISCO_LOCK (dc);
1920   if (dc->priv->current_error) {
1921     g_error_free (dc->priv->current_error);
1922     DISCO_UNLOCK (dc);
1923     gst_element_set_state ((GstElement *) dc->priv->pipeline, GST_STATE_NULL);
1924   } else {
1925     DISCO_UNLOCK (dc);
1926   }
1927
1928   gst_element_set_state ((GstElement *) dc->priv->pipeline, GST_STATE_READY);
1929   gst_bus_set_flushing (dc->priv->bus, FALSE);
1930
1931   DISCO_LOCK (dc);
1932   dc->priv->current_error = NULL;
1933   if (dc->priv->current_topology) {
1934     gst_structure_free (dc->priv->current_topology);
1935     dc->priv->current_topology = NULL;
1936   }
1937
1938   dc->priv->current_info = NULL;
1939
1940   if (dc->priv->all_tags) {
1941     gst_tag_list_unref (dc->priv->all_tags);
1942     dc->priv->all_tags = NULL;
1943   }
1944
1945   if (dc->priv->global_tags) {
1946     gst_tag_list_unref (dc->priv->global_tags);
1947     dc->priv->global_tags = NULL;
1948   }
1949
1950   dc->priv->pending_subtitle_pads = 0;
1951
1952   dc->priv->current_state = GST_STATE_NULL;
1953   dc->priv->target_state = GST_STATE_NULL;
1954   dc->priv->no_more_pads = FALSE;
1955   dc->priv->cleanup = FALSE;
1956
1957
1958   /* Try popping the next uri */
1959   if (dc->priv->async) {
1960     setup_next_uri_locked (dc);
1961   } else
1962     DISCO_UNLOCK (dc);
1963
1964   GST_DEBUG ("out");
1965 }
1966
1967 static void
1968 discoverer_bus_cb (GstBus * bus, GstMessage * msg, GstDiscoverer * dc)
1969 {
1970   if (dc->priv->processing) {
1971     if (handle_message (dc, msg)) {
1972       GST_DEBUG ("Stopping asynchronously");
1973       /* Serialise with _event_probe() */
1974       DISCO_LOCK (dc);
1975       dc->priv->processing = FALSE;
1976       DISCO_UNLOCK (dc);
1977       discoverer_collect (dc);
1978       discoverer_cleanup (dc);
1979     }
1980   }
1981 }
1982
1983 static gboolean
1984 async_timeout_cb (GstDiscoverer * dc)
1985 {
1986   if (!g_source_is_destroyed (g_main_current_source ())) {
1987     GST_DEBUG ("Setting result to TIMEOUT");
1988     dc->priv->current_info->result = GST_DISCOVERER_TIMEOUT;
1989     dc->priv->processing = FALSE;
1990     discoverer_collect (dc);
1991     discoverer_cleanup (dc);
1992   }
1993   return FALSE;
1994 }
1995
1996 /* If there is a pending URI, it will pop it from the list of pending
1997  * URIs and start the discovery on it.
1998  *
1999  * Returns GST_DISCOVERER_OK if the next URI was popped and is processing,
2000  * else a error flag.
2001  */
2002 static GstDiscovererResult
2003 start_discovering (GstDiscoverer * dc)
2004 {
2005   gboolean ready;
2006   GstDiscovererResult res = GST_DISCOVERER_OK;
2007
2008   GST_DEBUG ("Starting");
2009
2010   DISCO_LOCK (dc);
2011   if (dc->priv->pending_uris == NULL) {
2012     GST_WARNING ("No URI to process");
2013     res = GST_DISCOVERER_URI_INVALID;
2014     DISCO_UNLOCK (dc);
2015     goto beach;
2016   }
2017
2018   if (dc->priv->current_info != NULL) {
2019     GST_WARNING ("Already processing a file");
2020     res = GST_DISCOVERER_BUSY;
2021     DISCO_UNLOCK (dc);
2022     goto beach;
2023   }
2024
2025   g_signal_emit (dc, gst_discoverer_signals[SIGNAL_STARTING], 0);
2026
2027   ready = _setup_locked (dc);
2028
2029   DISCO_UNLOCK (dc);
2030
2031   if (dc->priv->async) {
2032     if (ready) {
2033       GSource *source;
2034
2035       source = g_idle_source_new ();
2036       g_source_set_callback (source,
2037           (GSourceFunc) emit_discovererd_and_next, gst_object_ref (dc),
2038           gst_object_unref);
2039       g_source_attach (source, dc->priv->ctx);
2040       goto beach;
2041     }
2042
2043     handle_current_async (dc);
2044   } else {
2045     if (!ready)
2046       handle_current_sync (dc);
2047   }
2048
2049 beach:
2050   return res;
2051 }
2052
2053 /* Serializing code */
2054
2055 static GVariant *
2056 _serialize_common_stream_info (GstDiscovererStreamInfo * sinfo,
2057     GstDiscovererSerializeFlags flags)
2058 {
2059   GVariant *common;
2060   GVariant *nextv = NULL;
2061   gchar *caps_str = NULL, *tags_str = NULL, *misc_str = NULL;
2062
2063   if (sinfo->caps && (flags & GST_DISCOVERER_SERIALIZE_CAPS))
2064     caps_str = gst_caps_to_string (sinfo->caps);
2065
2066   if (sinfo->tags && (flags & GST_DISCOVERER_SERIALIZE_TAGS))
2067     tags_str = gst_tag_list_to_string (sinfo->tags);
2068
2069   if (sinfo->misc && (flags & GST_DISCOVERER_SERIALIZE_MISC))
2070     misc_str = gst_structure_to_string (sinfo->misc);
2071
2072
2073   if (sinfo->next)
2074     nextv = gst_discoverer_info_to_variant_recurse (sinfo->next, flags);
2075   else
2076     nextv = g_variant_new ("()");
2077
2078   common =
2079       g_variant_new ("(msmsmsmsv)", sinfo->stream_id, caps_str, tags_str,
2080       misc_str, nextv);
2081
2082   g_free (caps_str);
2083   g_free (tags_str);
2084   g_free (misc_str);
2085
2086   return common;
2087 }
2088
2089 static GVariant *
2090 _serialize_info (GstDiscovererInfo * info, GstDiscovererSerializeFlags flags)
2091 {
2092   gchar *tags_str = NULL;
2093   GVariant *ret;
2094
2095   if (info->tags && (flags & GST_DISCOVERER_SERIALIZE_TAGS))
2096     tags_str = gst_tag_list_to_string (info->tags);
2097
2098   ret =
2099       g_variant_new ("(mstbmsb)", info->uri, info->duration, info->seekable,
2100       tags_str, info->live);
2101
2102   g_free (tags_str);
2103
2104   return ret;
2105 }
2106
2107 static GVariant *
2108 _serialize_audio_stream_info (GstDiscovererAudioInfo * ainfo)
2109 {
2110   return g_variant_new ("(uuuuumst)",
2111       ainfo->channels,
2112       ainfo->sample_rate,
2113       ainfo->bitrate, ainfo->max_bitrate, ainfo->depth, ainfo->language,
2114       ainfo->channel_mask);
2115 }
2116
2117 static GVariant *
2118 _serialize_video_stream_info (GstDiscovererVideoInfo * vinfo)
2119 {
2120   return g_variant_new ("(uuuuuuubuub)",
2121       vinfo->width,
2122       vinfo->height,
2123       vinfo->depth,
2124       vinfo->framerate_num,
2125       vinfo->framerate_denom,
2126       vinfo->par_num,
2127       vinfo->par_denom,
2128       vinfo->interlaced, vinfo->bitrate, vinfo->max_bitrate, vinfo->is_image);
2129 }
2130
2131 static GVariant *
2132 _serialize_subtitle_stream_info (GstDiscovererSubtitleInfo * sinfo)
2133 {
2134   return g_variant_new ("ms", sinfo->language);
2135 }
2136
2137 static GVariant *
2138 gst_discoverer_info_to_variant_recurse (GstDiscovererStreamInfo * sinfo,
2139     GstDiscovererSerializeFlags flags)
2140 {
2141   GVariant *stream_variant = NULL;
2142   GVariant *common_stream_variant =
2143       _serialize_common_stream_info (sinfo, flags);
2144
2145   if (GST_IS_DISCOVERER_CONTAINER_INFO (sinfo)) {
2146     GList *tmp;
2147     GList *streams =
2148         gst_discoverer_container_info_get_streams (GST_DISCOVERER_CONTAINER_INFO
2149         (sinfo));
2150
2151     if (g_list_length (streams) > 0) {
2152       GVariantBuilder children;
2153       GVariant *child_variant;
2154       g_variant_builder_init (&children, G_VARIANT_TYPE_ARRAY);
2155
2156       for (tmp = streams; tmp; tmp = tmp->next) {
2157         child_variant =
2158             gst_discoverer_info_to_variant_recurse (tmp->data, flags);
2159         g_variant_builder_add (&children, "v", child_variant);
2160       }
2161       stream_variant =
2162           g_variant_new ("(yvav)", 'c', common_stream_variant, &children);
2163     } else {
2164       stream_variant =
2165           g_variant_new ("(yvav)", 'c', common_stream_variant, NULL);
2166     }
2167
2168     gst_discoverer_stream_info_list_free (streams);
2169   } else if (GST_IS_DISCOVERER_AUDIO_INFO (sinfo)) {
2170     GVariant *audio_stream_info =
2171         _serialize_audio_stream_info (GST_DISCOVERER_AUDIO_INFO (sinfo));
2172     stream_variant =
2173         g_variant_new ("(yvv)", 'a', common_stream_variant, audio_stream_info);
2174   } else if (GST_IS_DISCOVERER_VIDEO_INFO (sinfo)) {
2175     GVariant *video_stream_info =
2176         _serialize_video_stream_info (GST_DISCOVERER_VIDEO_INFO (sinfo));
2177     stream_variant =
2178         g_variant_new ("(yvv)", 'v', common_stream_variant, video_stream_info);
2179   } else if (GST_IS_DISCOVERER_SUBTITLE_INFO (sinfo)) {
2180     GVariant *subtitle_stream_info =
2181         _serialize_subtitle_stream_info (GST_DISCOVERER_SUBTITLE_INFO (sinfo));
2182     stream_variant =
2183         g_variant_new ("(yvv)", 's', common_stream_variant,
2184         subtitle_stream_info);
2185   } else {
2186     GVariant *nextv = NULL;
2187     GstDiscovererStreamInfo *ninfo =
2188         gst_discoverer_stream_info_get_next (sinfo);
2189
2190     nextv = gst_discoverer_info_to_variant_recurse (ninfo, flags);
2191
2192     stream_variant =
2193         g_variant_new ("(yvv)", 'n', common_stream_variant,
2194         g_variant_new ("v", nextv));
2195   }
2196
2197   return stream_variant;
2198 }
2199
2200 /* Parsing code */
2201
2202 #define GET_FROM_TUPLE(v, t, n, val) G_STMT_START{         \
2203   GVariant *child = g_variant_get_child_value (v, n); \
2204   *val = g_variant_get_##t(child); \
2205   g_variant_unref (child); \
2206 }G_STMT_END
2207
2208 static const gchar *
2209 _maybe_get_string_from_tuple (GVariant * tuple, guint index)
2210 {
2211   const gchar *ret = NULL;
2212   GVariant *maybe;
2213   GET_FROM_TUPLE (tuple, maybe, index, &maybe);
2214   if (maybe) {
2215     ret = g_variant_get_string (maybe, NULL);
2216     g_variant_unref (maybe);
2217   }
2218
2219   return ret;
2220 }
2221
2222 static void
2223 _parse_info (GstDiscovererInfo * info, GVariant * info_variant)
2224 {
2225   const gchar *str;
2226
2227   str = _maybe_get_string_from_tuple (info_variant, 0);
2228   if (str)
2229     info->uri = g_strdup (str);
2230
2231   GET_FROM_TUPLE (info_variant, uint64, 1, &info->duration);
2232   GET_FROM_TUPLE (info_variant, boolean, 2, &info->seekable);
2233
2234   str = _maybe_get_string_from_tuple (info_variant, 3);
2235   if (str)
2236     info->tags = gst_tag_list_new_from_string (str);
2237
2238   GET_FROM_TUPLE (info_variant, boolean, 4, &info->live);
2239 }
2240
2241 static void
2242 _parse_common_stream_info (GstDiscovererStreamInfo * sinfo, GVariant * common,
2243     GstDiscovererInfo * info)
2244 {
2245   const gchar *str;
2246
2247   str = _maybe_get_string_from_tuple (common, 0);
2248   if (str)
2249     sinfo->stream_id = g_strdup (str);
2250
2251   str = _maybe_get_string_from_tuple (common, 1);
2252   if (str)
2253     sinfo->caps = gst_caps_from_string (str);
2254
2255   str = _maybe_get_string_from_tuple (common, 2);
2256   if (str)
2257     sinfo->tags = gst_tag_list_new_from_string (str);
2258
2259   str = _maybe_get_string_from_tuple (common, 3);
2260   if (str)
2261     sinfo->misc = gst_structure_new_from_string (str);
2262
2263   if (g_variant_n_children (common) > 4) {
2264     GVariant *nextv;
2265
2266     GET_FROM_TUPLE (common, variant, 4, &nextv);
2267     if (g_variant_n_children (nextv) > 0) {
2268       sinfo->next = _parse_discovery (nextv, info);
2269     }
2270     g_variant_unref (nextv);
2271   }
2272
2273   g_variant_unref (common);
2274 }
2275
2276 static void
2277 _parse_audio_stream_info (GstDiscovererAudioInfo * ainfo, GVariant * specific)
2278 {
2279   const gchar *str;
2280
2281   GET_FROM_TUPLE (specific, uint32, 0, &ainfo->channels);
2282   GET_FROM_TUPLE (specific, uint32, 1, &ainfo->sample_rate);
2283   GET_FROM_TUPLE (specific, uint32, 2, &ainfo->bitrate);
2284   GET_FROM_TUPLE (specific, uint32, 3, &ainfo->max_bitrate);
2285   GET_FROM_TUPLE (specific, uint32, 4, &ainfo->depth);
2286
2287   str = _maybe_get_string_from_tuple (specific, 5);
2288
2289   if (str)
2290     ainfo->language = g_strdup (str);
2291
2292   GET_FROM_TUPLE (specific, uint64, 6, &ainfo->channel_mask);
2293
2294   g_variant_unref (specific);
2295 }
2296
2297 static void
2298 _parse_video_stream_info (GstDiscovererVideoInfo * vinfo, GVariant * specific)
2299 {
2300   GET_FROM_TUPLE (specific, uint32, 0, &vinfo->width);
2301   GET_FROM_TUPLE (specific, uint32, 1, &vinfo->height);
2302   GET_FROM_TUPLE (specific, uint32, 2, &vinfo->depth);
2303   GET_FROM_TUPLE (specific, uint32, 3, &vinfo->framerate_num);
2304   GET_FROM_TUPLE (specific, uint32, 4, &vinfo->framerate_denom);
2305   GET_FROM_TUPLE (specific, uint32, 5, &vinfo->par_num);
2306   GET_FROM_TUPLE (specific, uint32, 6, &vinfo->par_denom);
2307   GET_FROM_TUPLE (specific, boolean, 7, &vinfo->interlaced);
2308   GET_FROM_TUPLE (specific, uint32, 8, &vinfo->bitrate);
2309   GET_FROM_TUPLE (specific, uint32, 9, &vinfo->max_bitrate);
2310   GET_FROM_TUPLE (specific, boolean, 10, &vinfo->is_image);
2311
2312   g_variant_unref (specific);
2313 }
2314
2315 static void
2316 _parse_subtitle_stream_info (GstDiscovererSubtitleInfo * sinfo,
2317     GVariant * specific)
2318 {
2319   GVariant *maybe;
2320
2321   maybe = g_variant_get_maybe (specific);
2322   if (maybe) {
2323     sinfo->language = g_strdup (g_variant_get_string (maybe, NULL));
2324     g_variant_unref (maybe);
2325   }
2326
2327   g_variant_unref (specific);
2328 }
2329
2330 static GstDiscovererStreamInfo *
2331 _parse_discovery (GVariant * variant, GstDiscovererInfo * info)
2332 {
2333   gchar type;
2334   GVariant *common = g_variant_get_child_value (variant, 1);
2335   GVariant *specific = g_variant_get_child_value (variant, 2);
2336   GstDiscovererStreamInfo *sinfo = NULL;
2337
2338   GET_FROM_TUPLE (variant, byte, 0, &type);
2339   switch (type) {
2340     case 'c':
2341       sinfo = g_object_new (GST_TYPE_DISCOVERER_CONTAINER_INFO, NULL);
2342       break;
2343     case 'a':
2344       sinfo = g_object_new (GST_TYPE_DISCOVERER_AUDIO_INFO, NULL);
2345       _parse_audio_stream_info (GST_DISCOVERER_AUDIO_INFO (sinfo),
2346           g_variant_get_child_value (specific, 0));
2347       break;
2348     case 'v':
2349       sinfo = g_object_new (GST_TYPE_DISCOVERER_VIDEO_INFO, NULL);
2350       _parse_video_stream_info (GST_DISCOVERER_VIDEO_INFO (sinfo),
2351           g_variant_get_child_value (specific, 0));
2352       break;
2353     case 's':
2354       sinfo = g_object_new (GST_TYPE_DISCOVERER_SUBTITLE_INFO, NULL);
2355       _parse_subtitle_stream_info (GST_DISCOVERER_SUBTITLE_INFO (sinfo),
2356           g_variant_get_child_value (specific, 0));
2357       break;
2358     case 'n':
2359       sinfo = g_object_new (GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
2360       break;
2361     default:
2362       GST_WARNING ("Unexpected discoverer info type %d", type);
2363       goto out;
2364   }
2365
2366   _parse_common_stream_info (sinfo, g_variant_get_child_value (common, 0),
2367       info);
2368
2369   if (!GST_IS_DISCOVERER_CONTAINER_INFO (sinfo)) {
2370     info->stream_list = g_list_append (info->stream_list, sinfo);
2371   }
2372
2373   if (!info->stream_info) {
2374     info->stream_info = sinfo;
2375   }
2376
2377   if (GST_IS_DISCOVERER_CONTAINER_INFO (sinfo)) {
2378     GVariantIter iter;
2379     GVariant *child;
2380
2381     GstDiscovererContainerInfo *cinfo = GST_DISCOVERER_CONTAINER_INFO (sinfo);
2382     g_variant_iter_init (&iter, specific);
2383     cinfo->tags = sinfo->tags;
2384     while ((child = g_variant_iter_next_value (&iter))) {
2385       GstDiscovererStreamInfo *child_info;
2386       child_info = _parse_discovery (g_variant_get_variant (child), info);
2387       if (child_info != NULL) {
2388         cinfo->streams =
2389             g_list_append (cinfo->streams,
2390             gst_discoverer_stream_info_ref (child_info));
2391       }
2392       g_variant_unref (child);
2393     }
2394   }
2395
2396 out:
2397
2398   g_variant_unref (common);
2399   g_variant_unref (specific);
2400   g_variant_unref (variant);
2401   return sinfo;
2402 }
2403
2404 /**
2405  * gst_discoverer_start:
2406  * @discoverer: A #GstDiscoverer
2407  *
2408  * Allow asynchronous discovering of URIs to take place.
2409  * A #GMainLoop must be available for #GstDiscoverer to properly work in
2410  * asynchronous mode.
2411  */
2412 void
2413 gst_discoverer_start (GstDiscoverer * discoverer)
2414 {
2415   GSource *source;
2416   GMainContext *ctx = NULL;
2417
2418   g_return_if_fail (GST_IS_DISCOVERER (discoverer));
2419
2420   GST_DEBUG_OBJECT (discoverer, "Starting...");
2421
2422   if (discoverer->priv->async) {
2423     GST_DEBUG_OBJECT (discoverer, "We were already started");
2424     return;
2425   }
2426
2427   discoverer->priv->async = TRUE;
2428   discoverer->priv->running = TRUE;
2429
2430   ctx = g_main_context_get_thread_default ();
2431
2432   /* Connect to bus signals */
2433   if (ctx == NULL)
2434     ctx = g_main_context_default ();
2435
2436   source = gst_bus_create_watch (discoverer->priv->bus);
2437   g_source_set_callback (source, (GSourceFunc) gst_bus_async_signal_func,
2438       NULL, NULL);
2439   g_source_attach (source, ctx);
2440   discoverer->priv->bus_source = source;
2441   discoverer->priv->ctx = g_main_context_ref (ctx);
2442
2443   start_discovering (discoverer);
2444   GST_DEBUG_OBJECT (discoverer, "Started");
2445 }
2446
2447 /**
2448  * gst_discoverer_stop:
2449  * @discoverer: A #GstDiscoverer
2450  *
2451  * Stop the discovery of any pending URIs and clears the list of
2452  * pending URIS (if any).
2453  */
2454 void
2455 gst_discoverer_stop (GstDiscoverer * discoverer)
2456 {
2457   g_return_if_fail (GST_IS_DISCOVERER (discoverer));
2458
2459   GST_DEBUG_OBJECT (discoverer, "Stopping...");
2460
2461   if (!discoverer->priv->async) {
2462     GST_DEBUG_OBJECT (discoverer,
2463         "We were already stopped, or running synchronously");
2464     return;
2465   }
2466
2467   DISCO_LOCK (discoverer);
2468   if (discoverer->priv->processing) {
2469     /* We prevent any further processing by setting the bus to
2470      * flushing and setting the pipeline to READY.
2471      * _reset() will take care of the rest of the cleanup */
2472     if (discoverer->priv->bus)
2473       gst_bus_set_flushing (discoverer->priv->bus, TRUE);
2474     if (discoverer->priv->pipeline)
2475       gst_element_set_state ((GstElement *) discoverer->priv->pipeline,
2476           GST_STATE_READY);
2477   }
2478   discoverer->priv->running = FALSE;
2479   DISCO_UNLOCK (discoverer);
2480
2481   /* Remove timeout handler */
2482   if (discoverer->priv->timeout_source) {
2483     g_source_destroy (discoverer->priv->timeout_source);
2484     g_source_unref (discoverer->priv->timeout_source);
2485     discoverer->priv->timeout_source = NULL;
2486   }
2487   /* Remove signal watch */
2488   if (discoverer->priv->bus_source) {
2489     g_source_destroy (discoverer->priv->bus_source);
2490     g_source_unref (discoverer->priv->bus_source);
2491     discoverer->priv->bus_source = NULL;
2492   }
2493   /* Unref main context */
2494   if (discoverer->priv->ctx) {
2495     g_main_context_unref (discoverer->priv->ctx);
2496     discoverer->priv->ctx = NULL;
2497   }
2498   discoverer_reset (discoverer);
2499
2500   discoverer->priv->async = FALSE;
2501
2502   GST_DEBUG_OBJECT (discoverer, "Stopped");
2503 }
2504
2505 /**
2506  * gst_discoverer_discover_uri_async:
2507  * @discoverer: A #GstDiscoverer
2508  * @uri: the URI to add.
2509  *
2510  * Appends the given @uri to the list of URIs to discoverer. The actual
2511  * discovery of the @uri will only take place if gst_discoverer_start() has
2512  * been called.
2513  *
2514  * A copy of @uri will be made internally, so the caller can safely g_free()
2515  * afterwards.
2516  *
2517  * Returns: %TRUE if the @uri was successfully appended to the list of pending
2518  * uris, else %FALSE
2519  */
2520 gboolean
2521 gst_discoverer_discover_uri_async (GstDiscoverer * discoverer,
2522     const gchar * uri)
2523 {
2524   gboolean can_run;
2525
2526   g_return_val_if_fail (GST_IS_DISCOVERER (discoverer), FALSE);
2527
2528   GST_DEBUG_OBJECT (discoverer, "uri : %s", uri);
2529
2530   DISCO_LOCK (discoverer);
2531   can_run = (discoverer->priv->pending_uris == NULL);
2532   discoverer->priv->pending_uris =
2533       g_list_append (discoverer->priv->pending_uris, g_strdup (uri));
2534   DISCO_UNLOCK (discoverer);
2535
2536   if (can_run)
2537     start_discovering (discoverer);
2538
2539   return TRUE;
2540 }
2541
2542
2543 /* Synchronous mode */
2544 /**
2545  * gst_discoverer_discover_uri:
2546  * @discoverer: A #GstDiscoverer
2547  * @uri: The URI to run on.
2548  * @err: (out) (optional): If an error occurred, this field will be filled in.
2549  *
2550  * Synchronously discovers the given @uri.
2551  *
2552  * A copy of @uri will be made internally, so the caller can safely g_free()
2553  * afterwards.
2554  *
2555  * Returns: (transfer full): the result of the scanning. Can be %NULL if an
2556  * error occurred.
2557  */
2558 GstDiscovererInfo *
2559 gst_discoverer_discover_uri (GstDiscoverer * discoverer, const gchar * uri,
2560     GError ** err)
2561 {
2562   GstDiscovererResult res = 0;
2563   GstDiscovererInfo *info;
2564
2565   g_return_val_if_fail (GST_IS_DISCOVERER (discoverer), NULL);
2566   g_return_val_if_fail (uri, NULL);
2567
2568   GST_DEBUG_OBJECT (discoverer, "uri:%s", uri);
2569
2570   DISCO_LOCK (discoverer);
2571   if (G_UNLIKELY (discoverer->priv->current_info)) {
2572     DISCO_UNLOCK (discoverer);
2573     GST_WARNING_OBJECT (discoverer, "Already handling a uri");
2574     if (err)
2575       *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
2576           "Already handling a uri");
2577     return NULL;
2578   }
2579
2580   discoverer->priv->pending_uris =
2581       g_list_append (discoverer->priv->pending_uris, g_strdup (uri));
2582   DISCO_UNLOCK (discoverer);
2583
2584   res = start_discovering (discoverer);
2585   discoverer_collect (discoverer);
2586
2587   /* Get results */
2588   if (err) {
2589     if (discoverer->priv->current_error)
2590       *err = g_error_copy (discoverer->priv->current_error);
2591     else
2592       *err = NULL;
2593   }
2594   if (res != GST_DISCOVERER_OK) {
2595     GST_DEBUG ("Setting result to %d (was %d)", res,
2596         discoverer->priv->current_info->result);
2597     discoverer->priv->current_info->result = res;
2598   }
2599   info = _ensure_info_tags (discoverer);
2600
2601   discoverer_cleanup (discoverer);
2602
2603   return info;
2604 }
2605
2606 /**
2607  * gst_discoverer_new:
2608  * @timeout: timeout per file, in nanoseconds. Allowed are values between
2609  *     one second (#GST_SECOND) and one hour (3600 * #GST_SECOND)
2610  * @err: (optional): a pointer to a #GError. can be %NULL
2611  *
2612  * Creates a new #GstDiscoverer with the provided timeout.
2613  *
2614  * Returns: (transfer full): The new #GstDiscoverer.
2615  * If an error occurred when creating the discoverer, @err will be set
2616  * accordingly and %NULL will be returned. If @err is set, the caller must
2617  * free it when no longer needed using g_error_free().
2618  */
2619 GstDiscoverer *
2620 gst_discoverer_new (GstClockTime timeout, GError ** err)
2621 {
2622   GstDiscoverer *res;
2623
2624   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (timeout), NULL);
2625
2626   res = g_object_new (GST_TYPE_DISCOVERER, "timeout", timeout, NULL);
2627   if (res->priv->uridecodebin == NULL) {
2628     if (err)
2629       *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN,
2630           "Couldn't create 'uridecodebin' element");
2631     gst_object_unref (res);
2632     res = NULL;
2633   }
2634   return res;
2635 }
2636
2637 /**
2638  * gst_discoverer_info_to_variant:
2639  * @info: A #GstDiscovererInfo
2640  * @flags: A combination of #GstDiscovererSerializeFlags to specify
2641  * what needs to be serialized.
2642  *
2643  * Serializes @info to a #GVariant that can be parsed again
2644  * through gst_discoverer_info_from_variant().
2645  *
2646  * Note that any #GstToc (s) that might have been discovered will not be serialized
2647  * for now.
2648  *
2649  * Returns: (transfer full): A newly-allocated #GVariant representing @info.
2650  *
2651  * Since: 1.6
2652  */
2653 GVariant *
2654 gst_discoverer_info_to_variant (GstDiscovererInfo * info,
2655     GstDiscovererSerializeFlags flags)
2656 {
2657   /* FIXME: implement TOC support */
2658   GVariant *stream_variant;
2659   GVariant *variant, *info_variant;
2660   GstDiscovererStreamInfo *sinfo;
2661   GVariant *wrapper;
2662
2663   g_return_val_if_fail (GST_IS_DISCOVERER_INFO (info), NULL);
2664   g_return_val_if_fail (gst_discoverer_info_get_result (info) ==
2665       GST_DISCOVERER_OK, NULL);
2666
2667   sinfo = gst_discoverer_info_get_stream_info (info);
2668   stream_variant = gst_discoverer_info_to_variant_recurse (sinfo, flags);
2669   info_variant = _serialize_info (info, flags);
2670
2671   variant = g_variant_new ("(vv)", info_variant, stream_variant);
2672
2673   /* Returning a wrapper implies some small overhead, but simplifies
2674    * deserializing from bytes */
2675   wrapper = g_variant_new_variant (variant);
2676
2677   gst_discoverer_stream_info_unref (sinfo);
2678   return wrapper;
2679 }
2680
2681 /**
2682  * gst_discoverer_info_from_variant:
2683  * @variant: A #GVariant to deserialize into a #GstDiscovererInfo.
2684  *
2685  * Parses a #GVariant as produced by gst_discoverer_info_to_variant()
2686  * back to a #GstDiscovererInfo.
2687  *
2688  * Returns: (transfer full): A newly-allocated #GstDiscovererInfo.
2689  *
2690  * Since: 1.6
2691  */
2692 GstDiscovererInfo *
2693 gst_discoverer_info_from_variant (GVariant * variant)
2694 {
2695   GstDiscovererInfo *info = g_object_new (GST_TYPE_DISCOVERER_INFO, NULL);
2696   GVariant *info_variant = g_variant_get_variant (variant);
2697   GVariant *info_specific_variant;
2698   GVariant *wrapped;
2699
2700   GET_FROM_TUPLE (info_variant, variant, 0, &info_specific_variant);
2701   GET_FROM_TUPLE (info_variant, variant, 1, &wrapped);
2702
2703   _parse_info (info, info_specific_variant);
2704   _parse_discovery (wrapped, info);
2705   g_variant_unref (info_specific_variant);
2706   g_variant_unref (info_variant);
2707
2708   return info;
2709 }