Merge remote-tracking branch 'origin/master' into 0.11
[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 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 decodebin_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->decodebin_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 decodebin so we can quickly detect
294    * when a decodebin 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 ("decodebin", NULL);
300   dc->priv->decodebin_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 GstProbeReturn
414 _event_probe (GstPad * pad, GstProbeType type, GstEvent * event,
415     PrivateStream * ps)
416 {
417   if (GST_EVENT_TYPE (event) == GST_EVENT_TAG) {
418     GstTagList *tl = NULL, *tmp;
419
420     gst_event_parse_tag (event, &tl);
421     GST_DEBUG_OBJECT (pad, "tags %" GST_PTR_FORMAT, tl);
422     DISCO_LOCK (ps->dc);
423     /* If preroll is complete, drop these tags - the collected information is
424      * possibly already being processed and adding more tags would be racy */
425     if (G_LIKELY (ps->dc->priv->processing)) {
426       GST_DEBUG_OBJECT (pad, "private stream %p old tags %" GST_PTR_FORMAT, ps,
427           ps->tags);
428       tmp = gst_tag_list_merge (ps->tags, tl, GST_TAG_MERGE_APPEND);
429       if (ps->tags)
430         gst_tag_list_free (ps->tags);
431       ps->tags = tmp;
432       GST_DEBUG_OBJECT (pad, "private stream %p new tags %" GST_PTR_FORMAT, ps,
433           tmp);
434     } else
435       GST_DEBUG_OBJECT (pad, "Dropping tags since preroll is done");
436     DISCO_UNLOCK (ps->dc);
437   }
438
439   return GST_PROBE_OK;
440 }
441
442 static gboolean
443 is_subtitle_caps (const GstCaps * caps)
444 {
445   static GstCaps *subs_caps = NULL;
446
447   if (!subs_caps) {
448     subs_caps = gst_caps_from_string ("text/plain; text/x-pango-markup; "
449         "subpicture/x-pgs; subpicture/x-dvb; application/x-subtitle-unknown; "
450         "application/x-ssa; application/x-ass; subtitle/x-kate; "
451         "application/x-kate; video/x-dvd-subpicture; ");
452   }
453
454   return gst_caps_can_intersect (caps, subs_caps);
455 }
456
457 static void
458 uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad,
459     GstDiscoverer * dc)
460 {
461   PrivateStream *ps;
462   GstPad *sinkpad = NULL;
463   GstCaps *caps;
464
465   GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
466
467   ps = g_slice_new0 (PrivateStream);
468
469   ps->dc = dc;
470   ps->pad = pad;
471   ps->queue = gst_element_factory_make ("queue", NULL);
472   ps->sink = gst_element_factory_make ("fakesink", NULL);
473
474   if (G_UNLIKELY (ps->queue == NULL || ps->sink == NULL))
475     goto error;
476
477   g_object_set (ps->sink, "silent", TRUE, NULL);
478   g_object_set (ps->queue, "max-size-buffers", 1, "silent", TRUE, NULL);
479
480   caps = gst_pad_get_caps (pad, NULL);
481
482   if (is_subtitle_caps (caps)) {
483     /* Subtitle streams are sparse and may not provide any information - don't
484      * wait for data to preroll */
485     g_object_set (ps->sink, "async", FALSE, NULL);
486   }
487
488   gst_caps_unref (caps);
489
490   gst_bin_add_many (dc->priv->pipeline, ps->queue, ps->sink, NULL);
491
492   if (!gst_element_link_pads_full (ps->queue, "src", ps->sink, "sink",
493           GST_PAD_LINK_CHECK_NOTHING))
494     goto error;
495   if (!gst_element_sync_state_with_parent (ps->sink))
496     goto error;
497   if (!gst_element_sync_state_with_parent (ps->queue))
498     goto error;
499
500   sinkpad = gst_element_get_static_pad (ps->queue, "sink");
501   if (sinkpad == NULL)
502     goto error;
503   if (gst_pad_link_full (pad, sinkpad,
504           GST_PAD_LINK_CHECK_NOTHING) != GST_PAD_LINK_OK)
505     goto error;
506   gst_object_unref (sinkpad);
507
508   /* Add an event probe */
509   gst_pad_add_probe (pad, GST_PROBE_TYPE_EVENT,
510       (GstPadProbeCallback) _event_probe, ps, NULL);
511
512   DISCO_LOCK (dc);
513   dc->priv->streams = g_list_append (dc->priv->streams, ps);
514   DISCO_UNLOCK (dc);
515
516   GST_DEBUG_OBJECT (dc, "Done handling pad");
517
518   return;
519
520 error:
521   GST_ERROR_OBJECT (dc, "Error while handling pad");
522   if (sinkpad)
523     gst_object_unref (sinkpad);
524   if (ps->queue)
525     gst_object_unref (ps->queue);
526   if (ps->sink)
527     gst_object_unref (ps->sink);
528   g_slice_free (PrivateStream, ps);
529   return;
530 }
531
532 static void
533 uridecodebin_pad_removed_cb (GstElement * uridecodebin, GstPad * pad,
534     GstDiscoverer * dc)
535 {
536   GList *tmp;
537   PrivateStream *ps;
538   GstPad *sinkpad;
539
540   GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
541
542   /* Find the PrivateStream */
543   DISCO_LOCK (dc);
544   for (tmp = dc->priv->streams; tmp; tmp = tmp->next) {
545     ps = (PrivateStream *) tmp->data;
546     if (ps->pad == pad)
547       break;
548   }
549
550   if (tmp == NULL) {
551     DISCO_UNLOCK (dc);
552     GST_DEBUG ("The removed pad wasn't controlled by us !");
553     return;
554   }
555
556   dc->priv->streams = g_list_delete_link (dc->priv->streams, tmp);
557   DISCO_UNLOCK (dc);
558
559   gst_element_set_state (ps->sink, GST_STATE_NULL);
560   gst_element_set_state (ps->queue, GST_STATE_NULL);
561   gst_element_unlink (ps->queue, ps->sink);
562
563   sinkpad = gst_element_get_static_pad (ps->queue, "sink");
564   gst_pad_unlink (pad, sinkpad);
565   gst_object_unref (sinkpad);
566
567   /* references removed here */
568   gst_bin_remove_many (dc->priv->pipeline, ps->sink, ps->queue, NULL);
569
570   if (ps->tags) {
571     gst_tag_list_free (ps->tags);
572   }
573
574   g_slice_free (PrivateStream, ps);
575
576   GST_DEBUG ("Done handling pad");
577 }
578
579 static GstStructure *
580 collect_stream_information (GstDiscoverer * dc, PrivateStream * ps, guint idx)
581 {
582   GstCaps *caps;
583   GstStructure *st;
584   gchar *stname;
585
586   stname = g_strdup_printf ("stream-%02d", idx);
587   st = gst_structure_empty_new (stname);
588   g_free (stname);
589
590   /* Get caps */
591   caps = gst_pad_get_current_caps (ps->pad);
592   if (!caps) {
593     GST_WARNING ("Couldn't get negotiated caps from %s:%s",
594         GST_DEBUG_PAD_NAME (ps->pad));
595     caps = gst_pad_get_caps (ps->pad, NULL);
596   }
597   if (caps) {
598     GST_DEBUG ("Got caps %" GST_PTR_FORMAT, caps);
599     gst_structure_id_set (st, _CAPS_QUARK, GST_TYPE_CAPS, caps, NULL);
600
601     gst_caps_unref (caps);
602   }
603   if (ps->tags)
604     gst_structure_id_set (st, _TAGS_QUARK, GST_TYPE_STRUCTURE, ps->tags, NULL);
605
606   return st;
607 }
608
609 /* Parses a set of caps and tags in st and populates a GstDiscovererStreamInfo
610  * structure (parent, if !NULL, otherwise it allocates one)
611  */
612 static GstDiscovererStreamInfo *
613 collect_information (GstDiscoverer * dc, const GstStructure * st,
614     GstDiscovererStreamInfo * parent)
615 {
616   GstCaps *caps;
617   GstStructure *caps_st, *tags_st;
618   const gchar *name;
619   int tmp;
620   guint utmp;
621
622   if (!st || !gst_structure_id_has_field (st, _CAPS_QUARK)) {
623     GST_WARNING ("Couldn't find caps !");
624     if (parent)
625       return parent;
626     else
627       return (GstDiscovererStreamInfo *)
628           g_object_new (GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
629   }
630
631   gst_structure_id_get (st, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL);
632   caps_st = gst_caps_get_structure (caps, 0);
633   name = gst_structure_get_name (caps_st);
634
635   if (g_str_has_prefix (name, "audio/")) {
636     GstDiscovererAudioInfo *info;
637
638     if (parent)
639       info = (GstDiscovererAudioInfo *) parent;
640     else {
641       info = (GstDiscovererAudioInfo *)
642           g_object_new (GST_TYPE_DISCOVERER_AUDIO_INFO, NULL);
643       info->parent.caps = caps;
644     }
645
646     if (gst_structure_get_int (caps_st, "rate", &tmp))
647       info->sample_rate = (guint) tmp;
648
649     if (gst_structure_get_int (caps_st, "channels", &tmp))
650       info->channels = (guint) tmp;
651
652     if (gst_structure_get_int (caps_st, "depth", &tmp))
653       info->depth = (guint) tmp;
654
655     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
656       gst_structure_id_get (st, _TAGS_QUARK,
657           GST_TYPE_STRUCTURE, &tags_st, NULL);
658       if (gst_structure_get_uint (tags_st, GST_TAG_BITRATE, &utmp) ||
659           gst_structure_get_uint (tags_st, GST_TAG_NOMINAL_BITRATE, &utmp))
660         info->bitrate = utmp;
661
662       if (gst_structure_get_uint (tags_st, GST_TAG_MAXIMUM_BITRATE, &utmp))
663         info->max_bitrate = utmp;
664
665       /* FIXME: Is it worth it to remove the tags we've parsed? */
666       info->parent.tags = gst_tag_list_merge (info->parent.tags,
667           (GstTagList *) tags_st, GST_TAG_MERGE_REPLACE);
668
669       gst_structure_free (tags_st);
670     }
671
672     if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) {
673       gchar *language;
674       if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags,
675               GST_TAG_LANGUAGE_CODE, &language)) {
676         info->language = language;
677       }
678     }
679
680     return (GstDiscovererStreamInfo *) info;
681
682   } else if (g_str_has_prefix (name, "video/") ||
683       g_str_has_prefix (name, "image/")) {
684     GstDiscovererVideoInfo *info;
685     GstVideoInfo vinfo;
686
687     if (parent)
688       info = (GstDiscovererVideoInfo *) parent;
689     else {
690       info = (GstDiscovererVideoInfo *)
691           g_object_new (GST_TYPE_DISCOVERER_VIDEO_INFO, NULL);
692       info->parent.caps = caps;
693     }
694
695     /* FIXME : gst_video_info_from_caps only works with raw caps,
696      * wouldn't we want to get all the info below for non-raw caps ? 
697      */
698     if (g_str_has_prefix (name, "video/x-raw") &&
699         gst_video_info_from_caps (&vinfo, caps)) {
700       info->width = (guint) vinfo.width;
701       info->height = (guint) vinfo.height;
702
703       info->depth = (guint) 0;
704
705       info->par_num = vinfo.par_n;
706       info->par_denom = vinfo.par_d;
707
708       info->framerate_num = vinfo.fps_n;
709       info->framerate_denom = vinfo.fps_d;
710
711       info->interlaced = (vinfo.flags & GST_VIDEO_FLAG_INTERLACED) != 0;
712     }
713
714     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
715       gst_structure_id_get (st, _TAGS_QUARK,
716           GST_TYPE_STRUCTURE, &tags_st, NULL);
717       if (gst_structure_get_uint (tags_st, GST_TAG_BITRATE, &utmp) ||
718           gst_structure_get_uint (tags_st, GST_TAG_NOMINAL_BITRATE, &utmp))
719         info->bitrate = utmp;
720
721       if (gst_structure_get_uint (tags_st, GST_TAG_MAXIMUM_BITRATE, &utmp))
722         info->max_bitrate = utmp;
723
724       /* FIXME: Is it worth it to remove the tags we've parsed? */
725       info->parent.tags = gst_tag_list_merge (info->parent.tags,
726           (GstTagList *) tags_st, GST_TAG_MERGE_REPLACE);
727       gst_structure_free (tags_st);
728     }
729
730     return (GstDiscovererStreamInfo *) info;
731
732   } else if (is_subtitle_caps (caps)) {
733     GstDiscovererSubtitleInfo *info;
734
735     if (parent)
736       info = (GstDiscovererSubtitleInfo *) parent;
737     else {
738       info = (GstDiscovererSubtitleInfo *)
739           g_object_new (GST_TYPE_DISCOVERER_SUBTITLE_INFO, NULL);
740       info->parent.caps = caps;
741     }
742
743     if (gst_structure_id_has_field (st, _TAGS_QUARK)) {
744       const gchar *language;
745
746       gst_structure_id_get (st, _TAGS_QUARK,
747           GST_TYPE_STRUCTURE, &tags_st, NULL);
748
749       language = gst_structure_get_string (caps_st, GST_TAG_LANGUAGE_CODE);
750       if (language)
751         info->language = g_strdup (language);
752
753       /* FIXME: Is it worth it to remove the tags we've parsed? */
754       info->parent.tags = gst_tag_list_merge (info->parent.tags,
755           (GstTagList *) tags_st, GST_TAG_MERGE_REPLACE);
756       gst_structure_free (tags_st);
757
758     }
759
760     if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) {
761       gchar *language;
762       if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags,
763               GST_TAG_LANGUAGE_CODE, &language)) {
764         info->language = language;
765       }
766     }
767
768     return (GstDiscovererStreamInfo *) info;
769
770   } else {
771     /* None of the above - populate what information we can */
772     GstDiscovererStreamInfo *info;
773
774     if (parent)
775       info = parent;
776     else {
777       info = (GstDiscovererStreamInfo *)
778           g_object_new (GST_TYPE_DISCOVERER_STREAM_INFO, NULL);
779       info->caps = caps;
780     }
781
782     if (gst_structure_id_get (st, _TAGS_QUARK,
783             GST_TYPE_STRUCTURE, &tags_st, NULL)) {
784       info->tags = gst_tag_list_merge (info->tags, (GstTagList *) tags_st,
785           GST_TAG_MERGE_REPLACE);
786       gst_structure_free (tags_st);
787     }
788
789     return info;
790   }
791
792 }
793
794 static GstStructure *
795 find_stream_for_node (GstDiscoverer * dc, const GstStructure * topology)
796 {
797   GstPad *pad;
798   GstPad *target_pad = NULL;
799   GstStructure *st = NULL;
800   PrivateStream *ps;
801   guint i;
802   GList *tmp;
803
804   if (!gst_structure_id_has_field (topology, _TOPOLOGY_PAD_QUARK)) {
805     GST_DEBUG ("Could not find pad for node %" GST_PTR_FORMAT "\n", topology);
806     return NULL;
807   }
808
809   gst_structure_id_get (topology, _TOPOLOGY_PAD_QUARK,
810       GST_TYPE_PAD, &pad, NULL);
811
812   if (!dc->priv->streams)
813     return NULL;
814
815   for (i = 0, tmp = dc->priv->streams; tmp; tmp = tmp->next, i++) {
816     ps = (PrivateStream *) tmp->data;
817
818     target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ps->pad));
819     gst_object_unref (target_pad);
820
821     if (target_pad == pad)
822       break;
823   }
824
825   if (tmp)
826     st = collect_stream_information (dc, ps, i);
827
828   gst_object_unref (pad);
829
830   return st;
831 }
832
833 static gboolean
834 child_is_raw_stream (GstCaps * parent, GstCaps * child)
835 {
836   GstStructure *st1, *st2;
837   const gchar *name1, *name2;
838
839   st1 = gst_caps_get_structure (parent, 0);
840   name1 = gst_structure_get_name (st1);
841   st2 = gst_caps_get_structure (child, 0);
842   name2 = gst_structure_get_name (st2);
843
844   if ((g_str_has_prefix (name1, "audio/") &&
845           g_str_has_prefix (name2, "audio/x-raw")) ||
846       ((g_str_has_prefix (name1, "video/") ||
847               g_str_has_prefix (name1, "image/")) &&
848           g_str_has_prefix (name2, "video/x-raw"))) {
849     /* child is the "raw" sub-stream corresponding to parent */
850     return TRUE;
851   }
852
853   if (is_subtitle_caps (parent))
854     return TRUE;
855
856   return FALSE;
857 }
858
859 /* If a parent is non-NULL, collected stream information will be appended to it
860  * (and where the information exists, it will be overriden)
861  */
862 static GstDiscovererStreamInfo *
863 parse_stream_topology (GstDiscoverer * dc, const GstStructure * topology,
864     GstDiscovererStreamInfo * parent)
865 {
866   GstDiscovererStreamInfo *res = NULL;
867   GstCaps *caps = NULL;
868   const GValue *nval = NULL;
869
870   GST_DEBUG ("parsing: %" GST_PTR_FORMAT, topology);
871
872   nval = gst_structure_get_value (topology, "next");
873
874   if (nval == NULL || GST_VALUE_HOLDS_STRUCTURE (nval)) {
875     GstStructure *st = find_stream_for_node (dc, topology);
876     gboolean add_to_list = TRUE;
877
878     if (st) {
879       res = collect_information (dc, st, parent);
880       gst_structure_free (st);
881     } else {
882       /* Didn't find a stream structure, so let's just use the caps we have */
883       res = collect_information (dc, topology, parent);
884     }
885
886     if (nval == NULL) {
887       /* FIXME : aggregate with information from main streams */
888       GST_DEBUG ("Coudn't find 'next' ! might be the last entry");
889     } else {
890       GstCaps *caps;
891       const GstStructure *st;
892
893       st = gst_value_get_structure (nval);
894
895       GST_DEBUG ("next is a structure %" GST_PTR_FORMAT, st);
896
897       if (!parent)
898         parent = res;
899
900       if (gst_structure_id_get (st, _CAPS_QUARK, GST_TYPE_CAPS, &caps, NULL)) {
901         if (gst_caps_can_intersect (parent->caps, caps)) {
902           /* We sometimes get an extra sub-stream from the parser. If this is
903            * the case, we just replace the parent caps with this stream's caps
904            * since they might contain more information */
905           gst_caps_unref (parent->caps);
906           parent->caps = caps;
907
908           parse_stream_topology (dc, st, parent);
909           add_to_list = FALSE;
910
911         } else if (child_is_raw_stream (parent->caps, caps)) {
912           /* This is the "raw" stream corresponding to the parent. This
913            * contains more information than the parent, tags etc. */
914           parse_stream_topology (dc, st, parent);
915           add_to_list = FALSE;
916           gst_caps_unref (caps);
917
918         } else {
919           GstDiscovererStreamInfo *next = parse_stream_topology (dc, st, NULL);
920           res->next = next;
921           next->previous = res;
922         }
923       }
924     }
925
926     if (add_to_list) {
927       dc->priv->current_info->stream_list =
928           g_list_append (dc->priv->current_info->stream_list, res);
929     }
930
931   } else if (GST_VALUE_HOLDS_LIST (nval)) {
932     guint i, len;
933     GstDiscovererContainerInfo *cont;
934     GstTagList *tags;
935
936     if (!gst_structure_id_get (topology, _CAPS_QUARK,
937             GST_TYPE_CAPS, &caps, NULL))
938       GST_WARNING ("Couldn't find caps !");
939
940     len = gst_value_list_get_size (nval);
941     GST_DEBUG ("next is a list of %d entries", len);
942
943     cont = (GstDiscovererContainerInfo *)
944         g_object_new (GST_TYPE_DISCOVERER_CONTAINER_INFO, NULL);
945     cont->parent.caps = caps;
946     res = (GstDiscovererStreamInfo *) cont;
947
948     if (gst_structure_id_has_field (topology, _TAGS_QUARK)) {
949       GstTagList *tmp;
950
951       gst_structure_id_get (topology, _TAGS_QUARK,
952           GST_TYPE_STRUCTURE, &tags, NULL);
953
954       GST_DEBUG ("Merge tags %" GST_PTR_FORMAT, tags);
955
956       tmp =
957           gst_tag_list_merge (cont->parent.tags, (GstTagList *) tags,
958           GST_TAG_MERGE_APPEND);
959       gst_tag_list_free (tags);
960       if (cont->parent.tags)
961         gst_tag_list_free (cont->parent.tags);
962       cont->parent.tags = tmp;
963       GST_DEBUG ("Container info tags %" GST_PTR_FORMAT, tmp);
964     }
965
966     for (i = 0; i < len; i++) {
967       const GValue *subv = gst_value_list_get_value (nval, i);
968       const GstStructure *subst = gst_value_get_structure (subv);
969       GstDiscovererStreamInfo *substream;
970
971       GST_DEBUG ("%d %" GST_PTR_FORMAT, i, subst);
972
973       substream = parse_stream_topology (dc, subst, NULL);
974
975       substream->previous = res;
976       cont->streams =
977           g_list_append (cont->streams,
978           gst_discoverer_stream_info_ref (substream));
979     }
980   }
981
982   return res;
983 }
984
985 /* Called when pipeline is pre-rolled */
986 static void
987 discoverer_collect (GstDiscoverer * dc)
988 {
989   GST_DEBUG ("Collecting information");
990
991   /* Stop the timeout handler if present */
992   if (dc->priv->timeoutid) {
993     g_source_remove (dc->priv->timeoutid);
994     dc->priv->timeoutid = 0;
995   }
996
997   if (dc->priv->streams) {
998     /* FIXME : Make this querying optional */
999     if (TRUE) {
1000       GstElement *pipeline = (GstElement *) dc->priv->pipeline;
1001       gint64 dur;
1002
1003       GST_DEBUG ("Attempting to query duration");
1004
1005       if (gst_element_query_duration (pipeline, GST_FORMAT_TIME, &dur)) {
1006         GST_DEBUG ("Got duration %" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
1007         dc->priv->current_info->duration = (guint64) dur;
1008       }
1009
1010       if (dc->priv->seeking_query) {
1011         if (gst_element_query (pipeline, dc->priv->seeking_query)) {
1012           GstFormat format;
1013           gboolean seekable;
1014
1015           gst_query_parse_seeking (dc->priv->seeking_query, &format,
1016               &seekable, NULL, NULL);
1017           if (format == GST_FORMAT_TIME) {
1018             GST_DEBUG ("Got seekable %d", seekable);
1019             dc->priv->current_info->seekable = seekable;
1020           }
1021         }
1022       }
1023     }
1024
1025     if (dc->priv->current_topology)
1026       dc->priv->current_info->stream_info = parse_stream_topology (dc,
1027           dc->priv->current_topology, NULL);
1028
1029     /*
1030      * Images need some special handling. They do not have a duration, have
1031      * caps named image/<foo> (th exception being MJPEG video which is also
1032      * type image/jpeg), and should consist of precisely one stream (actually
1033      * initially there are 2, the image and raw stream, but we squash these
1034      * while parsing the stream topology). At some point, if we find that these
1035      * conditions are not sufficient, we can count the number of decoders and
1036      * parsers in the chain, and if there's more than one decoder, or any
1037      * parser at all, we should not mark this as an image.
1038      */
1039     if (dc->priv->current_info->duration == 0 &&
1040         dc->priv->current_info->stream_info != NULL &&
1041         dc->priv->current_info->stream_info->next == NULL) {
1042       GstStructure *st =
1043           gst_caps_get_structure (dc->priv->current_info->stream_info->caps, 0);
1044
1045       if (g_str_has_prefix (gst_structure_get_name (st), "image/"))
1046         ((GstDiscovererVideoInfo *) dc->priv->current_info->stream_info)->
1047             is_image = TRUE;
1048     }
1049   }
1050
1051   if (dc->priv->async) {
1052     GST_DEBUG ("Emitting 'discoverered'");
1053     g_signal_emit (dc, gst_discoverer_signals[SIGNAL_DISCOVERED], 0,
1054         dc->priv->current_info, dc->priv->current_error);
1055     /* Clients get a copy of current_info since it is a boxed type */
1056     gst_discoverer_info_unref (dc->priv->current_info);
1057   }
1058 }
1059
1060 static void
1061 get_async_cb (gpointer cb_data, GSource * source, GSourceFunc * func,
1062     gpointer * data)
1063 {
1064   *func = (GSourceFunc) async_timeout_cb;
1065   *data = cb_data;
1066 }
1067
1068 /* Wrapper since GSourceCallbackFuncs don't expect a return value from ref() */
1069 static void
1070 _void_g_object_ref (gpointer object)
1071 {
1072   g_object_ref (G_OBJECT (object));
1073 }
1074
1075 static void
1076 handle_current_async (GstDiscoverer * dc)
1077 {
1078   GSource *source;
1079   static GSourceCallbackFuncs cb_funcs = {
1080     _void_g_object_ref,
1081     g_object_unref,
1082     get_async_cb,
1083   };
1084
1085   /* Attach a timeout to the main context */
1086   source = g_timeout_source_new (dc->priv->timeout / GST_MSECOND);
1087   g_source_set_callback_indirect (source, g_object_ref (dc), &cb_funcs);
1088   dc->priv->timeoutid = g_source_attach (source, dc->priv->ctx);
1089   g_source_unref (source);
1090 }
1091
1092
1093 /* Returns TRUE if processing should stop */
1094 static gboolean
1095 handle_message (GstDiscoverer * dc, GstMessage * msg)
1096 {
1097   gboolean done = FALSE;
1098
1099   GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "got a %s message",
1100       GST_MESSAGE_TYPE_NAME (msg));
1101
1102   switch (GST_MESSAGE_TYPE (msg)) {
1103     case GST_MESSAGE_ERROR:{
1104       GError *gerr;
1105       gchar *debug;
1106
1107       gst_message_parse_error (msg, &gerr, &debug);
1108       GST_WARNING_OBJECT (GST_MESSAGE_SRC (msg),
1109           "Got an error [debug:%s], [message:%s]", debug, gerr->message);
1110       dc->priv->current_error = gerr;
1111       g_free (debug);
1112
1113       /* We need to stop */
1114       done = TRUE;
1115
1116       GST_DEBUG ("Setting result to ERROR");
1117       dc->priv->current_info->result = GST_DISCOVERER_ERROR;
1118     }
1119       break;
1120
1121     case GST_MESSAGE_EOS:
1122       GST_DEBUG ("Got EOS !");
1123       done = TRUE;
1124       break;
1125
1126     case GST_MESSAGE_ASYNC_DONE:
1127       if (GST_MESSAGE_SRC (msg) == (GstObject *) dc->priv->pipeline) {
1128         GST_DEBUG ("Finished changing state asynchronously");
1129         done = TRUE;
1130
1131       }
1132       break;
1133
1134     case GST_MESSAGE_ELEMENT:
1135     {
1136       GQuark sttype;
1137       const GstStructure *structure;
1138
1139       structure = gst_message_get_structure (msg);
1140       sttype = gst_structure_get_name_id (structure);
1141       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg),
1142           "structure %" GST_PTR_FORMAT, structure);
1143       if (sttype == _MISSING_PLUGIN_QUARK) {
1144         GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg),
1145             "Setting result to MISSING_PLUGINS");
1146         dc->priv->current_info->result = GST_DISCOVERER_MISSING_PLUGINS;
1147         dc->priv->current_info->misc = gst_structure_copy (structure);
1148       } else if (sttype == _STREAM_TOPOLOGY_QUARK) {
1149         dc->priv->current_topology = gst_structure_copy (structure);
1150       }
1151     }
1152       break;
1153
1154     case GST_MESSAGE_TAG:
1155     {
1156       GstTagList *tl, *tmp;
1157
1158       gst_message_parse_tag (msg, &tl);
1159       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Got tags %" GST_PTR_FORMAT, tl);
1160       /* Merge with current tags */
1161       tmp =
1162           gst_tag_list_merge (dc->priv->current_info->tags, tl,
1163           GST_TAG_MERGE_APPEND);
1164       gst_tag_list_free (tl);
1165       if (dc->priv->current_info->tags)
1166         gst_tag_list_free (dc->priv->current_info->tags);
1167       dc->priv->current_info->tags = tmp;
1168       GST_DEBUG_OBJECT (GST_MESSAGE_SRC (msg), "Current info %p, tags %"
1169           GST_PTR_FORMAT, dc->priv->current_info, tmp);
1170     }
1171       break;
1172
1173     default:
1174       break;
1175   }
1176
1177   return done;
1178 }
1179
1180
1181 static void
1182 handle_current_sync (GstDiscoverer * dc)
1183 {
1184   GTimer *timer;
1185   gdouble deadline = ((gdouble) dc->priv->timeout) / GST_SECOND;
1186   GstMessage *msg;
1187   gboolean done = FALSE;
1188
1189   timer = g_timer_new ();
1190   g_timer_start (timer);
1191
1192   do {
1193     /* poll bus with timeout */
1194     /* FIXME : make the timeout more fine-tuned */
1195     if ((msg = gst_bus_timed_pop (dc->priv->bus, GST_SECOND / 2))) {
1196       done = handle_message (dc, msg);
1197       gst_message_unref (msg);
1198     }
1199
1200   } while (!done && (g_timer_elapsed (timer, NULL) < deadline));
1201
1202   /* return result */
1203   if (!done) {
1204     GST_DEBUG ("we timed out! Setting result to TIMEOUT");
1205     dc->priv->current_info->result = GST_DISCOVERER_TIMEOUT;
1206   }
1207
1208   GST_DEBUG ("Done");
1209
1210   g_timer_stop (timer);
1211   g_timer_destroy (timer);
1212 }
1213
1214 static void
1215 _setup_locked (GstDiscoverer * dc)
1216 {
1217   GstStateChangeReturn ret;
1218
1219   GST_DEBUG ("Setting up");
1220
1221   /* Pop URI off the pending URI list */
1222   dc->priv->current_info =
1223       (GstDiscovererInfo *) g_object_new (GST_TYPE_DISCOVERER_INFO, NULL);
1224   dc->priv->current_info->uri = (gchar *) dc->priv->pending_uris->data;
1225   dc->priv->pending_uris =
1226       g_list_delete_link (dc->priv->pending_uris, dc->priv->pending_uris);
1227
1228   /* set uri on uridecodebin */
1229   g_object_set (dc->priv->uridecodebin, "uri", dc->priv->current_info->uri,
1230       NULL);
1231
1232   GST_DEBUG ("Current is now %s", dc->priv->current_info->uri);
1233
1234   dc->priv->processing = TRUE;
1235
1236   /* set pipeline to PAUSED */
1237   DISCO_UNLOCK (dc);
1238   GST_DEBUG ("Setting pipeline to PAUSED");
1239   ret =
1240       gst_element_set_state ((GstElement *) dc->priv->pipeline,
1241       GST_STATE_PAUSED);
1242   DISCO_LOCK (dc);
1243
1244   GST_DEBUG_OBJECT (dc, "Pipeline going to PAUSED : %s",
1245       gst_element_state_change_return_get_name (ret));
1246 }
1247
1248 static void
1249 discoverer_cleanup (GstDiscoverer * dc)
1250 {
1251   GST_DEBUG ("Cleaning up");
1252
1253   gst_bus_set_flushing (dc->priv->bus, TRUE);
1254   gst_element_set_state ((GstElement *) dc->priv->pipeline, GST_STATE_READY);
1255   gst_bus_set_flushing (dc->priv->bus, FALSE);
1256
1257   DISCO_LOCK (dc);
1258   if (dc->priv->current_error)
1259     g_error_free (dc->priv->current_error);
1260   dc->priv->current_error = NULL;
1261   if (dc->priv->current_topology) {
1262     gst_structure_free (dc->priv->current_topology);
1263     dc->priv->current_topology = NULL;
1264   }
1265
1266   dc->priv->current_info = NULL;
1267
1268   /* Try popping the next uri */
1269   if (dc->priv->async) {
1270     if (dc->priv->pending_uris != NULL) {
1271       _setup_locked (dc);
1272       DISCO_UNLOCK (dc);
1273       /* Start timeout */
1274       handle_current_async (dc);
1275     } else {
1276       /* We're done ! */
1277       DISCO_UNLOCK (dc);
1278       g_signal_emit (dc, gst_discoverer_signals[SIGNAL_FINISHED], 0);
1279     }
1280   } else
1281     DISCO_UNLOCK (dc);
1282
1283   GST_DEBUG ("out");
1284 }
1285
1286 static void
1287 discoverer_bus_cb (GstBus * bus, GstMessage * msg, GstDiscoverer * dc)
1288 {
1289   if (dc->priv->processing) {
1290     if (handle_message (dc, msg)) {
1291       GST_DEBUG ("Stopping asynchronously");
1292       /* Serialise with _event_probe() */
1293       DISCO_LOCK (dc);
1294       dc->priv->processing = FALSE;
1295       DISCO_UNLOCK (dc);
1296       discoverer_collect (dc);
1297       discoverer_cleanup (dc);
1298     }
1299   }
1300 }
1301
1302 static gboolean
1303 async_timeout_cb (GstDiscoverer * dc)
1304 {
1305   if (!g_source_is_destroyed (g_main_current_source ())) {
1306     dc->priv->timeoutid = 0;
1307     GST_DEBUG ("Setting result to TIMEOUT");
1308     dc->priv->current_info->result = GST_DISCOVERER_TIMEOUT;
1309     dc->priv->processing = FALSE;
1310     discoverer_collect (dc);
1311     discoverer_cleanup (dc);
1312   }
1313   return FALSE;
1314 }
1315
1316 /* If there is a pending URI, it will pop it from the list of pending
1317  * URIs and start the discovery on it.
1318  *
1319  * Returns GST_DISCOVERER_OK if the next URI was popped and is processing,
1320  * else a error flag.
1321  */
1322 static GstDiscovererResult
1323 start_discovering (GstDiscoverer * dc)
1324 {
1325   GstDiscovererResult res = GST_DISCOVERER_OK;
1326
1327   GST_DEBUG ("Starting");
1328
1329   DISCO_LOCK (dc);
1330   if (dc->priv->pending_uris == NULL) {
1331     GST_WARNING ("No URI to process");
1332     res = GST_DISCOVERER_URI_INVALID;
1333     DISCO_UNLOCK (dc);
1334     goto beach;
1335   }
1336
1337   if (dc->priv->current_info != NULL) {
1338     GST_WARNING ("Already processing a file");
1339     res = GST_DISCOVERER_BUSY;
1340     DISCO_UNLOCK (dc);
1341     goto beach;
1342   }
1343
1344   g_signal_emit (dc, gst_discoverer_signals[SIGNAL_STARTING], 0);
1345
1346   _setup_locked (dc);
1347
1348   DISCO_UNLOCK (dc);
1349
1350   if (dc->priv->async)
1351     handle_current_async (dc);
1352   else
1353     handle_current_sync (dc);
1354
1355 beach:
1356   return res;
1357 }
1358
1359
1360 /**
1361  * gst_discoverer_start:
1362  * @discoverer: A #GstDiscoverer
1363  *
1364  * Allow asynchronous discovering of URIs to take place.
1365  * A #GMainLoop must be available for #GstDiscoverer to properly work in
1366  * asynchronous mode.
1367  *
1368  * Since: 0.10.31
1369  */
1370 void
1371 gst_discoverer_start (GstDiscoverer * discoverer)
1372 {
1373   GSource *source;
1374   GMainContext *ctx = NULL;
1375
1376   GST_DEBUG_OBJECT (discoverer, "Starting...");
1377
1378   if (discoverer->priv->async) {
1379     GST_DEBUG_OBJECT (discoverer, "We were already started");
1380     return;
1381   }
1382
1383   discoverer->priv->async = TRUE;
1384   discoverer->priv->running = TRUE;
1385
1386   ctx = g_main_context_get_thread_default ();
1387
1388   /* Connect to bus signals */
1389   if (ctx == NULL)
1390     ctx = g_main_context_default ();
1391
1392   source = gst_bus_create_watch (discoverer->priv->bus);
1393   g_source_set_callback (source, (GSourceFunc) gst_bus_async_signal_func,
1394       NULL, NULL);
1395   discoverer->priv->sourceid = g_source_attach (source, ctx);
1396   g_source_unref (source);
1397   discoverer->priv->ctx = g_main_context_ref (ctx);
1398
1399   start_discovering (discoverer);
1400   GST_DEBUG_OBJECT (discoverer, "Started");
1401 }
1402
1403 /**
1404  * gst_discoverer_stop:
1405  * @discoverer: A #GstDiscoverer
1406  *
1407  * Stop the discovery of any pending URIs and clears the list of
1408  * pending URIS (if any).
1409  *
1410  * Since: 0.10.31
1411  */
1412 void
1413 gst_discoverer_stop (GstDiscoverer * discoverer)
1414 {
1415   GST_DEBUG_OBJECT (discoverer, "Stopping...");
1416
1417   if (!discoverer->priv->async) {
1418     GST_DEBUG_OBJECT (discoverer,
1419         "We were already stopped, or running synchronously");
1420     return;
1421   }
1422
1423   DISCO_LOCK (discoverer);
1424   if (discoverer->priv->processing) {
1425     /* We prevent any further processing by setting the bus to
1426      * flushing and setting the pipeline to READY.
1427      * _reset() will take care of the rest of the cleanup */
1428     if (discoverer->priv->bus)
1429       gst_bus_set_flushing (discoverer->priv->bus, TRUE);
1430     if (discoverer->priv->pipeline)
1431       gst_element_set_state ((GstElement *) discoverer->priv->pipeline,
1432           GST_STATE_READY);
1433   }
1434   discoverer->priv->running = FALSE;
1435   DISCO_UNLOCK (discoverer);
1436
1437   /* Remove timeout handler */
1438   if (discoverer->priv->timeoutid) {
1439     g_source_remove (discoverer->priv->timeoutid);
1440     discoverer->priv->timeoutid = 0;
1441   }
1442   /* Remove signal watch */
1443   if (discoverer->priv->sourceid) {
1444     g_source_remove (discoverer->priv->sourceid);
1445     discoverer->priv->sourceid = 0;
1446   }
1447   /* Unref main context */
1448   if (discoverer->priv->ctx) {
1449     g_main_context_unref (discoverer->priv->ctx);
1450     discoverer->priv->ctx = NULL;
1451   }
1452   discoverer_reset (discoverer);
1453
1454   discoverer->priv->async = FALSE;
1455
1456   GST_DEBUG_OBJECT (discoverer, "Stopped");
1457 }
1458
1459 /**
1460  * gst_discoverer_discover_uri_async:
1461  * @discoverer: A #GstDiscoverer
1462  * @uri: the URI to add.
1463  *
1464  * Appends the given @uri to the list of URIs to discoverer. The actual
1465  * discovery of the @uri will only take place if gst_discoverer_start() has
1466  * been called.
1467  *
1468  * A copy of @uri will be made internally, so the caller can safely g_free()
1469  * afterwards.
1470  *
1471  * Returns: %TRUE if the @uri was succesfully appended to the list of pending
1472  * uris, else %FALSE
1473  *
1474  * Since: 0.10.31
1475  */
1476 gboolean
1477 gst_discoverer_discover_uri_async (GstDiscoverer * discoverer,
1478     const gchar * uri)
1479 {
1480   gboolean can_run;
1481
1482   GST_DEBUG_OBJECT (discoverer, "uri : %s", uri);
1483
1484   DISCO_LOCK (discoverer);
1485   can_run = (discoverer->priv->pending_uris == NULL);
1486   discoverer->priv->pending_uris =
1487       g_list_append (discoverer->priv->pending_uris, g_strdup (uri));
1488   DISCO_UNLOCK (discoverer);
1489
1490   if (can_run)
1491     start_discovering (discoverer);
1492
1493   return TRUE;
1494 }
1495
1496
1497 /* Synchronous mode */
1498 /**
1499  * gst_discoverer_discover_uri:
1500  * @discoverer: A #GstDiscoverer
1501  * @uri: The URI to run on.
1502  * @err: (out) (allow-none): If an error occurred, this field will be filled in.
1503  *
1504  * Synchronously discovers the given @uri.
1505  *
1506  * A copy of @uri will be made internally, so the caller can safely g_free()
1507  * afterwards.
1508  *
1509  * Returns: (transfer full): the result of the scanning. Can be %NULL if an
1510  * error occurred.
1511  *
1512  * Since: 0.10.31
1513  */
1514 GstDiscovererInfo *
1515 gst_discoverer_discover_uri (GstDiscoverer * discoverer, const gchar * uri,
1516     GError ** err)
1517 {
1518   GstDiscovererResult res = 0;
1519   GstDiscovererInfo *info;
1520
1521   GST_DEBUG_OBJECT (discoverer, "uri:%s", uri);
1522
1523   DISCO_LOCK (discoverer);
1524   if (G_UNLIKELY (discoverer->priv->current_info)) {
1525     DISCO_UNLOCK (discoverer);
1526     GST_WARNING_OBJECT (discoverer, "Already handling a uri");
1527     return NULL;
1528   }
1529
1530   discoverer->priv->pending_uris =
1531       g_list_append (discoverer->priv->pending_uris, g_strdup (uri));
1532   DISCO_UNLOCK (discoverer);
1533
1534   res = start_discovering (discoverer);
1535   discoverer_collect (discoverer);
1536
1537   /* Get results */
1538   if (err) {
1539     if (discoverer->priv->current_error)
1540       *err = g_error_copy (discoverer->priv->current_error);
1541     else
1542       *err = NULL;
1543   }
1544   if (res != GST_DISCOVERER_OK) {
1545     GST_DEBUG ("Setting result to %d (was %d)", res,
1546         discoverer->priv->current_info->result);
1547     discoverer->priv->current_info->result = res;
1548   }
1549   info = discoverer->priv->current_info;
1550
1551   discoverer_cleanup (discoverer);
1552
1553   return info;
1554 }
1555
1556 /**
1557  * gst_discoverer_new:
1558  * @timeout: timeout per file, in nanoseconds. Allowed are values between
1559  *     one second (#GST_SECOND) and one hour (3600 * #GST_SECOND)
1560  * @err: a pointer to a #GError. can be %NULL
1561  *
1562  * Creates a new #GstDiscoverer with the provided timeout.
1563  *
1564  * Returns: (transfer full): The new #GstDiscoverer.
1565  * If an error occurred when creating the discoverer, @err will be set
1566  * accordingly and %NULL will be returned. If @err is set, the caller must
1567  * free it when no longer needed using g_error_free().
1568  *
1569  * Since: 0.10.31
1570  */
1571 GstDiscoverer *
1572 gst_discoverer_new (GstClockTime timeout, GError ** err)
1573 {
1574   GstDiscoverer *res;
1575
1576   res = g_object_new (GST_TYPE_DISCOVERER, "timeout", timeout, NULL);
1577   if (res->priv->uridecodebin == NULL) {
1578     if (err)
1579       *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN,
1580           "Couldn't create 'uridecodebin' element");
1581     gst_object_unref (res);
1582     res = NULL;
1583   }
1584   return res;
1585 }