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