Merge remote-tracking branch 'origin/0.10'
[platform/upstream/gstreamer.git] / plugins / elements / gstqueue.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2003 Colin Walters <cwalters@gnome.org>
5  *                    2005 Wim Taymans <wim@fluendo.com>
6  *
7  * gstqueue.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  */
24
25 /**
26  * SECTION:element-queue
27  *
28  * Data is queued until one of the limits specified by the
29  * #GstQueue:max-size-buffers, #GstQueue:max-size-bytes and/or
30  * #GstQueue:max-size-time properties has been reached. Any attempt to push
31  * more buffers into the queue will block the pushing thread until more space
32  * becomes available.
33  *
34  * The queue will create a new thread on the source pad to decouple the
35  * processing on sink and source pad.
36  *
37  * You can query how many buffers are queued by reading the
38  * #GstQueue:current-level-buffers property. You can track changes
39  * by connecting to the notify::current-level-buffers signal (which
40  * like all signals will be emitted from the streaming thread). The same
41  * applies to the #GstQueue:current-level-time and
42  * #GstQueue:current-level-bytes properties.
43  *
44  * The default queue size limits are 200 buffers, 10MB of data, or
45  * one second worth of data, whichever is reached first.
46  *
47  * As said earlier, the queue blocks by default when one of the specified
48  * maximums (bytes, time, buffers) has been reached. You can set the
49  * #GstQueue:leaky property to specify that instead of blocking it should
50  * leak (drop) new or old buffers.
51  *
52  * The #GstQueue::underrun signal is emitted when the queue has less data than
53  * the specified minimum thresholds require (by default: when the queue is
54  * empty). The #GstQueue::overrun signal is emitted when the queue is filled
55  * up. Both signals are emitted from the context of the streaming thread.
56  */
57
58 #include "gst/gst_private.h"
59
60 #include <gst/gst.h>
61 #include "gstqueue.h"
62
63 #include "../../gst/gst-i18n-lib.h"
64 #include "../../gst/glib-compat-private.h"
65
66 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
67     GST_PAD_SINK,
68     GST_PAD_ALWAYS,
69     GST_STATIC_CAPS_ANY);
70
71 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
72     GST_PAD_SRC,
73     GST_PAD_ALWAYS,
74     GST_STATIC_CAPS_ANY);
75
76 GST_DEBUG_CATEGORY_STATIC (queue_debug);
77 #define GST_CAT_DEFAULT (queue_debug)
78 GST_DEBUG_CATEGORY_STATIC (queue_dataflow);
79
80 #define STATUS(queue, pad, msg) \
81   GST_CAT_LOG_OBJECT (queue_dataflow, queue, \
82                       "(%s:%s) " msg ": %u of %u-%u buffers, %u of %u-%u " \
83                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
84                       "-%" G_GUINT64_FORMAT " ns, %u items", \
85                       GST_DEBUG_PAD_NAME (pad), \
86                       queue->cur_level.buffers, \
87                       queue->min_threshold.buffers, \
88                       queue->max_size.buffers, \
89                       queue->cur_level.bytes, \
90                       queue->min_threshold.bytes, \
91                       queue->max_size.bytes, \
92                       queue->cur_level.time, \
93                       queue->min_threshold.time, \
94                       queue->max_size.time, \
95                       queue->queue.length)
96
97 /* Queue signals and args */
98 enum
99 {
100   SIGNAL_UNDERRUN,
101   SIGNAL_RUNNING,
102   SIGNAL_OVERRUN,
103   SIGNAL_PUSHING,
104   LAST_SIGNAL
105 };
106
107 enum
108 {
109   PROP_0,
110   /* FIXME: don't we have another way of doing this
111    * "Gstreamer format" (frame/byte/time) queries? */
112   PROP_CUR_LEVEL_BUFFERS,
113   PROP_CUR_LEVEL_BYTES,
114   PROP_CUR_LEVEL_TIME,
115   PROP_MAX_SIZE_BUFFERS,
116   PROP_MAX_SIZE_BYTES,
117   PROP_MAX_SIZE_TIME,
118   PROP_MIN_THRESHOLD_BUFFERS,
119   PROP_MIN_THRESHOLD_BYTES,
120   PROP_MIN_THRESHOLD_TIME,
121   PROP_LEAKY,
122   PROP_SILENT
123 };
124
125 /* default property values */
126 #define DEFAULT_MAX_SIZE_BUFFERS  200   /* 200 buffers */
127 #define DEFAULT_MAX_SIZE_BYTES    (10 * 1024 * 1024)    /* 10 MB       */
128 #define DEFAULT_MAX_SIZE_TIME     GST_SECOND    /* 1 second    */
129
130 #define GST_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
131   g_mutex_lock (&q->qlock);                                              \
132 } G_STMT_END
133
134 #define GST_QUEUE_MUTEX_LOCK_CHECK(q,label) G_STMT_START {              \
135   GST_QUEUE_MUTEX_LOCK (q);                                             \
136   if (q->srcresult != GST_FLOW_OK)                                      \
137     goto label;                                                         \
138 } G_STMT_END
139
140 #define GST_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
141   g_mutex_unlock (&q->qlock);                                            \
142 } G_STMT_END
143
144 #define GST_QUEUE_WAIT_DEL_CHECK(q, label) G_STMT_START {               \
145   STATUS (q, q->sinkpad, "wait for DEL");                               \
146   q->waiting_del = TRUE;                                                \
147   g_cond_wait (&q->item_del, &q->qlock);                                  \
148   q->waiting_del = FALSE;                                               \
149   if (q->srcresult != GST_FLOW_OK) {                                    \
150     STATUS (q, q->srcpad, "received DEL wakeup");                       \
151     goto label;                                                         \
152   }                                                                     \
153   STATUS (q, q->sinkpad, "received DEL");                               \
154 } G_STMT_END
155
156 #define GST_QUEUE_WAIT_ADD_CHECK(q, label) G_STMT_START {               \
157   STATUS (q, q->srcpad, "wait for ADD");                                \
158   q->waiting_add = TRUE;                                                \
159   g_cond_wait (&q->item_add, &q->qlock);                                  \
160   q->waiting_add = FALSE;                                               \
161   if (q->srcresult != GST_FLOW_OK) {                                    \
162     STATUS (q, q->srcpad, "received ADD wakeup");                       \
163     goto label;                                                         \
164   }                                                                     \
165   STATUS (q, q->srcpad, "received ADD");                                \
166 } G_STMT_END
167
168 #define GST_QUEUE_SIGNAL_DEL(q) G_STMT_START {                          \
169   if (q->waiting_del) {                                                 \
170     STATUS (q, q->srcpad, "signal DEL");                                \
171     g_cond_signal (&q->item_del);                                        \
172   }                                                                     \
173 } G_STMT_END
174
175 #define GST_QUEUE_SIGNAL_ADD(q) G_STMT_START {                          \
176   if (q->waiting_add) {                                                 \
177     STATUS (q, q->sinkpad, "signal ADD");                               \
178     g_cond_signal (&q->item_add);                                        \
179   }                                                                     \
180 } G_STMT_END
181
182 #define _do_init \
183     GST_DEBUG_CATEGORY_INIT (queue_debug, "queue", 0, "queue element"); \
184     GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue_dataflow", 0, \
185         "dataflow inside the queue element");
186 #define gst_queue_parent_class parent_class
187 G_DEFINE_TYPE_WITH_CODE (GstQueue, gst_queue, GST_TYPE_ELEMENT, _do_init);
188
189 static void gst_queue_finalize (GObject * object);
190
191 static void gst_queue_set_property (GObject * object,
192     guint prop_id, const GValue * value, GParamSpec * pspec);
193 static void gst_queue_get_property (GObject * object,
194     guint prop_id, GValue * value, GParamSpec * pspec);
195
196 static GstFlowReturn gst_queue_chain (GstPad * pad, GstObject * parent,
197     GstBuffer * buffer);
198 static GstFlowReturn gst_queue_push_one (GstQueue * queue);
199 static void gst_queue_loop (GstPad * pad);
200
201 static gboolean gst_queue_handle_sink_event (GstPad * pad, GstObject * parent,
202     GstEvent * event);
203 static gboolean gst_queue_handle_sink_query (GstPad * pad, GstObject * parent,
204     GstQuery * query);
205
206 static gboolean gst_queue_handle_src_event (GstPad * pad, GstObject * parent,
207     GstEvent * event);
208 static gboolean gst_queue_handle_src_query (GstPad * pad, GstObject * parent,
209     GstQuery * query);
210
211 static void gst_queue_locked_flush (GstQueue * queue);
212
213 static gboolean gst_queue_src_activate_mode (GstPad * pad, GstObject * parent,
214     GstPadMode mode, gboolean active);
215 static gboolean gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
216     GstPadMode mode, gboolean active);
217
218 static gboolean gst_queue_is_empty (GstQueue * queue);
219 static gboolean gst_queue_is_filled (GstQueue * queue);
220
221 #define GST_TYPE_QUEUE_LEAKY (queue_leaky_get_type ())
222
223 static GType
224 queue_leaky_get_type (void)
225 {
226   static GType queue_leaky_type = 0;
227   static const GEnumValue queue_leaky[] = {
228     {GST_QUEUE_NO_LEAK, "Not Leaky", "no"},
229     {GST_QUEUE_LEAK_UPSTREAM, "Leaky on upstream (new buffers)", "upstream"},
230     {GST_QUEUE_LEAK_DOWNSTREAM, "Leaky on downstream (old buffers)",
231         "downstream"},
232     {0, NULL, NULL},
233   };
234
235   if (!queue_leaky_type) {
236     queue_leaky_type = g_enum_register_static ("GstQueueLeaky", queue_leaky);
237   }
238   return queue_leaky_type;
239 }
240
241 static guint gst_queue_signals[LAST_SIGNAL] = { 0 };
242
243 static void
244 gst_queue_class_init (GstQueueClass * klass)
245 {
246   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
247   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
248
249   gobject_class->set_property = gst_queue_set_property;
250   gobject_class->get_property = gst_queue_get_property;
251
252   /* signals */
253   /**
254    * GstQueue::underrun:
255    * @queue: the queue instance
256    *
257    * Reports that the buffer became empty (underrun).
258    * A buffer is empty if the total amount of data inside it (num-buffers, time,
259    * size) is lower than the boundary values which can be set through the
260    * GObject properties.
261    */
262   gst_queue_signals[SIGNAL_UNDERRUN] =
263       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
264       G_STRUCT_OFFSET (GstQueueClass, underrun), NULL, NULL,
265       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
266   /**
267    * GstQueue::running:
268    * @queue: the queue instance
269    *
270    * Reports that enough (min-threshold) data is in the queue. Use this signal
271    * together with the underrun signal to pause the pipeline on underrun and
272    * wait for the queue to fill-up before resume playback.
273    */
274   gst_queue_signals[SIGNAL_RUNNING] =
275       g_signal_new ("running", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
276       G_STRUCT_OFFSET (GstQueueClass, running), NULL, NULL,
277       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
278   /**
279    * GstQueue::overrun:
280    * @queue: the queue instance
281    *
282    * Reports that the buffer became full (overrun).
283    * A buffer is full if the total amount of data inside it (num-buffers, time,
284    * size) is higher than the boundary values which can be set through the
285    * GObject properties.
286    */
287   gst_queue_signals[SIGNAL_OVERRUN] =
288       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
289       G_STRUCT_OFFSET (GstQueueClass, overrun), NULL, NULL,
290       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
291   /**
292    * GstQueue::pushing:
293    * @queue: the queue instance
294    *
295    * Reports when the queue has enough data to start pushing data again on the
296    * source pad.
297    */
298   gst_queue_signals[SIGNAL_PUSHING] =
299       g_signal_new ("pushing", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
300       G_STRUCT_OFFSET (GstQueueClass, pushing), NULL, NULL,
301       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
302
303   /* properties */
304   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
305       g_param_spec_uint ("current-level-bytes", "Current level (kB)",
306           "Current amount of data in the queue (bytes)",
307           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
308   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
309       g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
310           "Current number of buffers in the queue",
311           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
312   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
313       g_param_spec_uint64 ("current-level-time", "Current level (ns)",
314           "Current amount of data in the queue (in ns)",
315           0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
316
317   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
318       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
319           "Max. amount of data in the queue (bytes, 0=disable)",
320           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
321           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
322   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
323       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
324           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
325           DEFAULT_MAX_SIZE_BUFFERS,
326           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
327   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
328       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
329           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
330           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331
332   g_object_class_install_property (gobject_class, PROP_MIN_THRESHOLD_BYTES,
333       g_param_spec_uint ("min-threshold-bytes", "Min. threshold (kB)",
334           "Min. amount of data in the queue to allow reading (bytes, 0=disable)",
335           0, G_MAXUINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
336   g_object_class_install_property (gobject_class, PROP_MIN_THRESHOLD_BUFFERS,
337       g_param_spec_uint ("min-threshold-buffers", "Min. threshold (buffers)",
338           "Min. number of buffers in the queue to allow reading (0=disable)",
339           0, G_MAXUINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
340   g_object_class_install_property (gobject_class, PROP_MIN_THRESHOLD_TIME,
341       g_param_spec_uint64 ("min-threshold-time", "Min. threshold (ns)",
342           "Min. amount of data in the queue to allow reading (in ns, 0=disable)",
343           0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344
345   g_object_class_install_property (gobject_class, PROP_LEAKY,
346       g_param_spec_enum ("leaky", "Leaky",
347           "Where the queue leaks, if at all",
348           GST_TYPE_QUEUE_LEAKY, GST_QUEUE_NO_LEAK,
349           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
350
351   /**
352    * GstQueue:silent
353    *
354    * Don't emit queue signals. Makes queues more lightweight if no signals are
355    * needed.
356    *
357    * Since: 0.10.31
358    */
359   g_object_class_install_property (gobject_class, PROP_SILENT,
360       g_param_spec_boolean ("silent", "Silent",
361           "Don't emit queue signals", FALSE,
362           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
363
364   gobject_class->finalize = gst_queue_finalize;
365
366   gst_element_class_set_details_simple (gstelement_class,
367       "Queue",
368       "Generic", "Simple data queue", "Erik Walthinsen <omega@cse.ogi.edu>");
369   gst_element_class_add_pad_template (gstelement_class,
370       gst_static_pad_template_get (&srctemplate));
371   gst_element_class_add_pad_template (gstelement_class,
372       gst_static_pad_template_get (&sinktemplate));
373
374   /* Registering debug symbols for function pointers */
375   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_src_activate_mode);
376   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_sink_event);
377   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_sink_query);
378   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_src_event);
379   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_src_query);
380   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_chain);
381 }
382
383 static void
384 gst_queue_init (GstQueue * queue)
385 {
386   queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
387
388   gst_pad_set_chain_function (queue->sinkpad, gst_queue_chain);
389   gst_pad_set_activatemode_function (queue->sinkpad,
390       gst_queue_sink_activate_mode);
391   gst_pad_set_event_function (queue->sinkpad, gst_queue_handle_sink_event);
392   gst_pad_set_query_function (queue->sinkpad, gst_queue_handle_sink_query);
393   GST_PAD_SET_PROXY_CAPS (queue->sinkpad);
394   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
395
396   queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
397
398   gst_pad_set_activatemode_function (queue->srcpad,
399       gst_queue_src_activate_mode);
400   gst_pad_set_event_function (queue->srcpad, gst_queue_handle_src_event);
401   gst_pad_set_query_function (queue->srcpad, gst_queue_handle_src_query);
402   GST_PAD_SET_PROXY_CAPS (queue->srcpad);
403   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
404
405   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
406   queue->max_size.buffers = DEFAULT_MAX_SIZE_BUFFERS;
407   queue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
408   queue->max_size.time = DEFAULT_MAX_SIZE_TIME;
409   GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
410   GST_QUEUE_CLEAR_LEVEL (queue->orig_min_threshold);
411   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
412   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
413   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
414
415   queue->leaky = GST_QUEUE_NO_LEAK;
416   queue->srcresult = GST_FLOW_FLUSHING;
417
418   g_mutex_init (&queue->qlock);
419   g_cond_init (&queue->item_add);
420   g_cond_init (&queue->item_del);
421
422   g_queue_init (&queue->queue);
423
424   queue->sinktime = GST_CLOCK_TIME_NONE;
425   queue->srctime = GST_CLOCK_TIME_NONE;
426
427   queue->sink_tainted = TRUE;
428   queue->src_tainted = TRUE;
429
430   queue->newseg_applied_to_src = FALSE;
431
432   GST_DEBUG_OBJECT (queue,
433       "initialized queue's not_empty & not_full conditions");
434 }
435
436 /* called only once, as opposed to dispose */
437 static void
438 gst_queue_finalize (GObject * object)
439 {
440   GstMiniObject *data;
441   GstQueue *queue = GST_QUEUE (object);
442
443   GST_DEBUG_OBJECT (queue, "finalizing queue");
444
445   while ((data = g_queue_pop_head (&queue->queue)))
446     gst_mini_object_unref (data);
447
448   g_queue_clear (&queue->queue);
449   g_mutex_clear (&queue->qlock);
450   g_cond_clear (&queue->item_add);
451   g_cond_clear (&queue->item_del);
452
453   G_OBJECT_CLASS (parent_class)->finalize (object);
454 }
455
456 /* calculate the diff between running time on the sink and src of the queue.
457  * This is the total amount of time in the queue. */
458 static void
459 update_time_level (GstQueue * queue)
460 {
461   gint64 sink_time, src_time;
462
463   if (queue->sink_tainted) {
464     GST_LOG_OBJECT (queue, "update sink time");
465     queue->sinktime =
466         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
467         queue->sink_segment.position);
468     queue->sink_tainted = FALSE;
469   }
470   sink_time = queue->sinktime;
471
472   if (queue->src_tainted) {
473     GST_LOG_OBJECT (queue, "update src time");
474     queue->srctime =
475         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
476         queue->src_segment.position);
477     queue->src_tainted = FALSE;
478   }
479   src_time = queue->srctime;
480
481   GST_LOG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
482       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
483
484   if (sink_time >= src_time)
485     queue->cur_level.time = sink_time - src_time;
486   else
487     queue->cur_level.time = 0;
488 }
489
490 /* take a SEGMENT event and apply the values to segment, updating the time
491  * level of queue. */
492 static void
493 apply_segment (GstQueue * queue, GstEvent * event, GstSegment * segment,
494     gboolean sink)
495 {
496   gst_event_copy_segment (event, segment);
497
498   /* now configure the values, we use these to track timestamps on the
499    * sinkpad. */
500   if (segment->format != GST_FORMAT_TIME) {
501     /* non-time format, pretent the current time segment is closed with a
502      * 0 start and unknown stop time. */
503     segment->format = GST_FORMAT_TIME;
504     segment->start = 0;
505     segment->stop = -1;
506     segment->time = 0;
507   }
508   if (sink)
509     queue->sink_tainted = TRUE;
510   else
511     queue->src_tainted = TRUE;
512
513   GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
514
515   /* segment can update the time level of the queue */
516   update_time_level (queue);
517 }
518
519 /* take a buffer and update segment, updating the time level of the queue. */
520 static void
521 apply_buffer (GstQueue * queue, GstBuffer * buffer, GstSegment * segment,
522     gboolean with_duration, gboolean sink)
523 {
524   GstClockTime duration, timestamp;
525
526   timestamp = GST_BUFFER_TIMESTAMP (buffer);
527   duration = GST_BUFFER_DURATION (buffer);
528
529   /* if no timestamp is set, assume it's continuous with the previous
530    * time */
531   if (timestamp == GST_CLOCK_TIME_NONE)
532     timestamp = segment->position;
533
534   /* add duration */
535   if (with_duration && duration != GST_CLOCK_TIME_NONE)
536     timestamp += duration;
537
538   GST_LOG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
539       GST_TIME_ARGS (timestamp));
540
541   segment->position = timestamp;
542   if (sink)
543     queue->sink_tainted = TRUE;
544   else
545     queue->src_tainted = TRUE;
546
547
548   /* calc diff with other end */
549   update_time_level (queue);
550 }
551
552 static void
553 gst_queue_locked_flush (GstQueue * queue)
554 {
555   GstMiniObject *data;
556
557   while ((data = g_queue_pop_head (&queue->queue))) {
558     /* Then lose another reference because we are supposed to destroy that
559        data when flushing */
560     gst_mini_object_unref (data);
561   }
562   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
563   queue->min_threshold.buffers = queue->orig_min_threshold.buffers;
564   queue->min_threshold.bytes = queue->orig_min_threshold.bytes;
565   queue->min_threshold.time = queue->orig_min_threshold.time;
566   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
567   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
568   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
569
570   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
571   queue->sink_tainted = queue->src_tainted = TRUE;
572
573   /* we deleted a lot of something */
574   GST_QUEUE_SIGNAL_DEL (queue);
575 }
576
577 /* enqueue an item an update the level stats, with QUEUE_LOCK */
578 static inline void
579 gst_queue_locked_enqueue_buffer (GstQueue * queue, gpointer item)
580 {
581   GstBuffer *buffer = GST_BUFFER_CAST (item);
582
583   /* add buffer to the statistics */
584   queue->cur_level.buffers++;
585   queue->cur_level.bytes += gst_buffer_get_size (buffer);
586   apply_buffer (queue, buffer, &queue->sink_segment, TRUE, TRUE);
587
588   g_queue_push_tail (&queue->queue, item);
589   GST_QUEUE_SIGNAL_ADD (queue);
590 }
591
592 static inline void
593 gst_queue_locked_enqueue_event (GstQueue * queue, gpointer item)
594 {
595   GstEvent *event = GST_EVENT_CAST (item);
596
597   switch (GST_EVENT_TYPE (event)) {
598     case GST_EVENT_EOS:
599       /* Zero the thresholds, this makes sure the queue is completely
600        * filled and we can read all data from the queue. */
601       GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
602       /* mark the queue as EOS. This prevents us from accepting more data. */
603       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from upstream");
604       queue->eos = TRUE;
605       break;
606     case GST_EVENT_SEGMENT:
607       apply_segment (queue, event, &queue->sink_segment, TRUE);
608       /* if the queue is empty, apply sink segment on the source */
609       if (queue->queue.length == 0) {
610         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "Apply segment on srcpad");
611         apply_segment (queue, event, &queue->src_segment, FALSE);
612         queue->newseg_applied_to_src = TRUE;
613       }
614       /* a new segment allows us to accept more buffers if we got EOS
615        * from downstream */
616       queue->unexpected = FALSE;
617       break;
618     default:
619       break;
620   }
621
622   g_queue_push_tail (&queue->queue, item);
623   GST_QUEUE_SIGNAL_ADD (queue);
624 }
625
626 /* dequeue an item from the queue and update level stats, with QUEUE_LOCK */
627 static GstMiniObject *
628 gst_queue_locked_dequeue (GstQueue * queue)
629 {
630   GstMiniObject *item;
631
632   item = g_queue_pop_head (&queue->queue);
633   if (item == NULL)
634     goto no_item;
635
636   if (GST_IS_BUFFER (item)) {
637     GstBuffer *buffer = GST_BUFFER_CAST (item);
638
639     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
640         "retrieved buffer %p from queue", buffer);
641
642     queue->cur_level.buffers--;
643     queue->cur_level.bytes -= gst_buffer_get_size (buffer);
644     apply_buffer (queue, buffer, &queue->src_segment, TRUE, FALSE);
645
646     /* if the queue is empty now, update the other side */
647     if (queue->cur_level.buffers == 0)
648       queue->cur_level.time = 0;
649
650   } else if (GST_IS_EVENT (item)) {
651     GstEvent *event = GST_EVENT_CAST (item);
652
653     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
654         "retrieved event %p from queue", event);
655
656     switch (GST_EVENT_TYPE (event)) {
657       case GST_EVENT_EOS:
658         /* queue is empty now that we dequeued the EOS */
659         GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
660         break;
661       case GST_EVENT_SEGMENT:
662         /* apply newsegment if it has not already been applied */
663         if (G_LIKELY (!queue->newseg_applied_to_src)) {
664           apply_segment (queue, event, &queue->src_segment, FALSE);
665         } else {
666           queue->newseg_applied_to_src = FALSE;
667         }
668         break;
669       default:
670         break;
671     }
672   } else if (GST_IS_QUERY (item)) {
673     GstQuery *query = GST_QUERY_CAST (item);
674
675     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
676         "retrieved query %p from queue", query);
677   } else {
678     g_warning
679         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
680         item, GST_OBJECT_NAME (queue));
681     item = NULL;
682   }
683   GST_QUEUE_SIGNAL_DEL (queue);
684
685   return item;
686
687   /* ERRORS */
688 no_item:
689   {
690     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "the queue is empty");
691     return NULL;
692   }
693 }
694
695 static gboolean
696 gst_queue_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
697 {
698   GstQueue *queue;
699
700   queue = GST_QUEUE (parent);
701
702   switch (GST_EVENT_TYPE (event)) {
703     case GST_EVENT_FLUSH_START:
704     {
705       STATUS (queue, pad, "received flush start event");
706       /* forward event */
707       gst_pad_push_event (queue->srcpad, event);
708
709       /* now unblock the chain function */
710       GST_QUEUE_MUTEX_LOCK (queue);
711       queue->srcresult = GST_FLOW_FLUSHING;
712       /* unblock the loop and chain functions */
713       GST_QUEUE_SIGNAL_ADD (queue);
714       GST_QUEUE_SIGNAL_DEL (queue);
715       GST_QUEUE_MUTEX_UNLOCK (queue);
716
717       /* make sure it pauses, this should happen since we sent
718        * flush_start downstream. */
719       gst_pad_pause_task (queue->srcpad);
720       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
721       goto done;
722     }
723     case GST_EVENT_FLUSH_STOP:
724     {
725       STATUS (queue, pad, "received flush stop event");
726       /* forward event */
727       gst_pad_push_event (queue->srcpad, event);
728
729       GST_QUEUE_MUTEX_LOCK (queue);
730       gst_queue_locked_flush (queue);
731       queue->srcresult = GST_FLOW_OK;
732       queue->eos = FALSE;
733       queue->unexpected = FALSE;
734       gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue_loop,
735           queue->srcpad);
736       GST_QUEUE_MUTEX_UNLOCK (queue);
737
738       STATUS (queue, pad, "after flush");
739       goto done;
740     }
741     default:
742       if (GST_EVENT_IS_SERIALIZED (event)) {
743         /* serialized events go in the queue */
744         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
745         /* refuse more events on EOS */
746         if (queue->eos)
747           goto out_eos;
748         gst_queue_locked_enqueue_event (queue, event);
749         GST_QUEUE_MUTEX_UNLOCK (queue);
750       } else {
751         /* non-serialized events are passed upstream. */
752         gst_pad_push_event (queue->srcpad, event);
753       }
754       break;
755   }
756 done:
757   return TRUE;
758
759   /* ERRORS */
760 out_flushing:
761   {
762     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
763         "refusing event, we are flushing");
764     GST_QUEUE_MUTEX_UNLOCK (queue);
765     gst_event_unref (event);
766     return FALSE;
767   }
768 out_eos:
769   {
770     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "refusing event, we are EOS");
771     GST_QUEUE_MUTEX_UNLOCK (queue);
772     gst_event_unref (event);
773     return FALSE;
774   }
775 }
776
777 static gboolean
778 gst_queue_handle_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
779 {
780   GstQueue *queue = GST_QUEUE_CAST (parent);
781   gboolean res;
782
783   switch (GST_QUERY_TYPE (query)) {
784     default:
785       if (G_UNLIKELY (GST_QUERY_IS_SERIALIZED (query))) {
786         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
787         GST_LOG_OBJECT (queue, "queuing query %p (%s)", query,
788             GST_QUERY_TYPE_NAME (query));
789         g_queue_push_tail (&queue->queue, query);
790         GST_QUEUE_SIGNAL_ADD (queue);
791         while (queue->queue.length != 0) {
792           /* for as long as the queue has items, we know the query is
793            * not handled yet */
794           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
795         }
796         res = queue->last_query;
797         GST_QUEUE_MUTEX_UNLOCK (queue);
798       } else {
799         res = gst_pad_query_default (pad, parent, query);
800       }
801       break;
802   }
803   return res;
804
805   /* ERRORS */
806 out_flushing:
807   {
808     GST_DEBUG_OBJECT (queue, "we are flushing");
809     GST_QUEUE_MUTEX_UNLOCK (queue);
810     return FALSE;
811   }
812 }
813
814 static gboolean
815 gst_queue_is_empty (GstQueue * queue)
816 {
817   if (queue->queue.length == 0)
818     return TRUE;
819
820   /* It is possible that a max size is reached before all min thresholds are.
821    * Therefore, only consider it empty if it is not filled. */
822   return ((queue->min_threshold.buffers > 0 &&
823           queue->cur_level.buffers < queue->min_threshold.buffers) ||
824       (queue->min_threshold.bytes > 0 &&
825           queue->cur_level.bytes < queue->min_threshold.bytes) ||
826       (queue->min_threshold.time > 0 &&
827           queue->cur_level.time < queue->min_threshold.time)) &&
828       !gst_queue_is_filled (queue);
829 }
830
831 static gboolean
832 gst_queue_is_filled (GstQueue * queue)
833 {
834   return (((queue->max_size.buffers > 0 &&
835               queue->cur_level.buffers >= queue->max_size.buffers) ||
836           (queue->max_size.bytes > 0 &&
837               queue->cur_level.bytes >= queue->max_size.bytes) ||
838           (queue->max_size.time > 0 &&
839               queue->cur_level.time >= queue->max_size.time)));
840 }
841
842 static void
843 gst_queue_leak_downstream (GstQueue * queue)
844 {
845   /* for as long as the queue is filled, dequeue an item and discard it */
846   while (gst_queue_is_filled (queue)) {
847     GstMiniObject *leak;
848
849     leak = gst_queue_locked_dequeue (queue);
850     /* there is nothing to dequeue and the queue is still filled.. This should
851      * not happen */
852     g_assert (leak != NULL);
853
854     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
855         "queue is full, leaking item %p on downstream end", leak);
856     gst_mini_object_unref (leak);
857
858     /* last buffer needs to get a DISCONT flag */
859     queue->head_needs_discont = TRUE;
860   }
861 }
862
863 static GstFlowReturn
864 gst_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
865 {
866   GstQueue *queue;
867   GstClockTime duration, timestamp;
868
869   queue = GST_QUEUE_CAST (parent);
870
871   /* we have to lock the queue since we span threads */
872   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
873   /* when we received EOS, we refuse any more data */
874   if (queue->eos)
875     goto out_eos;
876   if (queue->unexpected)
877     goto out_unexpected;
878
879   timestamp = GST_BUFFER_TIMESTAMP (buffer);
880   duration = GST_BUFFER_DURATION (buffer);
881
882   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of size %"
883       G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
884       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
885       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
886
887   /* We make space available if we're "full" according to whatever
888    * the user defined as "full". Note that this only applies to buffers.
889    * We always handle events and they don't count in our statistics. */
890   while (gst_queue_is_filled (queue)) {
891     if (!queue->silent) {
892       GST_QUEUE_MUTEX_UNLOCK (queue);
893       g_signal_emit (queue, gst_queue_signals[SIGNAL_OVERRUN], 0);
894       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
895       /* we recheck, the signal could have changed the thresholds */
896       if (!gst_queue_is_filled (queue))
897         break;
898     }
899
900     /* how are we going to make space for this buffer? */
901     switch (queue->leaky) {
902       case GST_QUEUE_LEAK_UPSTREAM:
903         /* next buffer needs to get a DISCONT flag */
904         queue->tail_needs_discont = TRUE;
905         /* leak current buffer */
906         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
907             "queue is full, leaking buffer on upstream end");
908         /* now we can clean up and exit right away */
909         goto out_unref;
910       case GST_QUEUE_LEAK_DOWNSTREAM:
911         gst_queue_leak_downstream (queue);
912         break;
913       default:
914         g_warning ("Unknown leaky type, using default");
915         /* fall-through */
916       case GST_QUEUE_NO_LEAK:
917       {
918         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
919             "queue is full, waiting for free space");
920
921         /* don't leak. Instead, wait for space to be available */
922         do {
923           /* for as long as the queue is filled, wait till an item was deleted. */
924           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
925         } while (gst_queue_is_filled (queue));
926
927         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not full");
928
929         if (!queue->silent) {
930           GST_QUEUE_MUTEX_UNLOCK (queue);
931           g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
932           GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
933         }
934         break;
935       }
936     }
937   }
938
939   if (queue->tail_needs_discont) {
940     GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
941
942     if (subbuffer) {
943       buffer = subbuffer;
944       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
945     } else {
946       GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
947     }
948     queue->tail_needs_discont = FALSE;
949   }
950
951   /* put buffer in queue now */
952   gst_queue_locked_enqueue_buffer (queue, buffer);
953   GST_QUEUE_MUTEX_UNLOCK (queue);
954
955   return GST_FLOW_OK;
956
957   /* special conditions */
958 out_unref:
959   {
960     GST_QUEUE_MUTEX_UNLOCK (queue);
961
962     gst_buffer_unref (buffer);
963
964     return GST_FLOW_OK;
965   }
966 out_flushing:
967   {
968     GstFlowReturn ret = queue->srcresult;
969
970     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
971         "exit because task paused, reason: %s", gst_flow_get_name (ret));
972     GST_QUEUE_MUTEX_UNLOCK (queue);
973     gst_buffer_unref (buffer);
974
975     return ret;
976   }
977 out_eos:
978   {
979     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
980     GST_QUEUE_MUTEX_UNLOCK (queue);
981
982     gst_buffer_unref (buffer);
983
984     return GST_FLOW_EOS;
985   }
986 out_unexpected:
987   {
988     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
989     GST_QUEUE_MUTEX_UNLOCK (queue);
990
991     gst_buffer_unref (buffer);
992
993     return GST_FLOW_EOS;
994   }
995 }
996
997 /* dequeue an item from the queue an push it downstream. This functions returns
998  * the result of the push. */
999 static GstFlowReturn
1000 gst_queue_push_one (GstQueue * queue)
1001 {
1002   GstFlowReturn result = GST_FLOW_OK;
1003   GstMiniObject *data;
1004
1005   data = gst_queue_locked_dequeue (queue);
1006   if (data == NULL)
1007     goto no_item;
1008
1009 next:
1010   if (GST_IS_BUFFER (data)) {
1011     GstBuffer *buffer;
1012
1013     buffer = GST_BUFFER_CAST (data);
1014
1015     if (queue->head_needs_discont) {
1016       GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
1017
1018       if (subbuffer) {
1019         buffer = subbuffer;
1020         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1021       } else {
1022         GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
1023       }
1024       queue->head_needs_discont = FALSE;
1025     }
1026
1027     GST_QUEUE_MUTEX_UNLOCK (queue);
1028     result = gst_pad_push (queue->srcpad, buffer);
1029
1030     /* need to check for srcresult here as well */
1031     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1032
1033     if (result == GST_FLOW_EOS) {
1034       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
1035       /* stop pushing buffers, we dequeue all items until we see an item that we
1036        * can push again, which is EOS or SEGMENT. If there is nothing in the
1037        * queue we can push, we set a flag to make the sinkpad refuse more
1038        * buffers with an EOS return value. */
1039       while ((data = gst_queue_locked_dequeue (queue))) {
1040         if (GST_IS_BUFFER (data)) {
1041           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1042               "dropping EOS buffer %p", data);
1043           gst_buffer_unref (GST_BUFFER_CAST (data));
1044         } else if (GST_IS_EVENT (data)) {
1045           GstEvent *event = GST_EVENT_CAST (data);
1046           GstEventType type = GST_EVENT_TYPE (event);
1047
1048           if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
1049             /* we found a pushable item in the queue, push it out */
1050             GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1051                 "pushing pushable event %s after EOS",
1052                 GST_EVENT_TYPE_NAME (event));
1053             goto next;
1054           }
1055           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1056               "dropping EOS event %p", event);
1057           gst_event_unref (event);
1058         } else if (GST_IS_QUERY (data)) {
1059           GstQuery *query = GST_QUERY_CAST (data);
1060
1061           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1062               "dropping query %p because of EOS", query);
1063           queue->last_query = FALSE;
1064         }
1065       }
1066       /* no more items in the queue. Set the unexpected flag so that upstream
1067        * make us refuse any more buffers on the sinkpad. Since we will still
1068        * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
1069        * task function does not shut down. */
1070       queue->unexpected = TRUE;
1071       result = GST_FLOW_OK;
1072     }
1073   } else if (GST_IS_EVENT (data)) {
1074     GstEvent *event = GST_EVENT_CAST (data);
1075     GstEventType type = GST_EVENT_TYPE (event);
1076
1077     GST_QUEUE_MUTEX_UNLOCK (queue);
1078
1079     gst_pad_push_event (queue->srcpad, event);
1080
1081     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1082     /* if we're EOS, return EOS so that the task pauses. */
1083     if (type == GST_EVENT_EOS) {
1084       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1085           "pushed EOS event %p, return EOS", event);
1086       result = GST_FLOW_EOS;
1087     }
1088   } else if (GST_IS_QUERY (data)) {
1089     GstQuery *query = GST_QUERY_CAST (data);
1090
1091     queue->last_query = gst_pad_peer_query (queue->srcpad, query);
1092     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1093         "did query %p, return %d", query, queue->last_query);
1094   }
1095   return result;
1096
1097   /* ERRORS */
1098 no_item:
1099   {
1100     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1101         "exit because we have no item in the queue");
1102     return GST_FLOW_ERROR;
1103   }
1104 out_flushing:
1105   {
1106     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
1107     return GST_FLOW_FLUSHING;
1108   }
1109 }
1110
1111 static void
1112 gst_queue_loop (GstPad * pad)
1113 {
1114   GstQueue *queue;
1115   GstFlowReturn ret;
1116
1117   queue = (GstQueue *) GST_PAD_PARENT (pad);
1118
1119   /* have to lock for thread-safety */
1120   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1121
1122   while (gst_queue_is_empty (queue)) {
1123     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is empty");
1124     if (!queue->silent) {
1125       GST_QUEUE_MUTEX_UNLOCK (queue);
1126       g_signal_emit (queue, gst_queue_signals[SIGNAL_UNDERRUN], 0);
1127       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1128     }
1129
1130     /* we recheck, the signal could have changed the thresholds */
1131     while (gst_queue_is_empty (queue)) {
1132       GST_QUEUE_WAIT_ADD_CHECK (queue, out_flushing);
1133     }
1134
1135     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not empty");
1136     if (!queue->silent) {
1137       GST_QUEUE_MUTEX_UNLOCK (queue);
1138       g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
1139       g_signal_emit (queue, gst_queue_signals[SIGNAL_PUSHING], 0);
1140       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1141     }
1142   }
1143
1144   ret = gst_queue_push_one (queue);
1145   queue->srcresult = ret;
1146   if (ret != GST_FLOW_OK)
1147     goto out_flushing;
1148
1149   GST_QUEUE_MUTEX_UNLOCK (queue);
1150
1151   return;
1152
1153   /* ERRORS */
1154 out_flushing:
1155   {
1156     gboolean eos = queue->eos;
1157     GstFlowReturn ret = queue->srcresult;
1158
1159     gst_pad_pause_task (queue->srcpad);
1160     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1161         "pause task, reason:  %s", gst_flow_get_name (ret));
1162     GST_QUEUE_SIGNAL_DEL (queue);
1163     GST_QUEUE_MUTEX_UNLOCK (queue);
1164     /* let app know about us giving up if upstream is not expected to do so */
1165     /* EOS is already taken care of elsewhere */
1166     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1167       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
1168           (_("Internal data flow error.")),
1169           ("streaming task paused, reason %s (%d)",
1170               gst_flow_get_name (ret), ret));
1171       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
1172     }
1173     return;
1174   }
1175 }
1176
1177 static gboolean
1178 gst_queue_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1179 {
1180   gboolean res = TRUE;
1181   GstQueue *queue = GST_QUEUE (parent);
1182
1183 #ifndef GST_DISABLE_GST_DEBUG
1184   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%d)",
1185       event, GST_EVENT_TYPE (event));
1186 #endif
1187
1188   res = gst_pad_push_event (queue->sinkpad, event);
1189
1190   return res;
1191 }
1192
1193 static gboolean
1194 gst_queue_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1195 {
1196   GstQueue *queue = GST_QUEUE (parent);
1197   gboolean res;
1198
1199   res = gst_pad_query_default (pad, parent, query);
1200   if (!res)
1201     return FALSE;
1202
1203   switch (GST_QUERY_TYPE (query)) {
1204     case GST_QUERY_POSITION:
1205     {
1206       gint64 peer_pos;
1207       GstFormat format;
1208
1209       /* get peer position */
1210       gst_query_parse_position (query, &format, &peer_pos);
1211
1212       /* FIXME: this code assumes that there's no discont in the queue */
1213       switch (format) {
1214         case GST_FORMAT_BYTES:
1215           peer_pos -= queue->cur_level.bytes;
1216           break;
1217         case GST_FORMAT_TIME:
1218           peer_pos -= queue->cur_level.time;
1219           break;
1220         default:
1221           GST_DEBUG_OBJECT (queue, "Can't adjust query in %s format, don't "
1222               "know how to adjust value", gst_format_get_name (format));
1223           return TRUE;
1224       }
1225       /* set updated position */
1226       gst_query_set_position (query, format, peer_pos);
1227       break;
1228     }
1229     case GST_QUERY_LATENCY:
1230     {
1231       gboolean live;
1232       GstClockTime min, max;
1233
1234       gst_query_parse_latency (query, &live, &min, &max);
1235
1236       /* we can delay up to the limit of the queue in time. If we have no time
1237        * limit, the best thing we can do is to return an infinite delay. In
1238        * reality a better estimate would be the byte/buffer rate but that is not
1239        * possible right now. */
1240       if (queue->max_size.time > 0 && max != -1)
1241         max += queue->max_size.time;
1242       else
1243         max = -1;
1244
1245       /* adjust for min-threshold */
1246       if (queue->min_threshold.time > 0 && min != -1)
1247         min += queue->min_threshold.time;
1248
1249       gst_query_set_latency (query, live, min, max);
1250       break;
1251     }
1252     default:
1253       /* peer handled other queries */
1254       break;
1255   }
1256
1257   return TRUE;
1258 }
1259
1260 static gboolean
1261 gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1262     gboolean active)
1263 {
1264   gboolean result;
1265   GstQueue *queue;
1266
1267   queue = GST_QUEUE (parent);
1268
1269   switch (mode) {
1270     case GST_PAD_MODE_PUSH:
1271       if (active) {
1272         GST_QUEUE_MUTEX_LOCK (queue);
1273         queue->srcresult = GST_FLOW_OK;
1274         queue->eos = FALSE;
1275         queue->unexpected = FALSE;
1276         GST_QUEUE_MUTEX_UNLOCK (queue);
1277       } else {
1278         /* step 1, unblock chain function */
1279         GST_QUEUE_MUTEX_LOCK (queue);
1280         queue->srcresult = GST_FLOW_FLUSHING;
1281         gst_queue_locked_flush (queue);
1282         GST_QUEUE_MUTEX_UNLOCK (queue);
1283       }
1284       result = TRUE;
1285       break;
1286     default:
1287       result = FALSE;
1288       break;
1289   }
1290   return result;
1291 }
1292
1293 static gboolean
1294 gst_queue_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1295     gboolean active)
1296 {
1297   gboolean result;
1298   GstQueue *queue;
1299
1300   queue = GST_QUEUE (parent);
1301
1302   switch (mode) {
1303     case GST_PAD_MODE_PUSH:
1304       if (active) {
1305         GST_QUEUE_MUTEX_LOCK (queue);
1306         queue->srcresult = GST_FLOW_OK;
1307         queue->eos = FALSE;
1308         queue->unexpected = FALSE;
1309         result =
1310             gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad);
1311         GST_QUEUE_MUTEX_UNLOCK (queue);
1312       } else {
1313         /* step 1, unblock loop function */
1314         GST_QUEUE_MUTEX_LOCK (queue);
1315         queue->srcresult = GST_FLOW_FLUSHING;
1316         /* the item add signal will unblock */
1317         g_cond_signal (&queue->item_add);
1318         GST_QUEUE_MUTEX_UNLOCK (queue);
1319
1320         /* step 2, make sure streaming finishes */
1321         result = gst_pad_stop_task (pad);
1322       }
1323       break;
1324     default:
1325       result = FALSE;
1326       break;
1327   }
1328   return result;
1329 }
1330
1331 static void
1332 queue_capacity_change (GstQueue * queue)
1333 {
1334   if (queue->leaky == GST_QUEUE_LEAK_DOWNSTREAM) {
1335     gst_queue_leak_downstream (queue);
1336   }
1337
1338   /* changing the capacity of the queue must wake up
1339    * the _chain function, it might have more room now
1340    * to store the buffer/event in the queue */
1341   GST_QUEUE_SIGNAL_DEL (queue);
1342 }
1343
1344 /* Changing the minimum required fill level must
1345  * wake up the _loop function as it might now
1346  * be able to preceed.
1347  */
1348 #define QUEUE_THRESHOLD_CHANGE(q)\
1349   GST_QUEUE_SIGNAL_ADD (q);
1350
1351 static void
1352 gst_queue_set_property (GObject * object,
1353     guint prop_id, const GValue * value, GParamSpec * pspec)
1354 {
1355   GstQueue *queue = GST_QUEUE (object);
1356
1357   /* someone could change levels here, and since this
1358    * affects the get/put funcs, we need to lock for safety. */
1359   GST_QUEUE_MUTEX_LOCK (queue);
1360
1361   switch (prop_id) {
1362     case PROP_MAX_SIZE_BYTES:
1363       queue->max_size.bytes = g_value_get_uint (value);
1364       queue_capacity_change (queue);
1365       break;
1366     case PROP_MAX_SIZE_BUFFERS:
1367       queue->max_size.buffers = g_value_get_uint (value);
1368       queue_capacity_change (queue);
1369       break;
1370     case PROP_MAX_SIZE_TIME:
1371       queue->max_size.time = g_value_get_uint64 (value);
1372       queue_capacity_change (queue);
1373       break;
1374     case PROP_MIN_THRESHOLD_BYTES:
1375       queue->min_threshold.bytes = g_value_get_uint (value);
1376       queue->orig_min_threshold.bytes = queue->min_threshold.bytes;
1377       QUEUE_THRESHOLD_CHANGE (queue);
1378       break;
1379     case PROP_MIN_THRESHOLD_BUFFERS:
1380       queue->min_threshold.buffers = g_value_get_uint (value);
1381       queue->orig_min_threshold.buffers = queue->min_threshold.buffers;
1382       QUEUE_THRESHOLD_CHANGE (queue);
1383       break;
1384     case PROP_MIN_THRESHOLD_TIME:
1385       queue->min_threshold.time = g_value_get_uint64 (value);
1386       queue->orig_min_threshold.time = queue->min_threshold.time;
1387       QUEUE_THRESHOLD_CHANGE (queue);
1388       break;
1389     case PROP_LEAKY:
1390       queue->leaky = g_value_get_enum (value);
1391       break;
1392     case PROP_SILENT:
1393       queue->silent = g_value_get_boolean (value);
1394       break;
1395     default:
1396       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1397       break;
1398   }
1399
1400   GST_QUEUE_MUTEX_UNLOCK (queue);
1401 }
1402
1403 static void
1404 gst_queue_get_property (GObject * object,
1405     guint prop_id, GValue * value, GParamSpec * pspec)
1406 {
1407   GstQueue *queue = GST_QUEUE (object);
1408
1409   GST_QUEUE_MUTEX_LOCK (queue);
1410
1411   switch (prop_id) {
1412     case PROP_CUR_LEVEL_BYTES:
1413       g_value_set_uint (value, queue->cur_level.bytes);
1414       break;
1415     case PROP_CUR_LEVEL_BUFFERS:
1416       g_value_set_uint (value, queue->cur_level.buffers);
1417       break;
1418     case PROP_CUR_LEVEL_TIME:
1419       g_value_set_uint64 (value, queue->cur_level.time);
1420       break;
1421     case PROP_MAX_SIZE_BYTES:
1422       g_value_set_uint (value, queue->max_size.bytes);
1423       break;
1424     case PROP_MAX_SIZE_BUFFERS:
1425       g_value_set_uint (value, queue->max_size.buffers);
1426       break;
1427     case PROP_MAX_SIZE_TIME:
1428       g_value_set_uint64 (value, queue->max_size.time);
1429       break;
1430     case PROP_MIN_THRESHOLD_BYTES:
1431       g_value_set_uint (value, queue->min_threshold.bytes);
1432       break;
1433     case PROP_MIN_THRESHOLD_BUFFERS:
1434       g_value_set_uint (value, queue->min_threshold.buffers);
1435       break;
1436     case PROP_MIN_THRESHOLD_TIME:
1437       g_value_set_uint64 (value, queue->min_threshold.time);
1438       break;
1439     case PROP_LEAKY:
1440       g_value_set_enum (value, queue->leaky);
1441       break;
1442     case PROP_SILENT:
1443       g_value_set_boolean (value, queue->silent);
1444       break;
1445     default:
1446       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1447       break;
1448   }
1449
1450   GST_QUEUE_MUTEX_UNLOCK (queue);
1451 }