Merge remote-tracking branch 'origin/0.10'
[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., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /**
26  * SECTION:element-multiqueue
27  * @see_also: #GstQueue
28  *
29  * <refsect2>
30  * <para>
31  * Multiqueue is similar to a normal #GstQueue with the following additional
32  * features:
33  * <orderedlist>
34  * <listitem>
35  *   <itemizedlist><title>Multiple streamhandling</title>
36  *   <listitem><para>
37  *     The element handles queueing data on more than one stream at once. To
38  *     achieve such a feature it has request sink pads (sink&percnt;d) and
39  *     'sometimes' src pads (src&percnt;d).
40  *   </para><para>
41  *     When requesting a given sinkpad with gst_element_get_request_pad(),
42  *     the associated srcpad for that stream will be created.
43  *     Example: requesting sink1 will generate src1.
44  *   </para></listitem>
45  *   </itemizedlist>
46  * </listitem>
47  * <listitem>
48  *   <itemizedlist><title>Non-starvation on multiple streams</title>
49  *   <listitem><para>
50  *     If more than one stream is used with the element, the streams' queues
51  *     will be dynamically grown (up to a limit), in order to ensure that no
52  *     stream is risking data starvation. This guarantees that at any given
53  *     time there are at least N bytes queued and available for each individual
54  *     stream.
55  *   </para><para>
56  *     If an EOS event comes through a srcpad, the associated queue will be
57  *     considered as 'not-empty' in the queue-size-growing algorithm.
58  *   </para></listitem>
59  *   </itemizedlist>
60  * </listitem>
61  * <listitem>
62  *   <itemizedlist><title>Non-linked srcpads graceful handling</title>
63  *   <listitem><para>
64  *     In order to better support dynamic switching between streams, the multiqueue
65  *     (unlike the current GStreamer queue) continues to push buffers on non-linked
66  *     pads rather than shutting down.
67  *   </para><para>
68  *     In addition, to prevent a non-linked stream from very quickly consuming all
69  *     available buffers and thus 'racing ahead' of the other streams, the element
70  *     must ensure that buffers and inlined events for a non-linked stream are pushed
71  *     in the same order as they were received, relative to the other streams
72  *     controlled by the element. This means that a buffer cannot be pushed to a
73  *     non-linked pad any sooner than buffers in any other stream which were received
74  *     before it.
75  *   </para></listitem>
76  *   </itemizedlist>
77  * </listitem>
78  * </orderedlist>
79  * </para>
80  * <para>
81  *   Data is queued until one of the limits specified by the
82  *   #GstMultiQueue:max-size-buffers, #GstMultiQueue:max-size-bytes and/or
83  *   #GstMultiQueue:max-size-time properties has been reached. Any attempt to push
84  *   more buffers into the queue will block the pushing thread until more space
85  *   becomes available. #GstMultiQueue:extra-size-buffers,
86  * </para>
87  * <para>
88  *   #GstMultiQueue:extra-size-bytes and #GstMultiQueue:extra-size-time are
89  *   currently unused.
90  * </para>
91  * <para>
92  *   The default queue size limits are 5 buffers, 10MB of data, or
93  *   two second worth of data, whichever is reached first. Note that the number
94  *   of buffers will dynamically grow depending on the fill level of 
95  *   other queues.
96  * </para>
97  * <para>
98  *   The #GstMultiQueue::underrun signal is emitted when all of the queues
99  *   are empty. The #GstMultiQueue::overrun signal is emitted when one of the
100  *   queues is filled.
101  *   Both signals are emitted from the context of the streaming thread.
102  * </para>
103  * </refsect2>
104  *
105  * Last reviewed on 2008-01-25 (0.10.17)
106  */
107
108 #ifdef HAVE_CONFIG_H
109 #  include "config.h"
110 #endif
111
112 #include <gst/gst.h>
113 #include <stdio.h>
114 #include "gstmultiqueue.h"
115 #include <gst/glib-compat-private.h>
116
117 /**
118  * GstSingleQueue:
119  * @sinkpad: associated sink #GstPad
120  * @srcpad: associated source #GstPad
121  *
122  * Structure containing all information and properties about
123  * a single queue.
124  */
125 typedef struct _GstSingleQueue GstSingleQueue;
126
127 struct _GstSingleQueue
128 {
129   /* unique identifier of the queue */
130   guint id;
131
132   GstMultiQueue *mqueue;
133
134   GstPad *sinkpad;
135   GstPad *srcpad;
136
137   /* flowreturn of previous srcpad push */
138   GstFlowReturn srcresult;
139   /* If something was actually pushed on
140    * this pad after flushing/pad activation
141    * and the srcresult corresponds to something
142    * real
143    */
144   gboolean pushed;
145
146   /* segments */
147   GstSegment sink_segment;
148   GstSegment src_segment;
149
150   /* position of src/sink */
151   GstClockTime sinktime, srctime;
152   /* TRUE if either position needs to be recalculated */
153   gboolean sink_tainted, src_tainted;
154
155   /* queue of data */
156   GstDataQueue *queue;
157   GstDataQueueSize max_size, extra_size;
158   GstClockTime cur_time;
159   gboolean is_eos;
160   gboolean flushing;
161
162   /* Protected by global lock */
163   guint32 nextid;               /* ID of the next object waiting to be pushed */
164   guint32 oldid;                /* ID of the last object pushed (last in a series) */
165   guint32 last_oldid;           /* Previously observed old_id, reset to MAXUINT32 on flush */
166   GstClockTime next_time;       /* End running time of next buffer to be pushed */
167   GstClockTime last_time;       /* Start running time of last pushed buffer */
168   GCond turn;                   /* SingleQueue turn waiting conditional */
169
170   /* for serialized queries */
171   GCond query_handled;
172   gboolean last_query;
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
190 static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue, guint id);
191 static void gst_single_queue_free (GstSingleQueue * squeue);
192
193 static void wake_up_next_non_linked (GstMultiQueue * mq);
194 static void compute_high_id (GstMultiQueue * mq);
195 static void compute_high_time (GstMultiQueue * mq);
196 static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
197 static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
198
199 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink_%u",
200     GST_PAD_SINK,
201     GST_PAD_REQUEST,
202     GST_STATIC_CAPS_ANY);
203
204 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
205     GST_PAD_SRC,
206     GST_PAD_SOMETIMES,
207     GST_STATIC_CAPS_ANY);
208
209 GST_DEBUG_CATEGORY_STATIC (multi_queue_debug);
210 #define GST_CAT_DEFAULT (multi_queue_debug)
211
212 /* Signals and args */
213 enum
214 {
215   SIGNAL_UNDERRUN,
216   SIGNAL_OVERRUN,
217   LAST_SIGNAL
218 };
219
220 /* default limits, we try to keep up to 2 seconds of data and if there is not
221  * time, up to 10 MB. The number of buffers is dynamically scaled to make sure
222  * there is data in the queues. Normally, the byte and time limits are not hit
223  * in theses conditions. */
224 #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */
225 #define DEFAULT_MAX_SIZE_BUFFERS 5
226 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND
227
228 /* second limits. When we hit one of the above limits we are probably dealing
229  * with a badly muxed file and we scale the limits to these emergency values.
230  * This is currently not yet implemented.
231  * Since we dynamically scale the queue buffer size up to the limits but avoid
232  * going above the max-size-buffers when we can, we don't really need this
233  * aditional extra size. */
234 #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024       /* 10 MB */
235 #define DEFAULT_EXTRA_SIZE_BUFFERS 5
236 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND
237
238 #define DEFAULT_USE_BUFFERING FALSE
239 #define DEFAULT_LOW_PERCENT   10
240 #define DEFAULT_HIGH_PERCENT  99
241 #define DEFAULT_SYNC_BY_RUNNING_TIME FALSE
242
243 enum
244 {
245   PROP_0,
246   PROP_EXTRA_SIZE_BYTES,
247   PROP_EXTRA_SIZE_BUFFERS,
248   PROP_EXTRA_SIZE_TIME,
249   PROP_MAX_SIZE_BYTES,
250   PROP_MAX_SIZE_BUFFERS,
251   PROP_MAX_SIZE_TIME,
252   PROP_USE_BUFFERING,
253   PROP_LOW_PERCENT,
254   PROP_HIGH_PERCENT,
255   PROP_SYNC_BY_RUNNING_TIME,
256   PROP_LAST
257 };
258
259 #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
260   g_mutex_lock (&q->qlock);                                              \
261 } G_STMT_END
262
263 #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
264   g_mutex_unlock (&q->qlock);                                            \
265 } G_STMT_END
266
267 static void gst_multi_queue_finalize (GObject * object);
268 static void gst_multi_queue_set_property (GObject * object,
269     guint prop_id, const GValue * value, GParamSpec * pspec);
270 static void gst_multi_queue_get_property (GObject * object,
271     guint prop_id, GValue * value, GParamSpec * pspec);
272
273 static GstPad *gst_multi_queue_request_new_pad (GstElement * element,
274     GstPadTemplate * temp, const gchar * name, const GstCaps * caps);
275 static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad);
276 static GstStateChangeReturn gst_multi_queue_change_state (GstElement *
277     element, GstStateChange transition);
278
279 static void gst_multi_queue_loop (GstPad * pad);
280
281 #define _do_init \
282   GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element");
283 #define gst_multi_queue_parent_class parent_class
284 G_DEFINE_TYPE_WITH_CODE (GstMultiQueue, gst_multi_queue, GST_TYPE_ELEMENT,
285     _do_init);
286
287 static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 };
288
289 static void
290 gst_multi_queue_class_init (GstMultiQueueClass * klass)
291 {
292   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
293   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
294
295   gobject_class->set_property = gst_multi_queue_set_property;
296   gobject_class->get_property = gst_multi_queue_get_property;
297
298   /* SIGNALS */
299
300   /**
301    * GstMultiQueue::underrun:
302    * @multiqueue: the multqueue instance
303    *
304    * This signal is emitted from the streaming thread when there is
305    * no data in any of the queues inside the multiqueue instance (underrun).
306    *
307    * This indicates either starvation or EOS from the upstream data sources.
308    */
309   gst_multi_queue_signals[SIGNAL_UNDERRUN] =
310       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
311       G_STRUCT_OFFSET (GstMultiQueueClass, underrun), NULL, NULL,
312       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
313
314   /**
315    * GstMultiQueue::overrun:
316    * @multiqueue: the multiqueue instance
317    *
318    * Reports that one of the queues in the multiqueue is full (overrun).
319    * A queue is full if the total amount of data inside it (num-buffers, time,
320    * size) is higher than the boundary values which can be set through the
321    * GObject properties.
322    *
323    * This can be used as an indicator of pre-roll. 
324    */
325   gst_multi_queue_signals[SIGNAL_OVERRUN] =
326       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
327       G_STRUCT_OFFSET (GstMultiQueueClass, overrun), NULL, NULL,
328       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
329
330   /* PROPERTIES */
331
332   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
333       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
334           "Max. amount of data in the queue (bytes, 0=disable)",
335           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
336           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
337   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
338       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
339           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
340           DEFAULT_MAX_SIZE_BUFFERS,
341           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
342   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
343       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
344           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
345           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346
347   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BYTES,
348       g_param_spec_uint ("extra-size-bytes", "Extra Size (kB)",
349           "Amount of data the queues can grow if one of them is empty (bytes, 0=disable)"
350           " (NOT IMPLEMENTED)",
351           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BYTES,
352           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
353   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BUFFERS,
354       g_param_spec_uint ("extra-size-buffers", "Extra Size (buffers)",
355           "Amount of buffers the queues can grow if one of them is empty (0=disable)"
356           " (NOT IMPLEMENTED)",
357           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BUFFERS,
358           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
359   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_TIME,
360       g_param_spec_uint64 ("extra-size-time", "Extra Size (ns)",
361           "Amount of time the queues can grow if one of them is empty (in ns, 0=disable)"
362           " (NOT IMPLEMENTED)",
363           0, G_MAXUINT64, DEFAULT_EXTRA_SIZE_TIME,
364           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
365
366   /**
367    * GstMultiQueue:use-buffering
368    * 
369    * Enable the buffering option in multiqueue so that BUFFERING messages are
370    * emited based on low-/high-percent thresholds.
371    *
372    * Since: 0.10.26
373    */
374   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
375       g_param_spec_boolean ("use-buffering", "Use buffering",
376           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
377           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
378   /**
379    * GstMultiQueue:low-percent
380    * 
381    * Low threshold percent for buffering to start.
382    *
383    * Since: 0.10.26
384    */
385   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
386       g_param_spec_int ("low-percent", "Low percent",
387           "Low threshold for buffering to start", 0, 100,
388           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
389   /**
390    * GstMultiQueue:high-percent
391    * 
392    * High threshold percent for buffering to finish.
393    *
394    * Since: 0.10.26
395    */
396   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
397       g_param_spec_int ("high-percent", "High percent",
398           "High threshold for buffering to finish", 0, 100,
399           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
400
401   /**
402    * GstMultiQueue:sync-by-running-time
403    * 
404    * If enabled multiqueue will synchronize deactivated or not-linked streams
405    * to the activated and linked streams by taking the running time.
406    * Otherwise multiqueue will synchronize the deactivated or not-linked
407    * streams by keeping the order in which buffers and events arrived compared
408    * to active and linked streams.
409    *
410    * Since: 0.10.36
411    */
412   g_object_class_install_property (gobject_class, PROP_SYNC_BY_RUNNING_TIME,
413       g_param_spec_boolean ("sync-by-running-time", "Sync By Running Time",
414           "Synchronize deactivated or not-linked streams by running time",
415           DEFAULT_SYNC_BY_RUNNING_TIME,
416           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
417
418   gobject_class->finalize = gst_multi_queue_finalize;
419
420   gst_element_class_set_static_metadata (gstelement_class,
421       "MultiQueue",
422       "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>");
423   gst_element_class_add_pad_template (gstelement_class,
424       gst_static_pad_template_get (&sinktemplate));
425   gst_element_class_add_pad_template (gstelement_class,
426       gst_static_pad_template_get (&srctemplate));
427
428   gstelement_class->request_new_pad =
429       GST_DEBUG_FUNCPTR (gst_multi_queue_request_new_pad);
430   gstelement_class->release_pad =
431       GST_DEBUG_FUNCPTR (gst_multi_queue_release_pad);
432   gstelement_class->change_state =
433       GST_DEBUG_FUNCPTR (gst_multi_queue_change_state);
434 }
435
436 static void
437 gst_multi_queue_init (GstMultiQueue * mqueue)
438 {
439   mqueue->nbqueues = 0;
440   mqueue->queues = NULL;
441
442   mqueue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
443   mqueue->max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
444   mqueue->max_size.time = DEFAULT_MAX_SIZE_TIME;
445
446   mqueue->extra_size.bytes = DEFAULT_EXTRA_SIZE_BYTES;
447   mqueue->extra_size.visible = DEFAULT_EXTRA_SIZE_BUFFERS;
448   mqueue->extra_size.time = DEFAULT_EXTRA_SIZE_TIME;
449
450   mqueue->use_buffering = DEFAULT_USE_BUFFERING;
451   mqueue->low_percent = DEFAULT_LOW_PERCENT;
452   mqueue->high_percent = DEFAULT_HIGH_PERCENT;
453
454   mqueue->sync_by_running_time = DEFAULT_SYNC_BY_RUNNING_TIME;
455
456   mqueue->counter = 1;
457   mqueue->highid = -1;
458   mqueue->high_time = GST_CLOCK_TIME_NONE;
459
460   g_mutex_init (&mqueue->qlock);
461 }
462
463 static void
464 gst_multi_queue_finalize (GObject * object)
465 {
466   GstMultiQueue *mqueue = GST_MULTI_QUEUE (object);
467
468   g_list_foreach (mqueue->queues, (GFunc) gst_single_queue_free, NULL);
469   g_list_free (mqueue->queues);
470   mqueue->queues = NULL;
471   mqueue->queues_cookie++;
472
473   /* free/unref instance data */
474   g_mutex_clear (&mqueue->qlock);
475
476   G_OBJECT_CLASS (parent_class)->finalize (object);
477 }
478
479 #define SET_CHILD_PROPERTY(mq,format) G_STMT_START {            \
480     GList * tmp = mq->queues;                                   \
481     while (tmp) {                                               \
482       GstSingleQueue *q = (GstSingleQueue*)tmp->data;           \
483       q->max_size.format = mq->max_size.format;                 \
484       tmp = g_list_next(tmp);                                   \
485     };                                                          \
486 } G_STMT_END
487
488 static void
489 gst_multi_queue_set_property (GObject * object, guint prop_id,
490     const GValue * value, GParamSpec * pspec)
491 {
492   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
493
494   switch (prop_id) {
495     case PROP_MAX_SIZE_BYTES:
496       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
497       mq->max_size.bytes = g_value_get_uint (value);
498       SET_CHILD_PROPERTY (mq, bytes);
499       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
500       break;
501     case PROP_MAX_SIZE_BUFFERS:
502       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
503       mq->max_size.visible = g_value_get_uint (value);
504       SET_CHILD_PROPERTY (mq, visible);
505       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
506       break;
507     case PROP_MAX_SIZE_TIME:
508       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
509       mq->max_size.time = g_value_get_uint64 (value);
510       SET_CHILD_PROPERTY (mq, time);
511       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
512       break;
513     case PROP_EXTRA_SIZE_BYTES:
514       mq->extra_size.bytes = g_value_get_uint (value);
515       break;
516     case PROP_EXTRA_SIZE_BUFFERS:
517       mq->extra_size.visible = g_value_get_uint (value);
518       break;
519     case PROP_EXTRA_SIZE_TIME:
520       mq->extra_size.time = g_value_get_uint64 (value);
521       break;
522     case PROP_USE_BUFFERING:
523       mq->use_buffering = g_value_get_boolean (value);
524       break;
525     case PROP_LOW_PERCENT:
526       mq->low_percent = g_value_get_int (value);
527       break;
528     case PROP_HIGH_PERCENT:
529       mq->high_percent = g_value_get_int (value);
530       break;
531     case PROP_SYNC_BY_RUNNING_TIME:
532       mq->sync_by_running_time = g_value_get_boolean (value);
533       break;
534     default:
535       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
536       break;
537   }
538 }
539
540 static void
541 gst_multi_queue_get_property (GObject * object, guint prop_id,
542     GValue * value, GParamSpec * pspec)
543 {
544   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
545
546   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
547
548   switch (prop_id) {
549     case PROP_EXTRA_SIZE_BYTES:
550       g_value_set_uint (value, mq->extra_size.bytes);
551       break;
552     case PROP_EXTRA_SIZE_BUFFERS:
553       g_value_set_uint (value, mq->extra_size.visible);
554       break;
555     case PROP_EXTRA_SIZE_TIME:
556       g_value_set_uint64 (value, mq->extra_size.time);
557       break;
558     case PROP_MAX_SIZE_BYTES:
559       g_value_set_uint (value, mq->max_size.bytes);
560       break;
561     case PROP_MAX_SIZE_BUFFERS:
562       g_value_set_uint (value, mq->max_size.visible);
563       break;
564     case PROP_MAX_SIZE_TIME:
565       g_value_set_uint64 (value, mq->max_size.time);
566       break;
567     case PROP_USE_BUFFERING:
568       g_value_set_boolean (value, mq->use_buffering);
569       break;
570     case PROP_LOW_PERCENT:
571       g_value_set_int (value, mq->low_percent);
572       break;
573     case PROP_HIGH_PERCENT:
574       g_value_set_int (value, mq->high_percent);
575       break;
576     case PROP_SYNC_BY_RUNNING_TIME:
577       g_value_set_boolean (value, mq->sync_by_running_time);
578       break;
579     default:
580       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
581       break;
582   }
583
584   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
585 }
586
587 static GstIterator *
588 gst_multi_queue_iterate_internal_links (GstPad * pad, GstObject * parent)
589 {
590   GstIterator *it = NULL;
591   GstPad *opad;
592   GstSingleQueue *squeue;
593   GstMultiQueue *mq = GST_MULTI_QUEUE (parent);
594   GValue val = { 0, };
595
596   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
597   squeue = gst_pad_get_element_private (pad);
598   if (!squeue)
599     goto out;
600
601   if (squeue->sinkpad == pad)
602     opad = gst_object_ref (squeue->srcpad);
603   else if (squeue->srcpad == pad)
604     opad = gst_object_ref (squeue->sinkpad);
605   else
606     goto out;
607
608   g_value_init (&val, GST_TYPE_PAD);
609   g_value_set_object (&val, opad);
610   it = gst_iterator_new_single (GST_TYPE_PAD, &val);
611   g_value_unset (&val);
612
613   gst_object_unref (opad);
614
615 out:
616   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
617
618   return it;
619 }
620
621
622 /*
623  * GstElement methods
624  */
625
626 static GstPad *
627 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
628     const gchar * name, const GstCaps * caps)
629 {
630   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
631   GstSingleQueue *squeue;
632   guint temp_id = -1;
633
634   if (name) {
635     sscanf (name + 4, "_%u", &temp_id);
636     GST_LOG_OBJECT (element, "name : %s (id %d)", GST_STR_NULL (name), temp_id);
637   }
638
639   /* Create a new single queue, add the sink and source pad and return the sink pad */
640   squeue = gst_single_queue_new (mqueue, temp_id);
641
642   GST_DEBUG_OBJECT (mqueue, "Returning pad %s:%s",
643       GST_DEBUG_PAD_NAME (squeue->sinkpad));
644
645   return squeue ? squeue->sinkpad : NULL;
646 }
647
648 static void
649 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
650 {
651   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
652   GstSingleQueue *sq = NULL;
653   GList *tmp;
654
655   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
656
657   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
658   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
659   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
660     sq = (GstSingleQueue *) tmp->data;
661
662     if (sq->sinkpad == pad)
663       break;
664   }
665
666   if (!tmp) {
667     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
668     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
669     return;
670   }
671
672   /* FIXME: The removal of the singlequeue should probably not happen until it
673    * finishes draining */
674
675   /* remove it from the list */
676   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
677   mqueue->queues_cookie++;
678
679   /* FIXME : recompute next-non-linked */
680   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
681
682   /* delete SingleQueue */
683   gst_data_queue_set_flushing (sq->queue, TRUE);
684
685   gst_pad_set_active (sq->srcpad, FALSE);
686   gst_pad_set_active (sq->sinkpad, FALSE);
687   gst_pad_set_element_private (sq->srcpad, NULL);
688   gst_pad_set_element_private (sq->sinkpad, NULL);
689   gst_element_remove_pad (element, sq->srcpad);
690   gst_element_remove_pad (element, sq->sinkpad);
691   gst_single_queue_free (sq);
692 }
693
694 static GstStateChangeReturn
695 gst_multi_queue_change_state (GstElement * element, GstStateChange transition)
696 {
697   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
698   GstSingleQueue *sq = NULL;
699   GstStateChangeReturn result;
700
701   switch (transition) {
702     case GST_STATE_CHANGE_READY_TO_PAUSED:{
703       GList *tmp;
704
705       /* Set all pads to non-flushing */
706       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
707       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
708         sq = (GstSingleQueue *) tmp->data;
709         sq->flushing = FALSE;
710       }
711       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
712       break;
713     }
714     case GST_STATE_CHANGE_PAUSED_TO_READY:{
715       GList *tmp;
716
717       /* Un-wait all waiting pads */
718       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
719       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
720         sq = (GstSingleQueue *) tmp->data;
721         sq->flushing = TRUE;
722         g_cond_signal (&sq->turn);
723       }
724       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
725       break;
726     }
727     default:
728       break;
729   }
730
731   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
732
733   switch (transition) {
734     default:
735       break;
736   }
737
738   return result;
739
740
741
742 }
743
744 static gboolean
745 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush)
746 {
747   gboolean result;
748
749   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
750       sq->id);
751
752   if (flush) {
753     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
754     sq->srcresult = GST_FLOW_FLUSHING;
755     gst_data_queue_set_flushing (sq->queue, TRUE);
756
757     sq->flushing = TRUE;
758     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
759
760     /* wake up non-linked task */
761     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
762         sq->id);
763     g_cond_signal (&sq->turn);
764     sq->last_query = FALSE;
765     g_cond_signal (&sq->query_handled);
766     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
767
768     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
769     result = gst_pad_pause_task (sq->srcpad);
770     sq->sink_tainted = sq->src_tainted = TRUE;
771   } else {
772     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
773     gst_data_queue_flush (sq->queue);
774     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
775     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
776     /* All pads start off not-linked for a smooth kick-off */
777     sq->srcresult = GST_FLOW_OK;
778     sq->pushed = FALSE;
779     sq->cur_time = 0;
780     sq->max_size.visible = mq->max_size.visible;
781     sq->is_eos = FALSE;
782     sq->nextid = 0;
783     sq->oldid = 0;
784     sq->last_oldid = G_MAXUINT32;
785     sq->next_time = GST_CLOCK_TIME_NONE;
786     sq->last_time = GST_CLOCK_TIME_NONE;
787     gst_data_queue_set_flushing (sq->queue, FALSE);
788
789     /* Reset high time to be recomputed next */
790     mq->high_time = GST_CLOCK_TIME_NONE;
791
792     sq->flushing = FALSE;
793     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
794
795     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
796     result =
797         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
798         sq->srcpad);
799   }
800   return result;
801 }
802
803 static void
804 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
805 {
806   GstDataQueueSize size;
807   gint percent, tmp;
808   gboolean post = FALSE;
809
810   /* nothing to dowhen we are not in buffering mode */
811   if (!mq->use_buffering)
812     return;
813
814   gst_data_queue_get_level (sq->queue, &size);
815
816   GST_DEBUG_OBJECT (mq,
817       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
818       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
819       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
820
821   /* get bytes and time percentages and take the max */
822   if (sq->is_eos) {
823     percent = 100;
824   } else {
825     percent = 0;
826     if (sq->max_size.time > 0) {
827       tmp = (sq->cur_time * 100) / sq->max_size.time;
828       percent = MAX (percent, tmp);
829     }
830     if (sq->max_size.bytes > 0) {
831       tmp = (size.bytes * 100) / sq->max_size.bytes;
832       percent = MAX (percent, tmp);
833     }
834   }
835
836   if (mq->buffering) {
837     post = TRUE;
838     if (percent >= mq->high_percent) {
839       mq->buffering = FALSE;
840     }
841     /* make sure it increases */
842     percent = MAX (mq->percent, percent);
843
844     if (percent == mq->percent)
845       /* don't post if nothing changed */
846       post = FALSE;
847     else
848       /* else keep last value we posted */
849       mq->percent = percent;
850   } else {
851     if (percent < mq->low_percent) {
852       mq->buffering = TRUE;
853       mq->percent = percent;
854       post = TRUE;
855     }
856   }
857   if (post) {
858     GstMessage *message;
859
860     /* scale to high percent so that it becomes the 100% mark */
861     percent = percent * 100 / mq->high_percent;
862     /* clip */
863     if (percent > 100)
864       percent = 100;
865
866     GST_DEBUG_OBJECT (mq, "buffering %d percent", percent);
867     message = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
868
869     gst_element_post_message (GST_ELEMENT_CAST (mq), message);
870   } else {
871     GST_DEBUG_OBJECT (mq, "filled %d percent", percent);
872   }
873 }
874
875 /* calculate the diff between running time on the sink and src of the queue.
876  * This is the total amount of time in the queue. 
877  * WITH LOCK TAKEN */
878 static void
879 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
880 {
881   gint64 sink_time, src_time;
882
883   if (sq->sink_tainted) {
884     sink_time = sq->sinktime =
885         gst_segment_to_running_time (&sq->sink_segment, GST_FORMAT_TIME,
886         sq->sink_segment.position);
887
888     if (G_UNLIKELY (sink_time != GST_CLOCK_TIME_NONE))
889       /* if we have a time, we become untainted and use the time */
890       sq->sink_tainted = FALSE;
891   } else
892     sink_time = sq->sinktime;
893
894   if (sq->src_tainted) {
895     src_time = sq->srctime =
896         gst_segment_to_running_time (&sq->src_segment, GST_FORMAT_TIME,
897         sq->src_segment.position);
898     /* if we have a time, we become untainted and use the time */
899     if (G_UNLIKELY (src_time != GST_CLOCK_TIME_NONE))
900       sq->src_tainted = FALSE;
901   } else
902     src_time = sq->srctime;
903
904   GST_DEBUG_OBJECT (mq,
905       "queue %d, sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT, sq->id,
906       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
907
908   /* This allows for streams with out of order timestamping - sometimes the
909    * emerging timestamp is later than the arriving one(s) */
910   if (G_LIKELY (sink_time != -1 && src_time != -1 && sink_time > src_time))
911     sq->cur_time = sink_time - src_time;
912   else
913     sq->cur_time = 0;
914
915   /* updating the time level can change the buffering state */
916   update_buffering (mq, sq);
917
918   return;
919 }
920
921 /* take a SEGMENT event and apply the values to segment, updating the time
922  * level of queue. */
923 static void
924 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
925     GstSegment * segment)
926 {
927   gst_event_copy_segment (event, segment);
928
929   /* now configure the values, we use these to track timestamps on the
930    * sinkpad. */
931   if (segment->format != GST_FORMAT_TIME) {
932     /* non-time format, pretent the current time segment is closed with a
933      * 0 start and unknown stop time. */
934     segment->format = GST_FORMAT_TIME;
935     segment->start = 0;
936     segment->stop = -1;
937     segment->time = 0;
938   }
939   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
940
941   if (segment == &sq->sink_segment)
942     sq->sink_tainted = TRUE;
943   else
944     sq->src_tainted = TRUE;
945
946   GST_DEBUG_OBJECT (mq,
947       "queue %d, configured SEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
948
949   /* segment can update the time level of the queue */
950   update_time_level (mq, sq);
951
952   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
953 }
954
955 /* take a buffer and update segment, updating the time level of the queue. */
956 static void
957 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
958     GstClockTime duration, GstSegment * segment)
959 {
960   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
961
962   /* if no timestamp is set, assume it's continuous with the previous 
963    * time */
964   if (timestamp == GST_CLOCK_TIME_NONE)
965     timestamp = segment->position;
966
967   /* add duration */
968   if (duration != GST_CLOCK_TIME_NONE)
969     timestamp += duration;
970
971   GST_DEBUG_OBJECT (mq, "queue %d, position updated to %" GST_TIME_FORMAT,
972       sq->id, GST_TIME_ARGS (timestamp));
973
974   segment->position = timestamp;
975
976   if (segment == &sq->sink_segment)
977     sq->sink_tainted = TRUE;
978   else
979     sq->src_tainted = TRUE;
980
981   /* calc diff with other end */
982   update_time_level (mq, sq);
983   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
984 }
985
986 static GstClockTime
987 get_running_time (GstSegment * segment, GstMiniObject * object, gboolean end)
988 {
989   GstClockTime time = GST_CLOCK_TIME_NONE;
990
991   if (GST_IS_BUFFER (object)) {
992     GstBuffer *buf = GST_BUFFER_CAST (object);
993
994     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
995       time = GST_BUFFER_TIMESTAMP (buf);
996       if (end && GST_BUFFER_DURATION_IS_VALID (buf))
997         time += GST_BUFFER_DURATION (buf);
998       if (time > segment->stop)
999         time = segment->stop;
1000       time = gst_segment_to_running_time (segment, GST_FORMAT_TIME, time);
1001     }
1002   } else if (GST_IS_BUFFER_LIST (object)) {
1003     GstBufferList *list = GST_BUFFER_LIST_CAST (object);
1004     gint i, n;
1005     GstBuffer *buf;
1006
1007     n = gst_buffer_list_length (list);
1008     for (i = 0; i < n; i++) {
1009       buf = gst_buffer_list_get (list, i);
1010       if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1011         time = GST_BUFFER_TIMESTAMP (buf);
1012         if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1013           time += GST_BUFFER_DURATION (buf);
1014         if (time > segment->stop)
1015           time = segment->stop;
1016         time = gst_segment_to_running_time (segment, GST_FORMAT_TIME, time);
1017         if (!end)
1018           goto done;
1019       } else if (!end) {
1020         goto done;
1021       }
1022     }
1023   } else if (GST_IS_EVENT (object)) {
1024     GstEvent *event = GST_EVENT_CAST (object);
1025
1026     /* For newsegment events return the running time of the start position */
1027     if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
1028       const GstSegment *new_segment;
1029
1030       gst_event_parse_segment (event, &new_segment);
1031       if (new_segment->format == GST_FORMAT_TIME) {
1032         time =
1033             gst_segment_to_running_time (new_segment, GST_FORMAT_TIME,
1034             new_segment->start);
1035       }
1036     }
1037   }
1038
1039 done:
1040   return time;
1041 }
1042
1043 static GstFlowReturn
1044 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
1045     GstMiniObject * object)
1046 {
1047   GstFlowReturn result = GST_FLOW_OK;
1048
1049   if (GST_IS_BUFFER (object)) {
1050     GstBuffer *buffer;
1051     GstClockTime timestamp, duration;
1052
1053     buffer = GST_BUFFER_CAST (object);
1054     timestamp = GST_BUFFER_TIMESTAMP (buffer);
1055     duration = GST_BUFFER_DURATION (buffer);
1056
1057     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
1058
1059     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
1060     gst_data_queue_limits_changed (sq->queue);
1061
1062     GST_DEBUG_OBJECT (mq,
1063         "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
1064         sq->id, buffer, GST_TIME_ARGS (timestamp));
1065
1066     result = gst_pad_push (sq->srcpad, buffer);
1067   } else if (GST_IS_EVENT (object)) {
1068     GstEvent *event;
1069
1070     event = GST_EVENT_CAST (object);
1071
1072     switch (GST_EVENT_TYPE (event)) {
1073       case GST_EVENT_EOS:
1074         result = GST_FLOW_EOS;
1075         break;
1076       case GST_EVENT_SEGMENT:
1077         apply_segment (mq, sq, event, &sq->src_segment);
1078         /* Applying the segment may have made the queue non-full again, unblock it if needed */
1079         gst_data_queue_limits_changed (sq->queue);
1080         break;
1081       default:
1082         break;
1083     }
1084
1085     GST_DEBUG_OBJECT (mq,
1086         "SingleQueue %d : Pushing event %p of type %s",
1087         sq->id, event, GST_EVENT_TYPE_NAME (event));
1088
1089     gst_pad_push_event (sq->srcpad, event);
1090   } else if (GST_IS_QUERY (object)) {
1091     GstQuery *query;
1092     gboolean res;
1093
1094     query = GST_QUERY_CAST (object);
1095
1096     res = gst_pad_peer_query (sq->srcpad, query);
1097
1098     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1099     sq->last_query = res;
1100     g_cond_signal (&sq->query_handled);
1101     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1102   } else {
1103     g_warning ("Unexpected object in singlequeue %d (refcounting problem?)",
1104         sq->id);
1105   }
1106   return result;
1107
1108   /* ERRORS */
1109 }
1110
1111 static GstMiniObject *
1112 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
1113 {
1114   GstMiniObject *res;
1115
1116   res = item->object;
1117   item->object = NULL;
1118
1119   return res;
1120 }
1121
1122 static void
1123 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
1124 {
1125   if (item->object)
1126     gst_mini_object_unref (item->object);
1127   g_slice_free (GstMultiQueueItem, item);
1128 }
1129
1130 /* takes ownership of passed mini object! */
1131 static GstMultiQueueItem *
1132 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
1133 {
1134   GstMultiQueueItem *item;
1135
1136   item = g_slice_new (GstMultiQueueItem);
1137   item->object = object;
1138   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1139   item->posid = curid;
1140
1141   item->size = gst_buffer_get_size (GST_BUFFER_CAST (object));
1142   item->duration = GST_BUFFER_DURATION (object);
1143   if (item->duration == GST_CLOCK_TIME_NONE)
1144     item->duration = 0;
1145   item->visible = TRUE;
1146   return item;
1147 }
1148
1149 static GstMultiQueueItem *
1150 gst_multi_queue_mo_item_new (GstMiniObject * object, guint32 curid)
1151 {
1152   GstMultiQueueItem *item;
1153
1154   item = g_slice_new (GstMultiQueueItem);
1155   item->object = object;
1156   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1157   item->posid = curid;
1158
1159   item->size = 0;
1160   item->duration = 0;
1161   item->visible = FALSE;
1162   return item;
1163 }
1164
1165 /* Each main loop attempts to push buffers until the return value
1166  * is not-linked. not-linked pads are not allowed to push data beyond
1167  * any linked pads, so they don't 'rush ahead of the pack'.
1168  */
1169 static void
1170 gst_multi_queue_loop (GstPad * pad)
1171 {
1172   GstSingleQueue *sq;
1173   GstMultiQueueItem *item;
1174   GstDataQueueItem *sitem;
1175   GstMultiQueue *mq;
1176   GstMiniObject *object = NULL;
1177   guint32 newid;
1178   GstFlowReturn result;
1179   GstClockTime next_time;
1180   gboolean is_buffer;
1181
1182   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1183   mq = sq->mqueue;
1184
1185   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
1186
1187   if (sq->flushing)
1188     goto out_flushing;
1189
1190   /* Get something from the queue, blocking until that happens, or we get
1191    * flushed */
1192   if (!(gst_data_queue_pop (sq->queue, &sitem)))
1193     goto out_flushing;
1194
1195   item = (GstMultiQueueItem *) sitem;
1196   newid = item->posid;
1197
1198   /* steal the object and destroy the item */
1199   object = gst_multi_queue_item_steal_object (item);
1200   gst_multi_queue_item_destroy (item);
1201
1202   is_buffer = GST_IS_BUFFER (object);
1203
1204   /* Get running time of the item. Events will have GST_CLOCK_TIME_NONE */
1205   next_time = get_running_time (&sq->src_segment, object, TRUE);
1206
1207   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
1208       sq->id, newid, sq->last_oldid);
1209
1210   /* If we're not-linked, we do some extra work because we might need to
1211    * wait before pushing. If we're linked but there's a gap in the IDs,
1212    * or it's the first loop, or we just passed the previous highid, 
1213    * we might need to wake some sleeping pad up, so there's extra work 
1214    * there too */
1215   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1216   if (sq->srcresult == GST_FLOW_NOT_LINKED
1217       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
1218       || sq->last_oldid > mq->highid) {
1219     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
1220         gst_flow_get_name (sq->srcresult));
1221
1222     /* Check again if we're flushing after the lock is taken,
1223      * the flush flag might have been changed in the meantime */
1224     if (sq->flushing) {
1225       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1226       goto out_flushing;
1227     }
1228
1229     /* Update the nextid so other threads know when to wake us up */
1230     sq->nextid = newid;
1231     sq->next_time = next_time;
1232
1233     /* Update the oldid (the last ID we output) for highid tracking */
1234     if (sq->last_oldid != G_MAXUINT32)
1235       sq->oldid = sq->last_oldid;
1236
1237     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1238       /* Go to sleep until it's time to push this buffer */
1239
1240       /* Recompute the highid */
1241       compute_high_id (mq);
1242       /* Recompute the high time */
1243       compute_high_time (mq);
1244
1245       while (((mq->sync_by_running_time && next_time != GST_CLOCK_TIME_NONE &&
1246                   (mq->high_time == GST_CLOCK_TIME_NONE
1247                       || next_time >= mq->high_time))
1248               || (!mq->sync_by_running_time && newid > mq->highid))
1249           && sq->srcresult == GST_FLOW_NOT_LINKED) {
1250
1251         GST_DEBUG_OBJECT (mq,
1252             "queue %d sleeping for not-linked wakeup with "
1253             "newid %u, highid %u, next_time %" GST_TIME_FORMAT
1254             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1255             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1256
1257         /* Wake up all non-linked pads before we sleep */
1258         wake_up_next_non_linked (mq);
1259
1260         mq->numwaiting++;
1261         g_cond_wait (&sq->turn, &mq->qlock);
1262         mq->numwaiting--;
1263
1264         if (sq->flushing) {
1265           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1266           goto out_flushing;
1267         }
1268
1269         /* Recompute the high time */
1270         compute_high_time (mq);
1271
1272         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1273             "wakeup with newid %u, highid %u, next_time %" GST_TIME_FORMAT
1274             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1275             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1276       }
1277
1278       /* Re-compute the high_id in case someone else pushed */
1279       compute_high_id (mq);
1280     } else {
1281       compute_high_id (mq);
1282       /* Wake up all non-linked pads */
1283       wake_up_next_non_linked (mq);
1284     }
1285     /* We're done waiting, we can clear the nextid and nexttime */
1286     sq->nextid = 0;
1287     sq->next_time = GST_CLOCK_TIME_NONE;
1288   }
1289   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1290
1291   if (sq->flushing)
1292     goto out_flushing;
1293
1294   GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s",
1295       gst_flow_get_name (sq->srcresult));
1296
1297   /* Update time stats */
1298   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1299   next_time = get_running_time (&sq->src_segment, object, FALSE);
1300   if (next_time != GST_CLOCK_TIME_NONE) {
1301     if (sq->last_time == GST_CLOCK_TIME_NONE || sq->last_time < next_time)
1302       sq->last_time = next_time;
1303     if (mq->high_time == GST_CLOCK_TIME_NONE || mq->high_time <= next_time) {
1304       /* Wake up all non-linked pads now that we advanced the high time */
1305       mq->high_time = next_time;
1306       wake_up_next_non_linked (mq);
1307     }
1308   }
1309   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1310
1311   /* Try to push out the new object */
1312   result = gst_single_queue_push_one (mq, sq, object);
1313   object = NULL;
1314
1315   /* Check if we pushed something already and if this is
1316    * now a switch from an active to a non-active stream.
1317    *
1318    * If it is, we reset all the waiting streams, let them
1319    * push another buffer to see if they're now active again.
1320    * This allows faster switching between streams and prevents
1321    * deadlocks if downstream does any waiting too.
1322    */
1323   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1324   if (sq->pushed && sq->srcresult == GST_FLOW_OK
1325       && result == GST_FLOW_NOT_LINKED) {
1326     GList *tmp;
1327
1328     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
1329         sq->id);
1330
1331     compute_high_id (mq);
1332
1333     /* maybe no-one is waiting */
1334     if (mq->numwaiting > 0) {
1335       /* Else figure out which singlequeue(s) need waking up */
1336       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1337         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1338
1339         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
1340           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
1341           sq2->pushed = FALSE;
1342           sq2->srcresult = GST_FLOW_OK;
1343           g_cond_signal (&sq2->turn);
1344         }
1345       }
1346     }
1347   }
1348
1349   if (is_buffer)
1350     sq->pushed = TRUE;
1351   sq->srcresult = result;
1352   sq->last_oldid = newid;
1353   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1354
1355   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
1356       && result != GST_FLOW_EOS)
1357     goto out_flushing;
1358
1359   GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s",
1360       gst_flow_get_name (sq->srcresult));
1361
1362   return;
1363
1364 out_flushing:
1365   {
1366     if (object)
1367       gst_mini_object_unref (object);
1368
1369     /* Need to make sure wake up any sleeping pads when we exit */
1370     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1371     compute_high_time (mq);
1372     compute_high_id (mq);
1373     wake_up_next_non_linked (mq);
1374     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1375
1376     /* upstream needs to see fatal result ASAP to shut things down,
1377      * but might be stuck in one of our other full queues;
1378      * so empty this one and trigger dynamic queue growth. At
1379      * this point the srcresult is not OK, NOT_LINKED
1380      * or EOS, i.e. a real failure */
1381     gst_data_queue_flush (sq->queue);
1382     single_queue_underrun_cb (sq->queue, sq);
1383     gst_data_queue_set_flushing (sq->queue, TRUE);
1384     gst_pad_pause_task (sq->srcpad);
1385     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
1386         "SingleQueue[%d] task paused, reason:%s",
1387         sq->id, gst_flow_get_name (sq->srcresult));
1388     return;
1389   }
1390 }
1391
1392 /**
1393  * gst_multi_queue_chain:
1394  *
1395  * This is similar to GstQueue's chain function, except:
1396  * _ we don't have leak behaviours,
1397  * _ we push with a unique id (curid)
1398  */
1399 static GstFlowReturn
1400 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1401 {
1402   GstSingleQueue *sq;
1403   GstMultiQueue *mq;
1404   GstMultiQueueItem *item;
1405   guint32 curid;
1406   GstClockTime timestamp, duration;
1407
1408   sq = gst_pad_get_element_private (pad);
1409   mq = sq->mqueue;
1410
1411   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1412   if (sq->is_eos)
1413     goto was_eos;
1414
1415   /* Get a unique incrementing id */
1416   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1417
1418   GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d",
1419       sq->id, buffer, curid);
1420
1421   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
1422
1423   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1424   duration = GST_BUFFER_DURATION (buffer);
1425
1426   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1427     goto flushing;
1428
1429   /* update time level, we must do this after pushing the data in the queue so
1430    * that we never end up filling the queue first. */
1431   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
1432
1433 done:
1434   return sq->srcresult;
1435
1436   /* ERRORS */
1437 flushing:
1438   {
1439     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1440         sq->id, gst_flow_get_name (sq->srcresult));
1441     gst_multi_queue_item_destroy (item);
1442     goto done;
1443   }
1444 was_eos:
1445   {
1446     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
1447     gst_buffer_unref (buffer);
1448     return GST_FLOW_EOS;
1449   }
1450 }
1451
1452 static gboolean
1453 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
1454     GstPadMode mode, gboolean active)
1455 {
1456   gboolean res;
1457   GstSingleQueue *sq;
1458   GstMultiQueue *mq;
1459
1460   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1461   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
1462
1463   /* mq is NULL if the pad is activated/deactivated before being
1464    * added to the multiqueue */
1465   if (mq)
1466     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1467
1468   switch (mode) {
1469     case GST_PAD_MODE_PUSH:
1470       if (active) {
1471         /* All pads start off linked until they push one buffer */
1472         sq->srcresult = GST_FLOW_OK;
1473         sq->pushed = FALSE;
1474       } else {
1475         sq->srcresult = GST_FLOW_FLUSHING;
1476         gst_data_queue_flush (sq->queue);
1477       }
1478       res = TRUE;
1479       break;
1480     default:
1481       res = FALSE;
1482       break;
1483   }
1484
1485   if (mq) {
1486     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1487     gst_object_unref (mq);
1488   }
1489
1490   return res;
1491 }
1492
1493 static gboolean
1494 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1495 {
1496   GstSingleQueue *sq;
1497   GstMultiQueue *mq;
1498   guint32 curid;
1499   GstMultiQueueItem *item;
1500   gboolean res;
1501   GstEventType type;
1502   GstEvent *sref = NULL;
1503
1504   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1505   mq = (GstMultiQueue *) parent;
1506
1507   type = GST_EVENT_TYPE (event);
1508
1509   switch (type) {
1510     case GST_EVENT_FLUSH_START:
1511       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
1512           sq->id);
1513
1514       res = gst_pad_push_event (sq->srcpad, event);
1515
1516       gst_single_queue_flush (mq, sq, TRUE);
1517       goto done;
1518
1519     case GST_EVENT_FLUSH_STOP:
1520       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
1521           sq->id);
1522
1523       res = gst_pad_push_event (sq->srcpad, event);
1524
1525       gst_single_queue_flush (mq, sq, FALSE);
1526       goto done;
1527     case GST_EVENT_SEGMENT:
1528       /* take ref because the queue will take ownership and we need the event
1529        * afterwards to update the segment */
1530       sref = gst_event_ref (event);
1531       break;
1532
1533     default:
1534       if (!(GST_EVENT_IS_SERIALIZED (event))) {
1535         res = gst_pad_push_event (sq->srcpad, event);
1536         goto done;
1537       }
1538       break;
1539   }
1540
1541   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1542   if (sq->is_eos)
1543     goto was_eos;
1544
1545   /* Get an unique incrementing id. */
1546   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1547
1548   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
1549
1550   GST_DEBUG_OBJECT (mq,
1551       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
1552       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
1553
1554   if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1555     goto flushing;
1556
1557   /* mark EOS when we received one, we must do that after putting the
1558    * buffer in the queue because EOS marks the buffer as filled. No need to take
1559    * a lock, the _check_full happens from this thread only, right before pushing
1560    * into dataqueue. */
1561   switch (type) {
1562     case GST_EVENT_EOS:
1563       sq->is_eos = TRUE;
1564       /* EOS affects the buffering state */
1565       update_buffering (mq, sq);
1566       single_queue_overrun_cb (sq->queue, sq);
1567       break;
1568     case GST_EVENT_SEGMENT:
1569       apply_segment (mq, sq, sref, &sq->sink_segment);
1570       gst_event_unref (sref);
1571       break;
1572     default:
1573       break;
1574   }
1575 done:
1576   return res;
1577
1578 flushing:
1579   {
1580     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1581         sq->id, gst_flow_get_name (sq->srcresult));
1582     if (sref)
1583       gst_event_unref (sref);
1584     gst_multi_queue_item_destroy (item);
1585     goto done;
1586   }
1587 was_eos:
1588   {
1589     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return FALSE");
1590     gst_event_unref (event);
1591     res = FALSE;
1592     goto done;
1593   }
1594 }
1595
1596 static gboolean
1597 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1598 {
1599   gboolean res;
1600   GstSingleQueue *sq;
1601   GstMultiQueue *mq;
1602
1603   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1604   mq = (GstMultiQueue *) parent;
1605
1606   switch (GST_QUERY_TYPE (query)) {
1607     default:
1608       if (GST_QUERY_IS_SERIALIZED (query)) {
1609         guint32 curid;
1610         GstMultiQueueItem *item;
1611
1612         /* Get an unique incrementing id. */
1613         curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1614
1615         item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
1616
1617         GST_DEBUG_OBJECT (mq,
1618             "SingleQueue %d : Enqueuing query %p of type %s with id %d",
1619             sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
1620
1621         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1622         res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
1623         g_cond_wait (&sq->query_handled, &mq->qlock);
1624         res = sq->last_query;
1625         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1626       } else {
1627         /* default handling */
1628         res = gst_pad_query_default (pad, parent, query);
1629       }
1630       break;
1631   }
1632   return res;
1633 }
1634
1635 static gboolean
1636 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
1637     GstPadMode mode, gboolean active)
1638 {
1639   GstMultiQueue *mq;
1640   GstSingleQueue *sq;
1641   gboolean result;
1642
1643   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1644   mq = sq->mqueue;
1645
1646   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
1647
1648   switch (mode) {
1649     case GST_PAD_MODE_PUSH:
1650       if (active) {
1651         result = gst_single_queue_flush (mq, sq, FALSE);
1652       } else {
1653         result = gst_single_queue_flush (mq, sq, TRUE);
1654         /* make sure streaming finishes */
1655         result |= gst_pad_stop_task (pad);
1656       }
1657       break;
1658     default:
1659       result = FALSE;
1660       break;
1661   }
1662   return result;
1663 }
1664
1665 static gboolean
1666 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1667 {
1668   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1669
1670   return gst_pad_push_event (sq->sinkpad, event);
1671 }
1672
1673 static gboolean
1674 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1675 {
1676   gboolean res;
1677
1678   /* FIXME, Handle position offset depending on queue size */
1679   switch (GST_QUERY_TYPE (query)) {
1680     default:
1681       /* default handling */
1682       res = gst_pad_query_default (pad, parent, query);
1683       break;
1684   }
1685   return res;
1686 }
1687
1688 /*
1689  * Next-non-linked functions
1690  */
1691
1692 /* WITH LOCK TAKEN */
1693 static void
1694 wake_up_next_non_linked (GstMultiQueue * mq)
1695 {
1696   GList *tmp;
1697
1698   /* maybe no-one is waiting */
1699   if (mq->numwaiting < 1)
1700     return;
1701
1702   /* Else figure out which singlequeue(s) need waking up */
1703   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1704     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1705
1706     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1707       if ((mq->sync_by_running_time && mq->high_time != GST_CLOCK_TIME_NONE
1708               && sq->next_time != GST_CLOCK_TIME_NONE
1709               && sq->next_time >= mq->high_time)
1710           || (sq->nextid != 0 && sq->nextid <= mq->highid)) {
1711         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
1712         g_cond_signal (&sq->turn);
1713       }
1714     }
1715   }
1716 }
1717
1718 /* WITH LOCK TAKEN */
1719 static void
1720 compute_high_id (GstMultiQueue * mq)
1721 {
1722   /* The high-id is either the highest id among the linked pads, or if all
1723    * pads are not-linked, it's the lowest not-linked pad */
1724   GList *tmp;
1725   guint32 lowest = G_MAXUINT32;
1726   guint32 highid = G_MAXUINT32;
1727
1728   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1729     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1730
1731     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
1732         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
1733
1734     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1735       /* No need to consider queues which are not waiting */
1736       if (sq->nextid == 0) {
1737         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1738         continue;
1739       }
1740
1741       if (sq->nextid < lowest)
1742         lowest = sq->nextid;
1743     } else if (sq->srcresult != GST_FLOW_EOS) {
1744       /* If we don't have a global highid, or the global highid is lower than
1745        * this single queue's last outputted id, store the queue's one, 
1746        * unless the singlequeue is at EOS (srcresult = EOS) */
1747       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
1748         highid = sq->oldid;
1749     }
1750   }
1751
1752   if (highid == G_MAXUINT32 || lowest < highid)
1753     mq->highid = lowest;
1754   else
1755     mq->highid = highid;
1756
1757   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
1758       lowest);
1759 }
1760
1761 /* WITH LOCK TAKEN */
1762 static void
1763 compute_high_time (GstMultiQueue * mq)
1764 {
1765   /* The high-id is either the highest id among the linked pads, or if all
1766    * pads are not-linked, it's the lowest not-linked pad */
1767   GList *tmp;
1768   GstClockTime highest = GST_CLOCK_TIME_NONE;
1769   GstClockTime lowest = GST_CLOCK_TIME_NONE;
1770
1771   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1772     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1773
1774     GST_LOG_OBJECT (mq,
1775         "inspecting sq:%d , next_time:%" GST_TIME_FORMAT ", last_time:%"
1776         GST_TIME_FORMAT ", srcresult:%s", sq->id, GST_TIME_ARGS (sq->next_time),
1777         GST_TIME_ARGS (sq->last_time), gst_flow_get_name (sq->srcresult));
1778
1779     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1780       /* No need to consider queues which are not waiting */
1781       if (sq->next_time == GST_CLOCK_TIME_NONE) {
1782         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1783         continue;
1784       }
1785
1786       if (lowest == GST_CLOCK_TIME_NONE || sq->next_time < lowest)
1787         lowest = sq->next_time;
1788     } else if (sq->srcresult != GST_FLOW_EOS) {
1789       /* If we don't have a global highid, or the global highid is lower than
1790        * this single queue's last outputted id, store the queue's one, 
1791        * unless the singlequeue is at EOS (srcresult = EOS) */
1792       if (highest == GST_CLOCK_TIME_NONE || sq->last_time > highest)
1793         highest = sq->last_time;
1794     }
1795   }
1796
1797   mq->high_time = highest;
1798
1799   GST_LOG_OBJECT (mq,
1800       "High time is now : %" GST_TIME_FORMAT ", lowest non-linked %"
1801       GST_TIME_FORMAT, GST_TIME_ARGS (mq->high_time), GST_TIME_ARGS (lowest));
1802 }
1803
1804 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
1805      ((q)->max_size.format) <= (value))
1806
1807 /*
1808  * GstSingleQueue functions
1809  */
1810 static void
1811 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1812 {
1813   GstMultiQueue *mq = sq->mqueue;
1814   GList *tmp;
1815   GstDataQueueSize size;
1816   gboolean filled = FALSE;
1817
1818   gst_data_queue_get_level (sq->queue, &size);
1819
1820   GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id);
1821
1822   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1823   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1824     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1825     GstDataQueueSize ssize;
1826
1827     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
1828
1829     if (gst_data_queue_is_empty (oq->queue)) {
1830       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
1831       if (IS_FILLED (sq, visible, size.visible)) {
1832         sq->max_size.visible = size.visible + 1;
1833         GST_DEBUG_OBJECT (mq,
1834             "Another queue is empty, bumping single queue %d max visible to %d",
1835             sq->id, sq->max_size.visible);
1836       }
1837     }
1838     /* check if we reached the hard time/bytes limits */
1839     gst_data_queue_get_level (oq->queue, &ssize);
1840
1841     GST_DEBUG_OBJECT (mq,
1842         "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1843         G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible,
1844         ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time);
1845
1846     /* if this queue is filled completely we must signal overrun.
1847      * FIXME, this seems wrong in many ways
1848      *  - we're comparing the filled level of this queue against the
1849      *    values of the other one
1850      *  - we should only do this after we found no empty queues, ie, move
1851      *    this check outside of the loop
1852      *  - the debug statement talks about a different queue than the one
1853      *    we are checking here.
1854      */
1855     if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) ||
1856         IS_FILLED (sq, time, sq->cur_time)) {
1857       GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id);
1858       filled = TRUE;
1859     }
1860   }
1861   /* no queues were empty */
1862   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1863
1864   /* Overrun is always forwarded, since this is blocking the upstream element */
1865   if (filled) {
1866     GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun");
1867     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
1868   }
1869
1870   return;
1871 }
1872
1873 static void
1874 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1875 {
1876   gboolean empty = TRUE;
1877   GstMultiQueue *mq = sq->mqueue;
1878   GList *tmp;
1879
1880   GST_LOG_OBJECT (mq,
1881       "Single Queue %d is empty, Checking other single queues", sq->id);
1882
1883   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1884   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1885     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1886
1887     if (gst_data_queue_is_full (oq->queue)) {
1888       GstDataQueueSize size;
1889
1890       gst_data_queue_get_level (oq->queue, &size);
1891       if (IS_FILLED (oq, visible, size.visible)) {
1892         oq->max_size.visible = size.visible + 1;
1893         GST_DEBUG_OBJECT (mq,
1894             "queue %d is filled, bumping its max visible to %d", oq->id,
1895             oq->max_size.visible);
1896         gst_data_queue_limits_changed (oq->queue);
1897       }
1898     }
1899     if (!gst_data_queue_is_empty (oq->queue))
1900       empty = FALSE;
1901   }
1902   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1903
1904   if (empty) {
1905     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
1906     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
1907   }
1908 }
1909
1910 static gboolean
1911 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
1912     guint64 time, GstSingleQueue * sq)
1913 {
1914   gboolean res;
1915   GstMultiQueue *mq = sq->mqueue;
1916
1917   GST_DEBUG_OBJECT (mq,
1918       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1919       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
1920       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1921
1922   /* we are always filled on EOS */
1923   if (sq->is_eos)
1924     return TRUE;
1925
1926   /* we never go past the max visible items unless we are in buffering mode */
1927   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
1928     return TRUE;
1929
1930   /* check time or bytes */
1931   res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
1932
1933   return res;
1934 }
1935
1936 static void
1937 gst_single_queue_free (GstSingleQueue * sq)
1938 {
1939   /* DRAIN QUEUE */
1940   gst_data_queue_flush (sq->queue);
1941   g_object_unref (sq->queue);
1942   g_cond_clear (&sq->turn);
1943   g_cond_clear (&sq->query_handled);
1944   g_free (sq);
1945 }
1946
1947 static GstSingleQueue *
1948 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
1949 {
1950   GstSingleQueue *sq;
1951   gchar *name;
1952   GList *tmp;
1953   guint temp_id = (id == -1) ? 0 : id;
1954
1955   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1956
1957   /* Find an unused queue ID, if possible the passed one */
1958   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1959     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1960     /* This works because the IDs are sorted in ascending order */
1961     if (sq2->id == temp_id) {
1962       /* If this ID was requested by the caller return NULL,
1963        * otherwise just get us the next one */
1964       if (id == -1)
1965         temp_id = sq2->id + 1;
1966       else
1967         return NULL;
1968     } else if (sq2->id > temp_id) {
1969       break;
1970     }
1971   }
1972
1973   sq = g_new0 (GstSingleQueue, 1);
1974   mqueue->nbqueues++;
1975   sq->id = temp_id;
1976
1977   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
1978   mqueue->queues_cookie++;
1979
1980   /* copy over max_size and extra_size so we don't need to take the lock
1981    * any longer when checking if the queue is full. */
1982   sq->max_size.visible = mqueue->max_size.visible;
1983   sq->max_size.bytes = mqueue->max_size.bytes;
1984   sq->max_size.time = mqueue->max_size.time;
1985
1986   sq->extra_size.visible = mqueue->extra_size.visible;
1987   sq->extra_size.bytes = mqueue->extra_size.bytes;
1988   sq->extra_size.time = mqueue->extra_size.time;
1989
1990   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
1991
1992   sq->mqueue = mqueue;
1993   sq->srcresult = GST_FLOW_FLUSHING;
1994   sq->pushed = FALSE;
1995   sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction)
1996       single_queue_check_full,
1997       (GstDataQueueFullCallback) single_queue_overrun_cb,
1998       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
1999   sq->is_eos = FALSE;
2000   sq->flushing = FALSE;
2001   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
2002   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
2003
2004   sq->nextid = 0;
2005   sq->oldid = 0;
2006   sq->next_time = GST_CLOCK_TIME_NONE;
2007   sq->last_time = GST_CLOCK_TIME_NONE;
2008   g_cond_init (&sq->turn);
2009   g_cond_init (&sq->query_handled);
2010
2011   sq->sinktime = GST_CLOCK_TIME_NONE;
2012   sq->srctime = GST_CLOCK_TIME_NONE;
2013   sq->sink_tainted = TRUE;
2014   sq->src_tainted = TRUE;
2015
2016   name = g_strdup_printf ("sink_%u", sq->id);
2017   sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, name);
2018   g_free (name);
2019
2020   gst_pad_set_chain_function (sq->sinkpad,
2021       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
2022   gst_pad_set_activatemode_function (sq->sinkpad,
2023       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
2024   gst_pad_set_event_function (sq->sinkpad,
2025       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
2026   gst_pad_set_query_function (sq->sinkpad,
2027       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
2028   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
2029       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2030   GST_OBJECT_FLAG_SET (sq->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
2031
2032   name = g_strdup_printf ("src_%u", sq->id);
2033   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
2034   g_free (name);
2035
2036   gst_pad_set_activatemode_function (sq->srcpad,
2037       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
2038   gst_pad_set_event_function (sq->srcpad,
2039       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
2040   gst_pad_set_query_function (sq->srcpad,
2041       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
2042   gst_pad_set_iterate_internal_links_function (sq->srcpad,
2043       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2044   GST_OBJECT_FLAG_SET (sq->srcpad, GST_PAD_FLAG_PROXY_CAPS);
2045
2046   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
2047   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
2048
2049   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
2050
2051   /* only activate the pads when we are not in the NULL state
2052    * and add the pad under the state_lock to prevend state changes
2053    * between activating and adding */
2054   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
2055   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
2056     gst_pad_set_active (sq->srcpad, TRUE);
2057     gst_pad_set_active (sq->sinkpad, TRUE);
2058   }
2059   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
2060   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
2061   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
2062
2063   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
2064       sq->id);
2065
2066   return sq;
2067 }