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