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