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