32ec52a03cc3a5cce35c6040cdd055d9af4ac0cd
[platform/upstream/gstreamer.git] / plugins / elements / gstmultiqueue.c
1 /* GStreamer
2  * Copyright (C) 2006 Edward Hervey <edward@fluendo.com>
3  * Copyright (C) 2007 Jan Schmidt <jan@fluendo.com>
4  * Copyright (C) 2007 Wim Taymans <wim@fluendo.com>
5  * Copyright (C) 2011 Sebastian Dröge <sebastian.droege@collabora.co.uk>
6  *
7  * gstmultiqueue.c:
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:element-multiqueue
27  * @title: multiqueue
28  * @see_also: #GstQueue
29  *
30  * Multiqueue is similar to a normal #GstQueue with the following additional
31  * features:
32  *
33  * 1) Multiple streamhandling
34  *
35  *  * The element handles queueing data on more than one stream at once. To
36  * achieve such a feature it has request sink pads (sink%u) and
37  * 'sometimes' src pads (src%u). When requesting a given sinkpad with gst_element_request_pad(),
38  * the associated srcpad for that stream will be created.
39  * Example: requesting sink1 will generate src1.
40  *
41  * 2) Non-starvation on multiple stream
42  *
43  * * If more than one stream is used with the element, the streams' queues
44  * will be dynamically grown (up to a limit), in order to ensure that no
45  * stream is risking data starvation. This guarantees that at any given
46  * time there are at least N bytes queued and available for each individual
47  * stream. If an EOS event comes through a srcpad, the associated queue will be
48  * considered as 'not-empty' in the queue-size-growing algorithm.
49  *
50  * 3) Non-linked srcpads graceful handling
51  *
52  * * In order to better support dynamic switching between streams, the multiqueue
53  * (unlike the current GStreamer queue) continues to push buffers on non-linked
54  * pads rather than shutting down. In addition, to prevent a non-linked stream from very quickly consuming all
55  * available buffers and thus 'racing ahead' of the other streams, the element
56  * must ensure that buffers and inlined events for a non-linked stream are pushed
57  * in the same order as they were received, relative to the other streams
58  * controlled by the element. This means that a buffer cannot be pushed to a
59  * non-linked pad any sooner than buffers in any other stream which were received
60  * before it.
61  *
62  * Data is queued until one of the limits specified by the
63  * #GstMultiQueue:max-size-buffers, #GstMultiQueue:max-size-bytes and/or
64  * #GstMultiQueue:max-size-time properties has been reached. Any attempt to push
65  * more buffers into the queue will block the pushing thread until more space
66  * becomes available. #GstMultiQueue:extra-size-buffers,
67  *
68  *
69  * #GstMultiQueue:extra-size-bytes and #GstMultiQueue:extra-size-time are
70  * currently unused.
71  *
72  * The default queue size limits are 5 buffers, 10MB of data, or
73  * two second worth of data, whichever is reached first. Note that the number
74  * of buffers will dynamically grow depending on the fill level of
75  * other queues.
76  *
77  * The #GstMultiQueue::underrun signal is emitted when all of the queues
78  * are empty. The #GstMultiQueue::overrun signal is emitted when one of the
79  * queues is filled.
80  * Both signals are emitted from the context of the streaming thread.
81  *
82  * When using #GstMultiQueue:sync-by-running-time the unlinked streams will
83  * be throttled by the highest running-time of linked streams. This allows
84  * further relinking of those unlinked streams without them being in the
85  * future (i.e. to achieve gapless playback).
86  * When dealing with streams which have got different consumption requirements
87  * downstream (ex: video decoders which will consume more buffer (in time) than
88  * audio decoders), it is recommended to group streams of the same type
89  * by using the pad "group-id" property. This will further throttle streams
90  * in time within that group.
91  */
92
93 #ifdef HAVE_CONFIG_H
94 #  include "config.h"
95 #endif
96
97 #include <gst/gst.h>
98 #include <stdio.h>
99 #include "gstmultiqueue.h"
100 #include <gst/glib-compat-private.h>
101
102 /**
103  * GstSingleQueue:
104  * @sinkpad: associated sink #GstPad
105  * @srcpad: associated source #GstPad
106  *
107  * Structure containing all information and properties about
108  * a single queue.
109  */
110 typedef struct _GstSingleQueue GstSingleQueue;
111
112 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
113 /*RVU patch*/
114 enum
115 {
116   SQ_VIDEO_STREAM = 0,
117   SQ_AUDIO_STREAM,
118   SQ_OTHER_STREAM
119 };
120 #endif
121
122 struct _GstSingleQueue
123 {
124   /* unique identifier of the queue */
125   guint id;
126   /* group of streams to which this queue belongs to */
127   guint groupid;
128   GstClockTimeDiff group_high_time;
129
130   GstMultiQueue *mqueue;
131
132   GstPad *sinkpad;
133   GstPad *srcpad;
134
135   /* flowreturn of previous srcpad push */
136   GstFlowReturn srcresult;
137   /* If something was actually pushed on
138    * this pad after flushing/pad activation
139    * and the srcresult corresponds to something
140    * real
141    */
142   gboolean pushed;
143
144   /* segments */
145   GstSegment sink_segment;
146   GstSegment src_segment;
147   gboolean has_src_segment;     /* preferred over initializing the src_segment to
148                                  * UNDEFINED as this doesn't requires adding ifs
149                                  * in every segment usage */
150
151   /* position of src/sink */
152   GstClockTimeDiff sinktime, srctime;
153   /* cached input value, used for interleave */
154   GstClockTimeDiff cached_sinktime;
155   /* TRUE if either position needs to be recalculated */
156   gboolean sink_tainted, src_tainted;
157
158   /* queue of data */
159   GstDataQueue *queue;
160   GstDataQueueSize max_size, extra_size;
161   GstClockTime cur_time;
162   gboolean is_eos;
163   gboolean is_sparse;
164   gboolean flushing;
165   gboolean active;
166
167   /* Protected by global lock */
168   guint32 nextid;               /* ID of the next object waiting to be pushed */
169   guint32 oldid;                /* ID of the last object pushed (last in a series) */
170   guint32 last_oldid;           /* Previously observed old_id, reset to MAXUINT32 on flush */
171   GstClockTimeDiff next_time;   /* End running time of next buffer to be pushed */
172   GstClockTimeDiff last_time;   /* Start running time of last pushed buffer */
173   GCond turn;                   /* SingleQueue turn waiting conditional */
174
175   /* for serialized queries */
176   GCond query_handled;
177   gboolean last_query;
178   GstQuery *last_handled_query;
179
180   /* For interleave calculation */
181   GThread *thread;
182
183 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
184 /*RVU patch : update buffering percent*/
185   gint sq_stream_type;
186   GstClockTime cur_time_of_begin_buffering;
187 #endif
188 };
189
190
191 /* Extension of GstDataQueueItem structure for our usage */
192 typedef struct _GstMultiQueueItem GstMultiQueueItem;
193
194 struct _GstMultiQueueItem
195 {
196   GstMiniObject *object;
197   guint size;
198   guint64 duration;
199   gboolean visible;
200
201   GDestroyNotify destroy;
202   guint32 posid;
203
204   gboolean is_query;
205 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
206   /*RVU patch : for update single queue buffering percent*/
207   GstSingleQueue *sq;
208 #endif
209 };
210
211 static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue, guint id);
212 static void gst_single_queue_free (GstSingleQueue * squeue);
213
214 static void wake_up_next_non_linked (GstMultiQueue * mq);
215 static void compute_high_id (GstMultiQueue * mq);
216 static void compute_high_time (GstMultiQueue * mq, guint groupid);
217 static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
218 static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
219
220 static void update_buffering (GstMultiQueue * mq, GstSingleQueue * sq);
221 static void gst_multi_queue_post_buffering (GstMultiQueue * mq);
222 static void recheck_buffering_status (GstMultiQueue * mq);
223
224 static void gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full);
225
226 static void calculate_interleave (GstMultiQueue * mq);
227
228 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
229 /*RVU patch : work for get stream type to set single queue buffering params*/
230 static void single_queue_set_stream_type (GstSingleQueue * squeue,
231     GstBuffer * buffer);
232 static void early_exit_buffering (GstMultiQueue * mq);
233 #endif
234
235 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink_%u",
236     GST_PAD_SINK,
237     GST_PAD_REQUEST,
238     GST_STATIC_CAPS_ANY);
239
240 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
241     GST_PAD_SRC,
242     GST_PAD_SOMETIMES,
243     GST_STATIC_CAPS_ANY);
244
245 GST_DEBUG_CATEGORY_STATIC (multi_queue_debug);
246 #define GST_CAT_DEFAULT (multi_queue_debug)
247
248 /* Signals and args */
249 enum
250 {
251   SIGNAL_UNDERRUN,
252   SIGNAL_OVERRUN,
253   LAST_SIGNAL
254 };
255
256 /* default limits, we try to keep up to 2 seconds of data and if there is not
257  * time, up to 10 MB. The number of buffers is dynamically scaled to make sure
258  * there is data in the queues. Normally, the byte and time limits are not hit
259  * in theses conditions. */
260 #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */
261 #define DEFAULT_MAX_SIZE_BUFFERS 5
262 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND
263
264 /* second limits. When we hit one of the above limits we are probably dealing
265  * with a badly muxed file and we scale the limits to these emergency values.
266  * This is currently not yet implemented.
267  * Since we dynamically scale the queue buffer size up to the limits but avoid
268  * going above the max-size-buffers when we can, we don't really need this
269  * aditional extra size. */
270 #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024       /* 10 MB */
271 #define DEFAULT_EXTRA_SIZE_BUFFERS 5
272 #ifdef TIZEN_FEATURE_MQ_MODIFICATION_EXTRA_SIZE_TIME
273 #define DEFAULT_EXTRA_SIZE_TIME 10 * GST_SECOND
274 #else
275 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND
276 #endif
277
278 #define DEFAULT_USE_BUFFERING FALSE
279 #define DEFAULT_LOW_WATERMARK  0.01
280 #define DEFAULT_HIGH_WATERMARK 0.99
281 #define DEFAULT_SYNC_BY_RUNNING_TIME FALSE
282 #define DEFAULT_USE_INTERLEAVE FALSE
283 #define DEFAULT_UNLINKED_CACHE_TIME 250 * GST_MSECOND
284
285 #define DEFAULT_MINIMUM_INTERLEAVE (250 * GST_MSECOND)
286
287 enum
288 {
289   PROP_0,
290   PROP_EXTRA_SIZE_BYTES,
291   PROP_EXTRA_SIZE_BUFFERS,
292   PROP_EXTRA_SIZE_TIME,
293   PROP_MAX_SIZE_BYTES,
294   PROP_MAX_SIZE_BUFFERS,
295   PROP_MAX_SIZE_TIME,
296 #ifdef TIZEN_FEATURE_MQ_MODIFICATION
297   PROP_CURR_SIZE_BYTES,
298 #endif
299   PROP_USE_BUFFERING,
300   PROP_LOW_PERCENT,
301   PROP_HIGH_PERCENT,
302   PROP_LOW_WATERMARK,
303   PROP_HIGH_WATERMARK,
304   PROP_SYNC_BY_RUNNING_TIME,
305   PROP_USE_INTERLEAVE,
306   PROP_UNLINKED_CACHE_TIME,
307   PROP_MINIMUM_INTERLEAVE,
308 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
309 /*RVU patch : buffering params*/
310   PROP_MAX_AUDIO_SIZE_BYTES,
311   PROP_MAX_AUDIO_SIZE_BUFFERS,
312   PROP_MAX_AUDIO_SIZE_TIME,
313   PROP_MAX_VIDEO_SIZE_BYTES,
314   PROP_MAX_VIDEO_SIZE_BUFFERS,
315   PROP_MAX_VIDEO_SIZE_TIME,
316   PROP_ENABLE_BUFFERING_OPT,
317 /*RVU patch : rvu reset, disable audio buffering and adaptive buffering property*/
318   PROP_RESET_FLAG,
319   PROP_DISABLE_AUDIO_BUFFERING,
320   PROP_BUFFERING_ENHANCEMENT,
321 #endif
322   PROP_LAST
323 };
324
325 /* Explanation for buffer levels and percentages:
326  *
327  * The buffering_level functions here return a value in a normalized range
328  * that specifies the current fill level of a queue. The range goes from 0 to
329  * MAX_BUFFERING_LEVEL. The low/high watermarks also use this same range.
330  *
331  * This is not to be confused with the buffering_percent value, which is
332  * a *relative* quantity - relative to the low/high watermarks.
333  * buffering_percent = 0% means overall buffering_level is at the low watermark.
334  * buffering_percent = 100% means overall buffering_level is at the high watermark.
335  * buffering_percent is used for determining if the fill level has reached
336  * the high watermark, and for producing BUFFERING messages. This value
337  * always uses a 0..100 range (since it is a percentage).
338  *
339  * To avoid future confusions, whenever "buffering level" is mentioned, it
340  * refers to the absolute level which is in the 0..MAX_BUFFERING_LEVEL
341  * range. Whenever "buffering_percent" is mentioned, it refers to the
342  * percentage value that is relative to the low/high watermark. */
343
344 /* Using a buffering level range of 0..1000000 to allow for a
345  * resolution in ppm (1 ppm = 0.0001%) */
346 #define MAX_BUFFERING_LEVEL 1000000
347
348 /* How much 1% makes up in the buffer level range */
349 #define BUF_LEVEL_PERCENT_FACTOR ((MAX_BUFFERING_LEVEL) / 100)
350
351 /* GstMultiQueuePad */
352
353 #define DEFAULT_PAD_GROUP_ID 0
354
355 enum
356 {
357   PROP_PAD_0,
358   PROP_PAD_GROUP_ID,
359 };
360
361 #define GST_TYPE_MULTIQUEUE_PAD            (gst_multiqueue_pad_get_type())
362 #define GST_MULTIQUEUE_PAD(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_MULTIQUEUE_PAD,GstMultiQueuePad))
363 #define GST_IS_MULTIQUEUE_PAD(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_MULTIQUEUE_PAD))
364 #define GST_MULTIQUEUE_PAD_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST((klass) ,GST_TYPE_MULTIQUEUE_PAD,GstMultiQueuePadClass))
365 #define GST_IS_MULTIQUEUE_PAD_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass) ,GST_TYPE_MULTIQUEUE_PAD))
366 #define GST_MULTIQUEUE_PAD_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj) ,GST_TYPE_MULTIQUEUE_PAD,GstMultiQueuePadClass))
367
368 struct _GstMultiQueuePad
369 {
370   GstPad parent;
371
372   GstSingleQueue *sq;
373 };
374
375 struct _GstMultiQueuePadClass
376 {
377   GstPadClass parent_class;
378 };
379
380 GType gst_multiqueue_pad_get_type (void);
381
382 G_DEFINE_TYPE (GstMultiQueuePad, gst_multiqueue_pad, GST_TYPE_PAD);
383 static void
384 gst_multiqueue_pad_get_property (GObject * object, guint prop_id,
385     GValue * value, GParamSpec * pspec)
386 {
387   GstMultiQueuePad *pad = GST_MULTIQUEUE_PAD (object);
388
389   switch (prop_id) {
390     case PROP_PAD_GROUP_ID:
391       if (pad->sq)
392         g_value_set_uint (value, pad->sq->groupid);
393       break;
394     default:
395       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
396       break;
397   }
398 }
399
400 static void
401 gst_multiqueue_pad_set_property (GObject * object, guint prop_id,
402     const GValue * value, GParamSpec * pspec)
403 {
404   GstMultiQueuePad *pad = GST_MULTIQUEUE_PAD (object);
405
406   switch (prop_id) {
407     case PROP_PAD_GROUP_ID:
408       GST_OBJECT_LOCK (pad);
409       if (pad->sq)
410         pad->sq->groupid = g_value_get_uint (value);
411       GST_OBJECT_UNLOCK (pad);
412       break;
413     default:
414       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
415       break;
416   }
417 }
418
419 static void
420 gst_multiqueue_pad_class_init (GstMultiQueuePadClass * klass)
421 {
422   GObjectClass *gobject_class = (GObjectClass *) klass;
423
424   gobject_class->set_property = gst_multiqueue_pad_set_property;
425   gobject_class->get_property = gst_multiqueue_pad_get_property;
426
427   /**
428    * GstMultiQueuePad:group-id:
429    *
430    * Group to which this pad belongs.
431    *
432    * Since: 1.10
433    */
434   g_object_class_install_property (gobject_class, PROP_PAD_GROUP_ID,
435       g_param_spec_uint ("group-id", "Group ID",
436           "Group to which this pad belongs", 0, G_MAXUINT32,
437           DEFAULT_PAD_GROUP_ID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
438 }
439
440 static void
441 gst_multiqueue_pad_init (GstMultiQueuePad * pad)
442 {
443
444 }
445
446
447 #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
448   g_mutex_lock (&q->qlock);                                              \
449 } G_STMT_END
450
451 #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
452   g_mutex_unlock (&q->qlock);                                            \
453 } G_STMT_END
454
455 #define SET_PERCENT(mq, perc) G_STMT_START {                             \
456   if (perc != mq->buffering_percent) {                                   \
457     mq->buffering_percent = perc;                                        \
458     mq->buffering_percent_changed = TRUE;                                \
459     GST_DEBUG_OBJECT (mq, "buffering %d percent", perc);                 \
460   }                                                                      \
461 } G_STMT_END
462
463 /* Convenience function */
464 static inline GstClockTimeDiff
465 my_segment_to_running_time (GstSegment * segment, GstClockTime val)
466 {
467   GstClockTimeDiff res = GST_CLOCK_STIME_NONE;
468
469   if (GST_CLOCK_TIME_IS_VALID (val)) {
470     gboolean sign =
471         gst_segment_to_running_time_full (segment, GST_FORMAT_TIME, val, &val);
472     if (sign > 0)
473       res = val;
474     else if (sign < 0)
475       res = -val;
476   }
477   return res;
478 }
479
480 static void gst_multi_queue_finalize (GObject * object);
481 static void gst_multi_queue_set_property (GObject * object,
482     guint prop_id, const GValue * value, GParamSpec * pspec);
483 static void gst_multi_queue_get_property (GObject * object,
484     guint prop_id, GValue * value, GParamSpec * pspec);
485
486 static GstPad *gst_multi_queue_request_new_pad (GstElement * element,
487     GstPadTemplate * temp, const gchar * name, const GstCaps * caps);
488 static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad);
489 static GstStateChangeReturn gst_multi_queue_change_state (GstElement *
490     element, GstStateChange transition);
491
492 static void gst_multi_queue_loop (GstPad * pad);
493
494 #define _do_init \
495   GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element");
496 #define gst_multi_queue_parent_class parent_class
497 G_DEFINE_TYPE_WITH_CODE (GstMultiQueue, gst_multi_queue, GST_TYPE_ELEMENT,
498     _do_init);
499
500 static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 };
501
502 static void
503 gst_multi_queue_class_init (GstMultiQueueClass * klass)
504 {
505   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
506   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
507
508   gobject_class->set_property = gst_multi_queue_set_property;
509   gobject_class->get_property = gst_multi_queue_get_property;
510
511   /* SIGNALS */
512
513   /**
514    * GstMultiQueue::underrun:
515    * @multiqueue: the multiqueue instance
516    *
517    * This signal is emitted from the streaming thread when there is
518    * no data in any of the queues inside the multiqueue instance (underrun).
519    *
520    * This indicates either starvation or EOS from the upstream data sources.
521    */
522   gst_multi_queue_signals[SIGNAL_UNDERRUN] =
523       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
524       G_STRUCT_OFFSET (GstMultiQueueClass, underrun), NULL, NULL,
525       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
526
527   /**
528    * GstMultiQueue::overrun:
529    * @multiqueue: the multiqueue instance
530    *
531    * Reports that one of the queues in the multiqueue is full (overrun).
532    * A queue is full if the total amount of data inside it (num-buffers, time,
533    * size) is higher than the boundary values which can be set through the
534    * GObject properties.
535    *
536    * This can be used as an indicator of pre-roll.
537    */
538   gst_multi_queue_signals[SIGNAL_OVERRUN] =
539       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
540       G_STRUCT_OFFSET (GstMultiQueueClass, overrun), NULL, NULL,
541       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
542
543   /* PROPERTIES */
544   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
545       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
546           "Max. amount of data in the queue (bytes, 0=disable)",
547           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
548           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
549           G_PARAM_STATIC_STRINGS));
550   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
551       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
552           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
553           DEFAULT_MAX_SIZE_BUFFERS,
554           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
555           G_PARAM_STATIC_STRINGS));
556   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
557       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
558           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
559           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
560           G_PARAM_STATIC_STRINGS));
561 #ifdef TIZEN_FEATURE_MQ_MODIFICATION
562   g_object_class_install_property (gobject_class, PROP_CURR_SIZE_BYTES,
563       g_param_spec_uint ("curr-size-bytes", "Current buffered size (kB)",
564           "buffered amount of data in the queue (bytes)", 0, G_MAXUINT,
565                   0, G_PARAM_READABLE | GST_PARAM_MUTABLE_PLAYING |
566                   G_PARAM_STATIC_STRINGS));
567 #endif
568   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BYTES,
569       g_param_spec_uint ("extra-size-bytes", "Extra Size (kB)",
570           "Amount of data the queues can grow if one of them is empty (bytes, 0=disable)"
571           " (NOT IMPLEMENTED)",
572           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BYTES,
573           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
574   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BUFFERS,
575       g_param_spec_uint ("extra-size-buffers", "Extra Size (buffers)",
576           "Amount of buffers the queues can grow if one of them is empty (0=disable)"
577           " (NOT IMPLEMENTED)",
578           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BUFFERS,
579           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
580   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_TIME,
581       g_param_spec_uint64 ("extra-size-time", "Extra Size (ns)",
582           "Amount of time the queues can grow if one of them is empty (in ns, 0=disable)"
583           " (NOT IMPLEMENTED)",
584           0, G_MAXUINT64, DEFAULT_EXTRA_SIZE_TIME,
585           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
586
587   /**
588    * GstMultiQueue:use-buffering:
589    *
590    * Enable the buffering option in multiqueue so that BUFFERING messages are
591    * emitted based on low-/high-percent thresholds.
592    */
593   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
594       g_param_spec_boolean ("use-buffering", "Use buffering",
595           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
596           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
597           G_PARAM_STATIC_STRINGS));
598   /**
599    * GstMultiQueue:low-percent:
600    *
601    * Low threshold percent for buffering to start.
602    */
603   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
604       g_param_spec_int ("low-percent", "Low percent",
605           "Low threshold for buffering to start. Only used if use-buffering is True "
606           "(Deprecated: use low-watermark instead)",
607           0, 100, DEFAULT_LOW_WATERMARK * 100,
608           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
609   /**
610    * GstMultiQueue:high-percent:
611    *
612    * High threshold percent for buffering to finish.
613    */
614   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
615       g_param_spec_int ("high-percent", "High percent",
616           "High threshold for buffering to finish. Only used if use-buffering is True "
617           "(Deprecated: use high-watermark instead)",
618           0, 100, DEFAULT_HIGH_WATERMARK * 100,
619           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
620   /**
621    * GstMultiQueue:low-watermark:
622    *
623    * Low threshold watermark for buffering to start.
624    *
625    * Since: 1.10
626    */
627   g_object_class_install_property (gobject_class, PROP_LOW_WATERMARK,
628       g_param_spec_double ("low-watermark", "Low watermark",
629           "Low threshold for buffering to start. Only used if use-buffering is True",
630           0.0, 1.0, DEFAULT_LOW_WATERMARK,
631           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
632   /**
633    * GstMultiQueue:high-watermark:
634    *
635    * High threshold watermark for buffering to finish.
636    *
637    * Since: 1.10
638    */
639   g_object_class_install_property (gobject_class, PROP_HIGH_WATERMARK,
640       g_param_spec_double ("high-watermark", "High watermark",
641           "High threshold for buffering to finish. Only used if use-buffering is True",
642           0.0, 1.0, DEFAULT_HIGH_WATERMARK,
643           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
644
645   /**
646    * GstMultiQueue:sync-by-running-time:
647    *
648    * If enabled multiqueue will synchronize deactivated or not-linked streams
649    * to the activated and linked streams by taking the running time.
650    * Otherwise multiqueue will synchronize the deactivated or not-linked
651    * streams by keeping the order in which buffers and events arrived compared
652    * to active and linked streams.
653    */
654   g_object_class_install_property (gobject_class, PROP_SYNC_BY_RUNNING_TIME,
655       g_param_spec_boolean ("sync-by-running-time", "Sync By Running Time",
656           "Synchronize deactivated or not-linked streams by running time",
657           DEFAULT_SYNC_BY_RUNNING_TIME,
658           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
659 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
660 /*RVU patch : buffering params property*/
661   g_object_class_install_property (gobject_class, PROP_MAX_AUDIO_SIZE_BYTES,
662       g_param_spec_uint ("max-size-audio-bytes", "Max. size (kB)",
663           "Max. amount of data in the audio queue (bytes, 0=disable)", 0,
664           G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
665           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
666   g_object_class_install_property (gobject_class, PROP_MAX_AUDIO_SIZE_BUFFERS,
667       g_param_spec_uint ("max-size-audio-buffers", "Max. size (buffers)",
668           "Max. number of buffers in the audio queue (0=disable)", 0, G_MAXUINT,
669           DEFAULT_MAX_SIZE_BUFFERS,
670           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
671   g_object_class_install_property (gobject_class, PROP_MAX_AUDIO_SIZE_TIME,
672       g_param_spec_uint64 ("max-size-audio-time", "Max. size (ns)",
673           "Max. amount of data in the audio queue (in ns, 0=disable)", 0,
674           G_MAXUINT64, DEFAULT_MAX_SIZE_TIME,
675           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
676   g_object_class_install_property (gobject_class, PROP_MAX_VIDEO_SIZE_BYTES,
677       g_param_spec_uint ("max-size-video-bytes", "Max. size (kB)",
678           "Max. amount of data in the video queue (bytes, 0=disable)",
679           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
680           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
681   g_object_class_install_property (gobject_class, PROP_MAX_VIDEO_SIZE_BUFFERS,
682       g_param_spec_uint ("max-size-video-buffers", "Max. size (buffers)",
683           "Max. number of buffers in the video queue (0=disable)", 0, G_MAXUINT,
684           DEFAULT_MAX_SIZE_BUFFERS,
685           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
686   g_object_class_install_property (gobject_class, PROP_MAX_VIDEO_SIZE_TIME,
687       g_param_spec_uint64 ("max-size-video-time", "Max. size (ns)",
688           "Max. amount of data in the video queue (in ns, 0=disable)", 0,
689           G_MAXUINT64, DEFAULT_MAX_SIZE_TIME,
690           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
691   g_object_class_install_property (gobject_class, PROP_ENABLE_BUFFERING_OPT,
692       g_param_spec_boolean ("enable-buffering-opt",
693           "make buffering optimize enable",
694           "enable to control the buffering queue size and time.", FALSE,
695           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
696
697 /*RVU patch : rvu reset, disable audio buffering and adaptive buffering property*/
698   g_object_class_install_property (gobject_class, PROP_RESET_FLAG,
699       g_param_spec_int ("buffering-reset-flag", "reset flag",
700           "reset buffering flag", 0, 1, 0,
701           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
702
703   g_object_class_install_property (gobject_class, PROP_DISABLE_AUDIO_BUFFERING,
704       g_param_spec_boolean ("disable-audio-buffering",
705           "disable audio stream buffering", "disable audio buffering solution",
706           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
707   g_object_class_install_property (gobject_class, PROP_BUFFERING_ENHANCEMENT,
708       g_param_spec_boolean ("enhancement-buffering", "enhancement buffering solution",
709           "enhancement buffering solution",
710           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
711 #endif
712
713   g_object_class_install_property (gobject_class, PROP_USE_INTERLEAVE,
714       g_param_spec_boolean ("use-interleave", "Use interleave",
715           "Adjust time limits based on input interleave",
716           DEFAULT_USE_INTERLEAVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
717
718   g_object_class_install_property (gobject_class, PROP_UNLINKED_CACHE_TIME,
719       g_param_spec_uint64 ("unlinked-cache-time", "Unlinked cache time (ns)",
720           "Extra buffering in time for unlinked streams (if 'sync-by-running-time')",
721           0, G_MAXUINT64, DEFAULT_UNLINKED_CACHE_TIME,
722           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
723           G_PARAM_STATIC_STRINGS));
724
725   g_object_class_install_property (gobject_class, PROP_MINIMUM_INTERLEAVE,
726       g_param_spec_uint64 ("min-interleave-time", "Minimum interleave time",
727           "Minimum extra buffering for deinterleaving (size of the queues) when use-interleave=true",
728           0, G_MAXUINT64, DEFAULT_MINIMUM_INTERLEAVE,
729           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
730           G_PARAM_STATIC_STRINGS));
731
732   gobject_class->finalize = gst_multi_queue_finalize;
733
734   gst_element_class_set_static_metadata (gstelement_class,
735       "MultiQueue",
736       "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>");
737   gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
738   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
739
740   gstelement_class->request_new_pad =
741       GST_DEBUG_FUNCPTR (gst_multi_queue_request_new_pad);
742   gstelement_class->release_pad =
743       GST_DEBUG_FUNCPTR (gst_multi_queue_release_pad);
744   gstelement_class->change_state =
745       GST_DEBUG_FUNCPTR (gst_multi_queue_change_state);
746 }
747
748 static void
749 gst_multi_queue_init (GstMultiQueue * mqueue)
750 {
751   mqueue->nbqueues = 0;
752   mqueue->queues = NULL;
753
754   mqueue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
755   mqueue->max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
756   mqueue->max_size.time = DEFAULT_MAX_SIZE_TIME;
757
758   mqueue->extra_size.bytes = DEFAULT_EXTRA_SIZE_BYTES;
759   mqueue->extra_size.visible = DEFAULT_EXTRA_SIZE_BUFFERS;
760   mqueue->extra_size.time = DEFAULT_EXTRA_SIZE_TIME;
761
762   mqueue->use_buffering = DEFAULT_USE_BUFFERING;
763   mqueue->low_watermark = DEFAULT_LOW_WATERMARK * MAX_BUFFERING_LEVEL;
764   mqueue->high_watermark = DEFAULT_HIGH_WATERMARK * MAX_BUFFERING_LEVEL;
765
766   mqueue->sync_by_running_time = DEFAULT_SYNC_BY_RUNNING_TIME;
767   mqueue->use_interleave = DEFAULT_USE_INTERLEAVE;
768   mqueue->min_interleave_time = DEFAULT_MINIMUM_INTERLEAVE;
769   mqueue->unlinked_cache_time = DEFAULT_UNLINKED_CACHE_TIME;
770
771   mqueue->counter = 1;
772   mqueue->highid = -1;
773   mqueue->high_time = GST_CLOCK_STIME_NONE;
774 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
775 /*RVU patch : buffering params init*/
776   mqueue->audio_max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
777   mqueue->audio_max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
778   mqueue->audio_max_size.time = DEFAULT_MAX_SIZE_TIME;
779   mqueue->video_max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
780   mqueue->video_max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
781   mqueue->video_max_size.time = DEFAULT_MAX_SIZE_TIME;
782   mqueue->buffering_start_time = 0;
783   mqueue->stream_duration = 0;
784 /*RVU patch : rvu reset flag, disable audio buffering flag and adaptive buffering flag*/
785   mqueue->buffering_reset = FALSE;
786   mqueue->disable_audio_buffering = FALSE;
787   mqueue->enhancement_buffering = FALSE;
788 #endif
789
790   g_mutex_init (&mqueue->qlock);
791   g_mutex_init (&mqueue->buffering_post_lock);
792 }
793
794 static void
795 gst_multi_queue_finalize (GObject * object)
796 {
797   GstMultiQueue *mqueue = GST_MULTI_QUEUE (object);
798
799   g_list_foreach (mqueue->queues, (GFunc) gst_single_queue_free, NULL);
800   g_list_free (mqueue->queues);
801   mqueue->queues = NULL;
802   mqueue->queues_cookie++;
803
804   /* free/unref instance data */
805   g_mutex_clear (&mqueue->qlock);
806   g_mutex_clear (&mqueue->buffering_post_lock);
807
808   G_OBJECT_CLASS (parent_class)->finalize (object);
809 }
810
811 #define SET_CHILD_PROPERTY(mq,format) G_STMT_START {            \
812     GList * tmp = mq->queues;                                   \
813     while (tmp) {                                               \
814       GstSingleQueue *q = (GstSingleQueue*)tmp->data;           \
815       q->max_size.format = mq->max_size.format;                 \
816       update_buffering (mq, q);                                 \
817       gst_data_queue_limits_changed (q->queue);                 \
818       tmp = g_list_next(tmp);                                   \
819     };                                                          \
820 } G_STMT_END
821
822 static void
823 gst_multi_queue_set_property (GObject * object, guint prop_id,
824     const GValue * value, GParamSpec * pspec)
825 {
826   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
827
828   switch (prop_id) {
829     case PROP_MAX_SIZE_BYTES:
830       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
831       mq->max_size.bytes = g_value_get_uint (value);
832       SET_CHILD_PROPERTY (mq, bytes);
833       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
834       gst_multi_queue_post_buffering (mq);
835       break;
836     case PROP_MAX_SIZE_BUFFERS:
837     {
838       GList *tmp;
839       gint new_size = g_value_get_uint (value);
840
841       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
842
843       mq->max_size.visible = new_size;
844
845       tmp = mq->queues;
846       while (tmp) {
847         GstDataQueueSize size;
848         GstSingleQueue *q = (GstSingleQueue *) tmp->data;
849         gst_data_queue_get_level (q->queue, &size);
850
851         GST_DEBUG_OBJECT (mq, "Queue %d: Requested buffers size: %d,"
852             " current: %d, current max %d", q->id, new_size, size.visible,
853             q->max_size.visible);
854
855         /* do not reduce max size below current level if the single queue
856          * has grown because of empty queue */
857         if (new_size == 0) {
858           q->max_size.visible = new_size;
859         } else if (q->max_size.visible == 0) {
860           q->max_size.visible = MAX (new_size, size.visible);
861         } else if (new_size > size.visible) {
862           q->max_size.visible = new_size;
863         }
864         update_buffering (mq, q);
865         gst_data_queue_limits_changed (q->queue);
866         tmp = g_list_next (tmp);
867       }
868
869       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
870       gst_multi_queue_post_buffering (mq);
871
872       break;
873     }
874     case PROP_MAX_SIZE_TIME:
875       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
876       mq->max_size.time = g_value_get_uint64 (value);
877       SET_CHILD_PROPERTY (mq, time);
878       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
879       gst_multi_queue_post_buffering (mq);
880       break;
881 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
882 /*RVU patch : buffering params property*/
883     case PROP_MAX_AUDIO_SIZE_BYTES:
884       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
885       mq->audio_max_size.bytes = g_value_get_uint (value);
886       SET_CHILD_PROPERTY (mq, bytes);
887       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
888       break;
889     case PROP_MAX_AUDIO_SIZE_BUFFERS:
890       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
891       mq->audio_max_size.visible = g_value_get_uint (value);
892       SET_CHILD_PROPERTY (mq, visible);
893       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
894       break;
895     case PROP_MAX_AUDIO_SIZE_TIME:
896       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
897       mq->audio_max_size.time = g_value_get_uint64 (value);
898       SET_CHILD_PROPERTY (mq, time);
899       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
900       break;
901     case PROP_MAX_VIDEO_SIZE_BYTES:
902       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
903       mq->video_max_size.bytes = g_value_get_uint (value);
904       SET_CHILD_PROPERTY (mq, bytes);
905       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
906       break;
907     case PROP_MAX_VIDEO_SIZE_BUFFERS:
908       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
909       mq->video_max_size.visible = g_value_get_uint (value);
910       SET_CHILD_PROPERTY (mq, visible);
911       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
912       break;
913     case PROP_MAX_VIDEO_SIZE_TIME:
914       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
915       mq->video_max_size.time = g_value_get_uint64 (value);
916       SET_CHILD_PROPERTY (mq, time);
917       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
918       break;
919 #endif
920     case PROP_EXTRA_SIZE_BYTES:
921       mq->extra_size.bytes = g_value_get_uint (value);
922       break;
923     case PROP_EXTRA_SIZE_BUFFERS:
924       mq->extra_size.visible = g_value_get_uint (value);
925       break;
926     case PROP_EXTRA_SIZE_TIME:
927       mq->extra_size.time = g_value_get_uint64 (value);
928       break;
929     case PROP_USE_BUFFERING:
930       mq->use_buffering = g_value_get_boolean (value);
931       recheck_buffering_status (mq);
932       break;
933     case PROP_LOW_PERCENT:
934       mq->low_watermark = g_value_get_int (value) * BUF_LEVEL_PERCENT_FACTOR;
935       /* Recheck buffering status - the new low_watermark value might
936        * be above the current fill level. If the old low_watermark one
937        * was below the current level, this means that mq->buffering is
938        * disabled and needs to be re-enabled. */
939       recheck_buffering_status (mq);
940       break;
941     case PROP_HIGH_PERCENT:
942       mq->high_watermark = g_value_get_int (value) * BUF_LEVEL_PERCENT_FACTOR;
943       recheck_buffering_status (mq);
944       break;
945     case PROP_LOW_WATERMARK:
946       mq->low_watermark = g_value_get_double (value) * MAX_BUFFERING_LEVEL;
947       recheck_buffering_status (mq);
948       break;
949     case PROP_HIGH_WATERMARK:
950       mq->high_watermark = g_value_get_double (value) * MAX_BUFFERING_LEVEL;
951       recheck_buffering_status (mq);
952       break;
953     case PROP_SYNC_BY_RUNNING_TIME:
954       mq->sync_by_running_time = g_value_get_boolean (value);
955       break;
956     case PROP_USE_INTERLEAVE:
957       mq->use_interleave = g_value_get_boolean (value);
958       break;
959     case PROP_UNLINKED_CACHE_TIME:
960       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
961       mq->unlinked_cache_time = g_value_get_uint64 (value);
962       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
963       gst_multi_queue_post_buffering (mq);
964       break;
965     case PROP_MINIMUM_INTERLEAVE:
966       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
967       mq->min_interleave_time = g_value_get_uint64 (value);
968       if (mq->use_interleave)
969         calculate_interleave (mq);
970       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
971       break;
972
973 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
974 /*RVU patch : rvu reset buffering, disable audio buffering and adaptive buffering property*/
975     case PROP_RESET_FLAG:
976       mq->buffering = FALSE;
977       mq->percent = 0;
978       mq->buffering_reset = TRUE;
979       GST_DEBUG_OBJECT (mq, "MQ RESET FLAG!\n");
980       break;
981     case PROP_DISABLE_AUDIO_BUFFERING:
982     {
983       mq->disable_audio_buffering = g_value_get_boolean (value);
984       GST_LOG_OBJECT (mq, "disable-audio-buffering %d\n",
985           mq->disable_audio_buffering);
986     }
987       break;
988     case PROP_BUFFERING_ENHANCEMENT:
989     {
990       mq->enhancement_buffering = g_value_get_boolean (value);
991       GST_LOG_OBJECT (mq, "mq->enhancement_buffering %d\n",
992           mq->enhancement_buffering);
993     }
994       break;
995 #endif
996     default:
997       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
998       break;
999   }
1000 }
1001
1002 #ifdef TIZEN_FEATURE_MQ_MODIFICATION
1003 static guint
1004 get_current_size_bytes (GstMultiQueue * mq)
1005 {
1006   GList *tmp;
1007   GstClockTime highest = GST_CLOCK_TIME_NONE;
1008   GstClockTime lowest = GST_CLOCK_TIME_NONE;
1009   guint current_size_bytes = 0;
1010
1011   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1012     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1013     GstDataQueueSize size;
1014
1015     gst_data_queue_get_level (sq->queue, &size);
1016
1017     current_size_bytes += size.bytes;
1018
1019     GST_DEBUG_OBJECT (mq,
1020         "queue %d: bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1021         G_GUINT64_FORMAT, sq->id, size.bytes, sq->max_size.bytes,
1022         sq->cur_time, sq->max_size.time);
1023   }
1024
1025   GST_INFO_OBJECT (mq, "current_size_bytes : %u", current_size_bytes);
1026
1027   return current_size_bytes;
1028 }
1029 #endif
1030
1031 static void
1032 gst_multi_queue_get_property (GObject * object, guint prop_id,
1033     GValue * value, GParamSpec * pspec)
1034 {
1035   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
1036
1037   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1038
1039   switch (prop_id) {
1040     case PROP_EXTRA_SIZE_BYTES:
1041       g_value_set_uint (value, mq->extra_size.bytes);
1042       break;
1043     case PROP_EXTRA_SIZE_BUFFERS:
1044       g_value_set_uint (value, mq->extra_size.visible);
1045       break;
1046     case PROP_EXTRA_SIZE_TIME:
1047       g_value_set_uint64 (value, mq->extra_size.time);
1048       break;
1049     case PROP_MAX_SIZE_BYTES:
1050       g_value_set_uint (value, mq->max_size.bytes);
1051       break;
1052     case PROP_MAX_SIZE_BUFFERS:
1053       g_value_set_uint (value, mq->max_size.visible);
1054       break;
1055     case PROP_MAX_SIZE_TIME:
1056       g_value_set_uint64 (value, mq->max_size.time);
1057       break;
1058 #ifdef TIZEN_FEATURE_MQ_MODIFICATION
1059     case PROP_CURR_SIZE_BYTES:
1060       g_value_set_uint (value, get_current_size_bytes(mq));
1061       break;
1062 #endif
1063     case PROP_USE_BUFFERING:
1064       g_value_set_boolean (value, mq->use_buffering);
1065       break;
1066     case PROP_LOW_PERCENT:
1067       g_value_set_int (value, mq->low_watermark / BUF_LEVEL_PERCENT_FACTOR);
1068       break;
1069     case PROP_HIGH_PERCENT:
1070       g_value_set_int (value, mq->high_watermark / BUF_LEVEL_PERCENT_FACTOR);
1071       break;
1072     case PROP_LOW_WATERMARK:
1073       g_value_set_double (value, mq->low_watermark /
1074           (gdouble) MAX_BUFFERING_LEVEL);
1075       break;
1076     case PROP_HIGH_WATERMARK:
1077       g_value_set_double (value, mq->high_watermark /
1078           (gdouble) MAX_BUFFERING_LEVEL);
1079       break;
1080     case PROP_SYNC_BY_RUNNING_TIME:
1081       g_value_set_boolean (value, mq->sync_by_running_time);
1082       break;
1083     case PROP_USE_INTERLEAVE:
1084       g_value_set_boolean (value, mq->use_interleave);
1085       break;
1086     case PROP_UNLINKED_CACHE_TIME:
1087       g_value_set_uint64 (value, mq->unlinked_cache_time);
1088       break;
1089     case PROP_MINIMUM_INTERLEAVE:
1090       g_value_set_uint64 (value, mq->min_interleave_time);
1091       break;
1092 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1093 /*RVU patch : rvu disable audio buffering and adaptive buffering property*/
1094     case PROP_DISABLE_AUDIO_BUFFERING:
1095       g_value_set_boolean (value, mq->disable_audio_buffering);
1096       break;
1097     case PROP_BUFFERING_ENHANCEMENT:
1098       g_value_set_boolean (value, mq->enhancement_buffering);
1099       break;
1100 #endif
1101     default:
1102       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1103       break;
1104   }
1105
1106   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1107 }
1108
1109 static GstIterator *
1110 gst_multi_queue_iterate_internal_links (GstPad * pad, GstObject * parent)
1111 {
1112   GstIterator *it = NULL;
1113   GstPad *opad;
1114   GstSingleQueue *squeue;
1115   GstMultiQueue *mq = GST_MULTI_QUEUE (parent);
1116   GValue val = { 0, };
1117
1118   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1119   squeue = gst_pad_get_element_private (pad);
1120   if (!squeue)
1121     goto out;
1122
1123   if (squeue->sinkpad == pad)
1124     opad = gst_object_ref (squeue->srcpad);
1125   else if (squeue->srcpad == pad)
1126     opad = gst_object_ref (squeue->sinkpad);
1127   else
1128     goto out;
1129
1130   g_value_init (&val, GST_TYPE_PAD);
1131   g_value_set_object (&val, opad);
1132   it = gst_iterator_new_single (GST_TYPE_PAD, &val);
1133   g_value_unset (&val);
1134
1135   gst_object_unref (opad);
1136
1137 out:
1138   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1139
1140   return it;
1141 }
1142
1143
1144 /*
1145  * GstElement methods
1146  */
1147
1148 static GstPad *
1149 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
1150     const gchar * name, const GstCaps * caps)
1151 {
1152   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1153   GstSingleQueue *squeue;
1154   GstPad *new_pad;
1155   guint temp_id = -1;
1156
1157   if (name) {
1158     sscanf (name + 4, "_%u", &temp_id);
1159     GST_LOG_OBJECT (element, "name : %s (id %d)", GST_STR_NULL (name), temp_id);
1160   }
1161
1162   /* Create a new single queue, add the sink and source pad and return the sink pad */
1163   squeue = gst_single_queue_new (mqueue, temp_id);
1164
1165   new_pad = squeue ? squeue->sinkpad : NULL;
1166
1167   GST_DEBUG_OBJECT (mqueue, "Returning pad %" GST_PTR_FORMAT, new_pad);
1168
1169   return new_pad;
1170 }
1171
1172 static void
1173 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
1174 {
1175   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1176   GstSingleQueue *sq = NULL;
1177   GList *tmp;
1178
1179   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1180
1181   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1182   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
1183   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1184     sq = (GstSingleQueue *) tmp->data;
1185
1186     if (sq->sinkpad == pad)
1187       break;
1188   }
1189
1190   if (!tmp) {
1191     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
1192     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1193     return;
1194   }
1195
1196   /* FIXME: The removal of the singlequeue should probably not happen until it
1197    * finishes draining */
1198
1199   /* remove it from the list */
1200   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
1201   mqueue->queues_cookie++;
1202
1203   /* FIXME : recompute next-non-linked */
1204   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1205
1206   /* delete SingleQueue */
1207   gst_data_queue_set_flushing (sq->queue, TRUE);
1208
1209   gst_pad_set_active (sq->srcpad, FALSE);
1210   gst_pad_set_active (sq->sinkpad, FALSE);
1211   gst_pad_set_element_private (sq->srcpad, NULL);
1212   gst_pad_set_element_private (sq->sinkpad, NULL);
1213   gst_element_remove_pad (element, sq->srcpad);
1214   gst_element_remove_pad (element, sq->sinkpad);
1215   gst_single_queue_free (sq);
1216 }
1217
1218 static GstStateChangeReturn
1219 gst_multi_queue_change_state (GstElement * element, GstStateChange transition)
1220 {
1221   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1222   GstSingleQueue *sq = NULL;
1223   GstStateChangeReturn result;
1224
1225   switch (transition) {
1226     case GST_STATE_CHANGE_READY_TO_PAUSED:{
1227       GList *tmp;
1228
1229       /* Set all pads to non-flushing */
1230       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1231       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1232         sq = (GstSingleQueue *) tmp->data;
1233         sq->flushing = FALSE;
1234       }
1235
1236       /* the visible limit might not have been set on single queues that have grown because of other queueus were empty */
1237       SET_CHILD_PROPERTY (mqueue, visible);
1238
1239       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1240       gst_multi_queue_post_buffering (mqueue);
1241
1242       break;
1243     }
1244     case GST_STATE_CHANGE_PAUSED_TO_READY:{
1245       GList *tmp;
1246
1247       /* Un-wait all waiting pads */
1248       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1249       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1250         sq = (GstSingleQueue *) tmp->data;
1251         sq->flushing = TRUE;
1252         g_cond_signal (&sq->turn);
1253
1254         sq->last_query = FALSE;
1255         g_cond_signal (&sq->query_handled);
1256       }
1257       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1258       break;
1259     }
1260     default:
1261       break;
1262   }
1263
1264   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1265
1266   switch (transition) {
1267     default:
1268       break;
1269   }
1270
1271   return result;
1272 }
1273
1274 static gboolean
1275 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush,
1276     gboolean full)
1277 {
1278   gboolean result;
1279
1280   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
1281       sq->id);
1282
1283   if (flush) {
1284     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1285     sq->srcresult = GST_FLOW_FLUSHING;
1286     gst_data_queue_set_flushing (sq->queue, TRUE);
1287
1288     sq->flushing = TRUE;
1289
1290     /* wake up non-linked task */
1291     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
1292         sq->id);
1293     g_cond_signal (&sq->turn);
1294     sq->last_query = FALSE;
1295     g_cond_signal (&sq->query_handled);
1296     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1297
1298     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
1299     result = gst_pad_pause_task (sq->srcpad);
1300     sq->sink_tainted = sq->src_tainted = TRUE;
1301   } else {
1302     gst_single_queue_flush_queue (sq, full);
1303
1304     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1305     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
1306     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
1307     sq->has_src_segment = FALSE;
1308     /* All pads start off not-linked for a smooth kick-off */
1309     sq->srcresult = GST_FLOW_OK;
1310     sq->pushed = FALSE;
1311     sq->cur_time = 0;
1312     sq->max_size.visible = mq->max_size.visible;
1313     sq->is_eos = FALSE;
1314     sq->nextid = 0;
1315     sq->oldid = 0;
1316     sq->last_oldid = G_MAXUINT32;
1317     sq->next_time = GST_CLOCK_STIME_NONE;
1318     sq->last_time = GST_CLOCK_STIME_NONE;
1319     sq->cached_sinktime = GST_CLOCK_STIME_NONE;
1320     sq->group_high_time = GST_CLOCK_STIME_NONE;
1321     gst_data_queue_set_flushing (sq->queue, FALSE);
1322
1323     /* We will become active again on the next buffer/gap */
1324     sq->active = FALSE;
1325
1326     /* Reset high time to be recomputed next */
1327     mq->high_time = GST_CLOCK_STIME_NONE;
1328
1329     sq->flushing = FALSE;
1330     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1331
1332     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
1333     result =
1334         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
1335         sq->srcpad, NULL);
1336   }
1337   return result;
1338 }
1339
1340 /* WITH LOCK TAKEN */
1341 static gint
1342 get_buffering_level (GstSingleQueue * sq)
1343 {
1344   GstDataQueueSize size;
1345   gint buffering_level, tmp;
1346
1347   gst_data_queue_get_level (sq->queue, &size);
1348
1349   GST_DEBUG_OBJECT (sq->mqueue,
1350       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1351       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
1352       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1353
1354   /* get bytes and time buffer levels and take the max */
1355   if (sq->is_eos || sq->srcresult == GST_FLOW_NOT_LINKED || sq->is_sparse) {
1356     buffering_level = MAX_BUFFERING_LEVEL;
1357   } else {
1358     buffering_level = 0;
1359     if (sq->max_size.time > 0) {
1360       tmp =
1361           gst_util_uint64_scale (sq->cur_time,
1362           MAX_BUFFERING_LEVEL, sq->max_size.time);
1363       buffering_level = MAX (buffering_level, tmp);
1364     }
1365 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1366     /*RVU patch : rvu adaptive buffering */
1367     if (sq->mqueue->enhancement_buffering == TRUE)
1368       GST_LOG_OBJECT (sq->mqueue,
1369           "MULTIQUEUE ENHANCEMENT BUFFERING SOLUTION ENABLE!\n");
1370
1371     if (sq->mqueue->enhancement_buffering == FALSE) {
1372       if (sq->max_size.bytes > 0) {
1373         tmp = (size.bytes * 100) / sq->max_size.bytes;
1374         percent = MAX (percent, tmp);
1375       }
1376     } else {
1377       GST_LOG_OBJECT (sq->mqueue, "disable bytes buffering profile!\n");
1378     }
1379 #else
1380     if (sq->max_size.bytes > 0) {
1381       tmp =
1382           gst_util_uint64_scale_int (size.bytes,
1383           MAX_BUFFERING_LEVEL, sq->max_size.bytes);
1384       buffering_level = MAX (buffering_level, tmp);
1385     }
1386 #endif
1387   }
1388
1389   return buffering_level;
1390 }
1391
1392 /* WITH LOCK TAKEN */
1393 static void
1394 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
1395 {
1396   gint buffering_level, percent;
1397 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1398   /*RVU patch : disable mq audio buffering solution */
1399   GstPad *audio_pad = NULL;
1400   GstCaps *audio_caps = NULL;
1401   GstStructure *audio_caps_str = NULL;
1402   const char *audio_mime = NULL;
1403   const char *audio_stream_type = NULL;
1404 #endif
1405   /* nothing to dowhen we are not in buffering mode */
1406   if (!mq->use_buffering)
1407     return;
1408
1409 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1410   /*RVU patch : disable mq audio buffering solution */
1411   if ((sq != NULL) && (mq->disable_audio_buffering == TRUE)) {
1412     GST_LOG_OBJECT (mq, "disable audio buffering solution start!\n");
1413     audio_pad = GST_PAD_PEER (sq->sinkpad);
1414     audio_caps = gst_pad_get_current_caps (audio_pad);
1415     if (NULL == audio_caps) {
1416       GST_LOG_OBJECT (mq, "audio caps is null!\n");
1417       goto NEXT_STEP;
1418     }
1419
1420     audio_caps_str = gst_caps_get_structure (audio_caps, 0);
1421     if (NULL == audio_caps_str) {
1422       GST_LOG_OBJECT (mq, "audio caps string is NULL!\n");
1423       goto NEXT_STEP;
1424     }
1425
1426     audio_mime = gst_structure_get_name (audio_caps_str);
1427     if (NULL == audio_mime) {
1428       GST_LOG_OBJECT (mq, "audio caps string mime is NULL!\n");
1429       goto NEXT_STEP;
1430     }
1431
1432     GST_LOG_OBJECT (mq, "audio_mime:[%s]\n", audio_mime);
1433     if (g_strrstr (audio_mime, "audio")) {
1434       GST_LOG_OBJECT (mq,
1435           "non-drm audio single queue!, skip audio buffering\n");
1436       goto LAST_POS;
1437     } else if (g_strrstr (audio_mime, "drm")) {
1438       audio_stream_type =
1439           gst_structure_get_string (audio_caps_str, "stream-type");
1440       if (NULL == audio_stream_type) {
1441         GST_LOG_OBJECT (mq, "drm audio single queue can not get stream-type\n");
1442         goto NEXT_STEP;
1443       }
1444       if (g_strrstr (audio_stream_type, "audio")) {
1445         GST_LOG_OBJECT (mq, "drm audio single queue!, skip audio buffering!\n");
1446         goto LAST_POS;
1447       }
1448     }
1449     GST_LOG_OBJECT (mq, "disable audio buffering solution end!\n");
1450   }
1451
1452 NEXT_STEP:
1453   if (audio_caps != NULL) {
1454     GST_LOG_OBJECT (mq,
1455         "audio caps release for disable audio buffering solution!\n");
1456     gst_caps_unref (audio_caps);
1457     audio_caps = NULL;
1458   }
1459 #endif
1460
1461   buffering_level = get_buffering_level (sq);
1462
1463   /* scale so that if buffering_level equals the high watermark,
1464    * the percentage is 100% */
1465   percent = gst_util_uint64_scale (buffering_level, 100, mq->high_watermark);
1466   /* clip */
1467   if (percent > 100)
1468     percent = 100;
1469
1470   if (mq->buffering) {
1471     if (buffering_level >= mq->high_watermark) {
1472       mq->buffering = FALSE;
1473     }
1474 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1475 /*RVU patch : rvu reset buffering */
1476     if (mq->buffering_reset) {
1477       if (percent < mq->low_percent) {
1478         mq->buffering = TRUE;
1479         mq->percent = percent;
1480         mq->percent_changed = TRUE;
1481       }
1482     }
1483 #endif
1484     /* make sure it increases */
1485     percent = MAX (mq->buffering_percent, percent);
1486
1487     SET_PERCENT (mq, percent);
1488 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1489 /*RVU patch : adaptive buffering solution*/
1490     if (mq->enhancement_buffering == TRUE) {
1491       if (percent >= mq->high_percent) {
1492         mq->percent_changed = TRUE;
1493         GST_LOG_OBJECT (mq, "MULTIQUEUE ENHANCEMENT BUFFERING!\n");
1494       }
1495     }
1496 #endif
1497   } else {
1498     GList *iter;
1499     gboolean is_buffering = TRUE;
1500
1501     for (iter = mq->queues; iter; iter = g_list_next (iter)) {
1502       GstSingleQueue *oq = (GstSingleQueue *) iter->data;
1503
1504       if (get_buffering_level (oq) >= mq->high_watermark) {
1505         is_buffering = FALSE;
1506
1507         break;
1508       }
1509     }
1510
1511     if (is_buffering && buffering_level < mq->low_watermark) {
1512       mq->buffering = TRUE;
1513       SET_PERCENT (mq, percent);
1514     }
1515   }
1516 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1517 /*common update buffering */
1518 /*while starts buffering, need restore start time */
1519   if (mq->enable_buffering_opt) {
1520     if (percent < mq->low_percent && mq->buffering == TRUE) {
1521       struct timeval tv = { 0 };
1522       GList *iter = NULL;
1523       gettimeofday (&tv, NULL);
1524
1525       mq->buffering_start_time =
1526           GST_SECOND * (guint64) tv.tv_sec + (guint64) tv.tv_usec * GST_USECOND;
1527       /*update all single queue */
1528       for (iter = mq->queues; iter; iter = g_list_next (iter)) {
1529         GstSingleQueue *oq = (GstSingleQueue *) iter->data;
1530         oq->cur_time_of_begin_buffering = oq->cur_time;
1531       }
1532       GST_DEBUG_OBJECT (mq,
1533           "update buffering start time, cur_time is : %" G_GUINT64_FORMAT,
1534           sq->cur_time_of_begin_buffering);
1535     } else if (mq->buffering == TRUE) {
1536       struct timeval tv = { 0 };
1537       gettimeofday (&tv, NULL);
1538       GstClockTime buffering_duration = sq->cur_time;
1539       guint64 tmp_time =
1540           GST_SECOND * (guint64) tv.tv_sec + (guint64) tv.tv_usec * GST_USECOND;
1541       guint64 elapsed_time = 0;
1542
1543       /*caculate elapsed time */
1544       tmp_time -= mq->buffering_start_time;
1545       elapsed_time = tmp_time;
1546       /*buffering percentage increase until its src pad is blocked,  */
1547       if (sq->cur_time > sq->cur_time_of_begin_buffering)
1548         buffering_duration = sq->cur_time - sq->cur_time_of_begin_buffering;
1549
1550       GST_DEBUG_OBJECT (mq,
1551           "%s, elapsed time is: %" G_GUINT64_FORMAT " cur_time is: %"
1552           G_GUINT64_FORMAT, sq->sq_stream_type == SQ_VIDEO_STREAM ? "vq" : "aq",
1553           elapsed_time, buffering_duration);
1554       tmp_time /= GST_SECOND;
1555
1556       /*demuxer speed is lower than decoder */
1557       if (tmp_time > 0 && (tmp_time % 3 == 0)
1558           && buffering_duration < elapsed_time
1559           && sq->sq_stream_type == SQ_VIDEO_STREAM) {
1560         GstFormat format = GST_FORMAT_TIME;
1561         guint64 cur_position = sq->srctime;
1562         GstCaps *video_caps = NULL;
1563         GstStructure *caps_structure = NULL;
1564         gint rnum = 0, rdenom = 1;
1565         gint r_framerate = 0, remaining_frame = 0, instant_throughput =
1566             0, estimated_video_frame_count = 0;
1567         GstDataQueueSize size;
1568
1569         if (cur_position <= 0 || mq->stream_duration <= 0) {
1570           GST_DEBUG_OBJECT (mq, "no duration or position");
1571           return;
1572         }
1573         gst_data_queue_get_level (sq->queue, &size);
1574
1575         video_caps = gst_pad_get_current_caps (sq->sinkpad);
1576         GST_DEBUG_OBJECT (mq, "stream caps: %" GST_PTR_FORMAT, video_caps);
1577
1578         if (video_caps != NULL) {
1579           caps_structure = gst_caps_get_structure (video_caps, 0);
1580
1581           if (caps_structure != NULL)
1582             gst_structure_get_fraction (caps_structure, "r_framerate", &rnum,
1583                 &rdenom);
1584
1585           gst_caps_unref (video_caps);
1586         }
1587
1588         else
1589           return;
1590
1591         if (rdenom != 0)
1592           r_framerate = rnum / rdenom;
1593
1594         GST_DEBUG_OBJECT (mq, "r_framerate is %d ", r_framerate);
1595
1596         remaining_frame = (mq->stream_duration - cur_position) * r_framerate / GST_SECOND - size.visible;       // packets num in video queue;
1597         instant_throughput = size.visible * GST_SECOND / elapsed_time;  // packets num / per seconds
1598         GST_DEBUG_OBJECT (mq, "remaining_fram is %d, instant_throughput is %d",
1599             remaining_frame, instant_throughput);
1600         if (remaining_frame != 0)
1601           estimated_video_frame_count =
1602               (int) ((remaining_frame * r_framerate) / (r_framerate +
1603                   instant_throughput));
1604       }
1605     }
1606   }
1607 #endif
1608 #ifdef TIZEN_PROFILE_TV
1609 /*RVU patch : rvu case disable audio buffering */
1610   return;
1611 LAST_POS:
1612   if (audio_caps != NULL) {
1613     gst_caps_unref (audio_caps);
1614     audio_caps = NULL;
1615   }
1616   GST_LOG_OBJECT (mq, "DISABLE AUDIO BUFFERING MESSAGE HANDLE!\n");
1617   return;
1618 #endif
1619 }
1620
1621 static void
1622 gst_multi_queue_post_buffering (GstMultiQueue * mq)
1623 {
1624   GstMessage *msg = NULL;
1625
1626   g_mutex_lock (&mq->buffering_post_lock);
1627   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1628   if (mq->buffering_percent_changed) {
1629     gint percent = mq->buffering_percent;
1630
1631     mq->buffering_percent_changed = FALSE;
1632
1633     GST_DEBUG_OBJECT (mq, "Going to post buffering: %d%%", percent);
1634     msg = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
1635   }
1636   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1637
1638   if (msg != NULL)
1639     gst_element_post_message (GST_ELEMENT_CAST (mq), msg);
1640
1641   g_mutex_unlock (&mq->buffering_post_lock);
1642 }
1643
1644 static void
1645 recheck_buffering_status (GstMultiQueue * mq)
1646 {
1647   if (!mq->use_buffering && mq->buffering) {
1648     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1649     mq->buffering = FALSE;
1650     GST_DEBUG_OBJECT (mq,
1651         "Buffering property disabled, but queue was still buffering; "
1652         "setting buffering percentage to 100%%");
1653     SET_PERCENT (mq, 100);
1654     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1655   }
1656
1657   if (mq->use_buffering) {
1658     GList *tmp;
1659     gint old_perc;
1660
1661     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1662
1663     /* force buffering percentage to be recalculated */
1664     old_perc = mq->buffering_percent;
1665     mq->buffering_percent = 0;
1666
1667     tmp = mq->queues;
1668     while (tmp) {
1669       GstSingleQueue *q = (GstSingleQueue *) tmp->data;
1670       update_buffering (mq, q);
1671       gst_data_queue_limits_changed (q->queue);
1672       tmp = g_list_next (tmp);
1673     }
1674
1675     GST_DEBUG_OBJECT (mq,
1676         "Recalculated buffering percentage: old: %d%% new: %d%%",
1677         old_perc, mq->buffering_percent);
1678
1679     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1680   }
1681
1682   gst_multi_queue_post_buffering (mq);
1683 }
1684
1685 static void
1686 calculate_interleave (GstMultiQueue * mq)
1687 {
1688   GstClockTimeDiff low, high;
1689   GstClockTime interleave;
1690   GList *tmp;
1691
1692   low = high = GST_CLOCK_STIME_NONE;
1693   interleave = mq->interleave;
1694   /* Go over all single queues and calculate lowest/highest value */
1695   for (tmp = mq->queues; tmp; tmp = tmp->next) {
1696     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1697     /* Ignore sparse streams for interleave calculation */
1698     if (sq->is_sparse)
1699       continue;
1700     /* If a stream is not active yet (hasn't received any buffers), set
1701      * a maximum interleave to allow it to receive more data */
1702     if (!sq->active) {
1703       GST_LOG_OBJECT (mq,
1704           "queue %d is not active yet, forcing interleave to 5s", sq->id);
1705       mq->interleave = 5 * GST_SECOND;
1706       /* Update max-size time */
1707       mq->max_size.time = mq->interleave;
1708       SET_CHILD_PROPERTY (mq, time);
1709       goto beach;
1710     }
1711     if (GST_CLOCK_STIME_IS_VALID (sq->cached_sinktime)) {
1712       if (low == GST_CLOCK_STIME_NONE || sq->cached_sinktime < low)
1713         low = sq->cached_sinktime;
1714       if (high == GST_CLOCK_STIME_NONE || sq->cached_sinktime > high)
1715         high = sq->cached_sinktime;
1716     }
1717     GST_LOG_OBJECT (mq,
1718         "queue %d , sinktime:%" GST_STIME_FORMAT " low:%" GST_STIME_FORMAT
1719         " high:%" GST_STIME_FORMAT, sq->id,
1720         GST_STIME_ARGS (sq->cached_sinktime), GST_STIME_ARGS (low),
1721         GST_STIME_ARGS (high));
1722   }
1723
1724   if (GST_CLOCK_STIME_IS_VALID (low) && GST_CLOCK_STIME_IS_VALID (high)) {
1725     interleave = high - low;
1726     /* Padding of interleave and minimum value */
1727     interleave = (150 * interleave / 100) + mq->min_interleave_time;
1728
1729     /* Update the stored interleave if:
1730      * * No data has arrived yet (high == low)
1731      * * Or it went higher
1732      * * Or it went lower and we've gone past the previous interleave needed */
1733     if (high == low || interleave > mq->interleave ||
1734         ((mq->last_interleave_update + (2 * MIN (GST_SECOND,
1735                         mq->interleave)) < low)
1736             && interleave < (mq->interleave * 3 / 4))) {
1737       /* Update the interleave */
1738       mq->interleave = interleave;
1739       mq->last_interleave_update = high;
1740       /* Update max-size time */
1741       mq->max_size.time = mq->interleave;
1742       SET_CHILD_PROPERTY (mq, time);
1743     }
1744   }
1745
1746 beach:
1747   GST_DEBUG_OBJECT (mq,
1748       "low:%" GST_STIME_FORMAT " high:%" GST_STIME_FORMAT " interleave:%"
1749       GST_TIME_FORMAT " mq->interleave:%" GST_TIME_FORMAT
1750       " last_interleave_update:%" GST_STIME_FORMAT, GST_STIME_ARGS (low),
1751       GST_STIME_ARGS (high), GST_TIME_ARGS (interleave),
1752       GST_TIME_ARGS (mq->interleave),
1753       GST_STIME_ARGS (mq->last_interleave_update));
1754 }
1755
1756
1757 /* calculate the diff between running time on the sink and src of the queue.
1758  * This is the total amount of time in the queue.
1759  * WITH LOCK TAKEN */
1760 static void
1761 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
1762 {
1763   GstClockTimeDiff sink_time, src_time;
1764
1765   if (sq->sink_tainted) {
1766     sink_time = sq->sinktime = my_segment_to_running_time (&sq->sink_segment,
1767         sq->sink_segment.position);
1768
1769     GST_DEBUG_OBJECT (mq,
1770         "queue %d sink_segment.position:%" GST_TIME_FORMAT ", sink_time:%"
1771         GST_STIME_FORMAT, sq->id, GST_TIME_ARGS (sq->sink_segment.position),
1772         GST_STIME_ARGS (sink_time));
1773
1774     if (G_UNLIKELY (sq->last_time == GST_CLOCK_STIME_NONE)) {
1775       /* If the single queue still doesn't have a last_time set, this means
1776        * that nothing has been pushed out yet.
1777        * In order for the high_time computation to be as efficient as possible,
1778        * we set the last_time */
1779       sq->last_time = sink_time;
1780     }
1781     if (G_UNLIKELY (sink_time != GST_CLOCK_STIME_NONE)) {
1782       /* if we have a time, we become untainted and use the time */
1783       sq->sink_tainted = FALSE;
1784       if (mq->use_interleave) {
1785         sq->cached_sinktime = sink_time;
1786         calculate_interleave (mq);
1787       }
1788     }
1789   } else
1790     sink_time = sq->sinktime;
1791
1792   if (sq->src_tainted) {
1793     GstSegment *segment;
1794     gint64 position;
1795
1796     if (sq->has_src_segment) {
1797       segment = &sq->src_segment;
1798       position = sq->src_segment.position;
1799     } else {
1800       /*
1801        * If the src pad had no segment yet, use the sink segment
1802        * to avoid signalling overrun if the received sink segment has a
1803        * a position > max-size-time while the src pad time would be the default=0
1804        *
1805        * This can happen when switching pads on chained/adaptive streams and the
1806        * new chain has a segment with a much larger position
1807        */
1808       segment = &sq->sink_segment;
1809       position = sq->sink_segment.position;
1810     }
1811
1812     src_time = sq->srctime = my_segment_to_running_time (segment, position);
1813     /* if we have a time, we become untainted and use the time */
1814     if (G_UNLIKELY (src_time != GST_CLOCK_STIME_NONE)) {
1815       sq->src_tainted = FALSE;
1816     }
1817   } else
1818     src_time = sq->srctime;
1819
1820   GST_DEBUG_OBJECT (mq,
1821       "queue %d, sink %" GST_STIME_FORMAT ", src %" GST_STIME_FORMAT, sq->id,
1822       GST_STIME_ARGS (sink_time), GST_STIME_ARGS (src_time));
1823
1824   /* This allows for streams with out of order timestamping - sometimes the
1825    * emerging timestamp is later than the arriving one(s) */
1826   if (G_LIKELY (GST_CLOCK_STIME_IS_VALID (sink_time) &&
1827           GST_CLOCK_STIME_IS_VALID (src_time) && sink_time > src_time))
1828     sq->cur_time = sink_time - src_time;
1829   else
1830     sq->cur_time = 0;
1831
1832   /* updating the time level can change the buffering state */
1833   update_buffering (mq, sq);
1834
1835   return;
1836 }
1837
1838 /* take a SEGMENT event and apply the values to segment, updating the time
1839  * level of queue. */
1840 static void
1841 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
1842     GstSegment * segment)
1843 {
1844   gst_event_copy_segment (event, segment);
1845
1846   /* now configure the values, we use these to track timestamps on the
1847    * sinkpad. */
1848   if (segment->format != GST_FORMAT_TIME) {
1849     /* non-time format, pretent the current time segment is closed with a
1850      * 0 start and unknown stop time. */
1851     segment->format = GST_FORMAT_TIME;
1852     segment->start = 0;
1853     segment->stop = -1;
1854     segment->time = 0;
1855   }
1856   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1857
1858   /* Make sure we have a valid initial segment position (and not garbage
1859    * from upstream) */
1860   if (segment->rate > 0.0)
1861     segment->position = segment->start;
1862   else
1863     segment->position = segment->stop;
1864   if (segment == &sq->sink_segment)
1865     sq->sink_tainted = TRUE;
1866   else {
1867     sq->has_src_segment = TRUE;
1868     sq->src_tainted = TRUE;
1869   }
1870
1871   GST_DEBUG_OBJECT (mq,
1872       "queue %d, configured SEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
1873
1874   /* segment can update the time level of the queue */
1875   update_time_level (mq, sq);
1876
1877   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1878   gst_multi_queue_post_buffering (mq);
1879 }
1880
1881 /* take a buffer and update segment, updating the time level of the queue. */
1882 static void
1883 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
1884     GstClockTime duration, GstSegment * segment)
1885 {
1886   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1887
1888   /* if no timestamp is set, assume it's continuous with the previous
1889    * time */
1890   if (timestamp == GST_CLOCK_TIME_NONE)
1891     timestamp = segment->position;
1892
1893   /* add duration */
1894   if (duration != GST_CLOCK_TIME_NONE)
1895     timestamp += duration;
1896
1897   GST_DEBUG_OBJECT (mq, "queue %d, %s position updated to %" GST_TIME_FORMAT,
1898       sq->id, segment == &sq->sink_segment ? "sink" : "src",
1899       GST_TIME_ARGS (timestamp));
1900
1901   segment->position = timestamp;
1902
1903   if (segment == &sq->sink_segment)
1904     sq->sink_tainted = TRUE;
1905   else
1906     sq->src_tainted = TRUE;
1907
1908   /* calc diff with other end */
1909   update_time_level (mq, sq);
1910   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1911   gst_multi_queue_post_buffering (mq);
1912 }
1913
1914 static void
1915 apply_gap (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
1916     GstSegment * segment)
1917 {
1918   GstClockTime timestamp;
1919   GstClockTime duration;
1920
1921   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1922
1923   gst_event_parse_gap (event, &timestamp, &duration);
1924
1925   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1926
1927     if (GST_CLOCK_TIME_IS_VALID (duration)) {
1928       timestamp += duration;
1929     }
1930
1931     segment->position = timestamp;
1932
1933     if (segment == &sq->sink_segment)
1934       sq->sink_tainted = TRUE;
1935     else
1936       sq->src_tainted = TRUE;
1937
1938     /* calc diff with other end */
1939     update_time_level (mq, sq);
1940   }
1941
1942   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1943   gst_multi_queue_post_buffering (mq);
1944 }
1945
1946 static GstClockTimeDiff
1947 get_running_time (GstSegment * segment, GstMiniObject * object, gboolean end)
1948 {
1949   GstClockTimeDiff time = GST_CLOCK_STIME_NONE;
1950
1951   if (GST_IS_BUFFER (object)) {
1952     GstBuffer *buf = GST_BUFFER_CAST (object);
1953     GstClockTime btime = GST_BUFFER_DTS_OR_PTS (buf);
1954
1955     if (GST_CLOCK_TIME_IS_VALID (btime)) {
1956       if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1957         btime += GST_BUFFER_DURATION (buf);
1958       if (btime > segment->stop)
1959         btime = segment->stop;
1960       time = my_segment_to_running_time (segment, btime);
1961     }
1962   } else if (GST_IS_BUFFER_LIST (object)) {
1963     GstBufferList *list = GST_BUFFER_LIST_CAST (object);
1964     gint i, n;
1965     GstBuffer *buf;
1966
1967     n = gst_buffer_list_length (list);
1968     for (i = 0; i < n; i++) {
1969       GstClockTime btime;
1970       buf = gst_buffer_list_get (list, i);
1971       btime = GST_BUFFER_DTS_OR_PTS (buf);
1972       if (GST_CLOCK_TIME_IS_VALID (btime)) {
1973         if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1974           btime += GST_BUFFER_DURATION (buf);
1975         if (btime > segment->stop)
1976           btime = segment->stop;
1977         time = my_segment_to_running_time (segment, btime);
1978         if (!end)
1979           goto done;
1980       } else if (!end) {
1981         goto done;
1982       }
1983     }
1984   } else if (GST_IS_EVENT (object)) {
1985     GstEvent *event = GST_EVENT_CAST (object);
1986
1987     /* For newsegment events return the running time of the start position */
1988     if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
1989       const GstSegment *new_segment;
1990
1991       gst_event_parse_segment (event, &new_segment);
1992       if (new_segment->format == GST_FORMAT_TIME) {
1993         time =
1994             my_segment_to_running_time ((GstSegment *) new_segment,
1995             new_segment->start);
1996       }
1997     }
1998   }
1999
2000 done:
2001   return time;
2002 }
2003
2004 static GstFlowReturn
2005 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
2006     GstMiniObject * object, gboolean * allow_drop)
2007 {
2008   GstFlowReturn result = sq->srcresult;
2009
2010   if (GST_IS_BUFFER (object)) {
2011     GstBuffer *buffer;
2012     GstClockTime timestamp, duration;
2013
2014     buffer = GST_BUFFER_CAST (object);
2015     timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2016     duration = GST_BUFFER_DURATION (buffer);
2017
2018     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
2019
2020     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
2021     gst_data_queue_limits_changed (sq->queue);
2022
2023     if (G_UNLIKELY (*allow_drop)) {
2024       GST_DEBUG_OBJECT (mq,
2025           "SingleQueue %d : Dropping EOS buffer %p with ts %" GST_TIME_FORMAT,
2026           sq->id, buffer, GST_TIME_ARGS (timestamp));
2027       gst_buffer_unref (buffer);
2028     } else {
2029       GST_DEBUG_OBJECT (mq,
2030           "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
2031           sq->id, buffer, GST_TIME_ARGS (timestamp));
2032       result = gst_pad_push (sq->srcpad, buffer);
2033     }
2034   } else if (GST_IS_EVENT (object)) {
2035     GstEvent *event;
2036
2037     event = GST_EVENT_CAST (object);
2038
2039     switch (GST_EVENT_TYPE (event)) {
2040       case GST_EVENT_EOS:
2041         result = GST_FLOW_EOS;
2042         if (G_UNLIKELY (*allow_drop))
2043           *allow_drop = FALSE;
2044         break;
2045       case GST_EVENT_SEGMENT:
2046         apply_segment (mq, sq, event, &sq->src_segment);
2047         /* Applying the segment may have made the queue non-full again, unblock it if needed */
2048         gst_data_queue_limits_changed (sq->queue);
2049         if (G_UNLIKELY (*allow_drop)) {
2050           result = GST_FLOW_OK;
2051           *allow_drop = FALSE;
2052         }
2053         break;
2054       case GST_EVENT_GAP:
2055         apply_gap (mq, sq, event, &sq->src_segment);
2056         /* Applying the gap may have made the queue non-full again, unblock it if needed */
2057         gst_data_queue_limits_changed (sq->queue);
2058         break;
2059       default:
2060         break;
2061     }
2062
2063     if (G_UNLIKELY (*allow_drop)) {
2064       GST_DEBUG_OBJECT (mq,
2065           "SingleQueue %d : Dropping EOS event %p of type %s",
2066           sq->id, event, GST_EVENT_TYPE_NAME (event));
2067       gst_event_unref (event);
2068     } else {
2069       GST_DEBUG_OBJECT (mq,
2070           "SingleQueue %d : Pushing event %p of type %s",
2071           sq->id, event, GST_EVENT_TYPE_NAME (event));
2072
2073       gst_pad_push_event (sq->srcpad, event);
2074     }
2075   } else if (GST_IS_QUERY (object)) {
2076     GstQuery *query;
2077     gboolean res;
2078
2079     query = GST_QUERY_CAST (object);
2080
2081     if (G_UNLIKELY (*allow_drop)) {
2082       GST_DEBUG_OBJECT (mq,
2083           "SingleQueue %d : Dropping EOS query %p", sq->id, query);
2084       gst_query_unref (query);
2085       res = FALSE;
2086     } else {
2087       res = gst_pad_peer_query (sq->srcpad, query);
2088     }
2089
2090     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2091     sq->last_query = res;
2092     sq->last_handled_query = query;
2093     g_cond_signal (&sq->query_handled);
2094     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2095   } else {
2096     g_warning ("Unexpected object in singlequeue %u (refcounting problem?)",
2097         sq->id);
2098   }
2099   return result;
2100
2101   /* ERRORS */
2102 }
2103
2104 static GstMiniObject *
2105 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
2106 {
2107   GstMiniObject *res;
2108
2109   res = item->object;
2110   item->object = NULL;
2111
2112   return res;
2113 }
2114
2115 static void
2116 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
2117 {
2118   if (!item->is_query && item->object)
2119     gst_mini_object_unref (item->object);
2120   g_slice_free (GstMultiQueueItem, item);
2121 }
2122
2123 /* takes ownership of passed mini object! */
2124 static GstMultiQueueItem *
2125 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
2126 {
2127   GstMultiQueueItem *item;
2128
2129   item = g_slice_new (GstMultiQueueItem);
2130   item->object = object;
2131   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
2132   item->posid = curid;
2133   item->is_query = GST_IS_QUERY (object);
2134
2135   item->size = gst_buffer_get_size (GST_BUFFER_CAST (object));
2136   item->duration = GST_BUFFER_DURATION (object);
2137   if (item->duration == GST_CLOCK_TIME_NONE)
2138     item->duration = 0;
2139   item->visible = TRUE;
2140   return item;
2141 }
2142
2143 static GstMultiQueueItem *
2144 gst_multi_queue_mo_item_new (GstMiniObject * object, guint32 curid)
2145 {
2146   GstMultiQueueItem *item;
2147
2148   item = g_slice_new (GstMultiQueueItem);
2149   item->object = object;
2150   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
2151   item->posid = curid;
2152   item->is_query = GST_IS_QUERY (object);
2153
2154   item->size = 0;
2155   item->duration = 0;
2156   item->visible = FALSE;
2157   return item;
2158 }
2159
2160 /* Each main loop attempts to push buffers until the return value
2161  * is not-linked. not-linked pads are not allowed to push data beyond
2162  * any linked pads, so they don't 'rush ahead of the pack'.
2163  */
2164 static void
2165 gst_multi_queue_loop (GstPad * pad)
2166 {
2167   GstSingleQueue *sq;
2168   GstMultiQueueItem *item;
2169   GstDataQueueItem *sitem;
2170   GstMultiQueue *mq;
2171   GstMiniObject *object = NULL;
2172   guint32 newid;
2173   GstFlowReturn result;
2174   GstClockTimeDiff next_time;
2175   gboolean is_buffer;
2176   gboolean do_update_buffering = FALSE;
2177   gboolean dropping = FALSE;
2178
2179   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2180   mq = sq->mqueue;
2181
2182 next:
2183   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
2184
2185   if (sq->flushing)
2186     goto out_flushing;
2187 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
2188   if (mq->stream_duration == 0) {
2189     GstPad *peer = NULL;
2190     peer = gst_pad_get_peer (sq->sinkpad);
2191     if (peer) {
2192       if (!gst_pad_query_duration (peer, GST_FORMAT_TIME,
2193               &(mq->stream_duration)))
2194         GST_WARNING_OBJECT (mq, "Could not query upstream length!");
2195       gst_object_unref (peer);
2196     }
2197   }
2198 #endif
2199   /* Get something from the queue, blocking until that happens, or we get
2200    * flushed */
2201   if (!(gst_data_queue_pop (sq->queue, &sitem)))
2202     goto out_flushing;
2203
2204   item = (GstMultiQueueItem *) sitem;
2205   newid = item->posid;
2206
2207   /* steal the object and destroy the item */
2208   object = gst_multi_queue_item_steal_object (item);
2209   gst_multi_queue_item_destroy (item);
2210
2211   is_buffer = GST_IS_BUFFER (object);
2212
2213   /* Get running time of the item. Events will have GST_CLOCK_STIME_NONE */
2214   next_time = get_running_time (&sq->src_segment, object, FALSE);
2215
2216   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
2217       sq->id, newid, sq->last_oldid);
2218
2219   /* If we're not-linked, we do some extra work because we might need to
2220    * wait before pushing. If we're linked but there's a gap in the IDs,
2221    * or it's the first loop, or we just passed the previous highid,
2222    * we might need to wake some sleeping pad up, so there's extra work
2223    * there too */
2224   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2225   if (sq->srcresult == GST_FLOW_NOT_LINKED
2226       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
2227       || sq->last_oldid > mq->highid) {
2228     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
2229         gst_flow_get_name (sq->srcresult));
2230
2231     /* Check again if we're flushing after the lock is taken,
2232      * the flush flag might have been changed in the meantime */
2233     if (sq->flushing) {
2234       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2235       goto out_flushing;
2236     }
2237
2238     /* Update the nextid so other threads know when to wake us up */
2239     sq->nextid = newid;
2240     /* Take into account the extra cache time since we're unlinked */
2241     if (GST_CLOCK_STIME_IS_VALID (next_time))
2242       next_time += mq->unlinked_cache_time;
2243     sq->next_time = next_time;
2244
2245     /* Update the oldid (the last ID we output) for highid tracking */
2246     if (sq->last_oldid != G_MAXUINT32)
2247       sq->oldid = sq->last_oldid;
2248
2249     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2250       gboolean should_wait;
2251       /* Go to sleep until it's time to push this buffer */
2252
2253       /* Recompute the highid */
2254       compute_high_id (mq);
2255       /* Recompute the high time */
2256       compute_high_time (mq, sq->groupid);
2257
2258       GST_DEBUG_OBJECT (mq,
2259           "groupid %d high_time %" GST_STIME_FORMAT " next_time %"
2260           GST_STIME_FORMAT, sq->groupid, GST_STIME_ARGS (sq->group_high_time),
2261           GST_STIME_ARGS (next_time));
2262
2263       if (mq->sync_by_running_time) {
2264         if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2265           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2266               (mq->high_time == GST_CLOCK_STIME_NONE
2267               || next_time > mq->high_time);
2268         } else {
2269           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2270               next_time > sq->group_high_time;
2271         }
2272       } else
2273         should_wait = newid > mq->highid;
2274
2275       while (should_wait && sq->srcresult == GST_FLOW_NOT_LINKED) {
2276
2277         GST_DEBUG_OBJECT (mq,
2278             "queue %d sleeping for not-linked wakeup with "
2279             "newid %u, highid %u, next_time %" GST_STIME_FORMAT
2280             ", high_time %" GST_STIME_FORMAT, sq->id, newid, mq->highid,
2281             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time));
2282
2283         /* Wake up all non-linked pads before we sleep */
2284         wake_up_next_non_linked (mq);
2285
2286         mq->numwaiting++;
2287         g_cond_wait (&sq->turn, &mq->qlock);
2288         mq->numwaiting--;
2289
2290         if (sq->flushing) {
2291           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2292           goto out_flushing;
2293         }
2294
2295         /* Recompute the high time and ID */
2296         compute_high_time (mq, sq->groupid);
2297         compute_high_id (mq);
2298
2299         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
2300             "wakeup with newid %u, highid %u, next_time %" GST_STIME_FORMAT
2301             ", high_time %" GST_STIME_FORMAT " mq high_time %" GST_STIME_FORMAT,
2302             sq->id, newid, mq->highid,
2303             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time),
2304             GST_STIME_ARGS (mq->high_time));
2305
2306         if (mq->sync_by_running_time) {
2307           if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2308             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2309                 (mq->high_time == GST_CLOCK_STIME_NONE
2310                 || next_time > mq->high_time);
2311           } else {
2312             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2313                 next_time > sq->group_high_time;
2314           }
2315         } else
2316           should_wait = newid > mq->highid;
2317       }
2318
2319       /* Re-compute the high_id in case someone else pushed */
2320       compute_high_id (mq);
2321       compute_high_time (mq, sq->groupid);
2322     } else {
2323       compute_high_id (mq);
2324       compute_high_time (mq, sq->groupid);
2325       /* Wake up all non-linked pads */
2326       wake_up_next_non_linked (mq);
2327     }
2328     /* We're done waiting, we can clear the nextid and nexttime */
2329     sq->nextid = 0;
2330     sq->next_time = GST_CLOCK_STIME_NONE;
2331   }
2332   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2333
2334   if (sq->flushing)
2335     goto out_flushing;
2336
2337   GST_LOG_OBJECT (mq, "sq:%d BEFORE PUSHING sq->srcresult: %s", sq->id,
2338       gst_flow_get_name (sq->srcresult));
2339
2340   /* Update time stats */
2341   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2342   next_time = get_running_time (&sq->src_segment, object, TRUE);
2343   if (GST_CLOCK_STIME_IS_VALID (next_time)) {
2344     if (sq->last_time == GST_CLOCK_STIME_NONE || sq->last_time < next_time)
2345       sq->last_time = next_time;
2346     if (mq->high_time == GST_CLOCK_STIME_NONE || mq->high_time <= next_time) {
2347       /* Wake up all non-linked pads now that we advanced the high time */
2348       mq->high_time = next_time;
2349       wake_up_next_non_linked (mq);
2350     }
2351   }
2352   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2353
2354   /* Try to push out the new object */
2355   result = gst_single_queue_push_one (mq, sq, object, &dropping);
2356   object = NULL;
2357
2358   /* Check if we pushed something already and if this is
2359    * now a switch from an active to a non-active stream.
2360    *
2361    * If it is, we reset all the waiting streams, let them
2362    * push another buffer to see if they're now active again.
2363    * This allows faster switching between streams and prevents
2364    * deadlocks if downstream does any waiting too.
2365    */
2366   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2367   if (sq->pushed && sq->srcresult == GST_FLOW_OK
2368       && result == GST_FLOW_NOT_LINKED) {
2369     GList *tmp;
2370
2371     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
2372         sq->id);
2373
2374     compute_high_id (mq);
2375     compute_high_time (mq, sq->groupid);
2376     do_update_buffering = TRUE;
2377
2378     /* maybe no-one is waiting */
2379     if (mq->numwaiting > 0) {
2380       /* Else figure out which singlequeue(s) need waking up */
2381       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2382         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
2383
2384         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
2385           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
2386           sq2->pushed = FALSE;
2387           sq2->srcresult = GST_FLOW_OK;
2388           g_cond_signal (&sq2->turn);
2389         }
2390       }
2391     }
2392   }
2393
2394   if (is_buffer)
2395     sq->pushed = TRUE;
2396
2397   /* now hold on a bit;
2398    * can not simply throw this result to upstream, because
2399    * that might already be onto another segment, so we have to make
2400    * sure we are relaying the correct info wrt proper segment */
2401   if (result == GST_FLOW_EOS && !dropping &&
2402       sq->srcresult != GST_FLOW_NOT_LINKED) {
2403     GST_DEBUG_OBJECT (mq, "starting EOS drop on sq %d", sq->id);
2404     dropping = TRUE;
2405     /* pretend we have not seen EOS yet for upstream's sake */
2406     result = sq->srcresult;
2407   } else if (dropping && gst_data_queue_is_empty (sq->queue)) {
2408     /* queue empty, so stop dropping
2409      * we can commit the result we have now,
2410      * which is either OK after a segment, or EOS */
2411     GST_DEBUG_OBJECT (mq, "committed EOS drop on sq %d", sq->id);
2412     dropping = FALSE;
2413     result = GST_FLOW_EOS;
2414   }
2415   sq->srcresult = result;
2416   sq->last_oldid = newid;
2417
2418   if (do_update_buffering)
2419     update_buffering (mq, sq);
2420
2421   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2422   gst_multi_queue_post_buffering (mq);
2423
2424   GST_LOG_OBJECT (mq, "sq:%d AFTER PUSHING sq->srcresult: %s (is_eos:%d)",
2425       sq->id, gst_flow_get_name (sq->srcresult), GST_PAD_IS_EOS (sq->srcpad));
2426
2427   /* Need to make sure wake up any sleeping pads when we exit */
2428   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2429   if (mq->numwaiting > 0 && (GST_PAD_IS_EOS (sq->srcpad)
2430           || sq->srcresult == GST_FLOW_EOS)) {
2431     compute_high_time (mq, sq->groupid);
2432     compute_high_id (mq);
2433     wake_up_next_non_linked (mq);
2434   }
2435   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2436
2437   if (dropping)
2438     goto next;
2439
2440   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
2441       && result != GST_FLOW_EOS)
2442     goto out_flushing;
2443
2444   return;
2445
2446 out_flushing:
2447   {
2448     if (object)
2449       gst_mini_object_unref (object);
2450
2451     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2452     sq->last_query = FALSE;
2453     g_cond_signal (&sq->query_handled);
2454
2455     /* Post an error message if we got EOS while downstream
2456      * has returned an error flow return. After EOS there
2457      * will be no further buffer which could propagate the
2458      * error upstream */
2459     if (sq->is_eos && sq->srcresult < GST_FLOW_EOS) {
2460       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2461       GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2462     } else {
2463       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2464     }
2465
2466     /* upstream needs to see fatal result ASAP to shut things down,
2467      * but might be stuck in one of our other full queues;
2468      * so empty this one and trigger dynamic queue growth. At
2469      * this point the srcresult is not OK, NOT_LINKED
2470      * or EOS, i.e. a real failure */
2471     gst_single_queue_flush_queue (sq, FALSE);
2472     single_queue_underrun_cb (sq->queue, sq);
2473     gst_data_queue_set_flushing (sq->queue, TRUE);
2474     gst_pad_pause_task (sq->srcpad);
2475     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
2476         "SingleQueue[%d] task paused, reason:%s",
2477         sq->id, gst_flow_get_name (sq->srcresult));
2478     return;
2479   }
2480 }
2481
2482 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
2483 /*RVU patch : set buffering params*/
2484 static void
2485 single_queue_set_stream_type (GstSingleQueue * squeue, GstBuffer * buffer)
2486 {
2487   if (squeue->sq_stream_type == -1 && buffer) {
2488     GstCaps *buffer_caps = NULL;
2489     GstStructure *caps_str = NULL;
2490     const gchar *mime_type = NULL;
2491     const gchar *drm_stream_type = NULL;
2492     struct timeval tv = { 0 };
2493
2494     do {
2495       buffer_caps = gst_pad_get_current_caps (squeue->sinkpad); //GST_BUFFER_CAPS(buffer);
2496       if (NULL == buffer_caps) {
2497         GST_DEBUG_OBJECT (squeue->mqueue, "cannot get caps from single queue.");
2498         break;
2499       }
2500
2501       GST_DEBUG_OBJECT (squeue->mqueue, "single queue caps  %" GST_PTR_FORMAT,
2502           buffer_caps);
2503
2504       caps_str = gst_caps_get_structure (buffer_caps, 0);
2505       if (NULL == caps_str) {
2506         GST_DEBUG_OBJECT (squeue->mqueue, "cannot get structure from capse.");
2507         break;
2508       }
2509
2510       mime_type = gst_structure_get_name (caps_str);
2511       if (NULL == mime_type) {
2512         GST_DEBUG_OBJECT (squeue->mqueue,
2513             "cannot get mimetype from structure.");
2514         break;
2515       }
2516
2517       drm_stream_type = gst_structure_get_string (caps_str, "stream-type");
2518
2519       if (g_strrstr (mime_type, "video/") || (drm_stream_type
2520               && g_strrstr (drm_stream_type, "video/"))) {
2521         squeue->sq_stream_type = SQ_VIDEO_STREAM;
2522         /*subtitle stream */
2523         if (g_strrstr (mime_type, "video/x-dvb-subpicture"))
2524           squeue->sq_stream_type = SQ_OTHER_STREAM;
2525
2526         gettimeofday (&tv, NULL);
2527         if (squeue->mqueue->buffering_start_time == 0)
2528           squeue->mqueue->buffering_start_time =
2529               GST_SECOND * (guint64) tv.tv_sec +
2530               (guint64) tv.tv_usec * GST_USECOND;
2531       } else if (g_strrstr (mime_type, "audio/") || (drm_stream_type
2532               && g_strrstr (drm_stream_type, "audio/"))) {
2533         squeue->sq_stream_type = SQ_AUDIO_STREAM;
2534         gettimeofday (&tv, NULL);
2535         if (squeue->mqueue->buffering_start_time == 0)
2536           squeue->mqueue->buffering_start_time =
2537               GST_SECOND * (guint64) tv.tv_sec +
2538               (guint64) tv.tv_usec * GST_USECOND;
2539       } else {
2540         squeue->sq_stream_type = SQ_OTHER_STREAM;
2541       }
2542     } while (0);
2543   }
2544 }
2545 #endif
2546 /**
2547  * gst_multi_queue_chain:
2548  *
2549  * This is similar to GstQueue's chain function, except:
2550  * _ we don't have leak behaviours,
2551  * _ we push with a unique id (curid)
2552  */
2553 static GstFlowReturn
2554 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2555 {
2556   GstSingleQueue *sq;
2557   GstMultiQueue *mq;
2558   GstMultiQueueItem *item;
2559   guint32 curid;
2560   GstClockTime timestamp, duration;
2561
2562   sq = gst_pad_get_element_private (pad);
2563   mq = sq->mqueue;
2564
2565 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
2566   if (mq->enable_buffering_opt) {
2567     single_queue_set_stream_type (sq, buffer);
2568   }
2569 #endif
2570   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2571   if (sq->is_eos)
2572     goto was_eos;
2573
2574   sq->active = TRUE;
2575
2576   /* Get a unique incrementing id */
2577   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2578
2579   timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2580   duration = GST_BUFFER_DURATION (buffer);
2581
2582   GST_LOG_OBJECT (mq,
2583       "SingleQueue %d : about to enqueue buffer %p with id %d (pts:%"
2584       GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT " dur:%" GST_TIME_FORMAT ")",
2585       sq->id, buffer, curid, GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2586       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), GST_TIME_ARGS (duration));
2587
2588   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
2589
2590   /* Update interleave before pushing data into queue */
2591   if (mq->use_interleave) {
2592     GstClockTime val = timestamp;
2593     GstClockTimeDiff dval;
2594
2595     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2596     if (val == GST_CLOCK_TIME_NONE)
2597       val = sq->sink_segment.position;
2598     if (duration != GST_CLOCK_TIME_NONE)
2599       val += duration;
2600
2601     dval = my_segment_to_running_time (&sq->sink_segment, val);
2602     if (GST_CLOCK_STIME_IS_VALID (dval)) {
2603       sq->cached_sinktime = dval;
2604       GST_DEBUG_OBJECT (mq,
2605           "Queue %d cached sink time now %" G_GINT64_FORMAT " %"
2606           GST_STIME_FORMAT, sq->id, sq->cached_sinktime,
2607           GST_STIME_ARGS (sq->cached_sinktime));
2608       calculate_interleave (mq);
2609     }
2610     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2611   }
2612
2613   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
2614     goto flushing;
2615
2616   /* update time level, we must do this after pushing the data in the queue so
2617    * that we never end up filling the queue first. */
2618   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
2619
2620 done:
2621   return sq->srcresult;
2622
2623   /* ERRORS */
2624 flushing:
2625   {
2626     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2627         sq->id, gst_flow_get_name (sq->srcresult));
2628     gst_multi_queue_item_destroy (item);
2629     goto done;
2630   }
2631 was_eos:
2632   {
2633     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
2634     gst_buffer_unref (buffer);
2635     return GST_FLOW_EOS;
2636   }
2637 }
2638
2639 static gboolean
2640 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
2641     GstPadMode mode, gboolean active)
2642 {
2643   gboolean res;
2644   GstSingleQueue *sq;
2645   GstMultiQueue *mq;
2646
2647   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2648   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
2649
2650   /* mq is NULL if the pad is activated/deactivated before being
2651    * added to the multiqueue */
2652   if (mq)
2653     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2654
2655   switch (mode) {
2656     case GST_PAD_MODE_PUSH:
2657       if (active) {
2658         /* All pads start off linked until they push one buffer */
2659         sq->srcresult = GST_FLOW_OK;
2660         sq->pushed = FALSE;
2661         gst_data_queue_set_flushing (sq->queue, FALSE);
2662       } else {
2663         sq->srcresult = GST_FLOW_FLUSHING;
2664         sq->last_query = FALSE;
2665         g_cond_signal (&sq->query_handled);
2666         gst_data_queue_set_flushing (sq->queue, TRUE);
2667
2668         /* Wait until streaming thread has finished */
2669         if (mq)
2670           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2671         GST_PAD_STREAM_LOCK (pad);
2672         if (mq)
2673           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2674         gst_data_queue_flush (sq->queue);
2675         if (mq)
2676           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2677         GST_PAD_STREAM_UNLOCK (pad);
2678         if (mq)
2679           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2680       }
2681       res = TRUE;
2682       break;
2683     default:
2684       res = FALSE;
2685       break;
2686   }
2687
2688   if (mq) {
2689     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2690     gst_object_unref (mq);
2691   }
2692
2693   return res;
2694 }
2695
2696 static GstFlowReturn
2697 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2698 {
2699   GstSingleQueue *sq;
2700   GstMultiQueue *mq;
2701   guint32 curid;
2702   GstMultiQueueItem *item;
2703   gboolean res = TRUE;
2704   GstFlowReturn flowret = GST_FLOW_OK;
2705   GstEventType type;
2706   GstEvent *sref = NULL;
2707
2708   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2709   mq = (GstMultiQueue *) parent;
2710
2711   type = GST_EVENT_TYPE (event);
2712
2713   switch (type) {
2714     case GST_EVENT_STREAM_START:
2715     {
2716       if (mq->sync_by_running_time) {
2717         GstStreamFlags stream_flags;
2718         gst_event_parse_stream_flags (event, &stream_flags);
2719         if ((stream_flags & GST_STREAM_FLAG_SPARSE)) {
2720           GST_INFO_OBJECT (mq, "SingleQueue %d is a sparse stream", sq->id);
2721           sq->is_sparse = TRUE;
2722         }
2723       }
2724
2725       sq->thread = g_thread_self ();
2726
2727       /* Remove EOS flag */
2728       sq->is_eos = FALSE;
2729       break;
2730     }
2731     case GST_EVENT_FLUSH_START:
2732       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
2733           sq->id);
2734
2735       res = gst_pad_push_event (sq->srcpad, event);
2736
2737       gst_single_queue_flush (mq, sq, TRUE, FALSE);
2738       goto done;
2739
2740     case GST_EVENT_FLUSH_STOP:
2741       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
2742           sq->id);
2743
2744       res = gst_pad_push_event (sq->srcpad, event);
2745
2746       gst_single_queue_flush (mq, sq, FALSE, FALSE);
2747       goto done;
2748
2749     case GST_EVENT_SEGMENT:
2750       sref = gst_event_ref (event);
2751       break;
2752     case GST_EVENT_GAP:
2753       /* take ref because the queue will take ownership and we need the event
2754        * afterwards to update the segment */
2755       sref = gst_event_ref (event);
2756       if (mq->use_interleave) {
2757         GstClockTime val, dur;
2758         GstClockTime stime;
2759         gst_event_parse_gap (event, &val, &dur);
2760         if (GST_CLOCK_TIME_IS_VALID (val)) {
2761           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2762           if (GST_CLOCK_TIME_IS_VALID (dur))
2763             val += dur;
2764           stime = my_segment_to_running_time (&sq->sink_segment, val);
2765           if (GST_CLOCK_STIME_IS_VALID (stime)) {
2766             sq->cached_sinktime = stime;
2767             calculate_interleave (mq);
2768           }
2769           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2770         }
2771       }
2772       break;
2773
2774     default:
2775       if (!(GST_EVENT_IS_SERIALIZED (event))) {
2776         res = gst_pad_push_event (sq->srcpad, event);
2777         goto done;
2778       }
2779       break;
2780   }
2781
2782   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2783   if (sq->is_eos)
2784     goto was_eos;
2785
2786   /* Get an unique incrementing id. */
2787   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2788
2789   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
2790
2791   GST_DEBUG_OBJECT (mq,
2792       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
2793       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
2794
2795   if (!gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))
2796     goto flushing;
2797
2798   /* mark EOS when we received one, we must do that after putting the
2799    * buffer in the queue because EOS marks the buffer as filled. */
2800   switch (type) {
2801     case GST_EVENT_EOS:
2802       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2803       sq->is_eos = TRUE;
2804
2805       /* Post an error message if we got EOS while downstream
2806        * has returned an error flow return. After EOS there
2807        * will be no further buffer which could propagate the
2808        * error upstream */
2809       if (sq->srcresult < GST_FLOW_EOS) {
2810         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2811         GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2812       } else {
2813         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2814       }
2815
2816       /* EOS affects the buffering state */
2817       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2818       update_buffering (mq, sq);
2819       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2820       single_queue_overrun_cb (sq->queue, sq);
2821       gst_multi_queue_post_buffering (mq);
2822       break;
2823     case GST_EVENT_SEGMENT:
2824       apply_segment (mq, sq, sref, &sq->sink_segment);
2825       gst_event_unref (sref);
2826       /* a new segment allows us to accept more buffers if we got EOS
2827        * from downstream */
2828       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2829       if (sq->srcresult == GST_FLOW_EOS)
2830         sq->srcresult = GST_FLOW_OK;
2831       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2832       break;
2833     case GST_EVENT_GAP:
2834       sq->active = TRUE;
2835       apply_gap (mq, sq, sref, &sq->sink_segment);
2836       gst_event_unref (sref);
2837     default:
2838       break;
2839   }
2840
2841 done:
2842   if (res == FALSE)
2843     flowret = GST_FLOW_ERROR;
2844   GST_DEBUG_OBJECT (mq, "SingleQueue %d : returning %s", sq->id,
2845       gst_flow_get_name (flowret));
2846   return flowret;
2847
2848 flushing:
2849   {
2850     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2851         sq->id, gst_flow_get_name (sq->srcresult));
2852     if (sref)
2853       gst_event_unref (sref);
2854     gst_multi_queue_item_destroy (item);
2855     return sq->srcresult;
2856   }
2857 was_eos:
2858   {
2859     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return GST_FLOW_EOS");
2860     gst_event_unref (event);
2861     return GST_FLOW_EOS;
2862   }
2863 }
2864
2865 static gboolean
2866 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
2867 {
2868   gboolean res;
2869   GstSingleQueue *sq;
2870   GstMultiQueue *mq;
2871
2872   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2873   mq = (GstMultiQueue *) parent;
2874
2875   switch (GST_QUERY_TYPE (query)) {
2876     default:
2877       if (GST_QUERY_IS_SERIALIZED (query)) {
2878         guint32 curid;
2879         GstMultiQueueItem *item;
2880
2881         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2882         if (sq->srcresult != GST_FLOW_OK)
2883           goto out_flushing;
2884
2885         /* serialized events go in the queue. We need to be certain that we
2886          * don't cause deadlocks waiting for the query return value. We check if
2887          * the queue is empty (nothing is blocking downstream and the query can
2888          * be pushed for sure) or we are not buffering. If we are buffering,
2889          * the pipeline waits to unblock downstream until our queue fills up
2890          * completely, which can not happen if we block on the query..
2891          * Therefore we only potentially block when we are not buffering. */
2892         if (!mq->use_buffering || gst_data_queue_is_empty (sq->queue)) {
2893           /* Get an unique incrementing id. */
2894           curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2895
2896           item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
2897
2898           GST_DEBUG_OBJECT (mq,
2899               "SingleQueue %d : Enqueuing query %p of type %s with id %d",
2900               sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
2901           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2902           res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
2903           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2904           if (!res || sq->flushing)
2905             goto out_flushing;
2906           /* it might be that the query has been taken out of the queue
2907            * while we were unlocked. So, we need to check if the last
2908            * handled query is the same one than the one we just
2909            * pushed. If it is, we don't need to wait for the condition
2910            * variable, otherwise we wait for the condition variable to
2911            * be signaled. */
2912           while (!sq->flushing && sq->srcresult == GST_FLOW_OK
2913               && sq->last_handled_query != query)
2914             g_cond_wait (&sq->query_handled, &mq->qlock);
2915           res = sq->last_query;
2916           sq->last_handled_query = NULL;
2917         } else {
2918           GST_DEBUG_OBJECT (mq, "refusing query, we are buffering and the "
2919               "queue is not empty");
2920           res = FALSE;
2921         }
2922         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2923       } else {
2924         /* default handling */
2925         res = gst_pad_query_default (pad, parent, query);
2926       }
2927       break;
2928   }
2929   return res;
2930
2931 out_flushing:
2932   {
2933     GST_DEBUG_OBJECT (mq, "Flushing");
2934     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2935     return FALSE;
2936   }
2937 }
2938
2939 static gboolean
2940 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
2941     GstPadMode mode, gboolean active)
2942 {
2943   GstMultiQueue *mq;
2944   GstSingleQueue *sq;
2945   gboolean result;
2946
2947   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2948   mq = sq->mqueue;
2949
2950   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
2951
2952   switch (mode) {
2953     case GST_PAD_MODE_PUSH:
2954       if (active) {
2955         result = gst_single_queue_flush (mq, sq, FALSE, TRUE);
2956       } else {
2957         result = gst_single_queue_flush (mq, sq, TRUE, TRUE);
2958         /* make sure streaming finishes */
2959         result |= gst_pad_stop_task (pad);
2960       }
2961       break;
2962     default:
2963       result = FALSE;
2964       break;
2965   }
2966   return result;
2967 }
2968
2969 static gboolean
2970 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2971 {
2972   GstSingleQueue *sq = gst_pad_get_element_private (pad);
2973   GstMultiQueue *mq = sq->mqueue;
2974   gboolean ret;
2975
2976   switch (GST_EVENT_TYPE (event)) {
2977     case GST_EVENT_RECONFIGURE:
2978       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2979       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2980         sq->srcresult = GST_FLOW_OK;
2981         g_cond_signal (&sq->turn);
2982       }
2983       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2984
2985       ret = gst_pad_push_event (sq->sinkpad, event);
2986       break;
2987     default:
2988       ret = gst_pad_push_event (sq->sinkpad, event);
2989       break;
2990   }
2991
2992   return ret;
2993 }
2994
2995 static gboolean
2996 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2997 {
2998   gboolean res;
2999
3000   /* FIXME, Handle position offset depending on queue size */
3001   switch (GST_QUERY_TYPE (query)) {
3002     default:
3003       /* default handling */
3004       res = gst_pad_query_default (pad, parent, query);
3005       break;
3006   }
3007   return res;
3008 }
3009
3010 /*
3011  * Next-non-linked functions
3012  */
3013
3014 /* WITH LOCK TAKEN */
3015 static void
3016 wake_up_next_non_linked (GstMultiQueue * mq)
3017 {
3018   GList *tmp;
3019
3020   /* maybe no-one is waiting */
3021   if (mq->numwaiting < 1)
3022     return;
3023
3024   if (mq->sync_by_running_time && GST_CLOCK_STIME_IS_VALID (mq->high_time)) {
3025     /* Else figure out which singlequeue(s) need waking up */
3026     for (tmp = mq->queues; tmp; tmp = tmp->next) {
3027       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3028       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3029         GstClockTimeDiff high_time;
3030
3031         if (GST_CLOCK_STIME_IS_VALID (sq->group_high_time))
3032           high_time = sq->group_high_time;
3033         else
3034           high_time = mq->high_time;
3035
3036         if (GST_CLOCK_STIME_IS_VALID (sq->next_time) &&
3037             GST_CLOCK_STIME_IS_VALID (high_time)
3038             && sq->next_time <= high_time) {
3039           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
3040           g_cond_signal (&sq->turn);
3041         }
3042       }
3043     }
3044   } else {
3045     /* Else figure out which singlequeue(s) need waking up */
3046     for (tmp = mq->queues; tmp; tmp = tmp->next) {
3047       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3048       if (sq->srcresult == GST_FLOW_NOT_LINKED &&
3049           sq->nextid != 0 && sq->nextid <= mq->highid) {
3050         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
3051         g_cond_signal (&sq->turn);
3052       }
3053     }
3054   }
3055 }
3056
3057 /* WITH LOCK TAKEN */
3058 static void
3059 compute_high_id (GstMultiQueue * mq)
3060 {
3061   /* The high-id is either the highest id among the linked pads, or if all
3062    * pads are not-linked, it's the lowest not-linked pad */
3063   GList *tmp;
3064   guint32 lowest = G_MAXUINT32;
3065   guint32 highid = G_MAXUINT32;
3066
3067   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3068     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3069
3070     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
3071         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
3072
3073     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3074       /* No need to consider queues which are not waiting */
3075       if (sq->nextid == 0) {
3076         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3077         continue;
3078       }
3079
3080       if (sq->nextid < lowest)
3081         lowest = sq->nextid;
3082     } else if (!GST_PAD_IS_EOS (sq->srcpad) && sq->srcresult != GST_FLOW_EOS) {
3083       /* If we don't have a global highid, or the global highid is lower than
3084        * this single queue's last outputted id, store the queue's one,
3085        * unless the singlequeue output is at EOS */
3086       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
3087         highid = sq->oldid;
3088     }
3089   }
3090
3091   if (highid == G_MAXUINT32 || lowest < highid)
3092     mq->highid = lowest;
3093   else
3094     mq->highid = highid;
3095
3096   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
3097       lowest);
3098 }
3099
3100 /* WITH LOCK TAKEN */
3101 static void
3102 compute_high_time (GstMultiQueue * mq, guint groupid)
3103 {
3104   /* The high-time is either the highest last time among the linked
3105    * pads, or if all pads are not-linked, it's the lowest nex time of
3106    * not-linked pad */
3107   GList *tmp;
3108   GstClockTimeDiff highest = GST_CLOCK_STIME_NONE;
3109   GstClockTimeDiff lowest = GST_CLOCK_STIME_NONE;
3110   GstClockTimeDiff group_high = GST_CLOCK_STIME_NONE;
3111   GstClockTimeDiff group_low = GST_CLOCK_STIME_NONE;
3112   GstClockTimeDiff res;
3113   /* Number of streams which belong to groupid */
3114   guint group_count = 0;
3115
3116   if (!mq->sync_by_running_time)
3117     /* return GST_CLOCK_STIME_NONE; */
3118     return;
3119
3120   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3121     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3122
3123     GST_LOG_OBJECT (mq,
3124         "inspecting sq:%d (group:%d) , next_time:%" GST_STIME_FORMAT
3125         ", last_time:%" GST_STIME_FORMAT ", srcresult:%s", sq->id, sq->groupid,
3126         GST_STIME_ARGS (sq->next_time), GST_STIME_ARGS (sq->last_time),
3127         gst_flow_get_name (sq->srcresult));
3128
3129     if (sq->groupid == groupid)
3130       group_count++;
3131
3132     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3133       /* No need to consider queues which are not waiting */
3134       if (!GST_CLOCK_STIME_IS_VALID (sq->next_time)) {
3135         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3136         continue;
3137       }
3138
3139       if (lowest == GST_CLOCK_STIME_NONE || sq->next_time < lowest)
3140         lowest = sq->next_time;
3141       if (sq->groupid == groupid && (group_low == GST_CLOCK_STIME_NONE
3142               || sq->next_time < group_low))
3143         group_low = sq->next_time;
3144     } else if (!GST_PAD_IS_EOS (sq->srcpad) && sq->srcresult != GST_FLOW_EOS) {
3145       /* If we don't have a global high time, or the global high time
3146        * is lower than this single queue's last outputted time, store
3147        * the queue's one, unless the singlequeue output is at EOS. */
3148       if (highest == GST_CLOCK_STIME_NONE
3149           || (sq->last_time != GST_CLOCK_STIME_NONE && sq->last_time > highest))
3150         highest = sq->last_time;
3151       if (sq->groupid == groupid && (group_high == GST_CLOCK_STIME_NONE
3152               || (sq->last_time != GST_CLOCK_STIME_NONE
3153                   && sq->last_time > group_high)))
3154         group_high = sq->last_time;
3155     }
3156     GST_LOG_OBJECT (mq,
3157         "highest now %" GST_STIME_FORMAT " lowest %" GST_STIME_FORMAT,
3158         GST_STIME_ARGS (highest), GST_STIME_ARGS (lowest));
3159     if (sq->groupid == groupid)
3160       GST_LOG_OBJECT (mq,
3161           "grouphigh %" GST_STIME_FORMAT " grouplow %" GST_STIME_FORMAT,
3162           GST_STIME_ARGS (group_high), GST_STIME_ARGS (group_low));
3163   }
3164
3165   if (highest == GST_CLOCK_STIME_NONE)
3166     mq->high_time = lowest;
3167   else
3168     mq->high_time = highest;
3169
3170   /* If there's only one stream of a given type, use the global high */
3171   if (group_count < 2)
3172     res = GST_CLOCK_STIME_NONE;
3173   else if (group_high == GST_CLOCK_STIME_NONE)
3174     res = group_low;
3175   else
3176     res = group_high;
3177
3178   GST_LOG_OBJECT (mq, "group count %d for groupid %u", group_count, groupid);
3179   GST_LOG_OBJECT (mq,
3180       "MQ High time is now : %" GST_STIME_FORMAT ", group %d high time %"
3181       GST_STIME_FORMAT ", lowest non-linked %" GST_STIME_FORMAT,
3182       GST_STIME_ARGS (mq->high_time), groupid, GST_STIME_ARGS (mq->high_time),
3183       GST_STIME_ARGS (lowest));
3184
3185   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3186     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3187     if (groupid == sq->groupid)
3188       sq->group_high_time = res;
3189   }
3190 }
3191
3192 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
3193      ((q)->max_size.format) <= (value))
3194
3195 #ifdef TIZEN_FEATURE_MQ_MODIFICATION_EXTRA_SIZE_TIME
3196 #define IS_FILLED_EXTRA(q, format, value) ((((q)->extra_size.format) != 0) && (((q)->max_size.format) != 0) && \
3197      (((q)->extra_size.format)+((q)->max_size.format)) <= (value))
3198 #endif
3199 /*
3200  * GstSingleQueue functions
3201  */
3202 static void
3203 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3204 {
3205   GstMultiQueue *mq = sq->mqueue;
3206   GList *tmp;
3207   GstDataQueueSize size;
3208   gboolean filled = TRUE;
3209   gboolean empty_found = FALSE;
3210
3211   gst_data_queue_get_level (sq->queue, &size);
3212
3213   GST_LOG_OBJECT (mq,
3214       "Single Queue %d: EOS %d, visible %u/%u, bytes %u/%u, time %"
3215       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, sq->is_eos, size.visible,
3216       sq->max_size.visible, size.bytes, sq->max_size.bytes, sq->cur_time,
3217       sq->max_size.time);
3218
3219   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3220
3221   /* check if we reached the hard time/bytes limits;
3222      time limit is only taken into account for non-sparse streams */
3223   if (sq->is_eos || IS_FILLED (sq, bytes, size.bytes) ||
3224       (!sq->is_sparse && IS_FILLED (sq, time, sq->cur_time))) {
3225     goto done;
3226   }
3227
3228   /* Search for empty queues */
3229   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3230     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3231
3232     if (oq == sq)
3233       continue;
3234
3235     if (oq->srcresult == GST_FLOW_NOT_LINKED) {
3236       GST_LOG_OBJECT (mq, "Queue %d is not-linked", oq->id);
3237       continue;
3238     }
3239
3240     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
3241     if (gst_data_queue_is_empty (oq->queue) && !oq->is_sparse) {
3242       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
3243       empty_found = TRUE;
3244       break;
3245     }
3246   }
3247
3248   /* if hard limits are not reached then we allow one more buffer in the full
3249    * queue, but only if any of the other singelqueues are empty */
3250   if (empty_found) {
3251     if (IS_FILLED (sq, visible, size.visible)) {
3252       sq->max_size.visible = size.visible + 1;
3253       GST_DEBUG_OBJECT (mq,
3254           "Bumping single queue %d max visible to %d",
3255           sq->id, sq->max_size.visible);
3256       filled = FALSE;
3257     }
3258   }
3259
3260 done:
3261   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3262
3263   /* Overrun is always forwarded, since this is blocking the upstream element */
3264   if (filled) {
3265     GST_DEBUG_OBJECT (mq, "Queue %d is filled, signalling overrun", sq->id);
3266     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
3267   }
3268 }
3269
3270 static void
3271 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3272 {
3273   gboolean empty = TRUE;
3274   GstMultiQueue *mq = sq->mqueue;
3275   GList *tmp;
3276
3277   if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3278     GST_LOG_OBJECT (mq, "Single Queue %d is empty but not-linked", sq->id);
3279     return;
3280   } else {
3281     GST_LOG_OBJECT (mq,
3282         "Single Queue %d is empty, Checking other single queues", sq->id);
3283   }
3284
3285   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3286   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3287     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3288
3289     if (gst_data_queue_is_full (oq->queue)) {
3290       GstDataQueueSize size;
3291
3292       gst_data_queue_get_level (oq->queue, &size);
3293       if (IS_FILLED (oq, visible, size.visible)) {
3294         oq->max_size.visible = size.visible + 1;
3295         GST_DEBUG_OBJECT (mq,
3296             "queue %d is filled, bumping its max visible to %d", oq->id,
3297             oq->max_size.visible);
3298         gst_data_queue_limits_changed (oq->queue);
3299       }
3300     }
3301     if (!gst_data_queue_is_empty (oq->queue) || oq->is_sparse)
3302       empty = FALSE;
3303   }
3304   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3305
3306   if (empty) {
3307     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
3308     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
3309   }
3310 }
3311
3312 static gboolean
3313 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
3314     guint64 time, GstSingleQueue * sq)
3315 {
3316   gboolean res;
3317   GstMultiQueue *mq = sq->mqueue;
3318
3319   GST_DEBUG_OBJECT (mq,
3320       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
3321       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
3322       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
3323
3324   /* we are always filled on EOS */
3325   if (sq->is_eos)
3326     return TRUE;
3327
3328   /* we never go past the max visible items unless we are in buffering mode */
3329   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
3330     return TRUE;
3331
3332   /* check time or bytes */
3333 #ifdef TIZEN_FEATURE_MQ_MODIFICATION_EXTRA_SIZE_TIME
3334   res = IS_FILLED_EXTRA (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
3335 #else
3336   res = IS_FILLED (sq, bytes, bytes);
3337   /* We only care about limits in time if we're not a sparse stream or
3338    * we're not syncing by running time */
3339   if (!sq->is_sparse || !mq->sync_by_running_time) {
3340     /* If unlinked, take into account the extra unlinked cache time */
3341     if (mq->sync_by_running_time && sq->srcresult == GST_FLOW_NOT_LINKED) {
3342       if (sq->cur_time > mq->unlinked_cache_time)
3343         res |= IS_FILLED (sq, time, sq->cur_time - mq->unlinked_cache_time);
3344       else
3345         res = FALSE;
3346     } else
3347       res |= IS_FILLED (sq, time, sq->cur_time);
3348   }
3349
3350 #endif
3351   return res;
3352 }
3353
3354 static void
3355 gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full)
3356 {
3357   GstDataQueueItem *sitem;
3358   GstMultiQueueItem *mitem;
3359   gboolean was_flushing = FALSE;
3360
3361   while (!gst_data_queue_is_empty (sq->queue)) {
3362     GstMiniObject *data;
3363
3364     /* FIXME: If this fails here although the queue is not empty,
3365      * we're flushing... but we want to rescue all sticky
3366      * events nonetheless.
3367      */
3368     if (!gst_data_queue_pop (sq->queue, &sitem)) {
3369       was_flushing = TRUE;
3370       gst_data_queue_set_flushing (sq->queue, FALSE);
3371       continue;
3372     }
3373
3374     mitem = (GstMultiQueueItem *) sitem;
3375
3376     data = sitem->object;
3377
3378     if (!full && !mitem->is_query && GST_IS_EVENT (data)
3379         && GST_EVENT_IS_STICKY (data)
3380         && GST_EVENT_TYPE (data) != GST_EVENT_SEGMENT
3381         && GST_EVENT_TYPE (data) != GST_EVENT_EOS) {
3382       gst_pad_store_sticky_event (sq->srcpad, GST_EVENT_CAST (data));
3383     }
3384
3385     sitem->destroy (sitem);
3386   }
3387
3388   gst_data_queue_flush (sq->queue);
3389   if (was_flushing)
3390     gst_data_queue_set_flushing (sq->queue, TRUE);
3391
3392   GST_MULTI_QUEUE_MUTEX_LOCK (sq->mqueue);
3393   update_buffering (sq->mqueue, sq);
3394   GST_MULTI_QUEUE_MUTEX_UNLOCK (sq->mqueue);
3395   gst_multi_queue_post_buffering (sq->mqueue);
3396 }
3397
3398 static void
3399 gst_single_queue_free (GstSingleQueue * sq)
3400 {
3401   /* DRAIN QUEUE */
3402   gst_data_queue_flush (sq->queue);
3403   g_object_unref (sq->queue);
3404   g_cond_clear (&sq->turn);
3405   g_cond_clear (&sq->query_handled);
3406   g_free (sq);
3407 }
3408
3409 static GstSingleQueue *
3410 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
3411 {
3412   GstSingleQueue *sq;
3413   GstMultiQueuePad *mqpad;
3414   GstPadTemplate *templ;
3415   gchar *name;
3416   GList *tmp;
3417   guint temp_id = (id == -1) ? 0 : id;
3418
3419   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
3420
3421   /* Find an unused queue ID, if possible the passed one */
3422   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
3423     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
3424     /* This works because the IDs are sorted in ascending order */
3425     if (sq2->id == temp_id) {
3426       /* If this ID was requested by the caller return NULL,
3427        * otherwise just get us the next one */
3428       if (id == -1) {
3429         temp_id = sq2->id + 1;
3430       } else {
3431         GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3432         return NULL;
3433       }
3434     } else if (sq2->id > temp_id) {
3435       break;
3436     }
3437   }
3438
3439   sq = g_new0 (GstSingleQueue, 1);
3440   mqueue->nbqueues++;
3441   sq->id = temp_id;
3442   sq->groupid = DEFAULT_PAD_GROUP_ID;
3443   sq->group_high_time = GST_CLOCK_STIME_NONE;
3444
3445   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
3446   mqueue->queues_cookie++;
3447
3448   /* copy over max_size and extra_size so we don't need to take the lock
3449    * any longer when checking if the queue is full. */
3450   sq->max_size.visible = mqueue->max_size.visible;
3451   sq->max_size.bytes = mqueue->max_size.bytes;
3452   sq->max_size.time = mqueue->max_size.time;
3453
3454   sq->extra_size.visible = mqueue->extra_size.visible;
3455   sq->extra_size.bytes = mqueue->extra_size.bytes;
3456   sq->extra_size.time = mqueue->extra_size.time;
3457
3458   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
3459
3460   sq->mqueue = mqueue;
3461   sq->srcresult = GST_FLOW_FLUSHING;
3462   sq->pushed = FALSE;
3463   sq->queue = gst_data_queue_new ((GstDataQueueCheckFullFunction)
3464       single_queue_check_full,
3465       (GstDataQueueFullCallback) single_queue_overrun_cb,
3466       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
3467   sq->is_eos = FALSE;
3468   sq->is_sparse = FALSE;
3469   sq->flushing = FALSE;
3470   sq->active = FALSE;
3471   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
3472   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
3473
3474   sq->nextid = 0;
3475   sq->oldid = 0;
3476   sq->next_time = GST_CLOCK_STIME_NONE;
3477   sq->last_time = GST_CLOCK_STIME_NONE;
3478   g_cond_init (&sq->turn);
3479   g_cond_init (&sq->query_handled);
3480
3481   sq->sinktime = GST_CLOCK_STIME_NONE;
3482   sq->srctime = GST_CLOCK_STIME_NONE;
3483   sq->sink_tainted = TRUE;
3484   sq->src_tainted = TRUE;
3485
3486 #ifdef TIZEN_FEATURE_TRUSTZONE
3487   sq->sq_stream_type = -1;
3488 #endif
3489   name = g_strdup_printf ("sink_%u", sq->id);
3490   templ = gst_static_pad_template_get (&sinktemplate);
3491   sq->sinkpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
3492       "direction", templ->direction, "template", templ, NULL);
3493   gst_object_unref (templ);
3494   g_free (name);
3495
3496   mqpad = (GstMultiQueuePad *) sq->sinkpad;
3497   mqpad->sq = sq;
3498
3499   gst_pad_set_chain_function (sq->sinkpad,
3500       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
3501   gst_pad_set_activatemode_function (sq->sinkpad,
3502       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
3503   gst_pad_set_event_full_function (sq->sinkpad,
3504       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
3505   gst_pad_set_query_function (sq->sinkpad,
3506       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
3507   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
3508       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3509   GST_OBJECT_FLAG_SET (sq->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
3510
3511   name = g_strdup_printf ("src_%u", sq->id);
3512   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
3513   g_free (name);
3514
3515   gst_pad_set_activatemode_function (sq->srcpad,
3516       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
3517   gst_pad_set_event_function (sq->srcpad,
3518       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
3519   gst_pad_set_query_function (sq->srcpad,
3520       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
3521   gst_pad_set_iterate_internal_links_function (sq->srcpad,
3522       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3523   GST_OBJECT_FLAG_SET (sq->srcpad, GST_PAD_FLAG_PROXY_CAPS);
3524
3525   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
3526   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
3527
3528   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3529
3530   /* only activate the pads when we are not in the NULL state
3531    * and add the pad under the state_lock to prevend state changes
3532    * between activating and adding */
3533   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
3534   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3535     gst_pad_set_active (sq->srcpad, TRUE);
3536     gst_pad_set_active (sq->sinkpad, TRUE);
3537   }
3538   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
3539   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
3540   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
3541
3542   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
3543       sq->id);
3544
3545   return sq;
3546 }