multiqueue: fix potential crash on shutdown
[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;
2122   gboolean is_query = FALSE;
2123   gboolean do_update_buffering = FALSE;
2124   gboolean dropping = FALSE;
2125   GstPad *srcpad = NULL;
2126
2127   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2128   mq = g_weak_ref_get (&sq->mqueue);
2129   srcpad = g_weak_ref_get (&sq->srcpad);
2130
2131   if (!mq || !srcpad)
2132     goto done;
2133
2134 next:
2135   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
2136
2137   if (sq->flushing)
2138     goto out_flushing;
2139
2140   /* Get something from the queue, blocking until that happens, or we get
2141    * flushed */
2142   if (!(gst_data_queue_pop (sq->queue, &sitem)))
2143     goto out_flushing;
2144
2145   item = (GstMultiQueueItem *) sitem;
2146   newid = item->posid;
2147
2148   is_query = item->is_query;
2149
2150   /* steal the object and destroy the item */
2151   object = gst_multi_queue_item_steal_object (item);
2152   gst_multi_queue_item_destroy (item);
2153
2154   is_buffer = GST_IS_BUFFER (object);
2155
2156   /* Get running time of the item. Events will have GST_CLOCK_STIME_NONE */
2157   next_time = get_running_time (&sq->src_segment, object, FALSE);
2158
2159   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
2160       sq->id, newid, sq->last_oldid);
2161
2162   /* If we're not-linked, we do some extra work because we might need to
2163    * wait before pushing. If we're linked but there's a gap in the IDs,
2164    * or it's the first loop, or we just passed the previous highid,
2165    * we might need to wake some sleeping pad up, so there's extra work
2166    * there too */
2167   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2168   if (sq->srcresult == GST_FLOW_NOT_LINKED
2169       || (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1))
2170       || sq->last_oldid > mq->highid) {
2171     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
2172         gst_flow_get_name (sq->srcresult));
2173
2174     /* Check again if we're flushing after the lock is taken,
2175      * the flush flag might have been changed in the meantime */
2176     if (sq->flushing) {
2177       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2178       goto out_flushing;
2179     }
2180
2181     /* Update the nextid so other threads know when to wake us up */
2182     sq->nextid = newid;
2183     /* Take into account the extra cache time since we're unlinked */
2184     if (GST_CLOCK_STIME_IS_VALID (next_time))
2185       next_time += mq->unlinked_cache_time;
2186     sq->next_time = next_time;
2187
2188     /* Update the oldid (the last ID we output) for highid tracking */
2189     if (sq->last_oldid != G_MAXUINT32)
2190       sq->oldid = sq->last_oldid;
2191
2192     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2193       gboolean should_wait;
2194       /* Go to sleep until it's time to push this buffer */
2195
2196       /* Recompute the highid */
2197       compute_high_id (mq);
2198       /* Recompute the high time */
2199       compute_high_time (mq, sq->groupid);
2200
2201       GST_DEBUG_OBJECT (mq,
2202           "groupid %d high_time %" GST_STIME_FORMAT " next_time %"
2203           GST_STIME_FORMAT, sq->groupid, GST_STIME_ARGS (sq->group_high_time),
2204           GST_STIME_ARGS (next_time));
2205
2206       if (mq->sync_by_running_time) {
2207         if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2208           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2209               (mq->high_time == GST_CLOCK_STIME_NONE
2210               || next_time > mq->high_time);
2211         } else {
2212           should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2213               next_time > sq->group_high_time;
2214         }
2215       } else
2216         should_wait = newid > mq->highid;
2217
2218       while (should_wait && sq->srcresult == GST_FLOW_NOT_LINKED) {
2219
2220         GST_DEBUG_OBJECT (mq,
2221             "queue %d sleeping for not-linked wakeup with "
2222             "newid %u, highid %u, next_time %" GST_STIME_FORMAT
2223             ", high_time %" GST_STIME_FORMAT, sq->id, newid, mq->highid,
2224             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time));
2225
2226         /* Wake up all non-linked pads before we sleep */
2227         wake_up_next_non_linked (mq);
2228
2229         mq->numwaiting++;
2230         g_cond_wait (&sq->turn, &mq->qlock);
2231         mq->numwaiting--;
2232
2233         if (sq->flushing) {
2234           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2235           goto out_flushing;
2236         }
2237
2238         /* Recompute the high time and ID */
2239         compute_high_time (mq, sq->groupid);
2240         compute_high_id (mq);
2241
2242         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
2243             "wakeup with newid %u, highid %u, next_time %" GST_STIME_FORMAT
2244             ", high_time %" GST_STIME_FORMAT " mq high_time %" GST_STIME_FORMAT,
2245             sq->id, newid, mq->highid,
2246             GST_STIME_ARGS (next_time), GST_STIME_ARGS (sq->group_high_time),
2247             GST_STIME_ARGS (mq->high_time));
2248
2249         if (mq->sync_by_running_time) {
2250           if (sq->group_high_time == GST_CLOCK_STIME_NONE) {
2251             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2252                 (mq->high_time == GST_CLOCK_STIME_NONE
2253                 || next_time > mq->high_time);
2254           } else {
2255             should_wait = GST_CLOCK_STIME_IS_VALID (next_time) &&
2256                 next_time > sq->group_high_time;
2257           }
2258         } else
2259           should_wait = newid > mq->highid;
2260       }
2261
2262       /* Re-compute the high_id in case someone else pushed */
2263       compute_high_id (mq);
2264       compute_high_time (mq, sq->groupid);
2265     } else {
2266       compute_high_id (mq);
2267       compute_high_time (mq, sq->groupid);
2268       /* Wake up all non-linked pads */
2269       wake_up_next_non_linked (mq);
2270     }
2271     /* We're done waiting, we can clear the nextid and nexttime */
2272     sq->nextid = 0;
2273     sq->next_time = GST_CLOCK_STIME_NONE;
2274   }
2275   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2276
2277   if (sq->flushing)
2278     goto out_flushing;
2279
2280   GST_LOG_OBJECT (mq, "sq:%d BEFORE PUSHING sq->srcresult: %s", sq->id,
2281       gst_flow_get_name (sq->srcresult));
2282
2283   /* Update time stats */
2284   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2285   next_time = get_running_time (&sq->src_segment, object, TRUE);
2286   if (GST_CLOCK_STIME_IS_VALID (next_time)) {
2287     if (sq->last_time == GST_CLOCK_STIME_NONE || sq->last_time < next_time)
2288       sq->last_time = next_time;
2289     if (mq->high_time == GST_CLOCK_STIME_NONE || mq->high_time <= next_time) {
2290       /* Wake up all non-linked pads now that we advanced the high time */
2291       mq->high_time = next_time;
2292       wake_up_next_non_linked (mq);
2293     }
2294   }
2295   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2296
2297   /* Try to push out the new object */
2298   result = gst_single_queue_push_one (mq, sq, object, &dropping);
2299   object = NULL;
2300
2301   /* Check if we pushed something already and if this is
2302    * now a switch from an active to a non-active stream.
2303    *
2304    * If it is, we reset all the waiting streams, let them
2305    * push another buffer to see if they're now active again.
2306    * This allows faster switching between streams and prevents
2307    * deadlocks if downstream does any waiting too.
2308    */
2309   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2310   if (sq->pushed && sq->srcresult == GST_FLOW_OK
2311       && result == GST_FLOW_NOT_LINKED) {
2312     GList *tmp;
2313
2314     GST_LOG_OBJECT (mq, "SingleQueue %d : Changed from active to non-active",
2315         sq->id);
2316
2317     compute_high_id (mq);
2318     compute_high_time (mq, sq->groupid);
2319     do_update_buffering = TRUE;
2320
2321     /* maybe no-one is waiting */
2322     if (mq->numwaiting > 0) {
2323       /* Else figure out which singlequeue(s) need waking up */
2324       for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2325         GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
2326
2327         if (sq2->srcresult == GST_FLOW_NOT_LINKED) {
2328           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq2->id);
2329           sq2->pushed = FALSE;
2330           sq2->srcresult = GST_FLOW_OK;
2331           g_cond_signal (&sq2->turn);
2332         }
2333       }
2334     }
2335   }
2336
2337   if (is_buffer)
2338     sq->pushed = TRUE;
2339
2340   /* now hold on a bit;
2341    * can not simply throw this result to upstream, because
2342    * that might already be onto another segment, so we have to make
2343    * sure we are relaying the correct info wrt proper segment */
2344   if (result == GST_FLOW_EOS && !dropping &&
2345       sq->srcresult != GST_FLOW_NOT_LINKED) {
2346     GST_DEBUG_OBJECT (mq, "starting EOS drop on sq %d", sq->id);
2347     dropping = TRUE;
2348     /* pretend we have not seen EOS yet for upstream's sake */
2349     result = sq->srcresult;
2350   } else if (dropping && gst_data_queue_is_empty (sq->queue)) {
2351     /* queue empty, so stop dropping
2352      * we can commit the result we have now,
2353      * which is either OK after a segment, or EOS */
2354     GST_DEBUG_OBJECT (mq, "committed EOS drop on sq %d", sq->id);
2355     dropping = FALSE;
2356     result = GST_FLOW_EOS;
2357   }
2358   sq->srcresult = result;
2359   sq->last_oldid = newid;
2360
2361   if (do_update_buffering)
2362     update_buffering (mq, sq);
2363
2364   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2365   gst_multi_queue_post_buffering (mq);
2366
2367   GST_LOG_OBJECT (mq, "sq:%d AFTER PUSHING sq->srcresult: %s (is_eos:%d)",
2368       sq->id, gst_flow_get_name (sq->srcresult), GST_PAD_IS_EOS (srcpad));
2369
2370   /* Need to make sure wake up any sleeping pads when we exit */
2371   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2372   if (mq->numwaiting > 0 && (GST_PAD_IS_EOS (srcpad)
2373           || sq->srcresult == GST_FLOW_EOS)) {
2374     compute_high_time (mq, sq->groupid);
2375     compute_high_id (mq);
2376     wake_up_next_non_linked (mq);
2377   }
2378   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2379
2380   if (dropping)
2381     goto next;
2382
2383   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
2384       && result != GST_FLOW_EOS)
2385     goto out_flushing;
2386
2387 done:
2388   gst_clear_object (&mq);
2389   gst_clear_object (&srcpad);
2390
2391   return;
2392
2393 out_flushing:
2394   {
2395     if (object && !is_query)
2396       gst_mini_object_unref (object);
2397
2398     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2399     sq->last_query = FALSE;
2400     g_cond_signal (&sq->query_handled);
2401
2402     /* Post an error message if we got EOS while downstream
2403      * has returned an error flow return. After EOS there
2404      * will be no further buffer which could propagate the
2405      * error upstream */
2406     if ((sq->is_eos || sq->is_segment_done) && sq->srcresult < GST_FLOW_EOS) {
2407       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2408       GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2409     } else {
2410       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2411     }
2412
2413     /* upstream needs to see fatal result ASAP to shut things down,
2414      * but might be stuck in one of our other full queues;
2415      * so empty this one and trigger dynamic queue growth. At
2416      * this point the srcresult is not OK, NOT_LINKED
2417      * or EOS, i.e. a real failure */
2418     gst_single_queue_flush_queue (sq, FALSE);
2419     single_queue_underrun_cb (sq->queue, sq);
2420     gst_data_queue_set_flushing (sq->queue, TRUE);
2421     gst_pad_pause_task (srcpad);
2422     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
2423         "SingleQueue[%d] task paused, reason:%s",
2424         sq->id, gst_flow_get_name (sq->srcresult));
2425     goto done;
2426   }
2427 }
2428
2429 /**
2430  * gst_multi_queue_chain:
2431  *
2432  * This is similar to GstQueue's chain function, except:
2433  * _ we don't have leak behaviours,
2434  * _ we push with a unique id (curid)
2435  */
2436 static GstFlowReturn
2437 gst_multi_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2438 {
2439   GstSingleQueue *sq;
2440   GstMultiQueue *mq;
2441   GstMultiQueueItem *item = NULL;
2442   guint32 curid;
2443   GstClockTime timestamp, duration;
2444
2445   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2446   mq = g_weak_ref_get (&sq->mqueue);
2447
2448   if (!mq)
2449     goto done;
2450
2451   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2452   if (sq->is_eos)
2453     goto was_eos;
2454
2455   sq->active = TRUE;
2456
2457   /* Get a unique incrementing id */
2458   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2459
2460   timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2461   duration = GST_BUFFER_DURATION (buffer);
2462
2463   GST_LOG_OBJECT (mq,
2464       "SingleQueue %d : about to enqueue buffer %p with id %d (pts:%"
2465       GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT " dur:%" GST_TIME_FORMAT ")",
2466       sq->id, buffer, curid, GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2467       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), GST_TIME_ARGS (duration));
2468
2469   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
2470
2471   /* Update interleave before pushing data into queue */
2472   if (mq->use_interleave) {
2473     GstClockTime val = timestamp;
2474     GstClockTimeDiff dval;
2475
2476     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2477     if (val == GST_CLOCK_TIME_NONE)
2478       val = sq->sink_segment.position;
2479     if (duration != GST_CLOCK_TIME_NONE)
2480       val += duration;
2481
2482     dval = my_segment_to_running_time (&sq->sink_segment, val);
2483     if (GST_CLOCK_STIME_IS_VALID (dval)) {
2484       sq->cached_sinktime = dval;
2485       GST_DEBUG_OBJECT (mq,
2486           "Queue %d cached sink time now %" G_GINT64_FORMAT " %"
2487           GST_STIME_FORMAT, sq->id, sq->cached_sinktime,
2488           GST_STIME_ARGS (sq->cached_sinktime));
2489       calculate_interleave (mq, sq);
2490     }
2491     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2492   }
2493
2494   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
2495     goto flushing;
2496
2497   /* update time level, we must do this after pushing the data in the queue so
2498    * that we never end up filling the queue first. */
2499   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
2500
2501 done:
2502   gst_clear_object (&mq);
2503   return sq->srcresult;
2504
2505   /* ERRORS */
2506 flushing:
2507   {
2508     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2509         sq->id, gst_flow_get_name (sq->srcresult));
2510     if (item)
2511       gst_multi_queue_item_destroy (item);
2512     goto done;
2513   }
2514 was_eos:
2515   {
2516     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return EOS");
2517     gst_buffer_unref (buffer);
2518     gst_object_unref (mq);
2519     return GST_FLOW_EOS;
2520   }
2521 }
2522
2523 static gboolean
2524 gst_multi_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
2525     GstPadMode mode, gboolean active)
2526 {
2527   gboolean res;
2528   GstSingleQueue *sq;
2529   GstMultiQueue *mq;
2530
2531   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2532   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
2533
2534   /* mq is NULL if the pad is activated/deactivated before being
2535    * added to the multiqueue */
2536   if (mq)
2537     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2538
2539   switch (mode) {
2540     case GST_PAD_MODE_PUSH:
2541       if (active) {
2542         /* All pads start off linked until they push one buffer */
2543         sq->srcresult = GST_FLOW_OK;
2544         sq->pushed = FALSE;
2545         gst_data_queue_set_flushing (sq->queue, FALSE);
2546       } else {
2547         sq->srcresult = GST_FLOW_FLUSHING;
2548         sq->last_query = FALSE;
2549         g_cond_signal (&sq->query_handled);
2550         gst_data_queue_set_flushing (sq->queue, TRUE);
2551
2552         /* Wait until streaming thread has finished */
2553         if (mq)
2554           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2555         GST_PAD_STREAM_LOCK (pad);
2556         if (mq)
2557           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2558         gst_data_queue_flush (sq->queue);
2559         if (mq)
2560           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2561         GST_PAD_STREAM_UNLOCK (pad);
2562         if (mq)
2563           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2564       }
2565       res = TRUE;
2566       break;
2567     default:
2568       res = FALSE;
2569       break;
2570   }
2571
2572   if (mq) {
2573     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2574     gst_object_unref (mq);
2575   }
2576
2577   return res;
2578 }
2579
2580 static GstFlowReturn
2581 gst_multi_queue_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2582 {
2583   GstSingleQueue *sq;
2584   GstMultiQueue *mq;
2585   guint32 curid;
2586   GstMultiQueueItem *item;
2587   gboolean res = TRUE;
2588   GstFlowReturn flowret = GST_FLOW_OK;
2589   GstEventType type;
2590   GstEvent *sref = NULL;
2591   GstPad *srcpad;
2592
2593
2594   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2595   mq = (GstMultiQueue *) parent;
2596   srcpad = g_weak_ref_get (&sq->srcpad);
2597
2598   if (!srcpad) {
2599     GST_INFO_OBJECT (pad, "Pushing while corresponding sourcepad has been"
2600         " removed already");
2601
2602     return GST_FLOW_FLUSHING;
2603   }
2604
2605   type = GST_EVENT_TYPE (event);
2606
2607   switch (type) {
2608     case GST_EVENT_STREAM_START:
2609     {
2610       if (mq->sync_by_running_time) {
2611         GstStreamFlags stream_flags;
2612         gst_event_parse_stream_flags (event, &stream_flags);
2613         if ((stream_flags & GST_STREAM_FLAG_SPARSE)) {
2614           GST_INFO_OBJECT (mq, "SingleQueue %d is a sparse stream", sq->id);
2615           sq->is_sparse = TRUE;
2616         }
2617       }
2618
2619       sq->thread = g_thread_self ();
2620
2621       /* Remove EOS flag */
2622       sq->is_eos = FALSE;
2623       break;
2624     }
2625     case GST_EVENT_FLUSH_START:
2626       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
2627           sq->id);
2628
2629       res = gst_pad_push_event (srcpad, event);
2630
2631       gst_single_queue_flush (mq, sq, TRUE, FALSE);
2632       gst_single_queue_pause (mq, sq);
2633       goto done;
2634
2635     case GST_EVENT_FLUSH_STOP:
2636       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
2637           sq->id);
2638
2639       res = gst_pad_push_event (srcpad, event);
2640
2641       gst_single_queue_flush (mq, sq, FALSE, FALSE);
2642       gst_single_queue_start (mq, sq);
2643       goto done;
2644
2645     case GST_EVENT_SEGMENT:
2646       sq->is_segment_done = FALSE;
2647       sref = gst_event_ref (event);
2648       break;
2649     case GST_EVENT_GAP:
2650       /* take ref because the queue will take ownership and we need the event
2651        * afterwards to update the segment */
2652       sref = gst_event_ref (event);
2653       if (mq->use_interleave) {
2654         GstClockTime val, dur;
2655         GstClockTime stime;
2656         gst_event_parse_gap (event, &val, &dur);
2657         if (GST_CLOCK_TIME_IS_VALID (val)) {
2658           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2659           if (GST_CLOCK_TIME_IS_VALID (dur))
2660             val += dur;
2661           stime = my_segment_to_running_time (&sq->sink_segment, val);
2662           if (GST_CLOCK_STIME_IS_VALID (stime)) {
2663             sq->cached_sinktime = stime;
2664             calculate_interleave (mq, sq);
2665           }
2666           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2667         }
2668       }
2669       break;
2670
2671     default:
2672       if (!(GST_EVENT_IS_SERIALIZED (event))) {
2673         res = gst_pad_push_event (srcpad, event);
2674         goto done;
2675       }
2676       break;
2677   }
2678
2679   /* if eos, we are always full, so avoid hanging incoming indefinitely */
2680   if (sq->is_eos)
2681     goto was_eos;
2682
2683   /* Get an unique incrementing id. */
2684   curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2685
2686   item = gst_multi_queue_mo_item_new ((GstMiniObject *) event, curid);
2687
2688   GST_DEBUG_OBJECT (mq,
2689       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
2690       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
2691
2692   if (!gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))
2693     goto flushing;
2694
2695   /* mark EOS when we received one, we must do that after putting the
2696    * buffer in the queue because EOS marks the buffer as filled. */
2697   switch (type) {
2698     case GST_EVENT_SEGMENT_DONE:
2699       sq->is_segment_done = TRUE;
2700       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2701       update_buffering (mq, sq);
2702       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2703       single_queue_overrun_cb (sq->queue, sq);
2704       gst_multi_queue_post_buffering (mq);
2705       break;
2706     case GST_EVENT_EOS:
2707       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2708       sq->is_eos = TRUE;
2709
2710       /* Post an error message if we got EOS while downstream
2711        * has returned an error flow return. After EOS there
2712        * will be no further buffer which could propagate the
2713        * error upstream */
2714       if (sq->srcresult < GST_FLOW_EOS) {
2715         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2716         GST_ELEMENT_FLOW_ERROR (mq, sq->srcresult);
2717       } else {
2718         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2719       }
2720
2721       /* EOS affects the buffering state */
2722       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2723       update_buffering (mq, sq);
2724       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2725       single_queue_overrun_cb (sq->queue, sq);
2726       gst_multi_queue_post_buffering (mq);
2727       break;
2728     case GST_EVENT_SEGMENT:
2729       apply_segment (mq, sq, sref, &sq->sink_segment);
2730       gst_event_unref (sref);
2731       /* a new segment allows us to accept more buffers if we got EOS
2732        * from downstream */
2733       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2734       if (sq->srcresult == GST_FLOW_EOS)
2735         sq->srcresult = GST_FLOW_OK;
2736       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2737       break;
2738     case GST_EVENT_GAP:
2739       sq->active = TRUE;
2740       apply_gap (mq, sq, sref, &sq->sink_segment);
2741       gst_event_unref (sref);
2742     default:
2743       break;
2744   }
2745
2746 done:
2747
2748   gst_object_unref (srcpad);
2749   if (res == FALSE)
2750     flowret = GST_FLOW_ERROR;
2751   GST_DEBUG_OBJECT (mq, "SingleQueue %d : returning %s", sq->id,
2752       gst_flow_get_name (flowret));
2753   return flowret;
2754
2755 flushing:
2756   {
2757     gst_object_unref (srcpad);
2758     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
2759         sq->id, gst_flow_get_name (sq->srcresult));
2760     if (sref)
2761       gst_event_unref (sref);
2762     gst_multi_queue_item_destroy (item);
2763     return sq->srcresult;
2764   }
2765 was_eos:
2766   {
2767     gst_object_unref (srcpad);
2768     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return GST_FLOW_EOS");
2769     gst_event_unref (event);
2770     return GST_FLOW_EOS;
2771   }
2772 }
2773
2774 static gboolean
2775 gst_multi_queue_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
2776 {
2777   gboolean res;
2778   GstSingleQueue *sq;
2779   GstMultiQueue *mq;
2780
2781   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2782   mq = (GstMultiQueue *) parent;
2783
2784   switch (GST_QUERY_TYPE (query)) {
2785     default:
2786       if (GST_QUERY_IS_SERIALIZED (query)) {
2787         guint32 curid;
2788         GstMultiQueueItem *item;
2789
2790         GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2791         if (sq->srcresult != GST_FLOW_OK)
2792           goto out_flushing;
2793
2794         /* serialized events go in the queue. We need to be certain that we
2795          * don't cause deadlocks waiting for the query return value. We check if
2796          * the queue is empty (nothing is blocking downstream and the query can
2797          * be pushed for sure) or we are not buffering. If we are buffering,
2798          * the pipeline waits to unblock downstream until our queue fills up
2799          * completely, which can not happen if we block on the query..
2800          * Therefore we only potentially block when we are not buffering. */
2801         if (!mq->use_buffering || gst_data_queue_is_empty (sq->queue)) {
2802           /* Get an unique incrementing id. */
2803           curid = g_atomic_int_add ((gint *) & mq->counter, 1);
2804
2805           item = gst_multi_queue_mo_item_new ((GstMiniObject *) query, curid);
2806
2807           GST_DEBUG_OBJECT (mq,
2808               "SingleQueue %d : Enqueuing query %p of type %s with id %d",
2809               sq->id, query, GST_QUERY_TYPE_NAME (query), curid);
2810           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2811           res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item);
2812           GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2813           if (!res || sq->flushing)
2814             goto out_flushing;
2815           /* it might be that the query has been taken out of the queue
2816            * while we were unlocked. So, we need to check if the last
2817            * handled query is the same one than the one we just
2818            * pushed. If it is, we don't need to wait for the condition
2819            * variable, otherwise we wait for the condition variable to
2820            * be signaled. */
2821           while (!sq->flushing && sq->srcresult == GST_FLOW_OK
2822               && sq->last_handled_query != query)
2823             g_cond_wait (&sq->query_handled, &mq->qlock);
2824           res = sq->last_query;
2825           sq->last_handled_query = NULL;
2826         } else {
2827           GST_DEBUG_OBJECT (mq, "refusing query, we are buffering and the "
2828               "queue is not empty");
2829           res = FALSE;
2830         }
2831         GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2832       } else {
2833         /* default handling */
2834         res = gst_pad_query_default (pad, parent, query);
2835       }
2836       break;
2837   }
2838   return res;
2839
2840 out_flushing:
2841   {
2842     GST_DEBUG_OBJECT (mq, "Flushing");
2843     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2844     return FALSE;
2845   }
2846 }
2847
2848 static gboolean
2849 gst_multi_queue_src_activate_mode (GstPad * pad, GstObject * parent,
2850     GstPadMode mode, gboolean active)
2851 {
2852   GstMultiQueue *mq;
2853   GstSingleQueue *sq;
2854   gboolean result;
2855
2856   sq = GST_MULTIQUEUE_PAD (pad)->sq;
2857   mq = g_weak_ref_get (&sq->mqueue);
2858
2859   if (!mq) {
2860     GST_ERROR_OBJECT (pad, "No multique set anymore, can't activate pad");
2861
2862     return FALSE;
2863   }
2864
2865   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
2866
2867   switch (mode) {
2868     case GST_PAD_MODE_PUSH:
2869       if (active) {
2870         gst_single_queue_flush (mq, sq, FALSE, TRUE);
2871         result = parent ? gst_single_queue_start (mq, sq) : TRUE;
2872       } else {
2873         gst_single_queue_flush (mq, sq, TRUE, TRUE);
2874         result = gst_single_queue_stop (mq, sq);
2875       }
2876       break;
2877     default:
2878       result = FALSE;
2879       break;
2880   }
2881   gst_object_unref (mq);
2882   return result;
2883 }
2884
2885 static gboolean
2886 gst_multi_queue_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2887 {
2888   GstSingleQueue *sq = GST_MULTIQUEUE_PAD (pad)->sq;
2889   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
2890   gboolean ret;
2891   GstPad *sinkpad = g_weak_ref_get (&sq->sinkpad);
2892
2893   if (!mq || !sinkpad) {
2894     gst_clear_object (&sinkpad);
2895     gst_clear_object (&mq);
2896     GST_INFO_OBJECT (pad, "No multique/sinkpad set anymore, flushing");
2897
2898     return FALSE;
2899   }
2900
2901   switch (GST_EVENT_TYPE (event)) {
2902     case GST_EVENT_RECONFIGURE:
2903       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
2904       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2905         sq->srcresult = GST_FLOW_OK;
2906         g_cond_signal (&sq->turn);
2907       }
2908       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
2909
2910       ret = gst_pad_push_event (sinkpad, event);
2911       break;
2912     default:
2913       ret = gst_pad_push_event (sinkpad, event);
2914       break;
2915   }
2916
2917   gst_object_unref (sinkpad);
2918   gst_object_unref (mq);
2919
2920   return ret;
2921 }
2922
2923 static gboolean
2924 gst_multi_queue_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2925 {
2926   gboolean res;
2927
2928   /* FIXME, Handle position offset depending on queue size */
2929   switch (GST_QUERY_TYPE (query)) {
2930     default:
2931       /* default handling */
2932       res = gst_pad_query_default (pad, parent, query);
2933       break;
2934   }
2935   return res;
2936 }
2937
2938 /*
2939  * Next-non-linked functions
2940  */
2941
2942 /* WITH LOCK TAKEN */
2943 static void
2944 wake_up_next_non_linked (GstMultiQueue * mq)
2945 {
2946   GList *tmp;
2947
2948   /* maybe no-one is waiting */
2949   if (mq->numwaiting < 1)
2950     return;
2951
2952   if (mq->sync_by_running_time && GST_CLOCK_STIME_IS_VALID (mq->high_time)) {
2953     /* Else figure out which singlequeue(s) need waking up */
2954     for (tmp = mq->queues; tmp; tmp = tmp->next) {
2955       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2956       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
2957         GstClockTimeDiff high_time;
2958
2959         if (GST_CLOCK_STIME_IS_VALID (sq->group_high_time))
2960           high_time = sq->group_high_time;
2961         else
2962           high_time = mq->high_time;
2963
2964         if (GST_CLOCK_STIME_IS_VALID (sq->next_time) &&
2965             GST_CLOCK_STIME_IS_VALID (high_time)
2966             && sq->next_time <= high_time) {
2967           GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
2968           g_cond_signal (&sq->turn);
2969         }
2970       }
2971     }
2972   } else {
2973     /* Else figure out which singlequeue(s) need waking up */
2974     for (tmp = mq->queues; tmp; tmp = tmp->next) {
2975       GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2976       if (sq->srcresult == GST_FLOW_NOT_LINKED &&
2977           sq->nextid != 0 && sq->nextid <= mq->highid) {
2978         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
2979         g_cond_signal (&sq->turn);
2980       }
2981     }
2982   }
2983 }
2984
2985 /* WITH LOCK TAKEN */
2986 static void
2987 compute_high_id (GstMultiQueue * mq)
2988 {
2989   /* The high-id is either the highest id among the linked pads, or if all
2990    * pads are not-linked, it's the lowest not-linked pad */
2991   GList *tmp;
2992   guint32 lowest = G_MAXUINT32;
2993   guint32 highid = G_MAXUINT32;
2994
2995   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
2996     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
2997     GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
2998
2999     if (!srcpad) {
3000       GST_INFO_OBJECT (mq,
3001           "srcpad has been removed already... ignoring single queue");
3002
3003       continue;
3004     }
3005
3006     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
3007         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
3008
3009     /* No need to consider queues which are not waiting */
3010     if (sq->nextid == 0) {
3011       GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3012       gst_object_unref (srcpad);
3013       continue;
3014     }
3015
3016     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3017       if (sq->nextid < lowest)
3018         lowest = sq->nextid;
3019     } else if (!GST_PAD_IS_EOS (srcpad) && sq->srcresult != GST_FLOW_EOS) {
3020       /* If we don't have a global highid, or the global highid is lower than
3021        * this single queue's last outputted id, store the queue's one,
3022        * unless the singlequeue output is at EOS */
3023       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
3024         highid = sq->oldid;
3025     }
3026     gst_object_unref (srcpad);
3027   }
3028
3029   if (highid == G_MAXUINT32 || lowest < highid)
3030     mq->highid = lowest;
3031   else
3032     mq->highid = highid;
3033
3034   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
3035       lowest);
3036 }
3037
3038 /* WITH LOCK TAKEN */
3039 static void
3040 compute_high_time (GstMultiQueue * mq, guint groupid)
3041 {
3042   /* The high-time is either the highest last time among the linked
3043    * pads, or if all pads are not-linked, it's the lowest nex time of
3044    * not-linked pad */
3045   GList *tmp;
3046   GstClockTimeDiff highest = GST_CLOCK_STIME_NONE;
3047   GstClockTimeDiff lowest = GST_CLOCK_STIME_NONE;
3048   GstClockTimeDiff group_high = GST_CLOCK_STIME_NONE;
3049   GstClockTimeDiff group_low = GST_CLOCK_STIME_NONE;
3050   GstClockTimeDiff res;
3051   /* Number of streams which belong to groupid */
3052   guint group_count = 0;
3053
3054   if (!mq->sync_by_running_time)
3055     /* return GST_CLOCK_STIME_NONE; */
3056     return;
3057
3058   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3059     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3060     GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
3061
3062     if (!srcpad) {
3063       GST_INFO_OBJECT (mq,
3064           "srcpad has been removed already... ignoring single queue");
3065
3066       continue;
3067     }
3068
3069     GST_LOG_OBJECT (mq,
3070         "inspecting sq:%d (group:%d) , next_time:%" GST_STIME_FORMAT
3071         ", last_time:%" GST_STIME_FORMAT ", srcresult:%s", sq->id, sq->groupid,
3072         GST_STIME_ARGS (sq->next_time), GST_STIME_ARGS (sq->last_time),
3073         gst_flow_get_name (sq->srcresult));
3074
3075     if (sq->groupid == groupid)
3076       group_count++;
3077
3078     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3079       /* No need to consider queues which are not waiting */
3080       if (!GST_CLOCK_STIME_IS_VALID (sq->next_time)) {
3081         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
3082         gst_object_unref (srcpad);
3083         continue;
3084       }
3085
3086       if (lowest == GST_CLOCK_STIME_NONE || sq->next_time < lowest)
3087         lowest = sq->next_time;
3088       if (sq->groupid == groupid && (group_low == GST_CLOCK_STIME_NONE
3089               || sq->next_time < group_low))
3090         group_low = sq->next_time;
3091     } else if (!GST_PAD_IS_EOS (srcpad) && sq->srcresult != GST_FLOW_EOS) {
3092       /* If we don't have a global high time, or the global high time
3093        * is lower than this single queue's last outputted time, store
3094        * the queue's one, unless the singlequeue output is at EOS. */
3095       if (highest == GST_CLOCK_STIME_NONE
3096           || (sq->last_time != GST_CLOCK_STIME_NONE && sq->last_time > highest))
3097         highest = sq->last_time;
3098       if (sq->groupid == groupid && (group_high == GST_CLOCK_STIME_NONE
3099               || (sq->last_time != GST_CLOCK_STIME_NONE
3100                   && sq->last_time > group_high)))
3101         group_high = sq->last_time;
3102     }
3103     GST_LOG_OBJECT (mq,
3104         "highest now %" GST_STIME_FORMAT " lowest %" GST_STIME_FORMAT,
3105         GST_STIME_ARGS (highest), GST_STIME_ARGS (lowest));
3106     if (sq->groupid == groupid)
3107       GST_LOG_OBJECT (mq,
3108           "grouphigh %" GST_STIME_FORMAT " grouplow %" GST_STIME_FORMAT,
3109           GST_STIME_ARGS (group_high), GST_STIME_ARGS (group_low));
3110
3111     gst_object_unref (srcpad);
3112   }
3113
3114   if (highest == GST_CLOCK_STIME_NONE)
3115     mq->high_time = lowest;
3116   else
3117     mq->high_time = highest;
3118
3119   /* If there's only one stream of a given type, use the global high */
3120   if (group_count < 2)
3121     res = GST_CLOCK_STIME_NONE;
3122   else if (group_high == GST_CLOCK_STIME_NONE)
3123     res = group_low;
3124   else
3125     res = group_high;
3126
3127   GST_LOG_OBJECT (mq, "group count %d for groupid %u", group_count, groupid);
3128   GST_LOG_OBJECT (mq,
3129       "MQ High time is now : %" GST_STIME_FORMAT ", group %d high time %"
3130       GST_STIME_FORMAT ", lowest non-linked %" GST_STIME_FORMAT,
3131       GST_STIME_ARGS (mq->high_time), groupid, GST_STIME_ARGS (mq->high_time),
3132       GST_STIME_ARGS (lowest));
3133
3134   for (tmp = mq->queues; tmp; tmp = tmp->next) {
3135     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
3136     if (groupid == sq->groupid)
3137       sq->group_high_time = res;
3138   }
3139 }
3140
3141 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
3142      ((q)->max_size.format) <= (value))
3143
3144 /*
3145  * GstSingleQueue functions
3146  */
3147 static void
3148 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3149 {
3150   GList *tmp;
3151   GstDataQueueSize size;
3152   gboolean filled = TRUE;
3153   gboolean empty_found = FALSE;
3154   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3155
3156   if (!mq) {
3157     GST_ERROR ("No multique set anymore, not doing anything");
3158
3159     return;
3160   }
3161
3162   gst_data_queue_get_level (sq->queue, &size);
3163
3164   GST_LOG_OBJECT (mq,
3165       "Single Queue %d: EOS %d, visible %u/%u, bytes %u/%u, time %"
3166       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, sq->is_eos, size.visible,
3167       sq->max_size.visible, size.bytes, sq->max_size.bytes, sq->cur_time,
3168       sq->max_size.time);
3169
3170   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3171
3172   /* check if we reached the hard time/bytes limits;
3173      time limit is only taken into account for non-sparse streams */
3174   if (sq->is_eos || IS_FILLED (sq, bytes, size.bytes) ||
3175       (!sq->is_sparse && IS_FILLED (sq, time, sq->cur_time))) {
3176     goto done;
3177   }
3178
3179   /* Search for empty queues */
3180   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3181     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3182
3183     if (oq == sq)
3184       continue;
3185
3186     if (oq->srcresult == GST_FLOW_NOT_LINKED) {
3187       GST_LOG_OBJECT (mq, "Queue %d is not-linked", oq->id);
3188       continue;
3189     }
3190
3191     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
3192     if (gst_data_queue_is_empty (oq->queue) && !oq->is_sparse) {
3193       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
3194       empty_found = TRUE;
3195       break;
3196     }
3197   }
3198
3199   /* if hard limits are not reached then we allow one more buffer in the full
3200    * queue, but only if any of the other singelqueues are empty */
3201   if (empty_found) {
3202     if (IS_FILLED (sq, visible, size.visible)) {
3203       sq->max_size.visible = size.visible + 1;
3204       GST_DEBUG_OBJECT (mq,
3205           "Bumping single queue %d max visible to %d",
3206           sq->id, sq->max_size.visible);
3207       filled = FALSE;
3208     }
3209   }
3210
3211 done:
3212   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3213   gst_object_unref (mq);
3214
3215   /* Overrun is always forwarded, since this is blocking the upstream element */
3216   if (filled) {
3217     GST_DEBUG_OBJECT (mq, "Queue %d is filled, signalling overrun", sq->id);
3218     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
3219   }
3220 }
3221
3222 static void
3223 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
3224 {
3225   gboolean empty = TRUE;
3226   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3227   GList *tmp;
3228
3229   if (!mq) {
3230     GST_ERROR ("No multique set anymore, not doing anything");
3231
3232     return;
3233   }
3234
3235   if (sq->srcresult == GST_FLOW_NOT_LINKED) {
3236     GST_LOG_OBJECT (mq, "Single Queue %d is empty but not-linked", sq->id);
3237     gst_object_unref (mq);
3238     return;
3239   } else {
3240     GST_LOG_OBJECT (mq,
3241         "Single Queue %d is empty, Checking other single queues", sq->id);
3242   }
3243
3244   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3245   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
3246     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
3247
3248     if (gst_data_queue_is_full (oq->queue)) {
3249       GstDataQueueSize size;
3250
3251       gst_data_queue_get_level (oq->queue, &size);
3252       if (IS_FILLED (oq, visible, size.visible)) {
3253         oq->max_size.visible = size.visible + 1;
3254         GST_DEBUG_OBJECT (mq,
3255             "queue %d is filled, bumping its max visible to %d", oq->id,
3256             oq->max_size.visible);
3257         gst_data_queue_limits_changed (oq->queue);
3258       }
3259     }
3260     if (!gst_data_queue_is_empty (oq->queue) || oq->is_sparse)
3261       empty = FALSE;
3262   }
3263   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3264   gst_object_unref (mq);
3265
3266   if (empty) {
3267     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
3268     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
3269   }
3270 }
3271
3272 static gboolean
3273 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
3274     guint64 time, GstSingleQueue * sq)
3275 {
3276   gboolean res;
3277   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3278
3279   if (!mq) {
3280     GST_ERROR ("No multique set anymore, let's say we are full");
3281
3282     return TRUE;
3283   }
3284
3285   GST_DEBUG_OBJECT (mq,
3286       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
3287       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
3288       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
3289
3290   /* we are always filled on EOS */
3291   if (sq->is_eos || sq->is_segment_done) {
3292     res = TRUE;
3293     goto done;
3294   }
3295
3296   /* we never go past the max visible items unless we are in buffering mode */
3297   if (!mq->use_buffering && IS_FILLED (sq, visible, visible)) {
3298     res = TRUE;
3299     goto done;
3300   }
3301
3302   /* check time or bytes */
3303   res = IS_FILLED (sq, bytes, bytes);
3304   /* We only care about limits in time if we're not a sparse stream or
3305    * we're not syncing by running time */
3306   if (!sq->is_sparse || !mq->sync_by_running_time) {
3307     /* If unlinked, take into account the extra unlinked cache time */
3308     if (mq->sync_by_running_time && sq->srcresult == GST_FLOW_NOT_LINKED) {
3309       if (sq->cur_time > mq->unlinked_cache_time)
3310         res |= IS_FILLED (sq, time, sq->cur_time - mq->unlinked_cache_time);
3311       else
3312         res = FALSE;
3313     } else
3314       res |= IS_FILLED (sq, time, sq->cur_time);
3315   }
3316 done:
3317   gst_object_unref (mq);
3318
3319   return res;
3320 }
3321
3322 static void
3323 gst_single_queue_flush_queue (GstSingleQueue * sq, gboolean full)
3324 {
3325   GstDataQueueItem *sitem;
3326   GstMultiQueueItem *mitem;
3327   gboolean was_flushing = FALSE;
3328   GstPad *srcpad = g_weak_ref_get (&sq->srcpad);
3329   GstMultiQueue *mq = g_weak_ref_get (&sq->mqueue);
3330
3331   while (!gst_data_queue_is_empty (sq->queue)) {
3332     GstMiniObject *data;
3333
3334     /* FIXME: If this fails here although the queue is not empty,
3335      * we're flushing... but we want to rescue all sticky
3336      * events nonetheless.
3337      */
3338     if (!gst_data_queue_pop (sq->queue, &sitem)) {
3339       was_flushing = TRUE;
3340       gst_data_queue_set_flushing (sq->queue, FALSE);
3341       continue;
3342     }
3343
3344     mitem = (GstMultiQueueItem *) sitem;
3345
3346     data = sitem->object;
3347
3348     if (!full && !mitem->is_query && GST_IS_EVENT (data)
3349         && srcpad && GST_EVENT_IS_STICKY (data)
3350         && GST_EVENT_TYPE (data) != GST_EVENT_SEGMENT
3351         && GST_EVENT_TYPE (data) != GST_EVENT_EOS) {
3352       gst_pad_store_sticky_event (srcpad, GST_EVENT_CAST (data));
3353     }
3354
3355     sitem->destroy (sitem);
3356   }
3357   gst_clear_object (&srcpad);
3358
3359   gst_data_queue_flush (sq->queue);
3360   if (was_flushing)
3361     gst_data_queue_set_flushing (sq->queue, TRUE);
3362
3363   if (mq) {
3364     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
3365     update_buffering (mq, sq);
3366     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
3367     gst_multi_queue_post_buffering (mq);
3368     gst_object_unref (mq);
3369   }
3370 }
3371
3372 static void
3373 gst_single_queue_unref (GstSingleQueue * sq)
3374 {
3375   if (g_atomic_int_dec_and_test (&sq->refcount)) {
3376     /* DRAIN QUEUE */
3377     gst_data_queue_flush (sq->queue);
3378     g_object_unref (sq->queue);
3379     g_cond_clear (&sq->turn);
3380     g_cond_clear (&sq->query_handled);
3381     g_weak_ref_clear (&sq->sinkpad);
3382     g_weak_ref_clear (&sq->srcpad);
3383     g_weak_ref_clear (&sq->mqueue);
3384     g_free (sq);
3385   }
3386 }
3387
3388
3389 static GstSingleQueue *
3390 gst_single_queue_ref (GstSingleQueue * squeue)
3391 {
3392   g_atomic_int_inc (&squeue->refcount);
3393
3394   return squeue;
3395 }
3396
3397 static GstSingleQueue *
3398 gst_single_queue_new (GstMultiQueue * mqueue, guint id)
3399 {
3400   GstPad *srcpad, *sinkpad;
3401   GstSingleQueue *sq;
3402   GstPadTemplate *templ;
3403   gchar *name;
3404   GList *tmp;
3405   guint temp_id = (id == -1) ? 0 : id;
3406
3407   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
3408
3409   /* Find an unused queue ID, if possible the passed one */
3410   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
3411     GstSingleQueue *sq2 = (GstSingleQueue *) tmp->data;
3412     /* This works because the IDs are sorted in ascending order */
3413     if (sq2->id == temp_id) {
3414       /* If this ID was requested by the caller return NULL,
3415        * otherwise just get us the next one */
3416       if (id == -1) {
3417         temp_id = sq2->id + 1;
3418       } else {
3419         GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3420         return NULL;
3421       }
3422     } else if (sq2->id > temp_id) {
3423       break;
3424     }
3425   }
3426
3427   sq = g_new0 (GstSingleQueue, 1);
3428   g_atomic_int_set (&sq->refcount, 1);
3429
3430   mqueue->nbqueues++;
3431   sq->id = temp_id;
3432   sq->groupid = DEFAULT_PAD_GROUP_ID;
3433   sq->group_high_time = GST_CLOCK_STIME_NONE;
3434
3435   mqueue->queues = g_list_insert_before (mqueue->queues, tmp, sq);
3436   mqueue->queues_cookie++;
3437
3438   /* copy over max_size and extra_size so we don't need to take the lock
3439    * any longer when checking if the queue is full. */
3440   sq->max_size.visible = mqueue->max_size.visible;
3441   sq->max_size.bytes = mqueue->max_size.bytes;
3442   sq->max_size.time = mqueue->max_size.time;
3443
3444   sq->extra_size.visible = mqueue->extra_size.visible;
3445   sq->extra_size.bytes = mqueue->extra_size.bytes;
3446   sq->extra_size.time = mqueue->extra_size.time;
3447
3448   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
3449
3450   g_weak_ref_init (&sq->mqueue, mqueue);
3451   sq->srcresult = GST_FLOW_FLUSHING;
3452   sq->pushed = FALSE;
3453   sq->queue = gst_data_queue_new ((GstDataQueueCheckFullFunction)
3454       single_queue_check_full,
3455       (GstDataQueueFullCallback) single_queue_overrun_cb,
3456       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
3457   sq->is_eos = FALSE;
3458   sq->is_sparse = FALSE;
3459   sq->flushing = FALSE;
3460   sq->active = FALSE;
3461   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
3462   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
3463
3464   sq->nextid = 0;
3465   sq->oldid = 0;
3466   sq->next_time = GST_CLOCK_STIME_NONE;
3467   sq->last_time = GST_CLOCK_STIME_NONE;
3468   g_cond_init (&sq->turn);
3469   g_cond_init (&sq->query_handled);
3470
3471   sq->sinktime = GST_CLOCK_STIME_NONE;
3472   sq->srctime = GST_CLOCK_STIME_NONE;
3473   sq->sink_tainted = TRUE;
3474   sq->src_tainted = TRUE;
3475
3476   name = g_strdup_printf ("sink_%u", sq->id);
3477   templ = gst_static_pad_template_get (&sinktemplate);
3478   sinkpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
3479       "direction", templ->direction, "template", templ, NULL);
3480   g_weak_ref_init (&sq->sinkpad, sinkpad);
3481   gst_object_unref (templ);
3482   g_free (name);
3483
3484   GST_MULTIQUEUE_PAD (sinkpad)->sq = sq;
3485
3486   gst_pad_set_chain_function (sinkpad,
3487       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
3488   gst_pad_set_activatemode_function (sinkpad,
3489       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_mode));
3490   gst_pad_set_event_full_function (sinkpad,
3491       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
3492   gst_pad_set_query_function (sinkpad,
3493       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_query));
3494   gst_pad_set_iterate_internal_links_function (sinkpad,
3495       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3496   GST_OBJECT_FLAG_SET (sinkpad, GST_PAD_FLAG_PROXY_CAPS);
3497
3498   name = g_strdup_printf ("src_%u", sq->id);
3499   templ = gst_static_pad_template_get (&srctemplate);
3500   srcpad = g_object_new (GST_TYPE_MULTIQUEUE_PAD, "name", name,
3501       "direction", templ->direction, "template", templ, NULL);
3502   g_weak_ref_init (&sq->srcpad, srcpad);
3503   gst_object_unref (templ);
3504   g_free (name);
3505
3506   GST_MULTIQUEUE_PAD (srcpad)->sq = gst_single_queue_ref (sq);
3507
3508   gst_pad_set_activatemode_function (srcpad,
3509       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_mode));
3510   gst_pad_set_event_function (srcpad,
3511       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
3512   gst_pad_set_query_function (srcpad,
3513       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
3514   gst_pad_set_iterate_internal_links_function (srcpad,
3515       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
3516   GST_OBJECT_FLAG_SET (srcpad, GST_PAD_FLAG_PROXY_CAPS);
3517
3518   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
3519
3520   /* only activate the pads when we are not in the NULL state
3521    * and add the pad under the state_lock to prevent state changes
3522    * between activating and adding */
3523   g_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
3524   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3525     gst_pad_set_active (srcpad, TRUE);
3526     gst_pad_set_active (sinkpad, TRUE);
3527   }
3528   gst_element_add_pad (GST_ELEMENT (mqueue), srcpad);
3529   gst_element_add_pad (GST_ELEMENT (mqueue), sinkpad);
3530   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
3531     gst_single_queue_start (mqueue, sq);
3532   }
3533   g_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
3534
3535   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
3536       sq->id);
3537
3538   return sq;
3539 }