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