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