445cc717de116369c38c09f7a82264c38f364b6f
[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
759     /* wake up non-linked task */
760     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
761         sq->id);
762     g_cond_signal (&sq->turn);
763     sq->last_query = FALSE;
764     g_cond_signal (&sq->query_handled);
765     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
766
767     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
768     result = gst_pad_pause_task (sq->srcpad);
769     sq->sink_tainted = sq->src_tainted = TRUE;
770   } else {
771     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
772     gst_data_queue_flush (sq->queue);
773     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
774     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
775     /* All pads start off not-linked for a smooth kick-off */
776     sq->srcresult = GST_FLOW_OK;
777     sq->pushed = FALSE;
778     sq->cur_time = 0;
779     sq->max_size.visible = mq->max_size.visible;
780     sq->is_eos = FALSE;
781     sq->nextid = 0;
782     sq->oldid = 0;
783     sq->last_oldid = G_MAXUINT32;
784     sq->next_time = GST_CLOCK_TIME_NONE;
785     sq->last_time = GST_CLOCK_TIME_NONE;
786     gst_data_queue_set_flushing (sq->queue, FALSE);
787
788     /* Reset high time to be recomputed next */
789     mq->high_time = GST_CLOCK_TIME_NONE;
790
791     sq->flushing = FALSE;
792     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
793
794     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
795     result =
796         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
797         sq->srcpad, NULL);
798   }
799   return result;
800 }
801
802 static void
803 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
804 {
805   GstDataQueueSize size;
806   gint percent, tmp;
807   gboolean post = FALSE;
808
809   /* nothing to dowhen we are not in buffering mode */
810   if (!mq->use_buffering)
811     return;
812
813   gst_data_queue_get_level (sq->queue, &size);
814
815   GST_DEBUG_OBJECT (mq,
816       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
817       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
818       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
819
820   /* get bytes and time percentages and take the max */
821   if (sq->is_eos) {
822     percent = 100;
823   } else {
824     percent = 0;
825     if (sq->max_size.time > 0) {
826       tmp = (sq->cur_time * 100) / sq->max_size.time;
827       percent = MAX (percent, tmp);
828     }
829     if (sq->max_size.bytes > 0) {
830       tmp = (size.bytes * 100) / sq->max_size.bytes;
831       percent = MAX (percent, tmp);
832     }
833   }
834
835   if (mq->buffering) {
836     post = TRUE;
837     if (percent >= mq->high_percent) {
838       mq->buffering = FALSE;
839     }
840     /* make sure it increases */
841     percent = MAX (mq->percent, percent);
842
843     if (percent == mq->percent)
844       /* don't post if nothing changed */
845       post = FALSE;
846     else
847       /* else keep last value we posted */
848       mq->percent = percent;
849   } else {
850     if (percent < mq->low_percent) {
851       mq->buffering = TRUE;
852       mq->percent = percent;
853       post = TRUE;
854     }
855   }
856   if (post) {
857     GstMessage *message;
858
859     /* scale to high percent so that it becomes the 100% mark */
860     percent = percent * 100 / mq->high_percent;
861     /* clip */
862     if (percent > 100)
863       percent = 100;
864
865     GST_DEBUG_OBJECT (mq, "buffering %d percent", percent);
866     message = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
867
868     gst_element_post_message (GST_ELEMENT_CAST (mq), message);
869   } else {
870     GST_DEBUG_OBJECT (mq, "filled %d percent", percent);
871   }
872 }
873
874 /* calculate the diff between running time on the sink and src of the queue.
875  * This is the total amount of time in the queue. 
876  * WITH LOCK TAKEN */
877 static void
878 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
879 {
880   gint64 sink_time, src_time;
881
882   if (sq->sink_tainted) {
883     sink_time = sq->sinktime =
884         gst_segment_to_running_time (&sq->sink_segment, GST_FORMAT_TIME,
885         sq->sink_segment.position);
886
887     if (G_UNLIKELY (sink_time != GST_CLOCK_TIME_NONE))
888       /* if we have a time, we become untainted and use the time */
889       sq->sink_tainted = FALSE;
890   } else
891     sink_time = sq->sinktime;
892
893   if (sq->src_tainted) {
894     src_time = sq->srctime =
895         gst_segment_to_running_time (&sq->src_segment, GST_FORMAT_TIME,
896         sq->src_segment.position);
897     /* if we have a time, we become untainted and use the time */
898     if (G_UNLIKELY (src_time != GST_CLOCK_TIME_NONE))
899       sq->src_tainted = FALSE;
900   } else
901     src_time = sq->srctime;
902
903   GST_DEBUG_OBJECT (mq,
904       "queue %d, sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT, sq->id,
905       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
906
907   /* This allows for streams with out of order timestamping - sometimes the
908    * emerging timestamp is later than the arriving one(s) */
909   if (G_LIKELY (sink_time != -1 && src_time != -1 && sink_time > src_time))
910     sq->cur_time = sink_time - src_time;
911   else
912     sq->cur_time = 0;
913
914   /* updating the time level can change the buffering state */
915   update_buffering (mq, sq);
916
917   return;
918 }
919
920 /* take a SEGMENT event and apply the values to segment, updating the time
921  * level of queue. */
922 static void
923 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
924     GstSegment * segment)
925 {
926   gst_event_copy_segment (event, segment);
927
928   /* now configure the values, we use these to track timestamps on the
929    * sinkpad. */
930   if (segment->format != GST_FORMAT_TIME) {
931     /* non-time format, pretent the current time segment is closed with a
932      * 0 start and unknown stop time. */
933     segment->format = GST_FORMAT_TIME;
934     segment->start = 0;
935     segment->stop = -1;
936     segment->time = 0;
937   }
938   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
939
940   if (segment == &sq->sink_segment)
941     sq->sink_tainted = TRUE;
942   else
943     sq->src_tainted = TRUE;
944
945   GST_DEBUG_OBJECT (mq,
946       "queue %d, configured SEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
947
948   /* segment can update the time level of the queue */
949   update_time_level (mq, sq);
950
951   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
952 }
953
954 /* take a buffer and update segment, updating the time level of the queue. */
955 static void
956 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
957     GstClockTime duration, GstSegment * segment)
958 {
959   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
960
961   /* if no timestamp is set, assume it's continuous with the previous 
962    * time */
963   if (timestamp == GST_CLOCK_TIME_NONE)
964     timestamp = segment->position;
965
966   /* add duration */
967   if (duration != GST_CLOCK_TIME_NONE)
968     timestamp += duration;
969
970   GST_DEBUG_OBJECT (mq, "queue %d, position updated to %" GST_TIME_FORMAT,
971       sq->id, GST_TIME_ARGS (timestamp));
972
973   segment->position = timestamp;
974
975   if (segment == &sq->sink_segment)
976     sq->sink_tainted = TRUE;
977   else
978     sq->src_tainted = TRUE;
979
980   /* calc diff with other end */
981   update_time_level (mq, sq);
982   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
983 }
984
985 static GstClockTime
986 get_running_time (GstSegment * segment, GstMiniObject * object, gboolean end)
987 {
988   GstClockTime time = GST_CLOCK_TIME_NONE;
989
990   if (GST_IS_BUFFER (object)) {
991     GstBuffer *buf = GST_BUFFER_CAST (object);
992
993     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
994       time = GST_BUFFER_TIMESTAMP (buf);
995       if (end && GST_BUFFER_DURATION_IS_VALID (buf))
996         time += GST_BUFFER_DURATION (buf);
997       if (time > segment->stop)
998         time = segment->stop;
999       time = gst_segment_to_running_time (segment, GST_FORMAT_TIME, time);
1000     }
1001   } else if (GST_IS_BUFFER_LIST (object)) {
1002     GstBufferList *list = GST_BUFFER_LIST_CAST (object);
1003     gint i, n;
1004     GstBuffer *buf;
1005
1006     n = gst_buffer_list_length (list);
1007     for (i = 0; i < n; i++) {
1008       buf = gst_buffer_list_get (list, i);
1009       if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1010         time = GST_BUFFER_TIMESTAMP (buf);
1011         if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1012           time += GST_BUFFER_DURATION (buf);
1013         if (time > segment->stop)
1014           time = segment->stop;
1015         time = gst_segment_to_running_time (segment, GST_FORMAT_TIME, time);
1016         if (!end)
1017           goto done;
1018       } else if (!end) {
1019         goto done;
1020       }
1021     }
1022   } else if (GST_IS_EVENT (object)) {
1023     GstEvent *event = GST_EVENT_CAST (object);
1024
1025     /* For newsegment events return the running time of the start position */
1026     if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
1027       const GstSegment *new_segment;
1028
1029       gst_event_parse_segment (event, &new_segment);
1030       if (new_segment->format == GST_FORMAT_TIME) {
1031         time =
1032             gst_segment_to_running_time (new_segment, GST_FORMAT_TIME,
1033             new_segment->start);
1034       }
1035     }
1036   }
1037
1038 done:
1039   return time;
1040 }
1041
1042 static GstFlowReturn
1043 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
1044     GstMiniObject * object)
1045 {
1046   GstFlowReturn result = GST_FLOW_OK;
1047
1048   if (GST_IS_BUFFER (object)) {
1049     GstBuffer *buffer;
1050     GstClockTime timestamp, duration;
1051
1052     buffer = GST_BUFFER_CAST (object);
1053     timestamp = GST_BUFFER_TIMESTAMP (buffer);
1054     duration = GST_BUFFER_DURATION (buffer);
1055
1056     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
1057
1058     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
1059     gst_data_queue_limits_changed (sq->queue);
1060
1061     GST_DEBUG_OBJECT (mq,
1062         "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
1063         sq->id, buffer, GST_TIME_ARGS (timestamp));
1064
1065     result = gst_pad_push (sq->srcpad, buffer);
1066   } else if (GST_IS_EVENT (object)) {
1067     GstEvent *event;
1068
1069     event = GST_EVENT_CAST (object);
1070
1071     switch (GST_EVENT_TYPE (event)) {
1072       case GST_EVENT_EOS:
1073         result = GST_FLOW_EOS;
1074         break;
1075       case GST_EVENT_SEGMENT:
1076         apply_segment (mq, sq, event, &sq->src_segment);
1077         /* Applying the segment may have made the queue non-full again, unblock it if needed */
1078         gst_data_queue_limits_changed (sq->queue);
1079         break;
1080       default:
1081         break;
1082     }
1083
1084     GST_DEBUG_OBJECT (mq,
1085         "SingleQueue %d : Pushing event %p of type %s",
1086         sq->id, event, GST_EVENT_TYPE_NAME (event));
1087
1088     gst_pad_push_event (sq->srcpad, event);
1089   } else if (GST_IS_QUERY (object)) {
1090     GstQuery *query;
1091     gboolean res;
1092
1093     query = GST_QUERY_CAST (object);
1094
1095     res = gst_pad_peer_query (sq->srcpad, query);
1096
1097     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1098     sq->last_query = res;
1099     g_cond_signal (&sq->query_handled);
1100     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1101   } else {
1102     g_warning ("Unexpected object in singlequeue %d (refcounting problem?)",
1103         sq->id);
1104   }
1105   return result;
1106
1107   /* ERRORS */
1108 }
1109
1110 static GstMiniObject *
1111 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
1112 {
1113   GstMiniObject *res;
1114
1115   res = item->object;
1116   item->object = NULL;
1117
1118   return res;
1119 }
1120
1121 static void
1122 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
1123 {
1124   if (item->object)
1125     gst_mini_object_unref (item->object);
1126   g_slice_free (GstMultiQueueItem, item);
1127 }
1128
1129 /* takes ownership of passed mini object! */
1130 static GstMultiQueueItem *
1131 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
1132 {
1133   GstMultiQueueItem *item;
1134
1135   item = g_slice_new (GstMultiQueueItem);
1136   item->object = object;
1137   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1138   item->posid = curid;
1139
1140   item->size = gst_buffer_get_size (GST_BUFFER_CAST (object));
1141   item->duration = GST_BUFFER_DURATION (object);
1142   if (item->duration == GST_CLOCK_TIME_NONE)
1143     item->duration = 0;
1144   item->visible = TRUE;
1145   return item;
1146 }
1147
1148 static GstMultiQueueItem *
1149 gst_multi_queue_mo_item_new (GstMiniObject * object, guint32 curid)
1150 {
1151   GstMultiQueueItem *item;
1152
1153   item = g_slice_new (GstMultiQueueItem);
1154   item->object = object;
1155   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1156   item->posid = curid;
1157
1158   item->size = 0;
1159   item->duration = 0;
1160   item->visible = FALSE;
1161   return item;
1162 }
1163
1164 /* Each main loop attempts to push buffers until the return value
1165  * is not-linked. not-linked pads are not allowed to push data beyond
1166  * any linked pads, so they don't 'rush ahead of the pack'.
1167  */
1168 static void
1169 gst_multi_queue_loop (GstPad * pad)
1170 {
1171   GstSingleQueue *sq;
1172   GstMultiQueueItem *item;
1173   GstDataQueueItem *sitem;
1174   GstMultiQueue *mq;
1175   GstMiniObject *object = NULL;
1176   guint32 newid;
1177   GstFlowReturn result;
1178   GstClockTime next_time;
1179   gboolean is_buffer;
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   is_buffer = GST_IS_BUFFER (object);
1202
1203   /* Get running time of the item. Events will have GST_CLOCK_TIME_NONE */
1204   next_time = get_running_time (&sq->src_segment, object, TRUE);
1205
1206   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
1207       sq->id, newid, sq->last_oldid);
1208
1209   /* If we're not-linked, we do some extra work because we might need to
1210    * wait before pushing. If we're linked but there's a gap in the IDs,
1211    * or it's the first loop, or we just passed the previous highid, 
1212    * we might need to wake some sleeping pad up, so there's extra work 
1213    * there too */
1214   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1215   if (sq->srcresult == GST_FLOW_NOT_LINKED
1216       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
1217       || sq->last_oldid > mq->highid) {
1218     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
1219         gst_flow_get_name (sq->srcresult));
1220
1221     /* Check again if we're flushing after the lock is taken,
1222      * the flush flag might have been changed in the meantime */
1223     if (sq->flushing) {
1224       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1225       goto out_flushing;
1226     }
1227
1228     /* Update the nextid so other threads know when to wake us up */
1229     sq->nextid = newid;
1230     sq->next_time = next_time;
1231
1232     /* Update the oldid (the last ID we output) for highid tracking */
1233     if (sq->last_oldid != G_MAXUINT32)
1234       sq->oldid = sq->last_oldid;
1235
1236     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1237       /* Go to sleep until it's time to push this buffer */
1238
1239       /* Recompute the highid */
1240       compute_high_id (mq);
1241       /* Recompute the high time */
1242       compute_high_time (mq);
1243
1244       while (((mq->sync_by_running_time && next_time != GST_CLOCK_TIME_NONE &&
1245                   (mq->high_time == GST_CLOCK_TIME_NONE
1246                       || next_time >= mq->high_time))
1247               || (!mq->sync_by_running_time && newid > mq->highid))
1248           && sq->srcresult == GST_FLOW_NOT_LINKED) {
1249
1250         GST_DEBUG_OBJECT (mq,
1251             "queue %d sleeping for not-linked wakeup with "
1252             "newid %u, highid %u, next_time %" GST_TIME_FORMAT
1253             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1254             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1255
1256         /* Wake up all non-linked pads before we sleep */
1257         wake_up_next_non_linked (mq);
1258
1259         mq->numwaiting++;
1260         g_cond_wait (&sq->turn, &mq->qlock);
1261         mq->numwaiting--;
1262
1263         if (sq->flushing) {
1264           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1265           goto out_flushing;
1266         }
1267
1268         /* Recompute the high time */
1269         compute_high_time (mq);
1270
1271         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1272             "wakeup with newid %u, highid %u, next_time %" GST_TIME_FORMAT
1273             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1274             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1275       }
1276
1277       /* Re-compute the high_id in case someone else pushed */
1278       compute_high_id (mq);
1279     } else {
1280       compute_high_id (mq);
1281       /* Wake up all non-linked pads */
1282       wake_up_next_non_linked (mq);
1283     }
1284     /* We're done waiting, we can clear the nextid and nexttime */
1285     sq->nextid = 0;
1286     sq->next_time = GST_CLOCK_TIME_NONE;
1287   }
1288   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1289
1290   if (sq->flushing)
1291     goto out_flushing;
1292
1293   GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s",
1294       gst_flow_get_name (sq->srcresult));
1295
1296   /* Update time stats */
1297   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1298   next_time = get_running_time (&sq->src_segment, object, FALSE);
1299   if (next_time != GST_CLOCK_TIME_NONE) {
1300     if (sq->last_time == GST_CLOCK_TIME_NONE || sq->last_time < next_time)
1301       sq->last_time = next_time;
1302     if (mq->high_time == GST_CLOCK_TIME_NONE || mq->high_time <= next_time) {
1303       /* Wake up all non-linked pads now that we advanced the high time */
1304       mq->high_time = next_time;
1305       wake_up_next_non_linked (mq);
1306     }
1307   }
1308   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1309
1310   /* Try to push out the new object */
1311   result = gst_single_queue_push_one (mq, sq, object);
1312   object = NULL;
1313
1314   /* Check if we pushed something already and if this is
1315    * now a switch from an active to a non-active stream.
1316    *
1317    * If it is, we reset all the waiting streams, let them
1318    * push another buffer to see if they're now active again.
1319    * This allows faster switching between streams and prevents
1320    * deadlocks if downstream does any waiting too.
1321    */
1322   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1323   if (sq->pushed && sq->srcresult == GST_FLOW_OK
1324       && result == GST_FLOW_NOT_LINKED) {
1325     GList *tmp;
1326
1327     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
1328         sq->id);
1329
1330     compute_high_id (mq);
1331
1332     /* maybe no-one is waiting */
1333     if (mq->numwaiting > 0) {
1334       /* Else figure out which singlequeue(s) need waking up */
1335       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1336         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1337
1338         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
1339           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
1340           sq2->pushed = FALSE;
1341           sq2->srcresult = GST_FLOW_OK;
1342           g_cond_signal (&sq2->turn);
1343         }
1344       }
1345     }
1346   }
1347
1348   if (is_buffer)
1349     sq->pushed = TRUE;
1350   sq->srcresult = result;
1351   sq->last_oldid = newid;
1352   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1353
1354   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
1355       && result != GST_FLOW_EOS)
1356     goto out_flushing;
1357
1358   GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s",
1359       gst_flow_get_name (sq->srcresult));
1360
1361   return;
1362
1363 out_flushing:
1364   {
1365     if (object)
1366       gst_mini_object_unref (object);
1367
1368     /* Need to make sure wake up any sleeping pads when we exit */
1369     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1370     compute_high_time (mq);
1371     compute_high_id (mq);
1372     wake_up_next_non_linked (mq);
1373     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1374
1375     /* upstream needs to see fatal result ASAP to shut things down,
1376      * but might be stuck in one of our other full queues;
1377      * so empty this one and trigger dynamic queue growth. At
1378      * this point the srcresult is not OK, NOT_LINKED
1379      * or EOS, i.e. a real failure */
1380     gst_data_queue_flush (sq->queue);
1381     single_queue_underrun_cb (sq->queue, sq);
1382     gst_data_queue_set_flushing (sq->queue, TRUE);
1383     gst_pad_pause_task (sq->srcpad);
1384     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
1385         "SingleQueue[%d] task paused, reason:%s",
1386         sq->id, gst_flow_get_name (sq->srcresult));
1387     return;
1388   }
1389 }
1390
1391 /**
1392  * gst_multi_queue_chain:
1393  *
1394  * This is similar to GstQueue's chain function, except:
1395  * _ we don't have leak behaviours,
1396  * _ we push with a unique id (curid)
1397  */
1398 static GstFlowReturn
1399 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1400 {
1401   GstSingleQueue *sq;
1402   GstMultiQueue *mq;
1403   GstMultiQueueItem *item;
1404   guint32 curid;
1405   GstClockTime timestamp, duration;
1406
1407   sq = gst_pad_get_element_private (pad);
1408   mq = sq->mqueue;
1409
1410   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1411   if (sq->is_eos)
1412     goto was_eos;
1413
1414   /* Get a unique incrementing id */
1415   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1416
1417   GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d",
1418       sq->id, buffer, curid);
1419
1420   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
1421
1422   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1423   duration = GST_BUFFER_DURATION (buffer);
1424
1425   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1426     goto flushing;
1427
1428   /* update time level, we must do this after pushing the data in the queue so
1429    * that we never end up filling the queue first. */
1430   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
1431
1432 done:
1433   return sq->srcresult;
1434
1435   /* ERRORS */
1436 flushing:
1437   {
1438     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1439         sq->id, gst_flow_get_name (sq->srcresult));
1440     gst_multi_queue_item_destroy (item);
1441     goto done;
1442   }
1443 was_eos:
1444   {
1445     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
1446     gst_buffer_unref (buffer);
1447     return GST_FLOW_EOS;
1448   }
1449 }
1450
1451 static gboolean
1452 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
1453     GstPadMode mode, gboolean active)
1454 {
1455   gboolean res;
1456   GstSingleQueue *sq;
1457   GstMultiQueue *mq;
1458
1459   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1460   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
1461
1462   /* mq is NULL if the pad is activated/deactivated before being
1463    * added to the multiqueue */
1464   if (mq)
1465     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1466
1467   switch (mode) {
1468     case GST_PAD_MODE_PUSH:
1469       if (active) {
1470         /* All pads start off linked until they push one buffer */
1471         sq->srcresult = GST_FLOW_OK;
1472         sq->pushed = FALSE;
1473       } else {
1474         sq->srcresult = GST_FLOW_FLUSHING;
1475         gst_data_queue_flush (sq->queue);
1476       }
1477       res = TRUE;
1478       break;
1479     default:
1480       res = FALSE;
1481       break;
1482   }
1483
1484   if (mq) {
1485     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1486     gst_object_unref (mq);
1487   }
1488
1489   return res;
1490 }
1491
1492 static gboolean
1493 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1494 {
1495   GstSingleQueue *sq;
1496   GstMultiQueue *mq;
1497   guint32 curid;
1498   GstMultiQueueItem *item;
1499   gboolean res;
1500   GstEventType type;
1501   GstEvent *sref = NULL;
1502
1503   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1504   mq = (GstMultiQueue *) parent;
1505
1506   type = GST_EVENT_TYPE (event);
1507
1508   switch (type) {
1509     case GST_EVENT_FLUSH_START:
1510       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
1511           sq->id);
1512
1513       res = gst_pad_push_event (sq->srcpad, event);
1514
1515       gst_single_queue_flush (mq, sq, TRUE);
1516       goto done;
1517
1518     case GST_EVENT_FLUSH_STOP:
1519       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
1520           sq->id);
1521
1522       res = gst_pad_push_event (sq->srcpad, event);
1523
1524       gst_single_queue_flush (mq, sq, FALSE);
1525       goto done;
1526     case GST_EVENT_SEGMENT:
1527       /* take ref because the queue will take ownership and we need the event
1528        * afterwards to update the segment */
1529       sref = gst_event_ref (event);
1530       break;
1531
1532     default:
1533       if (!(GST_EVENT_IS_SERIALIZED (event))) {
1534         res = gst_pad_push_event (sq->srcpad, event);
1535         goto done;
1536       }
1537       break;
1538   }
1539
1540   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1541   if (sq->is_eos)
1542     goto was_eos;
1543
1544   /* Get an unique incrementing id. */
1545   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1546
1547   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
1548
1549   GST_DEBUG_OBJECT (mq,
1550       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
1551       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
1552
1553   if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1554     goto flushing;
1555
1556   /* mark EOS when we received one, we must do that after putting the
1557    * buffer in the queue because EOS marks the buffer as filled. No need to take
1558    * a lock, the _check_full happens from this thread only, right before pushing
1559    * into dataqueue. */
1560   switch (type) {
1561     case GST_EVENT_EOS:
1562       sq->is_eos = TRUE;
1563       /* EOS affects the buffering state */
1564       update_buffering (mq, sq);
1565       single_queue_overrun_cb (sq->queue, sq);
1566       break;
1567     case GST_EVENT_SEGMENT:
1568       apply_segment (mq, sq, sref, &sq->sink_segment);
1569       gst_event_unref (sref);
1570       break;
1571     default:
1572       break;
1573   }
1574 done:
1575   return res;
1576
1577 flushing:
1578   {
1579     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1580         sq->id, gst_flow_get_name (sq->srcresult));
1581     if (sref)
1582       gst_event_unref (sref);
1583     gst_multi_queue_item_destroy (item);
1584     goto done;
1585   }
1586 was_eos:
1587   {
1588     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return FALSE");
1589     gst_event_unref (event);
1590     res = FALSE;
1591     goto done;
1592   }
1593 }
1594
1595 static gboolean
1596 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1597 {
1598   gboolean res;
1599   GstSingleQueue *sq;
1600   GstMultiQueue *mq;
1601
1602   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1603   mq = (GstMultiQueue *) parent;
1604
1605   switch (GST_QUERY_TYPE (query)) {
1606     default:
1607       if (GST_QUERY_IS_SERIALIZED (query)) {
1608         guint32 curid;
1609         GstMultiQueueItem *item;
1610
1611         /* Get an unique incrementing id. */
1612         curid = g_atomic_int_add ((gint *) & mq->counter, 1);
1613
1614         item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
1615
1616         GST_DEBUG_OBJECT (mq,
1617             "SingleQueue %d : Enqueuing query %p of type %s with id %d",
1618             sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
1619
1620         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1621         res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
1622         g_cond_wait (&sq->query_handled, &mq->qlock);
1623         res = sq->last_query;
1624         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1625       } else {
1626         /* default handling */
1627         res = gst_pad_query_default (pad, parent, query);
1628       }
1629       break;
1630   }
1631   return res;
1632 }
1633
1634 static gboolean
1635 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
1636     GstPadMode mode, gboolean active)
1637 {
1638   GstMultiQueue *mq;
1639   GstSingleQueue *sq;
1640   gboolean result;
1641
1642   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1643   mq = sq->mqueue;
1644
1645   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
1646
1647   switch (mode) {
1648     case GST_PAD_MODE_PUSH:
1649       if (active) {
1650         result = gst_single_queue_flush (mq, sq, FALSE);
1651       } else {
1652         result = gst_single_queue_flush (mq, sq, TRUE);
1653         /* make sure streaming finishes */
1654         result |= gst_pad_stop_task (pad);
1655       }
1656       break;
1657     default:
1658       result = FALSE;
1659       break;
1660   }
1661   return result;
1662 }
1663
1664 static gboolean
1665 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1666 {
1667   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1668
1669   return gst_pad_push_event (sq->sinkpad, event);
1670 }
1671
1672 static gboolean
1673 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1674 {
1675   gboolean res;
1676
1677   /* FIXME, Handle position offset depending on queue size */
1678   switch (GST_QUERY_TYPE (query)) {
1679     default:
1680       /* default handling */
1681       res = gst_pad_query_default (pad, parent, query);
1682       break;
1683   }
1684   return res;
1685 }
1686
1687 /*
1688  * Next-non-linked functions
1689  */
1690
1691 /* WITH LOCK TAKEN */
1692 static void
1693 wake_up_next_non_linked (GstMultiQueue * mq)
1694 {
1695   GList *tmp;
1696
1697   /* maybe no-one is waiting */
1698   if (mq->numwaiting < 1)
1699     return;
1700
1701   /* Else figure out which singlequeue(s) need waking up */
1702   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1703     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1704
1705     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1706       if ((mq->sync_by_running_time && mq->high_time != GST_CLOCK_TIME_NONE
1707               && sq->next_time != GST_CLOCK_TIME_NONE
1708               && sq->next_time >= mq->high_time)
1709           || (sq->nextid != 0 && sq->nextid <= mq->highid)) {
1710         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
1711         g_cond_signal (&sq->turn);
1712       }
1713     }
1714   }
1715 }
1716
1717 /* WITH LOCK TAKEN */
1718 static void
1719 compute_high_id (GstMultiQueue * mq)
1720 {
1721   /* The high-id is either the highest id among the linked pads, or if all
1722    * pads are not-linked, it's the lowest not-linked pad */
1723   GList *tmp;
1724   guint32 lowest = G_MAXUINT32;
1725   guint32 highid = G_MAXUINT32;
1726
1727   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1728     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1729
1730     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
1731         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
1732
1733     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1734       /* No need to consider queues which are not waiting */
1735       if (sq->nextid == 0) {
1736         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1737         continue;
1738       }
1739
1740       if (sq->nextid < lowest)
1741         lowest = sq->nextid;
1742     } else if (sq->srcresult != GST_FLOW_EOS) {
1743       /* If we don't have a global highid, or the global highid is lower than
1744        * this single queue's last outputted id, store the queue's one, 
1745        * unless the singlequeue is at EOS (srcresult = EOS) */
1746       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
1747         highid = sq->oldid;
1748     }
1749   }
1750
1751   if (highid == G_MAXUINT32 || lowest < highid)
1752     mq->highid = lowest;
1753   else
1754     mq->highid = highid;
1755
1756   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
1757       lowest);
1758 }
1759
1760 /* WITH LOCK TAKEN */
1761 static void
1762 compute_high_time (GstMultiQueue * mq)
1763 {
1764   /* The high-id is either the highest id among the linked pads, or if all
1765    * pads are not-linked, it's the lowest not-linked pad */
1766   GList *tmp;
1767   GstClockTime highest = GST_CLOCK_TIME_NONE;
1768   GstClockTime lowest = GST_CLOCK_TIME_NONE;
1769
1770   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1771     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1772
1773     GST_LOG_OBJECT (mq,
1774         "inspecting sq:%d , next_time:%" GST_TIME_FORMAT ", last_time:%"
1775         GST_TIME_FORMAT ", srcresult:%s", sq->id, GST_TIME_ARGS (sq->next_time),
1776         GST_TIME_ARGS (sq->last_time), gst_flow_get_name (sq->srcresult));
1777
1778     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1779       /* No need to consider queues which are not waiting */
1780       if (sq->next_time == GST_CLOCK_TIME_NONE) {
1781         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1782         continue;
1783       }
1784
1785       if (lowest == GST_CLOCK_TIME_NONE || sq->next_time < lowest)
1786         lowest = sq->next_time;
1787     } else if (sq->srcresult != GST_FLOW_EOS) {
1788       /* If we don't have a global highid, or the global highid is lower than
1789        * this single queue's last outputted id, store the queue's one, 
1790        * unless the singlequeue is at EOS (srcresult = EOS) */
1791       if (highest == GST_CLOCK_TIME_NONE || sq->last_time > highest)
1792         highest = sq->last_time;
1793     }
1794   }
1795
1796   mq->high_time = highest;
1797
1798   GST_LOG_OBJECT (mq,
1799       "High time is now : %" GST_TIME_FORMAT ", lowest non-linked %"
1800       GST_TIME_FORMAT, GST_TIME_ARGS (mq->high_time), GST_TIME_ARGS (lowest));
1801 }
1802
1803 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
1804      ((q)->max_size.format) <= (value))
1805
1806 /*
1807  * GstSingleQueue functions
1808  */
1809 static void
1810 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1811 {
1812   GstMultiQueue *mq = sq->mqueue;
1813   GList *tmp;
1814   GstDataQueueSize size;
1815   gboolean filled = FALSE;
1816
1817   gst_data_queue_get_level (sq->queue, &size);
1818
1819   GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id);
1820
1821   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1822   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1823     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1824     GstDataQueueSize ssize;
1825
1826     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
1827
1828     if (gst_data_queue_is_empty (oq->queue)) {
1829       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
1830       if (IS_FILLED (sq, visible, size.visible)) {
1831         sq->max_size.visible = size.visible + 1;
1832         GST_DEBUG_OBJECT (mq,
1833             "Another queue is empty, bumping single queue %d max visible to %d",
1834             sq->id, sq->max_size.visible);
1835       }
1836     }
1837     /* check if we reached the hard time/bytes limits */
1838     gst_data_queue_get_level (oq->queue, &ssize);
1839
1840     GST_DEBUG_OBJECT (mq,
1841         "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1842         G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible,
1843         ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time);
1844
1845     /* if this queue is filled completely we must signal overrun.
1846      * FIXME, this seems wrong in many ways
1847      *  - we're comparing the filled level of this queue against the
1848      *    values of the other one
1849      *  - we should only do this after we found no empty queues, ie, move
1850      *    this check outside of the loop
1851      *  - the debug statement talks about a different queue than the one
1852      *    we are checking here.
1853      */
1854     if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) ||
1855         IS_FILLED (sq, time, sq->cur_time)) {
1856       GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id);
1857       filled = TRUE;
1858     }
1859   }
1860   /* no queues were empty */
1861   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1862
1863   /* Overrun is always forwarded, since this is blocking the upstream element */
1864   if (filled) {
1865     GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun");
1866     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
1867   }
1868
1869   return;
1870 }
1871
1872 static void
1873 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1874 {
1875   gboolean empty = TRUE;
1876   GstMultiQueue *mq = sq->mqueue;
1877   GList *tmp;
1878
1879   GST_LOG_OBJECT (mq,
1880       "Single Queue %d is empty, Checking other single queues", sq->id);
1881
1882   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1883   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1884     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1885
1886     if (gst_data_queue_is_full (oq->queue)) {
1887       GstDataQueueSize size;
1888
1889       gst_data_queue_get_level (oq->queue, &size);
1890       if (IS_FILLED (oq, visible, size.visible)) {
1891         oq->max_size.visible = size.visible + 1;
1892         GST_DEBUG_OBJECT (mq,
1893             "queue %d is filled, bumping its max visible to %d", oq->id,
1894             oq->max_size.visible);
1895         gst_data_queue_limits_changed (oq->queue);
1896       }
1897     }
1898     if (!gst_data_queue_is_empty (oq->queue))
1899       empty = FALSE;
1900   }
1901   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1902
1903   if (empty) {
1904     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
1905     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
1906   }
1907 }
1908
1909 static gboolean
1910 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
1911     guint64 time, GstSingleQueue * sq)
1912 {
1913   gboolean res;
1914   GstMultiQueue *mq = sq->mqueue;
1915
1916   GST_DEBUG_OBJECT (mq,
1917       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1918       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
1919       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1920
1921   /* we are always filled on EOS */
1922   if (sq->is_eos)
1923     return TRUE;
1924
1925   /* we never go past the max visible items unless we are in buffering mode */
1926   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
1927     return TRUE;
1928
1929   /* check time or bytes */
1930   res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
1931
1932   return res;
1933 }
1934
1935 static void
1936 gst_single_queue_free (GstSingleQueue * sq)
1937 {
1938   /* DRAIN QUEUE */
1939   gst_data_queue_flush (sq->queue);
1940   g_object_unref (sq->queue);
1941   g_cond_clear (&sq->turn);
1942   g_cond_clear (&sq->query_handled);
1943   g_free (sq);
1944 }
1945
1946 static GstSingleQueue *
1947 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
1948 {
1949   GstSingleQueue *sq;
1950   gchar *name;
1951   GList *tmp;
1952   guint temp_id = (id == -1) ? 0 : id;
1953
1954   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1955
1956   /* Find an unused queue ID, if possible the passed one */
1957   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1958     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1959     /* This works because the IDs are sorted in ascending order */
1960     if (sq2->id == temp_id) {
1961       /* If this ID was requested by the caller return NULL,
1962        * otherwise just get us the next one */
1963       if (id == -1)
1964         temp_id = sq2->id + 1;
1965       else
1966         return NULL;
1967     } else if (sq2->id > temp_id) {
1968       break;
1969     }
1970   }
1971
1972   sq = g_new0 (GstSingleQueue, 1);
1973   mqueue->nbqueues++;
1974   sq->id = temp_id;
1975
1976   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
1977   mqueue->queues_cookie++;
1978
1979   /* copy over max_size and extra_size so we don't need to take the lock
1980    * any longer when checking if the queue is full. */
1981   sq->max_size.visible = mqueue->max_size.visible;
1982   sq->max_size.bytes = mqueue->max_size.bytes;
1983   sq->max_size.time = mqueue->max_size.time;
1984
1985   sq->extra_size.visible = mqueue->extra_size.visible;
1986   sq->extra_size.bytes = mqueue->extra_size.bytes;
1987   sq->extra_size.time = mqueue->extra_size.time;
1988
1989   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
1990
1991   sq->mqueue = mqueue;
1992   sq->srcresult = GST_FLOW_FLUSHING;
1993   sq->pushed = FALSE;
1994   sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction)
1995       single_queue_check_full,
1996       (GstDataQueueFullCallback) single_queue_overrun_cb,
1997       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
1998   sq->is_eos = FALSE;
1999   sq->flushing = FALSE;
2000   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
2001   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
2002
2003   sq->nextid = 0;
2004   sq->oldid = 0;
2005   sq->next_time = GST_CLOCK_TIME_NONE;
2006   sq->last_time = GST_CLOCK_TIME_NONE;
2007   g_cond_init (&sq->turn);
2008   g_cond_init (&sq->query_handled);
2009
2010   sq->sinktime = GST_CLOCK_TIME_NONE;
2011   sq->srctime = GST_CLOCK_TIME_NONE;
2012   sq->sink_tainted = TRUE;
2013   sq->src_tainted = TRUE;
2014
2015   name = g_strdup_printf ("sink_%u", sq->id);
2016   sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, name);
2017   g_free (name);
2018
2019   gst_pad_set_chain_function (sq->sinkpad,
2020       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
2021   gst_pad_set_activatemode_function (sq->sinkpad,
2022       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
2023   gst_pad_set_event_function (sq->sinkpad,
2024       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
2025   gst_pad_set_query_function (sq->sinkpad,
2026       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
2027   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
2028       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2029   GST_OBJECT_FLAG_SET (sq->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
2030
2031   name = g_strdup_printf ("src_%u", sq->id);
2032   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
2033   g_free (name);
2034
2035   gst_pad_set_activatemode_function (sq->srcpad,
2036       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
2037   gst_pad_set_event_function (sq->srcpad,
2038       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
2039   gst_pad_set_query_function (sq->srcpad,
2040       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
2041   gst_pad_set_iterate_internal_links_function (sq->srcpad,
2042       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2043   GST_OBJECT_FLAG_SET (sq->srcpad, GST_PAD_FLAG_PROXY_CAPS);
2044
2045   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
2046   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
2047
2048   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
2049
2050   /* only activate the pads when we are not in the NULL state
2051    * and add the pad under the state_lock to prevend state changes
2052    * between activating and adding */
2053   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
2054   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
2055     gst_pad_set_active (sq->srcpad, TRUE);
2056     gst_pad_set_active (sq->sinkpad, TRUE);
2057   }
2058   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
2059   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
2060   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
2061
2062   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
2063       sq->id);
2064
2065   return sq;
2066 }