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