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