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