b8cc9fdadcdea77f9e8a47676ea018eb25181c33
[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   guint current_size_bytes = 0;
1008
1009   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1010     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1011     GstDataQueueSize size;
1012
1013     gst_data_queue_get_level (sq->queue, &size);
1014
1015     current_size_bytes += size.bytes;
1016
1017     GST_DEBUG_OBJECT (mq,
1018         "queue %d: bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1019         G_GUINT64_FORMAT, sq->id, size.bytes, sq->max_size.bytes,
1020         sq->cur_time, sq->max_size.time);
1021   }
1022
1023   GST_INFO_OBJECT (mq, "current_size_bytes : %u", current_size_bytes);
1024
1025   return current_size_bytes;
1026 }
1027 #endif
1028
1029 static void
1030 gst_multi_queue_get_property (GObject * object, guint prop_id,
1031     GValue * value, GParamSpec * pspec)
1032 {
1033   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
1034
1035   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1036
1037   switch (prop_id) {
1038     case PROP_EXTRA_SIZE_BYTES:
1039       g_value_set_uint (value, mq->extra_size.bytes);
1040       break;
1041     case PROP_EXTRA_SIZE_BUFFERS:
1042       g_value_set_uint (value, mq->extra_size.visible);
1043       break;
1044     case PROP_EXTRA_SIZE_TIME:
1045       g_value_set_uint64 (value, mq->extra_size.time);
1046       break;
1047     case PROP_MAX_SIZE_BYTES:
1048       g_value_set_uint (value, mq->max_size.bytes);
1049       break;
1050     case PROP_MAX_SIZE_BUFFERS:
1051       g_value_set_uint (value, mq->max_size.visible);
1052       break;
1053     case PROP_MAX_SIZE_TIME:
1054       g_value_set_uint64 (value, mq->max_size.time);
1055       break;
1056 #ifdef TIZEN_FEATURE_MQ_MODIFICATION
1057     case PROP_CURR_SIZE_BYTES:
1058       g_value_set_uint (value, get_current_size_bytes(mq));
1059       break;
1060 #endif
1061     case PROP_USE_BUFFERING:
1062       g_value_set_boolean (value, mq->use_buffering);
1063       break;
1064     case PROP_LOW_PERCENT:
1065       g_value_set_int (value, mq->low_watermark / BUF_LEVEL_PERCENT_FACTOR);
1066       break;
1067     case PROP_HIGH_PERCENT:
1068       g_value_set_int (value, mq->high_watermark / BUF_LEVEL_PERCENT_FACTOR);
1069       break;
1070     case PROP_LOW_WATERMARK:
1071       g_value_set_double (value, mq->low_watermark /
1072           (gdouble) MAX_BUFFERING_LEVEL);
1073       break;
1074     case PROP_HIGH_WATERMARK:
1075       g_value_set_double (value, mq->high_watermark /
1076           (gdouble) MAX_BUFFERING_LEVEL);
1077       break;
1078     case PROP_SYNC_BY_RUNNING_TIME:
1079       g_value_set_boolean (value, mq->sync_by_running_time);
1080       break;
1081     case PROP_USE_INTERLEAVE:
1082       g_value_set_boolean (value, mq->use_interleave);
1083       break;
1084     case PROP_UNLINKED_CACHE_TIME:
1085       g_value_set_uint64 (value, mq->unlinked_cache_time);
1086       break;
1087     case PROP_MINIMUM_INTERLEAVE:
1088       g_value_set_uint64 (value, mq->min_interleave_time);
1089       break;
1090 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1091 /*RVU patch : rvu disable audio buffering and adaptive buffering property*/
1092     case PROP_DISABLE_AUDIO_BUFFERING:
1093       g_value_set_boolean (value, mq->disable_audio_buffering);
1094       break;
1095     case PROP_BUFFERING_ENHANCEMENT:
1096       g_value_set_boolean (value, mq->enhancement_buffering);
1097       break;
1098 #endif
1099     default:
1100       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1101       break;
1102   }
1103
1104   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1105 }
1106
1107 static GstIterator *
1108 gst_multi_queue_iterate_internal_links (GstPad * pad, GstObject * parent)
1109 {
1110   GstIterator *it = NULL;
1111   GstPad *opad;
1112   GstSingleQueue *squeue;
1113   GstMultiQueue *mq = GST_MULTI_QUEUE (parent);
1114   GValue val = { 0, };
1115
1116   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1117   squeue = gst_pad_get_element_private (pad);
1118   if (!squeue)
1119     goto out;
1120
1121   if (squeue->sinkpad == pad)
1122     opad = gst_object_ref (squeue->srcpad);
1123   else if (squeue->srcpad == pad)
1124     opad = gst_object_ref (squeue->sinkpad);
1125   else
1126     goto out;
1127
1128   g_value_init (&val, GST_TYPE_PAD);
1129   g_value_set_object (&val, opad);
1130   it = gst_iterator_new_single (GST_TYPE_PAD, &val);
1131   g_value_unset (&val);
1132
1133   gst_object_unref (opad);
1134
1135 out:
1136   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1137
1138   return it;
1139 }
1140
1141
1142 /*
1143  * GstElement methods
1144  */
1145
1146 static GstPad *
1147 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
1148     const gchar * name, const GstCaps * caps)
1149 {
1150   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1151   GstSingleQueue *squeue;
1152   GstPad *new_pad;
1153   guint temp_id = -1;
1154
1155   if (name) {
1156     sscanf (name + 4, "_%u", &temp_id);
1157     GST_LOG_OBJECT (element, "name : %s (id %d)", GST_STR_NULL (name), temp_id);
1158   }
1159
1160   /* Create a new single queue, add the sink and source pad and return the sink pad */
1161   squeue = gst_single_queue_new (mqueue, temp_id);
1162
1163   new_pad = squeue ? squeue->sinkpad : NULL;
1164
1165   GST_DEBUG_OBJECT (mqueue, "Returning pad %" GST_PTR_FORMAT, new_pad);
1166
1167   return new_pad;
1168 }
1169
1170 static void
1171 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
1172 {
1173   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1174   GstSingleQueue *sq = NULL;
1175   GList *tmp;
1176
1177   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1178
1179   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1180   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
1181   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1182     sq = (GstSingleQueue *) tmp->data;
1183
1184     if (sq->sinkpad == pad)
1185       break;
1186   }
1187
1188   if (!tmp) {
1189     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
1190     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1191     return;
1192   }
1193
1194   /* FIXME: The removal of the singlequeue should probably not happen until it
1195    * finishes draining */
1196
1197   /* remove it from the list */
1198   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
1199   mqueue->queues_cookie++;
1200
1201   /* FIXME : recompute next-non-linked */
1202   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1203
1204   /* delete SingleQueue */
1205   gst_data_queue_set_flushing (sq->queue, TRUE);
1206
1207   gst_pad_set_active (sq->srcpad, FALSE);
1208   gst_pad_set_active (sq->sinkpad, FALSE);
1209   gst_pad_set_element_private (sq->srcpad, NULL);
1210   gst_pad_set_element_private (sq->sinkpad, NULL);
1211   gst_element_remove_pad (element, sq->srcpad);
1212   gst_element_remove_pad (element, sq->sinkpad);
1213   gst_single_queue_free (sq);
1214 }
1215
1216 static GstStateChangeReturn
1217 gst_multi_queue_change_state (GstElement * element, GstStateChange transition)
1218 {
1219   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1220   GstSingleQueue *sq = NULL;
1221   GstStateChangeReturn result;
1222
1223   switch (transition) {
1224     case GST_STATE_CHANGE_READY_TO_PAUSED:{
1225       GList *tmp;
1226
1227       /* Set all pads to non-flushing */
1228       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1229       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1230         sq = (GstSingleQueue *) tmp->data;
1231         sq->flushing = FALSE;
1232       }
1233
1234       /* the visible limit might not have been set on single queues that have grown because of other queueus were empty */
1235       SET_CHILD_PROPERTY (mqueue, visible);
1236
1237       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1238       gst_multi_queue_post_buffering (mqueue);
1239
1240       break;
1241     }
1242     case GST_STATE_CHANGE_PAUSED_TO_READY:{
1243       GList *tmp;
1244
1245       /* Un-wait all waiting pads */
1246       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1247       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1248         sq = (GstSingleQueue *) tmp->data;
1249         sq->flushing = TRUE;
1250         g_cond_signal (&sq->turn);
1251
1252         sq->last_query = FALSE;
1253         g_cond_signal (&sq->query_handled);
1254       }
1255       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1256       break;
1257     }
1258     default:
1259       break;
1260   }
1261
1262   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1263
1264   switch (transition) {
1265     default:
1266       break;
1267   }
1268
1269   return result;
1270 }
1271
1272 static gboolean
1273 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush,
1274     gboolean full)
1275 {
1276   gboolean result;
1277
1278   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
1279       sq->id);
1280
1281   if (flush) {
1282     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1283     sq->srcresult = GST_FLOW_FLUSHING;
1284     gst_data_queue_set_flushing (sq->queue, TRUE);
1285
1286     sq->flushing = TRUE;
1287
1288     /* wake up non-linked task */
1289     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
1290         sq->id);
1291     g_cond_signal (&sq->turn);
1292     sq->last_query = FALSE;
1293     g_cond_signal (&sq->query_handled);
1294     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1295
1296     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
1297     result = gst_pad_pause_task (sq->srcpad);
1298     sq->sink_tainted = sq->src_tainted = TRUE;
1299   } else {
1300     gst_single_queue_flush_queue (sq, full);
1301
1302     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1303     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
1304     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
1305     sq->has_src_segment = FALSE;
1306     /* All pads start off not-linked for a smooth kick-off */
1307     sq->srcresult = GST_FLOW_OK;
1308     sq->pushed = FALSE;
1309     sq->cur_time = 0;
1310     sq->max_size.visible = mq->max_size.visible;
1311     sq->is_eos = FALSE;
1312     sq->nextid = 0;
1313     sq->oldid = 0;
1314     sq->last_oldid = G_MAXUINT32;
1315     sq->next_time = GST_CLOCK_STIME_NONE;
1316     sq->last_time = GST_CLOCK_STIME_NONE;
1317     sq->cached_sinktime = GST_CLOCK_STIME_NONE;
1318     sq->group_high_time = GST_CLOCK_STIME_NONE;
1319     gst_data_queue_set_flushing (sq->queue, FALSE);
1320
1321     /* We will become active again on the next buffer/gap */
1322     sq->active = FALSE;
1323
1324     /* Reset high time to be recomputed next */
1325     mq->high_time = GST_CLOCK_STIME_NONE;
1326
1327     sq->flushing = FALSE;
1328     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1329
1330     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
1331     result =
1332         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
1333         sq->srcpad, NULL);
1334   }
1335   return result;
1336 }
1337
1338 /* WITH LOCK TAKEN */
1339 static gint
1340 get_buffering_level (GstSingleQueue * sq)
1341 {
1342   GstDataQueueSize size;
1343   gint buffering_level, tmp;
1344
1345   gst_data_queue_get_level (sq->queue, &size);
1346
1347   GST_DEBUG_OBJECT (sq->mqueue,
1348       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1349       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
1350       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1351
1352   /* get bytes and time buffer levels and take the max */
1353   if (sq->is_eos || sq->srcresult == GST_FLOW_NOT_LINKED || sq->is_sparse) {
1354     buffering_level = MAX_BUFFERING_LEVEL;
1355   } else {
1356     buffering_level = 0;
1357     if (sq->max_size.time > 0) {
1358       tmp =
1359           gst_util_uint64_scale (sq->cur_time,
1360           MAX_BUFFERING_LEVEL, sq->max_size.time);
1361       buffering_level = MAX (buffering_level, tmp);
1362     }
1363 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1364     /*RVU patch : rvu adaptive buffering */
1365     if (sq->mqueue->enhancement_buffering == TRUE)
1366       GST_LOG_OBJECT (sq->mqueue,
1367           "MULTIQUEUE ENHANCEMENT BUFFERING SOLUTION ENABLE!\n");
1368
1369     if (sq->mqueue->enhancement_buffering == FALSE) {
1370       if (sq->max_size.bytes > 0) {
1371         tmp = (size.bytes * 100) / sq->max_size.bytes;
1372         percent = MAX (percent, tmp);
1373       }
1374     } else {
1375       GST_LOG_OBJECT (sq->mqueue, "disable bytes buffering profile!\n");
1376     }
1377 #else
1378     if (sq->max_size.bytes > 0) {
1379       tmp =
1380           gst_util_uint64_scale_int (size.bytes,
1381           MAX_BUFFERING_LEVEL, sq->max_size.bytes);
1382       buffering_level = MAX (buffering_level, tmp);
1383     }
1384 #endif
1385   }
1386
1387   return buffering_level;
1388 }
1389
1390 /* WITH LOCK TAKEN */
1391 static void
1392 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
1393 {
1394   gint buffering_level, percent;
1395 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1396   /*RVU patch : disable mq audio buffering solution */
1397   GstPad *audio_pad = NULL;
1398   GstCaps *audio_caps = NULL;
1399   GstStructure *audio_caps_str = NULL;
1400   const char *audio_mime = NULL;
1401   const char *audio_stream_type = NULL;
1402 #endif
1403   /* nothing to dowhen we are not in buffering mode */
1404   if (!mq->use_buffering)
1405     return;
1406
1407 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1408   /*RVU patch : disable mq audio buffering solution */
1409   if ((sq != NULL) && (mq->disable_audio_buffering == TRUE)) {
1410     GST_LOG_OBJECT (mq, "disable audio buffering solution start!\n");
1411     audio_pad = GST_PAD_PEER (sq->sinkpad);
1412     audio_caps = gst_pad_get_current_caps (audio_pad);
1413     if (NULL == audio_caps) {
1414       GST_LOG_OBJECT (mq, "audio caps is null!\n");
1415       goto NEXT_STEP;
1416     }
1417
1418     audio_caps_str = gst_caps_get_structure (audio_caps, 0);
1419     if (NULL == audio_caps_str) {
1420       GST_LOG_OBJECT (mq, "audio caps string is NULL!\n");
1421       goto NEXT_STEP;
1422     }
1423
1424     audio_mime = gst_structure_get_name (audio_caps_str);
1425     if (NULL == audio_mime) {
1426       GST_LOG_OBJECT (mq, "audio caps string mime is NULL!\n");
1427       goto NEXT_STEP;
1428     }
1429
1430     GST_LOG_OBJECT (mq, "audio_mime:[%s]\n", audio_mime);
1431     if (g_strrstr (audio_mime, "audio")) {
1432       GST_LOG_OBJECT (mq,
1433           "non-drm audio single queue!, skip audio buffering\n");
1434       goto LAST_POS;
1435     } else if (g_strrstr (audio_mime, "drm")) {
1436       audio_stream_type =
1437           gst_structure_get_string (audio_caps_str, "stream-type");
1438       if (NULL == audio_stream_type) {
1439         GST_LOG_OBJECT (mq, "drm audio single queue can not get stream-type\n");
1440         goto NEXT_STEP;
1441       }
1442       if (g_strrstr (audio_stream_type, "audio")) {
1443         GST_LOG_OBJECT (mq, "drm audio single queue!, skip audio buffering!\n");
1444         goto LAST_POS;
1445       }
1446     }
1447     GST_LOG_OBJECT (mq, "disable audio buffering solution end!\n");
1448   }
1449
1450 NEXT_STEP:
1451   if (audio_caps != NULL) {
1452     GST_LOG_OBJECT (mq,
1453         "audio caps release for disable audio buffering solution!\n");
1454     gst_caps_unref (audio_caps);
1455     audio_caps = NULL;
1456   }
1457 #endif
1458
1459   buffering_level = get_buffering_level (sq);
1460
1461   /* scale so that if buffering_level equals the high watermark,
1462    * the percentage is 100% */
1463   percent = gst_util_uint64_scale (buffering_level, 100, mq->high_watermark);
1464   /* clip */
1465   if (percent > 100)
1466     percent = 100;
1467
1468   if (mq->buffering) {
1469     if (buffering_level >= mq->high_watermark) {
1470       mq->buffering = FALSE;
1471     }
1472 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1473 /*RVU patch : rvu reset buffering */
1474     if (mq->buffering_reset) {
1475       if (percent < mq->low_percent) {
1476         mq->buffering = TRUE;
1477         mq->percent = percent;
1478         mq->percent_changed = TRUE;
1479       }
1480     }
1481 #endif
1482     /* make sure it increases */
1483     percent = MAX (mq->buffering_percent, percent);
1484
1485     SET_PERCENT (mq, percent);
1486 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1487 /*RVU patch : adaptive buffering solution*/
1488     if (mq->enhancement_buffering == TRUE) {
1489       if (percent >= mq->high_percent) {
1490         mq->percent_changed = TRUE;
1491         GST_LOG_OBJECT (mq, "MULTIQUEUE ENHANCEMENT BUFFERING!\n");
1492       }
1493     }
1494 #endif
1495   } else {
1496     GList *iter;
1497     gboolean is_buffering = TRUE;
1498
1499     for (iter = mq->queues; iter; iter = g_list_next (iter)) {
1500       GstSingleQueue *oq = (GstSingleQueue *) iter->data;
1501
1502       if (get_buffering_level (oq) >= mq->high_watermark) {
1503         is_buffering = FALSE;
1504
1505         break;
1506       }
1507     }
1508
1509     if (is_buffering && buffering_level < mq->low_watermark) {
1510       mq->buffering = TRUE;
1511       SET_PERCENT (mq, percent);
1512     }
1513   }
1514 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
1515 /*common update buffering */
1516 /*while starts buffering, need restore start time */
1517   if (mq->enable_buffering_opt) {
1518     if (percent < mq->low_percent && mq->buffering == TRUE) {
1519       struct timeval tv = { 0 };
1520       GList *iter = NULL;
1521       gettimeofday (&tv, NULL);
1522
1523       mq->buffering_start_time =
1524           GST_SECOND * (guint64) tv.tv_sec + (guint64) tv.tv_usec * GST_USECOND;
1525       /*update all single queue */
1526       for (iter = mq->queues; iter; iter = g_list_next (iter)) {
1527         GstSingleQueue *oq = (GstSingleQueue *) iter->data;
1528         oq->cur_time_of_begin_buffering = oq->cur_time;
1529       }
1530       GST_DEBUG_OBJECT (mq,
1531           "update buffering start time, cur_time is : %" G_GUINT64_FORMAT,
1532           sq->cur_time_of_begin_buffering);
1533     } else if (mq->buffering == TRUE) {
1534       struct timeval tv = { 0 };
1535       gettimeofday (&tv, NULL);
1536       GstClockTime buffering_duration = sq->cur_time;
1537       guint64 tmp_time =
1538           GST_SECOND * (guint64) tv.tv_sec + (guint64) tv.tv_usec * GST_USECOND;
1539       guint64 elapsed_time = 0;
1540
1541       /*caculate elapsed time */
1542       tmp_time -= mq->buffering_start_time;
1543       elapsed_time = tmp_time;
1544       /*buffering percentage increase until its src pad is blocked,  */
1545       if (sq->cur_time > sq->cur_time_of_begin_buffering)
1546         buffering_duration = sq->cur_time - sq->cur_time_of_begin_buffering;
1547
1548       GST_DEBUG_OBJECT (mq,
1549           "%s, elapsed time is: %" G_GUINT64_FORMAT " cur_time is: %"
1550           G_GUINT64_FORMAT, sq->sq_stream_type == SQ_VIDEO_STREAM ? "vq" : "aq",
1551           elapsed_time, buffering_duration);
1552       tmp_time /= GST_SECOND;
1553
1554       /*demuxer speed is lower than decoder */
1555       if (tmp_time > 0 && (tmp_time % 3 == 0)
1556           && buffering_duration < elapsed_time
1557           && sq->sq_stream_type == SQ_VIDEO_STREAM) {
1558         GstFormat format = GST_FORMAT_TIME;
1559         guint64 cur_position = sq->srctime;
1560         GstCaps *video_caps = NULL;
1561         GstStructure *caps_structure = NULL;
1562         gint rnum = 0, rdenom = 1;
1563         gint r_framerate = 0, remaining_frame = 0, instant_throughput =
1564             0, estimated_video_frame_count = 0;
1565         GstDataQueueSize size;
1566
1567         if (cur_position <= 0 || mq->stream_duration <= 0) {
1568           GST_DEBUG_OBJECT (mq, "no duration or position");
1569           return;
1570         }
1571         gst_data_queue_get_level (sq->queue, &size);
1572
1573         video_caps = gst_pad_get_current_caps (sq->sinkpad);
1574         GST_DEBUG_OBJECT (mq, "stream caps: %" GST_PTR_FORMAT, video_caps);
1575
1576         if (video_caps != NULL) {
1577           caps_structure = gst_caps_get_structure (video_caps, 0);
1578
1579           if (caps_structure != NULL)
1580             gst_structure_get_fraction (caps_structure, "r_framerate", &rnum,
1581                 &rdenom);
1582
1583           gst_caps_unref (video_caps);
1584         }
1585
1586         else
1587           return;
1588
1589         if (rdenom != 0)
1590           r_framerate = rnum / rdenom;
1591
1592         GST_DEBUG_OBJECT (mq, "r_framerate is %d ", r_framerate);
1593
1594         remaining_frame = (mq->stream_duration - cur_position) * r_framerate / GST_SECOND - size.visible;       // packets num in video queue;
1595         instant_throughput = size.visible * GST_SECOND / elapsed_time;  // packets num / per seconds
1596         GST_DEBUG_OBJECT (mq, "remaining_fram is %d, instant_throughput is %d",
1597             remaining_frame, instant_throughput);
1598         if (remaining_frame != 0)
1599           estimated_video_frame_count =
1600               (int) ((remaining_frame * r_framerate) / (r_framerate +
1601                   instant_throughput));
1602       }
1603     }
1604   }
1605 #endif
1606 #ifdef TIZEN_PROFILE_TV
1607 /*RVU patch : rvu case disable audio buffering */
1608   return;
1609 LAST_POS:
1610   if (audio_caps != NULL) {
1611     gst_caps_unref (audio_caps);
1612     audio_caps = NULL;
1613   }
1614   GST_LOG_OBJECT (mq, "DISABLE AUDIO BUFFERING MESSAGE HANDLE!\n");
1615   return;
1616 #endif
1617 }
1618
1619 static void
1620 gst_multi_queue_post_buffering (GstMultiQueue * mq)
1621 {
1622   GstMessage *msg = NULL;
1623
1624   g_mutex_lock (&mq->buffering_post_lock);
1625   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1626   if (mq->buffering_percent_changed) {
1627     gint percent = mq->buffering_percent;
1628
1629     mq->buffering_percent_changed = FALSE;
1630
1631     GST_DEBUG_OBJECT (mq, "Going to post buffering: %d%%", percent);
1632     msg = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
1633   }
1634   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1635
1636   if (msg != NULL)
1637     gst_element_post_message (GST_ELEMENT_CAST (mq), msg);
1638
1639   g_mutex_unlock (&mq->buffering_post_lock);
1640 }
1641
1642 static void
1643 recheck_buffering_status (GstMultiQueue * mq)
1644 {
1645   if (!mq->use_buffering && mq->buffering) {
1646     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1647     mq->buffering = FALSE;
1648     GST_DEBUG_OBJECT (mq,
1649         "Buffering property disabled, but queue was still buffering; "
1650         "setting buffering percentage to 100%%");
1651     SET_PERCENT (mq, 100);
1652     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1653   }
1654
1655   if (mq->use_buffering) {
1656     GList *tmp;
1657     gint old_perc;
1658
1659     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1660
1661     /* force buffering percentage to be recalculated */
1662     old_perc = mq->buffering_percent;
1663     mq->buffering_percent = 0;
1664
1665     tmp = mq->queues;
1666     while (tmp) {
1667       GstSingleQueue *q = (GstSingleQueue *) tmp->data;
1668       update_buffering (mq, q);
1669       gst_data_queue_limits_changed (q->queue);
1670       tmp = g_list_next (tmp);
1671     }
1672
1673     GST_DEBUG_OBJECT (mq,
1674         "Recalculated buffering percentage: old: %d%% new: %d%%",
1675         old_perc, mq->buffering_percent);
1676
1677     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1678   }
1679
1680   gst_multi_queue_post_buffering (mq);
1681 }
1682
1683 static void
1684 calculate_interleave (GstMultiQueue * mq)
1685 {
1686   GstClockTimeDiff low, high;
1687   GstClockTime interleave;
1688   GList *tmp;
1689
1690   low = high = GST_CLOCK_STIME_NONE;
1691   interleave = mq->interleave;
1692   /* Go over all single queues and calculate lowest/highest value */
1693   for (tmp = mq->queues; tmp; tmp = tmp->next) {
1694     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1695     /* Ignore sparse streams for interleave calculation */
1696     if (sq->is_sparse)
1697       continue;
1698     /* If a stream is not active yet (hasn't received any buffers), set
1699      * a maximum interleave to allow it to receive more data */
1700     if (!sq->active) {
1701       GST_LOG_OBJECT (mq,
1702           "queue %d is not active yet, forcing interleave to 5s", sq->id);
1703       mq->interleave = 5 * GST_SECOND;
1704       /* Update max-size time */
1705       mq->max_size.time = mq->interleave;
1706       SET_CHILD_PROPERTY (mq, time);
1707       goto beach;
1708     }
1709     if (GST_CLOCK_STIME_IS_VALID (sq->cached_sinktime)) {
1710       if (low == GST_CLOCK_STIME_NONE || sq->cached_sinktime < low)
1711         low = sq->cached_sinktime;
1712       if (high == GST_CLOCK_STIME_NONE || sq->cached_sinktime > high)
1713         high = sq->cached_sinktime;
1714     }
1715     GST_LOG_OBJECT (mq,
1716         "queue %d , sinktime:%" GST_STIME_FORMAT " low:%" GST_STIME_FORMAT
1717         " high:%" GST_STIME_FORMAT, sq->id,
1718         GST_STIME_ARGS (sq->cached_sinktime), GST_STIME_ARGS (low),
1719         GST_STIME_ARGS (high));
1720   }
1721
1722   if (GST_CLOCK_STIME_IS_VALID (low) && GST_CLOCK_STIME_IS_VALID (high)) {
1723     interleave = high - low;
1724     /* Padding of interleave and minimum value */
1725     interleave = (150 * interleave / 100) + mq->min_interleave_time;
1726
1727     /* Update the stored interleave if:
1728      * * No data has arrived yet (high == low)
1729      * * Or it went higher
1730      * * Or it went lower and we've gone past the previous interleave needed */
1731     if (high == low || interleave > mq->interleave ||
1732         ((mq->last_interleave_update + (2 * MIN (GST_SECOND,
1733                         mq->interleave)) < low)
1734             && interleave < (mq->interleave * 3 / 4))) {
1735       /* Update the interleave */
1736       mq->interleave = interleave;
1737       mq->last_interleave_update = high;
1738       /* Update max-size time */
1739       mq->max_size.time = mq->interleave;
1740       SET_CHILD_PROPERTY (mq, time);
1741     }
1742   }
1743
1744 beach:
1745   GST_DEBUG_OBJECT (mq,
1746       "low:%" GST_STIME_FORMAT " high:%" GST_STIME_FORMAT " interleave:%"
1747       GST_TIME_FORMAT " mq->interleave:%" GST_TIME_FORMAT
1748       " last_interleave_update:%" GST_STIME_FORMAT, GST_STIME_ARGS (low),
1749       GST_STIME_ARGS (high), GST_TIME_ARGS (interleave),
1750       GST_TIME_ARGS (mq->interleave),
1751       GST_STIME_ARGS (mq->last_interleave_update));
1752 }
1753
1754
1755 /* calculate the diff between running time on the sink and src of the queue.
1756  * This is the total amount of time in the queue.
1757  * WITH LOCK TAKEN */
1758 static void
1759 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
1760 {
1761   GstClockTimeDiff sink_time, src_time;
1762
1763   if (sq->sink_tainted) {
1764     sink_time = sq->sinktime = my_segment_to_running_time (&sq->sink_segment,
1765         sq->sink_segment.position);
1766
1767     GST_DEBUG_OBJECT (mq,
1768         "queue %d sink_segment.position:%" GST_TIME_FORMAT ", sink_time:%"
1769         GST_STIME_FORMAT, sq->id, GST_TIME_ARGS (sq->sink_segment.position),
1770         GST_STIME_ARGS (sink_time));
1771
1772     if (G_UNLIKELY (sq->last_time == GST_CLOCK_STIME_NONE)) {
1773       /* If the single queue still doesn't have a last_time set, this means
1774        * that nothing has been pushed out yet.
1775        * In order for the high_time computation to be as efficient as possible,
1776        * we set the last_time */
1777       sq->last_time = sink_time;
1778     }
1779     if (G_UNLIKELY (sink_time != GST_CLOCK_STIME_NONE)) {
1780       /* if we have a time, we become untainted and use the time */
1781       sq->sink_tainted = FALSE;
1782       if (mq->use_interleave) {
1783         sq->cached_sinktime = sink_time;
1784         calculate_interleave (mq);
1785       }
1786     }
1787   } else
1788     sink_time = sq->sinktime;
1789
1790   if (sq->src_tainted) {
1791     GstSegment *segment;
1792     gint64 position;
1793
1794     if (sq->has_src_segment) {
1795       segment = &sq->src_segment;
1796       position = sq->src_segment.position;
1797     } else {
1798       /*
1799        * If the src pad had no segment yet, use the sink segment
1800        * to avoid signalling overrun if the received sink segment has a
1801        * a position > max-size-time while the src pad time would be the default=0
1802        *
1803        * This can happen when switching pads on chained/adaptive streams and the
1804        * new chain has a segment with a much larger position
1805        */
1806       segment = &sq->sink_segment;
1807       position = sq->sink_segment.position;
1808     }
1809
1810     src_time = sq->srctime = my_segment_to_running_time (segment, position);
1811     /* if we have a time, we become untainted and use the time */
1812     if (G_UNLIKELY (src_time != GST_CLOCK_STIME_NONE)) {
1813       sq->src_tainted = FALSE;
1814     }
1815   } else
1816     src_time = sq->srctime;
1817
1818   GST_DEBUG_OBJECT (mq,
1819       "queue %d, sink %" GST_STIME_FORMAT ", src %" GST_STIME_FORMAT, sq->id,
1820       GST_STIME_ARGS (sink_time), GST_STIME_ARGS (src_time));
1821
1822   /* This allows for streams with out of order timestamping - sometimes the
1823    * emerging timestamp is later than the arriving one(s) */
1824   if (G_LIKELY (GST_CLOCK_STIME_IS_VALID (sink_time) &&
1825           GST_CLOCK_STIME_IS_VALID (src_time) && sink_time > src_time))
1826     sq->cur_time = sink_time - src_time;
1827   else
1828     sq->cur_time = 0;
1829
1830   /* updating the time level can change the buffering state */
1831   update_buffering (mq, sq);
1832
1833   return;
1834 }
1835
1836 /* take a SEGMENT event and apply the values to segment, updating the time
1837  * level of queue. */
1838 static void
1839 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
1840     GstSegment * segment)
1841 {
1842   gst_event_copy_segment (event, segment);
1843
1844   /* now configure the values, we use these to track timestamps on the
1845    * sinkpad. */
1846   if (segment->format != GST_FORMAT_TIME) {
1847     /* non-time format, pretent the current time segment is closed with a
1848      * 0 start and unknown stop time. */
1849     segment->format = GST_FORMAT_TIME;
1850     segment->start = 0;
1851     segment->stop = -1;
1852     segment->time = 0;
1853   }
1854   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1855
1856   /* Make sure we have a valid initial segment position (and not garbage
1857    * from upstream) */
1858   if (segment->rate > 0.0)
1859     segment->position = segment->start;
1860   else
1861     segment->position = segment->stop;
1862   if (segment == &sq->sink_segment)
1863     sq->sink_tainted = TRUE;
1864   else {
1865     sq->has_src_segment = TRUE;
1866     sq->src_tainted = TRUE;
1867   }
1868
1869   GST_DEBUG_OBJECT (mq,
1870       "queue %d, configured SEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
1871
1872   /* segment can update the time level of the queue */
1873   update_time_level (mq, sq);
1874
1875   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1876   gst_multi_queue_post_buffering (mq);
1877 }
1878
1879 /* take a buffer and update segment, updating the time level of the queue. */
1880 static void
1881 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
1882     GstClockTime duration, GstSegment * segment)
1883 {
1884   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1885
1886   /* if no timestamp is set, assume it's continuous with the previous
1887    * time */
1888   if (timestamp == GST_CLOCK_TIME_NONE)
1889     timestamp = segment->position;
1890
1891   /* add duration */
1892   if (duration != GST_CLOCK_TIME_NONE)
1893     timestamp += duration;
1894
1895   GST_DEBUG_OBJECT (mq, "queue %d, %s position updated to %" GST_TIME_FORMAT,
1896       sq->id, segment == &sq->sink_segment ? "sink" : "src",
1897       GST_TIME_ARGS (timestamp));
1898
1899   segment->position = timestamp;
1900
1901   if (segment == &sq->sink_segment)
1902     sq->sink_tainted = TRUE;
1903   else
1904     sq->src_tainted = TRUE;
1905
1906   /* calc diff with other end */
1907   update_time_level (mq, sq);
1908   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1909   gst_multi_queue_post_buffering (mq);
1910 }
1911
1912 static void
1913 apply_gap (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
1914     GstSegment * segment)
1915 {
1916   GstClockTime timestamp;
1917   GstClockTime duration;
1918
1919   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1920
1921   gst_event_parse_gap (event, &timestamp, &duration);
1922
1923   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1924
1925     if (GST_CLOCK_TIME_IS_VALID (duration)) {
1926       timestamp += duration;
1927     }
1928
1929     segment->position = timestamp;
1930
1931     if (segment == &sq->sink_segment)
1932       sq->sink_tainted = TRUE;
1933     else
1934       sq->src_tainted = TRUE;
1935
1936     /* calc diff with other end */
1937     update_time_level (mq, sq);
1938   }
1939
1940   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1941   gst_multi_queue_post_buffering (mq);
1942 }
1943
1944 static GstClockTimeDiff
1945 get_running_time (GstSegment * segment, GstMiniObject * object, gboolean end)
1946 {
1947   GstClockTimeDiff time = GST_CLOCK_STIME_NONE;
1948
1949   if (GST_IS_BUFFER (object)) {
1950     GstBuffer *buf = GST_BUFFER_CAST (object);
1951     GstClockTime btime = GST_BUFFER_DTS_OR_PTS (buf);
1952
1953     if (GST_CLOCK_TIME_IS_VALID (btime)) {
1954       if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1955         btime += GST_BUFFER_DURATION (buf);
1956       if (btime > segment->stop)
1957         btime = segment->stop;
1958       time = my_segment_to_running_time (segment, btime);
1959     }
1960   } else if (GST_IS_BUFFER_LIST (object)) {
1961     GstBufferList *list = GST_BUFFER_LIST_CAST (object);
1962     gint i, n;
1963     GstBuffer *buf;
1964
1965     n = gst_buffer_list_length (list);
1966     for (i = 0; i < n; i++) {
1967       GstClockTime btime;
1968       buf = gst_buffer_list_get (list, i);
1969       btime = GST_BUFFER_DTS_OR_PTS (buf);
1970       if (GST_CLOCK_TIME_IS_VALID (btime)) {
1971         if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1972           btime += GST_BUFFER_DURATION (buf);
1973         if (btime > segment->stop)
1974           btime = segment->stop;
1975         time = my_segment_to_running_time (segment, btime);
1976         if (!end)
1977           goto done;
1978       } else if (!end) {
1979         goto done;
1980       }
1981     }
1982   } else if (GST_IS_EVENT (object)) {
1983     GstEvent *event = GST_EVENT_CAST (object);
1984
1985     /* For newsegment events return the running time of the start position */
1986     if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
1987       const GstSegment *new_segment;
1988
1989       gst_event_parse_segment (event, &new_segment);
1990       if (new_segment->format == GST_FORMAT_TIME) {
1991         time =
1992             my_segment_to_running_time ((GstSegment *) new_segment,
1993             new_segment->start);
1994       }
1995     }
1996   }
1997
1998 done:
1999   return time;
2000 }
2001
2002 static GstFlowReturn
2003 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
2004     GstMiniObject * object, gboolean * allow_drop)
2005 {
2006   GstFlowReturn result = sq->srcresult;
2007
2008   if (GST_IS_BUFFER (object)) {
2009     GstBuffer *buffer;
2010     GstClockTime timestamp, duration;
2011
2012     buffer = GST_BUFFER_CAST (object);
2013     timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2014     duration = GST_BUFFER_DURATION (buffer);
2015
2016     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
2017
2018     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
2019     gst_data_queue_limits_changed (sq->queue);
2020
2021     if (G_UNLIKELY (*allow_drop)) {
2022       GST_DEBUG_OBJECT (mq,
2023           "SingleQueue %d : Dropping EOS buffer %p with ts %" GST_TIME_FORMAT,
2024           sq->id, buffer, GST_TIME_ARGS (timestamp));
2025       gst_buffer_unref (buffer);
2026     } else {
2027       GST_DEBUG_OBJECT (mq,
2028           "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
2029           sq->id, buffer, GST_TIME_ARGS (timestamp));
2030       result = gst_pad_push (sq->srcpad, buffer);
2031     }
2032   } else if (GST_IS_EVENT (object)) {
2033     GstEvent *event;
2034
2035     event = GST_EVENT_CAST (object);
2036
2037     switch (GST_EVENT_TYPE (event)) {
2038       case GST_EVENT_EOS:
2039         result = GST_FLOW_EOS;
2040         if (G_UNLIKELY (*allow_drop))
2041           *allow_drop = FALSE;
2042         break;
2043       case GST_EVENT_SEGMENT:
2044         apply_segment (mq, sq, event, &sq->src_segment);
2045         /* Applying the segment may have made the queue non-full again, unblock it if needed */
2046         gst_data_queue_limits_changed (sq->queue);
2047         if (G_UNLIKELY (*allow_drop)) {
2048           result = GST_FLOW_OK;
2049           *allow_drop = FALSE;
2050         }
2051         break;
2052       case GST_EVENT_GAP:
2053         apply_gap (mq, sq, event, &sq->src_segment);
2054         /* Applying the gap may have made the queue non-full again, unblock it if needed */
2055         gst_data_queue_limits_changed (sq->queue);
2056         break;
2057       default:
2058         break;
2059     }
2060
2061     if (G_UNLIKELY (*allow_drop)) {
2062       GST_DEBUG_OBJECT (mq,
2063           "SingleQueue %d : Dropping EOS event %p of type %s",
2064           sq->id, event, GST_EVENT_TYPE_NAME (event));
2065       gst_event_unref (event);
2066     } else {
2067       GST_DEBUG_OBJECT (mq,
2068           "SingleQueue %d : Pushing event %p of type %s",
2069           sq->id, event, GST_EVENT_TYPE_NAME (event));
2070
2071       gst_pad_push_event (sq->srcpad, event);
2072     }
2073   } else if (GST_IS_QUERY (object)) {
2074     GstQuery *query;
2075     gboolean res;
2076
2077     query = GST_QUERY_CAST (object);
2078
2079     if (G_UNLIKELY (*allow_drop)) {
2080       GST_DEBUG_OBJECT (mq,
2081           "SingleQueue %d : Dropping EOS query %p", sq->id, query);
2082       gst_query_unref (query);
2083       res = FALSE;
2084     } else {
2085       res = gst_pad_peer_query (sq->srcpad, query);
2086     }
2087
2088     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2089     sq->last_query = res;
2090     sq->last_handled_query = query;
2091     g_cond_signal (&sq->query_handled);
2092     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2093   } else {
2094     g_warning ("Unexpected object in singlequeue %u (refcounting problem?)",
2095         sq->id);
2096   }
2097   return result;
2098
2099   /* ERRORS */
2100 }
2101
2102 static GstMiniObject *
2103 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
2104 {
2105   GstMiniObject *res;
2106
2107   res = item->object;
2108   item->object = NULL;
2109
2110   return res;
2111 }
2112
2113 static void
2114 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
2115 {
2116   if (!item->is_query && item->object)
2117     gst_mini_object_unref (item->object);
2118   g_slice_free (GstMultiQueueItem, item);
2119 }
2120
2121 /* takes ownership of passed mini object! */
2122 static GstMultiQueueItem *
2123 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
2124 {
2125   GstMultiQueueItem *item;
2126
2127   item = g_slice_new (GstMultiQueueItem);
2128   item->object = object;
2129   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
2130   item->posid = curid;
2131   item->is_query = GST_IS_QUERY (object);
2132
2133   item->size = gst_buffer_get_size (GST_BUFFER_CAST (object));
2134   item->duration = GST_BUFFER_DURATION (object);
2135   if (item->duration == GST_CLOCK_TIME_NONE)
2136     item->duration = 0;
2137   item->visible = TRUE;
2138   return item;
2139 }
2140
2141 static GstMultiQueueItem *
2142 gst_multi_queue_mo_item_new (GstMiniObject * object, guint32 curid)
2143 {
2144   GstMultiQueueItem *item;
2145
2146   item = g_slice_new (GstMultiQueueItem);
2147   item->object = object;
2148   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
2149   item->posid = curid;
2150   item->is_query = GST_IS_QUERY (object);
2151
2152   item->size = 0;
2153   item->duration = 0;
2154   item->visible = FALSE;
2155   return item;
2156 }
2157
2158 /* Each main loop attempts to push buffers until the return value
2159  * is not-linked. not-linked pads are not allowed to push data beyond
2160  * any linked pads, so they don't 'rush ahead of the pack'.
2161  */
2162 static void
2163 gst_multi_queue_loop (GstPad * pad)
2164 {
2165   GstSingleQueue *sq;
2166   GstMultiQueueItem *item;
2167   GstDataQueueItem *sitem;
2168   GstMultiQueue *mq;
2169   GstMiniObject *object = NULL;
2170   guint32 newid;
2171   GstFlowReturn result;
2172   GstClockTimeDiff next_time;
2173   gboolean is_buffer;
2174   gboolean do_update_buffering = FALSE;
2175   gboolean dropping = FALSE;
2176
2177   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2178   mq = sq->mqueue;
2179
2180 next:
2181   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
2182
2183   if (sq->flushing)
2184     goto out_flushing;
2185 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
2186   if (mq->stream_duration == 0) {
2187     GstPad *peer = NULL;
2188     peer = gst_pad_get_peer (sq->sinkpad);
2189     if (peer) {
2190       if (!gst_pad_query_duration (peer, GST_FORMAT_TIME,
2191               &(mq->stream_duration)))
2192         GST_WARNING_OBJECT (mq, "Could not query upstream length!");
2193       gst_object_unref (peer);
2194     }
2195   }
2196 #endif
2197   /* Get something from the queue, blocking until that happens, or we get
2198    * flushed */
2199   if (!(gst_data_queue_pop (sq->queue, &sitem)))
2200     goto out_flushing;
2201
2202   item = (GstMultiQueueItem *) sitem;
2203   newid = item->posid;
2204
2205   /* steal the object and destroy the item */
2206   object = gst_multi_queue_item_steal_object (item);
2207   gst_multi_queue_item_destroy (item);
2208
2209   is_buffer = GST_IS_BUFFER (object);
2210
2211   /* Get running time of the item. Events will have GST_CLOCK_STIME_NONE */
2212   next_time = get_running_time (&sq->src_segment, object, FALSE);
2213
2214   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
2215       sq->id, newid, sq->last_oldid);
2216
2217   /* If we're not-linked, we do some extra work because we might need to
2218    * wait before pushing. If we're linked but there's a gap in the IDs,
2219    * or it's the first loop, or we just passed the previous highid,
2220    * we might need to wake some sleeping pad up, so there's extra work
2221    * there too */
2222   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2223   if (sq->srcresult == GST_FLOW_NOT_LINKED
2224       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
2225       || sq->last_oldid > mq->highid) {
2226     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
2227         gst_flow_get_name (sq->srcresult));
2228
2229     /* Check again if we're flushing after the lock is taken,
2230      * the flush flag might have been changed in the meantime */
2231     if (sq->flushing) {
2232       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2233       goto out_flushing;
2234     }
2235
2236     /* Update the nextid so other threads know when to wake us up */
2237     sq->nextid = newid;
2238     /* Take into account the extra cache time since we're unlinked */
2239     if (GST_CLOCK_STIME_IS_VALID (next_time))
2240       next_time += mq->unlinked_cache_time;
2241     sq->next_time = next_time;
2242
2243     /* Update the oldid (the last ID we output) for highid tracking */
2244     if (sq->last_oldid != G_MAXUINT32)
2245       sq->oldid = sq->last_oldid;
2246
2247     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2248       gboolean should_wait;
2249       /* Go to sleep until it's time to push this buffer */
2250
2251       /* Recompute the highid */
2252       compute_high_id (mq);
2253       /* Recompute the high time */
2254       compute_high_time (mq, sq->groupid);
2255
2256       GST_DEBUG_OBJECT (mq,
2257           "groupid %d high_time %" GST_STIME_FORMAT " next_time %"
2258           GST_STIME_FORMAT, sq->groupid, GST_STIME_ARGS (sq->group_high_time),
2259           GST_STIME_ARGS (next_time));
2260
2261       if (mq->sync_by_running_time) {
2262         if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2263           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2264               (mq->high_time == GST_CLOCK_STIME_NONE
2265               || next_time > mq->high_time);
2266         } else {
2267           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2268               next_time > sq->group_high_time;
2269         }
2270       } else
2271         should_wait = newid > mq->highid;
2272
2273       while (should_wait && sq->srcresult == GST_FLOW_NOT_LINKED) {
2274
2275         GST_DEBUG_OBJECT (mq,
2276             "queue %d sleeping for not-linked wakeup with "
2277             "newid %u, highid %u, next_time %" GST_STIME_FORMAT
2278             ", high_time %" GST_STIME_FORMAT, sq->id, newid, mq->highid,
2279             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time));
2280
2281         /* Wake up all non-linked pads before we sleep */
2282         wake_up_next_non_linked (mq);
2283
2284         mq->numwaiting++;
2285         g_cond_wait (&sq->turn, &mq->qlock);
2286         mq->numwaiting--;
2287
2288         if (sq->flushing) {
2289           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2290           goto out_flushing;
2291         }
2292
2293         /* Recompute the high time and ID */
2294         compute_high_time (mq, sq->groupid);
2295         compute_high_id (mq);
2296
2297         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
2298             "wakeup with newid %u, highid %u, next_time %" GST_STIME_FORMAT
2299             ", high_time %" GST_STIME_FORMAT " mq high_time %" GST_STIME_FORMAT,
2300             sq->id, newid, mq->highid,
2301             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time),
2302             GST_STIME_ARGS (mq->high_time));
2303
2304         if (mq->sync_by_running_time) {
2305           if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2306             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2307                 (mq->high_time == GST_CLOCK_STIME_NONE
2308                 || next_time > mq->high_time);
2309           } else {
2310             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2311                 next_time > sq->group_high_time;
2312           }
2313         } else
2314           should_wait = newid > mq->highid;
2315       }
2316
2317       /* Re-compute the high_id in case someone else pushed */
2318       compute_high_id (mq);
2319       compute_high_time (mq, sq->groupid);
2320     } else {
2321       compute_high_id (mq);
2322       compute_high_time (mq, sq->groupid);
2323       /* Wake up all non-linked pads */
2324       wake_up_next_non_linked (mq);
2325     }
2326     /* We're done waiting, we can clear the nextid and nexttime */
2327     sq->nextid = 0;
2328     sq->next_time = GST_CLOCK_STIME_NONE;
2329   }
2330   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2331
2332   if (sq->flushing)
2333     goto out_flushing;
2334
2335   GST_LOG_OBJECT (mq, "sq:%d BEFORE PUSHING sq->srcresult: %s", sq->id,
2336       gst_flow_get_name (sq->srcresult));
2337
2338   /* Update time stats */
2339   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2340   next_time = get_running_time (&sq->src_segment, object, TRUE);
2341   if (GST_CLOCK_STIME_IS_VALID (next_time)) {
2342     if (sq->last_time == GST_CLOCK_STIME_NONE || sq->last_time < next_time)
2343       sq->last_time = next_time;
2344     if (mq->high_time == GST_CLOCK_STIME_NONE || mq->high_time <= next_time) {
2345       /* Wake up all non-linked pads now that we advanced the high time */
2346       mq->high_time = next_time;
2347       wake_up_next_non_linked (mq);
2348     }
2349   }
2350   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2351
2352   /* Try to push out the new object */
2353   result = gst_single_queue_push_one (mq, sq, object, &dropping);
2354   object = NULL;
2355
2356   /* Check if we pushed something already and if this is
2357    * now a switch from an active to a non-active stream.
2358    *
2359    * If it is, we reset all the waiting streams, let them
2360    * push another buffer to see if they're now active again.
2361    * This allows faster switching between streams and prevents
2362    * deadlocks if downstream does any waiting too.
2363    */
2364   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2365   if (sq->pushed && sq->srcresult == GST_FLOW_OK
2366       && result == GST_FLOW_NOT_LINKED) {
2367     GList *tmp;
2368
2369     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
2370         sq->id);
2371
2372     compute_high_id (mq);
2373     compute_high_time (mq, sq->groupid);
2374     do_update_buffering = TRUE;
2375
2376     /* maybe no-one is waiting */
2377     if (mq->numwaiting > 0) {
2378       /* Else figure out which singlequeue(s) need waking up */
2379       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2380         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
2381
2382         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
2383           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
2384           sq2->pushed = FALSE;
2385           sq2->srcresult = GST_FLOW_OK;
2386           g_cond_signal (&sq2->turn);
2387         }
2388       }
2389     }
2390   }
2391
2392   if (is_buffer)
2393     sq->pushed = TRUE;
2394
2395   /* now hold on a bit;
2396    * can not simply throw this result to upstream, because
2397    * that might already be onto another segment, so we have to make
2398    * sure we are relaying the correct info wrt proper segment */
2399   if (result == GST_FLOW_EOS && !dropping &&
2400       sq->srcresult != GST_FLOW_NOT_LINKED) {
2401     GST_DEBUG_OBJECT (mq, "starting EOS drop on sq %d", sq->id);
2402     dropping = TRUE;
2403     /* pretend we have not seen EOS yet for upstream's sake */
2404     result = sq->srcresult;
2405   } else if (dropping && gst_data_queue_is_empty (sq->queue)) {
2406     /* queue empty, so stop dropping
2407      * we can commit the result we have now,
2408      * which is either OK after a segment, or EOS */
2409     GST_DEBUG_OBJECT (mq, "committed EOS drop on sq %d", sq->id);
2410     dropping = FALSE;
2411     result = GST_FLOW_EOS;
2412   }
2413   sq->srcresult = result;
2414   sq->last_oldid = newid;
2415
2416   if (do_update_buffering)
2417     update_buffering (mq, sq);
2418
2419   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2420   gst_multi_queue_post_buffering (mq);
2421
2422   GST_LOG_OBJECT (mq, "sq:%d AFTER PUSHING sq->srcresult: %s (is_eos:%d)",
2423       sq->id, gst_flow_get_name (sq->srcresult), GST_PAD_IS_EOS (sq->srcpad));
2424
2425   /* Need to make sure wake up any sleeping pads when we exit */
2426   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2427   if (mq->numwaiting > 0 && (GST_PAD_IS_EOS (sq->srcpad)
2428           || sq->srcresult == GST_FLOW_EOS)) {
2429     compute_high_time (mq, sq->groupid);
2430     compute_high_id (mq);
2431     wake_up_next_non_linked (mq);
2432   }
2433   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2434
2435   if (dropping)
2436     goto next;
2437
2438   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
2439       && result != GST_FLOW_EOS)
2440     goto out_flushing;
2441
2442   return;
2443
2444 out_flushing:
2445   {
2446     if (object)
2447       gst_mini_object_unref (object);
2448
2449     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2450     sq->last_query = FALSE;
2451     g_cond_signal (&sq->query_handled);
2452
2453     /* Post an error message if we got EOS while downstream
2454      * has returned an error flow return. After EOS there
2455      * will be no further buffer which could propagate the
2456      * error upstream */
2457     if (sq->is_eos && sq->srcresult < GST_FLOW_EOS) {
2458       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2459       GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2460     } else {
2461       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2462     }
2463
2464     /* upstream needs to see fatal result ASAP to shut things down,
2465      * but might be stuck in one of our other full queues;
2466      * so empty this one and trigger dynamic queue growth. At
2467      * this point the srcresult is not OK, NOT_LINKED
2468      * or EOS, i.e. a real failure */
2469     gst_single_queue_flush_queue (sq, FALSE);
2470     single_queue_underrun_cb (sq->queue, sq);
2471     gst_data_queue_set_flushing (sq->queue, TRUE);
2472     gst_pad_pause_task (sq->srcpad);
2473     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
2474         "SingleQueue[%d] task paused, reason:%s",
2475         sq->id, gst_flow_get_name (sq->srcresult));
2476     return;
2477   }
2478 }
2479
2480 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
2481 /*RVU patch : set buffering params*/
2482 static void
2483 single_queue_set_stream_type (GstSingleQueue * squeue, GstBuffer * buffer)
2484 {
2485   if (squeue->sq_stream_type == -1 && buffer) {
2486     GstCaps *buffer_caps = NULL;
2487     GstStructure *caps_str = NULL;
2488     const gchar *mime_type = NULL;
2489     const gchar *drm_stream_type = NULL;
2490     struct timeval tv = { 0 };
2491
2492     do {
2493       buffer_caps = gst_pad_get_current_caps (squeue->sinkpad); //GST_BUFFER_CAPS(buffer);
2494       if (NULL == buffer_caps) {
2495         GST_DEBUG_OBJECT (squeue->mqueue, "cannot get caps from single queue.");
2496         break;
2497       }
2498
2499       GST_DEBUG_OBJECT (squeue->mqueue, "single queue caps  %" GST_PTR_FORMAT,
2500           buffer_caps);
2501
2502       caps_str = gst_caps_get_structure (buffer_caps, 0);
2503       if (NULL == caps_str) {
2504         GST_DEBUG_OBJECT (squeue->mqueue, "cannot get structure from capse.");
2505         break;
2506       }
2507
2508       mime_type = gst_structure_get_name (caps_str);
2509       if (NULL == mime_type) {
2510         GST_DEBUG_OBJECT (squeue->mqueue,
2511             "cannot get mimetype from structure.");
2512         break;
2513       }
2514
2515       drm_stream_type = gst_structure_get_string (caps_str, "stream-type");
2516
2517       if (g_strrstr (mime_type, "video/") || (drm_stream_type
2518               && g_strrstr (drm_stream_type, "video/"))) {
2519         squeue->sq_stream_type = SQ_VIDEO_STREAM;
2520         /*subtitle stream */
2521         if (g_strrstr (mime_type, "video/x-dvb-subpicture"))
2522           squeue->sq_stream_type = SQ_OTHER_STREAM;
2523
2524         gettimeofday (&tv, NULL);
2525         if (squeue->mqueue->buffering_start_time == 0)
2526           squeue->mqueue->buffering_start_time =
2527               GST_SECOND * (guint64) tv.tv_sec +
2528               (guint64) tv.tv_usec * GST_USECOND;
2529       } else if (g_strrstr (mime_type, "audio/") || (drm_stream_type
2530               && g_strrstr (drm_stream_type, "audio/"))) {
2531         squeue->sq_stream_type = SQ_AUDIO_STREAM;
2532         gettimeofday (&tv, NULL);
2533         if (squeue->mqueue->buffering_start_time == 0)
2534           squeue->mqueue->buffering_start_time =
2535               GST_SECOND * (guint64) tv.tv_sec +
2536               (guint64) tv.tv_usec * GST_USECOND;
2537       } else {
2538         squeue->sq_stream_type = SQ_OTHER_STREAM;
2539       }
2540     } while (0);
2541   }
2542 }
2543 #endif
2544 /**
2545  * gst_multi_queue_chain:
2546  *
2547  * This is similar to GstQueue's chain function, except:
2548  * _ we don't have leak behaviours,
2549  * _ we push with a unique id (curid)
2550  */
2551 static GstFlowReturn
2552 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2553 {
2554   GstSingleQueue *sq;
2555   GstMultiQueue *mq;
2556   GstMultiQueueItem *item;
2557   guint32 curid;
2558   GstClockTime timestamp, duration;
2559
2560   sq = gst_pad_get_element_private (pad);
2561   mq = sq->mqueue;
2562
2563 #ifdef RVU_LIVESTREAMING_OPTIMIZATION
2564   if (mq->enable_buffering_opt) {
2565     single_queue_set_stream_type (sq, buffer);
2566   }
2567 #endif
2568   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2569   if (sq->is_eos)
2570     goto was_eos;
2571
2572   sq->active = TRUE;
2573
2574   /* Get a unique incrementing id */
2575   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2576
2577   timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2578   duration = GST_BUFFER_DURATION (buffer);
2579
2580   GST_LOG_OBJECT (mq,
2581       "SingleQueue %d : about to enqueue buffer %p with id %d (pts:%"
2582       GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT " dur:%" GST_TIME_FORMAT ")",
2583       sq->id, buffer, curid, GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2584       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), GST_TIME_ARGS (duration));
2585
2586   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
2587
2588   /* Update interleave before pushing data into queue */
2589   if (mq->use_interleave) {
2590     GstClockTime val = timestamp;
2591     GstClockTimeDiff dval;
2592
2593     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2594     if (val == GST_CLOCK_TIME_NONE)
2595       val = sq->sink_segment.position;
2596     if (duration != GST_CLOCK_TIME_NONE)
2597       val += duration;
2598
2599     dval = my_segment_to_running_time (&sq->sink_segment, val);
2600     if (GST_CLOCK_STIME_IS_VALID (dval)) {
2601       sq->cached_sinktime = dval;
2602       GST_DEBUG_OBJECT (mq,
2603           "Queue %d cached sink time now %" G_GINT64_FORMAT " %"
2604           GST_STIME_FORMAT, sq->id, sq->cached_sinktime,
2605           GST_STIME_ARGS (sq->cached_sinktime));
2606       calculate_interleave (mq);
2607     }
2608     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2609   }
2610
2611   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
2612     goto flushing;
2613
2614   /* update time level, we must do this after pushing the data in the queue so
2615    * that we never end up filling the queue first. */
2616   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
2617
2618 done:
2619   return sq->srcresult;
2620
2621   /* ERRORS */
2622 flushing:
2623   {
2624     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2625         sq->id, gst_flow_get_name (sq->srcresult));
2626     gst_multi_queue_item_destroy (item);
2627     goto done;
2628   }
2629 was_eos:
2630   {
2631     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
2632     gst_buffer_unref (buffer);
2633     return GST_FLOW_EOS;
2634   }
2635 }
2636
2637 static gboolean
2638 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
2639     GstPadMode mode, gboolean active)
2640 {
2641   gboolean res;
2642   GstSingleQueue *sq;
2643   GstMultiQueue *mq;
2644
2645   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2646   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
2647
2648   /* mq is NULL if the pad is activated/deactivated before being
2649    * added to the multiqueue */
2650   if (mq)
2651     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2652
2653   switch (mode) {
2654     case GST_PAD_MODE_PUSH:
2655       if (active) {
2656         /* All pads start off linked until they push one buffer */
2657         sq->srcresult = GST_FLOW_OK;
2658         sq->pushed = FALSE;
2659         gst_data_queue_set_flushing (sq->queue, FALSE);
2660       } else {
2661         sq->srcresult = GST_FLOW_FLUSHING;
2662         sq->last_query = FALSE;
2663         g_cond_signal (&sq->query_handled);
2664         gst_data_queue_set_flushing (sq->queue, TRUE);
2665
2666         /* Wait until streaming thread has finished */
2667         if (mq)
2668           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2669         GST_PAD_STREAM_LOCK (pad);
2670         if (mq)
2671           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2672         gst_data_queue_flush (sq->queue);
2673         if (mq)
2674           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2675         GST_PAD_STREAM_UNLOCK (pad);
2676         if (mq)
2677           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2678       }
2679       res = TRUE;
2680       break;
2681     default:
2682       res = FALSE;
2683       break;
2684   }
2685
2686   if (mq) {
2687     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2688     gst_object_unref (mq);
2689   }
2690
2691   return res;
2692 }
2693
2694 static GstFlowReturn
2695 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2696 {
2697   GstSingleQueue *sq;
2698   GstMultiQueue *mq;
2699   guint32 curid;
2700   GstMultiQueueItem *item;
2701   gboolean res = TRUE;
2702   GstFlowReturn flowret = GST_FLOW_OK;
2703   GstEventType type;
2704   GstEvent *sref = NULL;
2705
2706   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2707   mq = (GstMultiQueue *) parent;
2708
2709   type = GST_EVENT_TYPE (event);
2710
2711   switch (type) {
2712     case GST_EVENT_STREAM_START:
2713     {
2714       if (mq->sync_by_running_time) {
2715         GstStreamFlags stream_flags;
2716         gst_event_parse_stream_flags (event, &stream_flags);
2717         if ((stream_flags & GST_STREAM_FLAG_SPARSE)) {
2718           GST_INFO_OBJECT (mq, "SingleQueue %d is a sparse stream", sq->id);
2719           sq->is_sparse = TRUE;
2720         }
2721       }
2722
2723       sq->thread = g_thread_self ();
2724
2725       /* Remove EOS flag */
2726       sq->is_eos = FALSE;
2727       break;
2728     }
2729     case GST_EVENT_FLUSH_START:
2730       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
2731           sq->id);
2732
2733       res = gst_pad_push_event (sq->srcpad, event);
2734
2735       gst_single_queue_flush (mq, sq, TRUE, FALSE);
2736       goto done;
2737
2738     case GST_EVENT_FLUSH_STOP:
2739       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
2740           sq->id);
2741
2742       res = gst_pad_push_event (sq->srcpad, event);
2743
2744       gst_single_queue_flush (mq, sq, FALSE, FALSE);
2745       goto done;
2746
2747     case GST_EVENT_SEGMENT:
2748       sref = gst_event_ref (event);
2749       break;
2750     case GST_EVENT_GAP:
2751       /* take ref because the queue will take ownership and we need the event
2752        * afterwards to update the segment */
2753       sref = gst_event_ref (event);
2754       if (mq->use_interleave) {
2755         GstClockTime val, dur;
2756         GstClockTime stime;
2757         gst_event_parse_gap (event, &val, &dur);
2758         if (GST_CLOCK_TIME_IS_VALID (val)) {
2759           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2760           if (GST_CLOCK_TIME_IS_VALID (dur))
2761             val += dur;
2762           stime = my_segment_to_running_time (&sq->sink_segment, val);
2763           if (GST_CLOCK_STIME_IS_VALID (stime)) {
2764             sq->cached_sinktime = stime;
2765             calculate_interleave (mq);
2766           }
2767           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2768         }
2769       }
2770       break;
2771
2772     default:
2773       if (!(GST_EVENT_IS_SERIALIZED (event))) {
2774         res = gst_pad_push_event (sq->srcpad, event);
2775         goto done;
2776       }
2777       break;
2778   }
2779
2780   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2781   if (sq->is_eos)
2782     goto was_eos;
2783
2784   /* Get an unique incrementing id. */
2785   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2786
2787   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
2788
2789   GST_DEBUG_OBJECT (mq,
2790       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
2791       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
2792
2793   if (!gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))
2794     goto flushing;
2795
2796   /* mark EOS when we received one, we must do that after putting the
2797    * buffer in the queue because EOS marks the buffer as filled. */
2798   switch (type) {
2799     case GST_EVENT_EOS:
2800       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2801       sq->is_eos = TRUE;
2802
2803       /* Post an error message if we got EOS while downstream
2804        * has returned an error flow return. After EOS there
2805        * will be no further buffer which could propagate the
2806        * error upstream */
2807       if (sq->srcresult < GST_FLOW_EOS) {
2808         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2809         GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2810       } else {
2811         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2812       }
2813
2814       /* EOS affects the buffering state */
2815       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2816       update_buffering (mq, sq);
2817       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2818       single_queue_overrun_cb (sq->queue, sq);
2819       gst_multi_queue_post_buffering (mq);
2820       break;
2821     case GST_EVENT_SEGMENT:
2822       apply_segment (mq, sq, sref, &sq->sink_segment);
2823       gst_event_unref (sref);
2824       /* a new segment allows us to accept more buffers if we got EOS
2825        * from downstream */
2826       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2827       if (sq->srcresult == GST_FLOW_EOS)
2828         sq->srcresult = GST_FLOW_OK;
2829       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2830       break;
2831     case GST_EVENT_GAP:
2832       sq->active = TRUE;
2833       apply_gap (mq, sq, sref, &sq->sink_segment);
2834       gst_event_unref (sref);
2835     default:
2836       break;
2837   }
2838
2839 done:
2840   if (res == FALSE)
2841     flowret = GST_FLOW_ERROR;
2842   GST_DEBUG_OBJECT (mq, "SingleQueue %d : returning %s", sq->id,
2843       gst_flow_get_name (flowret));
2844   return flowret;
2845
2846 flushing:
2847   {
2848     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2849         sq->id, gst_flow_get_name (sq->srcresult));
2850     if (sref)
2851       gst_event_unref (sref);
2852     gst_multi_queue_item_destroy (item);
2853     return sq->srcresult;
2854   }
2855 was_eos:
2856   {
2857     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return GST_FLOW_EOS");
2858     gst_event_unref (event);
2859     return GST_FLOW_EOS;
2860   }
2861 }
2862
2863 static gboolean
2864 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
2865 {
2866   gboolean res;
2867   GstSingleQueue *sq;
2868   GstMultiQueue *mq;
2869
2870   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2871   mq = (GstMultiQueue *) parent;
2872
2873   switch (GST_QUERY_TYPE (query)) {
2874     default:
2875       if (GST_QUERY_IS_SERIALIZED (query)) {
2876         guint32 curid;
2877         GstMultiQueueItem *item;
2878
2879         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2880         if (sq->srcresult != GST_FLOW_OK)
2881           goto out_flushing;
2882
2883         /* serialized events go in the queue. We need to be certain that we
2884          * don't cause deadlocks waiting for the query return value. We check if
2885          * the queue is empty (nothing is blocking downstream and the query can
2886          * be pushed for sure) or we are not buffering. If we are buffering,
2887          * the pipeline waits to unblock downstream until our queue fills up
2888          * completely, which can not happen if we block on the query..
2889          * Therefore we only potentially block when we are not buffering. */
2890         if (!mq->use_buffering || gst_data_queue_is_empty (sq->queue)) {
2891           /* Get an unique incrementing id. */
2892           curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2893
2894           item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
2895
2896           GST_DEBUG_OBJECT (mq,
2897               "SingleQueue %d : Enqueuing query %p of type %s with id %d",
2898               sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
2899           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2900           res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
2901           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2902           if (!res || sq->flushing)
2903             goto out_flushing;
2904           /* it might be that the query has been taken out of the queue
2905            * while we were unlocked. So, we need to check if the last
2906            * handled query is the same one than the one we just
2907            * pushed. If it is, we don't need to wait for the condition
2908            * variable, otherwise we wait for the condition variable to
2909            * be signaled. */
2910           while (!sq->flushing && sq->srcresult == GST_FLOW_OK
2911               && sq->last_handled_query != query)
2912             g_cond_wait (&sq->query_handled, &mq->qlock);
2913           res = sq->last_query;
2914           sq->last_handled_query = NULL;
2915         } else {
2916           GST_DEBUG_OBJECT (mq, "refusing query, we are buffering and the "
2917               "queue is not empty");
2918           res = FALSE;
2919         }
2920         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2921       } else {
2922         /* default handling */
2923         res = gst_pad_query_default (pad, parent, query);
2924       }
2925       break;
2926   }
2927   return res;
2928
2929 out_flushing:
2930   {
2931     GST_DEBUG_OBJECT (mq, "Flushing");
2932     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2933     return FALSE;
2934   }
2935 }
2936
2937 static gboolean
2938 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
2939     GstPadMode mode, gboolean active)
2940 {
2941   GstMultiQueue *mq;
2942   GstSingleQueue *sq;
2943   gboolean result;
2944
2945   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2946   mq = sq->mqueue;
2947
2948   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
2949
2950   switch (mode) {
2951     case GST_PAD_MODE_PUSH:
2952       if (active) {
2953         result = gst_single_queue_flush (mq, sq, FALSE, TRUE);
2954       } else {
2955         result = gst_single_queue_flush (mq, sq, TRUE, TRUE);
2956         /* make sure streaming finishes */
2957         result |= gst_pad_stop_task (pad);
2958       }
2959       break;
2960     default:
2961       result = FALSE;
2962       break;
2963   }
2964   return result;
2965 }
2966
2967 static gboolean
2968 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2969 {
2970   GstSingleQueue *sq = gst_pad_get_element_private (pad);
2971   GstMultiQueue *mq = sq->mqueue;
2972   gboolean ret;
2973
2974   switch (GST_EVENT_TYPE (event)) {
2975     case GST_EVENT_RECONFIGURE:
2976       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2977       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2978         sq->srcresult = GST_FLOW_OK;
2979         g_cond_signal (&sq->turn);
2980       }
2981       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2982
2983       ret = gst_pad_push_event (sq->sinkpad, event);
2984       break;
2985     default:
2986       ret = gst_pad_push_event (sq->sinkpad, event);
2987       break;
2988   }
2989
2990   return ret;
2991 }
2992
2993 static gboolean
2994 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2995 {
2996   gboolean res;
2997
2998   /* FIXME, Handle position offset depending on queue size */
2999   switch (GST_QUERY_TYPE (query)) {
3000     default:
3001       /* default handling */
3002       res = gst_pad_query_default (pad, parent, query);
3003       break;
3004   }
3005   return res;
3006 }
3007
3008 /*
3009  * Next-non-linked functions
3010  */
3011
3012 /* WITH LOCK TAKEN */
3013 static void
3014 wake_up_next_non_linked (GstMultiQueue * mq)
3015 {
3016   GList *tmp;
3017
3018   /* maybe no-one is waiting */
3019   if (mq->numwaiting < 1)
3020     return;
3021
3022   if (mq->sync_by_running_time && GST_CLOCK_STIME_IS_VALID (mq->high_time)) {
3023     /* Else figure out which singlequeue(s) need waking up */
3024     for (tmp = mq->queues; tmp; tmp = tmp->next) {
3025       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3026       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3027         GstClockTimeDiff high_time;
3028
3029         if (GST_CLOCK_STIME_IS_VALID (sq->group_high_time))
3030           high_time = sq->group_high_time;
3031         else
3032           high_time = mq->high_time;
3033
3034         if (GST_CLOCK_STIME_IS_VALID (sq->next_time) &&
3035             GST_CLOCK_STIME_IS_VALID (high_time)
3036             && sq->next_time <= high_time) {
3037           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
3038           g_cond_signal (&sq->turn);
3039         }
3040       }
3041     }
3042   } else {
3043     /* Else figure out which singlequeue(s) need waking up */
3044     for (tmp = mq->queues; tmp; tmp = tmp->next) {
3045       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3046       if (sq->srcresult == GST_FLOW_NOT_LINKED &&
3047           sq->nextid != 0 && sq->nextid <= mq->highid) {
3048         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
3049         g_cond_signal (&sq->turn);
3050       }
3051     }
3052   }
3053 }
3054
3055 /* WITH LOCK TAKEN */
3056 static void
3057 compute_high_id (GstMultiQueue * mq)
3058 {
3059   /* The high-id is either the highest id among the linked pads, or if all
3060    * pads are not-linked, it's the lowest not-linked pad */
3061   GList *tmp;
3062   guint32 lowest = G_MAXUINT32;
3063   guint32 highid = G_MAXUINT32;
3064
3065   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3066     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3067
3068     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
3069         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
3070
3071     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3072       /* No need to consider queues which are not waiting */
3073       if (sq->nextid == 0) {
3074         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3075         continue;
3076       }
3077
3078       if (sq->nextid < lowest)
3079         lowest = sq->nextid;
3080     } else if (!GST_PAD_IS_EOS (sq->srcpad) && sq->srcresult != GST_FLOW_EOS) {
3081       /* If we don't have a global highid, or the global highid is lower than
3082        * this single queue's last outputted id, store the queue's one,
3083        * unless the singlequeue output is at EOS */
3084       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
3085         highid = sq->oldid;
3086     }
3087   }
3088
3089   if (highid == G_MAXUINT32 || lowest < highid)
3090     mq->highid = lowest;
3091   else
3092     mq->highid = highid;
3093
3094   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
3095       lowest);
3096 }
3097
3098 /* WITH LOCK TAKEN */
3099 static void
3100 compute_high_time (GstMultiQueue * mq, guint groupid)
3101 {
3102   /* The high-time is either the highest last time among the linked
3103    * pads, or if all pads are not-linked, it's the lowest nex time of
3104    * not-linked pad */
3105   GList *tmp;
3106   GstClockTimeDiff highest = GST_CLOCK_STIME_NONE;
3107   GstClockTimeDiff lowest = GST_CLOCK_STIME_NONE;
3108   GstClockTimeDiff group_high = GST_CLOCK_STIME_NONE;
3109   GstClockTimeDiff group_low = GST_CLOCK_STIME_NONE;
3110   GstClockTimeDiff res;
3111   /* Number of streams which belong to groupid */
3112   guint group_count = 0;
3113
3114   if (!mq->sync_by_running_time)
3115     /* return GST_CLOCK_STIME_NONE; */
3116     return;
3117
3118   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3119     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3120
3121     GST_LOG_OBJECT (mq,
3122         "inspecting sq:%d (group:%d) , next_time:%" GST_STIME_FORMAT
3123         ", last_time:%" GST_STIME_FORMAT ", srcresult:%s", sq->id, sq->groupid,
3124         GST_STIME_ARGS (sq->next_time), GST_STIME_ARGS (sq->last_time),
3125         gst_flow_get_name (sq->srcresult));
3126
3127     if (sq->groupid == groupid)
3128       group_count++;
3129
3130     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3131       /* No need to consider queues which are not waiting */
3132       if (!GST_CLOCK_STIME_IS_VALID (sq->next_time)) {
3133         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3134         continue;
3135       }
3136
3137       if (lowest == GST_CLOCK_STIME_NONE || sq->next_time < lowest)
3138         lowest = sq->next_time;
3139       if (sq->groupid == groupid && (group_low == GST_CLOCK_STIME_NONE
3140               || sq->next_time < group_low))
3141         group_low = sq->next_time;
3142     } else if (!GST_PAD_IS_EOS (sq->srcpad) && sq->srcresult != GST_FLOW_EOS) {
3143       /* If we don't have a global high time, or the global high time
3144        * is lower than this single queue's last outputted time, store
3145        * the queue's one, unless the singlequeue output is at EOS. */
3146       if (highest == GST_CLOCK_STIME_NONE
3147           || (sq->last_time != GST_CLOCK_STIME_NONE && sq->last_time > highest))
3148         highest = sq->last_time;
3149       if (sq->groupid == groupid && (group_high == GST_CLOCK_STIME_NONE
3150               || (sq->last_time != GST_CLOCK_STIME_NONE
3151                   && sq->last_time > group_high)))
3152         group_high = sq->last_time;
3153     }
3154     GST_LOG_OBJECT (mq,
3155         "highest now %" GST_STIME_FORMAT " lowest %" GST_STIME_FORMAT,
3156         GST_STIME_ARGS (highest), GST_STIME_ARGS (lowest));
3157     if (sq->groupid == groupid)
3158       GST_LOG_OBJECT (mq,
3159           "grouphigh %" GST_STIME_FORMAT " grouplow %" GST_STIME_FORMAT,
3160           GST_STIME_ARGS (group_high), GST_STIME_ARGS (group_low));
3161   }
3162
3163   if (highest == GST_CLOCK_STIME_NONE)
3164     mq->high_time = lowest;
3165   else
3166     mq->high_time = highest;
3167
3168   /* If there's only one stream of a given type, use the global high */
3169   if (group_count < 2)
3170     res = GST_CLOCK_STIME_NONE;
3171   else if (group_high == GST_CLOCK_STIME_NONE)
3172     res = group_low;
3173   else
3174     res = group_high;
3175
3176   GST_LOG_OBJECT (mq, "group count %d for groupid %u", group_count, groupid);
3177   GST_LOG_OBJECT (mq,
3178       "MQ High time is now : %" GST_STIME_FORMAT ", group %d high time %"
3179       GST_STIME_FORMAT ", lowest non-linked %" GST_STIME_FORMAT,
3180       GST_STIME_ARGS (mq->high_time), groupid, GST_STIME_ARGS (mq->high_time),
3181       GST_STIME_ARGS (lowest));
3182
3183   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3184     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3185     if (groupid == sq->groupid)
3186       sq->group_high_time = res;
3187   }
3188 }
3189
3190 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
3191      ((q)->max_size.format) <= (value))
3192
3193 #ifdef TIZEN_FEATURE_MQ_MODIFICATION_EXTRA_SIZE_TIME
3194 #define IS_FILLED_EXTRA(q, format, value) ((((q)->extra_size.format) != 0) && (((q)->max_size.format) != 0) && \
3195      (((q)->extra_size.format)+((q)->max_size.format)) <= (value))
3196 #endif
3197 /*
3198  * GstSingleQueue functions
3199  */
3200 static void
3201 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3202 {
3203   GstMultiQueue *mq = sq->mqueue;
3204   GList *tmp;
3205   GstDataQueueSize size;
3206   gboolean filled = TRUE;
3207   gboolean empty_found = FALSE;
3208
3209   gst_data_queue_get_level (sq->queue, &size);
3210
3211   GST_LOG_OBJECT (mq,
3212       "Single Queue %d: EOS %d, visible %u/%u, bytes %u/%u, time %"
3213       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, sq->is_eos, size.visible,
3214       sq->max_size.visible, size.bytes, sq->max_size.bytes, sq->cur_time,
3215       sq->max_size.time);
3216
3217   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3218
3219   /* check if we reached the hard time/bytes limits;
3220      time limit is only taken into account for non-sparse streams */
3221   if (sq->is_eos || IS_FILLED (sq, bytes, size.bytes) ||
3222       (!sq->is_sparse && IS_FILLED (sq, time, sq->cur_time))) {
3223     goto done;
3224   }
3225
3226   /* Search for empty queues */
3227   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3228     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3229
3230     if (oq == sq)
3231       continue;
3232
3233     if (oq->srcresult == GST_FLOW_NOT_LINKED) {
3234       GST_LOG_OBJECT (mq, "Queue %d is not-linked", oq->id);
3235       continue;
3236     }
3237
3238     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
3239     if (gst_data_queue_is_empty (oq->queue) && !oq->is_sparse) {
3240       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
3241       empty_found = TRUE;
3242       break;
3243     }
3244   }
3245
3246   /* if hard limits are not reached then we allow one more buffer in the full
3247    * queue, but only if any of the other singelqueues are empty */
3248   if (empty_found) {
3249     if (IS_FILLED (sq, visible, size.visible)) {
3250       sq->max_size.visible = size.visible + 1;
3251       GST_DEBUG_OBJECT (mq,
3252           "Bumping single queue %d max visible to %d",
3253           sq->id, sq->max_size.visible);
3254       filled = FALSE;
3255     }
3256   }
3257
3258 done:
3259   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3260
3261   /* Overrun is always forwarded, since this is blocking the upstream element */
3262   if (filled) {
3263     GST_DEBUG_OBJECT (mq, "Queue %d is filled, signalling overrun", sq->id);
3264     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
3265   }
3266 }
3267
3268 static void
3269 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3270 {
3271   gboolean empty = TRUE;
3272   GstMultiQueue *mq = sq->mqueue;
3273   GList *tmp;
3274
3275   if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3276     GST_LOG_OBJECT (mq, "Single Queue %d is empty but not-linked", sq->id);
3277     return;
3278   } else {
3279     GST_LOG_OBJECT (mq,
3280         "Single Queue %d is empty, Checking other single queues", sq->id);
3281   }
3282
3283   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3284   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3285     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3286
3287     if (gst_data_queue_is_full (oq->queue)) {
3288       GstDataQueueSize size;
3289
3290       gst_data_queue_get_level (oq->queue, &size);
3291       if (IS_FILLED (oq, visible, size.visible)) {
3292         oq->max_size.visible = size.visible + 1;
3293         GST_DEBUG_OBJECT (mq,
3294             "queue %d is filled, bumping its max visible to %d", oq->id,
3295             oq->max_size.visible);
3296         gst_data_queue_limits_changed (oq->queue);
3297       }
3298     }
3299     if (!gst_data_queue_is_empty (oq->queue) || oq->is_sparse)
3300       empty = FALSE;
3301   }
3302   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3303
3304   if (empty) {
3305     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
3306     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
3307   }
3308 }
3309
3310 static gboolean
3311 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
3312     guint64 time, GstSingleQueue * sq)
3313 {
3314   gboolean res;
3315   GstMultiQueue *mq = sq->mqueue;
3316
3317   GST_DEBUG_OBJECT (mq,
3318       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
3319       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
3320       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
3321
3322   /* we are always filled on EOS */
3323   if (sq->is_eos)
3324     return TRUE;
3325
3326   /* we never go past the max visible items unless we are in buffering mode */
3327   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
3328     return TRUE;
3329
3330   /* check time or bytes */
3331 #ifdef TIZEN_FEATURE_MQ_MODIFICATION_EXTRA_SIZE_TIME
3332   res = IS_FILLED_EXTRA (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
3333 #else
3334   res = IS_FILLED (sq, bytes, bytes);
3335   /* We only care about limits in time if we're not a sparse stream or
3336    * we're not syncing by running time */
3337   if (!sq->is_sparse || !mq->sync_by_running_time) {
3338     /* If unlinked, take into account the extra unlinked cache time */
3339     if (mq->sync_by_running_time && sq->srcresult == GST_FLOW_NOT_LINKED) {
3340       if (sq->cur_time > mq->unlinked_cache_time)
3341         res |= IS_FILLED (sq, time, sq->cur_time - mq->unlinked_cache_time);
3342       else
3343         res = FALSE;
3344     } else
3345       res |= IS_FILLED (sq, time, sq->cur_time);
3346   }
3347
3348 #endif
3349   return res;
3350 }
3351
3352 static void
3353 gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full)
3354 {
3355   GstDataQueueItem *sitem;
3356   GstMultiQueueItem *mitem;
3357   gboolean was_flushing = FALSE;
3358
3359   while (!gst_data_queue_is_empty (sq->queue)) {
3360     GstMiniObject *data;
3361
3362     /* FIXME: If this fails here although the queue is not empty,
3363      * we're flushing... but we want to rescue all sticky
3364      * events nonetheless.
3365      */
3366     if (!gst_data_queue_pop (sq->queue, &sitem)) {
3367       was_flushing = TRUE;
3368       gst_data_queue_set_flushing (sq->queue, FALSE);
3369       continue;
3370     }
3371
3372     mitem = (GstMultiQueueItem *) sitem;
3373
3374     data = sitem->object;
3375
3376     if (!full && !mitem->is_query && GST_IS_EVENT (data)
3377         && GST_EVENT_IS_STICKY (data)
3378         && GST_EVENT_TYPE (data) != GST_EVENT_SEGMENT
3379         && GST_EVENT_TYPE (data) != GST_EVENT_EOS) {
3380       gst_pad_store_sticky_event (sq->srcpad, GST_EVENT_CAST (data));
3381     }
3382
3383     sitem->destroy (sitem);
3384   }
3385
3386   gst_data_queue_flush (sq->queue);
3387   if (was_flushing)
3388     gst_data_queue_set_flushing (sq->queue, TRUE);
3389
3390   GST_MULTI_QUEUE_MUTEX_LOCK (sq->mqueue);
3391   update_buffering (sq->mqueue, sq);
3392   GST_MULTI_QUEUE_MUTEX_UNLOCK (sq->mqueue);
3393   gst_multi_queue_post_buffering (sq->mqueue);
3394 }
3395
3396 static void
3397 gst_single_queue_free (GstSingleQueue * sq)
3398 {
3399   /* DRAIN QUEUE */
3400   gst_data_queue_flush (sq->queue);
3401   g_object_unref (sq->queue);
3402   g_cond_clear (&sq->turn);
3403   g_cond_clear (&sq->query_handled);
3404   g_free (sq);
3405 }
3406
3407 static GstSingleQueue *
3408 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
3409 {
3410   GstSingleQueue *sq;
3411   GstMultiQueuePad *mqpad;
3412   GstPadTemplate *templ;
3413   gchar *name;
3414   GList *tmp;
3415   guint temp_id = (id == -1) ? 0 : id;
3416
3417   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
3418
3419   /* Find an unused queue ID, if possible the passed one */
3420   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
3421     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
3422     /* This works because the IDs are sorted in ascending order */
3423     if (sq2->id == temp_id) {
3424       /* If this ID was requested by the caller return NULL,
3425        * otherwise just get us the next one */
3426       if (id == -1) {
3427         temp_id = sq2->id + 1;
3428       } else {
3429         GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3430         return NULL;
3431       }
3432     } else if (sq2->id > temp_id) {
3433       break;
3434     }
3435   }
3436
3437   sq = g_new0 (GstSingleQueue, 1);
3438   mqueue->nbqueues++;
3439   sq->id = temp_id;
3440   sq->groupid = DEFAULT_PAD_GROUP_ID;
3441   sq->group_high_time = GST_CLOCK_STIME_NONE;
3442
3443   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
3444   mqueue->queues_cookie++;
3445
3446   /* copy over max_size and extra_size so we don't need to take the lock
3447    * any longer when checking if the queue is full. */
3448   sq->max_size.visible = mqueue->max_size.visible;
3449   sq->max_size.bytes = mqueue->max_size.bytes;
3450   sq->max_size.time = mqueue->max_size.time;
3451
3452   sq->extra_size.visible = mqueue->extra_size.visible;
3453   sq->extra_size.bytes = mqueue->extra_size.bytes;
3454   sq->extra_size.time = mqueue->extra_size.time;
3455
3456   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
3457
3458   sq->mqueue = mqueue;
3459   sq->srcresult = GST_FLOW_FLUSHING;
3460   sq->pushed = FALSE;
3461   sq->queue = gst_data_queue_new ((GstDataQueueCheckFullFunction)
3462       single_queue_check_full,
3463       (GstDataQueueFullCallback) single_queue_overrun_cb,
3464       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
3465   sq->is_eos = FALSE;
3466   sq->is_sparse = FALSE;
3467   sq->flushing = FALSE;
3468   sq->active = FALSE;
3469   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
3470   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
3471
3472   sq->nextid = 0;
3473   sq->oldid = 0;
3474   sq->next_time = GST_CLOCK_STIME_NONE;
3475   sq->last_time = GST_CLOCK_STIME_NONE;
3476   g_cond_init (&sq->turn);
3477   g_cond_init (&sq->query_handled);
3478
3479   sq->sinktime = GST_CLOCK_STIME_NONE;
3480   sq->srctime = GST_CLOCK_STIME_NONE;
3481   sq->sink_tainted = TRUE;
3482   sq->src_tainted = TRUE;
3483
3484 #ifdef TIZEN_FEATURE_TRUSTZONE
3485   sq->sq_stream_type = -1;
3486 #endif
3487   name = g_strdup_printf ("sink_%u", sq->id);
3488   templ = gst_static_pad_template_get (&sinktemplate);
3489   sq->sinkpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
3490       "direction", templ->direction, "template", templ, NULL);
3491   gst_object_unref (templ);
3492   g_free (name);
3493
3494   mqpad = (GstMultiQueuePad *) sq->sinkpad;
3495   mqpad->sq = sq;
3496
3497   gst_pad_set_chain_function (sq->sinkpad,
3498       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
3499   gst_pad_set_activatemode_function (sq->sinkpad,
3500       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
3501   gst_pad_set_event_full_function (sq->sinkpad,
3502       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
3503   gst_pad_set_query_function (sq->sinkpad,
3504       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
3505   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
3506       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3507   GST_OBJECT_FLAG_SET (sq->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
3508
3509   name = g_strdup_printf ("src_%u", sq->id);
3510   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
3511   g_free (name);
3512
3513   gst_pad_set_activatemode_function (sq->srcpad,
3514       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
3515   gst_pad_set_event_function (sq->srcpad,
3516       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
3517   gst_pad_set_query_function (sq->srcpad,
3518       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
3519   gst_pad_set_iterate_internal_links_function (sq->srcpad,
3520       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3521   GST_OBJECT_FLAG_SET (sq->srcpad, GST_PAD_FLAG_PROXY_CAPS);
3522
3523   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
3524   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
3525
3526   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3527
3528   /* only activate the pads when we are not in the NULL state
3529    * and add the pad under the state_lock to prevend state changes
3530    * between activating and adding */
3531   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
3532   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3533     gst_pad_set_active (sq->srcpad, TRUE);
3534     gst_pad_set_active (sq->sinkpad, TRUE);
3535   }
3536   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
3537   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
3538   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
3539
3540   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
3541       sq->id);
3542
3543   return sq;
3544 }