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_details_simple (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
1181   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1182   mq = sq->mqueue;
1183
1184   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
1185
1186   if (sq->flushing)
1187     goto out_flushing;
1188
1189   /* Get something from the queue, blocking until that happens, or we get
1190    * flushed */
1191   if (!(gst_data_queue_pop (sq->queue, &sitem)))
1192     goto out_flushing;
1193
1194   item = (GstMultiQueueItem *) sitem;
1195   newid = item->posid;
1196
1197   /* steal the object and destroy the item */
1198   object = gst_multi_queue_item_steal_object (item);
1199   gst_multi_queue_item_destroy (item);
1200
1201   /* Get running time of the item. Events will have GST_CLOCK_TIME_NONE */
1202   next_time = get_running_time (&sq->src_segment, object, TRUE);
1203
1204   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
1205       sq->id, newid, sq->last_oldid);
1206
1207   /* If we're not-linked, we do some extra work because we might need to
1208    * wait before pushing. If we're linked but there's a gap in the IDs,
1209    * or it's the first loop, or we just passed the previous highid, 
1210    * we might need to wake some sleeping pad up, so there's extra work 
1211    * there too */
1212   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1213   if (sq->srcresult == GST_FLOW_NOT_LINKED
1214       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
1215       || sq->last_oldid > mq->highid) {
1216     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
1217         gst_flow_get_name (sq->srcresult));
1218
1219     /* Check again if we're flushing after the lock is taken,
1220      * the flush flag might have been changed in the meantime */
1221     if (sq->flushing) {
1222       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1223       goto out_flushing;
1224     }
1225
1226     /* Update the nextid so other threads know when to wake us up */
1227     sq->nextid = newid;
1228     sq->next_time = next_time;
1229
1230     /* Update the oldid (the last ID we output) for highid tracking */
1231     if (sq->last_oldid != G_MAXUINT32)
1232       sq->oldid = sq->last_oldid;
1233
1234     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1235       /* Go to sleep until it's time to push this buffer */
1236
1237       /* Recompute the highid */
1238       compute_high_id (mq);
1239       /* Recompute the high time */
1240       compute_high_time (mq);
1241
1242       while (((mq->sync_by_running_time && next_time != GST_CLOCK_TIME_NONE &&
1243                   (mq->high_time == GST_CLOCK_TIME_NONE
1244                       || next_time >= mq->high_time))
1245               || (!mq->sync_by_running_time && newid > mq->highid))
1246           && sq->srcresult == GST_FLOW_NOT_LINKED) {
1247
1248         GST_DEBUG_OBJECT (mq,
1249             "queue %d sleeping for not-linked wakeup with "
1250             "newid %u, highid %u, next_time %" GST_TIME_FORMAT
1251             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1252             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1253
1254         /* Wake up all non-linked pads before we sleep */
1255         wake_up_next_non_linked (mq);
1256
1257         mq->numwaiting++;
1258         g_cond_wait (&sq->turn, &mq->qlock);
1259         mq->numwaiting--;
1260
1261         if (sq->flushing) {
1262           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1263           goto out_flushing;
1264         }
1265
1266         /* Recompute the high time */
1267         compute_high_time (mq);
1268
1269         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1270             "wakeup with newid %u, highid %u, next_time %" GST_TIME_FORMAT
1271             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1272             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1273       }
1274
1275       /* Re-compute the high_id in case someone else pushed */
1276       compute_high_id (mq);
1277     } else {
1278       compute_high_id (mq);
1279       /* Wake up all non-linked pads */
1280       wake_up_next_non_linked (mq);
1281     }
1282     /* We're done waiting, we can clear the nextid and nexttime */
1283     sq->nextid = 0;
1284     sq->next_time = GST_CLOCK_TIME_NONE;
1285   }
1286   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1287
1288   if (sq->flushing)
1289     goto out_flushing;
1290
1291   GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s",
1292       gst_flow_get_name (sq->srcresult));
1293
1294   /* Update time stats */
1295   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1296   next_time = get_running_time (&sq->src_segment, object, FALSE);
1297   if (next_time != GST_CLOCK_TIME_NONE) {
1298     if (sq->last_time == GST_CLOCK_TIME_NONE || sq->last_time < next_time)
1299       sq->last_time = next_time;
1300     if (mq->high_time == GST_CLOCK_TIME_NONE || mq->high_time <= next_time) {
1301       /* Wake up all non-linked pads now that we advanced the high time */
1302       mq->high_time = next_time;
1303       wake_up_next_non_linked (mq);
1304     }
1305   }
1306   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1307
1308   /* Try to push out the new object */
1309   result = gst_single_queue_push_one (mq, sq, object);
1310
1311   /* Check if we pushed something already and if this is
1312    * now a switch from an active to a non-active stream.
1313    *
1314    * If it is, we reset all the waiting streams, let them
1315    * push another buffer to see if they're now active again.
1316    * This allows faster switching between streams and prevents
1317    * deadlocks if downstream does any waiting too.
1318    */
1319   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1320   if (sq->pushed && sq->srcresult == GST_FLOW_OK
1321       && result == GST_FLOW_NOT_LINKED) {
1322     GList *tmp;
1323
1324     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
1325         sq->id);
1326
1327     compute_high_id (mq);
1328
1329     /* maybe no-one is waiting */
1330     if (mq->numwaiting > 0) {
1331       /* Else figure out which singlequeue(s) need waking up */
1332       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1333         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1334
1335         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
1336           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
1337           sq2->pushed = FALSE;
1338           sq2->srcresult = GST_FLOW_OK;
1339           g_cond_signal (&sq2->turn);
1340         }
1341       }
1342     }
1343   }
1344
1345   if (GST_IS_BUFFER (object))
1346     sq->pushed = TRUE;
1347   sq->srcresult = result;
1348   sq->last_oldid = newid;
1349   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1350
1351   object = NULL;
1352
1353   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
1354       && result != GST_FLOW_EOS)
1355     goto out_flushing;
1356
1357   GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s",
1358       gst_flow_get_name (sq->srcresult));
1359
1360   return;
1361
1362 out_flushing:
1363   {
1364     if (object)
1365       gst_mini_object_unref (object);
1366
1367     /* Need to make sure wake up any sleeping pads when we exit */
1368     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1369     compute_high_time (mq);
1370     compute_high_id (mq);
1371     wake_up_next_non_linked (mq);
1372     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1373
1374     /* upstream needs to see fatal result ASAP to shut things down,
1375      * but might be stuck in one of our other full queues;
1376      * so empty this one and trigger dynamic queue growth. At
1377      * this point the srcresult is not OK, NOT_LINKED
1378      * or EOS, i.e. a real failure */
1379     gst_data_queue_flush (sq->queue);
1380     single_queue_underrun_cb (sq->queue, sq);
1381     gst_data_queue_set_flushing (sq->queue, TRUE);
1382     gst_pad_pause_task (sq->srcpad);
1383     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
1384         "SingleQueue[%d] task paused, reason:%s",
1385         sq->id, gst_flow_get_name (sq->srcresult));
1386     return;
1387   }
1388 }
1389
1390 /**
1391  * gst_multi_queue_chain:
1392  *
1393  * This is similar to GstQueue's chain function, except:
1394  * _ we don't have leak behaviours,
1395  * _ we push with a unique id (curid)
1396  */
1397 static GstFlowReturn
1398 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1399 {
1400   GstSingleQueue *sq;
1401   GstMultiQueue *mq;
1402   GstMultiQueueItem *item;
1403   guint32 curid;
1404   GstClockTime timestamp, duration;
1405
1406   sq = gst_pad_get_element_private (pad);
1407   mq = sq->mqueue;
1408
1409   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1410   if (sq->is_eos)
1411     goto was_eos;
1412
1413   /* Get a unique incrementing id */
1414   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1415
1416   GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d",
1417       sq->id, buffer, curid);
1418
1419   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
1420
1421   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1422   duration = GST_BUFFER_DURATION (buffer);
1423
1424   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1425     goto flushing;
1426
1427   /* update time level, we must do this after pushing the data in the queue so
1428    * that we never end up filling the queue first. */
1429   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
1430
1431 done:
1432   return sq->srcresult;
1433
1434   /* ERRORS */
1435 flushing:
1436   {
1437     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1438         sq->id, gst_flow_get_name (sq->srcresult));
1439     gst_multi_queue_item_destroy (item);
1440     goto done;
1441   }
1442 was_eos:
1443   {
1444     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
1445     gst_buffer_unref (buffer);
1446     return GST_FLOW_EOS;
1447   }
1448 }
1449
1450 static gboolean
1451 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
1452     GstPadMode mode, gboolean active)
1453 {
1454   gboolean res;
1455   GstSingleQueue *sq;
1456   GstMultiQueue *mq;
1457
1458   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1459   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
1460
1461   /* mq is NULL if the pad is activated/deactivated before being
1462    * added to the multiqueue */
1463   if (mq)
1464     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1465
1466   switch (mode) {
1467     case GST_PAD_MODE_PUSH:
1468       if (active) {
1469         /* All pads start off linked until they push one buffer */
1470         sq->srcresult = GST_FLOW_OK;
1471         sq->pushed = FALSE;
1472       } else {
1473         sq->srcresult = GST_FLOW_FLUSHING;
1474         gst_data_queue_flush (sq->queue);
1475       }
1476       res = TRUE;
1477       break;
1478     default:
1479       res = FALSE;
1480       break;
1481   }
1482
1483   if (mq) {
1484     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1485     gst_object_unref (mq);
1486   }
1487
1488   return res;
1489 }
1490
1491 static gboolean
1492 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1493 {
1494   GstSingleQueue *sq;
1495   GstMultiQueue *mq;
1496   guint32 curid;
1497   GstMultiQueueItem *item;
1498   gboolean res;
1499   GstEventType type;
1500   GstEvent *sref = NULL;
1501
1502   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1503   mq = (GstMultiQueue *) parent;
1504
1505   type = GST_EVENT_TYPE (event);
1506
1507   switch (type) {
1508     case GST_EVENT_FLUSH_START:
1509       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
1510           sq->id);
1511
1512       res = gst_pad_push_event (sq->srcpad, event);
1513
1514       gst_single_queue_flush (mq, sq, TRUE);
1515       goto done;
1516
1517     case GST_EVENT_FLUSH_STOP:
1518       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
1519           sq->id);
1520
1521       res = gst_pad_push_event (sq->srcpad, event);
1522
1523       gst_single_queue_flush (mq, sq, FALSE);
1524       goto done;
1525     case GST_EVENT_SEGMENT:
1526       /* take ref because the queue will take ownership and we need the event
1527        * afterwards to update the segment */
1528       sref = gst_event_ref (event);
1529       break;
1530
1531     default:
1532       if (!(GST_EVENT_IS_SERIALIZED (event))) {
1533         res = gst_pad_push_event (sq->srcpad, event);
1534         goto done;
1535       }
1536       break;
1537   }
1538
1539   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1540   if (sq->is_eos)
1541     goto was_eos;
1542
1543   /* Get an unique incrementing id. */
1544   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1545
1546   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
1547
1548   GST_DEBUG_OBJECT (mq,
1549       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
1550       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
1551
1552   if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1553     goto flushing;
1554
1555   /* mark EOS when we received one, we must do that after putting the
1556    * buffer in the queue because EOS marks the buffer as filled. No need to take
1557    * a lock, the _check_full happens from this thread only, right before pushing
1558    * into dataqueue. */
1559   switch (type) {
1560     case GST_EVENT_EOS:
1561       sq->is_eos = TRUE;
1562       /* EOS affects the buffering state */
1563       update_buffering (mq, sq);
1564       single_queue_overrun_cb (sq->queue, sq);
1565       break;
1566     case GST_EVENT_SEGMENT:
1567       apply_segment (mq, sq, sref, &sq->sink_segment);
1568       gst_event_unref (sref);
1569       break;
1570     default:
1571       break;
1572   }
1573 done:
1574   return res;
1575
1576 flushing:
1577   {
1578     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1579         sq->id, gst_flow_get_name (sq->srcresult));
1580     if (sref)
1581       gst_event_unref (sref);
1582     gst_multi_queue_item_destroy (item);
1583     goto done;
1584   }
1585 was_eos:
1586   {
1587     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return FALSE");
1588     gst_event_unref (event);
1589     res = FALSE;
1590     goto done;
1591   }
1592 }
1593
1594 static gboolean
1595 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1596 {
1597   gboolean res;
1598   GstSingleQueue *sq;
1599   GstMultiQueue *mq;
1600
1601   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1602   mq = (GstMultiQueue *) parent;
1603
1604   switch (GST_QUERY_TYPE (query)) {
1605     default:
1606       if (GST_QUERY_IS_SERIALIZED (query)) {
1607         guint32 curid;
1608         GstMultiQueueItem *item;
1609
1610         /* Get an unique incrementing id. */
1611         curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1612
1613         item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
1614
1615         GST_DEBUG_OBJECT (mq,
1616             "SingleQueue %d : Enqueuing query %p of type %s with id %d",
1617             sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
1618
1619         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1620         res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
1621         g_cond_wait (&sq->query_handled, &mq->qlock);
1622         res = sq->last_query;
1623         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1624       } else {
1625         /* default handling */
1626         res = gst_pad_query_default (pad, parent, query);
1627       }
1628       break;
1629   }
1630   return res;
1631 }
1632
1633 static gboolean
1634 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
1635     GstPadMode mode, gboolean active)
1636 {
1637   GstMultiQueue *mq;
1638   GstSingleQueue *sq;
1639   gboolean result;
1640
1641   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1642   mq = sq->mqueue;
1643
1644   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
1645
1646   switch (mode) {
1647     case GST_PAD_MODE_PUSH:
1648       if (active) {
1649         result = gst_single_queue_flush (mq, sq, FALSE);
1650       } else {
1651         result = gst_single_queue_flush (mq, sq, TRUE);
1652         /* make sure streaming finishes */
1653         result |= gst_pad_stop_task (pad);
1654       }
1655       break;
1656     default:
1657       result = FALSE;
1658       break;
1659   }
1660   return result;
1661 }
1662
1663 static gboolean
1664 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1665 {
1666   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1667
1668   return gst_pad_push_event (sq->sinkpad, event);
1669 }
1670
1671 static gboolean
1672 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1673 {
1674   gboolean res;
1675
1676   /* FIXME, Handle position offset depending on queue size */
1677   switch (GST_QUERY_TYPE (query)) {
1678     default:
1679       /* default handling */
1680       res = gst_pad_query_default (pad, parent, query);
1681       break;
1682   }
1683   return res;
1684 }
1685
1686 /*
1687  * Next-non-linked functions
1688  */
1689
1690 /* WITH LOCK TAKEN */
1691 static void
1692 wake_up_next_non_linked (GstMultiQueue * mq)
1693 {
1694   GList *tmp;
1695
1696   /* maybe no-one is waiting */
1697   if (mq->numwaiting < 1)
1698     return;
1699
1700   /* Else figure out which singlequeue(s) need waking up */
1701   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1702     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1703
1704     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1705       if ((mq->sync_by_running_time && mq->high_time != GST_CLOCK_TIME_NONE
1706               && sq->next_time != GST_CLOCK_TIME_NONE
1707               && sq->next_time >= mq->high_time)
1708           || (sq->nextid != 0 && sq->nextid <= mq->highid)) {
1709         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
1710         g_cond_signal (&sq->turn);
1711       }
1712     }
1713   }
1714 }
1715
1716 /* WITH LOCK TAKEN */
1717 static void
1718 compute_high_id (GstMultiQueue * mq)
1719 {
1720   /* The high-id is either the highest id among the linked pads, or if all
1721    * pads are not-linked, it's the lowest not-linked pad */
1722   GList *tmp;
1723   guint32 lowest = G_MAXUINT32;
1724   guint32 highid = G_MAXUINT32;
1725
1726   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1727     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1728
1729     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
1730         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
1731
1732     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1733       /* No need to consider queues which are not waiting */
1734       if (sq->nextid == 0) {
1735         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1736         continue;
1737       }
1738
1739       if (sq->nextid < lowest)
1740         lowest = sq->nextid;
1741     } else if (sq->srcresult != GST_FLOW_EOS) {
1742       /* If we don't have a global highid, or the global highid is lower than
1743        * this single queue's last outputted id, store the queue's one, 
1744        * unless the singlequeue is at EOS (srcresult = EOS) */
1745       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
1746         highid = sq->oldid;
1747     }
1748   }
1749
1750   if (highid == G_MAXUINT32 || lowest < highid)
1751     mq->highid = lowest;
1752   else
1753     mq->highid = highid;
1754
1755   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
1756       lowest);
1757 }
1758
1759 /* WITH LOCK TAKEN */
1760 static void
1761 compute_high_time (GstMultiQueue * mq)
1762 {
1763   /* The high-id is either the highest id among the linked pads, or if all
1764    * pads are not-linked, it's the lowest not-linked pad */
1765   GList *tmp;
1766   GstClockTime highest = GST_CLOCK_TIME_NONE;
1767   GstClockTime lowest = GST_CLOCK_TIME_NONE;
1768
1769   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1770     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1771
1772     GST_LOG_OBJECT (mq,
1773         "inspecting sq:%d , next_time:%" GST_TIME_FORMAT ", last_time:%"
1774         GST_TIME_FORMAT ", srcresult:%s", sq->id, GST_TIME_ARGS (sq->next_time),
1775         GST_TIME_ARGS (sq->last_time), gst_flow_get_name (sq->srcresult));
1776
1777     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1778       /* No need to consider queues which are not waiting */
1779       if (sq->next_time == GST_CLOCK_TIME_NONE) {
1780         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1781         continue;
1782       }
1783
1784       if (lowest == GST_CLOCK_TIME_NONE || sq->next_time < lowest)
1785         lowest = sq->next_time;
1786     } else if (sq->srcresult != GST_FLOW_EOS) {
1787       /* If we don't have a global highid, or the global highid is lower than
1788        * this single queue's last outputted id, store the queue's one, 
1789        * unless the singlequeue is at EOS (srcresult = EOS) */
1790       if (highest == GST_CLOCK_TIME_NONE || sq->last_time > highest)
1791         highest = sq->last_time;
1792     }
1793   }
1794
1795   mq->high_time = highest;
1796
1797   GST_LOG_OBJECT (mq,
1798       "High time is now : %" GST_TIME_FORMAT ", lowest non-linked %"
1799       GST_TIME_FORMAT, GST_TIME_ARGS (mq->high_time), GST_TIME_ARGS (lowest));
1800 }
1801
1802 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
1803      ((q)->max_size.format) <= (value))
1804
1805 /*
1806  * GstSingleQueue functions
1807  */
1808 static void
1809 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1810 {
1811   GstMultiQueue *mq = sq->mqueue;
1812   GList *tmp;
1813   GstDataQueueSize size;
1814   gboolean filled = FALSE;
1815
1816   gst_data_queue_get_level (sq->queue, &size);
1817
1818   GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id);
1819
1820   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1821   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1822     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1823     GstDataQueueSize ssize;
1824
1825     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
1826
1827     if (gst_data_queue_is_empty (oq->queue)) {
1828       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
1829       if (IS_FILLED (sq, visible, size.visible)) {
1830         sq->max_size.visible = size.visible + 1;
1831         GST_DEBUG_OBJECT (mq,
1832             "Another queue is empty, bumping single queue %d max visible to %d",
1833             sq->id, sq->max_size.visible);
1834       }
1835     }
1836     /* check if we reached the hard time/bytes limits */
1837     gst_data_queue_get_level (oq->queue, &ssize);
1838
1839     GST_DEBUG_OBJECT (mq,
1840         "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1841         G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible,
1842         ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time);
1843
1844     /* if this queue is filled completely we must signal overrun.
1845      * FIXME, this seems wrong in many ways
1846      *  - we're comparing the filled level of this queue against the
1847      *    values of the other one
1848      *  - we should only do this after we found no empty queues, ie, move
1849      *    this check outside of the loop
1850      *  - the debug statement talks about a different queue than the one
1851      *    we are checking here.
1852      */
1853     if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) ||
1854         IS_FILLED (sq, time, sq->cur_time)) {
1855       GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id);
1856       filled = TRUE;
1857     }
1858   }
1859   /* no queues were empty */
1860   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1861
1862   /* Overrun is always forwarded, since this is blocking the upstream element */
1863   if (filled) {
1864     GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun");
1865     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
1866   }
1867
1868   return;
1869 }
1870
1871 static void
1872 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1873 {
1874   gboolean empty = TRUE;
1875   GstMultiQueue *mq = sq->mqueue;
1876   GList *tmp;
1877
1878   GST_LOG_OBJECT (mq,
1879       "Single Queue %d is empty, Checking other single queues", sq->id);
1880
1881   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1882   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1883     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1884
1885     if (gst_data_queue_is_full (oq->queue)) {
1886       GstDataQueueSize size;
1887
1888       gst_data_queue_get_level (oq->queue, &size);
1889       if (IS_FILLED (oq, visible, size.visible)) {
1890         oq->max_size.visible = size.visible + 1;
1891         GST_DEBUG_OBJECT (mq,
1892             "queue %d is filled, bumping its max visible to %d", oq->id,
1893             oq->max_size.visible);
1894         gst_data_queue_limits_changed (oq->queue);
1895       }
1896     }
1897     if (!gst_data_queue_is_empty (oq->queue))
1898       empty = FALSE;
1899   }
1900   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1901
1902   if (empty) {
1903     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
1904     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
1905   }
1906 }
1907
1908 static gboolean
1909 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
1910     guint64 time, GstSingleQueue * sq)
1911 {
1912   gboolean res;
1913   GstMultiQueue *mq = sq->mqueue;
1914
1915   GST_DEBUG_OBJECT (mq,
1916       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1917       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
1918       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1919
1920   /* we are always filled on EOS */
1921   if (sq->is_eos)
1922     return TRUE;
1923
1924   /* we never go past the max visible items unless we are in buffering mode */
1925   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
1926     return TRUE;
1927
1928   /* check time or bytes */
1929   res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
1930
1931   return res;
1932 }
1933
1934 static void
1935 gst_single_queue_free (GstSingleQueue * sq)
1936 {
1937   /* DRAIN QUEUE */
1938   gst_data_queue_flush (sq->queue);
1939   g_object_unref (sq->queue);
1940   g_cond_clear (&sq->turn);
1941   g_cond_clear (&sq->query_handled);
1942   g_free (sq);
1943 }
1944
1945 static GstSingleQueue *
1946 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
1947 {
1948   GstSingleQueue *sq;
1949   gchar *name;
1950   GList *tmp;
1951   guint temp_id = (id == -1) ? 0 : id;
1952
1953   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1954
1955   /* Find an unused queue ID, if possible the passed one */
1956   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1957     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1958     /* This works because the IDs are sorted in ascending order */
1959     if (sq2->id == temp_id) {
1960       /* If this ID was requested by the caller return NULL,
1961        * otherwise just get us the next one */
1962       if (id == -1)
1963         temp_id = sq2->id + 1;
1964       else
1965         return NULL;
1966     } else if (sq2->id > temp_id) {
1967       break;
1968     }
1969   }
1970
1971   sq = g_new0 (GstSingleQueue, 1);
1972   mqueue->nbqueues++;
1973   sq->id = temp_id;
1974
1975   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
1976   mqueue->queues_cookie++;
1977
1978   /* copy over max_size and extra_size so we don't need to take the lock
1979    * any longer when checking if the queue is full. */
1980   sq->max_size.visible = mqueue->max_size.visible;
1981   sq->max_size.bytes = mqueue->max_size.bytes;
1982   sq->max_size.time = mqueue->max_size.time;
1983
1984   sq->extra_size.visible = mqueue->extra_size.visible;
1985   sq->extra_size.bytes = mqueue->extra_size.bytes;
1986   sq->extra_size.time = mqueue->extra_size.time;
1987
1988   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
1989
1990   sq->mqueue = mqueue;
1991   sq->srcresult = GST_FLOW_FLUSHING;
1992   sq->pushed = FALSE;
1993   sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction)
1994       single_queue_check_full,
1995       (GstDataQueueFullCallback) single_queue_overrun_cb,
1996       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
1997   sq->is_eos = FALSE;
1998   sq->flushing = FALSE;
1999   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
2000   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
2001
2002   sq->nextid = 0;
2003   sq->oldid = 0;
2004   sq->next_time = GST_CLOCK_TIME_NONE;
2005   sq->last_time = GST_CLOCK_TIME_NONE;
2006   g_cond_init (&sq->turn);
2007   g_cond_init (&sq->query_handled);
2008
2009   sq->sinktime = GST_CLOCK_TIME_NONE;
2010   sq->srctime = GST_CLOCK_TIME_NONE;
2011   sq->sink_tainted = TRUE;
2012   sq->src_tainted = TRUE;
2013
2014   name = g_strdup_printf ("sink_%u", sq->id);
2015   sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, name);
2016   g_free (name);
2017
2018   gst_pad_set_chain_function (sq->sinkpad,
2019       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
2020   gst_pad_set_activatemode_function (sq->sinkpad,
2021       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
2022   gst_pad_set_event_function (sq->sinkpad,
2023       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
2024   gst_pad_set_query_function (sq->sinkpad,
2025       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
2026   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
2027       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2028   GST_OBJECT_FLAG_SET (sq->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
2029
2030   name = g_strdup_printf ("src_%u", sq->id);
2031   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
2032   g_free (name);
2033
2034   gst_pad_set_activatemode_function (sq->srcpad,
2035       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
2036   gst_pad_set_event_function (sq->srcpad,
2037       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
2038   gst_pad_set_query_function (sq->srcpad,
2039       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
2040   gst_pad_set_iterate_internal_links_function (sq->srcpad,
2041       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2042   GST_OBJECT_FLAG_SET (sq->srcpad, GST_PAD_FLAG_PROXY_CAPS);
2043
2044   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
2045   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
2046
2047   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
2048
2049   /* only activate the pads when we are not in the NULL state
2050    * and add the pad under the state_lock to prevend state changes
2051    * between activating and adding */
2052   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
2053   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
2054     gst_pad_set_active (sq->srcpad, TRUE);
2055     gst_pad_set_active (sq->sinkpad, TRUE);
2056   }
2057   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
2058   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
2059   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
2060
2061   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
2062       sq->id);
2063
2064   return sq;
2065 }