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