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