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