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