1596670416c2eff44c55b307a04ca7990158d1a4
[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., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, 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
140   /* segments */
141   GstSegment sink_segment;
142   GstSegment src_segment;
143
144   /* position of src/sink */
145   GstClockTime sinktime, srctime;
146   /* TRUE if either position needs to be recalculated */
147   gboolean sink_tainted, src_tainted;
148
149   /* queue of data */
150   GstDataQueue *queue;
151   GstDataQueueSize max_size, extra_size;
152   GstClockTime cur_time;
153   gboolean is_eos;
154   gboolean flushing;
155
156   /* Protected by global lock */
157   guint32 nextid;               /* ID of the next object waiting to be pushed */
158   guint32 oldid;                /* ID of the last object pushed (last in a series) */
159   guint32 last_oldid;           /* Previously observed old_id, reset to MAXUINT32 on flush */
160   GstClockTime next_time;       /* End running time of next buffer to be pushed */
161   GstClockTime last_time;       /* Start running time of last pushed buffer */
162   GCond *turn;                  /* SingleQueue turn waiting conditional */
163 };
164
165
166 /* Extension of GstDataQueueItem structure for our usage */
167 typedef struct _GstMultiQueueItem GstMultiQueueItem;
168
169 struct _GstMultiQueueItem
170 {
171   GstMiniObject *object;
172   guint size;
173   guint64 duration;
174   gboolean visible;
175
176   GDestroyNotify destroy;
177   guint32 posid;
178 };
179
180 static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue, gint id);
181 static void gst_single_queue_free (GstSingleQueue * squeue);
182
183 static void wake_up_next_non_linked (GstMultiQueue * mq);
184 static void compute_high_id (GstMultiQueue * mq);
185 static void compute_high_time (GstMultiQueue * mq);
186 static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
187 static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
188
189 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink%d",
190     GST_PAD_SINK,
191     GST_PAD_REQUEST,
192     GST_STATIC_CAPS_ANY);
193
194 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src%d",
195     GST_PAD_SRC,
196     GST_PAD_SOMETIMES,
197     GST_STATIC_CAPS_ANY);
198
199 GST_DEBUG_CATEGORY_STATIC (multi_queue_debug);
200 #define GST_CAT_DEFAULT (multi_queue_debug)
201
202 /* Signals and args */
203 enum
204 {
205   SIGNAL_UNDERRUN,
206   SIGNAL_OVERRUN,
207   LAST_SIGNAL
208 };
209
210 /* default limits, we try to keep up to 2 seconds of data and if there is not
211  * time, up to 10 MB. The number of buffers is dynamically scaled to make sure
212  * there is data in the queues. Normally, the byte and time limits are not hit
213  * in theses conditions. */
214 #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */
215 #define DEFAULT_MAX_SIZE_BUFFERS 5
216 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND
217
218 /* second limits. When we hit one of the above limits we are probably dealing
219  * with a badly muxed file and we scale the limits to these emergency values.
220  * This is currently not yet implemented.
221  * Since we dynamically scale the queue buffer size up to the limits but avoid
222  * going above the max-size-buffers when we can, we don't really need this
223  * aditional extra size. */
224 #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024       /* 10 MB */
225 #define DEFAULT_EXTRA_SIZE_BUFFERS 5
226 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND
227
228 #define DEFAULT_USE_BUFFERING FALSE
229 #define DEFAULT_LOW_PERCENT   10
230 #define DEFAULT_HIGH_PERCENT  99
231 #define DEFAULT_SYNC_BY_RUNNING_TIME FALSE
232
233 enum
234 {
235   PROP_0,
236   PROP_EXTRA_SIZE_BYTES,
237   PROP_EXTRA_SIZE_BUFFERS,
238   PROP_EXTRA_SIZE_TIME,
239   PROP_MAX_SIZE_BYTES,
240   PROP_MAX_SIZE_BUFFERS,
241   PROP_MAX_SIZE_TIME,
242   PROP_USE_BUFFERING,
243   PROP_LOW_PERCENT,
244   PROP_HIGH_PERCENT,
245   PROP_SYNC_BY_RUNNING_TIME,
246   PROP_LAST
247 };
248
249 #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
250   g_mutex_lock (q->qlock);                                              \
251 } G_STMT_END
252
253 #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
254   g_mutex_unlock (q->qlock);                                            \
255 } G_STMT_END
256
257 static void gst_multi_queue_finalize (GObject * object);
258 static void gst_multi_queue_set_property (GObject * object,
259     guint prop_id, const GValue * value, GParamSpec * pspec);
260 static void gst_multi_queue_get_property (GObject * object,
261     guint prop_id, GValue * value, GParamSpec * pspec);
262
263 static GstPad *gst_multi_queue_request_new_pad (GstElement * element,
264     GstPadTemplate * temp, const gchar * name);
265 static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad);
266 static GstStateChangeReturn gst_multi_queue_change_state (GstElement *
267     element, GstStateChange transition);
268
269 static void gst_multi_queue_loop (GstPad * pad);
270
271 #define _do_init(bla) \
272   GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element");
273
274 GST_BOILERPLATE_FULL (GstMultiQueue, gst_multi_queue, GstElement,
275     GST_TYPE_ELEMENT, _do_init);
276
277 static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 };
278
279 static void
280 gst_multi_queue_base_init (gpointer g_class)
281 {
282   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
283
284   gst_element_class_set_details_simple (gstelement_class,
285       "MultiQueue",
286       "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>");
287   gst_element_class_add_pad_template (gstelement_class,
288       gst_static_pad_template_get (&sinktemplate));
289   gst_element_class_add_pad_template (gstelement_class,
290       gst_static_pad_template_get (&srctemplate));
291 }
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    * Since: 0.10.26
377    */
378   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
379       g_param_spec_boolean ("use-buffering", "Use buffering",
380           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
381           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
382   /**
383    * GstMultiQueue:low-percent
384    * 
385    * Low threshold percent for buffering to start.
386    *
387    * Since: 0.10.26
388    */
389   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
390       g_param_spec_int ("low-percent", "Low percent",
391           "Low threshold for buffering to start", 0, 100,
392           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
393   /**
394    * GstMultiQueue:high-percent
395    * 
396    * High threshold percent for buffering to finish.
397    *
398    * Since: 0.10.26
399    */
400   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
401       g_param_spec_int ("high-percent", "High percent",
402           "High threshold for buffering to finish", 0, 100,
403           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
404
405   /**
406    * GstMultiQueue:sync-by-running-time
407    * 
408    * If enabled multiqueue will synchronize deactivated or not-linked streams
409    * to the activated and linked streams by taking the running time.
410    * Otherwise multiqueue will synchronize the deactivated or not-linked
411    * streams by keeping the order in which buffers and events arrived compared
412    * to active and linked streams.
413    *
414    * Since: 0.10.35
415    */
416   g_object_class_install_property (gobject_class, PROP_SYNC_BY_RUNNING_TIME,
417       g_param_spec_boolean ("sync-by-running-time", "Sync By Running Time",
418           "Synchronize deactivated or not-linked streams by running time",
419           DEFAULT_SYNC_BY_RUNNING_TIME,
420           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
421
422   gobject_class->finalize = gst_multi_queue_finalize;
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, GstMultiQueueClass * klass)
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   mqueue->qlock = g_mutex_new ();
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_free (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       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
499       mq->max_size.visible = g_value_get_uint (value);
500       SET_CHILD_PROPERTY (mq, visible);
501       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
502       break;
503     case PROP_MAX_SIZE_TIME:
504       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
505       mq->max_size.time = g_value_get_uint64 (value);
506       SET_CHILD_PROPERTY (mq, time);
507       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
508       break;
509     case PROP_EXTRA_SIZE_BYTES:
510       mq->extra_size.bytes = g_value_get_uint (value);
511       break;
512     case PROP_EXTRA_SIZE_BUFFERS:
513       mq->extra_size.visible = g_value_get_uint (value);
514       break;
515     case PROP_EXTRA_SIZE_TIME:
516       mq->extra_size.time = g_value_get_uint64 (value);
517       break;
518     case PROP_USE_BUFFERING:
519       mq->use_buffering = g_value_get_boolean (value);
520       break;
521     case PROP_LOW_PERCENT:
522       mq->low_percent = g_value_get_int (value);
523       break;
524     case PROP_HIGH_PERCENT:
525       mq->high_percent = g_value_get_int (value);
526       break;
527     case PROP_SYNC_BY_RUNNING_TIME:
528       mq->sync_by_running_time = g_value_get_boolean (value);
529       break;
530     default:
531       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
532       break;
533   }
534 }
535
536 static void
537 gst_multi_queue_get_property (GObject * object, guint prop_id,
538     GValue * value, GParamSpec * pspec)
539 {
540   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
541
542   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
543
544   switch (prop_id) {
545     case PROP_EXTRA_SIZE_BYTES:
546       g_value_set_uint (value, mq->extra_size.bytes);
547       break;
548     case PROP_EXTRA_SIZE_BUFFERS:
549       g_value_set_uint (value, mq->extra_size.visible);
550       break;
551     case PROP_EXTRA_SIZE_TIME:
552       g_value_set_uint64 (value, mq->extra_size.time);
553       break;
554     case PROP_MAX_SIZE_BYTES:
555       g_value_set_uint (value, mq->max_size.bytes);
556       break;
557     case PROP_MAX_SIZE_BUFFERS:
558       g_value_set_uint (value, mq->max_size.visible);
559       break;
560     case PROP_MAX_SIZE_TIME:
561       g_value_set_uint64 (value, mq->max_size.time);
562       break;
563     case PROP_USE_BUFFERING:
564       g_value_set_boolean (value, mq->use_buffering);
565       break;
566     case PROP_LOW_PERCENT:
567       g_value_set_int (value, mq->low_percent);
568       break;
569     case PROP_HIGH_PERCENT:
570       g_value_set_int (value, mq->high_percent);
571       break;
572     case PROP_SYNC_BY_RUNNING_TIME:
573       g_value_set_boolean (value, mq->sync_by_running_time);
574       break;
575     default:
576       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
577       break;
578   }
579
580   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
581 }
582
583 static GstIterator *
584 gst_multi_queue_iterate_internal_links (GstPad * pad)
585 {
586   GstIterator *it = NULL;
587   GstPad *opad;
588   GstSingleQueue *squeue;
589   GstMultiQueue *mq = GST_MULTI_QUEUE (gst_pad_get_parent (pad));
590
591   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
592   squeue = gst_pad_get_element_private (pad);
593   if (!squeue)
594     goto out;
595
596   if (squeue->sinkpad == pad)
597     opad = gst_object_ref (squeue->srcpad);
598   else if (squeue->srcpad == pad)
599     opad = gst_object_ref (squeue->sinkpad);
600   else
601     goto out;
602
603   it = gst_iterator_new_single (GST_TYPE_PAD, opad,
604       (GstCopyFunction) gst_object_ref, (GFreeFunc) gst_object_unref);
605
606   gst_object_unref (opad);
607
608 out:
609   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
610   gst_object_unref (mq);
611
612   return it;
613 }
614
615
616 /*
617  * GstElement methods
618  */
619
620 static GstPad *
621 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
622     const gchar * name)
623 {
624   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
625   GstSingleQueue *squeue;
626   gint temp_id = -1;
627
628   if (name) {
629     sscanf (name + 4, "%d", &temp_id);
630     GST_LOG_OBJECT (element, "name : %s (id %d)", GST_STR_NULL (name), temp_id);
631   }
632
633   /* Create a new single queue, add the sink and source pad and return the sink pad */
634   squeue = gst_single_queue_new (mqueue, temp_id);
635
636   GST_DEBUG_OBJECT (mqueue, "Returning pad %s:%s",
637       GST_DEBUG_PAD_NAME (squeue->sinkpad));
638
639   return squeue ? squeue->sinkpad : NULL;
640 }
641
642 static void
643 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
644 {
645   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
646   GstSingleQueue *sq = NULL;
647   GList *tmp;
648
649   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
650
651   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
652   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
653   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
654     sq = (GstSingleQueue *) tmp->data;
655
656     if (sq->sinkpad == pad)
657       break;
658   }
659
660   if (!tmp) {
661     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
662     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
663     return;
664   }
665
666   /* FIXME: The removal of the singlequeue should probably not happen until it
667    * finishes draining */
668
669   /* remove it from the list */
670   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
671   mqueue->queues_cookie++;
672
673   /* FIXME : recompute next-non-linked */
674   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
675
676   /* delete SingleQueue */
677   gst_data_queue_set_flushing (sq->queue, TRUE);
678
679   gst_pad_set_active (sq->srcpad, FALSE);
680   gst_pad_set_active (sq->sinkpad, FALSE);
681   gst_pad_set_element_private (sq->srcpad, NULL);
682   gst_pad_set_element_private (sq->sinkpad, NULL);
683   gst_element_remove_pad (element, sq->srcpad);
684   gst_element_remove_pad (element, sq->sinkpad);
685   gst_single_queue_free (sq);
686 }
687
688 static GstStateChangeReturn
689 gst_multi_queue_change_state (GstElement * element, GstStateChange transition)
690 {
691   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
692   GstSingleQueue *sq = NULL;
693   GstStateChangeReturn result;
694
695   switch (transition) {
696     case GST_STATE_CHANGE_READY_TO_PAUSED:{
697       GList *tmp;
698
699       /* Set all pads to non-flushing */
700       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
701       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
702         sq = (GstSingleQueue *) tmp->data;
703         sq->flushing = FALSE;
704       }
705       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
706       break;
707     }
708     case GST_STATE_CHANGE_PAUSED_TO_READY:{
709       GList *tmp;
710
711       /* Un-wait all waiting pads */
712       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
713       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
714         sq = (GstSingleQueue *) tmp->data;
715         sq->flushing = TRUE;
716         g_cond_signal (sq->turn);
717       }
718       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
719       break;
720     }
721     default:
722       break;
723   }
724
725   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
726
727   switch (transition) {
728     default:
729       break;
730   }
731
732   return result;
733
734
735
736 }
737
738 static gboolean
739 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush)
740 {
741   gboolean result;
742
743   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
744       sq->id);
745
746   if (flush) {
747     sq->srcresult = GST_FLOW_WRONG_STATE;
748     gst_data_queue_set_flushing (sq->queue, TRUE);
749
750     sq->flushing = TRUE;
751
752     /* wake up non-linked task */
753     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
754         sq->id);
755     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
756     g_cond_signal (sq->turn);
757     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
758
759     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
760     result = gst_pad_pause_task (sq->srcpad);
761     sq->sink_tainted = sq->src_tainted = TRUE;
762   } else {
763     gst_data_queue_flush (sq->queue);
764     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
765     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
766     /* All pads start off not-linked for a smooth kick-off */
767     sq->srcresult = GST_FLOW_OK;
768     sq->cur_time = 0;
769     sq->max_size.visible = mq->max_size.visible;
770     sq->is_eos = FALSE;
771     sq->nextid = 0;
772     sq->oldid = 0;
773     sq->last_oldid = G_MAXUINT32;
774     sq->next_time = GST_CLOCK_TIME_NONE;
775     sq->last_time = GST_CLOCK_TIME_NONE;
776     gst_data_queue_set_flushing (sq->queue, FALSE);
777
778     /* Reset high time to be recomputed next */
779     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
780     mq->high_time = GST_CLOCK_TIME_NONE;
781     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
782
783     sq->flushing = FALSE;
784
785     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
786     result =
787         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
788         sq->srcpad);
789   }
790   return result;
791 }
792
793 static void
794 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
795 {
796   GstDataQueueSize size;
797   gint percent, tmp;
798   gboolean post = FALSE;
799
800   /* nothing to dowhen we are not in buffering mode */
801   if (!mq->use_buffering)
802     return;
803
804   gst_data_queue_get_level (sq->queue, &size);
805
806   GST_DEBUG_OBJECT (mq,
807       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
808       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
809       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
810
811   /* get bytes and time percentages and take the max */
812   if (sq->is_eos) {
813     percent = 100;
814   } else {
815     percent = 0;
816     if (sq->max_size.time > 0) {
817       tmp = (sq->cur_time * 100) / sq->max_size.time;
818       percent = MAX (percent, tmp);
819     }
820     if (sq->max_size.bytes > 0) {
821       tmp = (size.bytes * 100) / sq->max_size.bytes;
822       percent = MAX (percent, tmp);
823     }
824   }
825
826   if (mq->buffering) {
827     post = TRUE;
828     if (percent >= mq->high_percent) {
829       mq->buffering = FALSE;
830     }
831     /* make sure it increases */
832     percent = MAX (mq->percent, percent);
833
834     if (percent == mq->percent)
835       /* don't post if nothing changed */
836       post = FALSE;
837     else
838       /* else keep last value we posted */
839       mq->percent = percent;
840   } else {
841     if (percent < mq->low_percent) {
842       mq->buffering = TRUE;
843       mq->percent = percent;
844       post = TRUE;
845     }
846   }
847   if (post) {
848     GstMessage *message;
849
850     /* scale to high percent so that it becomes the 100% mark */
851     percent = percent * 100 / mq->high_percent;
852     /* clip */
853     if (percent > 100)
854       percent = 100;
855
856     GST_DEBUG_OBJECT (mq, "buffering %d percent", percent);
857     message = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
858
859     gst_element_post_message (GST_ELEMENT_CAST (mq), message);
860   } else {
861     GST_DEBUG_OBJECT (mq, "filled %d percent", percent);
862   }
863 }
864
865 /* calculate the diff between running time on the sink and src of the queue.
866  * This is the total amount of time in the queue. 
867  * WITH LOCK TAKEN */
868 static void
869 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
870 {
871   gint64 sink_time, src_time;
872
873   if (sq->sink_tainted) {
874     sink_time = sq->sinktime =
875         gst_segment_to_running_time (&sq->sink_segment, GST_FORMAT_TIME,
876         sq->sink_segment.last_stop);
877
878     if (G_UNLIKELY (sink_time != GST_CLOCK_TIME_NONE))
879       /* if we have a time, we become untainted and use the time */
880       sq->sink_tainted = FALSE;
881   } else
882     sink_time = sq->sinktime;
883
884   if (sq->src_tainted) {
885     src_time = sq->srctime =
886         gst_segment_to_running_time (&sq->src_segment, GST_FORMAT_TIME,
887         sq->src_segment.last_stop);
888     /* if we have a time, we become untainted and use the time */
889     if (G_UNLIKELY (src_time != GST_CLOCK_TIME_NONE))
890       sq->src_tainted = FALSE;
891   } else
892     src_time = sq->srctime;
893
894   GST_DEBUG_OBJECT (mq,
895       "queue %d, sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT, sq->id,
896       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
897
898   /* This allows for streams with out of order timestamping - sometimes the
899    * emerging timestamp is later than the arriving one(s) */
900   if (G_LIKELY (sink_time != -1 && src_time != -1 && sink_time > src_time))
901     sq->cur_time = sink_time - src_time;
902   else
903     sq->cur_time = 0;
904
905   /* updating the time level can change the buffering state */
906   update_buffering (mq, sq);
907
908   return;
909 }
910
911 /* take a NEWSEGMENT event and apply the values to segment, updating the time
912  * level of queue. */
913 static void
914 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
915     GstSegment * segment)
916 {
917   gboolean update;
918   GstFormat format;
919   gdouble rate, arate;
920   gint64 start, stop, time;
921
922   gst_event_parse_new_segment_full (event, &update, &rate, &arate,
923       &format, &start, &stop, &time);
924
925   /* now configure the values, we use these to track timestamps on the
926    * sinkpad. */
927   if (format != GST_FORMAT_TIME) {
928     /* non-time format, pretent the current time segment is closed with a
929      * 0 start and unknown stop time. */
930     update = FALSE;
931     format = GST_FORMAT_TIME;
932     start = 0;
933     stop = -1;
934     time = 0;
935   }
936
937   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
938
939   gst_segment_set_newsegment_full (segment, update,
940       rate, arate, format, start, stop, time);
941
942   if (segment == &sq->sink_segment)
943     sq->sink_tainted = TRUE;
944   else
945     sq->src_tainted = TRUE;
946
947   GST_DEBUG_OBJECT (mq,
948       "queue %d, configured NEWSEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
949
950   /* segment can update the time level of the queue */
951   update_time_level (mq, sq);
952
953   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
954 }
955
956 /* take a buffer and update segment, updating the time level of the queue. */
957 static void
958 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
959     GstClockTime duration, GstSegment * segment)
960 {
961   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
962
963   /* if no timestamp is set, assume it's continuous with the previous 
964    * time */
965   if (timestamp == GST_CLOCK_TIME_NONE)
966     timestamp = segment->last_stop;
967
968   /* add duration */
969   if (duration != GST_CLOCK_TIME_NONE)
970     timestamp += duration;
971
972   GST_DEBUG_OBJECT (mq, "queue %d, last_stop updated to %" GST_TIME_FORMAT,
973       sq->id, GST_TIME_ARGS (timestamp));
974
975   gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
976
977   if (segment == &sq->sink_segment)
978     sq->sink_tainted = TRUE;
979   else
980     sq->src_tainted = TRUE;
981
982   /* calc diff with other end */
983   update_time_level (mq, sq);
984   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
985 }
986
987 static GstClockTime
988 get_running_time (GstSegment * segment, GstMiniObject * object, gboolean end)
989 {
990   GstClockTime time = GST_CLOCK_TIME_NONE;
991
992   if (GST_IS_BUFFER (object)) {
993     GstBuffer *buf = GST_BUFFER_CAST (object);
994
995     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
996       time = GST_BUFFER_TIMESTAMP (buf);
997       if (end && GST_BUFFER_DURATION_IS_VALID (buf))
998         time += GST_BUFFER_DURATION (buf);
999       if (time > segment->stop)
1000         time = segment->stop;
1001       time = gst_segment_to_running_time (segment, GST_FORMAT_TIME, time);
1002     }
1003   } else if (GST_IS_BUFFER_LIST (object)) {
1004     GstBufferList *list = GST_BUFFER_LIST_CAST (object);
1005     GstBufferListIterator *it = gst_buffer_list_iterate (list);
1006     GstBuffer *buf;
1007
1008     do {
1009       while ((buf = gst_buffer_list_iterator_next (it))) {
1010         if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1011           time = GST_BUFFER_TIMESTAMP (buf);
1012           if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1013             time += GST_BUFFER_DURATION (buf);
1014           if (time > segment->stop)
1015             time = segment->stop;
1016           time = gst_segment_to_running_time (segment, GST_FORMAT_TIME, time);
1017           if (!end)
1018             goto done;
1019         } else if (!end) {
1020           goto done;
1021         }
1022       }
1023     } while (gst_buffer_list_iterator_next_group (it));
1024   } else if (GST_IS_EVENT (object)) {
1025     GstEvent *event = GST_EVENT_CAST (object);
1026
1027     /* For newsegment events return the running time of the start position */
1028     if (GST_EVENT_TYPE (event) == GST_EVENT_NEWSEGMENT) {
1029       GstSegment new_segment = *segment;
1030       gboolean update;
1031       gdouble rate, applied_rate;
1032       GstFormat format;
1033       gint64 start, stop, position;
1034
1035       gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
1036           &format, &start, &stop, &position);
1037       if (format == GST_FORMAT_TIME) {
1038         gst_segment_set_newsegment_full (&new_segment, update, rate,
1039             applied_rate, format, start, stop, position);
1040
1041         time =
1042             gst_segment_to_running_time (&new_segment, GST_FORMAT_TIME,
1043             new_segment.start);
1044       }
1045     }
1046   }
1047
1048 done:
1049   return time;
1050 }
1051
1052 static GstFlowReturn
1053 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
1054     GstMiniObject * object)
1055 {
1056   GstFlowReturn result = GST_FLOW_OK;
1057
1058   if (GST_IS_BUFFER (object)) {
1059     GstBuffer *buffer;
1060     GstClockTime timestamp, duration;
1061     GstCaps *caps;
1062
1063     buffer = GST_BUFFER_CAST (object);
1064     timestamp = GST_BUFFER_TIMESTAMP (buffer);
1065     duration = GST_BUFFER_DURATION (buffer);
1066     caps = GST_BUFFER_CAPS (buffer);
1067
1068     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
1069
1070     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
1071     gst_data_queue_limits_changed (sq->queue);
1072
1073     GST_DEBUG_OBJECT (mq,
1074         "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
1075         sq->id, buffer, GST_TIME_ARGS (timestamp));
1076
1077     /* Set caps on pad before pushing, this avoids core calling the acceptcaps
1078      * function on the srcpad, which will call acceptcaps upstream, which might
1079      * not accept these caps (anymore). */
1080     if (caps && caps != GST_PAD_CAPS (sq->srcpad))
1081       gst_pad_set_caps (sq->srcpad, caps);
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_UNEXPECTED;
1092         break;
1093       case GST_EVENT_NEWSEGMENT:
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 {
1108     g_warning ("Unexpected object in singlequeue %d (refcounting problem?)",
1109         sq->id);
1110   }
1111   return result;
1112
1113   /* ERRORS */
1114 }
1115
1116 static GstMiniObject *
1117 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
1118 {
1119   GstMiniObject *res;
1120
1121   res = item->object;
1122   item->object = NULL;
1123
1124   return res;
1125 }
1126
1127 static void
1128 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
1129 {
1130   if (item->object)
1131     gst_mini_object_unref (item->object);
1132   g_slice_free (GstMultiQueueItem, item);
1133 }
1134
1135 /* takes ownership of passed mini object! */
1136 static GstMultiQueueItem *
1137 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
1138 {
1139   GstMultiQueueItem *item;
1140
1141   item = g_slice_new (GstMultiQueueItem);
1142   item->object = object;
1143   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1144   item->posid = curid;
1145
1146   item->size = GST_BUFFER_SIZE (object);
1147   item->duration = GST_BUFFER_DURATION (object);
1148   if (item->duration == GST_CLOCK_TIME_NONE)
1149     item->duration = 0;
1150   item->visible = TRUE;
1151   return item;
1152 }
1153
1154 static GstMultiQueueItem *
1155 gst_multi_queue_event_item_new (GstMiniObject * object, guint32 curid)
1156 {
1157   GstMultiQueueItem *item;
1158
1159   item = g_slice_new (GstMultiQueueItem);
1160   item->object = object;
1161   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1162   item->posid = curid;
1163
1164   item->size = 0;
1165   item->duration = 0;
1166   item->visible = FALSE;
1167   return item;
1168 }
1169
1170 /* Each main loop attempts to push buffers until the return value
1171  * is not-linked. not-linked pads are not allowed to push data beyond
1172  * any linked pads, so they don't 'rush ahead of the pack'.
1173  */
1174 static void
1175 gst_multi_queue_loop (GstPad * pad)
1176 {
1177   GstSingleQueue *sq;
1178   GstMultiQueueItem *item;
1179   GstDataQueueItem *sitem;
1180   GstMultiQueue *mq;
1181   GstMiniObject *object = NULL;
1182   guint32 newid;
1183   GstFlowReturn result;
1184   GstClockTime next_time;
1185
1186   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1187   mq = sq->mqueue;
1188
1189   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
1190
1191   if (sq->flushing)
1192     goto out_flushing;
1193
1194   /* Get something from the queue, blocking until that happens, or we get
1195    * flushed */
1196   if (!(gst_data_queue_pop (sq->queue, &sitem)))
1197     goto out_flushing;
1198
1199   item = (GstMultiQueueItem *) sitem;
1200   newid = item->posid;
1201
1202   /* steal the object and destroy the item */
1203   object = gst_multi_queue_item_steal_object (item);
1204   gst_multi_queue_item_destroy (item);
1205
1206   /* Get running time of the item. Events will have GST_CLOCK_TIME_NONE */
1207   next_time = get_running_time (&sq->src_segment, object, TRUE);
1208
1209   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
1210       sq->id, newid, sq->last_oldid);
1211
1212   /* If we're not-linked, we do some extra work because we might need to
1213    * wait before pushing. If we're linked but there's a gap in the IDs,
1214    * or it's the first loop, or we just passed the previous highid, 
1215    * we might need to wake some sleeping pad up, so there's extra work 
1216    * there too */
1217   if (sq->srcresult == GST_FLOW_NOT_LINKED
1218       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
1219       || sq->last_oldid > mq->highid) {
1220     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
1221         gst_flow_get_name (sq->srcresult));
1222
1223     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1224
1225     /* Check again if we're flushing after the lock is taken,
1226      * the flush flag might have been changed in the meantime */
1227     if (sq->flushing) {
1228       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1229       goto out_flushing;
1230     }
1231
1232     /* Update the nextid so other threads know when to wake us up */
1233     sq->nextid = newid;
1234     sq->next_time = next_time;
1235
1236     /* Update the oldid (the last ID we output) for highid tracking */
1237     if (sq->last_oldid != G_MAXUINT32)
1238       sq->oldid = sq->last_oldid;
1239
1240     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1241       /* Go to sleep until it's time to push this buffer */
1242
1243       /* Recompute the highid */
1244       compute_high_id (mq);
1245       /* Recompute the high time */
1246       compute_high_time (mq);
1247
1248       while (((mq->sync_by_running_time && next_time != GST_CLOCK_TIME_NONE &&
1249                   (mq->high_time == GST_CLOCK_TIME_NONE
1250                       || next_time >= mq->high_time))
1251               || (!mq->sync_by_running_time && newid > mq->highid))
1252           && sq->srcresult == GST_FLOW_NOT_LINKED) {
1253
1254         GST_DEBUG_OBJECT (mq,
1255             "queue %d sleeping for not-linked wakeup with "
1256             "newid %u, highid %u, next_time %" GST_TIME_FORMAT
1257             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1258             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1259
1260         /* Wake up all non-linked pads before we sleep */
1261         wake_up_next_non_linked (mq);
1262
1263         mq->numwaiting++;
1264         g_cond_wait (sq->turn, mq->qlock);
1265         mq->numwaiting--;
1266
1267         if (sq->flushing) {
1268           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1269           goto out_flushing;
1270         }
1271
1272         /* Recompute the high time */
1273         compute_high_time (mq);
1274
1275         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1276             "wakeup with newid %u, highid %u, next_time %" GST_TIME_FORMAT
1277             ", high_time %" GST_TIME_FORMAT, sq->id, newid, mq->highid,
1278             GST_TIME_ARGS (next_time), GST_TIME_ARGS (mq->high_time));
1279       }
1280
1281       /* Re-compute the high_id in case someone else pushed */
1282       compute_high_id (mq);
1283     } else {
1284       compute_high_id (mq);
1285       /* Wake up all non-linked pads */
1286       wake_up_next_non_linked (mq);
1287     }
1288     /* We're done waiting, we can clear the nextid and nexttime */
1289     sq->nextid = 0;
1290     sq->next_time = GST_CLOCK_TIME_NONE;
1291
1292     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1293   }
1294
1295   if (sq->flushing)
1296     goto out_flushing;
1297
1298   GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s",
1299       gst_flow_get_name (sq->srcresult));
1300
1301   /* Update time stats */
1302   next_time = get_running_time (&sq->src_segment, object, FALSE);
1303   if (next_time != GST_CLOCK_TIME_NONE) {
1304     if (sq->last_time == GST_CLOCK_TIME_NONE || sq->last_time < next_time)
1305       sq->last_time = next_time;
1306     if (mq->high_time == GST_CLOCK_TIME_NONE || mq->high_time <= next_time) {
1307       /* Wake up all non-linked pads now that we advanced the high time */
1308       mq->high_time = next_time;
1309       wake_up_next_non_linked (mq);
1310     }
1311   }
1312
1313   /* Try to push out the new object */
1314   result = gst_single_queue_push_one (mq, sq, object);
1315   sq->srcresult = result;
1316   object = NULL;
1317
1318   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
1319       && result != GST_FLOW_UNEXPECTED)
1320     goto out_flushing;
1321
1322   GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s",
1323       gst_flow_get_name (sq->srcresult));
1324
1325   sq->last_oldid = newid;
1326
1327   return;
1328
1329 out_flushing:
1330   {
1331     if (object)
1332       gst_mini_object_unref (object);
1333
1334     /* Need to make sure wake up any sleeping pads when we exit */
1335     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1336     compute_high_id (mq);
1337     wake_up_next_non_linked (mq);
1338     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1339
1340     /* upstream needs to see fatal result ASAP to shut things down,
1341      * but might be stuck in one of our other full queues;
1342      * so empty this one and trigger dynamic queue growth. At
1343      * this point the srcresult is not OK, NOT_LINKED
1344      * or UNEXPECTED, i.e. a real failure */
1345     gst_data_queue_flush (sq->queue);
1346     single_queue_underrun_cb (sq->queue, sq);
1347     gst_data_queue_set_flushing (sq->queue, TRUE);
1348     gst_pad_pause_task (sq->srcpad);
1349     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
1350         "SingleQueue[%d] task paused, reason:%s",
1351         sq->id, gst_flow_get_name (sq->srcresult));
1352     return;
1353   }
1354 }
1355
1356 /**
1357  * gst_multi_queue_chain:
1358  *
1359  * This is similar to GstQueue's chain function, except:
1360  * _ we don't have leak behaviours,
1361  * _ we push with a unique id (curid)
1362  */
1363 static GstFlowReturn
1364 gst_multi_queue_chain (GstPad * pad, GstBuffer * buffer)
1365 {
1366   GstSingleQueue *sq;
1367   GstMultiQueue *mq;
1368   GstMultiQueueItem *item;
1369   guint32 curid;
1370   GstClockTime timestamp, duration;
1371
1372   sq = gst_pad_get_element_private (pad);
1373   mq = sq->mqueue;
1374
1375   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1376   if (sq->is_eos)
1377     goto was_eos;
1378
1379   /* Get a unique incrementing id */
1380   curid = G_ATOMIC_INT_ADD ((gint *) & mq->counter, 1);
1381
1382   GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d",
1383       sq->id, buffer, curid);
1384
1385   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
1386
1387   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1388   duration = GST_BUFFER_DURATION (buffer);
1389
1390   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1391     goto flushing;
1392
1393   /* update time level, we must do this after pushing the data in the queue so
1394    * that we never end up filling the queue first. */
1395   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
1396
1397 done:
1398   return sq->srcresult;
1399
1400   /* ERRORS */
1401 flushing:
1402   {
1403     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1404         sq->id, gst_flow_get_name (sq->srcresult));
1405     gst_multi_queue_item_destroy (item);
1406     goto done;
1407   }
1408 was_eos:
1409   {
1410     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return UNEXPECTED");
1411     gst_buffer_unref (buffer);
1412     return GST_FLOW_UNEXPECTED;
1413   }
1414 }
1415
1416 static gboolean
1417 gst_multi_queue_sink_activate_push (GstPad * pad, gboolean active)
1418 {
1419   GstSingleQueue *sq;
1420
1421   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1422
1423   if (active) {
1424     /* All pads start off linked until they push one buffer */
1425     sq->srcresult = GST_FLOW_OK;
1426   } else {
1427     sq->srcresult = GST_FLOW_WRONG_STATE;
1428     gst_data_queue_flush (sq->queue);
1429   }
1430   return TRUE;
1431 }
1432
1433 static gboolean
1434 gst_multi_queue_sink_event (GstPad * pad, GstEvent * event)
1435 {
1436   GstSingleQueue *sq;
1437   GstMultiQueue *mq;
1438   guint32 curid;
1439   GstMultiQueueItem *item;
1440   gboolean res;
1441   GstEventType type;
1442   GstEvent *sref = NULL;
1443
1444   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1445   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
1446
1447   type = GST_EVENT_TYPE (event);
1448
1449   switch (type) {
1450     case GST_EVENT_FLUSH_START:
1451       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
1452           sq->id);
1453
1454       res = gst_pad_push_event (sq->srcpad, event);
1455
1456       gst_single_queue_flush (mq, sq, TRUE);
1457       goto done;
1458
1459     case GST_EVENT_FLUSH_STOP:
1460       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
1461           sq->id);
1462
1463       res = gst_pad_push_event (sq->srcpad, event);
1464
1465       gst_single_queue_flush (mq, sq, FALSE);
1466       goto done;
1467     case GST_EVENT_NEWSEGMENT:
1468       /* take ref because the queue will take ownership and we need the event
1469        * afterwards to update the segment */
1470       sref = gst_event_ref (event);
1471       break;
1472
1473     default:
1474       if (!(GST_EVENT_IS_SERIALIZED (event))) {
1475         res = gst_pad_push_event (sq->srcpad, event);
1476         goto done;
1477       }
1478       break;
1479   }
1480
1481   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1482   if (sq->is_eos)
1483     goto was_eos;
1484
1485   /* Get an unique incrementing id. */
1486   curid = G_ATOMIC_INT_ADD ((gint *) & mq->counter, 1);
1487
1488   item = gst_multi_queue_event_item_new ((GstMiniObject *) event, curid);
1489
1490   GST_DEBUG_OBJECT (mq,
1491       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
1492       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
1493
1494   if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1495     goto flushing;
1496
1497   /* mark EOS when we received one, we must do that after putting the
1498    * buffer in the queue because EOS marks the buffer as filled. No need to take
1499    * a lock, the _check_full happens from this thread only, right before pushing
1500    * into dataqueue. */
1501   switch (type) {
1502     case GST_EVENT_EOS:
1503       sq->is_eos = TRUE;
1504       /* EOS affects the buffering state */
1505       update_buffering (mq, sq);
1506       single_queue_overrun_cb (sq->queue, sq);
1507       break;
1508     case GST_EVENT_NEWSEGMENT:
1509       apply_segment (mq, sq, sref, &sq->sink_segment);
1510       gst_event_unref (sref);
1511       break;
1512     default:
1513       break;
1514   }
1515 done:
1516   gst_object_unref (mq);
1517   return res;
1518
1519 flushing:
1520   {
1521     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1522         sq->id, gst_flow_get_name (sq->srcresult));
1523     if (sref)
1524       gst_event_unref (sref);
1525     gst_multi_queue_item_destroy (item);
1526     goto done;
1527   }
1528 was_eos:
1529   {
1530     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return FALSE");
1531     gst_event_unref (event);
1532     res = FALSE;
1533     goto done;
1534   }
1535 }
1536
1537 static GstCaps *
1538 gst_multi_queue_getcaps (GstPad * pad)
1539 {
1540   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1541   GstPad *otherpad;
1542   GstCaps *result;
1543
1544   otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad;
1545
1546   GST_LOG_OBJECT (otherpad, "Getting caps from the peer of this pad");
1547
1548   result = gst_pad_peer_get_caps (otherpad);
1549   if (result == NULL)
1550     result = gst_caps_new_any ();
1551
1552   return result;
1553 }
1554
1555 static gboolean
1556 gst_multi_queue_acceptcaps (GstPad * pad, GstCaps * caps)
1557 {
1558   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1559   GstPad *otherpad;
1560   gboolean result;
1561
1562   otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad;
1563
1564   GST_LOG_OBJECT (otherpad, "Accept caps from the peer of this pad");
1565
1566   result = gst_pad_peer_accept_caps (otherpad, caps);
1567
1568   return result;
1569 }
1570
1571 static GstFlowReturn
1572 gst_multi_queue_bufferalloc (GstPad * pad, guint64 offset, guint size,
1573     GstCaps * caps, GstBuffer ** buf)
1574 {
1575   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1576
1577   return gst_pad_alloc_buffer (sq->srcpad, offset, size, caps, buf);
1578 }
1579
1580 static gboolean
1581 gst_multi_queue_src_activate_push (GstPad * pad, gboolean active)
1582 {
1583   GstMultiQueue *mq;
1584   GstSingleQueue *sq;
1585   gboolean result = FALSE;
1586
1587   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1588   mq = sq->mqueue;
1589
1590   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
1591
1592   if (active) {
1593     result = gst_single_queue_flush (mq, sq, FALSE);
1594   } else {
1595     result = gst_single_queue_flush (mq, sq, TRUE);
1596     /* make sure streaming finishes */
1597     result |= gst_pad_stop_task (pad);
1598   }
1599   return result;
1600 }
1601
1602 static gboolean
1603 gst_multi_queue_src_event (GstPad * pad, GstEvent * event)
1604 {
1605   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1606
1607   return gst_pad_push_event (sq->sinkpad, event);
1608 }
1609
1610 static gboolean
1611 gst_multi_queue_src_query (GstPad * pad, GstQuery * query)
1612 {
1613   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1614   GstPad *peerpad;
1615   gboolean res;
1616
1617   /* FIXME, Handle position offset depending on queue size */
1618
1619   /* default handling */
1620   if (!(peerpad = gst_pad_get_peer (sq->sinkpad)))
1621     goto no_peer;
1622
1623   res = gst_pad_query (peerpad, query);
1624
1625   gst_object_unref (peerpad);
1626
1627   return res;
1628
1629   /* ERRORS */
1630 no_peer:
1631   {
1632     GST_LOG_OBJECT (sq->sinkpad, "Couldn't send query because we have no peer");
1633     return FALSE;
1634   }
1635 }
1636
1637 /*
1638  * Next-non-linked functions
1639  */
1640
1641 /* WITH LOCK TAKEN */
1642 static void
1643 wake_up_next_non_linked (GstMultiQueue * mq)
1644 {
1645   GList *tmp;
1646
1647   /* maybe no-one is waiting */
1648   if (mq->numwaiting < 1)
1649     return;
1650
1651   /* Else figure out which singlequeue(s) need waking up */
1652   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1653     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1654
1655     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1656       if ((mq->sync_by_running_time && mq->high_time != GST_CLOCK_TIME_NONE
1657               && sq->next_time != GST_CLOCK_TIME_NONE
1658               && sq->next_time >= mq->high_time)
1659           || (sq->nextid != 0 && sq->nextid <= mq->highid)) {
1660         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
1661         g_cond_signal (sq->turn);
1662       }
1663     }
1664   }
1665 }
1666
1667 /* WITH LOCK TAKEN */
1668 static void
1669 compute_high_id (GstMultiQueue * mq)
1670 {
1671   /* The high-id is either the highest id among the linked pads, or if all
1672    * pads are not-linked, it's the lowest not-linked pad */
1673   GList *tmp;
1674   guint32 lowest = G_MAXUINT32;
1675   guint32 highid = G_MAXUINT32;
1676
1677   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1678     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1679
1680     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
1681         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
1682
1683     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1684       /* No need to consider queues which are not waiting */
1685       if (sq->nextid == 0) {
1686         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1687         continue;
1688       }
1689
1690       if (sq->nextid < lowest)
1691         lowest = sq->nextid;
1692     } else if (sq->srcresult != GST_FLOW_UNEXPECTED) {
1693       /* If we don't have a global highid, or the global highid is lower than
1694        * this single queue's last outputted id, store the queue's one, 
1695        * unless the singlequeue is at EOS (srcresult = UNEXPECTED) */
1696       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
1697         highid = sq->oldid;
1698     }
1699   }
1700
1701   if (highid == G_MAXUINT32 || lowest < highid)
1702     mq->highid = lowest;
1703   else
1704     mq->highid = highid;
1705
1706   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
1707       lowest);
1708 }
1709
1710 /* WITH LOCK TAKEN */
1711 static void
1712 compute_high_time (GstMultiQueue * mq)
1713 {
1714   /* The high-id is either the highest id among the linked pads, or if all
1715    * pads are not-linked, it's the lowest not-linked pad */
1716   GList *tmp;
1717   GstClockTime highest = GST_CLOCK_TIME_NONE;
1718   GstClockTime lowest = GST_CLOCK_TIME_NONE;
1719
1720   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1721     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1722
1723     GST_LOG_OBJECT (mq,
1724         "inspecting sq:%d , next_time:%" GST_TIME_FORMAT ", last_time:%"
1725         GST_TIME_FORMAT ", srcresult:%s", sq->id, GST_TIME_ARGS (sq->next_time),
1726         GST_TIME_ARGS (sq->last_time), gst_flow_get_name (sq->srcresult));
1727
1728     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1729       /* No need to consider queues which are not waiting */
1730       if (sq->next_time == GST_CLOCK_TIME_NONE) {
1731         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1732         continue;
1733       }
1734
1735       if (lowest == GST_CLOCK_TIME_NONE || sq->next_time < lowest)
1736         lowest = sq->next_time;
1737     } else if (sq->srcresult != GST_FLOW_UNEXPECTED) {
1738       /* If we don't have a global highid, or the global highid is lower than
1739        * this single queue's last outputted id, store the queue's one, 
1740        * unless the singlequeue is at EOS (srcresult = UNEXPECTED) */
1741       if (highest == GST_CLOCK_TIME_NONE || sq->last_time > highest)
1742         highest = sq->last_time;
1743     }
1744   }
1745
1746   mq->high_time = highest;
1747
1748   GST_LOG_OBJECT (mq,
1749       "High time is now : %" GST_TIME_FORMAT ", lowest non-linked %"
1750       GST_TIME_FORMAT, GST_TIME_ARGS (mq->high_time), GST_TIME_ARGS (lowest));
1751 }
1752
1753 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
1754      ((q)->max_size.format) <= (value))
1755
1756 /*
1757  * GstSingleQueue functions
1758  */
1759 static void
1760 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1761 {
1762   GstMultiQueue *mq = sq->mqueue;
1763   GList *tmp;
1764   GstDataQueueSize size;
1765   gboolean filled = FALSE;
1766
1767   gst_data_queue_get_level (sq->queue, &size);
1768
1769   GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id);
1770
1771   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1772   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1773     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1774     GstDataQueueSize ssize;
1775
1776     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
1777
1778     if (gst_data_queue_is_empty (oq->queue)) {
1779       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
1780       if (IS_FILLED (sq, visible, size.visible)) {
1781         sq->max_size.visible = size.visible + 1;
1782         GST_DEBUG_OBJECT (mq,
1783             "Another queue is empty, bumping single queue %d max visible to %d",
1784             sq->id, sq->max_size.visible);
1785       }
1786       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1787       goto beach;
1788     }
1789     /* check if we reached the hard time/bytes limits */
1790     gst_data_queue_get_level (oq->queue, &ssize);
1791
1792     GST_DEBUG_OBJECT (mq,
1793         "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1794         G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible,
1795         ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time);
1796
1797     /* if this queue is filled completely we must signal overrun.
1798      * FIXME, this seems wrong in many ways
1799      *  - we're comparing the filled level of this queue against the
1800      *    values of the other one
1801      *  - we should only do this after we found no empty queues, ie, move
1802      *    this check outside of the loop
1803      *  - the debug statement talks about a different queue than the one
1804      *    we are checking here.
1805      */
1806     if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) ||
1807         IS_FILLED (sq, time, sq->cur_time)) {
1808       GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id);
1809       filled = TRUE;
1810     }
1811   }
1812   /* no queues were empty */
1813   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1814
1815   /* Overrun is always forwarded, since this is blocking the upstream element */
1816   if (filled) {
1817     GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun");
1818     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
1819   }
1820
1821 beach:
1822   return;
1823 }
1824
1825 static void
1826 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1827 {
1828   gboolean empty = TRUE;
1829   GstMultiQueue *mq = sq->mqueue;
1830   GList *tmp;
1831
1832   GST_LOG_OBJECT (mq,
1833       "Single Queue %d is empty, Checking other single queues", sq->id);
1834
1835   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1836   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1837     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1838
1839     if (gst_data_queue_is_full (oq->queue)) {
1840       GstDataQueueSize size;
1841
1842       gst_data_queue_get_level (oq->queue, &size);
1843       if (IS_FILLED (oq, visible, size.visible)) {
1844         oq->max_size.visible = size.visible + 1;
1845         GST_DEBUG_OBJECT (mq,
1846             "queue %d is filled, bumping its max visible to %d", oq->id,
1847             oq->max_size.visible);
1848         gst_data_queue_limits_changed (oq->queue);
1849       }
1850     }
1851     if (!gst_data_queue_is_empty (oq->queue))
1852       empty = FALSE;
1853   }
1854   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1855
1856   if (empty) {
1857     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
1858     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
1859   }
1860 }
1861
1862 static gboolean
1863 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
1864     guint64 time, GstSingleQueue * sq)
1865 {
1866   gboolean res;
1867   GstMultiQueue *mq = sq->mqueue;
1868
1869   GST_DEBUG_OBJECT (mq,
1870       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1871       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
1872       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1873
1874   /* we are always filled on EOS */
1875   if (sq->is_eos)
1876     return TRUE;
1877
1878   /* we never go past the max visible items unless we are in buffering mode */
1879   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
1880     return TRUE;
1881
1882   /* check time or bytes */
1883   res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
1884
1885   return res;
1886 }
1887
1888 static void
1889 gst_single_queue_free (GstSingleQueue * sq)
1890 {
1891   /* DRAIN QUEUE */
1892   gst_data_queue_flush (sq->queue);
1893   g_object_unref (sq->queue);
1894   g_cond_free (sq->turn);
1895   g_free (sq);
1896 }
1897
1898 static GstSingleQueue *
1899 gst_single_queue_new (GstMultiQueue * mqueue, gint id)
1900 {
1901   GstSingleQueue *sq;
1902   gchar *name;
1903   GList *tmp;
1904   gint temp_id = (id == -1) ? 0 : id;
1905
1906   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1907
1908   /* Find an unused queue ID, if possible the passed one */
1909   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1910     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
1911     /* This works because the IDs are sorted in ascending order */
1912     if (sq2->id == temp_id) {
1913       /* If this ID was requested by the caller return NULL,
1914        * otherwise just get us the next one */
1915       if (id == -1)
1916         temp_id = sq2->id + 1;
1917       else
1918         return NULL;
1919     } else if (sq2->id > temp_id) {
1920       break;
1921     }
1922   }
1923
1924   sq = g_new0 (GstSingleQueue, 1);
1925   mqueue->nbqueues++;
1926   sq->id = temp_id;
1927
1928   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
1929   mqueue->queues_cookie++;
1930
1931   /* copy over max_size and extra_size so we don't need to take the lock
1932    * any longer when checking if the queue is full. */
1933   sq->max_size.visible = mqueue->max_size.visible;
1934   sq->max_size.bytes = mqueue->max_size.bytes;
1935   sq->max_size.time = mqueue->max_size.time;
1936
1937   sq->extra_size.visible = mqueue->extra_size.visible;
1938   sq->extra_size.bytes = mqueue->extra_size.bytes;
1939   sq->extra_size.time = mqueue->extra_size.time;
1940
1941   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
1942
1943   sq->mqueue = mqueue;
1944   sq->srcresult = GST_FLOW_WRONG_STATE;
1945   sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction)
1946       single_queue_check_full,
1947       (GstDataQueueFullCallback) single_queue_overrun_cb,
1948       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
1949   sq->is_eos = FALSE;
1950   sq->flushing = FALSE;
1951   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
1952   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
1953
1954   sq->nextid = 0;
1955   sq->oldid = 0;
1956   sq->next_time = GST_CLOCK_TIME_NONE;
1957   sq->last_time = GST_CLOCK_TIME_NONE;
1958   sq->turn = g_cond_new ();
1959
1960   sq->sinktime = GST_CLOCK_TIME_NONE;
1961   sq->srctime = GST_CLOCK_TIME_NONE;
1962   sq->sink_tainted = TRUE;
1963   sq->src_tainted = TRUE;
1964
1965   name = g_strdup_printf ("sink%d", sq->id);
1966   sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, name);
1967   g_free (name);
1968
1969   gst_pad_set_chain_function (sq->sinkpad,
1970       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
1971   gst_pad_set_activatepush_function (sq->sinkpad,
1972       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_push));
1973   gst_pad_set_event_function (sq->sinkpad,
1974       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
1975   gst_pad_set_getcaps_function (sq->sinkpad,
1976       GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps));
1977   gst_pad_set_acceptcaps_function (sq->sinkpad,
1978       GST_DEBUG_FUNCPTR (gst_multi_queue_acceptcaps));
1979   gst_pad_set_bufferalloc_function (sq->sinkpad,
1980       GST_DEBUG_FUNCPTR (gst_multi_queue_bufferalloc));
1981   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
1982       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
1983
1984   name = g_strdup_printf ("src%d", sq->id);
1985   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, name);
1986   g_free (name);
1987
1988   gst_pad_set_activatepush_function (sq->srcpad,
1989       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_push));
1990   gst_pad_set_getcaps_function (sq->srcpad,
1991       GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps));
1992   gst_pad_set_acceptcaps_function (sq->srcpad,
1993       GST_DEBUG_FUNCPTR (gst_multi_queue_acceptcaps));
1994   gst_pad_set_event_function (sq->srcpad,
1995       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
1996   gst_pad_set_query_function (sq->srcpad,
1997       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
1998   gst_pad_set_iterate_internal_links_function (sq->srcpad,
1999       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
2000
2001   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
2002   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
2003
2004   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
2005
2006   /* only activate the pads when we are not in the NULL state
2007    * and add the pad under the state_lock to prevend state changes
2008    * between activating and adding */
2009   g_static_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
2010   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
2011     gst_pad_set_active (sq->srcpad, TRUE);
2012     gst_pad_set_active (sq->sinkpad, TRUE);
2013   }
2014   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
2015   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
2016   g_static_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
2017
2018   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
2019       sq->id);
2020
2021   return sq;
2022 }