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