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