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