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