multiqueue: Increase initial interleave growth rate
[platform/upstream/gstreamer.git] / subprojects / gstreamer / 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  * @title: multiqueue
28  * @see_also: #GstQueue
29  *
30  * Multiqueue is similar to a normal #GstQueue with the following additional
31  * features:
32  *
33  * 1) Multiple streamhandling
34  *
35  *  * The element handles queueing data on more than one stream at once. To
36  * achieve such a feature it has request sink pads (sink%u) and
37  * 'sometimes' src pads (src%u). When requesting a given sinkpad with gst_element_request_pad(),
38  * the associated srcpad for that stream will be created.
39  * Example: requesting sink1 will generate src1.
40  *
41  * 2) Non-starvation on multiple stream
42  *
43  * * If more than one stream is used with the element, the streams' queues
44  * will be dynamically grown (up to a limit), in order to ensure that no
45  * stream is risking data starvation. This guarantees that at any given
46  * time there are at least N bytes queued and available for each individual
47  * stream. If an EOS event comes through a srcpad, the associated queue will be
48  * considered as 'not-empty' in the queue-size-growing algorithm.
49  *
50  * 3) Non-linked srcpads graceful handling
51  *
52  * * In order to better support dynamic switching between streams, the multiqueue
53  * (unlike the current GStreamer queue) continues to push buffers on non-linked
54  * pads rather than shutting down. In addition, to prevent a non-linked stream from very quickly consuming all
55  * available buffers and thus 'racing ahead' of the other streams, the element
56  * must ensure that buffers and inlined events for a non-linked stream are pushed
57  * in the same order as they were received, relative to the other streams
58  * controlled by the element. This means that a buffer cannot be pushed to a
59  * non-linked pad any sooner than buffers in any other stream which were received
60  * before it.
61  *
62  * Data is queued until one of the limits specified by the
63  * #GstMultiQueue:max-size-buffers, #GstMultiQueue:max-size-bytes and/or
64  * #GstMultiQueue:max-size-time properties has been reached. Any attempt to push
65  * more buffers into the queue will block the pushing thread until more space
66  * becomes available. #GstMultiQueue:extra-size-buffers,
67  *
68  *
69  * #GstMultiQueue:extra-size-bytes and #GstMultiQueue:extra-size-time are
70  * currently unused.
71  *
72  * The default queue size limits are 5 buffers, 10MB of data, or
73  * two second worth of data, whichever is reached first. Note that the number
74  * of buffers will dynamically grow depending on the fill level of
75  * other queues.
76  *
77  * The #GstMultiQueue::underrun signal is emitted when all of the queues
78  * are empty. The #GstMultiQueue::overrun signal is emitted when one of the
79  * queues is filled.
80  * Both signals are emitted from the context of the streaming thread.
81  *
82  * When using #GstMultiQueue:sync-by-running-time the unlinked streams will
83  * be throttled by the highest running-time of linked streams. This allows
84  * further relinking of those unlinked streams without them being in the
85  * future (i.e. to achieve gapless playback).
86  * When dealing with streams which have got different consumption requirements
87  * downstream (ex: video decoders which will consume more buffer (in time) than
88  * audio decoders), it is recommended to group streams of the same type
89  * by using the pad "group-id" property. This will further throttle streams
90  * in time within that group.
91  */
92
93 #ifdef HAVE_CONFIG_H
94 #  include "config.h"
95 #endif
96
97 #include <gst/gst.h>
98 #include <gst/glib-compat-private.h>
99 #include <stdio.h>
100
101 #include "gstmultiqueue.h"
102 #include "gstcoreelementselements.h"
103
104 /* GstSingleQueue:
105  * @sinkpad: associated sink #GstPad
106  * @srcpad: associated source #GstPad
107  *
108  * Structure containing all information and properties about
109  * a single queue.
110  */
111 typedef struct _GstSingleQueue GstSingleQueue;
112
113 struct _GstSingleQueue
114 {
115   gint refcount;
116
117   /* unique identifier of the queue */
118   guint id;
119   /* group of streams to which this queue belongs to */
120   guint groupid;
121   GstClockTimeDiff group_high_time;
122
123   GWeakRef mqueue;
124   GWeakRef sinkpad;
125   GWeakRef srcpad;
126
127   /* flowreturn of previous srcpad push */
128   GstFlowReturn srcresult;
129   /* If something was actually pushed on
130    * this pad after flushing/pad activation
131    * and the srcresult corresponds to something
132    * real
133    */
134   gboolean pushed;
135
136   /* segments */
137   GstSegment sink_segment;
138   GstSegment src_segment;
139   gboolean has_src_segment;     /* preferred over initializing the src_segment to
140                                  * UNDEFINED as this doesn't requires adding ifs
141                                  * in every segment usage */
142
143   /* position of src/sink */
144   GstClockTimeDiff sinktime, srctime;
145   /* cached input value, used for interleave */
146   GstClockTimeDiff cached_sinktime;
147   /* TRUE if either position needs to be recalculated */
148   gboolean sink_tainted, src_tainted;
149
150   /* queue of data */
151   GstDataQueue *queue;
152   GstDataQueueSize max_size, extra_size;
153   GstClockTime cur_time;
154   gboolean is_eos;
155   gboolean is_segment_done;
156   gboolean is_sparse;
157   gboolean flushing;
158   gboolean active;
159
160   /* Protected by global lock */
161   guint32 nextid;               /* ID of the next object waiting to be pushed */
162   guint32 oldid;                /* ID of the last object pushed (last in a series) */
163   guint32 last_oldid;           /* Previously observed old_id, reset to MAXUINT32 on flush */
164   GstClockTimeDiff next_time;   /* End running time of next buffer to be pushed */
165   GstClockTimeDiff last_time;   /* Start running time of last pushed buffer */
166   GCond turn;                   /* SingleQueue turn waiting conditional */
167
168   /* for serialized queries */
169   GCond query_handled;
170   gboolean last_query;
171   GstQuery *last_handled_query;
172
173   /* For interleave calculation */
174   GThread *thread;              /* Streaming thread of SingleQueue */
175   GstClockTime interleave;      /* Calculated interleve within the thread */
176 };
177
178 /* Extension of GstDataQueueItem structure for our usage */
179 typedef struct _GstMultiQueueItem GstMultiQueueItem;
180
181 struct _GstMultiQueueItem
182 {
183   GstMiniObject *object;
184   guint size;
185   guint64 duration;
186   gboolean visible;
187
188   GDestroyNotify destroy;
189   guint32 posid;
190
191   gboolean is_query;
192 };
193
194 static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue, guint id);
195 static void gst_single_queue_unref (GstSingleQueue * squeue);
196 static GstSingleQueue *gst_single_queue_ref (GstSingleQueue * squeue);
197
198 static void wake_up_next_non_linked (GstMultiQueue * mq);
199 static void compute_high_id (GstMultiQueue * mq);
200 static void compute_high_time (GstMultiQueue * mq, guint groupid);
201 static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
202 static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
203
204 static void update_buffering (GstMultiQueue * mq, GstSingleQueue * sq);
205 static void gst_multi_queue_post_buffering (GstMultiQueue * mq);
206 static void recheck_buffering_status (GstMultiQueue * mq);
207
208 static void gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full);
209
210 static void calculate_interleave (GstMultiQueue * mq, GstSingleQueue * sq);
211
212 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink_%u",
213     GST_PAD_SINK,
214     GST_PAD_REQUEST,
215     GST_STATIC_CAPS_ANY);
216
217 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
218     GST_PAD_SRC,
219     GST_PAD_SOMETIMES,
220     GST_STATIC_CAPS_ANY);
221
222 GST_DEBUG_CATEGORY_STATIC (multi_queue_debug);
223 #define GST_CAT_DEFAULT (multi_queue_debug)
224
225 /* Signals and args */
226 enum
227 {
228   SIGNAL_UNDERRUN,
229   SIGNAL_OVERRUN,
230   LAST_SIGNAL
231 };
232
233 /* default limits, we try to keep up to 2 seconds of data and if there is not
234  * time, up to 10 MB. The number of buffers is dynamically scaled to make sure
235  * there is data in the queues. Normally, the byte and time limits are not hit
236  * in theses conditions. */
237 #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */
238 #define DEFAULT_MAX_SIZE_BUFFERS 5
239 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND
240
241 /* second limits. When we hit one of the above limits we are probably dealing
242  * with a badly muxed file and we scale the limits to these emergency values.
243  * This is currently not yet implemented.
244  * Since we dynamically scale the queue buffer size up to the limits but avoid
245  * going above the max-size-buffers when we can, we don't really need this
246  * additional extra size. */
247 #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024       /* 10 MB */
248 #define DEFAULT_EXTRA_SIZE_BUFFERS 5
249 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND
250
251 #define DEFAULT_USE_BUFFERING FALSE
252 #define DEFAULT_LOW_WATERMARK  0.01
253 #define DEFAULT_HIGH_WATERMARK 0.99
254 #define DEFAULT_SYNC_BY_RUNNING_TIME FALSE
255 #define DEFAULT_USE_INTERLEAVE FALSE
256 #define DEFAULT_UNLINKED_CACHE_TIME 250 * GST_MSECOND
257
258 #define DEFAULT_MINIMUM_INTERLEAVE (250 * GST_MSECOND)
259
260 enum
261 {
262   PROP_0,
263   PROP_EXTRA_SIZE_BYTES,
264   PROP_EXTRA_SIZE_BUFFERS,
265   PROP_EXTRA_SIZE_TIME,
266   PROP_MAX_SIZE_BYTES,
267   PROP_MAX_SIZE_BUFFERS,
268   PROP_MAX_SIZE_TIME,
269   PROP_USE_BUFFERING,
270   PROP_LOW_PERCENT,
271   PROP_HIGH_PERCENT,
272   PROP_LOW_WATERMARK,
273   PROP_HIGH_WATERMARK,
274   PROP_SYNC_BY_RUNNING_TIME,
275   PROP_USE_INTERLEAVE,
276   PROP_UNLINKED_CACHE_TIME,
277   PROP_MINIMUM_INTERLEAVE,
278   PROP_STATS,
279   PROP_LAST
280 };
281
282 /* Explanation for buffer levels and percentages:
283  *
284  * The buffering_level functions here return a value in a normalized range
285  * that specifies the current fill level of a queue. The range goes from 0 to
286  * MAX_BUFFERING_LEVEL. The low/high watermarks also use this same range.
287  *
288  * This is not to be confused with the buffering_percent value, which is
289  * a *relative* quantity - relative to the low/high watermarks.
290  * buffering_percent = 0% means overall buffering_level is at the low watermark.
291  * buffering_percent = 100% means overall buffering_level is at the high watermark.
292  * buffering_percent is used for determining if the fill level has reached
293  * the high watermark, and for producing BUFFERING messages. This value
294  * always uses a 0..100 range (since it is a percentage).
295  *
296  * To avoid future confusions, whenever "buffering level" is mentioned, it
297  * refers to the absolute level which is in the 0..MAX_BUFFERING_LEVEL
298  * range. Whenever "buffering_percent" is mentioned, it refers to the
299  * percentage value that is relative to the low/high watermark. */
300
301 /* Using a buffering level range of 0..1000000 to allow for a
302  * resolution in ppm (1 ppm = 0.0001%) */
303 #define MAX_BUFFERING_LEVEL 1000000
304
305 /* How much 1% makes up in the buffer level range */
306 #define BUF_LEVEL_PERCENT_FACTOR ((MAX_BUFFERING_LEVEL) / 100)
307
308 /* GstMultiQueuePad */
309
310 #define DEFAULT_PAD_GROUP_ID 0
311
312 enum
313 {
314   PROP_PAD_0,
315   PROP_PAD_GROUP_ID,
316   PROP_CURRENT_LEVEL_BUFFERS,
317   PROP_CURRENT_LEVEL_BYTES,
318   PROP_CURRENT_LEVEL_TIME,
319 };
320
321 #define GST_TYPE_MULTIQUEUE_PAD            (gst_multiqueue_pad_get_type())
322 #define GST_MULTIQUEUE_PAD(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_MULTIQUEUE_PAD,GstMultiQueuePad))
323 #define GST_IS_MULTIQUEUE_PAD(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_MULTIQUEUE_PAD))
324 #define GST_MULTIQUEUE_PAD_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST((klass) ,GST_TYPE_MULTIQUEUE_PAD,GstMultiQueuePadClass))
325 #define GST_IS_MULTIQUEUE_PAD_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass) ,GST_TYPE_MULTIQUEUE_PAD))
326 #define GST_MULTIQUEUE_PAD_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj) ,GST_TYPE_MULTIQUEUE_PAD,GstMultiQueuePadClass))
327
328 #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
329   g_mutex_lock (&q->qlock);                                              \
330 } G_STMT_END
331
332 #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
333   g_mutex_unlock (&q->qlock);                                            \
334 } G_STMT_END
335
336 #define SET_PERCENT(mq, perc) G_STMT_START {                             \
337   if (perc != mq->buffering_percent) {                                   \
338     mq->buffering_percent = perc;                                        \
339     mq->buffering_percent_changed = TRUE;                                \
340     GST_DEBUG_OBJECT (mq, "buffering %d percent", perc);                 \
341   }                                                                      \
342 } G_STMT_END
343
344 struct _GstMultiQueuePad
345 {
346   GstPad parent;
347
348   GstSingleQueue *sq;
349 };
350
351 struct _GstMultiQueuePadClass
352 {
353   GstPadClass parent_class;
354 };
355
356 GType gst_multiqueue_pad_get_type (void);
357
358 G_DEFINE_TYPE (GstMultiQueuePad, gst_multiqueue_pad, GST_TYPE_PAD);
359
360 static guint
361 gst_multiqueue_pad_get_group_id (GstMultiQueuePad * pad)
362 {
363   guint ret = 0;
364   GstMultiQueue *mq;
365
366   if (!pad->sq)
367     return 0;
368
369   mq = g_weak_ref_get (&pad->sq->mqueue);
370
371   if (mq) {
372     GST_OBJECT_LOCK (mq);
373   }
374
375   ret = pad->sq->groupid;
376
377   if (mq) {
378     GST_OBJECT_UNLOCK (mq);
379     gst_object_unref (mq);
380   }
381
382   return ret;
383 }
384
385 static guint
386 gst_multiqueue_pad_get_current_level_buffers (GstMultiQueuePad * pad)
387 {
388   GstSingleQueue *sq = pad->sq;
389   GstDataQueueSize level;
390   GstMultiQueue *mq;
391
392   if (!sq)
393     return 0;
394
395   mq = g_weak_ref_get (&pad->sq->mqueue);
396
397   if (mq) {
398     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
399   }
400
401   gst_data_queue_get_level (sq->queue, &level);
402
403   if (mq) {
404     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
405     gst_object_unref (mq);
406   }
407
408   return level.visible;
409 }
410
411 static guint
412 gst_multiqueue_pad_get_current_level_bytes (GstMultiQueuePad * pad)
413 {
414   GstSingleQueue *sq = pad->sq;
415   GstDataQueueSize level;
416   GstMultiQueue *mq;
417
418   if (!sq)
419     return 0;
420
421   mq = g_weak_ref_get (&pad->sq->mqueue);
422
423   if (mq) {
424     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
425   }
426
427   gst_data_queue_get_level (sq->queue, &level);
428
429   if (mq) {
430     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
431     gst_object_unref (mq);
432   }
433
434   return level.bytes;
435 }
436
437 static guint64
438 gst_multiqueue_pad_get_current_level_time (GstMultiQueuePad * pad)
439 {
440   GstSingleQueue *sq = pad->sq;
441   GstMultiQueue *mq;
442   guint64 ret;
443
444   if (!sq)
445     return 0;
446
447   mq = g_weak_ref_get (&pad->sq->mqueue);
448
449   if (mq) {
450     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
451   }
452
453   ret = sq->cur_time;
454
455   if (mq) {
456     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
457     gst_object_unref (mq);
458   }
459
460   return ret;
461 }
462
463 static void
464 gst_multiqueue_pad_get_property (GObject * object, guint prop_id,
465     GValue * value, GParamSpec * pspec)
466 {
467   GstMultiQueuePad *pad = GST_MULTIQUEUE_PAD (object);
468
469   switch (prop_id) {
470     case PROP_PAD_GROUP_ID:
471       g_value_set_uint (value, gst_multiqueue_pad_get_group_id (pad));
472       break;
473     case PROP_CURRENT_LEVEL_BUFFERS:{
474       g_value_set_uint (value,
475           gst_multiqueue_pad_get_current_level_buffers (pad));
476       break;
477     }
478     case PROP_CURRENT_LEVEL_BYTES:{
479       g_value_set_uint (value,
480           gst_multiqueue_pad_get_current_level_bytes (pad));
481       break;
482     }
483     case PROP_CURRENT_LEVEL_TIME:{
484       g_value_set_uint64 (value,
485           gst_multiqueue_pad_get_current_level_time (pad));
486       break;
487     }
488     default:
489       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
490       break;
491   }
492 }
493
494 static void
495 gst_multiqueue_pad_set_property (GObject * object, guint prop_id,
496     const GValue * value, GParamSpec * pspec)
497 {
498   GstMultiQueuePad *pad = GST_MULTIQUEUE_PAD (object);
499
500   switch (prop_id) {
501     case PROP_PAD_GROUP_ID:
502       if (pad->sq) {
503         GstMultiQueue *mqueue = g_weak_ref_get (&pad->sq->mqueue);
504
505         if (mqueue)
506           GST_OBJECT_LOCK (mqueue);
507
508         pad->sq->groupid = g_value_get_uint (value);
509
510         if (mqueue) {
511           GST_OBJECT_UNLOCK (mqueue);
512           gst_object_unref (mqueue);
513         }
514       }
515       break;
516     default:
517       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
518       break;
519   }
520 }
521
522 static void
523 gst_multiqueue_pad_finalize (GObject * object)
524 {
525   GstMultiQueuePad *pad = GST_MULTIQUEUE_PAD (object);
526
527   if (pad->sq)
528     gst_single_queue_unref (pad->sq);
529
530   G_OBJECT_CLASS (gst_multiqueue_pad_parent_class)->finalize (object);
531 }
532
533 static void
534 gst_multiqueue_pad_class_init (GstMultiQueuePadClass * klass)
535 {
536   GObjectClass *gobject_class = (GObjectClass *) klass;
537
538   gobject_class->set_property = gst_multiqueue_pad_set_property;
539   gobject_class->get_property = gst_multiqueue_pad_get_property;
540   gobject_class->finalize = gst_multiqueue_pad_finalize;
541
542   /**
543    * GstMultiQueuePad:group-id:
544    *
545    * Group to which this pad belongs.
546    *
547    * Since: 1.10
548    */
549   g_object_class_install_property (gobject_class, PROP_PAD_GROUP_ID,
550       g_param_spec_uint ("group-id", "Group ID",
551           "Group to which this pad belongs", 0, G_MAXUINT32,
552           DEFAULT_PAD_GROUP_ID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
553
554   /**
555    * GstMultiQueuePad:current-level-buffers:
556    *
557    * The corresponding queue's current level of buffers.
558    *
559    * Since: 1.18
560    */
561   g_object_class_install_property (gobject_class, PROP_CURRENT_LEVEL_BUFFERS,
562       g_param_spec_uint ("current-level-buffers", "Current level buffers",
563           "Current level buffers", 0, G_MAXUINT32,
564           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
565
566   /**
567    * GstMultiQueuePad:current-level-bytes:
568    *
569    * The corresponding queue's current level of bytes.
570    *
571    * Since: 1.18
572    */
573   g_object_class_install_property (gobject_class, PROP_CURRENT_LEVEL_BYTES,
574       g_param_spec_uint ("current-level-bytes", "Current level bytes",
575           "Current level bytes", 0, G_MAXUINT32,
576           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
577
578   /**
579    * GstMultiQueuePad:current-level-time:
580    *
581    * The corresponding queue's current level of time.
582    *
583    * Since: 1.18
584    */
585   g_object_class_install_property (gobject_class, PROP_CURRENT_LEVEL_TIME,
586       g_param_spec_uint64 ("current-level-time", "Current level time",
587           "Current level time", 0, G_MAXUINT64,
588           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
589 }
590
591 static void
592 gst_multiqueue_pad_init (GstMultiQueuePad * pad)
593 {
594
595 }
596
597
598 /* Convenience function */
599 static inline GstClockTimeDiff
600 my_segment_to_running_time (GstSegment * segment, GstClockTime val)
601 {
602   GstClockTimeDiff res = GST_CLOCK_STIME_NONE;
603
604   if (GST_CLOCK_TIME_IS_VALID (val)) {
605     gboolean sign =
606         gst_segment_to_running_time_full (segment, GST_FORMAT_TIME, val, &val);
607     if (sign > 0)
608       res = val;
609     else if (sign < 0)
610       res = -val;
611   }
612   return res;
613 }
614
615 static void gst_multi_queue_finalize (GObject * object);
616 static void gst_multi_queue_set_property (GObject * object,
617     guint prop_id, const GValue * value, GParamSpec * pspec);
618 static void gst_multi_queue_get_property (GObject * object,
619     guint prop_id, GValue * value, GParamSpec * pspec);
620
621 static GstPad *gst_multi_queue_request_new_pad (GstElement * element,
622     GstPadTemplate * temp, const gchar * name, const GstCaps * caps);
623 static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad);
624 static GstStateChangeReturn gst_multi_queue_change_state (GstElement *
625     element, GstStateChange transition);
626
627 static void gst_multi_queue_loop (GstPad * pad);
628
629 #define _do_init \
630   GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element");
631 #define gst_multi_queue_parent_class parent_class
632 G_DEFINE_TYPE_WITH_CODE (GstMultiQueue, gst_multi_queue, GST_TYPE_ELEMENT,
633     _do_init);
634 GST_ELEMENT_REGISTER_DEFINE (multiqueue, "multiqueue", GST_RANK_NONE,
635     GST_TYPE_MULTI_QUEUE);
636
637 static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 };
638
639 static void
640 gst_multi_queue_class_init (GstMultiQueueClass * klass)
641 {
642   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
643   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
644
645   gobject_class->set_property = gst_multi_queue_set_property;
646   gobject_class->get_property = gst_multi_queue_get_property;
647
648   /* SIGNALS */
649
650   /**
651    * GstMultiQueue::underrun:
652    * @multiqueue: the multiqueue instance
653    *
654    * This signal is emitted from the streaming thread when there is
655    * no data in any of the queues inside the multiqueue instance (underrun).
656    *
657    * This indicates either starvation or EOS from the upstream data sources.
658    */
659   gst_multi_queue_signals[SIGNAL_UNDERRUN] =
660       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
661       G_STRUCT_OFFSET (GstMultiQueueClass, underrun), NULL, NULL,
662       NULL, G_TYPE_NONE, 0);
663
664   /**
665    * GstMultiQueue::overrun:
666    * @multiqueue: the multiqueue instance
667    *
668    * Reports that one of the queues in the multiqueue is full (overrun).
669    * A queue is full if the total amount of data inside it (num-buffers, time,
670    * size) is higher than the boundary values which can be set through the
671    * GObject properties.
672    *
673    * This can be used as an indicator of pre-roll.
674    */
675   gst_multi_queue_signals[SIGNAL_OVERRUN] =
676       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
677       G_STRUCT_OFFSET (GstMultiQueueClass, overrun), NULL, NULL,
678       NULL, G_TYPE_NONE, 0);
679
680   /* PROPERTIES */
681
682   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
683       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
684           "Max. amount of data in the queue (bytes, 0=disable)",
685           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
686           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
687           G_PARAM_STATIC_STRINGS));
688   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
689       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
690           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
691           DEFAULT_MAX_SIZE_BUFFERS,
692           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
693           G_PARAM_STATIC_STRINGS));
694   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
695       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
696           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
697           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
698           G_PARAM_STATIC_STRINGS));
699
700   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BYTES,
701       g_param_spec_uint ("extra-size-bytes", "Extra Size (kB)",
702           "Amount of data the queues can grow if one of them is empty (bytes, 0=disable)"
703           " (NOT IMPLEMENTED)",
704           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BYTES,
705           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
706   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BUFFERS,
707       g_param_spec_uint ("extra-size-buffers", "Extra Size (buffers)",
708           "Amount of buffers the queues can grow if one of them is empty (0=disable)"
709           " (NOT IMPLEMENTED)",
710           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BUFFERS,
711           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
712   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_TIME,
713       g_param_spec_uint64 ("extra-size-time", "Extra Size (ns)",
714           "Amount of time the queues can grow if one of them is empty (in ns, 0=disable)"
715           " (NOT IMPLEMENTED)",
716           0, G_MAXUINT64, DEFAULT_EXTRA_SIZE_TIME,
717           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
718
719   /**
720    * GstMultiQueue:use-buffering:
721    *
722    * Enable the buffering option in multiqueue so that BUFFERING messages are
723    * emitted based on low-/high-percent thresholds.
724    */
725   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
726       g_param_spec_boolean ("use-buffering", "Use buffering",
727           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds "
728           "(0% = low-watermark, 100% = high-watermark)",
729           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
730           G_PARAM_STATIC_STRINGS));
731   /**
732    * GstMultiQueue:low-percent:
733    *
734    * Low threshold percent for buffering to start.
735    */
736   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
737       g_param_spec_int ("low-percent", "Low percent",
738           "Low threshold for buffering to start. Only used if use-buffering is True "
739           "(Deprecated: use low-watermark instead)",
740           0, 100, DEFAULT_LOW_WATERMARK * 100,
741           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
742   /**
743    * GstMultiQueue:high-percent:
744    *
745    * High threshold percent for buffering to finish.
746    */
747   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
748       g_param_spec_int ("high-percent", "High percent",
749           "High threshold for buffering to finish. Only used if use-buffering is True "
750           "(Deprecated: use high-watermark instead)",
751           0, 100, DEFAULT_HIGH_WATERMARK * 100,
752           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
753   /**
754    * GstMultiQueue:low-watermark:
755    *
756    * Low threshold watermark for buffering to start.
757    *
758    * Since: 1.10
759    */
760   g_object_class_install_property (gobject_class, PROP_LOW_WATERMARK,
761       g_param_spec_double ("low-watermark", "Low watermark",
762           "Low threshold for buffering to start. Only used if use-buffering is True",
763           0.0, 1.0, DEFAULT_LOW_WATERMARK,
764           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
765   /**
766    * GstMultiQueue:high-watermark:
767    *
768    * High threshold watermark for buffering to finish.
769    *
770    * Since: 1.10
771    */
772   g_object_class_install_property (gobject_class, PROP_HIGH_WATERMARK,
773       g_param_spec_double ("high-watermark", "High watermark",
774           "High threshold for buffering to finish. Only used if use-buffering is True",
775           0.0, 1.0, DEFAULT_HIGH_WATERMARK,
776           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
777
778   /**
779    * GstMultiQueue:sync-by-running-time:
780    *
781    * If enabled multiqueue will synchronize deactivated or not-linked streams
782    * to the activated and linked streams by taking the running time.
783    * Otherwise multiqueue will synchronize the deactivated or not-linked
784    * streams by keeping the order in which buffers and events arrived compared
785    * to active and linked streams.
786    */
787   g_object_class_install_property (gobject_class, PROP_SYNC_BY_RUNNING_TIME,
788       g_param_spec_boolean ("sync-by-running-time", "Sync By Running Time",
789           "Synchronize deactivated or not-linked streams by running time",
790           DEFAULT_SYNC_BY_RUNNING_TIME,
791           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
792
793   g_object_class_install_property (gobject_class, PROP_USE_INTERLEAVE,
794       g_param_spec_boolean ("use-interleave", "Use interleave",
795           "Adjust time limits based on input interleave",
796           DEFAULT_USE_INTERLEAVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
797
798   g_object_class_install_property (gobject_class, PROP_UNLINKED_CACHE_TIME,
799       g_param_spec_uint64 ("unlinked-cache-time", "Unlinked cache time (ns)",
800           "Extra buffering in time for unlinked streams (if 'sync-by-running-time')",
801           0, G_MAXUINT64, DEFAULT_UNLINKED_CACHE_TIME,
802           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
803           G_PARAM_STATIC_STRINGS));
804
805   g_object_class_install_property (gobject_class, PROP_MINIMUM_INTERLEAVE,
806       g_param_spec_uint64 ("min-interleave-time", "Minimum interleave time",
807           "Minimum extra buffering for deinterleaving (size of the queues) when use-interleave=true",
808           0, G_MAXUINT64, DEFAULT_MINIMUM_INTERLEAVE,
809           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
810           G_PARAM_STATIC_STRINGS));
811
812   /**
813    * GstMultiQueue:stats:
814    *
815    * Various #GstMultiQueue statistics. This property returns a #GstStructure
816    * with name "application/x-gst-multi-queue-stats" with the following fields:
817    *
818    * - "queues" GST_TYPE_ARRAY    Contains one GstStructure named "queue_%d"
819    *   (where \%d is the queue's ID) per internal queue:
820    *   - "buffers" G_TYPE_UINT    The queue's current level of buffers
821    *   - "bytes" G_TYPE_UINT    The queue's current level of bytes
822    *   - "time" G_TYPE_UINT64    The queue's current level of time
823    *
824    * Since: 1.18
825    */
826   g_object_class_install_property (gobject_class, PROP_STATS,
827       g_param_spec_boxed ("stats", "Stats",
828           "Multiqueue Statistics",
829           GST_TYPE_STRUCTURE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
830
831   gobject_class->finalize = gst_multi_queue_finalize;
832
833   gst_element_class_set_static_metadata (gstelement_class,
834       "MultiQueue",
835       "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>");
836   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
837       &sinktemplate, GST_TYPE_MULTIQUEUE_PAD);
838   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
839       &srctemplate, GST_TYPE_MULTIQUEUE_PAD);
840
841   gstelement_class->request_new_pad =
842       GST_DEBUG_FUNCPTR (gst_multi_queue_request_new_pad);
843   gstelement_class->release_pad =
844       GST_DEBUG_FUNCPTR (gst_multi_queue_release_pad);
845   gstelement_class->change_state =
846       GST_DEBUG_FUNCPTR (gst_multi_queue_change_state);
847
848   gst_type_mark_as_plugin_api (GST_TYPE_MULTIQUEUE_PAD, 0);
849 }
850
851 static void
852 gst_multi_queue_init (GstMultiQueue * mqueue)
853 {
854   mqueue->nbqueues = 0;
855   mqueue->queues = NULL;
856
857   mqueue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
858   mqueue->max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
859   mqueue->max_size.time = DEFAULT_MAX_SIZE_TIME;
860
861   mqueue->extra_size.bytes = DEFAULT_EXTRA_SIZE_BYTES;
862   mqueue->extra_size.visible = DEFAULT_EXTRA_SIZE_BUFFERS;
863   mqueue->extra_size.time = DEFAULT_EXTRA_SIZE_TIME;
864
865   mqueue->use_buffering = DEFAULT_USE_BUFFERING;
866   mqueue->low_watermark = DEFAULT_LOW_WATERMARK * MAX_BUFFERING_LEVEL;
867   mqueue->high_watermark = DEFAULT_HIGH_WATERMARK * MAX_BUFFERING_LEVEL;
868
869   mqueue->sync_by_running_time = DEFAULT_SYNC_BY_RUNNING_TIME;
870   mqueue->use_interleave = DEFAULT_USE_INTERLEAVE;
871   mqueue->min_interleave_time = DEFAULT_MINIMUM_INTERLEAVE;
872   mqueue->unlinked_cache_time = DEFAULT_UNLINKED_CACHE_TIME;
873
874   mqueue->counter = 1;
875   mqueue->highid = -1;
876   mqueue->high_time = GST_CLOCK_STIME_NONE;
877
878   g_mutex_init (&mqueue->qlock);
879   g_mutex_init (&mqueue->buffering_post_lock);
880 }
881
882 static void
883 gst_multi_queue_finalize (GObject * object)
884 {
885   GstMultiQueue *mqueue = GST_MULTI_QUEUE (object);
886
887   g_list_free_full (mqueue->queues, (GDestroyNotify) gst_single_queue_unref);
888   mqueue->queues = NULL;
889   mqueue->queues_cookie++;
890
891   /* free/unref instance data */
892   g_mutex_clear (&mqueue->qlock);
893   g_mutex_clear (&mqueue->buffering_post_lock);
894
895   G_OBJECT_CLASS (parent_class)->finalize (object);
896 }
897
898 #define SET_CHILD_PROPERTY(mq,format) G_STMT_START {            \
899     GList * tmp = mq->queues;                                   \
900     while (tmp) {                                               \
901       GstSingleQueue *q = (GstSingleQueue*)tmp->data;           \
902       q->max_size.format = mq->max_size.format;                 \
903       update_buffering (mq, q);                                 \
904       gst_data_queue_limits_changed (q->queue);                 \
905       tmp = g_list_next(tmp);                                   \
906     };                                                          \
907 } G_STMT_END
908
909 static void
910 gst_multi_queue_set_property (GObject * object, guint prop_id,
911     const GValue * value, GParamSpec * pspec)
912 {
913   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
914
915   switch (prop_id) {
916     case PROP_MAX_SIZE_BYTES:
917       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
918       mq->max_size.bytes = g_value_get_uint (value);
919       SET_CHILD_PROPERTY (mq, bytes);
920       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
921       gst_multi_queue_post_buffering (mq);
922       break;
923     case PROP_MAX_SIZE_BUFFERS:
924     {
925       GList *tmp;
926       gint new_size = g_value_get_uint (value);
927
928       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
929
930       mq->max_size.visible = new_size;
931
932       tmp = mq->queues;
933       while (tmp) {
934         GstDataQueueSize size;
935         GstSingleQueue *q = (GstSingleQueue *) tmp->data;
936         gst_data_queue_get_level (q->queue, &size);
937
938         GST_DEBUG_OBJECT (mq, "Queue %d: Requested buffers size: %d,"
939             " current: %d, current max %d", q->id, new_size, size.visible,
940             q->max_size.visible);
941
942         /* do not reduce max size below current level if the single queue
943          * has grown because of empty queue */
944         if (new_size == 0) {
945           q->max_size.visible = new_size;
946         } else if (q->max_size.visible == 0) {
947           q->max_size.visible = MAX (new_size, size.visible);
948         } else if (new_size > size.visible) {
949           q->max_size.visible = new_size;
950         }
951         update_buffering (mq, q);
952         gst_data_queue_limits_changed (q->queue);
953         tmp = g_list_next (tmp);
954       }
955
956       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
957       gst_multi_queue_post_buffering (mq);
958
959       break;
960     }
961     case PROP_MAX_SIZE_TIME:
962       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
963       mq->max_size.time = g_value_get_uint64 (value);
964       SET_CHILD_PROPERTY (mq, time);
965       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
966       gst_multi_queue_post_buffering (mq);
967       break;
968     case PROP_EXTRA_SIZE_BYTES:
969       mq->extra_size.bytes = g_value_get_uint (value);
970       break;
971     case PROP_EXTRA_SIZE_BUFFERS:
972       mq->extra_size.visible = g_value_get_uint (value);
973       break;
974     case PROP_EXTRA_SIZE_TIME:
975       mq->extra_size.time = g_value_get_uint64 (value);
976       break;
977     case PROP_USE_BUFFERING:
978       mq->use_buffering = g_value_get_boolean (value);
979       recheck_buffering_status (mq);
980       break;
981     case PROP_LOW_PERCENT:
982       mq->low_watermark = g_value_get_int (value) * BUF_LEVEL_PERCENT_FACTOR;
983       /* Recheck buffering status - the new low_watermark value might
984        * be above the current fill level. If the old low_watermark one
985        * was below the current level, this means that mq->buffering is
986        * disabled and needs to be re-enabled. */
987       recheck_buffering_status (mq);
988       break;
989     case PROP_HIGH_PERCENT:
990       mq->high_watermark = g_value_get_int (value) * BUF_LEVEL_PERCENT_FACTOR;
991       recheck_buffering_status (mq);
992       break;
993     case PROP_LOW_WATERMARK:
994       mq->low_watermark = g_value_get_double (value) * MAX_BUFFERING_LEVEL;
995       recheck_buffering_status (mq);
996       break;
997     case PROP_HIGH_WATERMARK:
998       mq->high_watermark = g_value_get_double (value) * MAX_BUFFERING_LEVEL;
999       recheck_buffering_status (mq);
1000       break;
1001     case PROP_SYNC_BY_RUNNING_TIME:
1002       mq->sync_by_running_time = g_value_get_boolean (value);
1003       break;
1004     case PROP_USE_INTERLEAVE:
1005       mq->use_interleave = g_value_get_boolean (value);
1006       break;
1007     case PROP_UNLINKED_CACHE_TIME:
1008       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1009       mq->unlinked_cache_time = g_value_get_uint64 (value);
1010       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1011       gst_multi_queue_post_buffering (mq);
1012       break;
1013     case PROP_MINIMUM_INTERLEAVE:
1014       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1015       mq->min_interleave_time = g_value_get_uint64 (value);
1016       if (mq->use_interleave)
1017         calculate_interleave (mq, NULL);
1018       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1019       break;
1020     default:
1021       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1022       break;
1023   }
1024 }
1025
1026 /* Called with mutex held */
1027 static GstStructure *
1028 gst_multi_queue_get_stats (GstMultiQueue * mq)
1029 {
1030   GstStructure *ret =
1031       gst_structure_new_empty ("application/x-gst-multi-queue-stats");
1032   GList *tmp;
1033   GstSingleQueue *sq;
1034
1035   if (mq->queues != NULL) {
1036     GValue queues = G_VALUE_INIT;
1037     GValue v = G_VALUE_INIT;
1038
1039     g_value_init (&queues, GST_TYPE_ARRAY);
1040
1041     for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1042       GstDataQueueSize level;
1043       GstStructure *s;
1044       gchar *id;
1045       g_value_init (&v, GST_TYPE_STRUCTURE);
1046
1047       sq = (GstSingleQueue *) tmp->data;
1048       gst_data_queue_get_level (sq->queue, &level);
1049       id = g_strdup_printf ("queue_%d", sq->id);
1050       s = gst_structure_new (id,
1051           "buffers", G_TYPE_UINT, level.visible,
1052           "bytes", G_TYPE_UINT, level.bytes,
1053           "time", G_TYPE_UINT64, sq->cur_time, NULL);
1054       g_value_take_boxed (&v, s);
1055       gst_value_array_append_and_take_value (&queues, &v);
1056       g_free (id);
1057     }
1058     gst_structure_take_value (ret, "queues", &queues);
1059   }
1060
1061   return ret;
1062 }
1063
1064 static void
1065 gst_multi_queue_get_property (GObject * object, guint prop_id,
1066     GValue * value, GParamSpec * pspec)
1067 {
1068   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
1069
1070   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1071
1072   switch (prop_id) {
1073     case PROP_EXTRA_SIZE_BYTES:
1074       g_value_set_uint (value, mq->extra_size.bytes);
1075       break;
1076     case PROP_EXTRA_SIZE_BUFFERS:
1077       g_value_set_uint (value, mq->extra_size.visible);
1078       break;
1079     case PROP_EXTRA_SIZE_TIME:
1080       g_value_set_uint64 (value, mq->extra_size.time);
1081       break;
1082     case PROP_MAX_SIZE_BYTES:
1083       g_value_set_uint (value, mq->max_size.bytes);
1084       break;
1085     case PROP_MAX_SIZE_BUFFERS:
1086       g_value_set_uint (value, mq->max_size.visible);
1087       break;
1088     case PROP_MAX_SIZE_TIME:
1089       g_value_set_uint64 (value, mq->max_size.time);
1090       break;
1091     case PROP_USE_BUFFERING:
1092       g_value_set_boolean (value, mq->use_buffering);
1093       break;
1094     case PROP_LOW_PERCENT:
1095       g_value_set_int (value, mq->low_watermark / BUF_LEVEL_PERCENT_FACTOR);
1096       break;
1097     case PROP_HIGH_PERCENT:
1098       g_value_set_int (value, mq->high_watermark / BUF_LEVEL_PERCENT_FACTOR);
1099       break;
1100     case PROP_LOW_WATERMARK:
1101       g_value_set_double (value, mq->low_watermark /
1102           (gdouble) MAX_BUFFERING_LEVEL);
1103       break;
1104     case PROP_HIGH_WATERMARK:
1105       g_value_set_double (value, mq->high_watermark /
1106           (gdouble) MAX_BUFFERING_LEVEL);
1107       break;
1108     case PROP_SYNC_BY_RUNNING_TIME:
1109       g_value_set_boolean (value, mq->sync_by_running_time);
1110       break;
1111     case PROP_USE_INTERLEAVE:
1112       g_value_set_boolean (value, mq->use_interleave);
1113       break;
1114     case PROP_UNLINKED_CACHE_TIME:
1115       g_value_set_uint64 (value, mq->unlinked_cache_time);
1116       break;
1117     case PROP_MINIMUM_INTERLEAVE:
1118       g_value_set_uint64 (value, mq->min_interleave_time);
1119       break;
1120     case PROP_STATS:
1121       g_value_take_boxed (value, gst_multi_queue_get_stats (mq));
1122       break;
1123     default:
1124       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1125       break;
1126   }
1127
1128   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1129 }
1130
1131 static GstIterator *
1132 gst_multi_queue_iterate_internal_links (GstPad * pad, GstObject * parent)
1133 {
1134   GstIterator *it = NULL;
1135   GstPad *opad, *sinkpad, *srcpad;
1136   GstSingleQueue *squeue;
1137   GstMultiQueue *mq = GST_MULTI_QUEUE (parent);
1138   GValue val = { 0, };
1139
1140   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1141   squeue = GST_MULTIQUEUE_PAD (pad)->sq;
1142   if (!squeue)
1143     goto out;
1144
1145   srcpad = g_weak_ref_get (&squeue->srcpad);
1146   sinkpad = g_weak_ref_get (&squeue->sinkpad);
1147   if (sinkpad == pad && srcpad) {
1148     opad = srcpad;
1149     gst_clear_object (&sinkpad);
1150
1151   } else if (srcpad == pad && sinkpad) {
1152     opad = sinkpad;
1153     gst_clear_object (&srcpad);
1154
1155   } else {
1156     gst_clear_object (&srcpad);
1157     gst_clear_object (&sinkpad);
1158     goto out;
1159   }
1160
1161   g_value_init (&val, GST_TYPE_PAD);
1162   g_value_set_object (&val, opad);
1163   it = gst_iterator_new_single (GST_TYPE_PAD, &val);
1164   g_value_unset (&val);
1165
1166   gst_object_unref (opad);
1167
1168 out:
1169   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1170
1171   return it;
1172 }
1173
1174
1175 /*
1176  * GstElement methods
1177  */
1178
1179 static GstPad *
1180 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
1181     const gchar * name, const GstCaps * caps)
1182 {
1183   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1184   GstSingleQueue *squeue;
1185   GstPad *new_pad;
1186   guint temp_id = -1;
1187
1188   if (name) {
1189     sscanf (name + 4, "_%u", &temp_id);
1190     GST_LOG_OBJECT (element, "name : %s (id %d)", GST_STR_NULL (name), temp_id);
1191   }
1192
1193   /* Create a new single queue, add the sink and source pad and return the sink pad */
1194   squeue = gst_single_queue_new (mqueue, temp_id);
1195
1196   new_pad = squeue ? g_weak_ref_get (&squeue->sinkpad) : NULL;
1197   /* request pad assumes the element is owning the ref of the pad it returns */
1198   if (new_pad)
1199     gst_object_unref (new_pad);
1200
1201   GST_DEBUG_OBJECT (mqueue, "Returning pad %" GST_PTR_FORMAT, new_pad);
1202
1203   return new_pad;
1204 }
1205
1206 static void
1207 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
1208 {
1209   GstPad *sinkpad = NULL, *srcpad = NULL;
1210   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1211   GstSingleQueue *sq = NULL;
1212   GList *tmp;
1213
1214   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1215
1216   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1217   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
1218   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1219     sq = (GstSingleQueue *) tmp->data;
1220     sinkpad = g_weak_ref_get (&sq->sinkpad);
1221
1222     if (sinkpad == pad) {
1223       srcpad = g_weak_ref_get (&sq->srcpad);
1224       break;
1225     }
1226
1227     gst_object_unref (sinkpad);
1228   }
1229
1230   if (!tmp) {
1231     gst_clear_object (&sinkpad);
1232     gst_clear_object (&srcpad);
1233     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
1234     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1235     return;
1236   }
1237
1238   /* FIXME: The removal of the singlequeue should probably not happen until it
1239    * finishes draining */
1240
1241   /* remove it from the list */
1242   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
1243   mqueue->queues_cookie++;
1244
1245   /* FIXME : recompute next-non-linked */
1246   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1247
1248   /* delete SingleQueue */
1249   gst_data_queue_set_flushing (sq->queue, TRUE);
1250
1251   gst_pad_set_active (srcpad, FALSE);
1252   gst_pad_set_active (sinkpad, FALSE);
1253   gst_element_remove_pad (element, srcpad);
1254   gst_element_remove_pad (element, sinkpad);
1255   gst_object_unref (srcpad);
1256   gst_object_unref (sinkpad);
1257 }
1258
1259 static GstStateChangeReturn
1260 gst_multi_queue_change_state (GstElement * element, GstStateChange transition)
1261 {
1262   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
1263   GstSingleQueue *sq = NULL;
1264   GstStateChangeReturn result;
1265
1266   switch (transition) {
1267     case GST_STATE_CHANGE_READY_TO_PAUSED:{
1268       GList *tmp;
1269
1270       /* Set all pads to non-flushing */
1271       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1272       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1273         sq = (GstSingleQueue *) tmp->data;
1274         sq->flushing = FALSE;
1275       }
1276
1277       /* the visible limit might not have been set on single queues that have grown because of other queueus were empty */
1278       SET_CHILD_PROPERTY (mqueue, visible);
1279
1280       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1281       gst_multi_queue_post_buffering (mqueue);
1282
1283       break;
1284     }
1285     case GST_STATE_CHANGE_PAUSED_TO_READY:{
1286       GList *tmp;
1287
1288       /* Un-wait all waiting pads */
1289       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1290       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
1291         sq = (GstSingleQueue *) tmp->data;
1292         sq->flushing = TRUE;
1293         g_cond_signal (&sq->turn);
1294
1295         sq->last_query = FALSE;
1296         g_cond_signal (&sq->query_handled);
1297       }
1298       mqueue->interleave_incomplete = FALSE;
1299       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1300       break;
1301     }
1302     default:
1303       break;
1304   }
1305
1306   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1307
1308   switch (transition) {
1309     default:
1310       break;
1311   }
1312
1313   return result;
1314 }
1315
1316 static gboolean
1317 gst_single_queue_start (GstMultiQueue * mq, GstSingleQueue * sq)
1318 {
1319   gboolean res = FALSE;
1320   GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
1321
1322   GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
1323
1324   if (srcpad) {
1325     res = gst_pad_start_task (srcpad,
1326         (GstTaskFunction) gst_multi_queue_loop, srcpad, NULL);
1327     gst_object_unref (srcpad);
1328   }
1329
1330   return res;
1331 }
1332
1333 static gboolean
1334 gst_single_queue_pause (GstMultiQueue * mq, GstSingleQueue * sq)
1335 {
1336   gboolean result = FALSE;
1337   GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
1338
1339   GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
1340   if (srcpad) {
1341     result = gst_pad_pause_task (srcpad);
1342     gst_object_unref (srcpad);
1343   }
1344
1345   sq->sink_tainted = sq->src_tainted = TRUE;
1346   return result;
1347 }
1348
1349 static gboolean
1350 gst_single_queue_stop (GstMultiQueue * mq, GstSingleQueue * sq)
1351 {
1352   gboolean result = FALSE;
1353   GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
1354
1355   GST_LOG_OBJECT (mq, "SingleQueue %d : stopping task", sq->id);
1356   if (srcpad) {
1357     result = gst_pad_stop_task (srcpad);
1358     gst_object_unref (srcpad);
1359   }
1360   sq->sink_tainted = sq->src_tainted = TRUE;
1361   return result;
1362 }
1363
1364 static void
1365 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush,
1366     gboolean full)
1367 {
1368   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
1369       sq->id);
1370
1371   if (flush) {
1372     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1373     sq->srcresult = GST_FLOW_FLUSHING;
1374     gst_data_queue_set_flushing (sq->queue, TRUE);
1375
1376     sq->flushing = TRUE;
1377
1378     /* wake up non-linked task */
1379     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
1380         sq->id);
1381     g_cond_signal (&sq->turn);
1382     sq->last_query = FALSE;
1383     g_cond_signal (&sq->query_handled);
1384     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1385   } else {
1386     gst_single_queue_flush_queue (sq, full);
1387
1388     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1389     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
1390     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
1391     sq->has_src_segment = FALSE;
1392     /* All pads start off OK for a smooth kick-off */
1393     sq->srcresult = GST_FLOW_OK;
1394     sq->pushed = FALSE;
1395     sq->cur_time = 0;
1396     sq->max_size.visible = mq->max_size.visible;
1397     sq->is_eos = FALSE;
1398     sq->is_segment_done = FALSE;
1399     sq->nextid = 0;
1400     sq->oldid = 0;
1401     sq->last_oldid = G_MAXUINT32;
1402     sq->next_time = GST_CLOCK_STIME_NONE;
1403     sq->last_time = GST_CLOCK_STIME_NONE;
1404     sq->cached_sinktime = GST_CLOCK_STIME_NONE;
1405     sq->group_high_time = GST_CLOCK_STIME_NONE;
1406     gst_data_queue_set_flushing (sq->queue, FALSE);
1407
1408     /* We will become active again on the next buffer/gap */
1409     sq->active = FALSE;
1410
1411     /* Reset high time to be recomputed next */
1412     mq->high_time = GST_CLOCK_STIME_NONE;
1413
1414     sq->flushing = FALSE;
1415     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1416   }
1417 }
1418
1419 /* WITH LOCK TAKEN */
1420 static gint
1421 get_buffering_level (GstMultiQueue * mq, GstSingleQueue * sq)
1422 {
1423   GstDataQueueSize size;
1424   gint buffering_level, tmp;
1425
1426   gst_data_queue_get_level (sq->queue, &size);
1427
1428   GST_DEBUG_OBJECT (mq,
1429       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1430       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
1431       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1432
1433   /* get bytes and time buffer levels and take the max */
1434   if (sq->is_eos || sq->is_segment_done || sq->srcresult == GST_FLOW_NOT_LINKED
1435       || sq->is_sparse) {
1436     buffering_level = MAX_BUFFERING_LEVEL;
1437   } else {
1438     buffering_level = 0;
1439     if (sq->max_size.time > 0) {
1440       tmp =
1441           gst_util_uint64_scale (sq->cur_time,
1442           MAX_BUFFERING_LEVEL, sq->max_size.time);
1443       buffering_level = MAX (buffering_level, tmp);
1444     }
1445     if (sq->max_size.bytes > 0) {
1446       tmp =
1447           gst_util_uint64_scale_int (size.bytes,
1448           MAX_BUFFERING_LEVEL, sq->max_size.bytes);
1449       buffering_level = MAX (buffering_level, tmp);
1450     }
1451   }
1452
1453   return buffering_level;
1454 }
1455
1456 /* WITH LOCK TAKEN */
1457 static void
1458 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
1459 {
1460   gint buffering_level, percent;
1461
1462   /* nothing to dowhen we are not in buffering mode */
1463   if (!mq->use_buffering)
1464     return;
1465
1466   buffering_level = get_buffering_level (mq, sq);
1467
1468   /* scale so that if buffering_level equals the high watermark,
1469    * the percentage is 100% */
1470   percent = gst_util_uint64_scale (buffering_level, 100, mq->high_watermark);
1471   /* clip */
1472   if (percent > 100)
1473     percent = 100;
1474
1475   if (mq->buffering) {
1476     if (buffering_level >= mq->high_watermark) {
1477       mq->buffering = FALSE;
1478     }
1479     /* make sure it increases */
1480     percent = MAX (mq->buffering_percent, percent);
1481
1482     SET_PERCENT (mq, percent);
1483   } else {
1484     GList *iter;
1485     gboolean is_buffering = TRUE;
1486
1487     for (iter = mq->queues; iter; iter = g_list_next (iter)) {
1488       GstSingleQueue *oq = (GstSingleQueue *) iter->data;
1489
1490       if (get_buffering_level (mq, oq) >= mq->high_watermark) {
1491         is_buffering = FALSE;
1492
1493         break;
1494       }
1495     }
1496
1497     if (is_buffering && buffering_level < mq->low_watermark) {
1498       mq->buffering = TRUE;
1499       SET_PERCENT (mq, percent);
1500     }
1501   }
1502 }
1503
1504 static void
1505 gst_multi_queue_post_buffering (GstMultiQueue * mq)
1506 {
1507   GstMessage *msg = NULL;
1508
1509   g_mutex_lock (&mq->buffering_post_lock);
1510   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1511   if (mq->buffering_percent_changed) {
1512     gint percent = mq->buffering_percent;
1513
1514     mq->buffering_percent_changed = FALSE;
1515
1516     GST_DEBUG_OBJECT (mq, "Going to post buffering: %d%%", percent);
1517     msg = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
1518   }
1519   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1520
1521   if (msg != NULL)
1522     gst_element_post_message (GST_ELEMENT_CAST (mq), msg);
1523
1524   g_mutex_unlock (&mq->buffering_post_lock);
1525 }
1526
1527 static void
1528 recheck_buffering_status (GstMultiQueue * mq)
1529 {
1530   if (!mq->use_buffering && mq->buffering) {
1531     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1532     mq->buffering = FALSE;
1533     GST_DEBUG_OBJECT (mq,
1534         "Buffering property disabled, but queue was still buffering; "
1535         "setting buffering percentage to 100%%");
1536     SET_PERCENT (mq, 100);
1537     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1538   }
1539
1540   if (mq->use_buffering) {
1541     GList *tmp;
1542     gint old_perc;
1543
1544     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1545
1546     /* force buffering percentage to be recalculated */
1547     old_perc = mq->buffering_percent;
1548     mq->buffering_percent = 0;
1549
1550     tmp = mq->queues;
1551     while (tmp) {
1552       GstSingleQueue *q = (GstSingleQueue *) tmp->data;
1553       update_buffering (mq, q);
1554       gst_data_queue_limits_changed (q->queue);
1555       tmp = g_list_next (tmp);
1556     }
1557
1558     GST_DEBUG_OBJECT (mq,
1559         "Recalculated buffering percentage: old: %d%% new: %d%%",
1560         old_perc, mq->buffering_percent);
1561
1562     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1563   }
1564
1565   gst_multi_queue_post_buffering (mq);
1566 }
1567
1568 static void
1569 calculate_interleave (GstMultiQueue * mq, GstSingleQueue * sq)
1570 {
1571   GstClockTimeDiff low, high;
1572   GstClockTime interleave, other_interleave = 0;
1573   gboolean some_inactive = FALSE;
1574   GList *tmp;
1575
1576   low = high = GST_CLOCK_STIME_NONE;
1577   interleave = mq->interleave;
1578   /* Go over all single queues and calculate lowest/highest value */
1579   for (tmp = mq->queues; tmp; tmp = tmp->next) {
1580     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1581     /* Ignore sparse streams for interleave calculation */
1582     if (oq->is_sparse)
1583       continue;
1584
1585     /* If some streams aren't active yet (haven't received any buffers), we will
1586      * grow interleave accordingly */
1587     if (!oq->active) {
1588       some_inactive = TRUE;
1589       continue;
1590     }
1591
1592     /* Calculate within each streaming thread */
1593     if (sq && sq->thread != oq->thread) {
1594       if (oq->interleave > other_interleave)
1595         other_interleave = oq->interleave;
1596       continue;
1597     }
1598
1599     /* If the stream isn't EOS, update the low/high input value */
1600     if (GST_CLOCK_STIME_IS_VALID (oq->cached_sinktime) && !oq->is_eos) {
1601       if (low == GST_CLOCK_STIME_NONE || oq->cached_sinktime < low)
1602         low = oq->cached_sinktime;
1603       if (high == GST_CLOCK_STIME_NONE || oq->cached_sinktime > high)
1604         high = oq->cached_sinktime;
1605
1606       /* If the input is before the segment start, consider as inactive to allow
1607        * the interleave to grow until *all* streams have data within the segment.
1608        *
1609        * The reason for this is that there is no requirements for data before
1610        * the segment start to be "aligned" and therefore interleave calculation
1611        * can't reliably be done. For example a demuxer could provide video data
1612        * from the previous keyframe but audio only from just before the segment
1613        * start */
1614       if (oq->cached_sinktime < 0)
1615         some_inactive = TRUE;
1616     }
1617     GST_LOG_OBJECT (mq,
1618         "queue %d , sinktime:%" GST_STIME_FORMAT " low:%" GST_STIME_FORMAT
1619         " high:%" GST_STIME_FORMAT, oq->id,
1620         GST_STIME_ARGS (oq->cached_sinktime), GST_STIME_ARGS (low),
1621         GST_STIME_ARGS (high));
1622   }
1623
1624   if (GST_CLOCK_STIME_IS_VALID (low) && GST_CLOCK_STIME_IS_VALID (high)) {
1625     gboolean do_update = high == low;
1626     interleave = high - low;
1627     /* Padding of interleave and minimum value */
1628     interleave = (150 * interleave / 100) + mq->min_interleave_time;
1629     if (sq)
1630       sq->interleave = interleave;
1631
1632     interleave = MAX (interleave, other_interleave);
1633
1634     /* Progressively grow up the interleave up to 5s if some streams were inactive */
1635     if (some_inactive && interleave <= mq->interleave) {
1636       interleave = MIN (5 * GST_SECOND, mq->interleave + 500 * GST_MSECOND);
1637       do_update = TRUE;
1638     }
1639
1640     /* We force the interleave update if:
1641      * * the interleave was previously set while some streams were not active
1642      *   yet but they now all are
1643      * * OR the interleave was previously based on all streams being active
1644      *   whereas some now aren't
1645      */
1646     if (mq->interleave_incomplete != some_inactive)
1647       do_update = TRUE;
1648
1649     mq->interleave_incomplete = some_inactive;
1650
1651     /* Update the stored interleave if:
1652      * * No data has arrived yet (high == low)
1653      * * Or it went higher
1654      * * Or it went lower and we've gone past the previous interleave needed */
1655     if (do_update || interleave > mq->interleave ||
1656         ((mq->last_interleave_update + (2 * MIN (GST_SECOND,
1657                         mq->interleave)) < low)
1658             && interleave < (mq->interleave * 3 / 4))) {
1659       /* Update the interleave */
1660       mq->interleave = interleave;
1661       mq->last_interleave_update = high;
1662       /* Update max-size time */
1663       mq->max_size.time = mq->interleave;
1664       SET_CHILD_PROPERTY (mq, time);
1665     }
1666   }
1667
1668   GST_DEBUG_OBJECT (mq,
1669       "low:%" GST_STIME_FORMAT " high:%" GST_STIME_FORMAT " interleave:%"
1670       GST_TIME_FORMAT " mq->interleave:%" GST_TIME_FORMAT
1671       " last_interleave_update:%" GST_STIME_FORMAT, GST_STIME_ARGS (low),
1672       GST_STIME_ARGS (high), GST_TIME_ARGS (interleave),
1673       GST_TIME_ARGS (mq->interleave),
1674       GST_STIME_ARGS (mq->last_interleave_update));
1675 }
1676
1677
1678 /* calculate the diff between running time on the sink and src of the queue.
1679  * This is the total amount of time in the queue.
1680  * WITH LOCK TAKEN */
1681 static void
1682 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
1683 {
1684   GstClockTimeDiff sink_time, src_time;
1685
1686   if (sq->sink_tainted) {
1687     sink_time = sq->sinktime = my_segment_to_running_time (&sq->sink_segment,
1688         sq->sink_segment.position);
1689
1690     GST_DEBUG_OBJECT (mq,
1691         "queue %d sink_segment.position:%" GST_TIME_FORMAT ", sink_time:%"
1692         GST_STIME_FORMAT, sq->id, GST_TIME_ARGS (sq->sink_segment.position),
1693         GST_STIME_ARGS (sink_time));
1694
1695     if (G_UNLIKELY (sq->last_time == GST_CLOCK_STIME_NONE)) {
1696       /* If the single queue still doesn't have a last_time set, this means
1697        * that nothing has been pushed out yet.
1698        * In order for the high_time computation to be as efficient as possible,
1699        * we set the last_time */
1700       sq->last_time = sink_time;
1701     }
1702     if (G_UNLIKELY (sink_time != GST_CLOCK_STIME_NONE)) {
1703       /* if we have a time, we become untainted and use the time */
1704       sq->sink_tainted = FALSE;
1705       if (mq->use_interleave) {
1706         sq->cached_sinktime = sink_time;
1707         calculate_interleave (mq, sq);
1708       }
1709     }
1710   } else
1711     sink_time = sq->sinktime;
1712
1713   if (sq->src_tainted) {
1714     GstSegment *segment;
1715     gint64 position;
1716
1717     if (sq->has_src_segment) {
1718       segment = &sq->src_segment;
1719       position = sq->src_segment.position;
1720     } else {
1721       /*
1722        * If the src pad had no segment yet, use the sink segment
1723        * to avoid signalling overrun if the received sink segment has a
1724        * a position > max-size-time while the src pad time would be the default=0
1725        *
1726        * This can happen when switching pads on chained/adaptive streams and the
1727        * new chain has a segment with a much larger position
1728        */
1729       segment = &sq->sink_segment;
1730       position = sq->sink_segment.position;
1731     }
1732
1733     src_time = sq->srctime = my_segment_to_running_time (segment, position);
1734     /* if we have a time, we become untainted and use the time */
1735     if (G_UNLIKELY (src_time != GST_CLOCK_STIME_NONE)) {
1736       sq->src_tainted = FALSE;
1737     }
1738   } else
1739     src_time = sq->srctime;
1740
1741   GST_DEBUG_OBJECT (mq,
1742       "queue %d, sink %" GST_STIME_FORMAT ", src %" GST_STIME_FORMAT, sq->id,
1743       GST_STIME_ARGS (sink_time), GST_STIME_ARGS (src_time));
1744
1745   /* This allows for streams with out of order timestamping - sometimes the
1746    * emerging timestamp is later than the arriving one(s) */
1747   if (G_LIKELY (GST_CLOCK_STIME_IS_VALID (sink_time) &&
1748           GST_CLOCK_STIME_IS_VALID (src_time) && sink_time > src_time))
1749     sq->cur_time = sink_time - src_time;
1750   else
1751     sq->cur_time = 0;
1752
1753   /* updating the time level can change the buffering state */
1754   update_buffering (mq, sq);
1755
1756   return;
1757 }
1758
1759 /* take a SEGMENT event and apply the values to segment, updating the time
1760  * level of queue. */
1761 static void
1762 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
1763     GstSegment * segment)
1764 {
1765   gst_event_copy_segment (event, segment);
1766
1767   /* now configure the values, we use these to track timestamps on the
1768    * sinkpad. */
1769   if (segment->format != GST_FORMAT_TIME) {
1770     /* non-time format, pretent the current time segment is closed with a
1771      * 0 start and unknown stop time. */
1772     segment->format = GST_FORMAT_TIME;
1773     segment->start = 0;
1774     segment->stop = -1;
1775     segment->time = 0;
1776   }
1777   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1778
1779   /* Make sure we have a valid initial segment position (and not garbage
1780    * from upstream) */
1781   if (segment->rate > 0.0)
1782     segment->position = segment->start;
1783   else
1784     segment->position = segment->stop;
1785   if (segment == &sq->sink_segment)
1786     sq->sink_tainted = TRUE;
1787   else {
1788     sq->has_src_segment = TRUE;
1789     sq->src_tainted = TRUE;
1790   }
1791
1792   GST_DEBUG_OBJECT (mq,
1793       "queue %d, configured SEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
1794
1795   /* segment can update the time level of the queue */
1796   update_time_level (mq, sq);
1797
1798   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1799   gst_multi_queue_post_buffering (mq);
1800 }
1801
1802 /* take a buffer and update segment, updating the time level of the queue. */
1803 static void
1804 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
1805     GstClockTime duration, GstSegment * segment)
1806 {
1807   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1808
1809   /* if no timestamp is set, assume it's continuous with the previous
1810    * time */
1811   if (timestamp == GST_CLOCK_TIME_NONE)
1812     timestamp = segment->position;
1813
1814   /* add duration */
1815   if (duration != GST_CLOCK_TIME_NONE)
1816     timestamp += duration;
1817
1818   GST_DEBUG_OBJECT (mq, "queue %d, %s position updated to %" GST_TIME_FORMAT,
1819       sq->id, segment == &sq->sink_segment ? "sink" : "src",
1820       GST_TIME_ARGS (timestamp));
1821
1822   segment->position = timestamp;
1823
1824   if (segment == &sq->sink_segment)
1825     sq->sink_tainted = TRUE;
1826   else
1827     sq->src_tainted = TRUE;
1828
1829   /* calc diff with other end */
1830   update_time_level (mq, sq);
1831   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1832   gst_multi_queue_post_buffering (mq);
1833 }
1834
1835 static void
1836 apply_gap (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
1837     GstSegment * segment)
1838 {
1839   GstClockTime timestamp;
1840   GstClockTime duration;
1841
1842   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1843
1844   gst_event_parse_gap (event, &timestamp, &duration);
1845
1846   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1847
1848     if (GST_CLOCK_TIME_IS_VALID (duration)) {
1849       timestamp += duration;
1850     }
1851
1852     GST_DEBUG_OBJECT (mq, "queue %d, %s position updated to %" GST_TIME_FORMAT,
1853         sq->id, segment == &sq->sink_segment ? "sink" : "src",
1854         GST_TIME_ARGS (timestamp));
1855
1856     segment->position = timestamp;
1857
1858     if (segment == &sq->sink_segment)
1859       sq->sink_tainted = TRUE;
1860     else
1861       sq->src_tainted = TRUE;
1862
1863     /* calc diff with other end */
1864     update_time_level (mq, sq);
1865   }
1866
1867   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1868   gst_multi_queue_post_buffering (mq);
1869 }
1870
1871 static GstClockTimeDiff
1872 get_running_time (GstSegment * segment, GstMiniObject * object, gboolean end)
1873 {
1874   GstClockTimeDiff time = GST_CLOCK_STIME_NONE;
1875
1876   if (GST_IS_BUFFER (object)) {
1877     GstBuffer *buf = GST_BUFFER_CAST (object);
1878     GstClockTime btime = GST_BUFFER_DTS_OR_PTS (buf);
1879
1880     if (GST_CLOCK_TIME_IS_VALID (btime)) {
1881       if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1882         btime += GST_BUFFER_DURATION (buf);
1883       time = my_segment_to_running_time (segment, btime);
1884     }
1885   } else if (GST_IS_BUFFER_LIST (object)) {
1886     GstBufferList *list = GST_BUFFER_LIST_CAST (object);
1887     gint i, n;
1888     GstBuffer *buf;
1889
1890     n = gst_buffer_list_length (list);
1891     for (i = 0; i < n; i++) {
1892       GstClockTime btime;
1893       buf = gst_buffer_list_get (list, i);
1894       btime = GST_BUFFER_DTS_OR_PTS (buf);
1895       if (GST_CLOCK_TIME_IS_VALID (btime)) {
1896         if (end && GST_BUFFER_DURATION_IS_VALID (buf))
1897           btime += GST_BUFFER_DURATION (buf);
1898         time = my_segment_to_running_time (segment, btime);
1899         if (!end)
1900           goto done;
1901       } else if (!end) {
1902         goto done;
1903       }
1904     }
1905   } else if (GST_IS_EVENT (object)) {
1906     GstEvent *event = GST_EVENT_CAST (object);
1907
1908     /* For newsegment events return the running time of the start position */
1909     if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
1910       const GstSegment *new_segment;
1911
1912       gst_event_parse_segment (event, &new_segment);
1913       if (new_segment->format == GST_FORMAT_TIME) {
1914         time =
1915             my_segment_to_running_time ((GstSegment *) new_segment,
1916             new_segment->start);
1917       }
1918     } else if (GST_EVENT_TYPE (event) == GST_EVENT_GAP) {
1919       GstClockTime ts, dur;
1920       gst_event_parse_gap (event, &ts, &dur);
1921       if (GST_CLOCK_TIME_IS_VALID (ts)) {
1922         if (GST_CLOCK_TIME_IS_VALID (dur))
1923           ts += dur;
1924         time = my_segment_to_running_time (segment, ts);
1925       }
1926     }
1927   }
1928
1929 done:
1930   return time;
1931 }
1932
1933 static GstFlowReturn
1934 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
1935     GstMiniObject * object, gboolean * allow_drop)
1936 {
1937   GstFlowReturn result = sq->srcresult;
1938   GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
1939
1940   if (!srcpad) {
1941     GST_INFO_OBJECT (mq,
1942         "Pushing while corresponding sourcepad has been cleared");
1943     return GST_FLOW_FLUSHING;
1944   }
1945
1946   if (GST_IS_BUFFER (object)) {
1947     GstBuffer *buffer;
1948     GstClockTime timestamp, duration;
1949
1950     buffer = GST_BUFFER_CAST (object);
1951     timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
1952     duration = GST_BUFFER_DURATION (buffer);
1953
1954     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
1955
1956     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
1957     gst_data_queue_limits_changed (sq->queue);
1958
1959     if (G_UNLIKELY (*allow_drop)) {
1960       GST_DEBUG_OBJECT (mq,
1961           "SingleQueue %d : Dropping EOS buffer %p with ts %" GST_TIME_FORMAT,
1962           sq->id, buffer, GST_TIME_ARGS (timestamp));
1963       gst_buffer_unref (buffer);
1964     } else {
1965       GST_DEBUG_OBJECT (mq,
1966           "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
1967           sq->id, buffer, GST_TIME_ARGS (timestamp));
1968       result = gst_pad_push (srcpad, buffer);
1969     }
1970   } else if (GST_IS_EVENT (object)) {
1971     GstEvent *event;
1972
1973     event = GST_EVENT_CAST (object);
1974
1975     switch (GST_EVENT_TYPE (event)) {
1976       case GST_EVENT_SEGMENT_DONE:
1977         *allow_drop = FALSE;
1978         break;
1979       case GST_EVENT_EOS:
1980         result = GST_FLOW_EOS;
1981         if (G_UNLIKELY (*allow_drop))
1982           *allow_drop = FALSE;
1983         break;
1984       case GST_EVENT_STREAM_START:
1985         result = GST_FLOW_OK;
1986         if (G_UNLIKELY (*allow_drop))
1987           *allow_drop = FALSE;
1988         break;
1989       case GST_EVENT_SEGMENT:
1990         apply_segment (mq, sq, event, &sq->src_segment);
1991         /* Applying the segment may have made the queue non-full again, unblock it if needed */
1992         gst_data_queue_limits_changed (sq->queue);
1993         if (G_UNLIKELY (*allow_drop)) {
1994           result = GST_FLOW_OK;
1995           *allow_drop = FALSE;
1996         }
1997         break;
1998       case GST_EVENT_GAP:
1999         apply_gap (mq, sq, event, &sq->src_segment);
2000         /* Applying the gap may have made the queue non-full again, unblock it if needed */
2001         gst_data_queue_limits_changed (sq->queue);
2002         break;
2003       default:
2004         break;
2005     }
2006
2007     if (G_UNLIKELY (*allow_drop)) {
2008       GST_DEBUG_OBJECT (mq,
2009           "SingleQueue %d : Dropping EOS event %p of type %s",
2010           sq->id, event, GST_EVENT_TYPE_NAME (event));
2011       gst_event_unref (event);
2012     } else {
2013       GST_DEBUG_OBJECT (mq,
2014           "SingleQueue %d : Pushing event %p of type %s",
2015           sq->id, event, GST_EVENT_TYPE_NAME (event));
2016
2017       gst_pad_push_event (srcpad, event);
2018     }
2019   } else if (GST_IS_QUERY (object)) {
2020     GstQuery *query;
2021     gboolean res;
2022
2023     query = GST_QUERY_CAST (object);
2024
2025     if (G_UNLIKELY (*allow_drop)) {
2026       GST_DEBUG_OBJECT (mq,
2027           "SingleQueue %d : Dropping EOS query %p", sq->id, query);
2028       gst_query_unref (query);
2029       res = FALSE;
2030     } else {
2031       res = gst_pad_peer_query (srcpad, query);
2032     }
2033
2034     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2035     sq->last_query = res;
2036     sq->last_handled_query = query;
2037     g_cond_signal (&sq->query_handled);
2038     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2039   } else {
2040     g_warning ("Unexpected object in singlequeue %u (refcounting problem?)",
2041         sq->id);
2042   }
2043
2044   gst_object_unref (srcpad);
2045   return result;
2046
2047   /* ERRORS */
2048 }
2049
2050 static GstMiniObject *
2051 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
2052 {
2053   GstMiniObject *res;
2054
2055   res = item->object;
2056   item->object = NULL;
2057
2058   return res;
2059 }
2060
2061 static void
2062 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
2063 {
2064   if (!item->is_query && item->object)
2065     gst_mini_object_unref (item->object);
2066   g_slice_free (GstMultiQueueItem, item);
2067 }
2068
2069 /* takes ownership of passed mini object! */
2070 static GstMultiQueueItem *
2071 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
2072 {
2073   GstMultiQueueItem *item;
2074
2075   item = g_slice_new (GstMultiQueueItem);
2076   item->object = object;
2077   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
2078   item->posid = curid;
2079   item->is_query = GST_IS_QUERY (object);
2080
2081   item->size = gst_buffer_get_size (GST_BUFFER_CAST (object));
2082   item->duration = GST_BUFFER_DURATION (object);
2083   if (item->duration == GST_CLOCK_TIME_NONE)
2084     item->duration = 0;
2085   item->visible = TRUE;
2086   return item;
2087 }
2088
2089 static GstMultiQueueItem *
2090 gst_multi_queue_mo_item_new (GstMiniObject * object, guint32 curid)
2091 {
2092   GstMultiQueueItem *item;
2093
2094   item = g_slice_new (GstMultiQueueItem);
2095   item->object = object;
2096   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
2097   item->posid = curid;
2098   item->is_query = GST_IS_QUERY (object);
2099
2100   item->size = 0;
2101   item->duration = 0;
2102   item->visible = FALSE;
2103   return item;
2104 }
2105
2106 /* Each main loop attempts to push buffers until the return value
2107  * is not-linked. not-linked pads are not allowed to push data beyond
2108  * any linked pads, so they don't 'rush ahead of the pack'.
2109  */
2110 static void
2111 gst_multi_queue_loop (GstPad * pad)
2112 {
2113   GstSingleQueue *sq;
2114   GstMultiQueueItem *item;
2115   GstDataQueueItem *sitem;
2116   GstMultiQueue *mq;
2117   GstMiniObject *object = NULL;
2118   guint32 newid;
2119   GstFlowReturn result;
2120   GstClockTimeDiff next_time;
2121   gboolean is_buffer, is_query;
2122   gboolean do_update_buffering = FALSE;
2123   gboolean dropping = FALSE;
2124   GstPad *srcpad = NULL;
2125
2126   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2127   mq = g_weak_ref_get (&sq->mqueue);
2128   srcpad = g_weak_ref_get (&sq->srcpad);
2129
2130   if (!mq || !srcpad)
2131     goto out_flushing;
2132
2133 next:
2134   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
2135
2136   if (sq->flushing)
2137     goto out_flushing;
2138
2139   /* Get something from the queue, blocking until that happens, or we get
2140    * flushed */
2141   if (!(gst_data_queue_pop (sq->queue, &sitem)))
2142     goto out_flushing;
2143
2144   item = (GstMultiQueueItem *) sitem;
2145   newid = item->posid;
2146
2147   is_query = item->is_query;
2148
2149   /* steal the object and destroy the item */
2150   object = gst_multi_queue_item_steal_object (item);
2151   gst_multi_queue_item_destroy (item);
2152
2153   is_buffer = GST_IS_BUFFER (object);
2154
2155   /* Get running time of the item. Events will have GST_CLOCK_STIME_NONE */
2156   next_time = get_running_time (&sq->src_segment, object, FALSE);
2157
2158   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
2159       sq->id, newid, sq->last_oldid);
2160
2161   /* If we're not-linked, we do some extra work because we might need to
2162    * wait before pushing. If we're linked but there's a gap in the IDs,
2163    * or it's the first loop, or we just passed the previous highid,
2164    * we might need to wake some sleeping pad up, so there's extra work
2165    * there too */
2166   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2167   if (sq->srcresult == GST_FLOW_NOT_LINKED
2168       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
2169       || sq->last_oldid > mq->highid) {
2170     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
2171         gst_flow_get_name (sq->srcresult));
2172
2173     /* Check again if we're flushing after the lock is taken,
2174      * the flush flag might have been changed in the meantime */
2175     if (sq->flushing) {
2176       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2177       goto out_flushing;
2178     }
2179
2180     /* Update the nextid so other threads know when to wake us up */
2181     sq->nextid = newid;
2182     /* Take into account the extra cache time since we're unlinked */
2183     if (GST_CLOCK_STIME_IS_VALID (next_time))
2184       next_time += mq->unlinked_cache_time;
2185     sq->next_time = next_time;
2186
2187     /* Update the oldid (the last ID we output) for highid tracking */
2188     if (sq->last_oldid != G_MAXUINT32)
2189       sq->oldid = sq->last_oldid;
2190
2191     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2192       gboolean should_wait;
2193       /* Go to sleep until it's time to push this buffer */
2194
2195       /* Recompute the highid */
2196       compute_high_id (mq);
2197       /* Recompute the high time */
2198       compute_high_time (mq, sq->groupid);
2199
2200       GST_DEBUG_OBJECT (mq,
2201           "groupid %d high_time %" GST_STIME_FORMAT " next_time %"
2202           GST_STIME_FORMAT, sq->groupid, GST_STIME_ARGS (sq->group_high_time),
2203           GST_STIME_ARGS (next_time));
2204
2205       if (mq->sync_by_running_time) {
2206         if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2207           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2208               (mq->high_time == GST_CLOCK_STIME_NONE
2209               || next_time > mq->high_time);
2210         } else {
2211           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2212               next_time > sq->group_high_time;
2213         }
2214       } else
2215         should_wait = newid > mq->highid;
2216
2217       while (should_wait && sq->srcresult == GST_FLOW_NOT_LINKED) {
2218
2219         GST_DEBUG_OBJECT (mq,
2220             "queue %d sleeping for not-linked wakeup with "
2221             "newid %u, highid %u, next_time %" GST_STIME_FORMAT
2222             ", high_time %" GST_STIME_FORMAT, sq->id, newid, mq->highid,
2223             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time));
2224
2225         /* Wake up all non-linked pads before we sleep */
2226         wake_up_next_non_linked (mq);
2227
2228         mq->numwaiting++;
2229         g_cond_wait (&sq->turn, &mq->qlock);
2230         mq->numwaiting--;
2231
2232         if (sq->flushing) {
2233           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2234           goto out_flushing;
2235         }
2236
2237         /* Recompute the high time and ID */
2238         compute_high_time (mq, sq->groupid);
2239         compute_high_id (mq);
2240
2241         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
2242             "wakeup with newid %u, highid %u, next_time %" GST_STIME_FORMAT
2243             ", high_time %" GST_STIME_FORMAT " mq high_time %" GST_STIME_FORMAT,
2244             sq->id, newid, mq->highid,
2245             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time),
2246             GST_STIME_ARGS (mq->high_time));
2247
2248         if (mq->sync_by_running_time) {
2249           if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2250             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2251                 (mq->high_time == GST_CLOCK_STIME_NONE
2252                 || next_time > mq->high_time);
2253           } else {
2254             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2255                 next_time > sq->group_high_time;
2256           }
2257         } else
2258           should_wait = newid > mq->highid;
2259       }
2260
2261       /* Re-compute the high_id in case someone else pushed */
2262       compute_high_id (mq);
2263       compute_high_time (mq, sq->groupid);
2264     } else {
2265       compute_high_id (mq);
2266       compute_high_time (mq, sq->groupid);
2267       /* Wake up all non-linked pads */
2268       wake_up_next_non_linked (mq);
2269     }
2270     /* We're done waiting, we can clear the nextid and nexttime */
2271     sq->nextid = 0;
2272     sq->next_time = GST_CLOCK_STIME_NONE;
2273   }
2274   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2275
2276   if (sq->flushing)
2277     goto out_flushing;
2278
2279   GST_LOG_OBJECT (mq, "sq:%d BEFORE PUSHING sq->srcresult: %s", sq->id,
2280       gst_flow_get_name (sq->srcresult));
2281
2282   /* Update time stats */
2283   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2284   next_time = get_running_time (&sq->src_segment, object, TRUE);
2285   if (GST_CLOCK_STIME_IS_VALID (next_time)) {
2286     if (sq->last_time == GST_CLOCK_STIME_NONE || sq->last_time < next_time)
2287       sq->last_time = next_time;
2288     if (mq->high_time == GST_CLOCK_STIME_NONE || mq->high_time <= next_time) {
2289       /* Wake up all non-linked pads now that we advanced the high time */
2290       mq->high_time = next_time;
2291       wake_up_next_non_linked (mq);
2292     }
2293   }
2294   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2295
2296   /* Try to push out the new object */
2297   result = gst_single_queue_push_one (mq, sq, object, &dropping);
2298   object = NULL;
2299
2300   /* Check if we pushed something already and if this is
2301    * now a switch from an active to a non-active stream.
2302    *
2303    * If it is, we reset all the waiting streams, let them
2304    * push another buffer to see if they're now active again.
2305    * This allows faster switching between streams and prevents
2306    * deadlocks if downstream does any waiting too.
2307    */
2308   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2309   if (sq->pushed && sq->srcresult == GST_FLOW_OK
2310       && result == GST_FLOW_NOT_LINKED) {
2311     GList *tmp;
2312
2313     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
2314         sq->id);
2315
2316     compute_high_id (mq);
2317     compute_high_time (mq, sq->groupid);
2318     do_update_buffering = TRUE;
2319
2320     /* maybe no-one is waiting */
2321     if (mq->numwaiting > 0) {
2322       /* Else figure out which singlequeue(s) need waking up */
2323       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2324         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
2325
2326         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
2327           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
2328           sq2->pushed = FALSE;
2329           sq2->srcresult = GST_FLOW_OK;
2330           g_cond_signal (&sq2->turn);
2331         }
2332       }
2333     }
2334   }
2335
2336   if (is_buffer)
2337     sq->pushed = TRUE;
2338
2339   /* now hold on a bit;
2340    * can not simply throw this result to upstream, because
2341    * that might already be onto another segment, so we have to make
2342    * sure we are relaying the correct info wrt proper segment */
2343   if (result == GST_FLOW_EOS && !dropping &&
2344       sq->srcresult != GST_FLOW_NOT_LINKED) {
2345     GST_DEBUG_OBJECT (mq, "starting EOS drop on sq %d", sq->id);
2346     dropping = TRUE;
2347     /* pretend we have not seen EOS yet for upstream's sake */
2348     result = sq->srcresult;
2349   } else if (dropping && gst_data_queue_is_empty (sq->queue)) {
2350     /* queue empty, so stop dropping
2351      * we can commit the result we have now,
2352      * which is either OK after a segment, or EOS */
2353     GST_DEBUG_OBJECT (mq, "committed EOS drop on sq %d", sq->id);
2354     dropping = FALSE;
2355     result = GST_FLOW_EOS;
2356   }
2357   sq->srcresult = result;
2358   sq->last_oldid = newid;
2359
2360   if (do_update_buffering)
2361     update_buffering (mq, sq);
2362
2363   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2364   gst_multi_queue_post_buffering (mq);
2365
2366   GST_LOG_OBJECT (mq, "sq:%d AFTER PUSHING sq->srcresult: %s (is_eos:%d)",
2367       sq->id, gst_flow_get_name (sq->srcresult), GST_PAD_IS_EOS (srcpad));
2368
2369   /* Need to make sure wake up any sleeping pads when we exit */
2370   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2371   if (mq->numwaiting > 0 && (GST_PAD_IS_EOS (srcpad)
2372           || sq->srcresult == GST_FLOW_EOS)) {
2373     compute_high_time (mq, sq->groupid);
2374     compute_high_id (mq);
2375     wake_up_next_non_linked (mq);
2376   }
2377   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2378
2379   if (dropping)
2380     goto next;
2381
2382   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
2383       && result != GST_FLOW_EOS)
2384     goto out_flushing;
2385
2386 done:
2387   gst_clear_object (&mq);
2388   gst_clear_object (&srcpad);
2389
2390   return;
2391
2392 out_flushing:
2393   {
2394     if (object && !is_query)
2395       gst_mini_object_unref (object);
2396
2397     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2398     sq->last_query = FALSE;
2399     g_cond_signal (&sq->query_handled);
2400
2401     /* Post an error message if we got EOS while downstream
2402      * has returned an error flow return. After EOS there
2403      * will be no further buffer which could propagate the
2404      * error upstream */
2405     if ((sq->is_eos || sq->is_segment_done) && sq->srcresult < GST_FLOW_EOS) {
2406       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2407       GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2408     } else {
2409       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2410     }
2411
2412     /* upstream needs to see fatal result ASAP to shut things down,
2413      * but might be stuck in one of our other full queues;
2414      * so empty this one and trigger dynamic queue growth. At
2415      * this point the srcresult is not OK, NOT_LINKED
2416      * or EOS, i.e. a real failure */
2417     gst_single_queue_flush_queue (sq, FALSE);
2418     single_queue_underrun_cb (sq->queue, sq);
2419     gst_data_queue_set_flushing (sq->queue, TRUE);
2420     gst_pad_pause_task (srcpad);
2421     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
2422         "SingleQueue[%d] task paused, reason:%s",
2423         sq->id, gst_flow_get_name (sq->srcresult));
2424     goto done;
2425   }
2426 }
2427
2428 /**
2429  * gst_multi_queue_chain:
2430  *
2431  * This is similar to GstQueue's chain function, except:
2432  * _ we don't have leak behaviours,
2433  * _ we push with a unique id (curid)
2434  */
2435 static GstFlowReturn
2436 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2437 {
2438   GstSingleQueue *sq;
2439   GstMultiQueue *mq;
2440   GstMultiQueueItem *item = NULL;
2441   guint32 curid;
2442   GstClockTime timestamp, duration;
2443
2444   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2445   mq = g_weak_ref_get (&sq->mqueue);
2446
2447   if (!mq)
2448     goto flushing;
2449
2450   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2451   if (sq->is_eos)
2452     goto was_eos;
2453
2454   sq->active = TRUE;
2455
2456   /* Get a unique incrementing id */
2457   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2458
2459   timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2460   duration = GST_BUFFER_DURATION (buffer);
2461
2462   GST_LOG_OBJECT (mq,
2463       "SingleQueue %d : about to enqueue buffer %p with id %d (pts:%"
2464       GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT " dur:%" GST_TIME_FORMAT ")",
2465       sq->id, buffer, curid, GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2466       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), GST_TIME_ARGS (duration));
2467
2468   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
2469
2470   /* Update interleave before pushing data into queue */
2471   if (mq->use_interleave) {
2472     GstClockTime val = timestamp;
2473     GstClockTimeDiff dval;
2474
2475     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2476     if (val == GST_CLOCK_TIME_NONE)
2477       val = sq->sink_segment.position;
2478     if (duration != GST_CLOCK_TIME_NONE)
2479       val += duration;
2480
2481     dval = my_segment_to_running_time (&sq->sink_segment, val);
2482     if (GST_CLOCK_STIME_IS_VALID (dval)) {
2483       sq->cached_sinktime = dval;
2484       GST_DEBUG_OBJECT (mq,
2485           "Queue %d cached sink time now %" G_GINT64_FORMAT " %"
2486           GST_STIME_FORMAT, sq->id, sq->cached_sinktime,
2487           GST_STIME_ARGS (sq->cached_sinktime));
2488       calculate_interleave (mq, sq);
2489     }
2490     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2491   }
2492
2493   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
2494     goto flushing;
2495
2496   /* update time level, we must do this after pushing the data in the queue so
2497    * that we never end up filling the queue first. */
2498   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
2499
2500 done:
2501   gst_clear_object (&mq);
2502   return sq->srcresult;
2503
2504   /* ERRORS */
2505 flushing:
2506   {
2507     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2508         sq->id, gst_flow_get_name (sq->srcresult));
2509     if (item)
2510       gst_multi_queue_item_destroy (item);
2511     goto done;
2512   }
2513 was_eos:
2514   {
2515     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
2516     gst_buffer_unref (buffer);
2517     gst_object_unref (mq);
2518     return GST_FLOW_EOS;
2519   }
2520 }
2521
2522 static gboolean
2523 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
2524     GstPadMode mode, gboolean active)
2525 {
2526   gboolean res;
2527   GstSingleQueue *sq;
2528   GstMultiQueue *mq;
2529
2530   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2531   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
2532
2533   /* mq is NULL if the pad is activated/deactivated before being
2534    * added to the multiqueue */
2535   if (mq)
2536     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2537
2538   switch (mode) {
2539     case GST_PAD_MODE_PUSH:
2540       if (active) {
2541         /* All pads start off linked until they push one buffer */
2542         sq->srcresult = GST_FLOW_OK;
2543         sq->pushed = FALSE;
2544         gst_data_queue_set_flushing (sq->queue, FALSE);
2545       } else {
2546         sq->srcresult = GST_FLOW_FLUSHING;
2547         sq->last_query = FALSE;
2548         g_cond_signal (&sq->query_handled);
2549         gst_data_queue_set_flushing (sq->queue, TRUE);
2550
2551         /* Wait until streaming thread has finished */
2552         if (mq)
2553           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2554         GST_PAD_STREAM_LOCK (pad);
2555         if (mq)
2556           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2557         gst_data_queue_flush (sq->queue);
2558         if (mq)
2559           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2560         GST_PAD_STREAM_UNLOCK (pad);
2561         if (mq)
2562           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2563       }
2564       res = TRUE;
2565       break;
2566     default:
2567       res = FALSE;
2568       break;
2569   }
2570
2571   if (mq) {
2572     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2573     gst_object_unref (mq);
2574   }
2575
2576   return res;
2577 }
2578
2579 static GstFlowReturn
2580 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2581 {
2582   GstSingleQueue *sq;
2583   GstMultiQueue *mq;
2584   guint32 curid;
2585   GstMultiQueueItem *item;
2586   gboolean res = TRUE;
2587   GstFlowReturn flowret = GST_FLOW_OK;
2588   GstEventType type;
2589   GstEvent *sref = NULL;
2590   GstPad *srcpad;
2591
2592
2593   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2594   mq = (GstMultiQueue *) parent;
2595   srcpad = g_weak_ref_get (&sq->srcpad);
2596
2597   if (!srcpad) {
2598     GST_INFO_OBJECT (pad, "Pushing while corresponding sourcepad has been"
2599         " removed already");
2600
2601     return GST_FLOW_FLUSHING;
2602   }
2603
2604   type = GST_EVENT_TYPE (event);
2605
2606   switch (type) {
2607     case GST_EVENT_STREAM_START:
2608     {
2609       if (mq->sync_by_running_time) {
2610         GstStreamFlags stream_flags;
2611         gst_event_parse_stream_flags (event, &stream_flags);
2612         if ((stream_flags & GST_STREAM_FLAG_SPARSE)) {
2613           GST_INFO_OBJECT (mq, "SingleQueue %d is a sparse stream", sq->id);
2614           sq->is_sparse = TRUE;
2615         }
2616       }
2617
2618       sq->thread = g_thread_self ();
2619
2620       /* Remove EOS flag */
2621       sq->is_eos = FALSE;
2622       break;
2623     }
2624     case GST_EVENT_FLUSH_START:
2625       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
2626           sq->id);
2627
2628       res = gst_pad_push_event (srcpad, event);
2629
2630       gst_single_queue_flush (mq, sq, TRUE, FALSE);
2631       gst_single_queue_pause (mq, sq);
2632       goto done;
2633
2634     case GST_EVENT_FLUSH_STOP:
2635       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
2636           sq->id);
2637
2638       res = gst_pad_push_event (srcpad, event);
2639
2640       gst_single_queue_flush (mq, sq, FALSE, FALSE);
2641       gst_single_queue_start (mq, sq);
2642       goto done;
2643
2644     case GST_EVENT_SEGMENT:
2645       sq->is_segment_done = FALSE;
2646       sref = gst_event_ref (event);
2647       break;
2648     case GST_EVENT_GAP:
2649       /* take ref because the queue will take ownership and we need the event
2650        * afterwards to update the segment */
2651       sref = gst_event_ref (event);
2652       if (mq->use_interleave) {
2653         GstClockTime val, dur;
2654         GstClockTime stime;
2655         gst_event_parse_gap (event, &val, &dur);
2656         if (GST_CLOCK_TIME_IS_VALID (val)) {
2657           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2658           if (GST_CLOCK_TIME_IS_VALID (dur))
2659             val += dur;
2660           stime = my_segment_to_running_time (&sq->sink_segment, val);
2661           if (GST_CLOCK_STIME_IS_VALID (stime)) {
2662             sq->cached_sinktime = stime;
2663             calculate_interleave (mq, sq);
2664           }
2665           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2666         }
2667       }
2668       break;
2669
2670     default:
2671       if (!(GST_EVENT_IS_SERIALIZED (event))) {
2672         res = gst_pad_push_event (srcpad, event);
2673         goto done;
2674       }
2675       break;
2676   }
2677
2678   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2679   if (sq->is_eos)
2680     goto was_eos;
2681
2682   /* Get an unique incrementing id. */
2683   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2684
2685   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
2686
2687   GST_DEBUG_OBJECT (mq,
2688       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
2689       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
2690
2691   if (!gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))
2692     goto flushing;
2693
2694   /* mark EOS when we received one, we must do that after putting the
2695    * buffer in the queue because EOS marks the buffer as filled. */
2696   switch (type) {
2697     case GST_EVENT_SEGMENT_DONE:
2698       sq->is_segment_done = TRUE;
2699       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2700       update_buffering (mq, sq);
2701       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2702       single_queue_overrun_cb (sq->queue, sq);
2703       gst_multi_queue_post_buffering (mq);
2704       break;
2705     case GST_EVENT_EOS:
2706       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2707       sq->is_eos = TRUE;
2708
2709       /* Post an error message if we got EOS while downstream
2710        * has returned an error flow return. After EOS there
2711        * will be no further buffer which could propagate the
2712        * error upstream */
2713       if (sq->srcresult < GST_FLOW_EOS) {
2714         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2715         GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2716       } else {
2717         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2718       }
2719
2720       /* EOS affects the buffering state */
2721       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2722       update_buffering (mq, sq);
2723       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2724       single_queue_overrun_cb (sq->queue, sq);
2725       gst_multi_queue_post_buffering (mq);
2726       break;
2727     case GST_EVENT_SEGMENT:
2728       apply_segment (mq, sq, sref, &sq->sink_segment);
2729       gst_event_unref (sref);
2730       /* a new segment allows us to accept more buffers if we got EOS
2731        * from downstream */
2732       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2733       if (sq->srcresult == GST_FLOW_EOS)
2734         sq->srcresult = GST_FLOW_OK;
2735       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2736       break;
2737     case GST_EVENT_GAP:
2738       sq->active = TRUE;
2739       apply_gap (mq, sq, sref, &sq->sink_segment);
2740       gst_event_unref (sref);
2741     default:
2742       break;
2743   }
2744
2745 done:
2746
2747   gst_object_unref (srcpad);
2748   if (res == FALSE)
2749     flowret = GST_FLOW_ERROR;
2750   GST_DEBUG_OBJECT (mq, "SingleQueue %d : returning %s", sq->id,
2751       gst_flow_get_name (flowret));
2752   return flowret;
2753
2754 flushing:
2755   {
2756     gst_object_unref (srcpad);
2757     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2758         sq->id, gst_flow_get_name (sq->srcresult));
2759     if (sref)
2760       gst_event_unref (sref);
2761     gst_multi_queue_item_destroy (item);
2762     return sq->srcresult;
2763   }
2764 was_eos:
2765   {
2766     gst_object_unref (srcpad);
2767     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return GST_FLOW_EOS");
2768     gst_event_unref (event);
2769     return GST_FLOW_EOS;
2770   }
2771 }
2772
2773 static gboolean
2774 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
2775 {
2776   gboolean res;
2777   GstSingleQueue *sq;
2778   GstMultiQueue *mq;
2779
2780   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2781   mq = (GstMultiQueue *) parent;
2782
2783   switch (GST_QUERY_TYPE (query)) {
2784     default:
2785       if (GST_QUERY_IS_SERIALIZED (query)) {
2786         guint32 curid;
2787         GstMultiQueueItem *item;
2788
2789         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2790         if (sq->srcresult != GST_FLOW_OK)
2791           goto out_flushing;
2792
2793         /* serialized events go in the queue. We need to be certain that we
2794          * don't cause deadlocks waiting for the query return value. We check if
2795          * the queue is empty (nothing is blocking downstream and the query can
2796          * be pushed for sure) or we are not buffering. If we are buffering,
2797          * the pipeline waits to unblock downstream until our queue fills up
2798          * completely, which can not happen if we block on the query..
2799          * Therefore we only potentially block when we are not buffering. */
2800         if (!mq->use_buffering || gst_data_queue_is_empty (sq->queue)) {
2801           /* Get an unique incrementing id. */
2802           curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2803
2804           item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
2805
2806           GST_DEBUG_OBJECT (mq,
2807               "SingleQueue %d : Enqueuing query %p of type %s with id %d",
2808               sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
2809           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2810           res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
2811           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2812           if (!res || sq->flushing)
2813             goto out_flushing;
2814           /* it might be that the query has been taken out of the queue
2815            * while we were unlocked. So, we need to check if the last
2816            * handled query is the same one than the one we just
2817            * pushed. If it is, we don't need to wait for the condition
2818            * variable, otherwise we wait for the condition variable to
2819            * be signaled. */
2820           while (!sq->flushing && sq->srcresult == GST_FLOW_OK
2821               && sq->last_handled_query != query)
2822             g_cond_wait (&sq->query_handled, &mq->qlock);
2823           res = sq->last_query;
2824           sq->last_handled_query = NULL;
2825         } else {
2826           GST_DEBUG_OBJECT (mq, "refusing query, we are buffering and the "
2827               "queue is not empty");
2828           res = FALSE;
2829         }
2830         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2831       } else {
2832         /* default handling */
2833         res = gst_pad_query_default (pad, parent, query);
2834       }
2835       break;
2836   }
2837   return res;
2838
2839 out_flushing:
2840   {
2841     GST_DEBUG_OBJECT (mq, "Flushing");
2842     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2843     return FALSE;
2844   }
2845 }
2846
2847 static gboolean
2848 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
2849     GstPadMode mode, gboolean active)
2850 {
2851   GstMultiQueue *mq;
2852   GstSingleQueue *sq;
2853   gboolean result;
2854
2855   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2856   mq = g_weak_ref_get (&sq->mqueue);
2857
2858   if (!mq) {
2859     GST_ERROR_OBJECT (pad, "No multique set anymore, can't activate pad");
2860
2861     return FALSE;
2862   }
2863
2864   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
2865
2866   switch (mode) {
2867     case GST_PAD_MODE_PUSH:
2868       if (active) {
2869         gst_single_queue_flush (mq, sq, FALSE, TRUE);
2870         result = parent ? gst_single_queue_start (mq, sq) : TRUE;
2871       } else {
2872         gst_single_queue_flush (mq, sq, TRUE, TRUE);
2873         result = gst_single_queue_stop (mq, sq);
2874       }
2875       break;
2876     default:
2877       result = FALSE;
2878       break;
2879   }
2880   gst_object_unref (mq);
2881   return result;
2882 }
2883
2884 static gboolean
2885 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2886 {
2887   GstSingleQueue *sq = GST_MULTIQUEUE_PAD (pad)->sq;
2888   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
2889   gboolean ret;
2890   GstPad *sinkpad = g_weak_ref_get (&sq->sinkpad);
2891
2892   if (!mq || !sinkpad) {
2893     gst_clear_object (&sinkpad);
2894     gst_clear_object (&mq);
2895     GST_INFO_OBJECT (pad, "No multique/sinkpad set anymore, flushing");
2896
2897     return FALSE;
2898   }
2899
2900   switch (GST_EVENT_TYPE (event)) {
2901     case GST_EVENT_RECONFIGURE:
2902       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2903       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2904         sq->srcresult = GST_FLOW_OK;
2905         g_cond_signal (&sq->turn);
2906       }
2907       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2908
2909       ret = gst_pad_push_event (sinkpad, event);
2910       break;
2911     default:
2912       ret = gst_pad_push_event (sinkpad, event);
2913       break;
2914   }
2915
2916   gst_object_unref (sinkpad);
2917   gst_object_unref (mq);
2918
2919   return ret;
2920 }
2921
2922 static gboolean
2923 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2924 {
2925   gboolean res;
2926
2927   /* FIXME, Handle position offset depending on queue size */
2928   switch (GST_QUERY_TYPE (query)) {
2929     default:
2930       /* default handling */
2931       res = gst_pad_query_default (pad, parent, query);
2932       break;
2933   }
2934   return res;
2935 }
2936
2937 /*
2938  * Next-non-linked functions
2939  */
2940
2941 /* WITH LOCK TAKEN */
2942 static void
2943 wake_up_next_non_linked (GstMultiQueue * mq)
2944 {
2945   GList *tmp;
2946
2947   /* maybe no-one is waiting */
2948   if (mq->numwaiting < 1)
2949     return;
2950
2951   if (mq->sync_by_running_time && GST_CLOCK_STIME_IS_VALID (mq->high_time)) {
2952     /* Else figure out which singlequeue(s) need waking up */
2953     for (tmp = mq->queues; tmp; tmp = tmp->next) {
2954       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2955       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2956         GstClockTimeDiff high_time;
2957
2958         if (GST_CLOCK_STIME_IS_VALID (sq->group_high_time))
2959           high_time = sq->group_high_time;
2960         else
2961           high_time = mq->high_time;
2962
2963         if (GST_CLOCK_STIME_IS_VALID (sq->next_time) &&
2964             GST_CLOCK_STIME_IS_VALID (high_time)
2965             && sq->next_time <= high_time) {
2966           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
2967           g_cond_signal (&sq->turn);
2968         }
2969       }
2970     }
2971   } else {
2972     /* Else figure out which singlequeue(s) need waking up */
2973     for (tmp = mq->queues; tmp; tmp = tmp->next) {
2974       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2975       if (sq->srcresult == GST_FLOW_NOT_LINKED &&
2976           sq->nextid != 0 && sq->nextid <= mq->highid) {
2977         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
2978         g_cond_signal (&sq->turn);
2979       }
2980     }
2981   }
2982 }
2983
2984 /* WITH LOCK TAKEN */
2985 static void
2986 compute_high_id (GstMultiQueue * mq)
2987 {
2988   /* The high-id is either the highest id among the linked pads, or if all
2989    * pads are not-linked, it's the lowest not-linked pad */
2990   GList *tmp;
2991   guint32 lowest = G_MAXUINT32;
2992   guint32 highid = G_MAXUINT32;
2993
2994   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2995     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2996     GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
2997
2998     if (!srcpad) {
2999       GST_INFO_OBJECT (mq,
3000           "srcpad has been removed already... ignoring single queue");
3001
3002       continue;
3003     }
3004
3005     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
3006         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
3007
3008     /* No need to consider queues which are not waiting */
3009     if (sq->nextid == 0) {
3010       GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3011       gst_object_unref (srcpad);
3012       continue;
3013     }
3014
3015     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3016       if (sq->nextid < lowest)
3017         lowest = sq->nextid;
3018     } else if (!GST_PAD_IS_EOS (srcpad) && sq->srcresult != GST_FLOW_EOS) {
3019       /* If we don't have a global highid, or the global highid is lower than
3020        * this single queue's last outputted id, store the queue's one,
3021        * unless the singlequeue output is at EOS */
3022       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
3023         highid = sq->oldid;
3024     }
3025     gst_object_unref (srcpad);
3026   }
3027
3028   if (highid == G_MAXUINT32 || lowest < highid)
3029     mq->highid = lowest;
3030   else
3031     mq->highid = highid;
3032
3033   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
3034       lowest);
3035 }
3036
3037 /* WITH LOCK TAKEN */
3038 static void
3039 compute_high_time (GstMultiQueue * mq, guint groupid)
3040 {
3041   /* The high-time is either the highest last time among the linked
3042    * pads, or if all pads are not-linked, it's the lowest nex time of
3043    * not-linked pad */
3044   GList *tmp;
3045   GstClockTimeDiff highest = GST_CLOCK_STIME_NONE;
3046   GstClockTimeDiff lowest = GST_CLOCK_STIME_NONE;
3047   GstClockTimeDiff group_high = GST_CLOCK_STIME_NONE;
3048   GstClockTimeDiff group_low = GST_CLOCK_STIME_NONE;
3049   GstClockTimeDiff res;
3050   /* Number of streams which belong to groupid */
3051   guint group_count = 0;
3052
3053   if (!mq->sync_by_running_time)
3054     /* return GST_CLOCK_STIME_NONE; */
3055     return;
3056
3057   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3058     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3059     GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
3060
3061     if (!srcpad) {
3062       GST_INFO_OBJECT (mq,
3063           "srcpad has been removed already... ignoring single queue");
3064
3065       continue;
3066     }
3067
3068     GST_LOG_OBJECT (mq,
3069         "inspecting sq:%d (group:%d) , next_time:%" GST_STIME_FORMAT
3070         ", last_time:%" GST_STIME_FORMAT ", srcresult:%s", sq->id, sq->groupid,
3071         GST_STIME_ARGS (sq->next_time), GST_STIME_ARGS (sq->last_time),
3072         gst_flow_get_name (sq->srcresult));
3073
3074     if (sq->groupid == groupid)
3075       group_count++;
3076
3077     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3078       /* No need to consider queues which are not waiting */
3079       if (!GST_CLOCK_STIME_IS_VALID (sq->next_time)) {
3080         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3081         gst_object_unref (srcpad);
3082         continue;
3083       }
3084
3085       if (lowest == GST_CLOCK_STIME_NONE || sq->next_time < lowest)
3086         lowest = sq->next_time;
3087       if (sq->groupid == groupid && (group_low == GST_CLOCK_STIME_NONE
3088               || sq->next_time < group_low))
3089         group_low = sq->next_time;
3090     } else if (!GST_PAD_IS_EOS (srcpad) && sq->srcresult != GST_FLOW_EOS) {
3091       /* If we don't have a global high time, or the global high time
3092        * is lower than this single queue's last outputted time, store
3093        * the queue's one, unless the singlequeue output is at EOS. */
3094       if (highest == GST_CLOCK_STIME_NONE
3095           || (sq->last_time != GST_CLOCK_STIME_NONE && sq->last_time > highest))
3096         highest = sq->last_time;
3097       if (sq->groupid == groupid && (group_high == GST_CLOCK_STIME_NONE
3098               || (sq->last_time != GST_CLOCK_STIME_NONE
3099                   && sq->last_time > group_high)))
3100         group_high = sq->last_time;
3101     }
3102     GST_LOG_OBJECT (mq,
3103         "highest now %" GST_STIME_FORMAT " lowest %" GST_STIME_FORMAT,
3104         GST_STIME_ARGS (highest), GST_STIME_ARGS (lowest));
3105     if (sq->groupid == groupid)
3106       GST_LOG_OBJECT (mq,
3107           "grouphigh %" GST_STIME_FORMAT " grouplow %" GST_STIME_FORMAT,
3108           GST_STIME_ARGS (group_high), GST_STIME_ARGS (group_low));
3109
3110     gst_object_unref (srcpad);
3111   }
3112
3113   if (highest == GST_CLOCK_STIME_NONE)
3114     mq->high_time = lowest;
3115   else
3116     mq->high_time = highest;
3117
3118   /* If there's only one stream of a given type, use the global high */
3119   if (group_count < 2)
3120     res = GST_CLOCK_STIME_NONE;
3121   else if (group_high == GST_CLOCK_STIME_NONE)
3122     res = group_low;
3123   else
3124     res = group_high;
3125
3126   GST_LOG_OBJECT (mq, "group count %d for groupid %u", group_count, groupid);
3127   GST_LOG_OBJECT (mq,
3128       "MQ High time is now : %" GST_STIME_FORMAT ", group %d high time %"
3129       GST_STIME_FORMAT ", lowest non-linked %" GST_STIME_FORMAT,
3130       GST_STIME_ARGS (mq->high_time), groupid, GST_STIME_ARGS (mq->high_time),
3131       GST_STIME_ARGS (lowest));
3132
3133   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3134     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3135     if (groupid == sq->groupid)
3136       sq->group_high_time = res;
3137   }
3138 }
3139
3140 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
3141      ((q)->max_size.format) <= (value))
3142
3143 /*
3144  * GstSingleQueue functions
3145  */
3146 static void
3147 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3148 {
3149   GList *tmp;
3150   GstDataQueueSize size;
3151   gboolean filled = TRUE;
3152   gboolean empty_found = FALSE;
3153   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3154
3155   if (!mq) {
3156     GST_ERROR ("No multique set anymore, not doing anything");
3157
3158     return;
3159   }
3160
3161   gst_data_queue_get_level (sq->queue, &size);
3162
3163   GST_LOG_OBJECT (mq,
3164       "Single Queue %d: EOS %d, visible %u/%u, bytes %u/%u, time %"
3165       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, sq->is_eos, size.visible,
3166       sq->max_size.visible, size.bytes, sq->max_size.bytes, sq->cur_time,
3167       sq->max_size.time);
3168
3169   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3170
3171   /* check if we reached the hard time/bytes limits;
3172      time limit is only taken into account for non-sparse streams */
3173   if (sq->is_eos || IS_FILLED (sq, bytes, size.bytes) ||
3174       (!sq->is_sparse && IS_FILLED (sq, time, sq->cur_time))) {
3175     goto done;
3176   }
3177
3178   /* Search for empty queues */
3179   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3180     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3181
3182     if (oq == sq)
3183       continue;
3184
3185     if (oq->srcresult == GST_FLOW_NOT_LINKED) {
3186       GST_LOG_OBJECT (mq, "Queue %d is not-linked", oq->id);
3187       continue;
3188     }
3189
3190     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
3191     if (gst_data_queue_is_empty (oq->queue) && !oq->is_sparse) {
3192       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
3193       empty_found = TRUE;
3194       break;
3195     }
3196   }
3197
3198   /* if hard limits are not reached then we allow one more buffer in the full
3199    * queue, but only if any of the other singelqueues are empty */
3200   if (empty_found) {
3201     if (IS_FILLED (sq, visible, size.visible)) {
3202       sq->max_size.visible = size.visible + 1;
3203       GST_DEBUG_OBJECT (mq,
3204           "Bumping single queue %d max visible to %d",
3205           sq->id, sq->max_size.visible);
3206       filled = FALSE;
3207     }
3208   }
3209
3210 done:
3211   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3212   gst_object_unref (mq);
3213
3214   /* Overrun is always forwarded, since this is blocking the upstream element */
3215   if (filled) {
3216     GST_DEBUG_OBJECT (mq, "Queue %d is filled, signalling overrun", sq->id);
3217     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
3218   }
3219 }
3220
3221 static void
3222 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3223 {
3224   gboolean empty = TRUE;
3225   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3226   GList *tmp;
3227
3228   if (!mq) {
3229     GST_ERROR ("No multique set anymore, not doing anything");
3230
3231     return;
3232   }
3233
3234   if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3235     GST_LOG_OBJECT (mq, "Single Queue %d is empty but not-linked", sq->id);
3236     gst_object_unref (mq);
3237     return;
3238   } else {
3239     GST_LOG_OBJECT (mq,
3240         "Single Queue %d is empty, Checking other single queues", sq->id);
3241   }
3242
3243   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3244   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3245     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3246
3247     if (gst_data_queue_is_full (oq->queue)) {
3248       GstDataQueueSize size;
3249
3250       gst_data_queue_get_level (oq->queue, &size);
3251       if (IS_FILLED (oq, visible, size.visible)) {
3252         oq->max_size.visible = size.visible + 1;
3253         GST_DEBUG_OBJECT (mq,
3254             "queue %d is filled, bumping its max visible to %d", oq->id,
3255             oq->max_size.visible);
3256         gst_data_queue_limits_changed (oq->queue);
3257       }
3258     }
3259     if (!gst_data_queue_is_empty (oq->queue) || oq->is_sparse)
3260       empty = FALSE;
3261   }
3262   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3263   gst_object_unref (mq);
3264
3265   if (empty) {
3266     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
3267     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
3268   }
3269 }
3270
3271 static gboolean
3272 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
3273     guint64 time, GstSingleQueue * sq)
3274 {
3275   gboolean res;
3276   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3277
3278   if (!mq) {
3279     GST_ERROR ("No multique set anymore, let's say we are full");
3280
3281     return TRUE;
3282   }
3283
3284   GST_DEBUG_OBJECT (mq,
3285       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
3286       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
3287       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
3288
3289   /* we are always filled on EOS */
3290   if (sq->is_eos || sq->is_segment_done) {
3291     res = TRUE;
3292     goto done;
3293   }
3294
3295   /* we never go past the max visible items unless we are in buffering mode */
3296   if (!mq->use_buffering && IS_FILLED (sq, visible, visible)) {
3297     res = TRUE;
3298     goto done;
3299   }
3300
3301   /* check time or bytes */
3302   res = IS_FILLED (sq, bytes, bytes);
3303   /* We only care about limits in time if we're not a sparse stream or
3304    * we're not syncing by running time */
3305   if (!sq->is_sparse || !mq->sync_by_running_time) {
3306     /* If unlinked, take into account the extra unlinked cache time */
3307     if (mq->sync_by_running_time && sq->srcresult == GST_FLOW_NOT_LINKED) {
3308       if (sq->cur_time > mq->unlinked_cache_time)
3309         res |= IS_FILLED (sq, time, sq->cur_time - mq->unlinked_cache_time);
3310       else
3311         res = FALSE;
3312     } else
3313       res |= IS_FILLED (sq, time, sq->cur_time);
3314   }
3315 done:
3316   gst_object_unref (mq);
3317
3318   return res;
3319 }
3320
3321 static void
3322 gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full)
3323 {
3324   GstDataQueueItem *sitem;
3325   GstMultiQueueItem *mitem;
3326   gboolean was_flushing = FALSE;
3327   GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
3328   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3329
3330   while (!gst_data_queue_is_empty (sq->queue)) {
3331     GstMiniObject *data;
3332
3333     /* FIXME: If this fails here although the queue is not empty,
3334      * we're flushing... but we want to rescue all sticky
3335      * events nonetheless.
3336      */
3337     if (!gst_data_queue_pop (sq->queue, &sitem)) {
3338       was_flushing = TRUE;
3339       gst_data_queue_set_flushing (sq->queue, FALSE);
3340       continue;
3341     }
3342
3343     mitem = (GstMultiQueueItem *) sitem;
3344
3345     data = sitem->object;
3346
3347     if (!full && !mitem->is_query && GST_IS_EVENT (data)
3348         && srcpad && GST_EVENT_IS_STICKY (data)
3349         && GST_EVENT_TYPE (data) != GST_EVENT_SEGMENT
3350         && GST_EVENT_TYPE (data) != GST_EVENT_EOS) {
3351       gst_pad_store_sticky_event (srcpad, GST_EVENT_CAST (data));
3352     }
3353
3354     sitem->destroy (sitem);
3355   }
3356   gst_clear_object (&srcpad);
3357
3358   gst_data_queue_flush (sq->queue);
3359   if (was_flushing)
3360     gst_data_queue_set_flushing (sq->queue, TRUE);
3361
3362   if (mq) {
3363     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3364     update_buffering (mq, sq);
3365     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3366     gst_multi_queue_post_buffering (mq);
3367     gst_object_unref (mq);
3368   }
3369 }
3370
3371 static void
3372 gst_single_queue_unref (GstSingleQueue * sq)
3373 {
3374   if (g_atomic_int_dec_and_test (&sq->refcount)) {
3375     /* DRAIN QUEUE */
3376     gst_data_queue_flush (sq->queue);
3377     g_object_unref (sq->queue);
3378     g_cond_clear (&sq->turn);
3379     g_cond_clear (&sq->query_handled);
3380     g_weak_ref_clear (&sq->sinkpad);
3381     g_weak_ref_clear (&sq->srcpad);
3382     g_weak_ref_clear (&sq->mqueue);
3383     g_free (sq);
3384   }
3385 }
3386
3387
3388 static GstSingleQueue *
3389 gst_single_queue_ref (GstSingleQueue * squeue)
3390 {
3391   g_atomic_int_inc (&squeue->refcount);
3392
3393   return squeue;
3394 }
3395
3396 static GstSingleQueue *
3397 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
3398 {
3399   GstPad *srcpad, *sinkpad;
3400   GstSingleQueue *sq;
3401   GstPadTemplate *templ;
3402   gchar *name;
3403   GList *tmp;
3404   guint temp_id = (id == -1) ? 0 : id;
3405
3406   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
3407
3408   /* Find an unused queue ID, if possible the passed one */
3409   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
3410     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
3411     /* This works because the IDs are sorted in ascending order */
3412     if (sq2->id == temp_id) {
3413       /* If this ID was requested by the caller return NULL,
3414        * otherwise just get us the next one */
3415       if (id == -1) {
3416         temp_id = sq2->id + 1;
3417       } else {
3418         GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3419         return NULL;
3420       }
3421     } else if (sq2->id > temp_id) {
3422       break;
3423     }
3424   }
3425
3426   sq = g_new0 (GstSingleQueue, 1);
3427   g_atomic_int_set (&sq->refcount, 1);
3428
3429   mqueue->nbqueues++;
3430   sq->id = temp_id;
3431   sq->groupid = DEFAULT_PAD_GROUP_ID;
3432   sq->group_high_time = GST_CLOCK_STIME_NONE;
3433
3434   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
3435   mqueue->queues_cookie++;
3436
3437   /* copy over max_size and extra_size so we don't need to take the lock
3438    * any longer when checking if the queue is full. */
3439   sq->max_size.visible = mqueue->max_size.visible;
3440   sq->max_size.bytes = mqueue->max_size.bytes;
3441   sq->max_size.time = mqueue->max_size.time;
3442
3443   sq->extra_size.visible = mqueue->extra_size.visible;
3444   sq->extra_size.bytes = mqueue->extra_size.bytes;
3445   sq->extra_size.time = mqueue->extra_size.time;
3446
3447   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
3448
3449   g_weak_ref_init (&sq->mqueue, mqueue);
3450   sq->srcresult = GST_FLOW_FLUSHING;
3451   sq->pushed = FALSE;
3452   sq->queue = gst_data_queue_new ((GstDataQueueCheckFullFunction)
3453       single_queue_check_full,
3454       (GstDataQueueFullCallback) single_queue_overrun_cb,
3455       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
3456   sq->is_eos = FALSE;
3457   sq->is_sparse = FALSE;
3458   sq->flushing = FALSE;
3459   sq->active = FALSE;
3460   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
3461   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
3462
3463   sq->nextid = 0;
3464   sq->oldid = 0;
3465   sq->next_time = GST_CLOCK_STIME_NONE;
3466   sq->last_time = GST_CLOCK_STIME_NONE;
3467   g_cond_init (&sq->turn);
3468   g_cond_init (&sq->query_handled);
3469
3470   sq->sinktime = GST_CLOCK_STIME_NONE;
3471   sq->srctime = GST_CLOCK_STIME_NONE;
3472   sq->sink_tainted = TRUE;
3473   sq->src_tainted = TRUE;
3474
3475   name = g_strdup_printf ("sink_%u", sq->id);
3476   templ = gst_static_pad_template_get (&sinktemplate);
3477   sinkpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
3478       "direction", templ->direction, "template", templ, NULL);
3479   g_weak_ref_init (&sq->sinkpad, sinkpad);
3480   gst_object_unref (templ);
3481   g_free (name);
3482
3483   GST_MULTIQUEUE_PAD (sinkpad)->sq = sq;
3484
3485   gst_pad_set_chain_function (sinkpad,
3486       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
3487   gst_pad_set_activatemode_function (sinkpad,
3488       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
3489   gst_pad_set_event_full_function (sinkpad,
3490       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
3491   gst_pad_set_query_function (sinkpad,
3492       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
3493   gst_pad_set_iterate_internal_links_function (sinkpad,
3494       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3495   GST_OBJECT_FLAG_SET (sinkpad, GST_PAD_FLAG_PROXY_CAPS);
3496
3497   name = g_strdup_printf ("src_%u", sq->id);
3498   templ = gst_static_pad_template_get (&srctemplate);
3499   srcpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
3500       "direction", templ->direction, "template", templ, NULL);
3501   g_weak_ref_init (&sq->srcpad, srcpad);
3502   gst_object_unref (templ);
3503   g_free (name);
3504
3505   GST_MULTIQUEUE_PAD (srcpad)->sq = gst_single_queue_ref (sq);
3506
3507   gst_pad_set_activatemode_function (srcpad,
3508       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
3509   gst_pad_set_event_function (srcpad,
3510       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
3511   gst_pad_set_query_function (srcpad,
3512       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
3513   gst_pad_set_iterate_internal_links_function (srcpad,
3514       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3515   GST_OBJECT_FLAG_SET (srcpad, GST_PAD_FLAG_PROXY_CAPS);
3516
3517   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3518
3519   /* only activate the pads when we are not in the NULL state
3520    * and add the pad under the state_lock to prevent state changes
3521    * between activating and adding */
3522   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
3523   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3524     gst_pad_set_active (srcpad, TRUE);
3525     gst_pad_set_active (sinkpad, TRUE);
3526   }
3527   gst_element_add_pad (GST_ELEMENT (mqueue), srcpad);
3528   gst_element_add_pad (GST_ELEMENT (mqueue), sinkpad);
3529   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3530     gst_single_queue_start (mqueue, sq);
3531   }
3532   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
3533
3534   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
3535       sq->id);
3536
3537   return sq;
3538 }