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