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