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