]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - glsdk/gstreamer0-10.git/blob - plugins/elements/gstmultiqueue.c
multiqueue: refactor buffering code
[glsdk/gstreamer0-10.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  *
6  * gstmultiqueue.c:
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
24 /**
25  * SECTION:element-multiqueue
26  * @see_also: #GstQueue
27  *
28  * <refsect2>
29  * <para>
30  * Multiqueue is similar to a normal #GstQueue with the following additional
31  * features:
32  * <orderedlist>
33  * <listitem>
34  *   <itemizedlist><title>Multiple streamhandling</title>
35  *   <listitem><para>
36  *     The element handles queueing data on more than one stream at once. To
37  *     achieve such a feature it has request sink pads (sink%d) and
38  *     'sometimes' src pads (src%d).
39  *   </para><para>
40  *     When requesting a given sinkpad with gst_element_get_request_pad(),
41  *     the associated srcpad for that stream will be created.
42  *     Example: requesting sink1 will generate src1.
43  *   </para></listitem>
44  *   </itemizedlist>
45  * </listitem>
46  * <listitem>
47  *   <itemizedlist><title>Non-starvation on multiple streams</title>
48  *   <listitem><para>
49  *     If more than one stream is used with the element, the streams' queues
50  *     will be dynamically grown (up to a limit), in order to ensure that no
51  *     stream is risking data starvation. This guarantees that at any given
52  *     time there are at least N bytes queued and available for each individual
53  *     stream.
54  *   </para><para>
55  *     If an EOS event comes through a srcpad, the associated queue will be
56  *     considered as 'not-empty' in the queue-size-growing algorithm.
57  *   </para></listitem>
58  *   </itemizedlist>
59  * </listitem>
60  * <listitem>
61  *   <itemizedlist><title>Non-linked srcpads graceful handling</title>
62  *   <listitem><para>
63  *     In order to better support dynamic switching between streams, the multiqueue
64  *     (unlike the current GStreamer queue) continues to push buffers on non-linked
65  *     pads rather than shutting down.
66  *   </para><para>
67  *     In addition, to prevent a non-linked stream from very quickly consuming all
68  *     available buffers and thus 'racing ahead' of the other streams, the element
69  *     must ensure that buffers and inlined events for a non-linked stream are pushed
70  *     in the same order as they were received, relative to the other streams
71  *     controlled by the element. This means that a buffer cannot be pushed to a
72  *     non-linked pad any sooner than buffers in any other stream which were received
73  *     before it.
74  *   </para></listitem>
75  *   </itemizedlist>
76  * </listitem>
77  * </orderedlist>
78  * </para>
79  * <para>
80  *   Data is queued until one of the limits specified by the
81  *   #GstMultiQueue:max-size-buffers, #GstMultiQueue:max-size-bytes and/or
82  *   #GstMultiQueue:max-size-time properties has been reached. Any attempt to push
83  *   more buffers into the queue will block the pushing thread until more space
84  *   becomes available. #GstMultiQueue:extra-size-buffers,
85  * </para>
86  * <para>
87  *   #GstMultiQueue:extra-size-bytes and #GstMultiQueue:extra-size-time are
88  *   currently unused.
89  * </para>
90  * <para>
91  *   The default queue size limits are 5 buffers, 10MB of data, or
92  *   two second worth of data, whichever is reached first. Note that the number
93  *   of buffers will dynamically grow depending on the fill level of 
94  *   other queues.
95  * </para>
96  * <para>
97  *   The #GstMultiQueue::underrun signal is emitted when all of the queues
98  *   are empty. The #GstMultiQueue::overrun signal is emitted when one of the
99  *   queues is filled.
100  *   Both signals are emitted from the context of the streaming thread.
101  * </para>
102  * </refsect2>
103  *
104  * Last reviewed on 2008-01-25 (0.10.17)
105  */
107 #ifdef HAVE_CONFIG_H
108 #  include "config.h"
109 #endif
111 #include <gst/gst.h>
112 #include "gstmultiqueue.h"
114 /**
115  * GstSingleQueue:
116  * @sinkpad: associated sink #GstPad
117  * @srcpad: associated source #GstPad
118  *
119  * Structure containing all information and properties about
120  * a single queue.
121  */
122 typedef struct _GstSingleQueue GstSingleQueue;
124 struct _GstSingleQueue
126   /* unique identifier of the queue */
127   guint id;
129   GstMultiQueue *mqueue;
131   GstPad *sinkpad;
132   GstPad *srcpad;
134   /* flowreturn of previous srcpad push */
135   GstFlowReturn srcresult;
137   /* segments */
138   GstSegment sink_segment;
139   GstSegment src_segment;
141   /* position of src/sink */
142   GstClockTime sinktime, srctime;
143   /* TRUE if either position needs to be recalculated */
144   gboolean sink_tainted, src_tainted;
146   /* queue of data */
147   GstDataQueue *queue;
148   GstDataQueueSize max_size, extra_size;
149   GstClockTime cur_time;
150   gboolean is_eos;
152   /* Protected by global lock */
153   guint32 nextid;               /* ID of the next object waiting to be pushed */
154   guint32 oldid;                /* ID of the last object pushed (last in a series) */
155   GCond *turn;                  /* SingleQueue turn waiting conditional */
156 };
159 /* Extension of GstDataQueueItem structure for our usage */
160 typedef struct _GstMultiQueueItem GstMultiQueueItem;
162 struct _GstMultiQueueItem
164   GstMiniObject *object;
165   guint size;
166   guint64 duration;
167   gboolean visible;
169   GDestroyNotify destroy;
170   guint32 posid;
171 };
173 static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue);
174 static void gst_single_queue_free (GstSingleQueue * squeue);
176 static void wake_up_next_non_linked (GstMultiQueue * mq);
177 static void compute_high_id (GstMultiQueue * mq);
178 static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
179 static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
181 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink%d",
182     GST_PAD_SINK,
183     GST_PAD_REQUEST,
184     GST_STATIC_CAPS_ANY);
186 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src%d",
187     GST_PAD_SRC,
188     GST_PAD_SOMETIMES,
189     GST_STATIC_CAPS_ANY);
191 GST_DEBUG_CATEGORY_STATIC (multi_queue_debug);
192 #define GST_CAT_DEFAULT (multi_queue_debug)
194 /* Signals and args */
195 enum
197   SIGNAL_UNDERRUN,
198   SIGNAL_OVERRUN,
199   LAST_SIGNAL
200 };
202 /* default limits, we try to keep up to 2 seconds of data and if there is not
203  * time, up to 10 MB. The number of buffers is dynamically scaled to make sure
204  * there is data in the queues. Normally, the byte and time limits are not hit
205  * in theses conditions. */
206 #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */
207 #define DEFAULT_MAX_SIZE_BUFFERS 5
208 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND
210 /* second limits. When we hit one of the above limits we are probably dealing
211  * with a badly muxed file and we scale the limits to these emergency values.
212  * This is currently not yet implemented.
213  * Since we dynamically scale the queue buffer size up to the limits but avoid
214  * going above the max-size-buffers when we can, we don't really need this
215  * aditional extra size. */
216 #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024       /* 10 MB */
217 #define DEFAULT_EXTRA_SIZE_BUFFERS 5
218 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND
220 #define DEFAULT_USE_BUFFERING FALSE
221 #define DEFAULT_LOW_PERCENT   10
222 #define DEFAULT_HIGH_PERCENT  99
224 enum
226   PROP_0,
227   PROP_EXTRA_SIZE_BYTES,
228   PROP_EXTRA_SIZE_BUFFERS,
229   PROP_EXTRA_SIZE_TIME,
230   PROP_MAX_SIZE_BYTES,
231   PROP_MAX_SIZE_BUFFERS,
232   PROP_MAX_SIZE_TIME,
233   PROP_USE_BUFFERING,
234   PROP_LOW_PERCENT,
235   PROP_HIGH_PERCENT,
236   PROP_LAST
237 };
239 #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
240   g_mutex_lock (q->qlock);                                              \
241 } G_STMT_END
243 #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
244   g_mutex_unlock (q->qlock);                                            \
245 } G_STMT_END
247 static void gst_multi_queue_finalize (GObject * object);
248 static void gst_multi_queue_set_property (GObject * object,
249     guint prop_id, const GValue * value, GParamSpec * pspec);
250 static void gst_multi_queue_get_property (GObject * object,
251     guint prop_id, GValue * value, GParamSpec * pspec);
253 static GstPad *gst_multi_queue_request_new_pad (GstElement * element,
254     GstPadTemplate * temp, const gchar * name);
255 static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad);
257 static void gst_multi_queue_loop (GstPad * pad);
259 #define _do_init(bla) \
260   GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element");
262 GST_BOILERPLATE_FULL (GstMultiQueue, gst_multi_queue, GstElement,
263     GST_TYPE_ELEMENT, _do_init);
265 static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 };
267 static void
268 gst_multi_queue_base_init (gpointer g_class)
270   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
272   gst_element_class_set_details_simple (gstelement_class,
273       "MultiQueue",
274       "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>");
275   gst_element_class_add_pad_template (gstelement_class,
276       gst_static_pad_template_get (&sinktemplate));
277   gst_element_class_add_pad_template (gstelement_class,
278       gst_static_pad_template_get (&srctemplate));
281 static void
282 gst_multi_queue_class_init (GstMultiQueueClass * klass)
284   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
285   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
287   gobject_class->set_property =
288       GST_DEBUG_FUNCPTR (gst_multi_queue_set_property);
289   gobject_class->get_property =
290       GST_DEBUG_FUNCPTR (gst_multi_queue_get_property);
292   /* SIGNALS */
294   /**
295    * GstMultiQueue::underrun:
296    * @multiqueue: the multqueue instance
297    *
298    * This signal is emitted from the streaming thread when there is
299    * no data in any of the queues inside the multiqueue instance (underrun).
300    *
301    * This indicates either starvation or EOS from the upstream data sources.
302    */
303   gst_multi_queue_signals[SIGNAL_UNDERRUN] =
304       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
305       G_STRUCT_OFFSET (GstMultiQueueClass, underrun), NULL, NULL,
306       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
308   /**
309    * GstMultiQueue::overrun:
310    * @multiqueue: the multiqueue instance
311    *
312    * Reports that one of the queues in the multiqueue is full (overrun).
313    * A queue is full if the total amount of data inside it (num-buffers, time,
314    * size) is higher than the boundary values which can be set through the
315    * GObject properties.
316    *
317    * This can be used as an indicator of pre-roll. 
318    */
319   gst_multi_queue_signals[SIGNAL_OVERRUN] =
320       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
321       G_STRUCT_OFFSET (GstMultiQueueClass, overrun), NULL, NULL,
322       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
324   /* PROPERTIES */
326   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
327       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
328           "Max. amount of data in the queue (bytes, 0=disable)",
329           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
330           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
332       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
333           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
334           DEFAULT_MAX_SIZE_BUFFERS,
335           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
336   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
337       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
338           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
339           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BYTES,
342       g_param_spec_uint ("extra-size-bytes", "Extra Size (kB)",
343           "Amount of data the queues can grow if one of them is empty (bytes, 0=disable)"
344           " (NOT IMPLEMENTED)",
345           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BYTES,
346           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
347   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BUFFERS,
348       g_param_spec_uint ("extra-size-buffers", "Extra Size (buffers)",
349           "Amount of buffers the queues can grow if one of them is empty (0=disable)"
350           " (NOT IMPLEMENTED)",
351           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BUFFERS,
352           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
353   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_TIME,
354       g_param_spec_uint64 ("extra-size-time", "Extra Size (ns)",
355           "Amount of time the queues can grow if one of them is empty (in ns, 0=disable)"
356           " (NOT IMPLEMENTED)",
357           0, G_MAXUINT64, DEFAULT_EXTRA_SIZE_TIME,
358           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
360   /**
361    * GstMultiQueue:use-buffering
362    * 
363    * Enable the buffering option in multiqueue so that BUFFERING messages are
364    * emited based on low-/high-percent thresholds.
365    *
366    * Not implemented yet.
367    *
368    * Since: 0.10.26
369    */
370   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
371       g_param_spec_boolean ("use-buffering", "Use buffering",
372           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds"
373           " (not implemented yet)",
374           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
375   /**
376    * GstMultiQueue:low-percent
377    * 
378    * Low threshold percent for buffering to start.
379    *
380    * Not implemented yet.
381    *
382    * Since: 0.10.26
383    */
384   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
385       g_param_spec_int ("low-percent", "Low percent",
386           "Low threshold for buffering to start (not implemented)", 0, 100,
387           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388   /**
389    * GstMultiQueue:high-percent
390    * 
391    * High threshold percent for buffering to finish.
392    *
393    * Not implemented yet.
394    *
395    * Since: 0.10.26
396    */
397   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
398       g_param_spec_int ("high-percent", "High percent",
399           "High threshold for buffering to finish (not implemented)", 0, 100,
400           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
403   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_multi_queue_finalize);
405   gstelement_class->request_new_pad =
406       GST_DEBUG_FUNCPTR (gst_multi_queue_request_new_pad);
407   gstelement_class->release_pad =
408       GST_DEBUG_FUNCPTR (gst_multi_queue_release_pad);
411 static void
412 gst_multi_queue_init (GstMultiQueue * mqueue, GstMultiQueueClass * klass)
414   mqueue->nbqueues = 0;
415   mqueue->queues = NULL;
417   mqueue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
418   mqueue->max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
419   mqueue->max_size.time = DEFAULT_MAX_SIZE_TIME;
421   mqueue->extra_size.bytes = DEFAULT_EXTRA_SIZE_BYTES;
422   mqueue->extra_size.visible = DEFAULT_EXTRA_SIZE_BUFFERS;
423   mqueue->extra_size.time = DEFAULT_EXTRA_SIZE_TIME;
425   mqueue->use_buffering = DEFAULT_USE_BUFFERING;
426   mqueue->low_percent = DEFAULT_LOW_PERCENT;
427   mqueue->high_percent = DEFAULT_HIGH_PERCENT;
429   mqueue->counter = 1;
430   mqueue->highid = -1;
431   mqueue->nextnotlinked = -1;
433   mqueue->qlock = g_mutex_new ();
436 static void
437 gst_multi_queue_finalize (GObject * object)
439   GstMultiQueue *mqueue = GST_MULTI_QUEUE (object);
441   g_list_foreach (mqueue->queues, (GFunc) gst_single_queue_free, NULL);
442   g_list_free (mqueue->queues);
443   mqueue->queues = NULL;
444   mqueue->queues_cookie++;
446   /* free/unref instance data */
447   g_mutex_free (mqueue->qlock);
449   G_OBJECT_CLASS (parent_class)->finalize (object);
452 #define SET_CHILD_PROPERTY(mq,format) G_STMT_START {            \
453     GList * tmp = mq->queues;                                   \
454     while (tmp) {                                               \
455       GstSingleQueue *q = (GstSingleQueue*)tmp->data;           \
456       q->max_size.format = mq->max_size.format;                 \
457       tmp = g_list_next(tmp);                                   \
458     };                                                          \
459 } G_STMT_END
461 static void
462 gst_multi_queue_set_property (GObject * object, guint prop_id,
463     const GValue * value, GParamSpec * pspec)
465   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
467   switch (prop_id) {
468     case PROP_MAX_SIZE_BYTES:
469       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
470       mq->max_size.bytes = g_value_get_uint (value);
471       SET_CHILD_PROPERTY (mq, bytes);
472       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
473       break;
474     case PROP_MAX_SIZE_BUFFERS:
475       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
476       mq->max_size.visible = g_value_get_uint (value);
477       SET_CHILD_PROPERTY (mq, visible);
478       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
479       break;
480     case PROP_MAX_SIZE_TIME:
481       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
482       mq->max_size.time = g_value_get_uint64 (value);
483       SET_CHILD_PROPERTY (mq, time);
484       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
485       break;
486     case PROP_EXTRA_SIZE_BYTES:
487       mq->extra_size.bytes = g_value_get_uint (value);
488       break;
489     case PROP_EXTRA_SIZE_BUFFERS:
490       mq->extra_size.visible = g_value_get_uint (value);
491       break;
492     case PROP_EXTRA_SIZE_TIME:
493       mq->extra_size.time = g_value_get_uint64 (value);
494       break;
495     case PROP_USE_BUFFERING:
496       mq->use_buffering = g_value_get_boolean (value);
497       break;
498     case PROP_LOW_PERCENT:
499       mq->low_percent = g_value_get_int (value);
500       break;
501     case PROP_HIGH_PERCENT:
502       mq->high_percent = g_value_get_int (value);
503       break;
504     default:
505       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
506       break;
507   }
510 static void
511 gst_multi_queue_get_property (GObject * object, guint prop_id,
512     GValue * value, GParamSpec * pspec)
514   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
516   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
518   switch (prop_id) {
519     case PROP_EXTRA_SIZE_BYTES:
520       g_value_set_uint (value, mq->extra_size.bytes);
521       break;
522     case PROP_EXTRA_SIZE_BUFFERS:
523       g_value_set_uint (value, mq->extra_size.visible);
524       break;
525     case PROP_EXTRA_SIZE_TIME:
526       g_value_set_uint64 (value, mq->extra_size.time);
527       break;
528     case PROP_MAX_SIZE_BYTES:
529       g_value_set_uint (value, mq->max_size.bytes);
530       break;
531     case PROP_MAX_SIZE_BUFFERS:
532       g_value_set_uint (value, mq->max_size.visible);
533       break;
534     case PROP_MAX_SIZE_TIME:
535       g_value_set_uint64 (value, mq->max_size.time);
536       break;
537     case PROP_USE_BUFFERING:
538       g_value_set_boolean (value, mq->use_buffering);
539       break;
540     case PROP_LOW_PERCENT:
541       g_value_set_int (value, mq->low_percent);
542       break;
543     case PROP_HIGH_PERCENT:
544       g_value_set_int (value, mq->high_percent);
545       break;
546     default:
547       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
548       break;
549   }
551   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
554 static GstIterator *
555 gst_multi_queue_iterate_internal_links (GstPad * pad)
557   GstIterator *it = NULL;
558   GstPad *opad;
559   GstSingleQueue *squeue;
560   GstMultiQueue *mq = GST_MULTI_QUEUE (gst_pad_get_parent (pad));
562   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
563   squeue = gst_pad_get_element_private (pad);
564   if (!squeue)
565     goto out;
567   if (squeue->sinkpad == pad)
568     opad = gst_object_ref (squeue->srcpad);
569   else if (squeue->srcpad == pad)
570     opad = gst_object_ref (squeue->sinkpad);
571   else
572     goto out;
574   it = gst_iterator_new_single (GST_TYPE_PAD, opad,
575       (GstCopyFunction) gst_object_ref, (GFreeFunc) gst_object_unref);
577   gst_object_unref (opad);
579 out:
580   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
581   gst_object_unref (mq);
583   return it;
587 /*
588  * GstElement methods
589  */
591 static GstPad *
592 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
593     const gchar * name)
595   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
596   GstSingleQueue *squeue;
598   GST_LOG_OBJECT (element, "name : %s", GST_STR_NULL (name));
600   /* Create a new single queue, add the sink and source pad and return the sink pad */
601   squeue = gst_single_queue_new (mqueue);
603   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
604   mqueue->queues = g_list_append (mqueue->queues, squeue);
605   mqueue->queues_cookie++;
606   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
608   GST_DEBUG_OBJECT (mqueue, "Returning pad %s:%s",
609       GST_DEBUG_PAD_NAME (squeue->sinkpad));
611   return squeue->sinkpad;
614 static void
615 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
617   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
618   GstSingleQueue *sq = NULL;
619   GList *tmp;
621   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
623   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
624   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
625   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
626     sq = (GstSingleQueue *) tmp->data;
628     if (sq->sinkpad == pad)
629       break;
630   }
632   if (!tmp) {
633     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
634     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
635     return;
636   }
638   /* FIXME: The removal of the singlequeue should probably not happen until it
639    * finishes draining */
641   /* remove it from the list */
642   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
643   mqueue->queues_cookie++;
645   /* FIXME : recompute next-non-linked */
646   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
648   /* delete SingleQueue */
649   gst_data_queue_set_flushing (sq->queue, TRUE);
651   gst_pad_set_active (sq->srcpad, FALSE);
652   gst_pad_set_active (sq->sinkpad, FALSE);
653   gst_pad_set_element_private (sq->srcpad, NULL);
654   gst_pad_set_element_private (sq->sinkpad, NULL);
655   gst_element_remove_pad (element, sq->srcpad);
656   gst_element_remove_pad (element, sq->sinkpad);
657   gst_single_queue_free (sq);
660 static gboolean
661 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush)
663   gboolean result;
665   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
666       sq->id);
668   if (flush) {
669     sq->srcresult = GST_FLOW_WRONG_STATE;
670     gst_data_queue_set_flushing (sq->queue, TRUE);
672     /* wake up non-linked task */
673     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
674         sq->id);
675     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
676     g_cond_signal (sq->turn);
677     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
679     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
680     result = gst_pad_pause_task (sq->srcpad);
681     sq->sink_tainted = sq->src_tainted = TRUE;
682   } else {
683     gst_data_queue_flush (sq->queue);
684     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
685     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
686     /* All pads start off not-linked for a smooth kick-off */
687     sq->srcresult = GST_FLOW_OK;
688     sq->cur_time = 0;
689     sq->max_size.visible = mq->max_size.visible;
690     sq->is_eos = FALSE;
691     sq->nextid = 0;
692     sq->oldid = 0;
693     gst_data_queue_set_flushing (sq->queue, FALSE);
695     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
696     result =
697         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
698         sq->srcpad);
699   }
700   return result;
703 static void
704 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
706   GstDataQueueSize size;
707   gint percent, tmp;
708   gboolean post = FALSE;
710   /* nothing to dowhen we are not in buffering mode */
711   if (!mq->use_buffering)
712     return;
714   gst_data_queue_get_level (sq->queue, &size);
716   GST_DEBUG_OBJECT (mq,
717       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
718       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
719       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
721   /* get bytes and time percentages and take the max */
722   if (sq->is_eos) {
723     percent = 100;
724   } else {
725     percent = 0;
726     if (sq->max_size.time > 0) {
727       tmp = (sq->cur_time * 100) / sq->max_size.time;
728       percent = MAX (percent, tmp);
729     }
730     if (sq->max_size.bytes > 0) {
731       tmp = (size.bytes * 100) / sq->max_size.bytes;
732       percent = MAX (percent, tmp);
733     }
734     percent = MIN (percent, 100);
735   }
737   if (mq->buffering) {
738     post = TRUE;
739     if (percent >= mq->high_percent) {
740       mq->buffering = FALSE;
741     }
742   } else {
743     if (percent < mq->low_percent) {
744       mq->buffering = TRUE;
745       post = TRUE;
746     }
747   }
748   if (post) {
749     GstMessage *message;
751     /* scale to high percent so that it becomes the 100% mark */
752     percent = percent * 100 / mq->high_percent;
753     /* clip */
754     if (percent > 100)
755       percent = 100;
757     GST_DEBUG_OBJECT (mq, "buffering %d percent", percent);
758     message = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
760     gst_element_post_message (GST_ELEMENT_CAST (mq), message);
761   } else {
762     GST_DEBUG_OBJECT (mq, "filled %d percent", percent);
763   }
766 /* calculate the diff between running time on the sink and src of the queue.
767  * This is the total amount of time in the queue. 
768  * WITH LOCK TAKEN */
769 static void
770 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
772   gint64 sink_time, src_time;
774   if (sq->sink_tainted) {
775     sink_time = sq->sinktime =
776         gst_segment_to_running_time (&sq->sink_segment, GST_FORMAT_TIME,
777         sq->sink_segment.last_stop);
779     if (G_UNLIKELY (sink_time != GST_CLOCK_TIME_NONE))
780       /* if we have a time, we become untainted and use the time */
781       sq->sink_tainted = FALSE;
782   } else
783     sink_time = sq->sinktime;
785   if (sq->src_tainted) {
786     src_time = sq->srctime =
787         gst_segment_to_running_time (&sq->src_segment, GST_FORMAT_TIME,
788         sq->src_segment.last_stop);
789     /* if we have a time, we become untainted and use the time */
790     if (G_UNLIKELY (src_time != GST_CLOCK_TIME_NONE))
791       sq->src_tainted = FALSE;
792   } else
793     src_time = sq->srctime;
795   GST_DEBUG_OBJECT (mq,
796       "queue %d, sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT, sq->id,
797       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
799   /* This allows for streams with out of order timestamping - sometimes the
800    * emerging timestamp is later than the arriving one(s) */
801   if (G_LIKELY (sink_time != -1 && src_time != -1 && sink_time > src_time))
802     sq->cur_time = sink_time - src_time;
803   else
804     sq->cur_time = 0;
806   /* updating the time level can change the buffering state */
807   update_buffering (mq, sq);
809   return;
812 /* take a NEWSEGMENT event and apply the values to segment, updating the time
813  * level of queue. */
814 static void
815 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
816     GstSegment * segment)
818   gboolean update;
819   GstFormat format;
820   gdouble rate, arate;
821   gint64 start, stop, time;
823   gst_event_parse_new_segment_full (event, &update, &rate, &arate,
824       &format, &start, &stop, &time);
826   /* now configure the values, we use these to track timestamps on the
827    * sinkpad. */
828   if (format != GST_FORMAT_TIME) {
829     /* non-time format, pretent the current time segment is closed with a
830      * 0 start and unknown stop time. */
831     update = FALSE;
832     format = GST_FORMAT_TIME;
833     start = 0;
834     stop = -1;
835     time = 0;
836   }
838   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
840   gst_segment_set_newsegment_full (segment, update,
841       rate, arate, format, start, stop, time);
843   if (segment == &sq->sink_segment)
844     sq->sink_tainted = TRUE;
845   else
846     sq->src_tainted = TRUE;
848   GST_DEBUG_OBJECT (mq,
849       "queue %d, configured NEWSEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
851   /* segment can update the time level of the queue */
852   update_time_level (mq, sq);
854   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
857 /* take a buffer and update segment, updating the time level of the queue. */
858 static void
859 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
860     GstClockTime duration, GstSegment * segment)
862   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
864   /* if no timestamp is set, assume it's continuous with the previous 
865    * time */
866   if (timestamp == GST_CLOCK_TIME_NONE)
867     timestamp = segment->last_stop;
869   /* add duration */
870   if (duration != GST_CLOCK_TIME_NONE)
871     timestamp += duration;
873   GST_DEBUG_OBJECT (mq, "queue %d, last_stop updated to %" GST_TIME_FORMAT,
874       sq->id, GST_TIME_ARGS (timestamp));
876   gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
878   if (segment == &sq->sink_segment)
879     sq->sink_tainted = TRUE;
880   else
881     sq->src_tainted = TRUE;
883   /* calc diff with other end */
884   update_time_level (mq, sq);
885   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
888 static GstFlowReturn
889 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
890     GstMiniObject * object)
892   GstFlowReturn result = GST_FLOW_OK;
894   if (GST_IS_BUFFER (object)) {
895     GstBuffer *buffer;
896     GstClockTime timestamp, duration;
897     GstCaps *caps;
899     buffer = GST_BUFFER_CAST (object);
900     timestamp = GST_BUFFER_TIMESTAMP (buffer);
901     duration = GST_BUFFER_DURATION (buffer);
902     caps = GST_BUFFER_CAPS (buffer);
904     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
906     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
907     gst_data_queue_limits_changed (sq->queue);
909     GST_DEBUG_OBJECT (mq,
910         "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
911         sq->id, buffer, GST_TIME_ARGS (timestamp));
913     /* Set caps on pad before pushing, this avoids core calling the acceptcaps
914      * function on the srcpad, which will call acceptcaps upstream, which might
915      * not accept these caps (anymore). */
916     if (caps && caps != GST_PAD_CAPS (sq->srcpad))
917       gst_pad_set_caps (sq->srcpad, caps);
919     result = gst_pad_push (sq->srcpad, buffer);
920   } else if (GST_IS_EVENT (object)) {
921     GstEvent *event;
923     event = GST_EVENT_CAST (object);
925     switch (GST_EVENT_TYPE (event)) {
926       case GST_EVENT_EOS:
927         result = GST_FLOW_UNEXPECTED;
928         break;
929       case GST_EVENT_NEWSEGMENT:
930         apply_segment (mq, sq, event, &sq->src_segment);
931         /* Applying the segment may have made the queue non-full again, unblock it if needed */
932         gst_data_queue_limits_changed (sq->queue);
933         break;
934       default:
935         break;
936     }
938     GST_DEBUG_OBJECT (mq,
939         "SingleQueue %d : Pushing event %p of type %s",
940         sq->id, event, GST_EVENT_TYPE_NAME (event));
942     gst_pad_push_event (sq->srcpad, event);
943   } else {
944     g_warning ("Unexpected object in singlequeue %d (refcounting problem?)",
945         sq->id);
946   }
947   return result;
949   /* ERRORS */
952 static GstMiniObject *
953 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
955   GstMiniObject *res;
957   res = item->object;
958   item->object = NULL;
960   return res;
963 static void
964 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
966   if (item->object)
967     gst_mini_object_unref (item->object);
968   g_slice_free (GstMultiQueueItem, item);
971 /* takes ownership of passed mini object! */
972 static GstMultiQueueItem *
973 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
975   GstMultiQueueItem *item;
977   item = g_slice_new (GstMultiQueueItem);
978   item->object = object;
979   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
980   item->posid = curid;
982   item->size = GST_BUFFER_SIZE (object);
983   item->duration = GST_BUFFER_DURATION (object);
984   if (item->duration == GST_CLOCK_TIME_NONE)
985     item->duration = 0;
986   item->visible = TRUE;
987   return item;
990 static GstMultiQueueItem *
991 gst_multi_queue_event_item_new (GstMiniObject * object, guint32 curid)
993   GstMultiQueueItem *item;
995   item = g_slice_new (GstMultiQueueItem);
996   item->object = object;
997   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
998   item->posid = curid;
1000   item->size = 0;
1001   item->duration = 0;
1002   item->visible = FALSE;
1003   return item;
1006 /* Each main loop attempts to push buffers until the return value
1007  * is not-linked. not-linked pads are not allowed to push data beyond
1008  * any linked pads, so they don't 'rush ahead of the pack'.
1009  */
1010 static void
1011 gst_multi_queue_loop (GstPad * pad)
1013   GstSingleQueue *sq;
1014   GstMultiQueueItem *item;
1015   GstDataQueueItem *sitem;
1016   GstMultiQueue *mq;
1017   GstMiniObject *object;
1018   guint32 newid;
1019   guint32 oldid = G_MAXUINT32;
1020   GstFlowReturn result;
1022   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1023   mq = sq->mqueue;
1025   do {
1026     GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
1028     /* Get something from the queue, blocking until that happens, or we get
1029      * flushed */
1030     if (!(gst_data_queue_pop (sq->queue, &sitem)))
1031       goto out_flushing;
1033     item = (GstMultiQueueItem *) sitem;
1034     newid = item->posid;
1036     /* steal the object and destroy the item */
1037     object = gst_multi_queue_item_steal_object (item);
1038     gst_multi_queue_item_destroy (item);
1040     GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
1041         sq->id, newid, oldid);
1043     /* If we're not-linked, we do some extra work because we might need to
1044      * wait before pushing. If we're linked but there's a gap in the IDs,
1045      * or it's the first loop, or we just passed the previous highid, 
1046      * we might need to wake some sleeping pad up, so there's extra work 
1047      * there too */
1048     if (sq->srcresult == GST_FLOW_NOT_LINKED ||
1049         (oldid == G_MAXUINT32) || (newid != (oldid + 1)) ||
1050         oldid > mq->highid) {
1051       GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
1052           gst_flow_get_name (sq->srcresult));
1054       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1056       /* Update the nextid so other threads know when to wake us up */
1057       sq->nextid = newid;
1059       /* Update the oldid (the last ID we output) for highid tracking */
1060       if (oldid != G_MAXUINT32)
1061         sq->oldid = oldid;
1063       if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1064         /* Go to sleep until it's time to push this buffer */
1066         /* Recompute the highid */
1067         compute_high_id (mq);
1068         while (newid > mq->highid && sq->srcresult == GST_FLOW_NOT_LINKED) {
1069           GST_DEBUG_OBJECT (mq, "queue %d sleeping for not-linked wakeup with "
1070               "newid %u and highid %u", sq->id, newid, mq->highid);
1073           /* Wake up all non-linked pads before we sleep */
1074           wake_up_next_non_linked (mq);
1076           mq->numwaiting++;
1077           g_cond_wait (sq->turn, mq->qlock);
1078           mq->numwaiting--;
1080           GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1081               "wakeup with newid %u and highid %u", sq->id, newid, mq->highid);
1082         }
1084         /* Re-compute the high_id in case someone else pushed */
1085         compute_high_id (mq);
1086       } else {
1087         compute_high_id (mq);
1088         /* Wake up all non-linked pads */
1089         wake_up_next_non_linked (mq);
1090       }
1091       /* We're done waiting, we can clear the nextid */
1092       sq->nextid = 0;
1094       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1095     }
1097     GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s",
1098         gst_flow_get_name (sq->srcresult));
1100     /* Try to push out the new object */
1101     result = gst_single_queue_push_one (mq, sq, object);
1102     sq->srcresult = result;
1104     if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED)
1105       goto out_flushing;
1107     GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s",
1108         gst_flow_get_name (sq->srcresult));
1110     oldid = newid;
1111   }
1112   while (TRUE);
1114 out_flushing:
1115   {
1116     /* Need to make sure wake up any sleeping pads when we exit */
1117     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1118     compute_high_id (mq);
1119     wake_up_next_non_linked (mq);
1120     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1122     /* upstream needs to see fatal result ASAP to shut things down,
1123      * but might be stuck in one of our other full queues;
1124      * so empty this one and trigger dynamic queue growth */
1125     if (GST_FLOW_IS_FATAL (sq->srcresult)) {
1126       gst_data_queue_flush (sq->queue);
1127       single_queue_underrun_cb (sq->queue, sq);
1128     }
1129     gst_data_queue_set_flushing (sq->queue, TRUE);
1130     gst_pad_pause_task (sq->srcpad);
1131     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
1132         "SingleQueue[%d] task paused, reason:%s",
1133         sq->id, gst_flow_get_name (sq->srcresult));
1134     return;
1135   }
1138 /**
1139  * gst_multi_queue_chain:
1140  *
1141  * This is similar to GstQueue's chain function, except:
1142  * _ we don't have leak behavioures,
1143  * _ we push with a unique id (curid)
1144  */
1145 static GstFlowReturn
1146 gst_multi_queue_chain (GstPad * pad, GstBuffer * buffer)
1148   GstSingleQueue *sq;
1149   GstMultiQueue *mq;
1150   GstMultiQueueItem *item;
1151   GstFlowReturn ret = GST_FLOW_OK;
1152   guint32 curid;
1153   GstClockTime timestamp, duration;
1155   sq = gst_pad_get_element_private (pad);
1156   mq = sq->mqueue;
1158   /* Get a unique incrementing id */
1159   curid = mq->counter++;
1161   GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d",
1162       sq->id, buffer, curid);
1164   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
1166   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1167   duration = GST_BUFFER_DURATION (buffer);
1169   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1170     goto flushing;
1172   /* update time level, we must do this after pushing the data in the queue so
1173    * that we never end up filling the queue first. */
1174   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
1176 done:
1177   return ret;
1179   /* ERRORS */
1180 flushing:
1181   {
1182     ret = sq->srcresult;
1183     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1184         sq->id, gst_flow_get_name (ret));
1185     gst_multi_queue_item_destroy (item);
1186     goto done;
1187   }
1190 static gboolean
1191 gst_multi_queue_sink_activate_push (GstPad * pad, gboolean active)
1193   GstSingleQueue *sq;
1195   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1197   if (active) {
1198     /* All pads start off linked until they push one buffer */
1199     sq->srcresult = GST_FLOW_OK;
1200   } else {
1201     sq->srcresult = GST_FLOW_WRONG_STATE;
1202     gst_data_queue_flush (sq->queue);
1203   }
1204   return TRUE;
1207 static gboolean
1208 gst_multi_queue_sink_event (GstPad * pad, GstEvent * event)
1210   GstSingleQueue *sq;
1211   GstMultiQueue *mq;
1212   guint32 curid;
1213   GstMultiQueueItem *item;
1214   gboolean res;
1215   GstEventType type;
1216   GstEvent *sref = NULL;
1218   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1219   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
1221   type = GST_EVENT_TYPE (event);
1223   switch (type) {
1224     case GST_EVENT_FLUSH_START:
1225       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
1226           sq->id);
1228       res = gst_pad_push_event (sq->srcpad, event);
1230       gst_single_queue_flush (mq, sq, TRUE);
1231       goto done;
1233     case GST_EVENT_FLUSH_STOP:
1234       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
1235           sq->id);
1237       res = gst_pad_push_event (sq->srcpad, event);
1239       gst_single_queue_flush (mq, sq, FALSE);
1240       goto done;
1241     case GST_EVENT_NEWSEGMENT:
1242       /* take ref because the queue will take ownership and we need the event
1243        * afterwards to update the segment */
1244       sref = gst_event_ref (event);
1245       break;
1247     default:
1248       if (!(GST_EVENT_IS_SERIALIZED (event))) {
1249         res = gst_pad_push_event (sq->srcpad, event);
1250         goto done;
1251       }
1252       break;
1253   }
1255   /* Get an unique incrementing id. protected with the STREAM_LOCK, unserialized
1256    * events already got pushed and don't end up in the queue. */
1257   curid = mq->counter++;
1259   item = gst_multi_queue_event_item_new ((GstMiniObject *) event, curid);
1261   GST_DEBUG_OBJECT (mq,
1262       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
1263       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
1265   if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1266     goto flushing;
1268   /* mark EOS when we received one, we must do that after putting the
1269    * buffer in the queue because EOS marks the buffer as filled. No need to take
1270    * a lock, the _check_full happens from this thread only, right before pushing
1271    * into dataqueue. */
1272   switch (type) {
1273     case GST_EVENT_EOS:
1274       sq->is_eos = TRUE;
1275       /* EOS affects the buffering state */
1276       update_buffering (mq, sq);
1277       single_queue_overrun_cb (sq->queue, sq);
1278       break;
1279     case GST_EVENT_NEWSEGMENT:
1280       apply_segment (mq, sq, sref, &sq->sink_segment);
1281       gst_event_unref (sref);
1282       break;
1283     default:
1284       break;
1285   }
1286 done:
1287   gst_object_unref (mq);
1288   return res;
1290 flushing:
1291   {
1292     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1293         sq->id, gst_flow_get_name (sq->srcresult));
1294     if (sref)
1295       gst_event_unref (sref);
1296     gst_multi_queue_item_destroy (item);
1297     goto done;
1298   }
1301 static GstCaps *
1302 gst_multi_queue_getcaps (GstPad * pad)
1304   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1305   GstPad *otherpad;
1306   GstCaps *result;
1308   otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad;
1310   GST_LOG_OBJECT (otherpad, "Getting caps from the peer of this pad");
1312   result = gst_pad_peer_get_caps (otherpad);
1313   if (result == NULL)
1314     result = gst_caps_new_any ();
1316   return result;
1319 static GstFlowReturn
1320 gst_multi_queue_bufferalloc (GstPad * pad, guint64 offset, guint size,
1321     GstCaps * caps, GstBuffer ** buf)
1323   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1325   return gst_pad_alloc_buffer (sq->srcpad, offset, size, caps, buf);
1328 static gboolean
1329 gst_multi_queue_src_activate_push (GstPad * pad, gboolean active)
1331   GstMultiQueue *mq;
1332   GstSingleQueue *sq;
1333   gboolean result = FALSE;
1335   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1336   mq = sq->mqueue;
1338   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
1340   if (active) {
1341     result = gst_single_queue_flush (mq, sq, FALSE);
1342   } else {
1343     result = gst_single_queue_flush (mq, sq, TRUE);
1344     /* make sure streaming finishes */
1345     result |= gst_pad_stop_task (pad);
1346   }
1347   return result;
1350 static gboolean
1351 gst_multi_queue_src_event (GstPad * pad, GstEvent * event)
1353   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1355   return gst_pad_push_event (sq->sinkpad, event);
1358 static gboolean
1359 gst_multi_queue_src_query (GstPad * pad, GstQuery * query)
1361   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1362   GstPad *peerpad;
1363   gboolean res;
1365   /* FIXME, Handle position offset depending on queue size */
1367   /* default handling */
1368   if (!(peerpad = gst_pad_get_peer (sq->sinkpad)))
1369     goto no_peer;
1371   res = gst_pad_query (peerpad, query);
1373   gst_object_unref (peerpad);
1375   return res;
1377   /* ERRORS */
1378 no_peer:
1379   {
1380     GST_LOG_OBJECT (sq->sinkpad, "Couldn't send query because we have no peer");
1381     return FALSE;
1382   }
1385 /*
1386  * Next-non-linked functions
1387  */
1389 /* WITH LOCK TAKEN */
1390 static void
1391 wake_up_next_non_linked (GstMultiQueue * mq)
1393   GList *tmp;
1395   /* maybe no-one is waiting */
1396   if (mq->numwaiting < 1)
1397     return;
1399   /* Else figure out which singlequeue(s) need waking up */
1400   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1401     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1403     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1404       if (sq->nextid != 0 && sq->nextid <= mq->highid) {
1405         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
1406         g_cond_signal (sq->turn);
1407       }
1408     }
1409   }
1412 /* WITH LOCK TAKEN */
1413 static void
1414 compute_high_id (GstMultiQueue * mq)
1416   /* The high-id is either the highest id among the linked pads, or if all
1417    * pads are not-linked, it's the lowest not-linked pad */
1418   GList *tmp;
1419   guint32 lowest = G_MAXUINT32;
1420   guint32 highid = G_MAXUINT32;
1422   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1423     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1425     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
1426         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
1428     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1429       /* No need to consider queues which are not waiting */
1430       if (sq->nextid == 0) {
1431         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1432         continue;
1433       }
1435       if (sq->nextid < lowest)
1436         lowest = sq->nextid;
1437     } else if (sq->srcresult != GST_FLOW_UNEXPECTED) {
1438       /* If we don't have a global highid, or the global highid is lower than
1439        * this single queue's last outputted id, store the queue's one, 
1440        * unless the singlequeue is at EOS (srcresult = UNEXPECTED) */
1441       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
1442         highid = sq->oldid;
1443     }
1444   }
1446   if (highid == G_MAXUINT32 || lowest < highid)
1447     mq->highid = lowest;
1448   else
1449     mq->highid = highid;
1451   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
1452       lowest);
1455 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
1456      ((q)->max_size.format) <= (value))
1458 /*
1459  * GstSingleQueue functions
1460  */
1461 static void
1462 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1464   GstMultiQueue *mq = sq->mqueue;
1465   GList *tmp;
1466   GstDataQueueSize size;
1467   gboolean filled = FALSE;
1469   gst_data_queue_get_level (sq->queue, &size);
1471   GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id);
1473   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1474   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1475     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1476     GstDataQueueSize ssize;
1478     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
1480     if (gst_data_queue_is_empty (oq->queue)) {
1481       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
1482       if (IS_FILLED (sq, visible, size.visible)) {
1483         sq->max_size.visible = size.visible + 1;
1484         GST_DEBUG_OBJECT (mq,
1485             "Another queue is empty, bumping single queue %d max visible to %d",
1486             sq->id, sq->max_size.visible);
1487       }
1488       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1489       goto beach;
1490     }
1491     /* check if we reached the hard time/bytes limits */
1492     gst_data_queue_get_level (oq->queue, &ssize);
1494     GST_DEBUG_OBJECT (mq,
1495         "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1496         G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible,
1497         ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time);
1499     /* if this queue is filled completely we must signal overrun.
1500      * FIXME, this seems wrong in many ways
1501      *  - we're comparing the filled level of this queue against the
1502      *    values of the other one
1503      *  - we should only do this after we found no empty queues, ie, move
1504      *    this check outside of the loop
1505      *  - the debug statement talks about a different queue than the one
1506      *    we are checking here.
1507      */
1508     if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) ||
1509         IS_FILLED (sq, time, sq->cur_time)) {
1510       GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id);
1511       filled = TRUE;
1512     }
1513   }
1514   /* no queues were empty */
1515   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1517   /* Overrun is always forwarded, since this is blocking the upstream element */
1518   if (filled) {
1519     GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun");
1520     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
1521   }
1523 beach:
1524   return;
1527 static void
1528 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1530   gboolean empty = TRUE;
1531   GstMultiQueue *mq = sq->mqueue;
1532   GList *tmp;
1534   GST_LOG_OBJECT (mq,
1535       "Single Queue %d is empty, Checking other single queues", sq->id);
1537   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1538   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1539     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1541     if (gst_data_queue_is_full (oq->queue)) {
1542       GstDataQueueSize size;
1544       gst_data_queue_get_level (oq->queue, &size);
1545       if (IS_FILLED (oq, visible, size.visible)) {
1546         oq->max_size.visible = size.visible + 1;
1547         GST_DEBUG_OBJECT (mq,
1548             "queue %d is filled, bumping its max visible to %d", oq->id,
1549             oq->max_size.visible);
1550         gst_data_queue_limits_changed (oq->queue);
1551       }
1552     }
1553     if (!gst_data_queue_is_empty (oq->queue))
1554       empty = FALSE;
1555   }
1556   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1558   if (empty) {
1559     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
1560     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
1561   }
1564 static gboolean
1565 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
1566     guint64 time, GstSingleQueue * sq)
1568   gboolean res;
1569   GstMultiQueue *mq = sq->mqueue;
1571   GST_DEBUG_OBJECT (mq,
1572       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1573       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
1574       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1576   /* we are always filled on EOS */
1577   if (sq->is_eos)
1578     return TRUE;
1580   /* we never go past the max visible items unless we are in buffering mode */
1581   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
1582     return TRUE;
1584   /* check time or bytes */
1585   res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
1587   return res;
1590 static void
1591 gst_single_queue_free (GstSingleQueue * sq)
1593   /* DRAIN QUEUE */
1594   gst_data_queue_flush (sq->queue);
1595   g_object_unref (sq->queue);
1596   g_cond_free (sq->turn);
1597   g_free (sq);
1600 static GstSingleQueue *
1601 gst_single_queue_new (GstMultiQueue * mqueue)
1603   GstSingleQueue *sq;
1604   gchar *tmp;
1606   sq = g_new0 (GstSingleQueue, 1);
1608   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1609   sq->id = mqueue->nbqueues++;
1611   /* copy over max_size and extra_size so we don't need to take the lock
1612    * any longer when checking if the queue is full. */
1613   sq->max_size.visible = mqueue->max_size.visible;
1614   sq->max_size.bytes = mqueue->max_size.bytes;
1615   sq->max_size.time = mqueue->max_size.time;
1617   sq->extra_size.visible = mqueue->extra_size.visible;
1618   sq->extra_size.bytes = mqueue->extra_size.bytes;
1619   sq->extra_size.time = mqueue->extra_size.time;
1621   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1623   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
1625   sq->mqueue = mqueue;
1626   sq->srcresult = GST_FLOW_WRONG_STATE;
1627   sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction)
1628       single_queue_check_full,
1629       (GstDataQueueFullCallback) single_queue_overrun_cb,
1630       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
1631   sq->is_eos = FALSE;
1632   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
1633   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
1635   sq->nextid = 0;
1636   sq->oldid = 0;
1637   sq->turn = g_cond_new ();
1639   sq->sinktime = GST_CLOCK_TIME_NONE;
1640   sq->srctime = GST_CLOCK_TIME_NONE;
1641   sq->sink_tainted = TRUE;
1642   sq->src_tainted = TRUE;
1644   tmp = g_strdup_printf ("sink%d", sq->id);
1645   sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, tmp);
1646   g_free (tmp);
1648   gst_pad_set_chain_function (sq->sinkpad,
1649       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
1650   gst_pad_set_activatepush_function (sq->sinkpad,
1651       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_push));
1652   gst_pad_set_event_function (sq->sinkpad,
1653       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
1654   gst_pad_set_getcaps_function (sq->sinkpad,
1655       GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps));
1656   gst_pad_set_bufferalloc_function (sq->sinkpad,
1657       GST_DEBUG_FUNCPTR (gst_multi_queue_bufferalloc));
1658   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
1659       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
1661   tmp = g_strdup_printf ("src%d", sq->id);
1662   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, tmp);
1663   g_free (tmp);
1665   gst_pad_set_activatepush_function (sq->srcpad,
1666       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_push));
1667   gst_pad_set_getcaps_function (sq->srcpad,
1668       GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps));
1669   gst_pad_set_event_function (sq->srcpad,
1670       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
1671   gst_pad_set_query_function (sq->srcpad,
1672       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
1673   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
1674       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
1676   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
1677   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
1679   /* only activate the pads when we are not in the NULL state
1680    * and add the pad under the state_lock to prevend state changes
1681    * between activating and adding */
1682   g_static_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
1683   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
1684     gst_pad_set_active (sq->srcpad, TRUE);
1685     gst_pad_set_active (sq->sinkpad, TRUE);
1686   }
1687   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
1688   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
1689   g_static_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
1691   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
1692       sq->id);
1694   return sq;