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