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