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