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