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