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