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