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