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