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