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