queue: Fix handling of min-threshold and serialized queries
[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_static_metadata (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   queue->queue = gst_queue_array_new (DEFAULT_MAX_SIZE_BUFFERS * 3 / 2);
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 (!gst_queue_array_is_empty (queue->queue)) {
446     data = gst_queue_array_pop_head (queue->queue);
447     if (!GST_IS_QUERY (data))
448       gst_mini_object_unref (data);
449   }
450   gst_queue_array_free (queue->queue);
451
452   g_mutex_clear (&queue->qlock);
453   g_cond_clear (&queue->item_add);
454   g_cond_clear (&queue->item_del);
455
456   G_OBJECT_CLASS (parent_class)->finalize (object);
457 }
458
459 /* calculate the diff between running time on the sink and src of the queue.
460  * This is the total amount of time in the queue. */
461 static void
462 update_time_level (GstQueue * queue)
463 {
464   gint64 sink_time, src_time;
465
466   if (queue->sink_tainted) {
467     GST_LOG_OBJECT (queue, "update sink time");
468     queue->sinktime =
469         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
470         queue->sink_segment.position);
471     queue->sink_tainted = FALSE;
472   }
473   sink_time = queue->sinktime;
474
475   if (queue->src_tainted) {
476     GST_LOG_OBJECT (queue, "update src time");
477     queue->srctime =
478         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
479         queue->src_segment.position);
480     queue->src_tainted = FALSE;
481   }
482   src_time = queue->srctime;
483
484   GST_LOG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
485       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
486
487   if (sink_time >= src_time)
488     queue->cur_level.time = sink_time - src_time;
489   else
490     queue->cur_level.time = 0;
491 }
492
493 /* take a SEGMENT event and apply the values to segment, updating the time
494  * level of queue. */
495 static void
496 apply_segment (GstQueue * queue, GstEvent * event, GstSegment * segment,
497     gboolean sink)
498 {
499   gst_event_copy_segment (event, segment);
500
501   /* now configure the values, we use these to track timestamps on the
502    * sinkpad. */
503   if (segment->format != GST_FORMAT_TIME) {
504     /* non-time format, pretent the current time segment is closed with a
505      * 0 start and unknown stop time. */
506     segment->format = GST_FORMAT_TIME;
507     segment->start = 0;
508     segment->stop = -1;
509     segment->time = 0;
510   }
511   if (sink)
512     queue->sink_tainted = TRUE;
513   else
514     queue->src_tainted = TRUE;
515
516   GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
517
518   /* segment can update the time level of the queue */
519   update_time_level (queue);
520 }
521
522 /* take a buffer and update segment, updating the time level of the queue. */
523 static void
524 apply_buffer (GstQueue * queue, GstBuffer * buffer, GstSegment * segment,
525     gboolean with_duration, gboolean sink)
526 {
527   GstClockTime duration, timestamp;
528
529   timestamp = GST_BUFFER_TIMESTAMP (buffer);
530   duration = GST_BUFFER_DURATION (buffer);
531
532   /* if no timestamp is set, assume it's continuous with the previous
533    * time */
534   if (timestamp == GST_CLOCK_TIME_NONE)
535     timestamp = segment->position;
536
537   /* add duration */
538   if (with_duration && duration != GST_CLOCK_TIME_NONE)
539     timestamp += duration;
540
541   GST_LOG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
542       GST_TIME_ARGS (timestamp));
543
544   segment->position = timestamp;
545   if (sink)
546     queue->sink_tainted = TRUE;
547   else
548     queue->src_tainted = TRUE;
549
550
551   /* calc diff with other end */
552   update_time_level (queue);
553 }
554
555 static void
556 gst_queue_locked_flush (GstQueue * queue)
557 {
558   GstMiniObject *data;
559
560   while (!gst_queue_array_is_empty (queue->queue)) {
561     data = gst_queue_array_pop_head (queue->queue);
562     /* Then lose another reference because we are supposed to destroy that
563        data when flushing */
564     if (!GST_IS_QUERY (data))
565       gst_mini_object_unref (data);
566   }
567   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
568   queue->min_threshold.buffers = queue->orig_min_threshold.buffers;
569   queue->min_threshold.bytes = queue->orig_min_threshold.bytes;
570   queue->min_threshold.time = queue->orig_min_threshold.time;
571   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
572   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
573   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
574
575   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
576   queue->sink_tainted = queue->src_tainted = TRUE;
577
578   /* we deleted a lot of something */
579   GST_QUEUE_SIGNAL_DEL (queue);
580 }
581
582 /* enqueue an item an update the level stats, with QUEUE_LOCK */
583 static inline void
584 gst_queue_locked_enqueue_buffer (GstQueue * queue, gpointer item)
585 {
586   GstBuffer *buffer = GST_BUFFER_CAST (item);
587
588   /* add buffer to the statistics */
589   queue->cur_level.buffers++;
590   queue->cur_level.bytes += gst_buffer_get_size (buffer);
591   apply_buffer (queue, buffer, &queue->sink_segment, TRUE, TRUE);
592
593   if (item)
594     gst_queue_array_push_tail (queue->queue, item);
595   GST_QUEUE_SIGNAL_ADD (queue);
596 }
597
598 static inline void
599 gst_queue_locked_enqueue_event (GstQueue * queue, gpointer item)
600 {
601   GstEvent *event = GST_EVENT_CAST (item);
602
603   switch (GST_EVENT_TYPE (event)) {
604     case GST_EVENT_EOS:
605       /* Zero the thresholds, this makes sure the queue is completely
606        * filled and we can read all data from the queue. */
607       GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
608       /* mark the queue as EOS. This prevents us from accepting more data. */
609       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from upstream");
610       queue->eos = TRUE;
611       break;
612     case GST_EVENT_SEGMENT:
613       apply_segment (queue, event, &queue->sink_segment, TRUE);
614       /* if the queue is empty, apply sink segment on the source */
615       if (queue->queue->length == 0) {
616         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "Apply segment on srcpad");
617         apply_segment (queue, event, &queue->src_segment, FALSE);
618         queue->newseg_applied_to_src = TRUE;
619       }
620       /* a new segment allows us to accept more buffers if we got EOS
621        * from downstream */
622       queue->unexpected = FALSE;
623       break;
624     default:
625       break;
626   }
627
628   if (item)
629     gst_queue_array_push_tail (queue->queue, item);
630   GST_QUEUE_SIGNAL_ADD (queue);
631 }
632
633 /* dequeue an item from the queue and update level stats, with QUEUE_LOCK */
634 static GstMiniObject *
635 gst_queue_locked_dequeue (GstQueue * queue)
636 {
637   GstMiniObject *item;
638
639   item = gst_queue_array_pop_head (queue->queue);
640   if (item == NULL)
641     goto no_item;
642
643   if (GST_IS_BUFFER (item)) {
644     GstBuffer *buffer = GST_BUFFER_CAST (item);
645
646     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
647         "retrieved buffer %p from queue", buffer);
648
649     queue->cur_level.buffers--;
650     queue->cur_level.bytes -= gst_buffer_get_size (buffer);
651     apply_buffer (queue, buffer, &queue->src_segment, TRUE, FALSE);
652
653     /* if the queue is empty now, update the other side */
654     if (queue->cur_level.buffers == 0)
655       queue->cur_level.time = 0;
656
657   } else if (GST_IS_EVENT (item)) {
658     GstEvent *event = GST_EVENT_CAST (item);
659
660     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
661         "retrieved event %p from queue", event);
662
663     switch (GST_EVENT_TYPE (event)) {
664       case GST_EVENT_EOS:
665         /* queue is empty now that we dequeued the EOS */
666         GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
667         break;
668       case GST_EVENT_SEGMENT:
669         /* apply newsegment if it has not already been applied */
670         if (G_LIKELY (!queue->newseg_applied_to_src)) {
671           apply_segment (queue, event, &queue->src_segment, FALSE);
672         } else {
673           queue->newseg_applied_to_src = FALSE;
674         }
675         break;
676       default:
677         break;
678     }
679   } else if (GST_IS_QUERY (item)) {
680     GstQuery *query = GST_QUERY_CAST (item);
681
682     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
683         "retrieved query %p from queue", query);
684   } else {
685     g_warning
686         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
687         item, GST_OBJECT_NAME (queue));
688     item = NULL;
689   }
690   GST_QUEUE_SIGNAL_DEL (queue);
691
692   return item;
693
694   /* ERRORS */
695 no_item:
696   {
697     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "the queue is empty");
698     return NULL;
699   }
700 }
701
702 static gboolean
703 gst_queue_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
704 {
705   GstQueue *queue;
706
707   queue = GST_QUEUE (parent);
708
709   switch (GST_EVENT_TYPE (event)) {
710     case GST_EVENT_FLUSH_START:
711     {
712       STATUS (queue, pad, "received flush start event");
713       /* forward event */
714       gst_pad_push_event (queue->srcpad, event);
715
716       /* now unblock the chain function */
717       GST_QUEUE_MUTEX_LOCK (queue);
718       queue->srcresult = GST_FLOW_FLUSHING;
719       /* unblock the loop and chain functions */
720       GST_QUEUE_SIGNAL_ADD (queue);
721       GST_QUEUE_SIGNAL_DEL (queue);
722       GST_QUEUE_MUTEX_UNLOCK (queue);
723
724       /* make sure it pauses, this should happen since we sent
725        * flush_start downstream. */
726       gst_pad_pause_task (queue->srcpad);
727       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
728       goto done;
729     }
730     case GST_EVENT_FLUSH_STOP:
731     {
732       STATUS (queue, pad, "received flush stop event");
733       /* forward event */
734       gst_pad_push_event (queue->srcpad, event);
735
736       GST_QUEUE_MUTEX_LOCK (queue);
737       gst_queue_locked_flush (queue);
738       queue->srcresult = GST_FLOW_OK;
739       queue->eos = FALSE;
740       queue->unexpected = FALSE;
741       gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue_loop,
742           queue->srcpad, NULL);
743       GST_QUEUE_MUTEX_UNLOCK (queue);
744
745       STATUS (queue, pad, "after flush");
746       goto done;
747     }
748     default:
749       if (GST_EVENT_IS_SERIALIZED (event)) {
750         /* serialized events go in the queue */
751         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
752         /* refuse more events on EOS */
753         if (queue->eos)
754           goto out_eos;
755         gst_queue_locked_enqueue_event (queue, event);
756         GST_QUEUE_MUTEX_UNLOCK (queue);
757       } else {
758         /* non-serialized events are passed upstream. */
759         gst_pad_push_event (queue->srcpad, event);
760       }
761       break;
762   }
763 done:
764   return TRUE;
765
766   /* ERRORS */
767 out_flushing:
768   {
769     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
770         "refusing event, we are flushing");
771     GST_QUEUE_MUTEX_UNLOCK (queue);
772     gst_event_unref (event);
773     return FALSE;
774   }
775 out_eos:
776   {
777     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "refusing event, we are EOS");
778     GST_QUEUE_MUTEX_UNLOCK (queue);
779     gst_event_unref (event);
780     return FALSE;
781   }
782 }
783
784 static gboolean
785 gst_queue_handle_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
786 {
787   GstQueue *queue = GST_QUEUE_CAST (parent);
788   gboolean res;
789
790   switch (GST_QUERY_TYPE (query)) {
791     default:
792       if (G_UNLIKELY (GST_QUERY_IS_SERIALIZED (query))) {
793         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
794         GST_LOG_OBJECT (queue, "queuing query %p (%s)", query,
795             GST_QUERY_TYPE_NAME (query));
796         gst_queue_array_push_tail (queue->queue, query);
797         GST_QUEUE_SIGNAL_ADD (queue);
798         while (queue->queue->length != 0) {
799           /* for as long as the queue has items, we know the query is
800            * not handled yet */
801           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
802         }
803         res = queue->last_query;
804         GST_QUEUE_MUTEX_UNLOCK (queue);
805       } else {
806         res = gst_pad_query_default (pad, parent, query);
807       }
808       break;
809   }
810   return res;
811
812   /* ERRORS */
813 out_flushing:
814   {
815     GST_DEBUG_OBJECT (queue, "we are flushing");
816     GST_QUEUE_MUTEX_UNLOCK (queue);
817     return FALSE;
818   }
819 }
820
821 static gboolean
822 gst_queue_is_empty (GstQueue * queue)
823 {
824   GstMiniObject *head;
825
826   if (queue->queue->length == 0)
827     return TRUE;
828
829   /* Only consider the queue empty if the minimum thresholds
830    * are not reached and data is at the queue head. Otherwise
831    * we would block forever on serialized queries.
832    */
833   head = queue->queue->array[queue->queue->head];
834   if (!GST_IS_BUFFER (head) && !GST_IS_BUFFER_LIST (head))
835     return FALSE;
836
837   /* It is possible that a max size is reached before all min thresholds are.
838    * Therefore, only consider it empty if it is not filled. */
839   return ((queue->min_threshold.buffers > 0 &&
840           queue->cur_level.buffers < queue->min_threshold.buffers) ||
841       (queue->min_threshold.bytes > 0 &&
842           queue->cur_level.bytes < queue->min_threshold.bytes) ||
843       (queue->min_threshold.time > 0 &&
844           queue->cur_level.time < queue->min_threshold.time)) &&
845       !gst_queue_is_filled (queue);
846 }
847
848 static gboolean
849 gst_queue_is_filled (GstQueue * queue)
850 {
851   return (((queue->max_size.buffers > 0 &&
852               queue->cur_level.buffers >= queue->max_size.buffers) ||
853           (queue->max_size.bytes > 0 &&
854               queue->cur_level.bytes >= queue->max_size.bytes) ||
855           (queue->max_size.time > 0 &&
856               queue->cur_level.time >= queue->max_size.time)));
857 }
858
859 static void
860 gst_queue_leak_downstream (GstQueue * queue)
861 {
862   /* for as long as the queue is filled, dequeue an item and discard it */
863   while (gst_queue_is_filled (queue)) {
864     GstMiniObject *leak;
865
866     leak = gst_queue_locked_dequeue (queue);
867     /* there is nothing to dequeue and the queue is still filled.. This should
868      * not happen */
869     g_assert (leak != NULL);
870
871     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
872         "queue is full, leaking item %p on downstream end", leak);
873     if (!GST_IS_QUERY (leak))
874       gst_mini_object_unref (leak);
875
876     /* last buffer needs to get a DISCONT flag */
877     queue->head_needs_discont = TRUE;
878   }
879 }
880
881 static GstFlowReturn
882 gst_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
883 {
884   GstQueue *queue;
885   GstClockTime duration, timestamp;
886
887   queue = GST_QUEUE_CAST (parent);
888
889   /* we have to lock the queue since we span threads */
890   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
891   /* when we received EOS, we refuse any more data */
892   if (queue->eos)
893     goto out_eos;
894   if (queue->unexpected)
895     goto out_unexpected;
896
897   timestamp = GST_BUFFER_TIMESTAMP (buffer);
898   duration = GST_BUFFER_DURATION (buffer);
899
900   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of size %"
901       G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
902       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
903       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
904
905   /* We make space available if we're "full" according to whatever
906    * the user defined as "full". Note that this only applies to buffers.
907    * We always handle events and they don't count in our statistics. */
908   while (gst_queue_is_filled (queue)) {
909     if (!queue->silent) {
910       GST_QUEUE_MUTEX_UNLOCK (queue);
911       g_signal_emit (queue, gst_queue_signals[SIGNAL_OVERRUN], 0);
912       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
913       /* we recheck, the signal could have changed the thresholds */
914       if (!gst_queue_is_filled (queue))
915         break;
916     }
917
918     /* how are we going to make space for this buffer? */
919     switch (queue->leaky) {
920       case GST_QUEUE_LEAK_UPSTREAM:
921         /* next buffer needs to get a DISCONT flag */
922         queue->tail_needs_discont = TRUE;
923         /* leak current buffer */
924         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
925             "queue is full, leaking buffer on upstream end");
926         /* now we can clean up and exit right away */
927         goto out_unref;
928       case GST_QUEUE_LEAK_DOWNSTREAM:
929         gst_queue_leak_downstream (queue);
930         break;
931       default:
932         g_warning ("Unknown leaky type, using default");
933         /* fall-through */
934       case GST_QUEUE_NO_LEAK:
935       {
936         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
937             "queue is full, waiting for free space");
938
939         /* don't leak. Instead, wait for space to be available */
940         do {
941           /* for as long as the queue is filled, wait till an item was deleted. */
942           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
943         } while (gst_queue_is_filled (queue));
944
945         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not full");
946
947         if (!queue->silent) {
948           GST_QUEUE_MUTEX_UNLOCK (queue);
949           g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
950           GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
951         }
952         break;
953       }
954     }
955   }
956
957   if (queue->tail_needs_discont) {
958     GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
959
960     if (subbuffer) {
961       buffer = subbuffer;
962       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
963     } else {
964       GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
965     }
966     queue->tail_needs_discont = FALSE;
967   }
968
969   /* put buffer in queue now */
970   gst_queue_locked_enqueue_buffer (queue, buffer);
971   GST_QUEUE_MUTEX_UNLOCK (queue);
972
973   return GST_FLOW_OK;
974
975   /* special conditions */
976 out_unref:
977   {
978     GST_QUEUE_MUTEX_UNLOCK (queue);
979
980     gst_buffer_unref (buffer);
981
982     return GST_FLOW_OK;
983   }
984 out_flushing:
985   {
986     GstFlowReturn ret = queue->srcresult;
987
988     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
989         "exit because task paused, reason: %s", gst_flow_get_name (ret));
990     GST_QUEUE_MUTEX_UNLOCK (queue);
991     gst_buffer_unref (buffer);
992
993     return ret;
994   }
995 out_eos:
996   {
997     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
998     GST_QUEUE_MUTEX_UNLOCK (queue);
999
1000     gst_buffer_unref (buffer);
1001
1002     return GST_FLOW_EOS;
1003   }
1004 out_unexpected:
1005   {
1006     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1007     GST_QUEUE_MUTEX_UNLOCK (queue);
1008
1009     gst_buffer_unref (buffer);
1010
1011     return GST_FLOW_EOS;
1012   }
1013 }
1014
1015 /* dequeue an item from the queue an push it downstream. This functions returns
1016  * the result of the push. */
1017 static GstFlowReturn
1018 gst_queue_push_one (GstQueue * queue)
1019 {
1020   GstFlowReturn result = GST_FLOW_OK;
1021   GstMiniObject *data;
1022
1023   data = gst_queue_locked_dequeue (queue);
1024   if (data == NULL)
1025     goto no_item;
1026
1027 next:
1028   if (GST_IS_BUFFER (data)) {
1029     GstBuffer *buffer;
1030
1031     buffer = GST_BUFFER_CAST (data);
1032
1033     if (queue->head_needs_discont) {
1034       GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
1035
1036       if (subbuffer) {
1037         buffer = subbuffer;
1038         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1039       } else {
1040         GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
1041       }
1042       queue->head_needs_discont = FALSE;
1043     }
1044
1045     GST_QUEUE_MUTEX_UNLOCK (queue);
1046     result = gst_pad_push (queue->srcpad, buffer);
1047
1048     /* need to check for srcresult here as well */
1049     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1050
1051     if (result == GST_FLOW_EOS) {
1052       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
1053       /* stop pushing buffers, we dequeue all items until we see an item that we
1054        * can push again, which is EOS or SEGMENT. If there is nothing in the
1055        * queue we can push, we set a flag to make the sinkpad refuse more
1056        * buffers with an EOS return value. */
1057       while ((data = gst_queue_locked_dequeue (queue))) {
1058         if (GST_IS_BUFFER (data)) {
1059           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1060               "dropping EOS buffer %p", data);
1061           gst_buffer_unref (GST_BUFFER_CAST (data));
1062         } else if (GST_IS_EVENT (data)) {
1063           GstEvent *event = GST_EVENT_CAST (data);
1064           GstEventType type = GST_EVENT_TYPE (event);
1065
1066           if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
1067             /* we found a pushable item in the queue, push it out */
1068             GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1069                 "pushing pushable event %s after EOS",
1070                 GST_EVENT_TYPE_NAME (event));
1071             goto next;
1072           }
1073           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1074               "dropping EOS event %p", event);
1075           gst_event_unref (event);
1076         } else if (GST_IS_QUERY (data)) {
1077           GstQuery *query = GST_QUERY_CAST (data);
1078
1079           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1080               "dropping query %p because of EOS", query);
1081           queue->last_query = FALSE;
1082         }
1083       }
1084       /* no more items in the queue. Set the unexpected flag so that upstream
1085        * make us refuse any more buffers on the sinkpad. Since we will still
1086        * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
1087        * task function does not shut down. */
1088       queue->unexpected = TRUE;
1089       result = GST_FLOW_OK;
1090     }
1091   } else if (GST_IS_EVENT (data)) {
1092     GstEvent *event = GST_EVENT_CAST (data);
1093     GstEventType type = GST_EVENT_TYPE (event);
1094
1095     GST_QUEUE_MUTEX_UNLOCK (queue);
1096
1097     gst_pad_push_event (queue->srcpad, event);
1098
1099     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1100     /* if we're EOS, return EOS so that the task pauses. */
1101     if (type == GST_EVENT_EOS) {
1102       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1103           "pushed EOS event %p, return EOS", event);
1104       result = GST_FLOW_EOS;
1105     }
1106   } else if (GST_IS_QUERY (data)) {
1107     GstQuery *query = GST_QUERY_CAST (data);
1108
1109     queue->last_query = gst_pad_peer_query (queue->srcpad, query);
1110     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1111         "did query %p, return %d", query, queue->last_query);
1112   }
1113   return result;
1114
1115   /* ERRORS */
1116 no_item:
1117   {
1118     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1119         "exit because we have no item in the queue");
1120     return GST_FLOW_ERROR;
1121   }
1122 out_flushing:
1123   {
1124     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
1125     return GST_FLOW_FLUSHING;
1126   }
1127 }
1128
1129 static void
1130 gst_queue_loop (GstPad * pad)
1131 {
1132   GstQueue *queue;
1133   GstFlowReturn ret;
1134
1135   queue = (GstQueue *) GST_PAD_PARENT (pad);
1136
1137   /* have to lock for thread-safety */
1138   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1139
1140   while (gst_queue_is_empty (queue)) {
1141     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is empty");
1142     if (!queue->silent) {
1143       GST_QUEUE_MUTEX_UNLOCK (queue);
1144       g_signal_emit (queue, gst_queue_signals[SIGNAL_UNDERRUN], 0);
1145       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1146     }
1147
1148     /* we recheck, the signal could have changed the thresholds */
1149     while (gst_queue_is_empty (queue)) {
1150       GST_QUEUE_WAIT_ADD_CHECK (queue, out_flushing);
1151     }
1152
1153     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not empty");
1154     if (!queue->silent) {
1155       GST_QUEUE_MUTEX_UNLOCK (queue);
1156       g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
1157       g_signal_emit (queue, gst_queue_signals[SIGNAL_PUSHING], 0);
1158       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1159     }
1160   }
1161
1162   ret = gst_queue_push_one (queue);
1163   queue->srcresult = ret;
1164   if (ret != GST_FLOW_OK)
1165     goto out_flushing;
1166
1167   GST_QUEUE_MUTEX_UNLOCK (queue);
1168
1169   return;
1170
1171   /* ERRORS */
1172 out_flushing:
1173   {
1174     gboolean eos = queue->eos;
1175     GstFlowReturn ret = queue->srcresult;
1176
1177     gst_pad_pause_task (queue->srcpad);
1178     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1179         "pause task, reason:  %s", gst_flow_get_name (ret));
1180     if (ret == GST_FLOW_FLUSHING)
1181       gst_queue_locked_flush (queue);
1182     else
1183       GST_QUEUE_SIGNAL_DEL (queue);
1184     GST_QUEUE_MUTEX_UNLOCK (queue);
1185     /* let app know about us giving up if upstream is not expected to do so */
1186     /* EOS is already taken care of elsewhere */
1187     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1188       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
1189           (_("Internal data flow error.")),
1190           ("streaming task paused, reason %s (%d)",
1191               gst_flow_get_name (ret), ret));
1192       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
1193     }
1194     return;
1195   }
1196 }
1197
1198 static gboolean
1199 gst_queue_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1200 {
1201   gboolean res = TRUE;
1202   GstQueue *queue = GST_QUEUE (parent);
1203
1204 #ifndef GST_DISABLE_GST_DEBUG
1205   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%d)",
1206       event, GST_EVENT_TYPE (event));
1207 #endif
1208
1209   res = gst_pad_push_event (queue->sinkpad, event);
1210
1211   return res;
1212 }
1213
1214 static gboolean
1215 gst_queue_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1216 {
1217   GstQueue *queue = GST_QUEUE (parent);
1218   gboolean res;
1219
1220   res = gst_pad_query_default (pad, parent, query);
1221   if (!res)
1222     return FALSE;
1223
1224   switch (GST_QUERY_TYPE (query)) {
1225     case GST_QUERY_POSITION:
1226     {
1227       gint64 peer_pos;
1228       GstFormat format;
1229
1230       /* get peer position */
1231       gst_query_parse_position (query, &format, &peer_pos);
1232
1233       /* FIXME: this code assumes that there's no discont in the queue */
1234       switch (format) {
1235         case GST_FORMAT_BYTES:
1236           peer_pos -= queue->cur_level.bytes;
1237           break;
1238         case GST_FORMAT_TIME:
1239           peer_pos -= queue->cur_level.time;
1240           break;
1241         default:
1242           GST_DEBUG_OBJECT (queue, "Can't adjust query in %s format, don't "
1243               "know how to adjust value", gst_format_get_name (format));
1244           return TRUE;
1245       }
1246       /* set updated position */
1247       gst_query_set_position (query, format, peer_pos);
1248       break;
1249     }
1250     case GST_QUERY_LATENCY:
1251     {
1252       gboolean live;
1253       GstClockTime min, max;
1254
1255       gst_query_parse_latency (query, &live, &min, &max);
1256
1257       /* we can delay up to the limit of the queue in time. If we have no time
1258        * limit, the best thing we can do is to return an infinite delay. In
1259        * reality a better estimate would be the byte/buffer rate but that is not
1260        * possible right now. */
1261       if (queue->max_size.time > 0 && max != -1)
1262         max += queue->max_size.time;
1263       else
1264         max = -1;
1265
1266       /* adjust for min-threshold */
1267       if (queue->min_threshold.time > 0 && min != -1)
1268         min += queue->min_threshold.time;
1269
1270       gst_query_set_latency (query, live, min, max);
1271       break;
1272     }
1273     default:
1274       /* peer handled other queries */
1275       break;
1276   }
1277
1278   return TRUE;
1279 }
1280
1281 static gboolean
1282 gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1283     gboolean active)
1284 {
1285   gboolean result;
1286   GstQueue *queue;
1287
1288   queue = GST_QUEUE (parent);
1289
1290   switch (mode) {
1291     case GST_PAD_MODE_PUSH:
1292       if (active) {
1293         GST_QUEUE_MUTEX_LOCK (queue);
1294         queue->srcresult = GST_FLOW_OK;
1295         queue->eos = FALSE;
1296         queue->unexpected = FALSE;
1297         GST_QUEUE_MUTEX_UNLOCK (queue);
1298       } else {
1299         /* step 1, unblock chain function */
1300         GST_QUEUE_MUTEX_LOCK (queue);
1301         queue->srcresult = GST_FLOW_FLUSHING;
1302         gst_queue_locked_flush (queue);
1303         GST_QUEUE_MUTEX_UNLOCK (queue);
1304       }
1305       result = TRUE;
1306       break;
1307     default:
1308       result = FALSE;
1309       break;
1310   }
1311   return result;
1312 }
1313
1314 static gboolean
1315 gst_queue_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1316     gboolean active)
1317 {
1318   gboolean result;
1319   GstQueue *queue;
1320
1321   queue = GST_QUEUE (parent);
1322
1323   switch (mode) {
1324     case GST_PAD_MODE_PUSH:
1325       if (active) {
1326         GST_QUEUE_MUTEX_LOCK (queue);
1327         queue->srcresult = GST_FLOW_OK;
1328         queue->eos = FALSE;
1329         queue->unexpected = FALSE;
1330         result =
1331             gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad,
1332             NULL);
1333         GST_QUEUE_MUTEX_UNLOCK (queue);
1334       } else {
1335         /* step 1, unblock loop function */
1336         GST_QUEUE_MUTEX_LOCK (queue);
1337         queue->srcresult = GST_FLOW_FLUSHING;
1338         /* the item add signal will unblock */
1339         g_cond_signal (&queue->item_add);
1340         GST_QUEUE_MUTEX_UNLOCK (queue);
1341
1342         /* step 2, make sure streaming finishes */
1343         result = gst_pad_stop_task (pad);
1344       }
1345       break;
1346     default:
1347       result = FALSE;
1348       break;
1349   }
1350   return result;
1351 }
1352
1353 static void
1354 queue_capacity_change (GstQueue * queue)
1355 {
1356   if (queue->leaky == GST_QUEUE_LEAK_DOWNSTREAM) {
1357     gst_queue_leak_downstream (queue);
1358   }
1359
1360   /* changing the capacity of the queue must wake up
1361    * the _chain function, it might have more room now
1362    * to store the buffer/event in the queue */
1363   GST_QUEUE_SIGNAL_DEL (queue);
1364 }
1365
1366 /* Changing the minimum required fill level must
1367  * wake up the _loop function as it might now
1368  * be able to preceed.
1369  */
1370 #define QUEUE_THRESHOLD_CHANGE(q)\
1371   GST_QUEUE_SIGNAL_ADD (q);
1372
1373 static void
1374 gst_queue_set_property (GObject * object,
1375     guint prop_id, const GValue * value, GParamSpec * pspec)
1376 {
1377   GstQueue *queue = GST_QUEUE (object);
1378
1379   /* someone could change levels here, and since this
1380    * affects the get/put funcs, we need to lock for safety. */
1381   GST_QUEUE_MUTEX_LOCK (queue);
1382
1383   switch (prop_id) {
1384     case PROP_MAX_SIZE_BYTES:
1385       queue->max_size.bytes = g_value_get_uint (value);
1386       queue_capacity_change (queue);
1387       break;
1388     case PROP_MAX_SIZE_BUFFERS:
1389       queue->max_size.buffers = g_value_get_uint (value);
1390       queue_capacity_change (queue);
1391       break;
1392     case PROP_MAX_SIZE_TIME:
1393       queue->max_size.time = g_value_get_uint64 (value);
1394       queue_capacity_change (queue);
1395       break;
1396     case PROP_MIN_THRESHOLD_BYTES:
1397       queue->min_threshold.bytes = g_value_get_uint (value);
1398       queue->orig_min_threshold.bytes = queue->min_threshold.bytes;
1399       QUEUE_THRESHOLD_CHANGE (queue);
1400       break;
1401     case PROP_MIN_THRESHOLD_BUFFERS:
1402       queue->min_threshold.buffers = g_value_get_uint (value);
1403       queue->orig_min_threshold.buffers = queue->min_threshold.buffers;
1404       QUEUE_THRESHOLD_CHANGE (queue);
1405       break;
1406     case PROP_MIN_THRESHOLD_TIME:
1407       queue->min_threshold.time = g_value_get_uint64 (value);
1408       queue->orig_min_threshold.time = queue->min_threshold.time;
1409       QUEUE_THRESHOLD_CHANGE (queue);
1410       break;
1411     case PROP_LEAKY:
1412       queue->leaky = g_value_get_enum (value);
1413       break;
1414     case PROP_SILENT:
1415       queue->silent = g_value_get_boolean (value);
1416       break;
1417     default:
1418       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1419       break;
1420   }
1421
1422   GST_QUEUE_MUTEX_UNLOCK (queue);
1423 }
1424
1425 static void
1426 gst_queue_get_property (GObject * object,
1427     guint prop_id, GValue * value, GParamSpec * pspec)
1428 {
1429   GstQueue *queue = GST_QUEUE (object);
1430
1431   GST_QUEUE_MUTEX_LOCK (queue);
1432
1433   switch (prop_id) {
1434     case PROP_CUR_LEVEL_BYTES:
1435       g_value_set_uint (value, queue->cur_level.bytes);
1436       break;
1437     case PROP_CUR_LEVEL_BUFFERS:
1438       g_value_set_uint (value, queue->cur_level.buffers);
1439       break;
1440     case PROP_CUR_LEVEL_TIME:
1441       g_value_set_uint64 (value, queue->cur_level.time);
1442       break;
1443     case PROP_MAX_SIZE_BYTES:
1444       g_value_set_uint (value, queue->max_size.bytes);
1445       break;
1446     case PROP_MAX_SIZE_BUFFERS:
1447       g_value_set_uint (value, queue->max_size.buffers);
1448       break;
1449     case PROP_MAX_SIZE_TIME:
1450       g_value_set_uint64 (value, queue->max_size.time);
1451       break;
1452     case PROP_MIN_THRESHOLD_BYTES:
1453       g_value_set_uint (value, queue->min_threshold.bytes);
1454       break;
1455     case PROP_MIN_THRESHOLD_BUFFERS:
1456       g_value_set_uint (value, queue->min_threshold.buffers);
1457       break;
1458     case PROP_MIN_THRESHOLD_TIME:
1459       g_value_set_uint64 (value, queue->min_threshold.time);
1460       break;
1461     case PROP_LEAKY:
1462       g_value_set_enum (value, queue->leaky);
1463       break;
1464     case PROP_SILENT:
1465       g_value_set_boolean (value, queue->silent);
1466       break;
1467     default:
1468       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1469       break;
1470   }
1471
1472   GST_QUEUE_MUTEX_UNLOCK (queue);
1473 }