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