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