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