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