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