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