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