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