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