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