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