• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19 
20 /**
21  * SECTION:element-uridecodebin
22  * @title: uridecodebin
23  *
24  * Decodes data from a URI into raw media. It selects a source element that can
25  * handle the given #GstURIDecodeBin:uri scheme and connects it to a decodebin.
26  */
27 
28 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
29  * with newer GLib versions (>= 2.31.0) */
30 #define GLIB_DISABLE_DEPRECATION_WARNINGS
31 
32 #ifdef HAVE_CONFIG_H
33 #  include "config.h"
34 #endif
35 
36 #include <string.h>
37 
38 #include <gst/gst.h>
39 #include <gst/gst-i18n-plugin.h>
40 #include <gst/pbutils/missing-plugins.h>
41 
42 #include "gstplay-enum.h"
43 #include "gstrawcaps.h"
44 #include "gstplayback.h"
45 #include "gstplaybackutils.h"
46 
47 #define GST_TYPE_URI_DECODE_BIN \
48   (gst_uri_decode_bin_get_type())
49 #define GST_URI_DECODE_BIN(obj) \
50   (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_URI_DECODE_BIN,GstURIDecodeBin))
51 #define GST_URI_DECODE_BIN_CLASS(klass) \
52   (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_URI_DECODE_BIN,GstURIDecodeBinClass))
53 #define GST_IS_URI_DECODE_BIN(obj) \
54   (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_URI_DECODE_BIN))
55 #define GST_IS_URI_DECODE_BIN_CLASS(klass) \
56   (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_URI_DECODE_BIN))
57 #define GST_URI_DECODE_BIN_CAST(obj) ((GstURIDecodeBin *) (obj))
58 
59 typedef struct _GstURIDecodeBin GstURIDecodeBin;
60 typedef struct _GstURIDecodeBinClass GstURIDecodeBinClass;
61 
62 #define GST_URI_DECODE_BIN_LOCK(dec) (g_mutex_lock(&((GstURIDecodeBin*)(dec))->lock))
63 #define GST_URI_DECODE_BIN_UNLOCK(dec) (g_mutex_unlock(&((GstURIDecodeBin*)(dec))->lock))
64 
65 typedef struct _GstURIDecodeBinStream
66 {
67   gulong probe_id;
68   guint bitrate;
69 } GstURIDecodeBinStream;
70 
71 /**
72  * GstURIDecodeBin
73  *
74  * uridecodebin element struct
75  */
76 struct _GstURIDecodeBin
77 {
78   GstBin parent_instance;
79 
80   GMutex lock;                  /* lock for constructing */
81 
82   GMutex factories_lock;
83   guint32 factories_cookie;
84   GList *factories;             /* factories we can use for selecting elements */
85 
86   gchar *uri;
87   guint64 connection_speed;
88   GstCaps *caps;
89   gchar *encoding;
90 
91   gboolean is_stream;
92   gboolean is_adaptive;
93   gboolean need_queue;
94   guint64 buffer_duration;      /* When buffering, buffer duration (ns) */
95   guint buffer_size;            /* When buffering, buffer size (bytes) */
96   gboolean download;
97   gboolean use_buffering;
98 
99   GstElement *source;
100   GstElement *queue;
101   GstElement *typefind;
102   guint have_type_id;           /* have-type signal id from typefind */
103   GSList *decodebins;
104   GSList *pending_decodebins;
105   GHashTable *streams;
106   guint numpads;
107 
108   /* for dynamic sources */
109   guint src_np_sig_id;          /* new-pad signal id */
110   guint src_nmp_sig_id;         /* no-more-pads signal id */
111   gint pending;
112   GList *missing_plugin_errors;
113 
114   gboolean async_pending;       /* async-start has been emitted */
115 
116   gboolean expose_allstreams;   /* Whether to expose unknow type streams or not */
117 
118   guint64 ring_buffer_max_size; /* 0 means disabled */
119 #ifdef OHOS_EXT_FUNC
120   //ohos.ext.func.0012
121   gint low_percent;
122   gint high_percent;
123 #endif
124 };
125 
126 struct _GstURIDecodeBinClass
127 {
128   GstBinClass parent_class;
129 
130   /* signal fired when we found a pad that we cannot decode */
131   void (*unknown_type) (GstElement * element, GstPad * pad, GstCaps * caps);
132 
133   /* signal fired to know if we continue trying to decode the given caps */
134     gboolean (*autoplug_continue) (GstElement * element, GstPad * pad,
135       GstCaps * caps);
136   /* signal fired to get a list of factories to try to autoplug */
137   GValueArray *(*autoplug_factories) (GstElement * element, GstPad * pad,
138       GstCaps * caps);
139   /* signal fired to sort the factories */
140   GValueArray *(*autoplug_sort) (GstElement * element, GstPad * pad,
141       GstCaps * caps, GValueArray * factories);
142   /* signal fired to select from the proposed list of factories */
143     GstAutoplugSelectResult (*autoplug_select) (GstElement * element,
144       GstPad * pad, GstCaps * caps, GstElementFactory * factory);
145   /* signal fired when a autoplugged element that is not linked downstream
146    * or exposed wants to query something */
147     gboolean (*autoplug_query) (GstElement * element, GstPad * pad,
148       GstQuery * query);
149 
150   /* emitted when all data is decoded */
151   void (*drained) (GstElement * element);
152 };
153 
154 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
155     GST_PAD_SRC,
156     GST_PAD_SOMETIMES,
157     GST_STATIC_CAPS_ANY);
158 
159 static GstStaticCaps default_raw_caps = GST_STATIC_CAPS (DEFAULT_RAW_CAPS);
160 
161 GST_DEBUG_CATEGORY_STATIC (gst_uri_decode_bin_debug);
162 #define GST_CAT_DEFAULT gst_uri_decode_bin_debug
163 
164 /* signals */
165 enum
166 {
167   SIGNAL_UNKNOWN_TYPE,
168   SIGNAL_AUTOPLUG_CONTINUE,
169   SIGNAL_AUTOPLUG_FACTORIES,
170   SIGNAL_AUTOPLUG_SELECT,
171   SIGNAL_AUTOPLUG_SORT,
172   SIGNAL_AUTOPLUG_QUERY,
173   SIGNAL_DRAINED,
174   SIGNAL_SOURCE_SETUP,
175   LAST_SIGNAL
176 };
177 
178 /* properties */
179 #define DEFAULT_PROP_URI            NULL
180 #define DEFAULT_PROP_SOURCE         NULL
181 #define DEFAULT_CONNECTION_SPEED    0
182 #define DEFAULT_CAPS                (gst_static_caps_get (&default_raw_caps))
183 #define DEFAULT_SUBTITLE_ENCODING   NULL
184 #ifdef OHOS_EXT_FUNC
185 // ohos.ext.func.0012
186 #define DEFAULT_BUFFER_DURATION     0
187 #else
188 #define DEFAULT_BUFFER_DURATION     -1
189 #endif
190 #define DEFAULT_BUFFER_SIZE         -1
191 #define DEFAULT_DOWNLOAD            FALSE
192 #define DEFAULT_USE_BUFFERING       FALSE
193 #define DEFAULT_EXPOSE_ALL_STREAMS  TRUE
194 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
195 
196 #ifdef OHOS_EXT_FUNC
197   // ohos.ext.func.0012
198 #define DEFAULT_LOW_PERCENT       10
199 #define DEFAULT_HIGH_PERCENT      99
200 #define DEFAULT_TIMEOUT           15
201 #endif
202 
203 enum
204 {
205   PROP_0,
206   PROP_URI,
207   PROP_SOURCE,
208   PROP_CONNECTION_SPEED,
209   PROP_CAPS,
210   PROP_SUBTITLE_ENCODING,
211   PROP_BUFFER_SIZE,
212   PROP_BUFFER_DURATION,
213   PROP_DOWNLOAD,
214   PROP_USE_BUFFERING,
215   PROP_EXPOSE_ALL_STREAMS,
216 #ifdef OHOS_EXT_FUNC
217   // ohos.ext.func.0012
218   PROP_LOW_PERCENT,
219   PROP_HIGH_PERCENT,
220   PROP_STATE_CHANGE,
221   PROP_EXIT_BLOCK,
222   PROP_TIMEOUT,
223 #endif
224   PROP_RING_BUFFER_MAX_SIZE
225 };
226 
227 static guint gst_uri_decode_bin_signals[LAST_SIGNAL] = { 0 };
228 
229 GType gst_uri_decode_bin_get_type (void);
230 #define gst_uri_decode_bin_parent_class parent_class
231 G_DEFINE_TYPE (GstURIDecodeBin, gst_uri_decode_bin, GST_TYPE_BIN);
232 
233 static void remove_decoders (GstURIDecodeBin * bin, gboolean force);
234 static void gst_uri_decode_bin_set_property (GObject * object, guint prop_id,
235     const GValue * value, GParamSpec * pspec);
236 static void gst_uri_decode_bin_get_property (GObject * object, guint prop_id,
237     GValue * value, GParamSpec * pspec);
238 static void gst_uri_decode_bin_finalize (GObject * obj);
239 
240 static void handle_message (GstBin * bin, GstMessage * msg);
241 
242 static gboolean gst_uri_decode_bin_query (GstElement * element,
243     GstQuery * query);
244 static GstStateChangeReturn gst_uri_decode_bin_change_state (GstElement *
245     element, GstStateChange transition);
246 
247 static gboolean
_gst_boolean_accumulator(GSignalInvocationHint * ihint,GValue * return_accu,const GValue * handler_return,gpointer dummy)248 _gst_boolean_accumulator (GSignalInvocationHint * ihint,
249     GValue * return_accu, const GValue * handler_return, gpointer dummy)
250 {
251   gboolean myboolean;
252 
253   myboolean = g_value_get_boolean (handler_return);
254   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
255     g_value_set_boolean (return_accu, myboolean);
256 
257   /* stop emission if FALSE */
258   return myboolean;
259 }
260 
261 static gboolean
_gst_boolean_or_accumulator(GSignalInvocationHint * ihint,GValue * return_accu,const GValue * handler_return,gpointer dummy)262 _gst_boolean_or_accumulator (GSignalInvocationHint * ihint,
263     GValue * return_accu, const GValue * handler_return, gpointer dummy)
264 {
265   gboolean myboolean;
266   gboolean retboolean;
267 
268   myboolean = g_value_get_boolean (handler_return);
269   retboolean = g_value_get_boolean (return_accu);
270 
271   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
272     g_value_set_boolean (return_accu, myboolean || retboolean);
273 
274   return TRUE;
275 }
276 
277 static gboolean
_gst_array_accumulator(GSignalInvocationHint * ihint,GValue * return_accu,const GValue * handler_return,gpointer dummy)278 _gst_array_accumulator (GSignalInvocationHint * ihint,
279     GValue * return_accu, const GValue * handler_return, gpointer dummy)
280 {
281   gpointer array;
282 
283   array = g_value_get_boxed (handler_return);
284   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
285     g_value_set_boxed (return_accu, array);
286 
287   return FALSE;
288 }
289 
290 static gboolean
_gst_select_accumulator(GSignalInvocationHint * ihint,GValue * return_accu,const GValue * handler_return,gpointer dummy)291 _gst_select_accumulator (GSignalInvocationHint * ihint,
292     GValue * return_accu, const GValue * handler_return, gpointer dummy)
293 {
294   GstAutoplugSelectResult res;
295 
296   res = g_value_get_enum (handler_return);
297   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
298     g_value_set_enum (return_accu, res);
299 
300   /* Call the next handler in the chain (if any) when the current callback
301    * returns TRY. This makes it possible to register separate autoplug-select
302    * handlers that implement different TRY/EXPOSE/SKIP strategies.
303    */
304   if (res == GST_AUTOPLUG_SELECT_TRY)
305     return TRUE;
306 
307   return FALSE;
308 }
309 
310 static gboolean
_gst_array_hasvalue_accumulator(GSignalInvocationHint * ihint,GValue * return_accu,const GValue * handler_return,gpointer dummy)311 _gst_array_hasvalue_accumulator (GSignalInvocationHint * ihint,
312     GValue * return_accu, const GValue * handler_return, gpointer dummy)
313 {
314   gpointer array;
315 
316   array = g_value_get_boxed (handler_return);
317   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
318     g_value_set_boxed (return_accu, array);
319 
320   if (array != NULL)
321     return FALSE;
322 
323   return TRUE;
324 }
325 
326 static gboolean
gst_uri_decode_bin_autoplug_continue(GstElement * element,GstPad * pad,GstCaps * caps)327 gst_uri_decode_bin_autoplug_continue (GstElement * element, GstPad * pad,
328     GstCaps * caps)
329 {
330   /* by default we always continue */
331   return TRUE;
332 }
333 
334 /* Must be called with factories lock! */
335 static void
gst_uri_decode_bin_update_factories_list(GstURIDecodeBin * dec)336 gst_uri_decode_bin_update_factories_list (GstURIDecodeBin * dec)
337 {
338   guint32 cookie;
339 
340   cookie = gst_registry_get_feature_list_cookie (gst_registry_get ());
341   if (!dec->factories || dec->factories_cookie != cookie) {
342     if (dec->factories)
343       gst_plugin_feature_list_free (dec->factories);
344     dec->factories =
345         gst_element_factory_list_get_elements
346         (GST_ELEMENT_FACTORY_TYPE_DECODABLE, GST_RANK_MARGINAL);
347     dec->factories =
348         g_list_sort (dec->factories, gst_playback_utils_compare_factories_func);
349     dec->factories_cookie = cookie;
350   }
351 }
352 
353 static GValueArray *
gst_uri_decode_bin_autoplug_factories(GstElement * element,GstPad * pad,GstCaps * caps)354 gst_uri_decode_bin_autoplug_factories (GstElement * element, GstPad * pad,
355     GstCaps * caps)
356 {
357   GList *list, *tmp;
358   GValueArray *result;
359   GstURIDecodeBin *dec = GST_URI_DECODE_BIN_CAST (element);
360 
361   GST_DEBUG_OBJECT (element, "finding factories");
362 
363   /* return all compatible factories for caps */
364   g_mutex_lock (&dec->factories_lock);
365   gst_uri_decode_bin_update_factories_list (dec);
366   list =
367       gst_element_factory_list_filter (dec->factories, caps, GST_PAD_SINK,
368       gst_caps_is_fixed (caps));
369   g_mutex_unlock (&dec->factories_lock);
370 
371   result = g_value_array_new (g_list_length (list));
372   for (tmp = list; tmp; tmp = tmp->next) {
373     GstElementFactory *factory = GST_ELEMENT_FACTORY_CAST (tmp->data);
374     GValue val = { 0, };
375 
376     g_value_init (&val, G_TYPE_OBJECT);
377     g_value_set_object (&val, factory);
378     g_value_array_append (result, &val);
379     g_value_unset (&val);
380   }
381   gst_plugin_feature_list_free (list);
382 
383   GST_DEBUG_OBJECT (element, "autoplug-factories returns %p", result);
384 
385   return result;
386 }
387 
388 static GValueArray *
gst_uri_decode_bin_autoplug_sort(GstElement * element,GstPad * pad,GstCaps * caps,GValueArray * factories)389 gst_uri_decode_bin_autoplug_sort (GstElement * element, GstPad * pad,
390     GstCaps * caps, GValueArray * factories)
391 {
392   return NULL;
393 }
394 
395 static GstAutoplugSelectResult
gst_uri_decode_bin_autoplug_select(GstElement * element,GstPad * pad,GstCaps * caps,GstElementFactory * factory)396 gst_uri_decode_bin_autoplug_select (GstElement * element, GstPad * pad,
397     GstCaps * caps, GstElementFactory * factory)
398 {
399   GST_DEBUG_OBJECT (element, "default autoplug-select returns TRY");
400 
401   /* Try factory. */
402   return GST_AUTOPLUG_SELECT_TRY;
403 }
404 
405 static gboolean
gst_uri_decode_bin_autoplug_query(GstElement * element,GstPad * pad,GstQuery * query)406 gst_uri_decode_bin_autoplug_query (GstElement * element, GstPad * pad,
407     GstQuery * query)
408 {
409   /* No query handled here */
410   return FALSE;
411 }
412 
413 static void
gst_uri_decode_bin_class_init(GstURIDecodeBinClass * klass)414 gst_uri_decode_bin_class_init (GstURIDecodeBinClass * klass)
415 {
416   GObjectClass *gobject_class;
417   GstElementClass *gstelement_class;
418   GstBinClass *gstbin_class;
419 
420   gobject_class = G_OBJECT_CLASS (klass);
421   gstelement_class = GST_ELEMENT_CLASS (klass);
422   gstbin_class = GST_BIN_CLASS (klass);
423 
424   gobject_class->set_property = gst_uri_decode_bin_set_property;
425   gobject_class->get_property = gst_uri_decode_bin_get_property;
426   gobject_class->finalize = gst_uri_decode_bin_finalize;
427 
428   g_object_class_install_property (gobject_class, PROP_URI,
429       g_param_spec_string ("uri", "URI", "URI to decode",
430           DEFAULT_PROP_URI, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
431 
432   g_object_class_install_property (gobject_class, PROP_SOURCE,
433       g_param_spec_object ("source", "Source", "Source object used",
434           GST_TYPE_ELEMENT, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
435 
436   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
437       g_param_spec_uint64 ("connection-speed", "Connection Speed",
438           "Network connection speed in kbps (0 = unknown)",
439           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
440           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
441 
442   g_object_class_install_property (gobject_class, PROP_CAPS,
443       g_param_spec_boxed ("caps", "Caps",
444           "The caps on which to stop decoding. (NULL = default)",
445           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446 
447   g_object_class_install_property (gobject_class, PROP_SUBTITLE_ENCODING,
448       g_param_spec_string ("subtitle-encoding", "subtitle encoding",
449           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
450           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
451           "be checked for an encoding to use. If that is not set either, "
452           "ISO-8859-15 will be assumed.", NULL,
453           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
454 
455   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
456       g_param_spec_int ("buffer-size", "Buffer size (bytes)",
457           "Buffer size when buffering streams (-1 default value)",
458           -1, G_MAXINT, DEFAULT_BUFFER_SIZE,
459           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
460 #ifdef OHOS_EXT_FUNC
461   // ohos.ext.func.0012
462   g_object_class_install_property (gobject_class, PROP_BUFFER_DURATION,
463       g_param_spec_uint64 ("buffer-duration", "Buffer duration (ns)",
464           "Buffer duration when buffering streams (-1 default value)",
465           0, G_MAXUINT64 / 1000, DEFAULT_BUFFER_DURATION,
466           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
467 
468   g_object_class_install_property (gobject_class, PROP_STATE_CHANGE,
469     g_param_spec_int ("state-change", "state-change from adaptive-demux",
470         "state-change from adaptive-demux", 0, (gint) (G_MAXINT32), 0,
471         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
472 
473   g_object_class_install_property (gobject_class, PROP_EXIT_BLOCK,
474       g_param_spec_int ("exit-block", "EXIT BLOCK",
475           "souphttpsrc exit block", 0, (gint) (G_MAXINT32), 0,
476           G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
477 
478   /*
479    * GstURIDecodeBin:low-percent
480    * Low threshold percent for buffering to start.
481    */
482   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
483       g_param_spec_int ("low-percent", "Low percent",
484           "Low threshold for buffering to start", 0, 100,
485           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
486   /*
487    * GstURIDecodeBin:high-percent
488    * High threshold percent for buffering to finish.
489    */
490   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
491       g_param_spec_int ("high-percent", "High percent",
492           "High threshold for buffering to finish", 0, 100,
493           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
494 
495   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
496       g_param_spec_uint ("timeout", "timeout",
497           "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
498           3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
499 #else
500   g_object_class_install_property (gobject_class, PROP_BUFFER_DURATION,
501       g_param_spec_int64 ("buffer-duration", "Buffer duration (ns)",
502           "Buffer duration when buffering streams (-1 default value)",
503           -1, G_MAXINT64, DEFAULT_BUFFER_DURATION,
504           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
505 #endif
506 
507   /**
508    * GstURIDecodeBin::download:
509    *
510    * For certain media type, enable download buffering.
511    */
512   g_object_class_install_property (gobject_class, PROP_DOWNLOAD,
513       g_param_spec_boolean ("download", "Download",
514           "Attempt download buffering when buffering network streams",
515           DEFAULT_DOWNLOAD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
516   /**
517    * GstURIDecodeBin::use-buffering:
518    *
519    * Emit BUFFERING messages based on low-/high-percent thresholds of the
520    * demuxed or parsed data.
521    * When download buffering is activated and used for the current media
522    * type, this property does nothing. Otherwise perform buffering on the
523    * demuxed or parsed media.
524    */
525   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
526       g_param_spec_boolean ("use-buffering", "Use Buffering",
527           "Perform buffering on demuxed/parsed media",
528           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
529 
530   /**
531    * GstURIDecodeBin::expose-all-streams
532    *
533    * Expose streams of unknown type.
534    *
535    * If set to %FALSE, then only the streams that can be decoded to the final
536    * caps (see 'caps' property) will have a pad exposed. Streams that do not
537    * match those caps but could have been decoded will not have decoder plugged
538    * in internally and will not have a pad exposed.
539    */
540   g_object_class_install_property (gobject_class, PROP_EXPOSE_ALL_STREAMS,
541       g_param_spec_boolean ("expose-all-streams", "Expose All Streams",
542           "Expose all streams, including those of unknown type or that don't match the 'caps' property",
543           DEFAULT_EXPOSE_ALL_STREAMS,
544           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
545 
546   /**
547    * GstURIDecodeBin::ring-buffer-max-size
548    *
549    * The maximum size of the ring buffer in kilobytes. If set to 0, the ring
550    * buffer is disabled. Default is 0.
551    */
552   g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
553       g_param_spec_uint64 ("ring-buffer-max-size",
554           "Max. ring buffer size (bytes)",
555           "Max. amount of data in the ring buffer (bytes, 0 = ring buffer disabled)",
556           0, G_MAXUINT, DEFAULT_RING_BUFFER_MAX_SIZE,
557           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
558 
559   /**
560    * GstURIDecodeBin::unknown-type:
561    * @bin: The uridecodebin.
562    * @pad: the new pad containing caps that cannot be resolved to a 'final'.
563    * stream type.
564    * @caps: the #GstCaps of the pad that cannot be resolved.
565    *
566    * This signal is emitted when a pad for which there is no further possible
567    * decoding is added to the uridecodebin.
568    */
569   gst_uri_decode_bin_signals[SIGNAL_UNKNOWN_TYPE] =
570       g_signal_new ("unknown-type", G_TYPE_FROM_CLASS (klass),
571       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass, unknown_type),
572       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
573       GST_TYPE_PAD, GST_TYPE_CAPS);
574 
575   /**
576    * GstURIDecodeBin::autoplug-continue:
577    * @bin: The uridecodebin.
578    * @pad: The #GstPad.
579    * @caps: The #GstCaps found.
580    *
581    * This signal is emitted whenever uridecodebin finds a new stream. It is
582    * emitted before looking for any elements that can handle that stream.
583    *
584    * >   Invocation of signal handlers stops after the first signal handler
585    * >   returns %FALSE. Signal handlers are invoked in the order they were
586    * >   connected in.
587    *
588    * Returns: %TRUE if you wish uridecodebin to look for elements that can
589    * handle the given @caps. If %FALSE, those caps will be considered as
590    * final and the pad will be exposed as such (see 'pad-added' signal of
591    * #GstElement).
592    */
593   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE] =
594       g_signal_new ("autoplug-continue", G_TYPE_FROM_CLASS (klass),
595       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass,
596           autoplug_continue), _gst_boolean_accumulator, NULL,
597       g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, GST_TYPE_PAD,
598       GST_TYPE_CAPS);
599 
600   /**
601    * GstURIDecodeBin::autoplug-factories:
602    * @bin: The uridecodebin.
603    * @pad: The #GstPad.
604    * @caps: The #GstCaps found.
605    *
606    * This function is emitted when an array of possible factories for @caps on
607    * @pad is needed. Uridecodebin will by default return an array with all
608    * compatible factories, sorted by rank.
609    *
610    * If this function returns NULL, @pad will be exposed as a final caps.
611    *
612    * If this function returns an empty array, the pad will be considered as
613    * having an unhandled type media type.
614    *
615    * >   Only the signal handler that is connected first will ever by invoked.
616    * >   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
617    * >   signal, they will never be invoked!
618    *
619    * Returns: a #GValueArray* with a list of factories to try. The factories are
620    * by default tried in the returned order or based on the index returned by
621    * "autoplug-select".
622    */
623   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES] =
624       g_signal_new ("autoplug-factories", G_TYPE_FROM_CLASS (klass),
625       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass,
626           autoplug_factories), _gst_array_accumulator, NULL,
627       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 2,
628       GST_TYPE_PAD, GST_TYPE_CAPS);
629 
630   /**
631    * GstURIDecodeBin::autoplug-sort:
632    * @bin: The uridecodebin.
633    * @pad: The #GstPad.
634    * @caps: The #GstCaps.
635    * @factories: A #GValueArray of possible #GstElementFactory to use.
636    *
637    * Once decodebin has found the possible #GstElementFactory objects to try
638    * for @caps on @pad, this signal is emitted. The purpose of the signal is for
639    * the application to perform additional sorting or filtering on the element
640    * factory array.
641    *
642    * The callee should copy and modify @factories or return %NULL if the
643    * order should not change.
644    *
645    * >   Invocation of signal handlers stops after one signal handler has
646    * >   returned something else than %NULL. Signal handlers are invoked in
647    * >   the order they were connected in.
648    * >   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
649    * >   signal, they will never be invoked!
650    *
651    * Returns: A new sorted array of #GstElementFactory objects.
652    */
653   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SORT] =
654       g_signal_new ("autoplug-sort", G_TYPE_FROM_CLASS (klass),
655       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass, autoplug_sort),
656       _gst_array_hasvalue_accumulator, NULL,
657       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 3, GST_TYPE_PAD,
658       GST_TYPE_CAPS, G_TYPE_VALUE_ARRAY | G_SIGNAL_TYPE_STATIC_SCOPE);
659 
660   /**
661    * GstURIDecodeBin::autoplug-select:
662    * @bin: The uridecodebin.
663    * @pad: The #GstPad.
664    * @caps: The #GstCaps.
665    * @factory: A #GstElementFactory to use.
666    *
667    * This signal is emitted once uridecodebin has found all the possible
668    * #GstElementFactory that can be used to handle the given @caps. For each of
669    * those factories, this signal is emitted.
670    *
671    * The signal handler should return a #GST_TYPE_AUTOPLUG_SELECT_RESULT enum
672    * value indicating what decodebin should do next.
673    *
674    * A value of #GST_AUTOPLUG_SELECT_TRY will try to autoplug an element from
675    * @factory.
676    *
677    * A value of #GST_AUTOPLUG_SELECT_EXPOSE will expose @pad without plugging
678    * any element to it.
679    *
680    * A value of #GST_AUTOPLUG_SELECT_SKIP will skip @factory and move to the
681    * next factory.
682    *
683    * >   The signal handler will not be invoked if any of the previously
684    * >   registered signal handlers (if any) return a value other than
685    * >   GST_AUTOPLUG_SELECT_TRY. Which also means that if you return
686    * >   GST_AUTOPLUG_SELECT_TRY from one signal handler, handlers that get
687    * >   registered next (again, if any) can override that decision.
688    *
689    * Returns: a #GST_TYPE_AUTOPLUG_SELECT_RESULT that indicates the required
690    * operation. The default handler will always return
691    * #GST_AUTOPLUG_SELECT_TRY.
692    */
693   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT] =
694       g_signal_new ("autoplug-select", G_TYPE_FROM_CLASS (klass),
695       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass,
696           autoplug_select), _gst_select_accumulator, NULL,
697       g_cclosure_marshal_generic,
698       GST_TYPE_AUTOPLUG_SELECT_RESULT, 3, GST_TYPE_PAD, GST_TYPE_CAPS,
699       GST_TYPE_ELEMENT_FACTORY);
700 
701   /**
702    * GstDecodeBin::autoplug-query:
703    * @bin: The decodebin.
704    * @child: The child element doing the query
705    * @pad: The #GstPad.
706    * @query: The #GstQuery.
707    *
708    * This signal is emitted whenever an autoplugged element that is
709    * not linked downstream yet and not exposed does a query. It can
710    * be used to tell the element about the downstream supported caps
711    * for example.
712    *
713    * Returns: %TRUE if the query was handled, %FALSE otherwise.
714    */
715   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_QUERY] =
716       g_signal_new ("autoplug-query", G_TYPE_FROM_CLASS (klass),
717       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass, autoplug_query),
718       _gst_boolean_or_accumulator, NULL, g_cclosure_marshal_generic,
719       G_TYPE_BOOLEAN, 3, GST_TYPE_PAD, GST_TYPE_ELEMENT,
720       GST_TYPE_QUERY | G_SIGNAL_TYPE_STATIC_SCOPE);
721 
722   /**
723    * GstURIDecodeBin::drained:
724    *
725    * This signal is emitted when the data for the current uri is played.
726    */
727   gst_uri_decode_bin_signals[SIGNAL_DRAINED] =
728       g_signal_new ("drained", G_TYPE_FROM_CLASS (klass),
729       G_SIGNAL_RUN_LAST,
730       G_STRUCT_OFFSET (GstURIDecodeBinClass, drained), NULL, NULL,
731       g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
732 
733   /**
734    * GstURIDecodeBin::source-setup:
735    * @bin: the uridecodebin.
736    * @source: source element
737    *
738    * This signal is emitted after the source element has been created, so
739    * it can be configured by setting additional properties (e.g. set a
740    * proxy server for an http source, or set the device and read speed for
741    * an audio cd source). This is functionally equivalent to connecting to
742    * the notify::source signal, but more convenient.
743    */
744   gst_uri_decode_bin_signals[SIGNAL_SOURCE_SETUP] =
745       g_signal_new ("source-setup", G_TYPE_FROM_CLASS (klass),
746       G_SIGNAL_RUN_LAST, 0, NULL, NULL,
747       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
748 
749   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
750   gst_element_class_set_static_metadata (gstelement_class,
751       "URI Decoder", "Generic/Bin/Decoder",
752       "Autoplug and decode an URI to raw media",
753       "Wim Taymans <wim.taymans@gmail.com>");
754 
755   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_uri_decode_bin_query);
756   gstelement_class->change_state =
757       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_change_state);
758 
759   gstbin_class->handle_message = GST_DEBUG_FUNCPTR (handle_message);
760 
761   klass->autoplug_continue =
762       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_continue);
763   klass->autoplug_factories =
764       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_factories);
765   klass->autoplug_sort = GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_sort);
766   klass->autoplug_select =
767       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_select);
768   klass->autoplug_query = GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_query);
769 }
770 
771 static void
gst_uri_decode_bin_init(GstURIDecodeBin * dec)772 gst_uri_decode_bin_init (GstURIDecodeBin * dec)
773 {
774   /* first filter out the interesting element factories */
775   g_mutex_init (&dec->factories_lock);
776 
777   g_mutex_init (&dec->lock);
778 
779   dec->uri = g_strdup (DEFAULT_PROP_URI);
780   dec->connection_speed = DEFAULT_CONNECTION_SPEED;
781   dec->caps = DEFAULT_CAPS;
782   dec->encoding = g_strdup (DEFAULT_SUBTITLE_ENCODING);
783 
784   dec->buffer_duration = DEFAULT_BUFFER_DURATION;
785   dec->buffer_size = DEFAULT_BUFFER_SIZE;
786   dec->download = DEFAULT_DOWNLOAD;
787   dec->use_buffering = DEFAULT_USE_BUFFERING;
788   dec->expose_allstreams = DEFAULT_EXPOSE_ALL_STREAMS;
789   dec->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
790 
791 #ifdef OHOS_EXT_FUNC
792   // ohos.ext.func.0012
793   dec->low_percent = DEFAULT_LOW_PERCENT;
794   dec->high_percent = DEFAULT_HIGH_PERCENT;
795 #endif
796 
797   GST_OBJECT_FLAG_SET (dec, GST_ELEMENT_FLAG_SOURCE);
798   gst_bin_set_suppressed_flags (GST_BIN (dec),
799       GST_ELEMENT_FLAG_SOURCE | GST_ELEMENT_FLAG_SINK);
800 }
801 
802 static void
gst_uri_decode_bin_finalize(GObject * obj)803 gst_uri_decode_bin_finalize (GObject * obj)
804 {
805   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (obj);
806 
807   remove_decoders (dec, TRUE);
808   g_mutex_clear (&dec->lock);
809   g_mutex_clear (&dec->factories_lock);
810   g_free (dec->uri);
811   g_free (dec->encoding);
812   if (dec->factories)
813     gst_plugin_feature_list_free (dec->factories);
814   if (dec->caps)
815     gst_caps_unref (dec->caps);
816 
817   G_OBJECT_CLASS (parent_class)->finalize (obj);
818 }
819 
820 static void
gst_uri_decode_bin_set_encoding(GstURIDecodeBin * dec,const gchar * encoding)821 gst_uri_decode_bin_set_encoding (GstURIDecodeBin * dec, const gchar * encoding)
822 {
823   GSList *walk;
824 
825   GST_URI_DECODE_BIN_LOCK (dec);
826 
827   /* set property first */
828   GST_OBJECT_LOCK (dec);
829   g_free (dec->encoding);
830   dec->encoding = g_strdup (encoding);
831   GST_OBJECT_UNLOCK (dec);
832 
833   /* set the property on all decodebins now */
834   for (walk = dec->decodebins; walk; walk = g_slist_next (walk)) {
835     GObject *decodebin = G_OBJECT (walk->data);
836 
837     g_object_set (decodebin, "subtitle-encoding", encoding, NULL);
838   }
839   GST_URI_DECODE_BIN_UNLOCK (dec);
840 }
841 
842 #ifdef OHOS_EXT_FUNC
843 // ohos.ext.func.0012
844 static void
set_property_to_decodebin(GstURIDecodeBin * dec,guint property_id,const void * property_value)845 set_property_to_decodebin (GstURIDecodeBin *dec, guint property_id, const void *property_value)
846 {
847   if (dec->decodebins == NULL) {
848     return;
849   }
850 
851   GSList *walk = NULL;
852   for (walk = dec->decodebins; walk;  walk = g_slist_next (walk)) {
853     if (walk->data == NULL) {
854       continue;
855     }
856     GObject *decodebin = G_OBJECT (walk->data);
857 
858     if (property_id == PROP_TIMEOUT) {
859       const guint *timeout = (const guint *) property_value;
860       g_object_set (decodebin, "timeout", *timeout, NULL);
861     } else if (property_id == PROP_STATE_CHANGE) {
862       const gint *state = (const gint *) property_value;
863       g_object_set (decodebin, "state-change", *state, NULL);
864     } else if (property_id == PROP_EXIT_BLOCK) {
865       const gint *exit_block = (const gint *) property_value;
866       g_object_set (decodebin, "exit-block", *exit_block, NULL);
867     }
868   }
869 }
870 #endif
871 
872 static void
gst_uri_decode_bin_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)873 gst_uri_decode_bin_set_property (GObject * object, guint prop_id,
874     const GValue * value, GParamSpec * pspec)
875 {
876   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (object);
877 
878   switch (prop_id) {
879     case PROP_URI:
880       GST_OBJECT_LOCK (dec);
881       g_free (dec->uri);
882       dec->uri = g_value_dup_string (value);
883       GST_OBJECT_UNLOCK (dec);
884       break;
885     case PROP_CONNECTION_SPEED:
886       GST_OBJECT_LOCK (dec);
887       dec->connection_speed = g_value_get_uint64 (value) * 1000;
888       GST_OBJECT_UNLOCK (dec);
889       break;
890     case PROP_CAPS:
891       GST_OBJECT_LOCK (dec);
892       if (dec->caps)
893         gst_caps_unref (dec->caps);
894       dec->caps = g_value_dup_boxed (value);
895       GST_OBJECT_UNLOCK (dec);
896       break;
897     case PROP_SUBTITLE_ENCODING:
898       gst_uri_decode_bin_set_encoding (dec, g_value_get_string (value));
899       break;
900     case PROP_BUFFER_SIZE:
901       dec->buffer_size = g_value_get_int (value);
902       break;
903     case PROP_BUFFER_DURATION:
904 #ifdef OHOS_EXT_FUNC
905       // ohos.ext.func.0012
906       dec->buffer_duration = g_value_get_uint64 (value);
907 #else
908       dec->buffer_duration = g_value_get_int64 (value);
909 #endif
910       break;
911     case PROP_DOWNLOAD:
912       dec->download = g_value_get_boolean (value);
913       break;
914     case PROP_USE_BUFFERING:
915       dec->use_buffering = g_value_get_boolean (value);
916       break;
917     case PROP_EXPOSE_ALL_STREAMS:
918       dec->expose_allstreams = g_value_get_boolean (value);
919       break;
920     case PROP_RING_BUFFER_MAX_SIZE:
921       dec->ring_buffer_max_size = g_value_get_uint64 (value);
922       break;
923 #ifdef OHOS_EXT_FUNC
924     // ohos.ext.func.0012
925     case PROP_TIMEOUT: {
926       guint timeout = g_value_get_uint (value);
927       g_object_set (dec->source, "timeout", timeout, NULL);
928       set_property_to_decodebin(dec, prop_id, (void *)&timeout);
929       break;
930     }
931     case PROP_STATE_CHANGE: {
932       gint state = g_value_get_int (value);
933       g_object_set (dec->source, "state-change", state, NULL);
934       set_property_to_decodebin(dec, prop_id, (void *)&state);
935       break;
936     }
937     case PROP_EXIT_BLOCK: {
938       gint exit_block = g_value_get_int (value);
939       g_object_set (dec->source, "exit-block", exit_block, NULL);
940       set_property_to_decodebin(dec, prop_id, (void *)&exit_block);
941       break;
942     }
943     case PROP_LOW_PERCENT:
944       dec->low_percent = g_value_get_int (value);
945       GST_INFO_OBJECT (dec, "gsturidecbin set property low_percent=%d", dec->low_percent);
946       break;
947     case PROP_HIGH_PERCENT:
948       dec->high_percent = g_value_get_int (value);
949       GST_INFO_OBJECT (dec, "gsturidecbin set property high_percent=%d", dec->high_percent);
950       break;
951 #endif
952     default:
953       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
954       break;
955   }
956 }
957 
958 static void
gst_uri_decode_bin_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)959 gst_uri_decode_bin_get_property (GObject * object, guint prop_id,
960     GValue * value, GParamSpec * pspec)
961 {
962   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (object);
963 
964   switch (prop_id) {
965     case PROP_URI:
966       GST_OBJECT_LOCK (dec);
967       g_value_set_string (value, dec->uri);
968       GST_OBJECT_UNLOCK (dec);
969       break;
970     case PROP_SOURCE:
971       GST_OBJECT_LOCK (dec);
972       g_value_set_object (value, dec->source);
973       GST_OBJECT_UNLOCK (dec);
974       break;
975     case PROP_CONNECTION_SPEED:
976       GST_OBJECT_LOCK (dec);
977       g_value_set_uint64 (value, dec->connection_speed / 1000);
978       GST_OBJECT_UNLOCK (dec);
979       break;
980     case PROP_CAPS:
981       GST_OBJECT_LOCK (dec);
982       g_value_set_boxed (value, dec->caps);
983       GST_OBJECT_UNLOCK (dec);
984       break;
985     case PROP_SUBTITLE_ENCODING:
986       GST_OBJECT_LOCK (dec);
987       g_value_set_string (value, dec->encoding);
988       GST_OBJECT_UNLOCK (dec);
989       break;
990     case PROP_BUFFER_SIZE:
991       GST_OBJECT_LOCK (dec);
992       g_value_set_int (value, dec->buffer_size);
993       GST_OBJECT_UNLOCK (dec);
994       break;
995     case PROP_BUFFER_DURATION:
996       GST_OBJECT_LOCK (dec);
997 #ifdef OHOS_EXT_FUNC
998       // ohos.ext.func.0012
999       g_value_set_uint64 (value, dec->buffer_duration);
1000 #else
1001       g_value_set_int64 (value, dec->buffer_duration);
1002 #endif
1003       GST_OBJECT_UNLOCK (dec);
1004       break;
1005     case PROP_DOWNLOAD:
1006       g_value_set_boolean (value, dec->download);
1007       break;
1008     case PROP_USE_BUFFERING:
1009       g_value_set_boolean (value, dec->use_buffering);
1010       break;
1011     case PROP_EXPOSE_ALL_STREAMS:
1012       g_value_set_boolean (value, dec->expose_allstreams);
1013       break;
1014     case PROP_RING_BUFFER_MAX_SIZE:
1015       g_value_set_uint64 (value, dec->ring_buffer_max_size);
1016       break;
1017 #ifdef OHOS_EXT_FUNC
1018     // ohos.ext.func.0012
1019     case PROP_LOW_PERCENT:
1020       g_value_set_int (value, dec->low_percent);
1021       break;
1022     case PROP_HIGH_PERCENT:
1023       g_value_set_int (value, dec->high_percent);
1024       break;
1025 #endif
1026     default:
1027       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1028       break;
1029   }
1030 }
1031 
1032 static void
do_async_start(GstURIDecodeBin * dbin)1033 do_async_start (GstURIDecodeBin * dbin)
1034 {
1035   GstMessage *message;
1036 
1037   dbin->async_pending = TRUE;
1038 
1039   message = gst_message_new_async_start (GST_OBJECT_CAST (dbin));
1040   GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST (dbin), message);
1041 }
1042 
1043 static void
do_async_done(GstURIDecodeBin * dbin)1044 do_async_done (GstURIDecodeBin * dbin)
1045 {
1046   GstMessage *message;
1047 
1048   if (dbin->async_pending) {
1049     GST_DEBUG_OBJECT (dbin, "posting ASYNC_DONE");
1050     message =
1051         gst_message_new_async_done (GST_OBJECT_CAST (dbin),
1052         GST_CLOCK_TIME_NONE);
1053     GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST (dbin), message);
1054 
1055     dbin->async_pending = FALSE;
1056   }
1057 }
1058 
1059 #define DEFAULT_QUEUE_SIZE          (3 * GST_SECOND)
1060 #define DEFAULT_QUEUE_MIN_THRESHOLD ((DEFAULT_QUEUE_SIZE * 30) / 100)
1061 #define DEFAULT_QUEUE_THRESHOLD     ((DEFAULT_QUEUE_SIZE * 95) / 100)
1062 
1063 static void
unknown_type_cb(GstElement * element,GstPad * pad,GstCaps * caps,GstURIDecodeBin * decoder)1064 unknown_type_cb (GstElement * element, GstPad * pad, GstCaps * caps,
1065     GstURIDecodeBin * decoder)
1066 {
1067   gchar *capsstr;
1068 
1069   capsstr = gst_caps_to_string (caps);
1070   GST_ELEMENT_WARNING (decoder, STREAM, CODEC_NOT_FOUND,
1071       (_("No decoder available for type \'%s\'."), capsstr), (NULL));
1072   g_free (capsstr);
1073 }
1074 
1075 /* add a streaminfo that indicates that the stream is handled by the
1076  * given element. This usually means that a stream without actual data is
1077  * produced but one that is sunken by an element. Examples of this are:
1078  * cdaudio, a hardware decoder/sink, dvd meta bins etc...
1079  */
1080 static void
add_element_stream(GstElement * element,GstURIDecodeBin * decoder)1081 add_element_stream (GstElement * element, GstURIDecodeBin * decoder)
1082 {
1083   g_warning ("add element stream");
1084 }
1085 
1086 /* when the decoder element signals that no more pads will be generated, we
1087  * can commit the current group.
1088  */
1089 static void
no_more_pads_full(GstElement * element,gboolean subs,GstURIDecodeBin * decoder)1090 no_more_pads_full (GstElement * element, gboolean subs,
1091     GstURIDecodeBin * decoder)
1092 {
1093   gboolean final;
1094 
1095   /* setup phase */
1096   GST_DEBUG_OBJECT (element, "no more pads, %d pending", decoder->pending);
1097 
1098   GST_URI_DECODE_BIN_LOCK (decoder);
1099   final = (decoder->pending == 0);
1100 
1101   /* nothing pending, we can exit */
1102   if (final)
1103     goto done;
1104 
1105   /* the object has no pending no_more_pads */
1106   if (!g_object_get_data (G_OBJECT (element), "pending"))
1107     goto done;
1108   g_object_set_data (G_OBJECT (element), "pending", NULL);
1109 
1110   decoder->pending--;
1111   final = (decoder->pending == 0);
1112 
1113 done:
1114   GST_URI_DECODE_BIN_UNLOCK (decoder);
1115 
1116   if (final) {
1117     /* If we got not a single stream yet, that means that all
1118      * decodebins had missing plugins for all of their streams!
1119      */
1120     if (!decoder->streams || g_hash_table_size (decoder->streams) == 0) {
1121       if (decoder->missing_plugin_errors) {
1122         GString *str = g_string_new ("");
1123         GList *l;
1124 
1125         for (l = decoder->missing_plugin_errors; l; l = l->next) {
1126           GstMessage *msg = l->data;
1127           gchar *debug;
1128 
1129           gst_message_parse_error (msg, NULL, &debug);
1130           g_string_append (str, debug);
1131           g_free (debug);
1132           gst_message_unref (msg);
1133         }
1134         g_list_free (decoder->missing_plugin_errors);
1135         decoder->missing_plugin_errors = NULL;
1136 
1137         GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
1138             ("no suitable plugins found:\n%s", str->str));
1139         g_string_free (str, TRUE);
1140       } else {
1141         GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
1142             ("no suitable plugins found"));
1143       }
1144     } else {
1145       gst_element_no_more_pads (GST_ELEMENT_CAST (decoder));
1146     }
1147     do_async_done (decoder);
1148   }
1149 
1150   return;
1151 }
1152 
1153 static void
no_more_pads(GstElement * element,GstURIDecodeBin * decoder)1154 no_more_pads (GstElement * element, GstURIDecodeBin * decoder)
1155 {
1156   no_more_pads_full (element, FALSE, decoder);
1157 }
1158 
1159 static void
source_no_more_pads(GstElement * element,GstURIDecodeBin * bin)1160 source_no_more_pads (GstElement * element, GstURIDecodeBin * bin)
1161 {
1162   GST_DEBUG_OBJECT (bin, "No more pads in source element %s.",
1163       GST_ELEMENT_NAME (element));
1164 
1165   g_signal_handler_disconnect (element, bin->src_np_sig_id);
1166   bin->src_np_sig_id = 0;
1167   g_signal_handler_disconnect (element, bin->src_nmp_sig_id);
1168   bin->src_nmp_sig_id = 0;
1169 
1170   no_more_pads_full (element, FALSE, bin);
1171 }
1172 
1173 static void
configure_stream_buffering(GstURIDecodeBin * decoder)1174 configure_stream_buffering (GstURIDecodeBin * decoder)
1175 {
1176   GstElement *queue = NULL;
1177   GHashTableIter iter;
1178   gpointer key, value;
1179   gint bitrate = 0;
1180 
1181   /* automatic configuration enabled ? */
1182   if (decoder->buffer_size != -1)
1183     return;
1184 
1185   GST_URI_DECODE_BIN_LOCK (decoder);
1186   if (decoder->queue)
1187     queue = gst_object_ref (decoder->queue);
1188 
1189   g_hash_table_iter_init (&iter, decoder->streams);
1190   while (g_hash_table_iter_next (&iter, &key, &value)) {
1191     GstURIDecodeBinStream *stream = value;
1192 
1193     if (stream->bitrate && bitrate >= 0)
1194       bitrate += stream->bitrate;
1195     else
1196       bitrate = -1;
1197   }
1198   GST_URI_DECODE_BIN_UNLOCK (decoder);
1199 
1200   GST_DEBUG_OBJECT (decoder, "overall bitrate %d", bitrate);
1201   if (!queue)
1202     return;
1203 
1204   if (bitrate > 0) {
1205     guint64 time;
1206     guint bytes;
1207 
1208     /* all streams have a bitrate;
1209      * configure queue size based on queue duration using combined bitrate */
1210     g_object_get (queue, "max-size-time", &time, NULL);
1211     GST_DEBUG_OBJECT (decoder, "queue buffering time %" GST_TIME_FORMAT,
1212         GST_TIME_ARGS (time));
1213     if (time > 0) {
1214       bytes = gst_util_uint64_scale (time, bitrate, 8 * GST_SECOND);
1215       GST_DEBUG_OBJECT (decoder, "corresponds to buffer size %d", bytes);
1216       g_object_set (queue, "max-size-bytes", bytes, NULL);
1217     }
1218   }
1219 
1220   gst_object_unref (queue);
1221 }
1222 
1223 static GstPadProbeReturn
decoded_pad_event_probe(GstPad * pad,GstPadProbeInfo * info,gpointer user_data)1224 decoded_pad_event_probe (GstPad * pad, GstPadProbeInfo * info,
1225     gpointer user_data)
1226 {
1227   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
1228   GstURIDecodeBin *decoder = user_data;
1229 
1230   GST_LOG_OBJECT (pad, "%s, decoder %p", GST_EVENT_TYPE_NAME (event), decoder);
1231 
1232   /* look for a bitrate tag */
1233   switch (GST_EVENT_TYPE (event)) {
1234     case GST_EVENT_TAG:
1235     {
1236       GstTagList *list;
1237       guint bitrate = 0;
1238       GstURIDecodeBinStream *stream;
1239 
1240       gst_event_parse_tag (event, &list);
1241       if (!gst_tag_list_get_uint_index (list, GST_TAG_NOMINAL_BITRATE, 0,
1242               &bitrate)) {
1243         gst_tag_list_get_uint_index (list, GST_TAG_BITRATE, 0, &bitrate);
1244       }
1245       GST_DEBUG_OBJECT (pad, "found bitrate %u", bitrate);
1246       if (bitrate) {
1247         GST_URI_DECODE_BIN_LOCK (decoder);
1248         stream = g_hash_table_lookup (decoder->streams, pad);
1249         GST_URI_DECODE_BIN_UNLOCK (decoder);
1250         if (stream) {
1251           stream->bitrate = bitrate;
1252           /* no longer need this probe now */
1253           gst_pad_remove_probe (pad, stream->probe_id);
1254           /* configure buffer if possible */
1255           configure_stream_buffering (decoder);
1256         }
1257       }
1258       break;
1259     }
1260     default:
1261       break;
1262   }
1263 
1264   /* never drop */
1265   return GST_PAD_PROBE_OK;
1266 }
1267 
1268 
1269 static gboolean
copy_sticky_events(GstPad * pad,GstEvent ** event,gpointer user_data)1270 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
1271 {
1272   GstPad *gpad = GST_PAD_CAST (user_data);
1273 
1274   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
1275   gst_pad_store_sticky_event (gpad, *event);
1276 
1277   return TRUE;
1278 }
1279 
1280 /* Called by the signal handlers when a decodebin has found a new raw pad */
1281 static void
new_decoded_pad_added_cb(GstElement * element,GstPad * pad,GstURIDecodeBin * decoder)1282 new_decoded_pad_added_cb (GstElement * element, GstPad * pad,
1283     GstURIDecodeBin * decoder)
1284 {
1285   GstPad *newpad;
1286   GstPadTemplate *pad_tmpl;
1287   gchar *padname;
1288   GstURIDecodeBinStream *stream;
1289 
1290   GST_DEBUG_OBJECT (element, "new decoded pad, name: <%s>", GST_PAD_NAME (pad));
1291 
1292   GST_URI_DECODE_BIN_LOCK (decoder);
1293   padname = g_strdup_printf ("src_%u", decoder->numpads);
1294   decoder->numpads++;
1295   GST_URI_DECODE_BIN_UNLOCK (decoder);
1296 
1297   pad_tmpl = gst_static_pad_template_get (&srctemplate);
1298   newpad = gst_ghost_pad_new_from_template (padname, pad, pad_tmpl);
1299   gst_object_unref (pad_tmpl);
1300   g_free (padname);
1301 
1302   /* store ref to the ghostpad so we can remove it */
1303   g_object_set_data (G_OBJECT (pad), "uridecodebin.ghostpad", newpad);
1304 
1305   /* add event probe to monitor tags */
1306   stream = g_slice_alloc0 (sizeof (GstURIDecodeBinStream));
1307   stream->probe_id =
1308       gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
1309       decoded_pad_event_probe, decoder, NULL);
1310   GST_URI_DECODE_BIN_LOCK (decoder);
1311   g_hash_table_insert (decoder->streams, pad, stream);
1312   GST_URI_DECODE_BIN_UNLOCK (decoder);
1313 
1314   gst_pad_set_active (newpad, TRUE);
1315   gst_pad_sticky_events_foreach (pad, copy_sticky_events, newpad);
1316   gst_element_add_pad (GST_ELEMENT_CAST (decoder), newpad);
1317 }
1318 
1319 static GstPadProbeReturn
source_pad_event_probe(GstPad * pad,GstPadProbeInfo * info,gpointer user_data)1320 source_pad_event_probe (GstPad * pad, GstPadProbeInfo * info,
1321     gpointer user_data)
1322 {
1323   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
1324   GstURIDecodeBin *decoder = user_data;
1325 
1326   GST_LOG_OBJECT (pad, "%s, decoder %p", GST_EVENT_TYPE_NAME (event), decoder);
1327 
1328   if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
1329     GST_DEBUG_OBJECT (pad, "we received EOS");
1330 
1331     g_signal_emit (decoder,
1332         gst_uri_decode_bin_signals[SIGNAL_DRAINED], 0, NULL);
1333   }
1334   /* never drop events */
1335   return GST_PAD_PROBE_OK;
1336 }
1337 
1338 /* called when we found a raw pad on the source element. We need to set up a
1339  * padprobe to detect EOS before exposing the pad. */
1340 static void
expose_decoded_pad(GstElement * element,GstPad * pad,GstURIDecodeBin * decoder)1341 expose_decoded_pad (GstElement * element, GstPad * pad,
1342     GstURIDecodeBin * decoder)
1343 {
1344   gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
1345       source_pad_event_probe, decoder, NULL);
1346 
1347   new_decoded_pad_added_cb (element, pad, decoder);
1348 }
1349 
1350 static void
pad_removed_cb(GstElement * element,GstPad * pad,GstURIDecodeBin * decoder)1351 pad_removed_cb (GstElement * element, GstPad * pad, GstURIDecodeBin * decoder)
1352 {
1353   GstPad *ghost;
1354 
1355   GST_DEBUG_OBJECT (element, "pad removed name: <%s:%s>",
1356       GST_DEBUG_PAD_NAME (pad));
1357 
1358   /* we only care about srcpads */
1359   if (!GST_PAD_IS_SRC (pad))
1360     return;
1361 
1362   if (!(ghost = g_object_get_data (G_OBJECT (pad), "uridecodebin.ghostpad")))
1363     goto no_ghost;
1364 
1365   /* unghost the pad */
1366   gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (ghost), NULL);
1367 
1368   /* deactivate and remove */
1369   gst_pad_set_active (pad, FALSE);
1370   gst_element_remove_pad (GST_ELEMENT_CAST (decoder), ghost);
1371 
1372   return;
1373 
1374   /* ERRORS */
1375 no_ghost:
1376   {
1377     GST_WARNING_OBJECT (element, "no ghost pad found");
1378     return;
1379   }
1380 }
1381 
1382 /* helper function to lookup stuff in lists */
1383 static gboolean
array_has_value(const gchar * values[],const gchar * value)1384 array_has_value (const gchar * values[], const gchar * value)
1385 {
1386   gint i;
1387 
1388   for (i = 0; values[i]; i++) {
1389     if (g_str_has_prefix (value, values[i]))
1390       return TRUE;
1391   }
1392   return FALSE;
1393 }
1394 
1395 static gboolean
array_has_uri_value(const gchar * values[],const gchar * value)1396 array_has_uri_value (const gchar * values[], const gchar * value)
1397 {
1398   gint i;
1399 
1400   for (i = 0; values[i]; i++) {
1401     if (!g_ascii_strncasecmp (value, values[i], strlen (values[i])))
1402       return TRUE;
1403   }
1404   return FALSE;
1405 }
1406 
1407 /* list of URIs that we consider to be streams and that need buffering.
1408  * We have no mechanism yet to figure this out with a query. */
1409 static const gchar *stream_uris[] = { "http://", "https://", "mms://",
1410   "mmsh://", "mmsu://", "mmst://", "fd://", "myth://", "ssh://",
1411   "ftp://", "sftp://",
1412   NULL
1413 };
1414 
1415 /* list of URIs that need a queue because they are pretty bursty */
1416 static const gchar *queue_uris[] = { "cdda://", NULL };
1417 
1418 /* blacklisted URIs, we know they will always fail. */
1419 static const gchar *blacklisted_uris[] = { NULL };
1420 
1421 /* media types that use adaptive streaming */
1422 static const gchar *adaptive_media[] = {
1423   "application/x-hls", "application/vnd.ms-sstr+xml",
1424   "application/dash+xml", NULL
1425 };
1426 
1427 #define IS_STREAM_URI(uri)          (array_has_uri_value (stream_uris, uri))
1428 #define IS_QUEUE_URI(uri)           (array_has_uri_value (queue_uris, uri))
1429 #define IS_BLACKLISTED_URI(uri)     (array_has_uri_value (blacklisted_uris, uri))
1430 #define IS_ADAPTIVE_MEDIA(media)    (array_has_value (adaptive_media, media))
1431 
1432 /*
1433  * Generate and configure a source element.
1434  */
1435 static GstElement *
gen_source_element(GstURIDecodeBin * decoder)1436 gen_source_element (GstURIDecodeBin * decoder)
1437 {
1438   GObjectClass *source_class;
1439   GstElement *source;
1440   GParamSpec *pspec;
1441   GstQuery *query;
1442   GstSchedulingFlags flags;
1443   GError *err = NULL;
1444 
1445   if (!decoder->uri)
1446     goto no_uri;
1447 
1448   GST_LOG_OBJECT (decoder, "finding source for %s", decoder->uri);
1449 
1450   if (!gst_uri_is_valid (decoder->uri))
1451     goto invalid_uri;
1452 
1453   if (IS_BLACKLISTED_URI (decoder->uri))
1454     goto uri_blacklisted;
1455 
1456   source =
1457       gst_element_make_from_uri (GST_URI_SRC, decoder->uri, "source", &err);
1458   if (!source)
1459     goto no_source;
1460 
1461   GST_LOG_OBJECT (decoder, "found source type %s", G_OBJECT_TYPE_NAME (source));
1462 
1463   query = gst_query_new_scheduling ();
1464   if (gst_element_query (source, query)) {
1465     gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
1466     decoder->is_stream = flags & GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
1467   } else
1468     decoder->is_stream = IS_STREAM_URI (decoder->uri);
1469   gst_query_unref (query);
1470 
1471   GST_LOG_OBJECT (decoder, "source is stream: %d", decoder->is_stream);
1472 
1473   decoder->need_queue = IS_QUEUE_URI (decoder->uri);
1474   GST_LOG_OBJECT (decoder, "source needs queue: %d", decoder->need_queue);
1475 
1476   source_class = G_OBJECT_GET_CLASS (source);
1477 
1478   pspec = g_object_class_find_property (source_class, "connection-speed");
1479   if (pspec != NULL) {
1480     guint64 speed = decoder->connection_speed / 1000;
1481     gboolean wrong_type = FALSE;
1482 
1483     if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_UINT) {
1484       GParamSpecUInt *pspecuint = G_PARAM_SPEC_UINT (pspec);
1485 
1486       speed = CLAMP (speed, pspecuint->minimum, pspecuint->maximum);
1487     } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_INT) {
1488       GParamSpecInt *pspecint = G_PARAM_SPEC_INT (pspec);
1489 
1490       speed = CLAMP (speed, pspecint->minimum, pspecint->maximum);
1491     } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_UINT64) {
1492       GParamSpecUInt64 *pspecuint = G_PARAM_SPEC_UINT64 (pspec);
1493 
1494       speed = CLAMP (speed, pspecuint->minimum, pspecuint->maximum);
1495     } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_INT64) {
1496       GParamSpecInt64 *pspecint = G_PARAM_SPEC_INT64 (pspec);
1497 
1498       speed = CLAMP (speed, pspecint->minimum, pspecint->maximum);
1499     } else {
1500       GST_WARNING_OBJECT (decoder,
1501           "The connection speed property %" G_GUINT64_FORMAT
1502           " of type %s is not usefull not setting it", speed,
1503           g_type_name (G_PARAM_SPEC_TYPE (pspec)));
1504       wrong_type = TRUE;
1505     }
1506 
1507     if (!wrong_type) {
1508       g_object_set (source, "connection-speed", speed, NULL);
1509 
1510       GST_DEBUG_OBJECT (decoder,
1511           "setting connection-speed=%" G_GUINT64_FORMAT " to source element",
1512           speed);
1513     }
1514   }
1515 
1516   pspec = g_object_class_find_property (source_class, "subtitle-encoding");
1517   if (pspec != NULL && G_PARAM_SPEC_VALUE_TYPE (pspec) == G_TYPE_STRING) {
1518     GST_DEBUG_OBJECT (decoder,
1519         "setting subtitle-encoding=%s to source element", decoder->encoding);
1520     g_object_set (source, "subtitle-encoding", decoder->encoding, NULL);
1521   }
1522   return source;
1523 
1524   /* ERRORS */
1525 no_uri:
1526   {
1527     GST_ELEMENT_ERROR (decoder, RESOURCE, NOT_FOUND,
1528         (_("No URI specified to play from.")), (NULL));
1529     return NULL;
1530   }
1531 invalid_uri:
1532   {
1533     GST_ELEMENT_ERROR (decoder, RESOURCE, NOT_FOUND,
1534         (_("Invalid URI \"%s\"."), decoder->uri), (NULL));
1535     g_clear_error (&err);
1536     return NULL;
1537   }
1538 uri_blacklisted:
1539   {
1540     GST_ELEMENT_ERROR (decoder, RESOURCE, FAILED,
1541         (_("This stream type cannot be played yet.")), (NULL));
1542     return NULL;
1543   }
1544 no_source:
1545   {
1546     /* whoops, could not create the source element, dig a little deeper to
1547      * figure out what might be wrong. */
1548     if (err != NULL && err->code == GST_URI_ERROR_UNSUPPORTED_PROTOCOL) {
1549       gchar *prot;
1550 
1551       prot = gst_uri_get_protocol (decoder->uri);
1552       if (prot == NULL)
1553         goto invalid_uri;
1554 
1555       gst_element_post_message (GST_ELEMENT_CAST (decoder),
1556           gst_missing_uri_source_message_new (GST_ELEMENT (decoder), prot));
1557 
1558       GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN,
1559           (_("No URI handler implemented for \"%s\"."), prot), (NULL));
1560 
1561       g_free (prot);
1562     } else {
1563       GST_ELEMENT_ERROR (decoder, RESOURCE, NOT_FOUND,
1564           ("%s", (err) ? err->message : "URI was not accepted by any element"),
1565           ("No element accepted URI '%s'", decoder->uri));
1566     }
1567 
1568     g_clear_error (&err);
1569     return NULL;
1570   }
1571 }
1572 
1573 /**
1574  * has_all_raw_caps:
1575  * @pad: a #GstPad
1576  * @all_raw: pointer to hold the result
1577  *
1578  * check if the caps of the pad are all raw. The caps are all raw if
1579  * all of its structures contain audio/x-raw or video/x-raw.
1580  *
1581  * Returns: %FALSE @pad has no caps. Else TRUE and @all_raw set t the result.
1582  */
1583 static gboolean
has_all_raw_caps(GstPad * pad,GstCaps * rawcaps,gboolean * all_raw)1584 has_all_raw_caps (GstPad * pad, GstCaps * rawcaps, gboolean * all_raw)
1585 {
1586   GstCaps *caps, *intersection;
1587   gint capssize;
1588   gboolean res = FALSE;
1589 
1590   caps = gst_pad_query_caps (pad, NULL);
1591   if (caps == NULL)
1592     return FALSE;
1593 
1594   GST_DEBUG_OBJECT (pad, "have caps %" GST_PTR_FORMAT, caps);
1595 
1596   capssize = gst_caps_get_size (caps);
1597   /* no caps, skip and move to the next pad */
1598   if (capssize == 0 || gst_caps_is_empty (caps) || gst_caps_is_any (caps))
1599     goto done;
1600 
1601   intersection = gst_caps_intersect (caps, rawcaps);
1602   *all_raw = !gst_caps_is_empty (intersection)
1603       && (gst_caps_get_size (intersection) == capssize);
1604   gst_caps_unref (intersection);
1605 
1606   res = TRUE;
1607 
1608 done:
1609   gst_caps_unref (caps);
1610   return res;
1611 }
1612 
1613 static void
post_missing_plugin_error(GstElement * dec,const gchar * element_name)1614 post_missing_plugin_error (GstElement * dec, const gchar * element_name)
1615 {
1616   GstMessage *msg;
1617 
1618   msg = gst_missing_element_message_new (dec, element_name);
1619   gst_element_post_message (dec, msg);
1620 
1621   GST_ELEMENT_ERROR (dec, CORE, MISSING_PLUGIN,
1622       (_("Missing element '%s' - check your GStreamer installation."),
1623           element_name), (NULL));
1624   do_async_done (GST_URI_DECODE_BIN (dec));
1625 }
1626 
1627 /**
1628  * analyse_source:
1629  * @decoder: a #GstURIDecodeBin
1630  * @is_raw: are all pads raw data
1631  * @have_out: does the source have output
1632  * @is_dynamic: is this a dynamic source
1633  * @use_queue: put a queue before raw output pads
1634  *
1635  * Check the source of @decoder and collect information about it.
1636  *
1637  * @is_raw will be set to TRUE if the source only produces raw pads. When this
1638  * function returns, all of the raw pad of the source will be added
1639  * to @decoder.
1640  *
1641  * @have_out: will be set to TRUE if the source has output pads.
1642  *
1643  * @is_dynamic: TRUE if the element will create (more) pads dynamically later
1644  * on.
1645  *
1646  * Returns: FALSE if a fatal error occured while scanning.
1647  */
1648 static gboolean
analyse_source(GstURIDecodeBin * decoder,gboolean * is_raw,gboolean * have_out,gboolean * is_dynamic,gboolean use_queue)1649 analyse_source (GstURIDecodeBin * decoder, gboolean * is_raw,
1650     gboolean * have_out, gboolean * is_dynamic, gboolean use_queue)
1651 {
1652   GstIterator *pads_iter;
1653   gboolean done = FALSE;
1654   gboolean res = TRUE;
1655   GstCaps *rawcaps;
1656   GstPad *pad;
1657   GValue item = { 0, };
1658 
1659   *have_out = FALSE;
1660   *is_raw = FALSE;
1661   *is_dynamic = FALSE;
1662 
1663   g_object_get (decoder, "caps", &rawcaps, NULL);
1664   if (!rawcaps)
1665     rawcaps = DEFAULT_CAPS;
1666 
1667   pads_iter = gst_element_iterate_src_pads (decoder->source);
1668   while (!done) {
1669     switch (gst_iterator_next (pads_iter, &item)) {
1670       case GST_ITERATOR_ERROR:
1671         res = FALSE;
1672         /* FALLTROUGH */
1673       case GST_ITERATOR_DONE:
1674         done = TRUE;
1675         break;
1676       case GST_ITERATOR_RESYNC:
1677         /* reset results and resync */
1678         *have_out = FALSE;
1679         *is_raw = FALSE;
1680         *is_dynamic = FALSE;
1681         gst_iterator_resync (pads_iter);
1682         break;
1683       case GST_ITERATOR_OK:
1684         pad = g_value_dup_object (&item);
1685         /* we now officially have an ouput pad */
1686         *have_out = TRUE;
1687 
1688         /* if FALSE, this pad has no caps and we continue with the next pad. */
1689         if (!has_all_raw_caps (pad, rawcaps, is_raw)) {
1690           gst_object_unref (pad);
1691           g_value_reset (&item);
1692           break;
1693         }
1694 
1695         /* caps on source pad are all raw, we can add the pad */
1696         if (*is_raw) {
1697           GstElement *outelem;
1698 
1699           if (use_queue) {
1700             GstPad *sinkpad;
1701 
1702             /* insert a queue element right before the raw pad */
1703             outelem = gst_element_factory_make ("queue2", NULL);
1704             if (!outelem)
1705               goto no_queue2;
1706 
1707             gst_bin_add (GST_BIN_CAST (decoder), outelem);
1708 
1709             sinkpad = gst_element_get_static_pad (outelem, "sink");
1710             gst_pad_link (pad, sinkpad);
1711             gst_object_unref (sinkpad);
1712 
1713             /* save queue pointer so we can remove it later */
1714             decoder->queue = outelem;
1715 
1716             /* get the new raw srcpad */
1717             gst_object_unref (pad);
1718             pad = gst_element_get_static_pad (outelem, "src");
1719           } else {
1720             outelem = decoder->source;
1721           }
1722           expose_decoded_pad (outelem, pad, decoder);
1723         }
1724         gst_object_unref (pad);
1725         g_value_reset (&item);
1726         break;
1727     }
1728   }
1729   g_value_unset (&item);
1730   gst_iterator_free (pads_iter);
1731   gst_caps_unref (rawcaps);
1732 
1733   if (!*have_out) {
1734     GstElementClass *elemclass;
1735     GList *walk;
1736 
1737     /* element has no output pads, check for padtemplates that list SOMETIMES
1738      * pads. */
1739     elemclass = GST_ELEMENT_GET_CLASS (decoder->source);
1740 
1741     walk = gst_element_class_get_pad_template_list (elemclass);
1742     while (walk != NULL) {
1743       GstPadTemplate *templ;
1744 
1745       templ = (GstPadTemplate *) walk->data;
1746       if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SRC) {
1747         if (GST_PAD_TEMPLATE_PRESENCE (templ) == GST_PAD_SOMETIMES)
1748           *is_dynamic = TRUE;
1749         break;
1750       }
1751       walk = g_list_next (walk);
1752     }
1753   }
1754 
1755   return res;
1756 no_queue2:
1757   {
1758     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "queue2");
1759 
1760     gst_object_unref (pad);
1761     g_value_unset (&item);
1762     gst_iterator_free (pads_iter);
1763     gst_caps_unref (rawcaps);
1764 
1765     return FALSE;
1766   }
1767 }
1768 
1769 /* Remove all decodebin from ourself
1770  * If force is FALSE, then the decodebin instances will be stored in
1771  * pending_decodebins for re-use later on.
1772  * If force is TRUE, then all decodebin instances will be unreferenced
1773  * and cleared, including the pending ones. */
1774 static void
remove_decoders(GstURIDecodeBin * bin,gboolean force)1775 remove_decoders (GstURIDecodeBin * bin, gboolean force)
1776 {
1777   GSList *walk;
1778 
1779   for (walk = bin->decodebins; walk; walk = g_slist_next (walk)) {
1780     GstElement *decoder = GST_ELEMENT_CAST (walk->data);
1781 
1782     GST_DEBUG_OBJECT (bin, "removing old decoder element");
1783 
1784     /* Even if we reuse this decodebin, the previous topology will
1785      * be irrelevant */
1786     g_object_set_data (G_OBJECT (decoder), "uridecodebin-topology", NULL);
1787 
1788     if (force) {
1789       gst_element_set_state (decoder, GST_STATE_NULL);
1790       gst_bin_remove (GST_BIN_CAST (bin), decoder);
1791     } else {
1792       GstCaps *caps;
1793 
1794       gst_element_set_state (decoder, GST_STATE_READY);
1795       /* add it to our list of pending decodebins */
1796       g_object_ref (decoder);
1797       gst_bin_remove (GST_BIN_CAST (bin), decoder);
1798       /* restore some properties we might have changed */
1799       g_object_set (decoder, "sink-caps", NULL, NULL);
1800       caps = DEFAULT_CAPS;
1801       g_object_set (decoder, "caps", caps, NULL);
1802       gst_caps_unref (caps);
1803       /* make it freshly floating again */
1804       g_object_force_floating (G_OBJECT (decoder));
1805 
1806       bin->pending_decodebins =
1807           g_slist_prepend (bin->pending_decodebins, decoder);
1808     }
1809   }
1810   g_slist_free (bin->decodebins);
1811   bin->decodebins = NULL;
1812   if (force) {
1813     GSList *tmp;
1814 
1815     for (tmp = bin->pending_decodebins; tmp; tmp = tmp->next) {
1816       gst_element_set_state ((GstElement *) tmp->data, GST_STATE_NULL);
1817       gst_object_unref ((GstElement *) tmp->data);
1818     }
1819     g_slist_free (bin->pending_decodebins);
1820     bin->pending_decodebins = NULL;
1821 
1822   }
1823 }
1824 
1825 static void
proxy_unknown_type_signal(GstElement * decodebin,GstPad * pad,GstCaps * caps,GstURIDecodeBin * dec)1826 proxy_unknown_type_signal (GstElement * decodebin, GstPad * pad, GstCaps * caps,
1827     GstURIDecodeBin * dec)
1828 {
1829   GST_DEBUG_OBJECT (dec, "unknown-type signaled");
1830 
1831   g_signal_emit (dec,
1832       gst_uri_decode_bin_signals[SIGNAL_UNKNOWN_TYPE], 0, pad, caps);
1833 }
1834 
1835 static gboolean
proxy_autoplug_continue_signal(GstElement * decodebin,GstPad * pad,GstCaps * caps,GstURIDecodeBin * dec)1836 proxy_autoplug_continue_signal (GstElement * decodebin, GstPad * pad,
1837     GstCaps * caps, GstURIDecodeBin * dec)
1838 {
1839   gboolean result;
1840 
1841   g_signal_emit (dec,
1842       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, pad, caps,
1843       &result);
1844 
1845   GST_DEBUG_OBJECT (dec, "autoplug-continue returned %d", result);
1846 
1847   return result;
1848 }
1849 
1850 static GValueArray *
proxy_autoplug_factories_signal(GstElement * decodebin,GstPad * pad,GstCaps * caps,GstURIDecodeBin * dec)1851 proxy_autoplug_factories_signal (GstElement * decodebin, GstPad * pad,
1852     GstCaps * caps, GstURIDecodeBin * dec)
1853 {
1854   GValueArray *result;
1855 
1856   g_signal_emit (dec,
1857       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES], 0, pad, caps,
1858       &result);
1859 
1860   GST_DEBUG_OBJECT (dec, "autoplug-factories returned %p", result);
1861 
1862   return result;
1863 }
1864 
1865 static GValueArray *
proxy_autoplug_sort_signal(GstElement * decodebin,GstPad * pad,GstCaps * caps,GValueArray * factories,GstURIDecodeBin * dec)1866 proxy_autoplug_sort_signal (GstElement * decodebin, GstPad * pad,
1867     GstCaps * caps, GValueArray * factories, GstURIDecodeBin * dec)
1868 {
1869   GValueArray *result;
1870 
1871   g_signal_emit (dec,
1872       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SORT], 0, pad, caps,
1873       factories, &result);
1874 
1875   GST_DEBUG_OBJECT (dec, "autoplug-sort returned %p", result);
1876 
1877   return result;
1878 }
1879 
1880 static GstAutoplugSelectResult
proxy_autoplug_select_signal(GstElement * decodebin,GstPad * pad,GstCaps * caps,GstElementFactory * factory,GstURIDecodeBin * dec)1881 proxy_autoplug_select_signal (GstElement * decodebin, GstPad * pad,
1882     GstCaps * caps, GstElementFactory * factory, GstURIDecodeBin * dec)
1883 {
1884   GstAutoplugSelectResult result;
1885 
1886   g_signal_emit (dec,
1887       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT], 0, pad, caps, factory,
1888       &result);
1889 
1890   GST_DEBUG_OBJECT (dec, "autoplug-select returned %d", result);
1891 
1892   return result;
1893 }
1894 
1895 static gboolean
proxy_autoplug_query_signal(GstElement * decodebin,GstPad * pad,GstElement * element,GstQuery * query,GstURIDecodeBin * dec)1896 proxy_autoplug_query_signal (GstElement * decodebin, GstPad * pad,
1897     GstElement * element, GstQuery * query, GstURIDecodeBin * dec)
1898 {
1899   gboolean ret = FALSE;
1900 
1901   g_signal_emit (dec,
1902       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_QUERY], 0, pad, element, query,
1903       &ret);
1904 
1905   GST_DEBUG_OBJECT (dec, "autoplug-query returned %d", ret);
1906 
1907   return ret;
1908 }
1909 
1910 static void
proxy_drained_signal(GstElement * decodebin,GstURIDecodeBin * dec)1911 proxy_drained_signal (GstElement * decodebin, GstURIDecodeBin * dec)
1912 {
1913   GST_DEBUG_OBJECT (dec, "drained signaled");
1914 
1915   g_signal_emit (dec, gst_uri_decode_bin_signals[SIGNAL_DRAINED], 0, NULL);
1916 }
1917 
1918 #ifdef OHOS_EXT_FUNC
1919 // ohos.ext.func.0012
1920 static void
set_buffering_info(GstURIDecodeBin * decoder,GstElement * decodebin)1921 set_buffering_info (GstURIDecodeBin *decoder, GstElement *decodebin)
1922 {
1923   /* configure sizes when buffering */
1924   if (decoder->buffer_size == DEFAULT_BUFFER_SIZE) {
1925     decoder->buffer_size = 2 * 1024 * 1024; //2M
1926   }
1927 
1928   if (decoder->buffer_duration == DEFAULT_BUFFER_DURATION) {
1929     decoder->buffer_duration = 5 * GST_SECOND; //5s
1930   }
1931 
1932   g_object_set (decodebin, "max-size-bytes", decoder->buffer_size, "max-size-buffers",
1933       (guint) 0, "max-size-time", decoder->buffer_duration, NULL);
1934 
1935   g_object_set (decodebin, "low-percent", decoder->low_percent, "high-percent", decoder->high_percent, NULL);
1936 }
1937 #endif
1938 
1939 /* make a decodebin and connect to all the signals */
1940 static GstElement *
make_decoder(GstURIDecodeBin * decoder)1941 make_decoder (GstURIDecodeBin * decoder)
1942 {
1943   GstElement *decodebin;
1944 
1945   /* re-use pending decodebin */
1946   if (decoder->pending_decodebins) {
1947     GSList *first = decoder->pending_decodebins;
1948     GST_LOG_OBJECT (decoder, "re-using pending decodebin");
1949     decodebin = (GstElement *) first->data;
1950     decoder->pending_decodebins =
1951         g_slist_delete_link (decoder->pending_decodebins, first);
1952   } else {
1953     GST_LOG_OBJECT (decoder, "making new decodebin");
1954 
1955     /* now create the decoder element */
1956     decodebin = gst_element_factory_make ("decodebin", NULL);
1957 
1958     if (!decodebin)
1959       goto no_decodebin;
1960 
1961     /* sanity check */
1962     if (decodebin->numsinkpads == 0)
1963       goto no_typefind;
1964 
1965     /* connect signals to proxy */
1966     g_signal_connect (decodebin, "unknown-type",
1967         G_CALLBACK (proxy_unknown_type_signal), decoder);
1968     g_signal_connect (decodebin, "autoplug-continue",
1969         G_CALLBACK (proxy_autoplug_continue_signal), decoder);
1970     g_signal_connect (decodebin, "autoplug-factories",
1971         G_CALLBACK (proxy_autoplug_factories_signal), decoder);
1972     g_signal_connect (decodebin, "autoplug-sort",
1973         G_CALLBACK (proxy_autoplug_sort_signal), decoder);
1974     g_signal_connect (decodebin, "autoplug-select",
1975         G_CALLBACK (proxy_autoplug_select_signal), decoder);
1976     g_signal_connect (decodebin, "autoplug-query",
1977         G_CALLBACK (proxy_autoplug_query_signal), decoder);
1978     g_signal_connect (decodebin, "drained",
1979         G_CALLBACK (proxy_drained_signal), decoder);
1980 
1981     /* set up callbacks to create the links between decoded data
1982      * and video/audio/subtitle rendering/output. */
1983     g_signal_connect (decodebin,
1984         "pad-added", G_CALLBACK (new_decoded_pad_added_cb), decoder);
1985     g_signal_connect (decodebin,
1986         "pad-removed", G_CALLBACK (pad_removed_cb), decoder);
1987     g_signal_connect (decodebin, "no-more-pads",
1988         G_CALLBACK (no_more_pads), decoder);
1989     g_signal_connect (decodebin,
1990         "unknown-type", G_CALLBACK (unknown_type_cb), decoder);
1991   }
1992 
1993   /* configure caps if we have any */
1994   if (decoder->caps)
1995     g_object_set (decodebin, "caps", decoder->caps, NULL);
1996 
1997   /* Propagate expose-all-streams and connection-speed properties */
1998   g_object_set (decodebin, "expose-all-streams", decoder->expose_allstreams,
1999       "connection-speed", decoder->connection_speed / 1000, NULL);
2000 
2001 #ifdef OHOS_EXT_FUNC
2002   // ohos.ext.func.0012
2003   /*
2004    * modify for http buffering, If it is streaming, use buffering
2005    */
2006   if (!decoder->is_stream) {
2007     decoder->use_buffering = FALSE;
2008   }
2009   /*
2010    * propagate the use-buffering property but only when we are not already
2011    * doing stream buffering with queue2.
2012    */
2013   g_object_set (decodebin, "use-buffering", decoder->use_buffering, NULL);
2014   if (decoder->use_buffering) {
2015     set_buffering_info(decoder, decodebin);
2016   }
2017 #else
2018   if (!decoder->is_stream || decoder->is_adaptive) {
2019     /* propagate the use-buffering property but only when we are not already
2020      * doing stream buffering with queue2. FIXME, we might want to do stream
2021      * buffering with the multiqueue buffering instead of queue2. */
2022     g_object_set (decodebin, "use-buffering", decoder->use_buffering
2023         || decoder->is_adaptive, NULL);
2024 
2025     if (decoder->use_buffering || decoder->is_adaptive) {
2026       guint max_bytes;
2027       guint64 max_time;
2028 
2029       /* configure sizes when buffering */
2030       if ((max_bytes = decoder->buffer_size) == -1)
2031         max_bytes = 2 * 1024 * 1024;
2032       if ((max_time = decoder->buffer_duration) == -1)
2033         max_time = 5 * GST_SECOND;
2034 
2035       g_object_set (decodebin, "max-size-bytes", max_bytes, "max-size-buffers",
2036           (guint) 0, "max-size-time", max_time, NULL);
2037     }
2038   }
2039 #endif
2040 
2041   g_object_set_data (G_OBJECT (decodebin), "pending", GINT_TO_POINTER (1));
2042   g_object_set (decodebin, "subtitle-encoding", decoder->encoding, NULL);
2043   decoder->pending++;
2044   GST_LOG_OBJECT (decoder, "have %d pending dynamic objects", decoder->pending);
2045 
2046   gst_bin_add (GST_BIN_CAST (decoder), decodebin);
2047 
2048   decoder->decodebins = g_slist_prepend (decoder->decodebins, decodebin);
2049 
2050   return decodebin;
2051 
2052   /* ERRORS */
2053 no_decodebin:
2054   {
2055     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "decodebin");
2056     GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
2057         ("No decodebin element, check your installation"));
2058     do_async_done (decoder);
2059     return NULL;
2060   }
2061 no_typefind:
2062   {
2063     gst_object_unref (decodebin);
2064     GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
2065         ("No typefind element, decodebin is unusable, check your installation"));
2066     do_async_done (decoder);
2067     return NULL;
2068   }
2069 }
2070 
2071 /* signaled when we have a stream and we need to configure the download
2072  * buffering or regular buffering */
2073 static void
type_found(GstElement * typefind,guint probability,GstCaps * caps,GstURIDecodeBin * decoder)2074 type_found (GstElement * typefind, guint probability,
2075     GstCaps * caps, GstURIDecodeBin * decoder)
2076 {
2077   GstElement *src_elem, *dec_elem, *queue = NULL;
2078   GstStructure *s;
2079   const gchar *media_type, *elem_name;
2080   gboolean do_download = FALSE;
2081 
2082   GST_DEBUG_OBJECT (decoder, "typefind found caps %" GST_PTR_FORMAT, caps);
2083 
2084   s = gst_caps_get_structure (caps, 0);
2085   media_type = gst_structure_get_name (s);
2086 
2087   decoder->is_adaptive = IS_ADAPTIVE_MEDIA (media_type);
2088 
2089   /* only enable download buffering if the upstream duration is known */
2090   if (decoder->download) {
2091     gint64 dur;
2092 
2093     do_download = (gst_element_query_duration (typefind, GST_FORMAT_BYTES, &dur)
2094         && dur != -1);
2095   }
2096 
2097   dec_elem = make_decoder (decoder);
2098   if (!dec_elem)
2099     goto no_decodebin;
2100 
2101   if (decoder->is_adaptive) {
2102     src_elem = typefind;
2103   } else {
2104     if (do_download) {
2105       elem_name = "downloadbuffer";
2106     } else {
2107       elem_name = "queue2";
2108     }
2109     queue = gst_element_factory_make (elem_name, NULL);
2110     if (!queue)
2111       goto no_buffer_element;
2112 
2113     decoder->queue = queue;
2114 
2115     GST_DEBUG_OBJECT (decoder, "check media-type %s, %d", media_type,
2116         do_download);
2117 
2118     if (do_download) {
2119       gchar *temp_template, *filename;
2120       const gchar *tmp_dir, *prgname;
2121 
2122       tmp_dir = g_get_user_cache_dir ();
2123       prgname = g_get_prgname ();
2124       if (prgname == NULL)
2125         prgname = "GStreamer";
2126 
2127       filename = g_strdup_printf ("%s-XXXXXX", prgname);
2128 
2129       /* build our filename */
2130       temp_template = g_build_filename (tmp_dir, filename, NULL);
2131 
2132       GST_DEBUG_OBJECT (decoder, "enable download buffering in %s (%s, %s, %s)",
2133           temp_template, tmp_dir, prgname, filename);
2134 
2135       /* configure progressive download for selected media types */
2136       g_object_set (queue, "temp-template", temp_template, NULL);
2137 
2138       g_free (filename);
2139       g_free (temp_template);
2140     } else {
2141 #ifdef OHOS_EXT_FUNC
2142       // ohos.ext.func.0012
2143       /*
2144        * modify for http buffering, queue2 setting buffer is false by default
2145        */
2146       g_object_set (queue, "use-buffering", FALSE, NULL);
2147 #else
2148       g_object_set (queue, "use-buffering", TRUE, NULL);
2149 #endif
2150       g_object_set (queue, "ring-buffer-max-size",
2151           decoder->ring_buffer_max_size, NULL);
2152       /* Disable max-size-buffers */
2153       g_object_set (queue, "max-size-buffers", 0, NULL);
2154     }
2155 
2156 #ifndef OHOS_EXT_FUNC
2157     // ohos.ext.func.0012
2158     /* If buffer size or duration are set, set them on the element */
2159     if (decoder->buffer_size != -1)
2160       g_object_set (queue, "max-size-bytes", decoder->buffer_size, NULL);
2161     if (decoder->buffer_duration != -1)
2162       g_object_set (queue, "max-size-time", decoder->buffer_duration, NULL);
2163 #endif
2164 
2165     gst_bin_add (GST_BIN_CAST (decoder), queue);
2166 
2167     if (!gst_element_link_pads (typefind, "src", queue, "sink"))
2168       goto could_not_link;
2169     src_elem = queue;
2170   }
2171 
2172   /* to force caps on the decodebin element and avoid reparsing stuff by
2173    * typefind. It also avoids a deadlock in the way typefind activates pads in
2174    * the state change */
2175   g_object_set (dec_elem, "sink-caps", caps, NULL);
2176 
2177   if (!gst_element_link_pads (src_elem, "src", dec_elem, "sink"))
2178     goto could_not_link;
2179 
2180   /* PLAYING in one go might fail (see bug #632782) */
2181   gst_element_set_state (dec_elem, GST_STATE_PAUSED);
2182   gst_element_sync_state_with_parent (dec_elem);
2183   if (queue)
2184     gst_element_sync_state_with_parent (queue);
2185 
2186   return;
2187 
2188   /* ERRORS */
2189 no_decodebin:
2190   {
2191     /* error was posted */
2192     return;
2193   }
2194 could_not_link:
2195   {
2196     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION,
2197         (NULL), ("Can't link typefind to decodebin element"));
2198     do_async_done (decoder);
2199     return;
2200   }
2201 no_buffer_element:
2202   {
2203     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), elem_name);
2204     return;
2205   }
2206 }
2207 
2208 /* setup a streaming source. This will first plug a typefind element to the
2209  * source. After we find the type, we decide to plug a queue2 and continue to
2210  * plug a decodebin starting from the found caps */
2211 static gboolean
setup_streaming(GstURIDecodeBin * decoder)2212 setup_streaming (GstURIDecodeBin * decoder)
2213 {
2214   GstElement *typefind;
2215 
2216   /* now create the decoder element */
2217   typefind = gst_element_factory_make ("typefind", NULL);
2218   if (!typefind)
2219     goto no_typefind;
2220 
2221   gst_bin_add (GST_BIN_CAST (decoder), typefind);
2222 
2223   if (!gst_element_link_pads (decoder->source, NULL, typefind, "sink"))
2224     goto could_not_link;
2225 
2226   decoder->typefind = typefind;
2227 
2228   /* connect a signal to find out when the typefind element found
2229    * a type */
2230   decoder->have_type_id =
2231       g_signal_connect (decoder->typefind, "have-type",
2232       G_CALLBACK (type_found), decoder);
2233 
2234   return TRUE;
2235 
2236   /* ERRORS */
2237 no_typefind:
2238   {
2239     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "typefind");
2240     GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
2241         ("No typefind element, check your installation"));
2242     do_async_done (decoder);
2243     return FALSE;
2244   }
2245 could_not_link:
2246   {
2247     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION,
2248         (NULL), ("Can't link source to typefind element"));
2249     gst_bin_remove (GST_BIN_CAST (decoder), typefind);
2250     do_async_done (decoder);
2251     return FALSE;
2252   }
2253 }
2254 
2255 static void
free_stream(gpointer value)2256 free_stream (gpointer value)
2257 {
2258   g_slice_free (GstURIDecodeBinStream, value);
2259 }
2260 
2261 /* remove source and all related elements */
2262 static void
remove_source(GstURIDecodeBin * bin)2263 remove_source (GstURIDecodeBin * bin)
2264 {
2265   GstElement *source = bin->source;
2266 
2267   if (source) {
2268     GST_DEBUG_OBJECT (bin, "removing old src element");
2269     gst_element_set_state (source, GST_STATE_NULL);
2270 
2271     if (bin->src_np_sig_id) {
2272       g_signal_handler_disconnect (source, bin->src_np_sig_id);
2273       bin->src_np_sig_id = 0;
2274     }
2275     if (bin->src_nmp_sig_id) {
2276       g_signal_handler_disconnect (source, bin->src_nmp_sig_id);
2277       bin->src_nmp_sig_id = 0;
2278     }
2279     GST_OBJECT_LOCK (bin);
2280     bin->source = NULL;
2281     GST_OBJECT_UNLOCK (bin);
2282     gst_bin_remove (GST_BIN_CAST (bin), source);
2283   }
2284   if (bin->queue) {
2285     GST_DEBUG_OBJECT (bin, "removing old queue element");
2286     gst_element_set_state (bin->queue, GST_STATE_NULL);
2287     gst_bin_remove (GST_BIN_CAST (bin), bin->queue);
2288     bin->queue = NULL;
2289   }
2290   if (bin->typefind) {
2291     GST_DEBUG_OBJECT (bin, "removing old typefind element");
2292     gst_element_set_state (bin->typefind, GST_STATE_NULL);
2293     gst_bin_remove (GST_BIN_CAST (bin), bin->typefind);
2294     bin->typefind = NULL;
2295   }
2296   if (bin->streams) {
2297     g_hash_table_destroy (bin->streams);
2298     bin->streams = NULL;
2299   }
2300 }
2301 
2302 /* is called when a dynamic source element created a new pad. */
2303 static void
source_new_pad(GstElement * element,GstPad * pad,GstURIDecodeBin * bin)2304 source_new_pad (GstElement * element, GstPad * pad, GstURIDecodeBin * bin)
2305 {
2306   GstElement *decoder;
2307   gboolean is_raw;
2308   GstCaps *rawcaps;
2309 
2310   GST_URI_DECODE_BIN_LOCK (bin);
2311   GST_DEBUG_OBJECT (bin, "Found new pad %s.%s in source element %s",
2312       GST_DEBUG_PAD_NAME (pad), GST_ELEMENT_NAME (element));
2313 
2314   g_object_get (bin, "caps", &rawcaps, NULL);
2315   if (!rawcaps)
2316     rawcaps = DEFAULT_CAPS;
2317 
2318   /* if this is a pad with all raw caps, we can expose it */
2319   if (has_all_raw_caps (pad, rawcaps, &is_raw) && is_raw) {
2320     /* it's all raw, create output pads. */
2321     GST_URI_DECODE_BIN_UNLOCK (bin);
2322     gst_caps_unref (rawcaps);
2323     expose_decoded_pad (element, pad, bin);
2324     return;
2325   }
2326   gst_caps_unref (rawcaps);
2327 
2328   /* not raw, create decoder */
2329   decoder = make_decoder (bin);
2330   if (!decoder)
2331     goto no_decodebin;
2332 
2333   /* and link to decoder */
2334   if (!gst_element_link_pads (bin->source, NULL, decoder, "sink"))
2335     goto could_not_link;
2336 
2337   GST_DEBUG_OBJECT (bin, "linked decoder to new pad");
2338 
2339   gst_element_sync_state_with_parent (decoder);
2340   GST_URI_DECODE_BIN_UNLOCK (bin);
2341 
2342   return;
2343 
2344   /* ERRORS */
2345 no_decodebin:
2346   {
2347     /* error was posted */
2348     GST_URI_DECODE_BIN_UNLOCK (bin);
2349     return;
2350   }
2351 could_not_link:
2352   {
2353     GST_ELEMENT_ERROR (bin, CORE, NEGOTIATION,
2354         (NULL), ("Can't link source to decoder element"));
2355     GST_URI_DECODE_BIN_UNLOCK (bin);
2356     do_async_done (bin);
2357     return;
2358   }
2359 }
2360 
2361 static gboolean
is_live_source(GstElement * source)2362 is_live_source (GstElement * source)
2363 {
2364   GObjectClass *source_class = NULL;
2365   gboolean is_live = FALSE;
2366   GParamSpec *pspec;
2367 
2368   source_class = G_OBJECT_GET_CLASS (source);
2369   pspec = g_object_class_find_property (source_class, "is-live");
2370   if (!pspec || G_PARAM_SPEC_VALUE_TYPE (pspec) != G_TYPE_BOOLEAN)
2371     return FALSE;
2372 
2373   g_object_get (G_OBJECT (source), "is-live", &is_live, NULL);
2374 
2375   return is_live;
2376 }
2377 
2378 /* construct and run the source and decoder elements until we found
2379  * all the streams or until a preroll queue has been filled.
2380 */
2381 static gboolean
setup_source(GstURIDecodeBin * decoder)2382 setup_source (GstURIDecodeBin * decoder)
2383 {
2384   gboolean is_raw, have_out, is_dynamic;
2385   GstElement *source;
2386 
2387   GST_DEBUG_OBJECT (decoder, "setup source");
2388 
2389   /* delete old src */
2390   remove_source (decoder);
2391 
2392   decoder->pending = 0;
2393 
2394   /* create and configure an element that can handle the uri */
2395   source = gen_source_element (decoder);
2396   GST_OBJECT_LOCK (decoder);
2397   if (!(decoder->source = source)) {
2398     GST_OBJECT_UNLOCK (decoder);
2399 
2400     goto no_source;
2401   }
2402   GST_OBJECT_UNLOCK (decoder);
2403 
2404   /* state will be merged later - if file is not found, error will be
2405    * handled by the application right after. */
2406   gst_bin_add (GST_BIN_CAST (decoder), decoder->source);
2407 
2408   /* notify of the new source used */
2409   g_object_notify (G_OBJECT (decoder), "source");
2410 
2411   g_signal_emit (decoder, gst_uri_decode_bin_signals[SIGNAL_SOURCE_SETUP],
2412       0, decoder->source);
2413 
2414   if (is_live_source (decoder->source))
2415     decoder->is_stream = FALSE;
2416 
2417   /* remove the old decoders now, if any */
2418   remove_decoders (decoder, FALSE);
2419 
2420   /* stream admin setup */
2421   decoder->streams = g_hash_table_new_full (NULL, NULL, NULL, free_stream);
2422 
2423   /* see if the source element emits raw audio/video all by itself,
2424    * if so, we can create streams for the pads and be done with it.
2425    * Also check that is has source pads, if not, we assume it will
2426    * do everything itself.  */
2427   if (!analyse_source (decoder, &is_raw, &have_out, &is_dynamic,
2428           decoder->need_queue))
2429     goto invalid_source;
2430 
2431   if (is_raw) {
2432     GST_DEBUG_OBJECT (decoder, "Source provides all raw data");
2433     /* source provides raw data, we added the pads and we can now signal a
2434      * no_more pads because we are done. */
2435     gst_element_no_more_pads (GST_ELEMENT_CAST (decoder));
2436     do_async_done (decoder);
2437     return TRUE;
2438   }
2439   if (!have_out && !is_dynamic) {
2440     GST_DEBUG_OBJECT (decoder, "Source has no output pads");
2441     /* create a stream to indicate that this uri is handled by a self
2442      * contained element. We are now done. */
2443     add_element_stream (decoder->source, decoder);
2444     return TRUE;
2445   }
2446   if (is_dynamic) {
2447     GST_DEBUG_OBJECT (decoder, "Source has dynamic output pads");
2448     /* connect a handler for the new-pad signal */
2449     decoder->src_np_sig_id =
2450         g_signal_connect (decoder->source, "pad-added",
2451         G_CALLBACK (source_new_pad), decoder);
2452     decoder->src_nmp_sig_id =
2453         g_signal_connect (decoder->source, "no-more-pads",
2454         G_CALLBACK (source_no_more_pads), decoder);
2455     g_object_set_data (G_OBJECT (decoder->source), "pending",
2456         GINT_TO_POINTER (1));
2457     decoder->pending++;
2458   } else {
2459     if (decoder->is_stream) {
2460       GST_DEBUG_OBJECT (decoder, "Setting up streaming");
2461       /* do the stream things here */
2462       if (!setup_streaming (decoder))
2463         goto streaming_failed;
2464     } else {
2465       GstElement *dec_elem;
2466 
2467       /* no streaming source, we can link now */
2468       GST_DEBUG_OBJECT (decoder, "Plugging decodebin to source");
2469 
2470       dec_elem = make_decoder (decoder);
2471       if (!dec_elem)
2472         goto no_decoder;
2473 
2474       if (!gst_element_link_pads (decoder->source, NULL, dec_elem, "sink"))
2475         goto could_not_link;
2476     }
2477   }
2478   return TRUE;
2479 
2480   /* ERRORS */
2481 no_source:
2482   {
2483     /* error message was already posted */
2484     return FALSE;
2485   }
2486 invalid_source:
2487   {
2488     GST_ELEMENT_ERROR (decoder, CORE, FAILED,
2489         (_("Source element is invalid.")), (NULL));
2490     return FALSE;
2491   }
2492 no_decoder:
2493   {
2494     /* message was posted */
2495     return FALSE;
2496   }
2497 streaming_failed:
2498   {
2499     /* message was posted */
2500     return FALSE;
2501   }
2502 could_not_link:
2503   {
2504     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION,
2505         (NULL), ("Can't link source to decoder element"));
2506     return FALSE;
2507   }
2508 }
2509 
2510 static void
value_list_append_structure_list(GValue * list_val,GstStructure ** first,GList * structure_list)2511 value_list_append_structure_list (GValue * list_val, GstStructure ** first,
2512     GList * structure_list)
2513 {
2514   GList *l;
2515 
2516   for (l = structure_list; l != NULL; l = l->next) {
2517     GValue val = { 0, };
2518 
2519     if (*first == NULL)
2520       *first = gst_structure_copy ((GstStructure *) l->data);
2521 
2522     g_value_init (&val, GST_TYPE_STRUCTURE);
2523     g_value_take_boxed (&val, gst_structure_copy ((GstStructure *) l->data));
2524     gst_value_list_append_value (list_val, &val);
2525     g_value_unset (&val);
2526   }
2527 }
2528 
2529 /* if it's a redirect message with multiple redirect locations we might
2530  * want to pick a different 'best' location depending on the required
2531  * bitrates and the connection speed */
2532 static GstMessage *
handle_redirect_message(GstURIDecodeBin * dec,GstMessage * msg)2533 handle_redirect_message (GstURIDecodeBin * dec, GstMessage * msg)
2534 {
2535   const GValue *locations_list, *location_val;
2536   GstMessage *new_msg;
2537   GstStructure *new_structure = NULL;
2538   GList *l_good = NULL, *l_neutral = NULL, *l_bad = NULL;
2539   GValue new_list = { 0, };
2540   guint size, i;
2541   const GstStructure *structure;
2542 
2543   GST_DEBUG_OBJECT (dec, "redirect message: %" GST_PTR_FORMAT, msg);
2544   GST_DEBUG_OBJECT (dec, "connection speed: %" G_GUINT64_FORMAT,
2545       dec->connection_speed);
2546 
2547   structure = gst_message_get_structure (msg);
2548   if (dec->connection_speed == 0 || structure == NULL)
2549     return msg;
2550 
2551   locations_list = gst_structure_get_value (structure, "locations");
2552   if (locations_list == NULL)
2553     return msg;
2554 
2555   size = gst_value_list_get_size (locations_list);
2556   if (size < 2)
2557     return msg;
2558 
2559   /* maintain existing order as much as possible, just sort references
2560    * with too high a bitrate to the end (the assumption being that if
2561    * bitrates are given they are given for all interesting streams and
2562    * that the you-need-at-least-version-xyz redirect has the same bitrate
2563    * as the lowest referenced redirect alternative) */
2564   for (i = 0; i < size; ++i) {
2565     const GstStructure *s;
2566     gint bitrate = 0;
2567 
2568     location_val = gst_value_list_get_value (locations_list, i);
2569     s = (const GstStructure *) g_value_get_boxed (location_val);
2570     if (!gst_structure_get_int (s, "minimum-bitrate", &bitrate) || bitrate <= 0) {
2571       GST_DEBUG_OBJECT (dec, "no bitrate: %" GST_PTR_FORMAT, s);
2572       l_neutral = g_list_append (l_neutral, (gpointer) s);
2573     } else if (bitrate > dec->connection_speed) {
2574       GST_DEBUG_OBJECT (dec, "bitrate too high: %" GST_PTR_FORMAT, s);
2575       l_bad = g_list_append (l_bad, (gpointer) s);
2576     } else if (bitrate <= dec->connection_speed) {
2577       GST_DEBUG_OBJECT (dec, "bitrate OK: %" GST_PTR_FORMAT, s);
2578       l_good = g_list_append (l_good, (gpointer) s);
2579     }
2580   }
2581 
2582   g_value_init (&new_list, GST_TYPE_LIST);
2583   value_list_append_structure_list (&new_list, &new_structure, l_good);
2584   value_list_append_structure_list (&new_list, &new_structure, l_neutral);
2585   value_list_append_structure_list (&new_list, &new_structure, l_bad);
2586   gst_structure_take_value (new_structure, "locations", &new_list);
2587 
2588   g_list_free (l_good);
2589   g_list_free (l_neutral);
2590   g_list_free (l_bad);
2591 
2592   new_msg = gst_message_new_element (msg->src, new_structure);
2593   gst_message_unref (msg);
2594 
2595   GST_DEBUG_OBJECT (dec, "new redirect message: %" GST_PTR_FORMAT, new_msg);
2596   return new_msg;
2597 }
2598 
2599 static GstMessage *
make_topology_message(GstURIDecodeBin * dec)2600 make_topology_message (GstURIDecodeBin * dec)
2601 {
2602   GSList *tmp;
2603   GstStructure *aggregated_topology = NULL;
2604   GValue list = G_VALUE_INIT;
2605   GstCaps *caps = NULL;
2606   gchar *name, *proto;
2607 
2608   aggregated_topology = gst_structure_new_empty ("stream-topology");
2609   g_value_init (&list, GST_TYPE_LIST);
2610 
2611   for (tmp = dec->decodebins; tmp; tmp = tmp->next) {
2612     GValue item = G_VALUE_INIT;
2613     GstStructure *dec_topology =
2614         g_object_get_data (G_OBJECT (tmp->data), "uridecodebin-topology");
2615 
2616     g_value_init (&item, GST_TYPE_STRUCTURE);
2617     gst_value_set_structure (&item, dec_topology);
2618     gst_value_list_append_and_take_value (&list, &item);
2619   }
2620 
2621   gst_structure_take_value (aggregated_topology, "next", &list);
2622 
2623   /* This is a bit wacky, but that's the best way I can find to express
2624    * uridecodebin 'caps' as subsequently shown by gst-discoverer */
2625   proto = gst_uri_get_protocol (dec->uri);
2626   name = g_strdup_printf ("application/%s", proto);
2627   g_free (proto);
2628 
2629   caps = gst_caps_new_empty_simple (name);
2630   g_free (name);
2631 
2632   gst_structure_set (aggregated_topology, "caps", GST_TYPE_CAPS, caps, NULL);
2633   gst_caps_unref (caps);
2634 
2635   return gst_message_new_element (GST_OBJECT (dec), aggregated_topology);
2636 }
2637 
2638 static void
check_topology(gpointer data,gpointer user_data)2639 check_topology (gpointer data, gpointer user_data)
2640 {
2641   gboolean *has_topo = user_data;
2642 
2643   if (g_object_get_data (data, "uridecodebin-topology") == NULL)
2644     *has_topo = FALSE;
2645 }
2646 
2647 static void
handle_message(GstBin * bin,GstMessage * msg)2648 handle_message (GstBin * bin, GstMessage * msg)
2649 {
2650   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (bin);
2651 
2652   switch (GST_MESSAGE_TYPE (msg)) {
2653     case GST_MESSAGE_ELEMENT:{
2654 
2655       if (gst_message_has_name (msg, "stream-topology")) {
2656         GstElement *element = GST_ELEMENT (GST_MESSAGE_SRC (msg));
2657         gboolean has_all_topo = TRUE;
2658 
2659         if (dec->pending || (dec->decodebins && dec->decodebins->next != NULL)) {
2660           const GstStructure *structure;
2661 
2662           /* If there is only one, just let it through, so this case is if
2663            * there is more than one.
2664            */
2665 
2666           structure = gst_message_get_structure (msg);
2667 
2668           g_object_set_data_full (G_OBJECT (element), "uridecodebin-topology",
2669               gst_structure_copy (structure),
2670               (GDestroyNotify) gst_structure_free);
2671 
2672           gst_message_unref (msg);
2673           msg = NULL;
2674 
2675           g_slist_foreach (dec->decodebins, check_topology, &has_all_topo);
2676           if (has_all_topo)
2677             msg = make_topology_message (dec);
2678         }
2679       } else if (gst_message_has_name (msg, "redirect")) {
2680         /* sort redirect messages based on the connection speed. This simplifies
2681          * the user of this element as it can in most cases just pick the first item
2682          * of the sorted list as a good redirection candidate. It can of course
2683          * choose something else from the list if it has a better way. */
2684         msg = handle_redirect_message (dec, msg);
2685       }
2686       break;
2687     }
2688     case GST_MESSAGE_ERROR:{
2689       GError *err = NULL;
2690 
2691       /* Filter out missing plugin error messages from the decodebins. Only if
2692        * all decodebins exposed no streams we will report a missing plugin
2693        * error from no_more_pads_full()
2694        */
2695       gst_message_parse_error (msg, &err, NULL);
2696       if (g_error_matches (err, GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN)
2697           || g_error_matches (err, GST_STREAM_ERROR,
2698               GST_STREAM_ERROR_CODEC_NOT_FOUND)) {
2699         dec->missing_plugin_errors =
2700             g_list_prepend (dec->missing_plugin_errors, gst_message_ref (msg));
2701 
2702         no_more_pads_full (GST_ELEMENT (GST_MESSAGE_SRC (msg)), FALSE,
2703             GST_URI_DECODE_BIN (bin));
2704         gst_message_unref (msg);
2705         msg = NULL;
2706       }
2707       g_clear_error (&err);
2708       break;
2709     }
2710     default:
2711       break;
2712   }
2713 
2714   if (msg)
2715     GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
2716 }
2717 
2718 /* generic struct passed to all query fold methods
2719  * FIXME, move to core.
2720  */
2721 typedef struct
2722 {
2723   GstQuery *query;
2724   gint64 min;
2725   gint64 max;
2726   gboolean seekable;
2727   gboolean live;
2728 } QueryFold;
2729 
2730 typedef void (*QueryInitFunction) (GstURIDecodeBin * dec, QueryFold * fold);
2731 typedef void (*QueryDoneFunction) (GstURIDecodeBin * dec, QueryFold * fold);
2732 
2733 /* for duration/position we collect all durations/positions and take
2734  * the MAX of all valid results */
2735 static void
decoder_query_init(GstURIDecodeBin * dec,QueryFold * fold)2736 decoder_query_init (GstURIDecodeBin * dec, QueryFold * fold)
2737 {
2738   fold->min = 0;
2739   fold->max = -1;
2740   fold->seekable = TRUE;
2741   fold->live = 0;
2742 }
2743 
2744 static gboolean
decoder_query_duration_fold(const GValue * item,GValue * ret,QueryFold * fold)2745 decoder_query_duration_fold (const GValue * item, GValue * ret,
2746     QueryFold * fold)
2747 {
2748   GstPad *pad = g_value_get_object (item);
2749 
2750   if (gst_pad_query (pad, fold->query)) {
2751     gint64 duration;
2752 
2753     g_value_set_boolean (ret, TRUE);
2754 
2755     gst_query_parse_duration (fold->query, NULL, &duration);
2756 
2757     GST_DEBUG_OBJECT (item, "got duration %" G_GINT64_FORMAT, duration);
2758 
2759     if (duration > fold->max)
2760       fold->max = duration;
2761   }
2762   return TRUE;
2763 }
2764 
2765 static void
decoder_query_duration_done(GstURIDecodeBin * dec,QueryFold * fold)2766 decoder_query_duration_done (GstURIDecodeBin * dec, QueryFold * fold)
2767 {
2768   GstFormat format;
2769 
2770   gst_query_parse_duration (fold->query, &format, NULL);
2771   /* store max in query result */
2772   gst_query_set_duration (fold->query, format, fold->max);
2773 
2774   GST_DEBUG ("max duration %" G_GINT64_FORMAT, fold->max);
2775 }
2776 
2777 static gboolean
decoder_query_position_fold(const GValue * item,GValue * ret,QueryFold * fold)2778 decoder_query_position_fold (const GValue * item, GValue * ret,
2779     QueryFold * fold)
2780 {
2781   GstPad *pad = g_value_get_object (item);
2782 
2783   if (gst_pad_query (pad, fold->query)) {
2784     gint64 position;
2785 
2786     g_value_set_boolean (ret, TRUE);
2787 
2788     gst_query_parse_position (fold->query, NULL, &position);
2789 
2790     GST_DEBUG_OBJECT (item, "got position %" G_GINT64_FORMAT, position);
2791 
2792     if (position > fold->max)
2793       fold->max = position;
2794   }
2795 
2796   return TRUE;
2797 }
2798 
2799 static void
decoder_query_position_done(GstURIDecodeBin * dec,QueryFold * fold)2800 decoder_query_position_done (GstURIDecodeBin * dec, QueryFold * fold)
2801 {
2802   GstFormat format;
2803 
2804   gst_query_parse_position (fold->query, &format, NULL);
2805   /* store max in query result */
2806   gst_query_set_position (fold->query, format, fold->max);
2807 
2808   GST_DEBUG_OBJECT (dec, "max position %" G_GINT64_FORMAT, fold->max);
2809 }
2810 
2811 static gboolean
decoder_query_latency_fold(const GValue * item,GValue * ret,QueryFold * fold)2812 decoder_query_latency_fold (const GValue * item, GValue * ret, QueryFold * fold)
2813 {
2814   GstPad *pad = g_value_get_object (item);
2815 
2816   if (gst_pad_query (pad, fold->query)) {
2817     GstClockTime min, max;
2818     gboolean live;
2819 
2820     gst_query_parse_latency (fold->query, &live, &min, &max);
2821 
2822     GST_DEBUG_OBJECT (pad,
2823         "got latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
2824         ", live %d", GST_TIME_ARGS (min), GST_TIME_ARGS (max), live);
2825 
2826     if (live) {
2827       /* for the combined latency we collect the MAX of all min latencies and
2828        * the MIN of all max latencies */
2829       if (min > fold->min)
2830         fold->min = min;
2831       if (fold->max == -1)
2832         fold->max = max;
2833       else if (max < fold->max)
2834         fold->max = max;
2835 
2836       fold->live = TRUE;
2837     }
2838   } else {
2839     GST_LOG_OBJECT (pad, "latency query failed");
2840     g_value_set_boolean (ret, FALSE);
2841   }
2842 
2843   return TRUE;
2844 }
2845 
2846 static void
decoder_query_latency_done(GstURIDecodeBin * dec,QueryFold * fold)2847 decoder_query_latency_done (GstURIDecodeBin * dec, QueryFold * fold)
2848 {
2849   /* store max in query result */
2850   gst_query_set_latency (fold->query, fold->live, fold->min, fold->max);
2851 
2852   GST_DEBUG_OBJECT (dec,
2853       "latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
2854       ", live %d", GST_TIME_ARGS (fold->min), GST_TIME_ARGS (fold->max),
2855       fold->live);
2856 }
2857 
2858 /* we are seekable if all srcpads are seekable */
2859 static gboolean
decoder_query_seeking_fold(const GValue * item,GValue * ret,QueryFold * fold)2860 decoder_query_seeking_fold (const GValue * item, GValue * ret, QueryFold * fold)
2861 {
2862   GstPad *pad = g_value_get_object (item);
2863 
2864   if (gst_pad_query (pad, fold->query)) {
2865     gboolean seekable;
2866 
2867     g_value_set_boolean (ret, TRUE);
2868     gst_query_parse_seeking (fold->query, NULL, &seekable, NULL, NULL);
2869 
2870     GST_DEBUG_OBJECT (item, "got seekable %d", seekable);
2871 
2872     if (fold->seekable)
2873       fold->seekable = seekable;
2874   }
2875 
2876   return TRUE;
2877 }
2878 
2879 static void
decoder_query_seeking_done(GstURIDecodeBin * dec,QueryFold * fold)2880 decoder_query_seeking_done (GstURIDecodeBin * dec, QueryFold * fold)
2881 {
2882   GstFormat format;
2883 
2884   gst_query_parse_seeking (fold->query, &format, NULL, NULL, NULL);
2885   gst_query_set_seeking (fold->query, format, fold->seekable, 0, -1);
2886 
2887   GST_DEBUG_OBJECT (dec, "seekable %d", fold->seekable);
2888 }
2889 
2890 /* generic fold, return first valid result */
2891 static gboolean
decoder_query_generic_fold(const GValue * item,GValue * ret,QueryFold * fold)2892 decoder_query_generic_fold (const GValue * item, GValue * ret, QueryFold * fold)
2893 {
2894   GstPad *pad = g_value_get_object (item);
2895   gboolean res;
2896 
2897   if ((res = gst_pad_query (pad, fold->query))) {
2898     g_value_set_boolean (ret, TRUE);
2899     GST_DEBUG_OBJECT (item, "answered query %p", fold->query);
2900   }
2901 
2902   /* and stop as soon as we have a valid result */
2903   return !res;
2904 }
2905 
2906 
2907 /* we're a bin, the default query handler iterates sink elements, which we don't
2908  * have normally. We should just query all source pads.
2909  */
2910 static gboolean
gst_uri_decode_bin_query(GstElement * element,GstQuery * query)2911 gst_uri_decode_bin_query (GstElement * element, GstQuery * query)
2912 {
2913   GstURIDecodeBin *decoder;
2914   gboolean res = FALSE;
2915   GstIterator *iter;
2916   GstIteratorFoldFunction fold_func;
2917   QueryInitFunction fold_init = NULL;
2918   QueryDoneFunction fold_done = NULL;
2919   QueryFold fold_data;
2920   GValue ret = { 0 };
2921   gboolean default_ret = FALSE;
2922 
2923   decoder = GST_URI_DECODE_BIN (element);
2924 
2925   switch (GST_QUERY_TYPE (query)) {
2926     case GST_QUERY_DURATION:
2927       /* iterate and collect durations */
2928       fold_func = (GstIteratorFoldFunction) decoder_query_duration_fold;
2929       fold_init = decoder_query_init;
2930       fold_done = decoder_query_duration_done;
2931       break;
2932     case GST_QUERY_POSITION:
2933       /* iterate and collect durations */
2934       fold_func = (GstIteratorFoldFunction) decoder_query_position_fold;
2935       fold_init = decoder_query_init;
2936       fold_done = decoder_query_position_done;
2937       break;
2938     case GST_QUERY_LATENCY:
2939       /* iterate and collect durations */
2940       fold_func = (GstIteratorFoldFunction) decoder_query_latency_fold;
2941       fold_init = decoder_query_init;
2942       fold_done = decoder_query_latency_done;
2943       default_ret = TRUE;
2944       break;
2945     case GST_QUERY_SEEKING:
2946       /* iterate and collect durations */
2947       fold_func = (GstIteratorFoldFunction) decoder_query_seeking_fold;
2948       fold_init = decoder_query_init;
2949       fold_done = decoder_query_seeking_done;
2950       break;
2951     default:
2952       fold_func = (GstIteratorFoldFunction) decoder_query_generic_fold;
2953       break;
2954   }
2955 
2956   fold_data.query = query;
2957 
2958   g_value_init (&ret, G_TYPE_BOOLEAN);
2959   g_value_set_boolean (&ret, default_ret);
2960 
2961   iter = gst_element_iterate_src_pads (element);
2962   GST_DEBUG_OBJECT (element, "Sending query %p (type %d) to src pads",
2963       query, GST_QUERY_TYPE (query));
2964 
2965   if (fold_init)
2966     fold_init (decoder, &fold_data);
2967 
2968   while (TRUE) {
2969     GstIteratorResult ires;
2970 
2971     ires = gst_iterator_fold (iter, fold_func, &ret, &fold_data);
2972 
2973     switch (ires) {
2974       case GST_ITERATOR_RESYNC:
2975         gst_iterator_resync (iter);
2976         if (fold_init)
2977           fold_init (decoder, &fold_data);
2978         g_value_set_boolean (&ret, default_ret);
2979         break;
2980       case GST_ITERATOR_OK:
2981       case GST_ITERATOR_DONE:
2982         res = g_value_get_boolean (&ret);
2983         if (fold_done != NULL && res)
2984           fold_done (decoder, &fold_data);
2985         goto done;
2986       default:
2987         res = FALSE;
2988         goto done;
2989     }
2990   }
2991 done:
2992   gst_iterator_free (iter);
2993 
2994   return res;
2995 }
2996 
2997 static GstStateChangeReturn
gst_uri_decode_bin_change_state(GstElement * element,GstStateChange transition)2998 gst_uri_decode_bin_change_state (GstElement * element,
2999     GstStateChange transition)
3000 {
3001   GstStateChangeReturn ret;
3002   GstURIDecodeBin *decoder;
3003 
3004   decoder = GST_URI_DECODE_BIN (element);
3005 
3006   switch (transition) {
3007     case GST_STATE_CHANGE_READY_TO_PAUSED:
3008       do_async_start (decoder);
3009       break;
3010     default:
3011       break;
3012   }
3013 
3014   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3015   if (ret == GST_STATE_CHANGE_FAILURE)
3016     goto setup_failed;
3017 
3018   switch (transition) {
3019     case GST_STATE_CHANGE_READY_TO_PAUSED:
3020       GST_DEBUG ("ready to paused");
3021       if (!setup_source (decoder))
3022         goto source_failed;
3023 
3024       ret = GST_STATE_CHANGE_ASYNC;
3025 
3026       /* And now sync the states of everything we added */
3027       g_slist_foreach (decoder->decodebins,
3028           (GFunc) gst_element_sync_state_with_parent, NULL);
3029       if (decoder->typefind)
3030         ret = gst_element_set_state (decoder->typefind, GST_STATE_PAUSED);
3031       if (ret == GST_STATE_CHANGE_FAILURE)
3032         goto setup_failed;
3033       if (decoder->queue)
3034         ret = gst_element_set_state (decoder->queue, GST_STATE_PAUSED);
3035       if (ret == GST_STATE_CHANGE_FAILURE)
3036         goto setup_failed;
3037       if (decoder->source)
3038         ret = gst_element_set_state (decoder->source, GST_STATE_PAUSED);
3039       if (ret == GST_STATE_CHANGE_FAILURE)
3040         goto setup_failed;
3041       if (ret == GST_STATE_CHANGE_SUCCESS)
3042         ret = GST_STATE_CHANGE_ASYNC;
3043 
3044       break;
3045     case GST_STATE_CHANGE_PAUSED_TO_READY:
3046       GST_DEBUG ("paused to ready");
3047       remove_decoders (decoder, FALSE);
3048       remove_source (decoder);
3049       do_async_done (decoder);
3050       g_list_free_full (decoder->missing_plugin_errors,
3051           (GDestroyNotify) gst_message_unref);
3052       decoder->missing_plugin_errors = NULL;
3053       break;
3054     case GST_STATE_CHANGE_READY_TO_NULL:
3055       GST_DEBUG ("ready to null");
3056       remove_decoders (decoder, TRUE);
3057       remove_source (decoder);
3058       break;
3059     default:
3060       break;
3061   }
3062 
3063   if (ret == GST_STATE_CHANGE_NO_PREROLL)
3064     do_async_done (decoder);
3065 
3066   return ret;
3067 
3068   /* ERRORS */
3069 source_failed:
3070   {
3071     do_async_done (decoder);
3072     return GST_STATE_CHANGE_FAILURE;
3073   }
3074 setup_failed:
3075   {
3076     /* clean up leftover groups */
3077     do_async_done (decoder);
3078     return GST_STATE_CHANGE_FAILURE;
3079   }
3080 }
3081 
3082 gboolean
gst_uri_decode_bin_plugin_init(GstPlugin * plugin)3083 gst_uri_decode_bin_plugin_init (GstPlugin * plugin)
3084 {
3085   GST_DEBUG_CATEGORY_INIT (gst_uri_decode_bin_debug, "uridecodebin", 0,
3086       "URI decoder element");
3087 
3088   return gst_element_register (plugin, "uridecodebin", GST_RANK_NONE,
3089       GST_TYPE_URI_DECODE_BIN);
3090 }
3091