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