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