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