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