fed846d01a0c48ebcaaf9f56bc836b8c537854c7
[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 (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         if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
1833           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
1834               (mq->high_time == GST_CLOCK_STIME_NONE
1835               || next_time > mq->high_time);
1836         } else {
1837           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
1838               next_time > sq->group_high_time;
1839         }
1840       } else
1841         should_wait = newid > mq->highid;
1842
1843       while (should_wait && sq->srcresult == GST_FLOW_NOT_LINKED) {
1844
1845         GST_DEBUG_OBJECT (mq,
1846             "queue %d sleeping for not-linked wakeup with "
1847             "newid %u, highid %u, next_time %" GST_STIME_FORMAT
1848             ", high_time %" GST_STIME_FORMAT, sq->id, newid, mq->highid,
1849             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time));
1850
1851         /* Wake up all non-linked pads before we sleep */
1852         wake_up_next_non_linked (mq);
1853
1854         mq->numwaiting++;
1855         g_cond_wait (&sq->turn, &mq->qlock);
1856         mq->numwaiting--;
1857
1858         if (sq->flushing) {
1859           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1860           goto out_flushing;
1861         }
1862
1863         /* Recompute the high time and ID */
1864         compute_high_time (mq, sq->groupid);
1865         compute_high_id (mq);
1866
1867         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1868             "wakeup with newid %u, highid %u, next_time %" GST_STIME_FORMAT
1869             ", high_time %" GST_STIME_FORMAT " mq high_time %" GST_STIME_FORMAT,
1870             sq->id, newid, mq->highid,
1871             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time),
1872             GST_STIME_ARGS (mq->high_time));
1873
1874         if (mq->sync_by_running_time) {
1875           if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
1876             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
1877                 (mq->high_time == GST_CLOCK_STIME_NONE
1878                 || next_time > mq->high_time);
1879           } else {
1880             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
1881                 next_time > sq->group_high_time;
1882           }
1883         } else
1884           should_wait = newid > mq->highid;
1885       }
1886
1887       /* Re-compute the high_id in case someone else pushed */
1888       compute_high_id (mq);
1889       compute_high_time (mq, sq->groupid);
1890     } else {
1891       compute_high_id (mq);
1892       compute_high_time (mq, sq->groupid);
1893       /* Wake up all non-linked pads */
1894       wake_up_next_non_linked (mq);
1895     }
1896     /* We're done waiting, we can clear the nextid and nexttime */
1897     sq->nextid = 0;
1898     sq->next_time = GST_CLOCK_STIME_NONE;
1899   }
1900   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1901
1902   if (sq->flushing)
1903     goto out_flushing;
1904
1905   GST_LOG_OBJECT (mq, "sq:%d BEFORE PUSHING sq->srcresult: %s", sq->id,
1906       gst_flow_get_name (sq->srcresult));
1907
1908   /* Update time stats */
1909   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1910   next_time = get_running_time (&sq->src_segment, object, TRUE);
1911   if (GST_CLOCK_STIME_IS_VALID (next_time)) {
1912     if (sq->last_time == GST_CLOCK_STIME_NONE || sq->last_time < next_time)
1913       sq->last_time = next_time;
1914     if (mq->high_time == GST_CLOCK_STIME_NONE || mq->high_time <= next_time) {
1915       /* Wake up all non-linked pads now that we advanced the high time */
1916       mq->high_time = next_time;
1917       wake_up_next_non_linked (mq);
1918     }
1919   }
1920   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1921
1922   /* Try to push out the new object */
1923   result = gst_single_queue_push_one (mq, sq, object, &dropping);
1924   object = NULL;
1925
1926   /* Check if we pushed something already and if this is
1927    * now a switch from an active to a non-active stream.
1928    *
1929    * If it is, we reset all the waiting streams, let them
1930    * push another buffer to see if they're now active again.
1931    * This allows faster switching between streams and prevents
1932    * deadlocks if downstream does any waiting too.
1933    */
1934   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1935   if (sq->pushed && sq->srcresult == GST_FLOW_OK
1936       && result == GST_FLOW_NOT_LINKED) {
1937     GList *tmp;
1938
1939     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
1940         sq->id);
1941
1942     compute_high_id (mq);
1943     compute_high_time (mq, sq->groupid);
1944     do_update_buffering = TRUE;
1945
1946     /* maybe no-one is waiting */
1947     if (mq->numwaiting > 0) {
1948       /* Else figure out which singlequeue(s) need waking up */
1949       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1950         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1951
1952         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
1953           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
1954           sq2->pushed = FALSE;
1955           sq2->srcresult = GST_FLOW_OK;
1956           g_cond_signal (&sq2->turn);
1957         }
1958       }
1959     }
1960   }
1961
1962   if (is_buffer)
1963     sq->pushed = TRUE;
1964
1965   /* now hold on a bit;
1966    * can not simply throw this result to upstream, because
1967    * that might already be onto another segment, so we have to make
1968    * sure we are relaying the correct info wrt proper segment */
1969   if (result == GST_FLOW_EOS && !dropping &&
1970       sq->srcresult != GST_FLOW_NOT_LINKED) {
1971     GST_DEBUG_OBJECT (mq, "starting EOS drop on sq %d", sq->id);
1972     dropping = TRUE;
1973     /* pretend we have not seen EOS yet for upstream's sake */
1974     result = sq->srcresult;
1975   } else if (dropping && gst_data_queue_is_empty (sq->queue)) {
1976     /* queue empty, so stop dropping
1977      * we can commit the result we have now,
1978      * which is either OK after a segment, or EOS */
1979     GST_DEBUG_OBJECT (mq, "committed EOS drop on sq %d", sq->id);
1980     dropping = FALSE;
1981     result = GST_FLOW_EOS;
1982   }
1983   sq->srcresult = result;
1984   sq->last_oldid = newid;
1985
1986   if (do_update_buffering)
1987     update_buffering (mq, sq);
1988
1989   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1990   gst_multi_queue_post_buffering (mq);
1991
1992   GST_LOG_OBJECT (mq, "sq:%d AFTER PUSHING sq->srcresult: %s (is_eos:%d)",
1993       sq->id, gst_flow_get_name (sq->srcresult), GST_PAD_IS_EOS (sq->srcpad));
1994
1995   /* Need to make sure wake up any sleeping pads when we exit */
1996   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1997   if (mq->numwaiting > 0 && (GST_PAD_IS_EOS (sq->srcpad)
1998           || sq->srcresult == GST_FLOW_EOS)) {
1999     compute_high_time (mq, sq->groupid);
2000     compute_high_id (mq);
2001     wake_up_next_non_linked (mq);
2002   }
2003   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2004
2005   if (dropping)
2006     goto next;
2007
2008   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
2009       && result != GST_FLOW_EOS)
2010     goto out_flushing;
2011
2012   return;
2013
2014 out_flushing:
2015   {
2016     if (object)
2017       gst_mini_object_unref (object);
2018
2019     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2020     sq->last_query = FALSE;
2021     g_cond_signal (&sq->query_handled);
2022
2023     /* Post an error message if we got EOS while downstream
2024      * has returned an error flow return. After EOS there
2025      * will be no further buffer which could propagate the
2026      * error upstream */
2027     if (sq->is_eos && sq->srcresult < GST_FLOW_EOS) {
2028       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2029       GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2030     } else {
2031       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2032     }
2033
2034     /* upstream needs to see fatal result ASAP to shut things down,
2035      * but might be stuck in one of our other full queues;
2036      * so empty this one and trigger dynamic queue growth. At
2037      * this point the srcresult is not OK, NOT_LINKED
2038      * or EOS, i.e. a real failure */
2039     gst_single_queue_flush_queue (sq, FALSE);
2040     single_queue_underrun_cb (sq->queue, sq);
2041     gst_data_queue_set_flushing (sq->queue, TRUE);
2042     gst_pad_pause_task (sq->srcpad);
2043     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
2044         "SingleQueue[%d] task paused, reason:%s",
2045         sq->id, gst_flow_get_name (sq->srcresult));
2046     return;
2047   }
2048 }
2049
2050 /**
2051  * gst_multi_queue_chain:
2052  *
2053  * This is similar to GstQueue's chain function, except:
2054  * _ we don't have leak behaviours,
2055  * _ we push with a unique id (curid)
2056  */
2057 static GstFlowReturn
2058 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2059 {
2060   GstSingleQueue *sq;
2061   GstMultiQueue *mq;
2062   GstMultiQueueItem *item;
2063   guint32 curid;
2064   GstClockTime timestamp, duration;
2065
2066   sq = gst_pad_get_element_private (pad);
2067   mq = sq->mqueue;
2068
2069   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2070   if (sq->is_eos)
2071     goto was_eos;
2072
2073   sq->active = TRUE;
2074
2075   /* Get a unique incrementing id */
2076   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2077
2078   timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2079   duration = GST_BUFFER_DURATION (buffer);
2080
2081   GST_LOG_OBJECT (mq,
2082       "SingleQueue %d : about to enqueue buffer %p with id %d (pts:%"
2083       GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT " dur:%" GST_TIME_FORMAT ")",
2084       sq->id, buffer, curid, GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2085       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), GST_TIME_ARGS (duration));
2086
2087   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
2088
2089   /* Update interleave before pushing data into queue */
2090   if (mq->use_interleave) {
2091     GstClockTime val = timestamp;
2092     GstClockTimeDiff dval;
2093
2094     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2095     if (val == GST_CLOCK_TIME_NONE)
2096       val = sq->sink_segment.position;
2097     if (duration != GST_CLOCK_TIME_NONE)
2098       val += duration;
2099
2100     dval = my_segment_to_running_time (&sq->sink_segment, val);
2101     if (GST_CLOCK_STIME_IS_VALID (dval)) {
2102       sq->cached_sinktime = dval;
2103       GST_DEBUG_OBJECT (mq,
2104           "Queue %d cached sink time now %" G_GINT64_FORMAT " %"
2105           GST_STIME_FORMAT, sq->id, sq->cached_sinktime,
2106           GST_STIME_ARGS (sq->cached_sinktime));
2107       calculate_interleave (mq);
2108     }
2109     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2110   }
2111
2112   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
2113     goto flushing;
2114
2115   /* update time level, we must do this after pushing the data in the queue so
2116    * that we never end up filling the queue first. */
2117   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
2118
2119 done:
2120   return sq->srcresult;
2121
2122   /* ERRORS */
2123 flushing:
2124   {
2125     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2126         sq->id, gst_flow_get_name (sq->srcresult));
2127     gst_multi_queue_item_destroy (item);
2128     goto done;
2129   }
2130 was_eos:
2131   {
2132     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
2133     gst_buffer_unref (buffer);
2134     return GST_FLOW_EOS;
2135   }
2136 }
2137
2138 static gboolean
2139 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
2140     GstPadMode mode, gboolean active)
2141 {
2142   gboolean res;
2143   GstSingleQueue *sq;
2144   GstMultiQueue *mq;
2145
2146   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2147   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
2148
2149   /* mq is NULL if the pad is activated/deactivated before being
2150    * added to the multiqueue */
2151   if (mq)
2152     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2153
2154   switch (mode) {
2155     case GST_PAD_MODE_PUSH:
2156       if (active) {
2157         /* All pads start off linked until they push one buffer */
2158         sq->srcresult = GST_FLOW_OK;
2159         sq->pushed = FALSE;
2160         gst_data_queue_set_flushing (sq->queue, FALSE);
2161       } else {
2162         sq->srcresult = GST_FLOW_FLUSHING;
2163         sq->last_query = FALSE;
2164         g_cond_signal (&sq->query_handled);
2165         gst_data_queue_set_flushing (sq->queue, TRUE);
2166
2167         /* Wait until streaming thread has finished */
2168         if (mq)
2169           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2170         GST_PAD_STREAM_LOCK (pad);
2171         if (mq)
2172           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2173         gst_data_queue_flush (sq->queue);
2174         if (mq)
2175           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2176         GST_PAD_STREAM_UNLOCK (pad);
2177         if (mq)
2178           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2179       }
2180       res = TRUE;
2181       break;
2182     default:
2183       res = FALSE;
2184       break;
2185   }
2186
2187   if (mq) {
2188     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2189     gst_object_unref (mq);
2190   }
2191
2192   return res;
2193 }
2194
2195 static GstFlowReturn
2196 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2197 {
2198   GstSingleQueue *sq;
2199   GstMultiQueue *mq;
2200   guint32 curid;
2201   GstMultiQueueItem *item;
2202   gboolean res = TRUE;
2203   GstFlowReturn flowret = GST_FLOW_OK;
2204   GstEventType type;
2205   GstEvent *sref = NULL;
2206
2207   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2208   mq = (GstMultiQueue *) parent;
2209
2210   type = GST_EVENT_TYPE (event);
2211
2212   switch (type) {
2213     case GST_EVENT_STREAM_START:
2214     {
2215       if (mq->sync_by_running_time) {
2216         GstStreamFlags stream_flags;
2217         gst_event_parse_stream_flags (event, &stream_flags);
2218         if ((stream_flags & GST_STREAM_FLAG_SPARSE)) {
2219           GST_INFO_OBJECT (mq, "SingleQueue %d is a sparse stream", sq->id);
2220           sq->is_sparse = TRUE;
2221         }
2222       }
2223
2224       sq->thread = g_thread_self ();
2225
2226       /* Remove EOS flag */
2227       sq->is_eos = FALSE;
2228       break;
2229     }
2230     case GST_EVENT_FLUSH_START:
2231       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
2232           sq->id);
2233
2234       res = gst_pad_push_event (sq->srcpad, event);
2235
2236       gst_single_queue_flush (mq, sq, TRUE, FALSE);
2237       goto done;
2238
2239     case GST_EVENT_FLUSH_STOP:
2240       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
2241           sq->id);
2242
2243       res = gst_pad_push_event (sq->srcpad, event);
2244
2245       gst_single_queue_flush (mq, sq, FALSE, FALSE);
2246       goto done;
2247
2248     case GST_EVENT_SEGMENT:
2249       sref = gst_event_ref (event);
2250       break;
2251     case GST_EVENT_GAP:
2252       /* take ref because the queue will take ownership and we need the event
2253        * afterwards to update the segment */
2254       sref = gst_event_ref (event);
2255       if (mq->use_interleave) {
2256         GstClockTime val, dur;
2257         GstClockTime stime;
2258         gst_event_parse_gap (event, &val, &dur);
2259         if (GST_CLOCK_TIME_IS_VALID (val)) {
2260           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2261           if (GST_CLOCK_TIME_IS_VALID (dur))
2262             val += dur;
2263           stime = my_segment_to_running_time (&sq->sink_segment, val);
2264           if (GST_CLOCK_STIME_IS_VALID (stime)) {
2265             sq->cached_sinktime = stime;
2266             calculate_interleave (mq);
2267           }
2268           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2269         }
2270       }
2271       break;
2272
2273     default:
2274       if (!(GST_EVENT_IS_SERIALIZED (event))) {
2275         res = gst_pad_push_event (sq->srcpad, event);
2276         goto done;
2277       }
2278       break;
2279   }
2280
2281   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2282   if (sq->is_eos)
2283     goto was_eos;
2284
2285   /* Get an unique incrementing id. */
2286   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2287
2288   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
2289
2290   GST_DEBUG_OBJECT (mq,
2291       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
2292       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
2293
2294   if (!gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))
2295     goto flushing;
2296
2297   /* mark EOS when we received one, we must do that after putting the
2298    * buffer in the queue because EOS marks the buffer as filled. */
2299   switch (type) {
2300     case GST_EVENT_EOS:
2301       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2302       sq->is_eos = TRUE;
2303
2304       /* Post an error message if we got EOS while downstream
2305        * has returned an error flow return. After EOS there
2306        * will be no further buffer which could propagate the
2307        * error upstream */
2308       if (sq->srcresult < GST_FLOW_EOS) {
2309         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2310         GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2311       } else {
2312         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2313       }
2314
2315       /* EOS affects the buffering state */
2316       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2317       update_buffering (mq, sq);
2318       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2319       single_queue_overrun_cb (sq->queue, sq);
2320       gst_multi_queue_post_buffering (mq);
2321       break;
2322     case GST_EVENT_SEGMENT:
2323       apply_segment (mq, sq, sref, &sq->sink_segment);
2324       gst_event_unref (sref);
2325       /* a new segment allows us to accept more buffers if we got EOS
2326        * from downstream */
2327       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2328       if (sq->srcresult == GST_FLOW_EOS)
2329         sq->srcresult = GST_FLOW_OK;
2330       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2331       break;
2332     case GST_EVENT_GAP:
2333       sq->active = TRUE;
2334       apply_gap (mq, sq, sref, &sq->sink_segment);
2335       gst_event_unref (sref);
2336     default:
2337       break;
2338   }
2339
2340 done:
2341   if (res == FALSE)
2342     flowret = GST_FLOW_ERROR;
2343   GST_DEBUG_OBJECT (mq, "SingleQueue %d : returning %s", sq->id,
2344       gst_flow_get_name (flowret));
2345   return flowret;
2346
2347 flushing:
2348   {
2349     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2350         sq->id, gst_flow_get_name (sq->srcresult));
2351     if (sref)
2352       gst_event_unref (sref);
2353     gst_multi_queue_item_destroy (item);
2354     return sq->srcresult;
2355   }
2356 was_eos:
2357   {
2358     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return GST_FLOW_EOS");
2359     gst_event_unref (event);
2360     return GST_FLOW_EOS;
2361   }
2362 }
2363
2364 static gboolean
2365 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
2366 {
2367   gboolean res;
2368   GstSingleQueue *sq;
2369   GstMultiQueue *mq;
2370
2371   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2372   mq = (GstMultiQueue *) parent;
2373
2374   switch (GST_QUERY_TYPE (query)) {
2375     default:
2376       if (GST_QUERY_IS_SERIALIZED (query)) {
2377         guint32 curid;
2378         GstMultiQueueItem *item;
2379
2380         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2381         if (sq->srcresult != GST_FLOW_OK)
2382           goto out_flushing;
2383
2384         /* serialized events go in the queue. We need to be certain that we
2385          * don't cause deadlocks waiting for the query return value. We check if
2386          * the queue is empty (nothing is blocking downstream and the query can
2387          * be pushed for sure) or we are not buffering. If we are buffering,
2388          * the pipeline waits to unblock downstream until our queue fills up
2389          * completely, which can not happen if we block on the query..
2390          * Therefore we only potentially block when we are not buffering. */
2391         if (!mq->use_buffering || gst_data_queue_is_empty (sq->queue)) {
2392           /* Get an unique incrementing id. */
2393           curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2394
2395           item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
2396
2397           GST_DEBUG_OBJECT (mq,
2398               "SingleQueue %d : Enqueuing query %p of type %s with id %d",
2399               sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
2400           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2401           res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
2402           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2403           if (!res || sq->flushing)
2404             goto out_flushing;
2405           /* it might be that the query has been taken out of the queue
2406            * while we were unlocked. So, we need to check if the last
2407            * handled query is the same one than the one we just
2408            * pushed. If it is, we don't need to wait for the condition
2409            * variable, otherwise we wait for the condition variable to
2410            * be signaled. */
2411           while (!sq->flushing && sq->srcresult == GST_FLOW_OK
2412               && sq->last_handled_query != query)
2413             g_cond_wait (&sq->query_handled, &mq->qlock);
2414           res = sq->last_query;
2415           sq->last_handled_query = NULL;
2416         } else {
2417           GST_DEBUG_OBJECT (mq, "refusing query, we are buffering and the "
2418               "queue is not empty");
2419           res = FALSE;
2420         }
2421         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2422       } else {
2423         /* default handling */
2424         res = gst_pad_query_default (pad, parent, query);
2425       }
2426       break;
2427   }
2428   return res;
2429
2430 out_flushing:
2431   {
2432     GST_DEBUG_OBJECT (mq, "Flushing");
2433     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2434     return FALSE;
2435   }
2436 }
2437
2438 static gboolean
2439 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
2440     GstPadMode mode, gboolean active)
2441 {
2442   GstMultiQueue *mq;
2443   GstSingleQueue *sq;
2444   gboolean result;
2445
2446   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
2447   mq = sq->mqueue;
2448
2449   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
2450
2451   switch (mode) {
2452     case GST_PAD_MODE_PUSH:
2453       if (active) {
2454         result = gst_single_queue_flush (mq, sq, FALSE, TRUE);
2455       } else {
2456         result = gst_single_queue_flush (mq, sq, TRUE, TRUE);
2457         /* make sure streaming finishes */
2458         result |= gst_pad_stop_task (pad);
2459       }
2460       break;
2461     default:
2462       result = FALSE;
2463       break;
2464   }
2465   return result;
2466 }
2467
2468 static gboolean
2469 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2470 {
2471   GstSingleQueue *sq = gst_pad_get_element_private (pad);
2472   GstMultiQueue *mq = sq->mqueue;
2473   gboolean ret;
2474
2475   switch (GST_EVENT_TYPE (event)) {
2476     case GST_EVENT_RECONFIGURE:
2477       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2478       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2479         sq->srcresult = GST_FLOW_OK;
2480         g_cond_signal (&sq->turn);
2481       }
2482       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2483
2484       ret = gst_pad_push_event (sq->sinkpad, event);
2485       break;
2486     default:
2487       ret = gst_pad_push_event (sq->sinkpad, event);
2488       break;
2489   }
2490
2491   return ret;
2492 }
2493
2494 static gboolean
2495 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2496 {
2497   gboolean res;
2498
2499   /* FIXME, Handle position offset depending on queue size */
2500   switch (GST_QUERY_TYPE (query)) {
2501     default:
2502       /* default handling */
2503       res = gst_pad_query_default (pad, parent, query);
2504       break;
2505   }
2506   return res;
2507 }
2508
2509 /*
2510  * Next-non-linked functions
2511  */
2512
2513 /* WITH LOCK TAKEN */
2514 static void
2515 wake_up_next_non_linked (GstMultiQueue * mq)
2516 {
2517   GList *tmp;
2518
2519   /* maybe no-one is waiting */
2520   if (mq->numwaiting < 1)
2521     return;
2522
2523   if (mq->sync_by_running_time && GST_CLOCK_STIME_IS_VALID (mq->high_time)) {
2524     /* Else figure out which singlequeue(s) need waking up */
2525     for (tmp = mq->queues; tmp; tmp = tmp->next) {
2526       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2527       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2528         GstClockTimeDiff high_time;
2529
2530         if (GST_CLOCK_STIME_IS_VALID (sq->group_high_time))
2531           high_time = sq->group_high_time;
2532         else
2533           high_time = mq->high_time;
2534
2535         if (GST_CLOCK_STIME_IS_VALID (sq->next_time) &&
2536             GST_CLOCK_STIME_IS_VALID (high_time)
2537             && sq->next_time <= high_time) {
2538           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
2539           g_cond_signal (&sq->turn);
2540         }
2541       }
2542     }
2543   } else {
2544     /* Else figure out which singlequeue(s) need waking up */
2545     for (tmp = mq->queues; tmp; tmp = tmp->next) {
2546       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2547       if (sq->srcresult == GST_FLOW_NOT_LINKED &&
2548           sq->nextid != 0 && sq->nextid <= mq->highid) {
2549         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
2550         g_cond_signal (&sq->turn);
2551       }
2552     }
2553   }
2554 }
2555
2556 /* WITH LOCK TAKEN */
2557 static void
2558 compute_high_id (GstMultiQueue * mq)
2559 {
2560   /* The high-id is either the highest id among the linked pads, or if all
2561    * pads are not-linked, it's the lowest not-linked pad */
2562   GList *tmp;
2563   guint32 lowest = G_MAXUINT32;
2564   guint32 highid = G_MAXUINT32;
2565
2566   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2567     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2568
2569     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
2570         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
2571
2572     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2573       /* No need to consider queues which are not waiting */
2574       if (sq->nextid == 0) {
2575         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
2576         continue;
2577       }
2578
2579       if (sq->nextid < lowest)
2580         lowest = sq->nextid;
2581     } else if (!GST_PAD_IS_EOS (sq->srcpad) && sq->srcresult != GST_FLOW_EOS) {
2582       /* If we don't have a global highid, or the global highid is lower than
2583        * this single queue's last outputted id, store the queue's one, 
2584        * unless the singlequeue output is at EOS */
2585       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
2586         highid = sq->oldid;
2587     }
2588   }
2589
2590   if (highid == G_MAXUINT32 || lowest < highid)
2591     mq->highid = lowest;
2592   else
2593     mq->highid = highid;
2594
2595   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
2596       lowest);
2597 }
2598
2599 /* WITH LOCK TAKEN */
2600 static void
2601 compute_high_time (GstMultiQueue * mq, guint groupid)
2602 {
2603   /* The high-time is either the highest last time among the linked
2604    * pads, or if all pads are not-linked, it's the lowest nex time of
2605    * not-linked pad */
2606   GList *tmp;
2607   GstClockTimeDiff highest = GST_CLOCK_STIME_NONE;
2608   GstClockTimeDiff lowest = GST_CLOCK_STIME_NONE;
2609   GstClockTimeDiff group_high = GST_CLOCK_STIME_NONE;
2610   GstClockTimeDiff group_low = GST_CLOCK_STIME_NONE;
2611   GstClockTimeDiff res;
2612   /* Number of streams which belong to groupid */
2613   guint group_count = 0;
2614
2615   if (!mq->sync_by_running_time)
2616     /* return GST_CLOCK_STIME_NONE; */
2617     return;
2618
2619   for (tmp = mq->queues; tmp; tmp = tmp->next) {
2620     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2621
2622     GST_LOG_OBJECT (mq,
2623         "inspecting sq:%d (group:%d) , next_time:%" GST_STIME_FORMAT
2624         ", last_time:%" GST_STIME_FORMAT ", srcresult:%s", sq->id, sq->groupid,
2625         GST_STIME_ARGS (sq->next_time), GST_STIME_ARGS (sq->last_time),
2626         gst_flow_get_name (sq->srcresult));
2627
2628     if (sq->groupid == groupid)
2629       group_count++;
2630
2631     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2632       /* No need to consider queues which are not waiting */
2633       if (!GST_CLOCK_STIME_IS_VALID (sq->next_time)) {
2634         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
2635         continue;
2636       }
2637
2638       if (lowest == GST_CLOCK_STIME_NONE || sq->next_time < lowest)
2639         lowest = sq->next_time;
2640       if (sq->groupid == groupid && (group_low == GST_CLOCK_STIME_NONE
2641               || sq->next_time < group_low))
2642         group_low = sq->next_time;
2643     } else if (!GST_PAD_IS_EOS (sq->srcpad) && sq->srcresult != GST_FLOW_EOS) {
2644       /* If we don't have a global high time, or the global high time
2645        * is lower than this single queue's last outputted time, store
2646        * the queue's one, unless the singlequeue output is at EOS. */
2647       if (highest == GST_CLOCK_STIME_NONE
2648           || (sq->last_time != GST_CLOCK_STIME_NONE && sq->last_time > highest))
2649         highest = sq->last_time;
2650       if (sq->groupid == groupid && (group_high == GST_CLOCK_STIME_NONE
2651               || (sq->last_time != GST_CLOCK_STIME_NONE
2652                   && sq->last_time > group_high)))
2653         group_high = sq->last_time;
2654     }
2655     GST_LOG_OBJECT (mq,
2656         "highest now %" GST_STIME_FORMAT " lowest %" GST_STIME_FORMAT,
2657         GST_STIME_ARGS (highest), GST_STIME_ARGS (lowest));
2658     if (sq->groupid == groupid)
2659       GST_LOG_OBJECT (mq,
2660           "grouphigh %" GST_STIME_FORMAT " grouplow %" GST_STIME_FORMAT,
2661           GST_STIME_ARGS (group_high), GST_STIME_ARGS (group_low));
2662   }
2663
2664   if (highest == GST_CLOCK_STIME_NONE)
2665     mq->high_time = lowest;
2666   else
2667     mq->high_time = highest;
2668
2669   /* If there's only one stream of a given type, use the global high */
2670   if (group_count < 2)
2671     res = GST_CLOCK_STIME_NONE;
2672   else if (group_high == GST_CLOCK_STIME_NONE)
2673     res = group_low;
2674   else
2675     res = group_high;
2676
2677   GST_LOG_OBJECT (mq, "group count %d for groupid %u", group_count, groupid);
2678   GST_LOG_OBJECT (mq,
2679       "MQ High time is now : %" GST_STIME_FORMAT ", group %d high time %"
2680       GST_STIME_FORMAT ", lowest non-linked %" GST_STIME_FORMAT,
2681       GST_STIME_ARGS (mq->high_time), groupid, GST_STIME_ARGS (mq->high_time),
2682       GST_STIME_ARGS (lowest));
2683
2684   for (tmp = mq->queues; tmp; tmp = tmp->next) {
2685     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2686     if (groupid == sq->groupid)
2687       sq->group_high_time = res;
2688   }
2689 }
2690
2691 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
2692      ((q)->max_size.format) <= (value))
2693
2694 /*
2695  * GstSingleQueue functions
2696  */
2697 static void
2698 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
2699 {
2700   GstMultiQueue *mq = sq->mqueue;
2701   GList *tmp;
2702   GstDataQueueSize size;
2703   gboolean filled = TRUE;
2704   gboolean empty_found = FALSE;
2705
2706   gst_data_queue_get_level (sq->queue, &size);
2707
2708   GST_LOG_OBJECT (mq,
2709       "Single Queue %d: EOS %d, visible %u/%u, bytes %u/%u, time %"
2710       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, sq->is_eos, size.visible,
2711       sq->max_size.visible, size.bytes, sq->max_size.bytes, sq->cur_time,
2712       sq->max_size.time);
2713
2714   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2715
2716   /* check if we reached the hard time/bytes limits;
2717      time limit is only taken into account for non-sparse streams */
2718   if (sq->is_eos || IS_FILLED (sq, bytes, size.bytes) ||
2719       (!sq->is_sparse && IS_FILLED (sq, time, sq->cur_time))) {
2720     goto done;
2721   }
2722
2723   /* Search for empty queues */
2724   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2725     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
2726
2727     if (oq == sq)
2728       continue;
2729
2730     if (oq->srcresult == GST_FLOW_NOT_LINKED) {
2731       GST_LOG_OBJECT (mq, "Queue %d is not-linked", oq->id);
2732       continue;
2733     }
2734
2735     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
2736     if (gst_data_queue_is_empty (oq->queue) && !oq->is_sparse) {
2737       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
2738       empty_found = TRUE;
2739       break;
2740     }
2741   }
2742
2743   /* if hard limits are not reached then we allow one more buffer in the full
2744    * queue, but only if any of the other singelqueues are empty */
2745   if (empty_found) {
2746     if (IS_FILLED (sq, visible, size.visible)) {
2747       sq->max_size.visible = size.visible + 1;
2748       GST_DEBUG_OBJECT (mq,
2749           "Bumping single queue %d max visible to %d",
2750           sq->id, sq->max_size.visible);
2751       filled = FALSE;
2752     }
2753   }
2754
2755 done:
2756   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2757
2758   /* Overrun is always forwarded, since this is blocking the upstream element */
2759   if (filled) {
2760     GST_DEBUG_OBJECT (mq, "Queue %d is filled, signalling overrun", sq->id);
2761     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
2762   }
2763 }
2764
2765 static void
2766 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
2767 {
2768   gboolean empty = TRUE;
2769   GstMultiQueue *mq = sq->mqueue;
2770   GList *tmp;
2771
2772   if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2773     GST_LOG_OBJECT (mq, "Single Queue %d is empty but not-linked", sq->id);
2774     return;
2775   } else {
2776     GST_LOG_OBJECT (mq,
2777         "Single Queue %d is empty, Checking other single queues", sq->id);
2778   }
2779
2780   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2781   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2782     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
2783
2784     if (gst_data_queue_is_full (oq->queue)) {
2785       GstDataQueueSize size;
2786
2787       gst_data_queue_get_level (oq->queue, &size);
2788       if (IS_FILLED (oq, visible, size.visible)) {
2789         oq->max_size.visible = size.visible + 1;
2790         GST_DEBUG_OBJECT (mq,
2791             "queue %d is filled, bumping its max visible to %d", oq->id,
2792             oq->max_size.visible);
2793         gst_data_queue_limits_changed (oq->queue);
2794       }
2795     }
2796     if (!gst_data_queue_is_empty (oq->queue) || oq->is_sparse)
2797       empty = FALSE;
2798   }
2799   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2800
2801   if (empty) {
2802     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
2803     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
2804   }
2805 }
2806
2807 static gboolean
2808 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
2809     guint64 time, GstSingleQueue * sq)
2810 {
2811   gboolean res;
2812   GstMultiQueue *mq = sq->mqueue;
2813
2814   GST_DEBUG_OBJECT (mq,
2815       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
2816       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
2817       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
2818
2819   /* we are always filled on EOS */
2820   if (sq->is_eos)
2821     return TRUE;
2822
2823   /* we never go past the max visible items unless we are in buffering mode */
2824   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
2825     return TRUE;
2826
2827   /* check time or bytes */
2828   res = IS_FILLED (sq, bytes, bytes);
2829   /* We only care about limits in time if we're not a sparse stream or
2830    * we're not syncing by running time */
2831   if (!sq->is_sparse || !mq->sync_by_running_time) {
2832     /* If unlinked, take into account the extra unlinked cache time */
2833     if (mq->sync_by_running_time && sq->srcresult == GST_FLOW_NOT_LINKED) {
2834       if (sq->cur_time > mq->unlinked_cache_time)
2835         res |= IS_FILLED (sq, time, sq->cur_time - mq->unlinked_cache_time);
2836       else
2837         res = FALSE;
2838     } else
2839       res |= IS_FILLED (sq, time, sq->cur_time);
2840   }
2841
2842   return res;
2843 }
2844
2845 static void
2846 gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full)
2847 {
2848   GstDataQueueItem *sitem;
2849   GstMultiQueueItem *mitem;
2850   gboolean was_flushing = FALSE;
2851
2852   while (!gst_data_queue_is_empty (sq->queue)) {
2853     GstMiniObject *data;
2854
2855     /* FIXME: If this fails here although the queue is not empty,
2856      * we're flushing... but we want to rescue all sticky
2857      * events nonetheless.
2858      */
2859     if (!gst_data_queue_pop (sq->queue, &sitem)) {
2860       was_flushing = TRUE;
2861       gst_data_queue_set_flushing (sq->queue, FALSE);
2862       continue;
2863     }
2864
2865     mitem = (GstMultiQueueItem *) sitem;
2866
2867     data = sitem->object;
2868
2869     if (!full && !mitem->is_query && GST_IS_EVENT (data)
2870         && GST_EVENT_IS_STICKY (data)
2871         && GST_EVENT_TYPE (data) != GST_EVENT_SEGMENT
2872         && GST_EVENT_TYPE (data) != GST_EVENT_EOS) {
2873       gst_pad_store_sticky_event (sq->srcpad, GST_EVENT_CAST (data));
2874     }
2875
2876     sitem->destroy (sitem);
2877   }
2878
2879   gst_data_queue_flush (sq->queue);
2880   if (was_flushing)
2881     gst_data_queue_set_flushing (sq->queue, TRUE);
2882
2883   GST_MULTI_QUEUE_MUTEX_LOCK (sq->mqueue);
2884   update_buffering (sq->mqueue, sq);
2885   GST_MULTI_QUEUE_MUTEX_UNLOCK (sq->mqueue);
2886   gst_multi_queue_post_buffering (sq->mqueue);
2887 }
2888
2889 static void
2890 gst_single_queue_free (GstSingleQueue * sq)
2891 {
2892   /* DRAIN QUEUE */
2893   gst_data_queue_flush (sq->queue);
2894   g_object_unref (sq->queue);
2895   g_cond_clear (&sq->turn);
2896   g_cond_clear (&sq->query_handled);
2897   g_free (sq);
2898 }
2899
2900 static GstSingleQueue *
2901 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
2902 {
2903   GstSingleQueue *sq;
2904   GstMultiQueuePad *mqpad;
2905   GstPadTemplate *templ;
2906   gchar *name;
2907   GList *tmp;
2908   guint temp_id = (id == -1) ? 0 : id;
2909
2910   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
2911
2912   /* Find an unused queue ID, if possible the passed one */
2913   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
2914     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
2915     /* This works because the IDs are sorted in ascending order */
2916     if (sq2->id == temp_id) {
2917       /* If this ID was requested by the caller return NULL,
2918        * otherwise just get us the next one */
2919       if (id == -1) {
2920         temp_id = sq2->id + 1;
2921       } else {
2922         GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
2923         return NULL;
2924       }
2925     } else if (sq2->id > temp_id) {
2926       break;
2927     }
2928   }
2929
2930   sq = g_new0 (GstSingleQueue, 1);
2931   mqueue->nbqueues++;
2932   sq->id = temp_id;
2933   sq->groupid = DEFAULT_PAD_GROUP_ID;
2934   sq->group_high_time = GST_CLOCK_STIME_NONE;
2935
2936   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
2937   mqueue->queues_cookie++;
2938
2939   /* copy over max_size and extra_size so we don't need to take the lock
2940    * any longer when checking if the queue is full. */
2941   sq->max_size.visible = mqueue->max_size.visible;
2942   sq->max_size.bytes = mqueue->max_size.bytes;
2943   sq->max_size.time = mqueue->max_size.time;
2944
2945   sq->extra_size.visible = mqueue->extra_size.visible;
2946   sq->extra_size.bytes = mqueue->extra_size.bytes;
2947   sq->extra_size.time = mqueue->extra_size.time;
2948
2949   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
2950
2951   sq->mqueue = mqueue;
2952   sq->srcresult = GST_FLOW_FLUSHING;
2953   sq->pushed = FALSE;
2954   sq->queue = gst_data_queue_new ((GstDataQueueCheckFullFunction)
2955       single_queue_check_full,
2956       (GstDataQueueFullCallback) single_queue_overrun_cb,
2957       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
2958   sq->is_eos = FALSE;
2959   sq->is_sparse = FALSE;
2960   sq->flushing = FALSE;
2961   sq->active = FALSE;
2962   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
2963   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
2964
2965   sq->nextid = 0;
2966   sq->oldid = 0;
2967   sq->next_time = GST_CLOCK_STIME_NONE;
2968   sq->last_time = GST_CLOCK_STIME_NONE;
2969   g_cond_init (&sq->turn);
2970   g_cond_init (&sq->query_handled);
2971
2972   sq->sinktime = GST_CLOCK_STIME_NONE;
2973   sq->srctime = GST_CLOCK_STIME_NONE;
2974   sq->sink_tainted = TRUE;
2975   sq->src_tainted = TRUE;
2976
2977   name = g_strdup_printf ("sink_%u", sq->id);
2978   templ = gst_static_pad_template_get (&sinktemplate);
2979   sq->sinkpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
2980       "direction", templ->direction, "template", templ, NULL);
2981   gst_object_unref (templ);
2982   g_free (name);
2983
2984   mqpad = (GstMultiQueuePad *) sq->sinkpad;
2985   mqpad->sq = sq;
2986
2987   gst_pad_set_chain_function (sq->sinkpad,
2988       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
2989   gst_pad_set_activatemode_function (sq->sinkpad,
2990       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
2991   gst_pad_set_event_full_function (sq->sinkpad,
2992       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
2993   gst_pad_set_query_function (sq->sinkpad,
2994       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
2995   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
2996       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2997   GST_OBJECT_FLAG_SET (sq->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
2998
2999   name = g_strdup_printf ("src_%u", sq->id);
3000   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
3001   g_free (name);
3002
3003   gst_pad_set_activatemode_function (sq->srcpad,
3004       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
3005   gst_pad_set_event_function (sq->srcpad,
3006       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
3007   gst_pad_set_query_function (sq->srcpad,
3008       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
3009   gst_pad_set_iterate_internal_links_function (sq->srcpad,
3010       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3011   GST_OBJECT_FLAG_SET (sq->srcpad, GST_PAD_FLAG_PROXY_CAPS);
3012
3013   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
3014   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
3015
3016   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3017
3018   /* only activate the pads when we are not in the NULL state
3019    * and add the pad under the state_lock to prevend state changes
3020    * between activating and adding */
3021   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
3022   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3023     gst_pad_set_active (sq->srcpad, TRUE);
3024     gst_pad_set_active (sq->sinkpad, TRUE);
3025   }
3026   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
3027   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
3028   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
3029
3030   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
3031       sq->id);
3032
3033   return sq;
3034 }