]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - glsdk/gstreamer0-10.git/blob - plugins/elements/gstmultiqueue.c
multiqueue: Increment unique item counter with atomic operations
[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  * 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., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
25 /**
26  * SECTION:element-multiqueue
27  * @see_also: #GstQueue
28  *
29  * <refsect2>
30  * <para>
31  * Multiqueue is similar to a normal #GstQueue with the following additional
32  * features:
33  * <orderedlist>
34  * <listitem>
35  *   <itemizedlist><title>Multiple streamhandling</title>
36  *   <listitem><para>
37  *     The element handles queueing data on more than one stream at once. To
38  *     achieve such a feature it has request sink pads (sink&percnt;d) and
39  *     'sometimes' src pads (src&percnt;d).
40  *   </para><para>
41  *     When requesting a given sinkpad with gst_element_get_request_pad(),
42  *     the associated srcpad for that stream will be created.
43  *     Example: requesting sink1 will generate src1.
44  *   </para></listitem>
45  *   </itemizedlist>
46  * </listitem>
47  * <listitem>
48  *   <itemizedlist><title>Non-starvation on multiple streams</title>
49  *   <listitem><para>
50  *     If more than one stream is used with the element, the streams' queues
51  *     will be dynamically grown (up to a limit), in order to ensure that no
52  *     stream is risking data starvation. This guarantees that at any given
53  *     time there are at least N bytes queued and available for each individual
54  *     stream.
55  *   </para><para>
56  *     If an EOS event comes through a srcpad, the associated queue will be
57  *     considered as 'not-empty' in the queue-size-growing algorithm.
58  *   </para></listitem>
59  *   </itemizedlist>
60  * </listitem>
61  * <listitem>
62  *   <itemizedlist><title>Non-linked srcpads graceful handling</title>
63  *   <listitem><para>
64  *     In order to better support dynamic switching between streams, the multiqueue
65  *     (unlike the current GStreamer queue) continues to push buffers on non-linked
66  *     pads rather than shutting down.
67  *   </para><para>
68  *     In addition, to prevent a non-linked stream from very quickly consuming all
69  *     available buffers and thus 'racing ahead' of the other streams, the element
70  *     must ensure that buffers and inlined events for a non-linked stream are pushed
71  *     in the same order as they were received, relative to the other streams
72  *     controlled by the element. This means that a buffer cannot be pushed to a
73  *     non-linked pad any sooner than buffers in any other stream which were received
74  *     before it.
75  *   </para></listitem>
76  *   </itemizedlist>
77  * </listitem>
78  * </orderedlist>
79  * </para>
80  * <para>
81  *   Data is queued until one of the limits specified by the
82  *   #GstMultiQueue:max-size-buffers, #GstMultiQueue:max-size-bytes and/or
83  *   #GstMultiQueue:max-size-time properties has been reached. Any attempt to push
84  *   more buffers into the queue will block the pushing thread until more space
85  *   becomes available. #GstMultiQueue:extra-size-buffers,
86  * </para>
87  * <para>
88  *   #GstMultiQueue:extra-size-bytes and #GstMultiQueue:extra-size-time are
89  *   currently unused.
90  * </para>
91  * <para>
92  *   The default queue size limits are 5 buffers, 10MB of data, or
93  *   two second worth of data, whichever is reached first. Note that the number
94  *   of buffers will dynamically grow depending on the fill level of 
95  *   other queues.
96  * </para>
97  * <para>
98  *   The #GstMultiQueue::underrun signal is emitted when all of the queues
99  *   are empty. The #GstMultiQueue::overrun signal is emitted when one of the
100  *   queues is filled.
101  *   Both signals are emitted from the context of the streaming thread.
102  * </para>
103  * </refsect2>
104  *
105  * Last reviewed on 2008-01-25 (0.10.17)
106  */
108 #ifdef HAVE_CONFIG_H
109 #  include "config.h"
110 #endif
112 #include <gst/gst.h>
113 #include "gstmultiqueue.h"
115 /**
116  * GstSingleQueue:
117  * @sinkpad: associated sink #GstPad
118  * @srcpad: associated source #GstPad
119  *
120  * Structure containing all information and properties about
121  * a single queue.
122  */
123 typedef struct _GstSingleQueue GstSingleQueue;
125 struct _GstSingleQueue
127   /* unique identifier of the queue */
128   guint id;
130   GstMultiQueue *mqueue;
132   GstPad *sinkpad;
133   GstPad *srcpad;
135   /* flowreturn of previous srcpad push */
136   GstFlowReturn srcresult;
138   /* segments */
139   GstSegment sink_segment;
140   GstSegment src_segment;
142   /* position of src/sink */
143   GstClockTime sinktime, srctime;
144   /* TRUE if either position needs to be recalculated */
145   gboolean sink_tainted, src_tainted;
147   /* queue of data */
148   GstDataQueue *queue;
149   GstDataQueueSize max_size, extra_size;
150   GstClockTime cur_time;
151   gboolean is_eos;
152   gboolean flushing;
154   /* Protected by global lock */
155   guint32 nextid;               /* ID of the next object waiting to be pushed */
156   guint32 oldid;                /* ID of the last object pushed (last in a series) */
157   guint32 last_oldid;           /* Previously observed old_id, reset to MAXUINT32 on flush */
158   GCond *turn;                  /* SingleQueue turn waiting conditional */
159 };
162 /* Extension of GstDataQueueItem structure for our usage */
163 typedef struct _GstMultiQueueItem GstMultiQueueItem;
165 struct _GstMultiQueueItem
167   GstMiniObject *object;
168   guint size;
169   guint64 duration;
170   gboolean visible;
172   GDestroyNotify destroy;
173   guint32 posid;
174 };
176 static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue);
177 static void gst_single_queue_free (GstSingleQueue * squeue);
179 static void wake_up_next_non_linked (GstMultiQueue * mq);
180 static void compute_high_id (GstMultiQueue * mq);
181 static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
182 static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq);
184 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink%d",
185     GST_PAD_SINK,
186     GST_PAD_REQUEST,
187     GST_STATIC_CAPS_ANY);
189 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src%d",
190     GST_PAD_SRC,
191     GST_PAD_SOMETIMES,
192     GST_STATIC_CAPS_ANY);
194 GST_DEBUG_CATEGORY_STATIC (multi_queue_debug);
195 #define GST_CAT_DEFAULT (multi_queue_debug)
197 /* Signals and args */
198 enum
200   SIGNAL_UNDERRUN,
201   SIGNAL_OVERRUN,
202   LAST_SIGNAL
203 };
205 /* default limits, we try to keep up to 2 seconds of data and if there is not
206  * time, up to 10 MB. The number of buffers is dynamically scaled to make sure
207  * there is data in the queues. Normally, the byte and time limits are not hit
208  * in theses conditions. */
209 #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */
210 #define DEFAULT_MAX_SIZE_BUFFERS 5
211 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND
213 /* second limits. When we hit one of the above limits we are probably dealing
214  * with a badly muxed file and we scale the limits to these emergency values.
215  * This is currently not yet implemented.
216  * Since we dynamically scale the queue buffer size up to the limits but avoid
217  * going above the max-size-buffers when we can, we don't really need this
218  * aditional extra size. */
219 #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024       /* 10 MB */
220 #define DEFAULT_EXTRA_SIZE_BUFFERS 5
221 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND
223 #define DEFAULT_USE_BUFFERING FALSE
224 #define DEFAULT_LOW_PERCENT   10
225 #define DEFAULT_HIGH_PERCENT  99
227 enum
229   PROP_0,
230   PROP_EXTRA_SIZE_BYTES,
231   PROP_EXTRA_SIZE_BUFFERS,
232   PROP_EXTRA_SIZE_TIME,
233   PROP_MAX_SIZE_BYTES,
234   PROP_MAX_SIZE_BUFFERS,
235   PROP_MAX_SIZE_TIME,
236   PROP_USE_BUFFERING,
237   PROP_LOW_PERCENT,
238   PROP_HIGH_PERCENT,
239   PROP_LAST
240 };
242 #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
243   g_mutex_lock (q->qlock);                                              \
244 } G_STMT_END
246 #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
247   g_mutex_unlock (q->qlock);                                            \
248 } G_STMT_END
250 static void gst_multi_queue_finalize (GObject * object);
251 static void gst_multi_queue_set_property (GObject * object,
252     guint prop_id, const GValue * value, GParamSpec * pspec);
253 static void gst_multi_queue_get_property (GObject * object,
254     guint prop_id, GValue * value, GParamSpec * pspec);
256 static GstPad *gst_multi_queue_request_new_pad (GstElement * element,
257     GstPadTemplate * temp, const gchar * name);
258 static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad);
259 static GstStateChangeReturn gst_multi_queue_change_state (GstElement *
260     element, GstStateChange transition);
262 static void gst_multi_queue_loop (GstPad * pad);
264 #define _do_init(bla) \
265   GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element");
267 GST_BOILERPLATE_FULL (GstMultiQueue, gst_multi_queue, GstElement,
268     GST_TYPE_ELEMENT, _do_init);
270 static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 };
272 static void
273 gst_multi_queue_base_init (gpointer g_class)
275   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
277   gst_element_class_set_details_simple (gstelement_class,
278       "MultiQueue",
279       "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>");
280   gst_element_class_add_pad_template (gstelement_class,
281       gst_static_pad_template_get (&sinktemplate));
282   gst_element_class_add_pad_template (gstelement_class,
283       gst_static_pad_template_get (&srctemplate));
286 static void
287 gst_multi_queue_class_init (GstMultiQueueClass * klass)
289   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
290   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
292   gobject_class->set_property = gst_multi_queue_set_property;
293   gobject_class->get_property = gst_multi_queue_get_property;
295   /* SIGNALS */
297   /**
298    * GstMultiQueue::underrun:
299    * @multiqueue: the multqueue instance
300    *
301    * This signal is emitted from the streaming thread when there is
302    * no data in any of the queues inside the multiqueue instance (underrun).
303    *
304    * This indicates either starvation or EOS from the upstream data sources.
305    */
306   gst_multi_queue_signals[SIGNAL_UNDERRUN] =
307       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
308       G_STRUCT_OFFSET (GstMultiQueueClass, underrun), NULL, NULL,
309       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
311   /**
312    * GstMultiQueue::overrun:
313    * @multiqueue: the multiqueue instance
314    *
315    * Reports that one of the queues in the multiqueue is full (overrun).
316    * A queue is full if the total amount of data inside it (num-buffers, time,
317    * size) is higher than the boundary values which can be set through the
318    * GObject properties.
319    *
320    * This can be used as an indicator of pre-roll. 
321    */
322   gst_multi_queue_signals[SIGNAL_OVERRUN] =
323       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
324       G_STRUCT_OFFSET (GstMultiQueueClass, overrun), NULL, NULL,
325       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
327   /* PROPERTIES */
329   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
330       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
331           "Max. amount of data in the queue (bytes, 0=disable)",
332           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
333           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
334   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
335       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
336           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
337           DEFAULT_MAX_SIZE_BUFFERS,
338           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
339   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
340       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
341           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
342           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BYTES,
345       g_param_spec_uint ("extra-size-bytes", "Extra Size (kB)",
346           "Amount of data the queues can grow if one of them is empty (bytes, 0=disable)"
347           " (NOT IMPLEMENTED)",
348           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BYTES,
349           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
350   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BUFFERS,
351       g_param_spec_uint ("extra-size-buffers", "Extra Size (buffers)",
352           "Amount of buffers the queues can grow if one of them is empty (0=disable)"
353           " (NOT IMPLEMENTED)",
354           0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BUFFERS,
355           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
356   g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_TIME,
357       g_param_spec_uint64 ("extra-size-time", "Extra Size (ns)",
358           "Amount of time the queues can grow if one of them is empty (in ns, 0=disable)"
359           " (NOT IMPLEMENTED)",
360           0, G_MAXUINT64, DEFAULT_EXTRA_SIZE_TIME,
361           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
363   /**
364    * GstMultiQueue:use-buffering
365    * 
366    * Enable the buffering option in multiqueue so that BUFFERING messages are
367    * emited based on low-/high-percent thresholds.
368    *
369    * Since: 0.10.26
370    */
371   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
372       g_param_spec_boolean ("use-buffering", "Use buffering",
373           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
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    * Since: 0.10.26
381    */
382   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
383       g_param_spec_int ("low-percent", "Low percent",
384           "Low threshold for buffering to start", 0, 100,
385           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
386   /**
387    * GstMultiQueue:high-percent
388    * 
389    * High threshold percent for buffering to finish.
390    *
391    * Since: 0.10.26
392    */
393   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
394       g_param_spec_int ("high-percent", "High percent",
395           "High threshold for buffering to finish", 0, 100,
396           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
399   gobject_class->finalize = gst_multi_queue_finalize;
401   gstelement_class->request_new_pad =
402       GST_DEBUG_FUNCPTR (gst_multi_queue_request_new_pad);
403   gstelement_class->release_pad =
404       GST_DEBUG_FUNCPTR (gst_multi_queue_release_pad);
405   gstelement_class->change_state =
406       GST_DEBUG_FUNCPTR (gst_multi_queue_change_state);
409 static void
410 gst_multi_queue_init (GstMultiQueue * mqueue, GstMultiQueueClass * klass)
412   mqueue->nbqueues = 0;
413   mqueue->queues = NULL;
415   mqueue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
416   mqueue->max_size.visible = DEFAULT_MAX_SIZE_BUFFERS;
417   mqueue->max_size.time = DEFAULT_MAX_SIZE_TIME;
419   mqueue->extra_size.bytes = DEFAULT_EXTRA_SIZE_BYTES;
420   mqueue->extra_size.visible = DEFAULT_EXTRA_SIZE_BUFFERS;
421   mqueue->extra_size.time = DEFAULT_EXTRA_SIZE_TIME;
423   mqueue->use_buffering = DEFAULT_USE_BUFFERING;
424   mqueue->low_percent = DEFAULT_LOW_PERCENT;
425   mqueue->high_percent = DEFAULT_HIGH_PERCENT;
427   mqueue->counter = 1;
428   mqueue->highid = -1;
430   mqueue->qlock = g_mutex_new ();
433 static void
434 gst_multi_queue_finalize (GObject * object)
436   GstMultiQueue *mqueue = GST_MULTI_QUEUE (object);
438   g_list_foreach (mqueue->queues, (GFunc) gst_single_queue_free, NULL);
439   g_list_free (mqueue->queues);
440   mqueue->queues = NULL;
441   mqueue->queues_cookie++;
443   /* free/unref instance data */
444   g_mutex_free (mqueue->qlock);
446   G_OBJECT_CLASS (parent_class)->finalize (object);
449 #define SET_CHILD_PROPERTY(mq,format) G_STMT_START {            \
450     GList * tmp = mq->queues;                                   \
451     while (tmp) {                                               \
452       GstSingleQueue *q = (GstSingleQueue*)tmp->data;           \
453       q->max_size.format = mq->max_size.format;                 \
454       tmp = g_list_next(tmp);                                   \
455     };                                                          \
456 } G_STMT_END
458 static void
459 gst_multi_queue_set_property (GObject * object, guint prop_id,
460     const GValue * value, GParamSpec * pspec)
462   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
464   switch (prop_id) {
465     case PROP_MAX_SIZE_BYTES:
466       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
467       mq->max_size.bytes = g_value_get_uint (value);
468       SET_CHILD_PROPERTY (mq, bytes);
469       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
470       break;
471     case PROP_MAX_SIZE_BUFFERS:
472       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
473       mq->max_size.visible = g_value_get_uint (value);
474       SET_CHILD_PROPERTY (mq, visible);
475       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
476       break;
477     case PROP_MAX_SIZE_TIME:
478       GST_MULTI_QUEUE_MUTEX_LOCK (mq);
479       mq->max_size.time = g_value_get_uint64 (value);
480       SET_CHILD_PROPERTY (mq, time);
481       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
482       break;
483     case PROP_EXTRA_SIZE_BYTES:
484       mq->extra_size.bytes = g_value_get_uint (value);
485       break;
486     case PROP_EXTRA_SIZE_BUFFERS:
487       mq->extra_size.visible = g_value_get_uint (value);
488       break;
489     case PROP_EXTRA_SIZE_TIME:
490       mq->extra_size.time = g_value_get_uint64 (value);
491       break;
492     case PROP_USE_BUFFERING:
493       mq->use_buffering = g_value_get_boolean (value);
494       break;
495     case PROP_LOW_PERCENT:
496       mq->low_percent = g_value_get_int (value);
497       break;
498     case PROP_HIGH_PERCENT:
499       mq->high_percent = g_value_get_int (value);
500       break;
501     default:
502       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
503       break;
504   }
507 static void
508 gst_multi_queue_get_property (GObject * object, guint prop_id,
509     GValue * value, GParamSpec * pspec)
511   GstMultiQueue *mq = GST_MULTI_QUEUE (object);
513   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
515   switch (prop_id) {
516     case PROP_EXTRA_SIZE_BYTES:
517       g_value_set_uint (value, mq->extra_size.bytes);
518       break;
519     case PROP_EXTRA_SIZE_BUFFERS:
520       g_value_set_uint (value, mq->extra_size.visible);
521       break;
522     case PROP_EXTRA_SIZE_TIME:
523       g_value_set_uint64 (value, mq->extra_size.time);
524       break;
525     case PROP_MAX_SIZE_BYTES:
526       g_value_set_uint (value, mq->max_size.bytes);
527       break;
528     case PROP_MAX_SIZE_BUFFERS:
529       g_value_set_uint (value, mq->max_size.visible);
530       break;
531     case PROP_MAX_SIZE_TIME:
532       g_value_set_uint64 (value, mq->max_size.time);
533       break;
534     case PROP_USE_BUFFERING:
535       g_value_set_boolean (value, mq->use_buffering);
536       break;
537     case PROP_LOW_PERCENT:
538       g_value_set_int (value, mq->low_percent);
539       break;
540     case PROP_HIGH_PERCENT:
541       g_value_set_int (value, mq->high_percent);
542       break;
543     default:
544       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
545       break;
546   }
548   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
551 static GstIterator *
552 gst_multi_queue_iterate_internal_links (GstPad * pad)
554   GstIterator *it = NULL;
555   GstPad *opad;
556   GstSingleQueue *squeue;
557   GstMultiQueue *mq = GST_MULTI_QUEUE (gst_pad_get_parent (pad));
559   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
560   squeue = gst_pad_get_element_private (pad);
561   if (!squeue)
562     goto out;
564   if (squeue->sinkpad == pad)
565     opad = gst_object_ref (squeue->srcpad);
566   else if (squeue->srcpad == pad)
567     opad = gst_object_ref (squeue->sinkpad);
568   else
569     goto out;
571   it = gst_iterator_new_single (GST_TYPE_PAD, opad,
572       (GstCopyFunction) gst_object_ref, (GFreeFunc) gst_object_unref);
574   gst_object_unref (opad);
576 out:
577   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
578   gst_object_unref (mq);
580   return it;
584 /*
585  * GstElement methods
586  */
588 static GstPad *
589 gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp,
590     const gchar * name)
592   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
593   GstSingleQueue *squeue;
595   GST_LOG_OBJECT (element, "name : %s", GST_STR_NULL (name));
597   /* Create a new single queue, add the sink and source pad and return the sink pad */
598   squeue = gst_single_queue_new (mqueue);
600   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
601   mqueue->queues = g_list_append (mqueue->queues, squeue);
602   mqueue->queues_cookie++;
603   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
605   GST_DEBUG_OBJECT (mqueue, "Returning pad %s:%s",
606       GST_DEBUG_PAD_NAME (squeue->sinkpad));
608   return squeue->sinkpad;
611 static void
612 gst_multi_queue_release_pad (GstElement * element, GstPad * pad)
614   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
615   GstSingleQueue *sq = NULL;
616   GList *tmp;
618   GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
620   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
621   /* Find which single queue it belongs to, knowing that it should be a sinkpad */
622   for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
623     sq = (GstSingleQueue *) tmp->data;
625     if (sq->sinkpad == pad)
626       break;
627   }
629   if (!tmp) {
630     GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???");
631     GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
632     return;
633   }
635   /* FIXME: The removal of the singlequeue should probably not happen until it
636    * finishes draining */
638   /* remove it from the list */
639   mqueue->queues = g_list_delete_link (mqueue->queues, tmp);
640   mqueue->queues_cookie++;
642   /* FIXME : recompute next-non-linked */
643   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
645   /* delete SingleQueue */
646   gst_data_queue_set_flushing (sq->queue, TRUE);
648   gst_pad_set_active (sq->srcpad, FALSE);
649   gst_pad_set_active (sq->sinkpad, FALSE);
650   gst_pad_set_element_private (sq->srcpad, NULL);
651   gst_pad_set_element_private (sq->sinkpad, NULL);
652   gst_element_remove_pad (element, sq->srcpad);
653   gst_element_remove_pad (element, sq->sinkpad);
654   gst_single_queue_free (sq);
657 static GstStateChangeReturn
658 gst_multi_queue_change_state (GstElement * element, GstStateChange transition)
660   GstMultiQueue *mqueue = GST_MULTI_QUEUE (element);
661   GstSingleQueue *sq = NULL;
662   GstStateChangeReturn result;
664   switch (transition) {
665     case GST_STATE_CHANGE_READY_TO_PAUSED:{
666       GList *tmp;
668       /* Set all pads to non-flushing */
669       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
670       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
671         sq = (GstSingleQueue *) tmp->data;
672         sq->flushing = FALSE;
673       }
674       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
675       break;
676     }
677     case GST_STATE_CHANGE_PAUSED_TO_READY:{
678       GList *tmp;
680       /* Un-wait all waiting pads */
681       GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
682       for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) {
683         sq = (GstSingleQueue *) tmp->data;
684         sq->flushing = TRUE;
685         g_cond_signal (sq->turn);
686       }
687       GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
688       break;
689     }
690     default:
691       break;
692   }
694   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
696   switch (transition) {
697     default:
698       break;
699   }
701   return result;
707 static gboolean
708 gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush)
710   gboolean result;
712   GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"),
713       sq->id);
715   if (flush) {
716     sq->srcresult = GST_FLOW_WRONG_STATE;
717     gst_data_queue_set_flushing (sq->queue, TRUE);
719     sq->flushing = TRUE;
721     /* wake up non-linked task */
722     GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task",
723         sq->id);
724     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
725     g_cond_signal (sq->turn);
726     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
728     GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id);
729     result = gst_pad_pause_task (sq->srcpad);
730     sq->sink_tainted = sq->src_tainted = TRUE;
731   } else {
732     gst_data_queue_flush (sq->queue);
733     gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
734     gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
735     /* All pads start off not-linked for a smooth kick-off */
736     sq->srcresult = GST_FLOW_OK;
737     sq->cur_time = 0;
738     sq->max_size.visible = mq->max_size.visible;
739     sq->is_eos = FALSE;
740     sq->nextid = 0;
741     sq->oldid = 0;
742     sq->last_oldid = G_MAXUINT32;
743     gst_data_queue_set_flushing (sq->queue, FALSE);
745     sq->flushing = FALSE;
747     GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id);
748     result =
749         gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop,
750         sq->srcpad);
751   }
752   return result;
755 static void
756 update_buffering (GstMultiQueue * mq, GstSingleQueue * sq)
758   GstDataQueueSize size;
759   gint percent, tmp;
760   gboolean post = FALSE;
762   /* nothing to dowhen we are not in buffering mode */
763   if (!mq->use_buffering)
764     return;
766   gst_data_queue_get_level (sq->queue, &size);
768   GST_DEBUG_OBJECT (mq,
769       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
770       G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible,
771       size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time);
773   /* get bytes and time percentages and take the max */
774   if (sq->is_eos) {
775     percent = 100;
776   } else {
777     percent = 0;
778     if (sq->max_size.time > 0) {
779       tmp = (sq->cur_time * 100) / sq->max_size.time;
780       percent = MAX (percent, tmp);
781     }
782     if (sq->max_size.bytes > 0) {
783       tmp = (size.bytes * 100) / sq->max_size.bytes;
784       percent = MAX (percent, tmp);
785     }
786   }
788   if (mq->buffering) {
789     post = TRUE;
790     if (percent >= mq->high_percent) {
791       mq->buffering = FALSE;
792     }
793     /* make sure it increases */
794     percent = MAX (mq->percent, percent);
796     if (percent == mq->percent)
797       /* don't post if nothing changed */
798       post = FALSE;
799     else
800       /* else keep last value we posted */
801       mq->percent = percent;
802   } else {
803     if (percent < mq->low_percent) {
804       mq->buffering = TRUE;
805       mq->percent = percent;
806       post = TRUE;
807     }
808   }
809   if (post) {
810     GstMessage *message;
812     /* scale to high percent so that it becomes the 100% mark */
813     percent = percent * 100 / mq->high_percent;
814     /* clip */
815     if (percent > 100)
816       percent = 100;
818     GST_DEBUG_OBJECT (mq, "buffering %d percent", percent);
819     message = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent);
821     gst_element_post_message (GST_ELEMENT_CAST (mq), message);
822   } else {
823     GST_DEBUG_OBJECT (mq, "filled %d percent", percent);
824   }
827 /* calculate the diff between running time on the sink and src of the queue.
828  * This is the total amount of time in the queue. 
829  * WITH LOCK TAKEN */
830 static void
831 update_time_level (GstMultiQueue * mq, GstSingleQueue * sq)
833   gint64 sink_time, src_time;
835   if (sq->sink_tainted) {
836     sink_time = sq->sinktime =
837         gst_segment_to_running_time (&sq->sink_segment, GST_FORMAT_TIME,
838         sq->sink_segment.last_stop);
840     if (G_UNLIKELY (sink_time != GST_CLOCK_TIME_NONE))
841       /* if we have a time, we become untainted and use the time */
842       sq->sink_tainted = FALSE;
843   } else
844     sink_time = sq->sinktime;
846   if (sq->src_tainted) {
847     src_time = sq->srctime =
848         gst_segment_to_running_time (&sq->src_segment, GST_FORMAT_TIME,
849         sq->src_segment.last_stop);
850     /* if we have a time, we become untainted and use the time */
851     if (G_UNLIKELY (src_time != GST_CLOCK_TIME_NONE))
852       sq->src_tainted = FALSE;
853   } else
854     src_time = sq->srctime;
856   GST_DEBUG_OBJECT (mq,
857       "queue %d, sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT, sq->id,
858       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
860   /* This allows for streams with out of order timestamping - sometimes the
861    * emerging timestamp is later than the arriving one(s) */
862   if (G_LIKELY (sink_time != -1 && src_time != -1 && sink_time > src_time))
863     sq->cur_time = sink_time - src_time;
864   else
865     sq->cur_time = 0;
867   /* updating the time level can change the buffering state */
868   update_buffering (mq, sq);
870   return;
873 /* take a NEWSEGMENT event and apply the values to segment, updating the time
874  * level of queue. */
875 static void
876 apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event,
877     GstSegment * segment)
879   gboolean update;
880   GstFormat format;
881   gdouble rate, arate;
882   gint64 start, stop, time;
884   gst_event_parse_new_segment_full (event, &update, &rate, &arate,
885       &format, &start, &stop, &time);
887   /* now configure the values, we use these to track timestamps on the
888    * sinkpad. */
889   if (format != GST_FORMAT_TIME) {
890     /* non-time format, pretent the current time segment is closed with a
891      * 0 start and unknown stop time. */
892     update = FALSE;
893     format = GST_FORMAT_TIME;
894     start = 0;
895     stop = -1;
896     time = 0;
897   }
899   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
901   gst_segment_set_newsegment_full (segment, update,
902       rate, arate, format, start, stop, time);
904   if (segment == &sq->sink_segment)
905     sq->sink_tainted = TRUE;
906   else
907     sq->src_tainted = TRUE;
909   GST_DEBUG_OBJECT (mq,
910       "queue %d, configured NEWSEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment);
912   /* segment can update the time level of the queue */
913   update_time_level (mq, sq);
915   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
918 /* take a buffer and update segment, updating the time level of the queue. */
919 static void
920 apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp,
921     GstClockTime duration, GstSegment * segment)
923   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
925   /* if no timestamp is set, assume it's continuous with the previous 
926    * time */
927   if (timestamp == GST_CLOCK_TIME_NONE)
928     timestamp = segment->last_stop;
930   /* add duration */
931   if (duration != GST_CLOCK_TIME_NONE)
932     timestamp += duration;
934   GST_DEBUG_OBJECT (mq, "queue %d, last_stop updated to %" GST_TIME_FORMAT,
935       sq->id, GST_TIME_ARGS (timestamp));
937   gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
939   if (segment == &sq->sink_segment)
940     sq->sink_tainted = TRUE;
941   else
942     sq->src_tainted = TRUE;
944   /* calc diff with other end */
945   update_time_level (mq, sq);
946   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
949 static GstFlowReturn
950 gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq,
951     GstMiniObject * object)
953   GstFlowReturn result = GST_FLOW_OK;
955   if (GST_IS_BUFFER (object)) {
956     GstBuffer *buffer;
957     GstClockTime timestamp, duration;
958     GstCaps *caps;
960     buffer = GST_BUFFER_CAST (object);
961     timestamp = GST_BUFFER_TIMESTAMP (buffer);
962     duration = GST_BUFFER_DURATION (buffer);
963     caps = GST_BUFFER_CAPS (buffer);
965     apply_buffer (mq, sq, timestamp, duration, &sq->src_segment);
967     /* Applying the buffer may have made the queue non-full again, unblock it if needed */
968     gst_data_queue_limits_changed (sq->queue);
970     GST_DEBUG_OBJECT (mq,
971         "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT,
972         sq->id, buffer, GST_TIME_ARGS (timestamp));
974     /* Set caps on pad before pushing, this avoids core calling the acceptcaps
975      * function on the srcpad, which will call acceptcaps upstream, which might
976      * not accept these caps (anymore). */
977     if (caps && caps != GST_PAD_CAPS (sq->srcpad))
978       gst_pad_set_caps (sq->srcpad, caps);
980     result = gst_pad_push (sq->srcpad, buffer);
981   } else if (GST_IS_EVENT (object)) {
982     GstEvent *event;
984     event = GST_EVENT_CAST (object);
986     switch (GST_EVENT_TYPE (event)) {
987       case GST_EVENT_EOS:
988         result = GST_FLOW_UNEXPECTED;
989         break;
990       case GST_EVENT_NEWSEGMENT:
991         apply_segment (mq, sq, event, &sq->src_segment);
992         /* Applying the segment may have made the queue non-full again, unblock it if needed */
993         gst_data_queue_limits_changed (sq->queue);
994         break;
995       default:
996         break;
997     }
999     GST_DEBUG_OBJECT (mq,
1000         "SingleQueue %d : Pushing event %p of type %s",
1001         sq->id, event, GST_EVENT_TYPE_NAME (event));
1003     gst_pad_push_event (sq->srcpad, event);
1004   } else {
1005     g_warning ("Unexpected object in singlequeue %d (refcounting problem?)",
1006         sq->id);
1007   }
1008   return result;
1010   /* ERRORS */
1013 static GstMiniObject *
1014 gst_multi_queue_item_steal_object (GstMultiQueueItem * item)
1016   GstMiniObject *res;
1018   res = item->object;
1019   item->object = NULL;
1021   return res;
1024 static void
1025 gst_multi_queue_item_destroy (GstMultiQueueItem * item)
1027   if (item->object)
1028     gst_mini_object_unref (item->object);
1029   g_slice_free (GstMultiQueueItem, item);
1032 /* takes ownership of passed mini object! */
1033 static GstMultiQueueItem *
1034 gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid)
1036   GstMultiQueueItem *item;
1038   item = g_slice_new (GstMultiQueueItem);
1039   item->object = object;
1040   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1041   item->posid = curid;
1043   item->size = GST_BUFFER_SIZE (object);
1044   item->duration = GST_BUFFER_DURATION (object);
1045   if (item->duration == GST_CLOCK_TIME_NONE)
1046     item->duration = 0;
1047   item->visible = TRUE;
1048   return item;
1051 static GstMultiQueueItem *
1052 gst_multi_queue_event_item_new (GstMiniObject * object, guint32 curid)
1054   GstMultiQueueItem *item;
1056   item = g_slice_new (GstMultiQueueItem);
1057   item->object = object;
1058   item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy;
1059   item->posid = curid;
1061   item->size = 0;
1062   item->duration = 0;
1063   item->visible = FALSE;
1064   return item;
1067 /* Each main loop attempts to push buffers until the return value
1068  * is not-linked. not-linked pads are not allowed to push data beyond
1069  * any linked pads, so they don't 'rush ahead of the pack'.
1070  */
1071 static void
1072 gst_multi_queue_loop (GstPad * pad)
1074   GstSingleQueue *sq;
1075   GstMultiQueueItem *item;
1076   GstDataQueueItem *sitem;
1077   GstMultiQueue *mq;
1078   GstMiniObject *object;
1079   guint32 newid;
1080   GstFlowReturn result;
1082   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1083   mq = sq->mqueue;
1085   GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id);
1087   if (sq->flushing)
1088     goto out_flushing;
1090   /* Get something from the queue, blocking until that happens, or we get
1091    * flushed */
1092   if (!(gst_data_queue_pop (sq->queue, &sitem)))
1093     goto out_flushing;
1095   item = (GstMultiQueueItem *) sitem;
1096   newid = item->posid;
1098   /* steal the object and destroy the item */
1099   object = gst_multi_queue_item_steal_object (item);
1100   gst_multi_queue_item_destroy (item);
1102   GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d",
1103       sq->id, newid, sq->last_oldid);
1105   /* If we're not-linked, we do some extra work because we might need to
1106    * wait before pushing. If we're linked but there's a gap in the IDs,
1107    * or it's the first loop, or we just passed the previous highid, 
1108    * we might need to wake some sleeping pad up, so there's extra work 
1109    * there too */
1110   if (sq->srcresult == GST_FLOW_NOT_LINKED ||
1111       (sq->last_oldid == G_MAXUINT32) || (newid != (sq->last_oldid + 1)) ||
1112       sq->last_oldid > mq->highid) {
1113     GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s",
1114         gst_flow_get_name (sq->srcresult));
1116     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1118     /* Update the nextid so other threads know when to wake us up */
1119     sq->nextid = newid;
1121     /* Update the oldid (the last ID we output) for highid tracking */
1122     if (sq->last_oldid != G_MAXUINT32)
1123       sq->oldid = sq->last_oldid;
1125     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1126       /* Go to sleep until it's time to push this buffer */
1128       /* Recompute the highid */
1129       compute_high_id (mq);
1130       while (newid > mq->highid && sq->srcresult == GST_FLOW_NOT_LINKED) {
1131         GST_DEBUG_OBJECT (mq, "queue %d sleeping for not-linked wakeup with "
1132             "newid %u and highid %u", sq->id, newid, mq->highid);
1135         /* Wake up all non-linked pads before we sleep */
1136         wake_up_next_non_linked (mq);
1138         mq->numwaiting++;
1139         g_cond_wait (sq->turn, mq->qlock);
1140         mq->numwaiting--;
1142         if (sq->flushing) {
1143           GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1144           goto out_flushing;
1145         }
1147         GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked "
1148             "wakeup with newid %u and highid %u", sq->id, newid, mq->highid);
1149       }
1151       /* Re-compute the high_id in case someone else pushed */
1152       compute_high_id (mq);
1153     } else {
1154       compute_high_id (mq);
1155       /* Wake up all non-linked pads */
1156       wake_up_next_non_linked (mq);
1157     }
1158     /* We're done waiting, we can clear the nextid */
1159     sq->nextid = 0;
1161     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1162   }
1164   if (sq->flushing)
1165     goto out_flushing;
1167   GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s",
1168       gst_flow_get_name (sq->srcresult));
1170   /* Try to push out the new object */
1171   result = gst_single_queue_push_one (mq, sq, object);
1172   sq->srcresult = result;
1174   if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED
1175       && result != GST_FLOW_UNEXPECTED)
1176     goto out_flushing;
1178   GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s",
1179       gst_flow_get_name (sq->srcresult));
1181   sq->last_oldid = newid;
1182   return;
1184 out_flushing:
1185   {
1186     /* Need to make sure wake up any sleeping pads when we exit */
1187     GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1188     compute_high_id (mq);
1189     wake_up_next_non_linked (mq);
1190     GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1192     /* upstream needs to see fatal result ASAP to shut things down,
1193      * but might be stuck in one of our other full queues;
1194      * so empty this one and trigger dynamic queue growth. At
1195      * this point the srcresult is not OK, NOT_LINKED
1196      * or UNEXPECTED, i.e. a real failure */
1197     gst_data_queue_flush (sq->queue);
1198     single_queue_underrun_cb (sq->queue, sq);
1199     gst_data_queue_set_flushing (sq->queue, TRUE);
1200     gst_pad_pause_task (sq->srcpad);
1201     GST_CAT_LOG_OBJECT (multi_queue_debug, mq,
1202         "SingleQueue[%d] task paused, reason:%s",
1203         sq->id, gst_flow_get_name (sq->srcresult));
1204     return;
1205   }
1208 /**
1209  * gst_multi_queue_chain:
1210  *
1211  * This is similar to GstQueue's chain function, except:
1212  * _ we don't have leak behavioures,
1213  * _ we push with a unique id (curid)
1214  */
1215 static GstFlowReturn
1216 gst_multi_queue_chain (GstPad * pad, GstBuffer * buffer)
1218   GstSingleQueue *sq;
1219   GstMultiQueue *mq;
1220   GstMultiQueueItem *item;
1221   guint32 curid;
1222   GstClockTime timestamp, duration;
1224   sq = gst_pad_get_element_private (pad);
1225   mq = sq->mqueue;
1227   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1228   if (sq->is_eos)
1229     goto was_eos;
1231   /* Get a unique incrementing id */
1232   curid = g_atomic_int_exchange_and_add ((gint *) & mq->counter, 1);
1234   GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d",
1235       sq->id, buffer, curid);
1237   item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid);
1239   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1240   duration = GST_BUFFER_DURATION (buffer);
1242   if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1243     goto flushing;
1245   /* update time level, we must do this after pushing the data in the queue so
1246    * that we never end up filling the queue first. */
1247   apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment);
1249 done:
1250   return sq->srcresult;
1252   /* ERRORS */
1253 flushing:
1254   {
1255     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1256         sq->id, gst_flow_get_name (sq->srcresult));
1257     gst_multi_queue_item_destroy (item);
1258     goto done;
1259   }
1260 was_eos:
1261   {
1262     GST_DEBUG_OBJECT (mq, "we are EOS, dropping buffer, return UNEXPECTED");
1263     gst_buffer_unref (buffer);
1264     return GST_FLOW_UNEXPECTED;
1265   }
1268 static gboolean
1269 gst_multi_queue_sink_activate_push (GstPad * pad, gboolean active)
1271   GstSingleQueue *sq;
1273   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1275   if (active) {
1276     /* All pads start off linked until they push one buffer */
1277     sq->srcresult = GST_FLOW_OK;
1278   } else {
1279     sq->srcresult = GST_FLOW_WRONG_STATE;
1280     gst_data_queue_flush (sq->queue);
1281   }
1282   return TRUE;
1285 static gboolean
1286 gst_multi_queue_sink_event (GstPad * pad, GstEvent * event)
1288   GstSingleQueue *sq;
1289   GstMultiQueue *mq;
1290   guint32 curid;
1291   GstMultiQueueItem *item;
1292   gboolean res;
1293   GstEventType type;
1294   GstEvent *sref = NULL;
1296   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1297   mq = (GstMultiQueue *) gst_pad_get_parent (pad);
1299   type = GST_EVENT_TYPE (event);
1301   switch (type) {
1302     case GST_EVENT_FLUSH_START:
1303       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event",
1304           sq->id);
1306       res = gst_pad_push_event (sq->srcpad, event);
1308       gst_single_queue_flush (mq, sq, TRUE);
1309       goto done;
1311     case GST_EVENT_FLUSH_STOP:
1312       GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event",
1313           sq->id);
1315       res = gst_pad_push_event (sq->srcpad, event);
1317       gst_single_queue_flush (mq, sq, FALSE);
1318       goto done;
1319     case GST_EVENT_NEWSEGMENT:
1320       /* take ref because the queue will take ownership and we need the event
1321        * afterwards to update the segment */
1322       sref = gst_event_ref (event);
1323       break;
1325     default:
1326       if (!(GST_EVENT_IS_SERIALIZED (event))) {
1327         res = gst_pad_push_event (sq->srcpad, event);
1328         goto done;
1329       }
1330       break;
1331   }
1333   /* if eos, we are always full, so avoid hanging incoming indefinitely */
1334   if (sq->is_eos)
1335     goto was_eos;
1337   /* Get an unique incrementing id. */
1338   curid = g_atomic_int_exchange_and_add ((gint *) & mq->counter, 1);
1340   item = gst_multi_queue_event_item_new ((GstMiniObject *) event, curid);
1342   GST_DEBUG_OBJECT (mq,
1343       "SingleQueue %d : Enqueuing event %p of type %s with id %d",
1344       sq->id, event, GST_EVENT_TYPE_NAME (event), curid);
1346   if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item)))
1347     goto flushing;
1349   /* mark EOS when we received one, we must do that after putting the
1350    * buffer in the queue because EOS marks the buffer as filled. No need to take
1351    * a lock, the _check_full happens from this thread only, right before pushing
1352    * into dataqueue. */
1353   switch (type) {
1354     case GST_EVENT_EOS:
1355       sq->is_eos = TRUE;
1356       /* EOS affects the buffering state */
1357       update_buffering (mq, sq);
1358       single_queue_overrun_cb (sq->queue, sq);
1359       break;
1360     case GST_EVENT_NEWSEGMENT:
1361       apply_segment (mq, sq, sref, &sq->sink_segment);
1362       gst_event_unref (sref);
1363       break;
1364     default:
1365       break;
1366   }
1367 done:
1368   gst_object_unref (mq);
1369   return res;
1371 flushing:
1372   {
1373     GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s",
1374         sq->id, gst_flow_get_name (sq->srcresult));
1375     if (sref)
1376       gst_event_unref (sref);
1377     gst_multi_queue_item_destroy (item);
1378     goto done;
1379   }
1380 was_eos:
1381   {
1382     GST_DEBUG_OBJECT (mq, "we are EOS, dropping event, return FALSE");
1383     gst_event_unref (event);
1384     res = FALSE;
1385     goto done;
1386   }
1389 static GstCaps *
1390 gst_multi_queue_getcaps (GstPad * pad)
1392   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1393   GstPad *otherpad;
1394   GstCaps *result;
1396   otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad;
1398   GST_LOG_OBJECT (otherpad, "Getting caps from the peer of this pad");
1400   result = gst_pad_peer_get_caps (otherpad);
1401   if (result == NULL)
1402     result = gst_caps_new_any ();
1404   return result;
1407 static gboolean
1408 gst_multi_queue_acceptcaps (GstPad * pad, GstCaps * caps)
1410   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1411   GstPad *otherpad;
1412   gboolean result;
1414   otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad;
1416   GST_LOG_OBJECT (otherpad, "Accept caps from the peer of this pad");
1418   result = gst_pad_peer_accept_caps (otherpad, caps);
1420   return result;
1423 static GstFlowReturn
1424 gst_multi_queue_bufferalloc (GstPad * pad, guint64 offset, guint size,
1425     GstCaps * caps, GstBuffer ** buf)
1427   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1429   return gst_pad_alloc_buffer (sq->srcpad, offset, size, caps, buf);
1432 static gboolean
1433 gst_multi_queue_src_activate_push (GstPad * pad, gboolean active)
1435   GstMultiQueue *mq;
1436   GstSingleQueue *sq;
1437   gboolean result = FALSE;
1439   sq = (GstSingleQueue *) gst_pad_get_element_private (pad);
1440   mq = sq->mqueue;
1442   GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id);
1444   if (active) {
1445     result = gst_single_queue_flush (mq, sq, FALSE);
1446   } else {
1447     result = gst_single_queue_flush (mq, sq, TRUE);
1448     /* make sure streaming finishes */
1449     result |= gst_pad_stop_task (pad);
1450   }
1451   return result;
1454 static gboolean
1455 gst_multi_queue_src_event (GstPad * pad, GstEvent * event)
1457   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1459   return gst_pad_push_event (sq->sinkpad, event);
1462 static gboolean
1463 gst_multi_queue_src_query (GstPad * pad, GstQuery * query)
1465   GstSingleQueue *sq = gst_pad_get_element_private (pad);
1466   GstPad *peerpad;
1467   gboolean res;
1469   /* FIXME, Handle position offset depending on queue size */
1471   /* default handling */
1472   if (!(peerpad = gst_pad_get_peer (sq->sinkpad)))
1473     goto no_peer;
1475   res = gst_pad_query (peerpad, query);
1477   gst_object_unref (peerpad);
1479   return res;
1481   /* ERRORS */
1482 no_peer:
1483   {
1484     GST_LOG_OBJECT (sq->sinkpad, "Couldn't send query because we have no peer");
1485     return FALSE;
1486   }
1489 /*
1490  * Next-non-linked functions
1491  */
1493 /* WITH LOCK TAKEN */
1494 static void
1495 wake_up_next_non_linked (GstMultiQueue * mq)
1497   GList *tmp;
1499   /* maybe no-one is waiting */
1500   if (mq->numwaiting < 1)
1501     return;
1503   /* Else figure out which singlequeue(s) need waking up */
1504   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1505     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1507     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1508       if (sq->nextid != 0 && sq->nextid <= mq->highid) {
1509         GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id);
1510         g_cond_signal (sq->turn);
1511       }
1512     }
1513   }
1516 /* WITH LOCK TAKEN */
1517 static void
1518 compute_high_id (GstMultiQueue * mq)
1520   /* The high-id is either the highest id among the linked pads, or if all
1521    * pads are not-linked, it's the lowest not-linked pad */
1522   GList *tmp;
1523   guint32 lowest = G_MAXUINT32;
1524   guint32 highid = G_MAXUINT32;
1526   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1527     GstSingleQueue *sq = (GstSingleQueue *) tmp->data;
1529     GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s",
1530         sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult));
1532     if (sq->srcresult == GST_FLOW_NOT_LINKED) {
1533       /* No need to consider queues which are not waiting */
1534       if (sq->nextid == 0) {
1535         GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id);
1536         continue;
1537       }
1539       if (sq->nextid < lowest)
1540         lowest = sq->nextid;
1541     } else if (sq->srcresult != GST_FLOW_UNEXPECTED) {
1542       /* If we don't have a global highid, or the global highid is lower than
1543        * this single queue's last outputted id, store the queue's one, 
1544        * unless the singlequeue is at EOS (srcresult = UNEXPECTED) */
1545       if ((highid == G_MAXUINT32) || (sq->oldid > highid))
1546         highid = sq->oldid;
1547     }
1548   }
1550   if (highid == G_MAXUINT32 || lowest < highid)
1551     mq->highid = lowest;
1552   else
1553     mq->highid = highid;
1555   GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid,
1556       lowest);
1559 #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \
1560      ((q)->max_size.format) <= (value))
1562 /*
1563  * GstSingleQueue functions
1564  */
1565 static void
1566 single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1568   GstMultiQueue *mq = sq->mqueue;
1569   GList *tmp;
1570   GstDataQueueSize size;
1571   gboolean filled = FALSE;
1573   gst_data_queue_get_level (sq->queue, &size);
1575   GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id);
1577   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1578   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1579     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1580     GstDataQueueSize ssize;
1582     GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id);
1584     if (gst_data_queue_is_empty (oq->queue)) {
1585       GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id);
1586       if (IS_FILLED (sq, visible, size.visible)) {
1587         sq->max_size.visible = size.visible + 1;
1588         GST_DEBUG_OBJECT (mq,
1589             "Another queue is empty, bumping single queue %d max visible to %d",
1590             sq->id, sq->max_size.visible);
1591       }
1592       GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1593       goto beach;
1594     }
1595     /* check if we reached the hard time/bytes limits */
1596     gst_data_queue_get_level (oq->queue, &ssize);
1598     GST_DEBUG_OBJECT (mq,
1599         "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1600         G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible,
1601         ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time);
1603     /* if this queue is filled completely we must signal overrun.
1604      * FIXME, this seems wrong in many ways
1605      *  - we're comparing the filled level of this queue against the
1606      *    values of the other one
1607      *  - we should only do this after we found no empty queues, ie, move
1608      *    this check outside of the loop
1609      *  - the debug statement talks about a different queue than the one
1610      *    we are checking here.
1611      */
1612     if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) ||
1613         IS_FILLED (sq, time, sq->cur_time)) {
1614       GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id);
1615       filled = TRUE;
1616     }
1617   }
1618   /* no queues were empty */
1619   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1621   /* Overrun is always forwarded, since this is blocking the upstream element */
1622   if (filled) {
1623     GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun");
1624     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0);
1625   }
1627 beach:
1628   return;
1631 static void
1632 single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq)
1634   gboolean empty = TRUE;
1635   GstMultiQueue *mq = sq->mqueue;
1636   GList *tmp;
1638   GST_LOG_OBJECT (mq,
1639       "Single Queue %d is empty, Checking other single queues", sq->id);
1641   GST_MULTI_QUEUE_MUTEX_LOCK (mq);
1642   for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) {
1643     GstSingleQueue *oq = (GstSingleQueue *) tmp->data;
1645     if (gst_data_queue_is_full (oq->queue)) {
1646       GstDataQueueSize size;
1648       gst_data_queue_get_level (oq->queue, &size);
1649       if (IS_FILLED (oq, visible, size.visible)) {
1650         oq->max_size.visible = size.visible + 1;
1651         GST_DEBUG_OBJECT (mq,
1652             "queue %d is filled, bumping its max visible to %d", oq->id,
1653             oq->max_size.visible);
1654         gst_data_queue_limits_changed (oq->queue);
1655       }
1656     }
1657     if (!gst_data_queue_is_empty (oq->queue))
1658       empty = FALSE;
1659   }
1660   GST_MULTI_QUEUE_MUTEX_UNLOCK (mq);
1662   if (empty) {
1663     GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it");
1664     g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0);
1665   }
1668 static gboolean
1669 single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes,
1670     guint64 time, GstSingleQueue * sq)
1672   gboolean res;
1673   GstMultiQueue *mq = sq->mqueue;
1675   GST_DEBUG_OBJECT (mq,
1676       "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%"
1677       G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes,
1678       sq->max_size.bytes, sq->cur_time, sq->max_size.time);
1680   /* we are always filled on EOS */
1681   if (sq->is_eos)
1682     return TRUE;
1684   /* we never go past the max visible items unless we are in buffering mode */
1685   if (!mq->use_buffering && IS_FILLED (sq, visible, visible))
1686     return TRUE;
1688   /* check time or bytes */
1689   res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes);
1691   return res;
1694 static void
1695 gst_single_queue_free (GstSingleQueue * sq)
1697   /* DRAIN QUEUE */
1698   gst_data_queue_flush (sq->queue);
1699   g_object_unref (sq->queue);
1700   g_cond_free (sq->turn);
1701   g_free (sq);
1704 static GstSingleQueue *
1705 gst_single_queue_new (GstMultiQueue * mqueue)
1707   GstSingleQueue *sq;
1708   gchar *tmp;
1710   sq = g_new0 (GstSingleQueue, 1);
1712   GST_MULTI_QUEUE_MUTEX_LOCK (mqueue);
1713   sq->id = mqueue->nbqueues++;
1715   /* copy over max_size and extra_size so we don't need to take the lock
1716    * any longer when checking if the queue is full. */
1717   sq->max_size.visible = mqueue->max_size.visible;
1718   sq->max_size.bytes = mqueue->max_size.bytes;
1719   sq->max_size.time = mqueue->max_size.time;
1721   sq->extra_size.visible = mqueue->extra_size.visible;
1722   sq->extra_size.bytes = mqueue->extra_size.bytes;
1723   sq->extra_size.time = mqueue->extra_size.time;
1725   GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue);
1727   GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id);
1729   sq->mqueue = mqueue;
1730   sq->srcresult = GST_FLOW_WRONG_STATE;
1731   sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction)
1732       single_queue_check_full,
1733       (GstDataQueueFullCallback) single_queue_overrun_cb,
1734       (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq);
1735   sq->is_eos = FALSE;
1736   sq->flushing = FALSE;
1737   gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME);
1738   gst_segment_init (&sq->src_segment, GST_FORMAT_TIME);
1740   sq->nextid = 0;
1741   sq->oldid = 0;
1742   sq->turn = g_cond_new ();
1744   sq->sinktime = GST_CLOCK_TIME_NONE;
1745   sq->srctime = GST_CLOCK_TIME_NONE;
1746   sq->sink_tainted = TRUE;
1747   sq->src_tainted = TRUE;
1749   tmp = g_strdup_printf ("sink%d", sq->id);
1750   sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, tmp);
1751   g_free (tmp);
1753   gst_pad_set_chain_function (sq->sinkpad,
1754       GST_DEBUG_FUNCPTR (gst_multi_queue_chain));
1755   gst_pad_set_activatepush_function (sq->sinkpad,
1756       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_push));
1757   gst_pad_set_event_function (sq->sinkpad,
1758       GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event));
1759   gst_pad_set_getcaps_function (sq->sinkpad,
1760       GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps));
1761   gst_pad_set_acceptcaps_function (sq->sinkpad,
1762       GST_DEBUG_FUNCPTR (gst_multi_queue_acceptcaps));
1763   gst_pad_set_bufferalloc_function (sq->sinkpad,
1764       GST_DEBUG_FUNCPTR (gst_multi_queue_bufferalloc));
1765   gst_pad_set_iterate_internal_links_function (sq->sinkpad,
1766       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
1768   tmp = g_strdup_printf ("src%d", sq->id);
1769   sq->srcpad = gst_pad_new_from_static_template (&srctemplate, tmp);
1770   g_free (tmp);
1772   gst_pad_set_activatepush_function (sq->srcpad,
1773       GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_push));
1774   gst_pad_set_getcaps_function (sq->srcpad,
1775       GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps));
1776   gst_pad_set_acceptcaps_function (sq->srcpad,
1777       GST_DEBUG_FUNCPTR (gst_multi_queue_acceptcaps));
1778   gst_pad_set_event_function (sq->srcpad,
1779       GST_DEBUG_FUNCPTR (gst_multi_queue_src_event));
1780   gst_pad_set_query_function (sq->srcpad,
1781       GST_DEBUG_FUNCPTR (gst_multi_queue_src_query));
1782   gst_pad_set_iterate_internal_links_function (sq->srcpad,
1783       GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links));
1785   gst_pad_set_element_private (sq->sinkpad, (gpointer) sq);
1786   gst_pad_set_element_private (sq->srcpad, (gpointer) sq);
1788   /* only activate the pads when we are not in the NULL state
1789    * and add the pad under the state_lock to prevend state changes
1790    * between activating and adding */
1791   g_static_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue));
1792   if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) {
1793     gst_pad_set_active (sq->srcpad, TRUE);
1794     gst_pad_set_active (sq->sinkpad, TRUE);
1795   }
1796   gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad);
1797   gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad);
1798   g_static_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue));
1800   GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added",
1801       sq->id);
1803   return sq;