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