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