queue: Do not forget to release the QUEUE_LOCK in the out_flow_error path
[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 /* take a buffer and update segment, updating the time level of the queue. */
565 static void
566 apply_buffer (GstQueue * queue, GstBuffer * buffer, GstSegment * segment,
567     gboolean with_duration, gboolean sink)
568 {
569   GstClockTime duration, timestamp;
570
571   timestamp = GST_BUFFER_TIMESTAMP (buffer);
572   duration = GST_BUFFER_DURATION (buffer);
573
574   /* if no timestamp is set, assume it's continuous with the previous
575    * time */
576   if (timestamp == GST_CLOCK_TIME_NONE)
577     timestamp = segment->position;
578
579   /* add duration */
580   if (with_duration && duration != GST_CLOCK_TIME_NONE)
581     timestamp += duration;
582
583   GST_LOG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
584       GST_TIME_ARGS (timestamp));
585
586   segment->position = timestamp;
587   if (sink)
588     queue->sink_tainted = TRUE;
589   else
590     queue->src_tainted = TRUE;
591
592
593   /* calc diff with other end */
594   update_time_level (queue);
595 }
596
597 static void
598 gst_queue_locked_flush (GstQueue * queue, gboolean full)
599 {
600   while (!gst_queue_array_is_empty (queue->queue)) {
601     GstQueueItem *qitem = gst_queue_array_pop_head (queue->queue);
602
603     /* Then lose another reference because we are supposed to destroy that
604        data when flushing */
605     if (!full && !qitem->is_query && GST_IS_EVENT (qitem->item)
606         && GST_EVENT_IS_STICKY (qitem->item)
607         && GST_EVENT_TYPE (qitem->item) != GST_EVENT_SEGMENT
608         && GST_EVENT_TYPE (qitem->item) != GST_EVENT_EOS) {
609       gst_pad_store_sticky_event (queue->srcpad, GST_EVENT_CAST (qitem->item));
610     }
611     if (!qitem->is_query)
612       gst_mini_object_unref (qitem->item);
613     g_slice_free (GstQueueItem, qitem);
614   }
615   queue->last_query = FALSE;
616   g_cond_signal (&queue->query_handled);
617   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
618   queue->min_threshold.buffers = queue->orig_min_threshold.buffers;
619   queue->min_threshold.bytes = queue->orig_min_threshold.bytes;
620   queue->min_threshold.time = queue->orig_min_threshold.time;
621   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
622   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
623   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
624
625   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
626   queue->sink_tainted = queue->src_tainted = TRUE;
627
628   /* we deleted a lot of something */
629   GST_QUEUE_SIGNAL_DEL (queue);
630 }
631
632 /* enqueue an item an update the level stats, with QUEUE_LOCK */
633 static inline void
634 gst_queue_locked_enqueue_buffer (GstQueue * queue, gpointer item)
635 {
636   GstQueueItem *qitem;
637   GstBuffer *buffer = GST_BUFFER_CAST (item);
638   gsize bsize = gst_buffer_get_size (buffer);
639
640   /* add buffer to the statistics */
641   queue->cur_level.buffers++;
642   queue->cur_level.bytes += bsize;
643   apply_buffer (queue, buffer, &queue->sink_segment, TRUE, TRUE);
644
645   qitem = g_slice_new (GstQueueItem);
646   qitem->item = item;
647   qitem->is_query = FALSE;
648   qitem->size = bsize;
649   gst_queue_array_push_tail (queue->queue, qitem);
650   GST_QUEUE_SIGNAL_ADD (queue);
651 }
652
653 static inline void
654 gst_queue_locked_enqueue_event (GstQueue * queue, gpointer item)
655 {
656   GstQueueItem *qitem;
657   GstEvent *event = GST_EVENT_CAST (item);
658
659   switch (GST_EVENT_TYPE (event)) {
660     case GST_EVENT_EOS:
661       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from upstream");
662       /* Zero the thresholds, this makes sure the queue is completely
663        * filled and we can read all data from the queue. */
664       if (queue->flush_on_eos)
665         gst_queue_locked_flush (queue, FALSE);
666       else
667         GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
668       /* mark the queue as EOS. This prevents us from accepting more data. */
669       queue->eos = TRUE;
670       break;
671     case GST_EVENT_SEGMENT:
672       apply_segment (queue, event, &queue->sink_segment, TRUE);
673       /* if the queue is empty, apply sink segment on the source */
674       if (gst_queue_array_is_empty (queue->queue)) {
675         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "Apply segment on srcpad");
676         apply_segment (queue, event, &queue->src_segment, FALSE);
677         queue->newseg_applied_to_src = TRUE;
678       }
679       /* a new segment allows us to accept more buffers if we got EOS
680        * from downstream */
681       queue->unexpected = FALSE;
682       break;
683     default:
684       break;
685   }
686
687   qitem = g_slice_new (GstQueueItem);
688   qitem->item = item;
689   qitem->is_query = FALSE;
690   gst_queue_array_push_tail (queue->queue, qitem);
691   GST_QUEUE_SIGNAL_ADD (queue);
692 }
693
694 /* dequeue an item from the queue and update level stats, with QUEUE_LOCK */
695 static GstMiniObject *
696 gst_queue_locked_dequeue (GstQueue * queue)
697 {
698   GstQueueItem *qitem;
699   GstMiniObject *item;
700   gsize bufsize;
701
702   qitem = gst_queue_array_pop_head (queue->queue);
703   if (qitem == NULL)
704     goto no_item;
705
706   item = qitem->item;
707   bufsize = qitem->size;
708   g_slice_free (GstQueueItem, qitem);
709
710   if (GST_IS_BUFFER (item)) {
711     GstBuffer *buffer = GST_BUFFER_CAST (item);
712
713     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
714         "retrieved buffer %p from queue", buffer);
715
716     queue->cur_level.buffers--;
717     queue->cur_level.bytes -= bufsize;
718     apply_buffer (queue, buffer, &queue->src_segment, TRUE, FALSE);
719
720     /* if the queue is empty now, update the other side */
721     if (queue->cur_level.buffers == 0)
722       queue->cur_level.time = 0;
723
724   } else if (GST_IS_EVENT (item)) {
725     GstEvent *event = GST_EVENT_CAST (item);
726
727     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
728         "retrieved event %p from queue", event);
729
730     switch (GST_EVENT_TYPE (event)) {
731       case GST_EVENT_EOS:
732         /* queue is empty now that we dequeued the EOS */
733         GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
734         break;
735       case GST_EVENT_SEGMENT:
736         /* apply newsegment if it has not already been applied */
737         if (G_LIKELY (!queue->newseg_applied_to_src)) {
738           apply_segment (queue, event, &queue->src_segment, FALSE);
739         } else {
740           queue->newseg_applied_to_src = FALSE;
741         }
742         break;
743       default:
744         break;
745     }
746   } else if (GST_IS_QUERY (item)) {
747     GstQuery *query = GST_QUERY_CAST (item);
748
749     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
750         "retrieved query %p from queue", query);
751   } else {
752     g_warning
753         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
754         item, GST_OBJECT_NAME (queue));
755     item = NULL;
756   }
757   GST_QUEUE_SIGNAL_DEL (queue);
758
759   return item;
760
761   /* ERRORS */
762 no_item:
763   {
764     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "the queue is empty");
765     return NULL;
766   }
767 }
768
769 static gboolean
770 gst_queue_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
771 {
772   gboolean ret = TRUE;
773   GstQueue *queue;
774
775   queue = GST_QUEUE (parent);
776
777   switch (GST_EVENT_TYPE (event)) {
778     case GST_EVENT_FLUSH_START:
779       STATUS (queue, pad, "received flush start event");
780       /* forward event */
781       ret = gst_pad_push_event (queue->srcpad, event);
782
783       /* now unblock the chain function */
784       GST_QUEUE_MUTEX_LOCK (queue);
785       queue->srcresult = GST_FLOW_FLUSHING;
786       /* unblock the loop and chain functions */
787       GST_QUEUE_SIGNAL_ADD (queue);
788       GST_QUEUE_SIGNAL_DEL (queue);
789       queue->last_query = FALSE;
790       g_cond_signal (&queue->query_handled);
791       GST_QUEUE_MUTEX_UNLOCK (queue);
792
793       /* make sure it pauses, this should happen since we sent
794        * flush_start downstream. */
795       gst_pad_pause_task (queue->srcpad);
796       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
797       break;
798     case GST_EVENT_FLUSH_STOP:
799       STATUS (queue, pad, "received flush stop event");
800       /* forward event */
801       ret = gst_pad_push_event (queue->srcpad, event);
802
803       GST_QUEUE_MUTEX_LOCK (queue);
804       gst_queue_locked_flush (queue, FALSE);
805       queue->srcresult = GST_FLOW_OK;
806       queue->eos = FALSE;
807       queue->unexpected = FALSE;
808       if (gst_pad_is_active (queue->srcpad)) {
809         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue_loop,
810             queue->srcpad, NULL);
811       } else {
812         GST_INFO_OBJECT (queue->srcpad, "not re-starting task on srcpad, "
813             "pad not active any longer");
814       }
815       GST_QUEUE_MUTEX_UNLOCK (queue);
816
817       STATUS (queue, pad, "after flush");
818       break;
819     default:
820       if (GST_EVENT_IS_SERIALIZED (event)) {
821         /* serialized events go in the queue */
822         GST_QUEUE_MUTEX_LOCK (queue);
823         if (queue->srcresult != GST_FLOW_OK) {
824           /* Errors in sticky event pushing are no problem and ignored here
825            * as they will cause more meaningful errors during data flow.
826            * For EOS events, that are not followed by data flow, we still
827            * return FALSE here though and report an error.
828            */
829           if (!GST_EVENT_IS_STICKY (event)) {
830             GST_QUEUE_MUTEX_UNLOCK (queue);
831             goto out_flow_error;
832           } else if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
833             if (queue->srcresult == GST_FLOW_NOT_LINKED
834                 || queue->srcresult < GST_FLOW_EOS) {
835               GST_QUEUE_MUTEX_UNLOCK (queue);
836               GST_ELEMENT_ERROR (queue, STREAM, FAILED,
837                   (_("Internal data flow error.")),
838                   ("streaming task paused, reason %s (%d)",
839                       gst_flow_get_name (queue->srcresult), queue->srcresult));
840             } else {
841               GST_QUEUE_MUTEX_UNLOCK (queue);
842             }
843             goto out_flow_error;
844           }
845         }
846         /* refuse more events on EOS */
847         if (queue->eos)
848           goto out_eos;
849         gst_queue_locked_enqueue_event (queue, event);
850         GST_QUEUE_MUTEX_UNLOCK (queue);
851       } else {
852         /* non-serialized events are forwarded downstream immediately */
853         ret = gst_pad_push_event (queue->srcpad, event);
854       }
855       break;
856   }
857   return ret;
858
859   /* ERRORS */
860 out_eos:
861   {
862     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "refusing event, we are EOS");
863     GST_QUEUE_MUTEX_UNLOCK (queue);
864     gst_event_unref (event);
865     return FALSE;
866   }
867 out_flow_error:
868   {
869     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
870         "refusing event, we have a downstream flow error: %s",
871         gst_flow_get_name (queue->srcresult));
872     gst_event_unref (event);
873     return FALSE;
874   }
875 }
876
877 static gboolean
878 gst_queue_handle_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
879 {
880   GstQueue *queue = GST_QUEUE_CAST (parent);
881   gboolean res;
882
883   switch (GST_QUERY_TYPE (query)) {
884     default:
885       if (G_UNLIKELY (GST_QUERY_IS_SERIALIZED (query))) {
886         GstQueueItem *qitem;
887
888         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
889         GST_LOG_OBJECT (queue, "queuing query %p (%s)", query,
890             GST_QUERY_TYPE_NAME (query));
891         qitem = g_slice_new (GstQueueItem);
892         qitem->item = GST_MINI_OBJECT_CAST (query);
893         qitem->is_query = TRUE;
894         gst_queue_array_push_tail (queue->queue, qitem);
895         GST_QUEUE_SIGNAL_ADD (queue);
896         g_cond_wait (&queue->query_handled, &queue->qlock);
897         if (queue->srcresult != GST_FLOW_OK)
898           goto out_flushing;
899         res = queue->last_query;
900         GST_QUEUE_MUTEX_UNLOCK (queue);
901       } else {
902         res = gst_pad_query_default (pad, parent, query);
903       }
904       break;
905   }
906   return res;
907
908   /* ERRORS */
909 out_flushing:
910   {
911     GST_DEBUG_OBJECT (queue, "we are flushing");
912     GST_QUEUE_MUTEX_UNLOCK (queue);
913     return FALSE;
914   }
915 }
916
917 static gboolean
918 gst_queue_is_empty (GstQueue * queue)
919 {
920   GstQueueItem *head;
921
922   if (gst_queue_array_is_empty (queue->queue))
923     return TRUE;
924
925   /* Only consider the queue empty if the minimum thresholds
926    * are not reached and data is at the queue head. Otherwise
927    * we would block forever on serialized queries.
928    */
929   head = gst_queue_array_peek_head (queue->queue);
930   if (!GST_IS_BUFFER (head->item) && !GST_IS_BUFFER_LIST (head->item))
931     return FALSE;
932
933   /* It is possible that a max size is reached before all min thresholds are.
934    * Therefore, only consider it empty if it is not filled. */
935   return ((queue->min_threshold.buffers > 0 &&
936           queue->cur_level.buffers < queue->min_threshold.buffers) ||
937       (queue->min_threshold.bytes > 0 &&
938           queue->cur_level.bytes < queue->min_threshold.bytes) ||
939       (queue->min_threshold.time > 0 &&
940           queue->cur_level.time < queue->min_threshold.time)) &&
941       !gst_queue_is_filled (queue);
942 }
943
944 static gboolean
945 gst_queue_is_filled (GstQueue * queue)
946 {
947   return (((queue->max_size.buffers > 0 &&
948               queue->cur_level.buffers >= queue->max_size.buffers) ||
949           (queue->max_size.bytes > 0 &&
950               queue->cur_level.bytes >= queue->max_size.bytes) ||
951           (queue->max_size.time > 0 &&
952               queue->cur_level.time >= queue->max_size.time)));
953 }
954
955 static void
956 gst_queue_leak_downstream (GstQueue * queue)
957 {
958   /* for as long as the queue is filled, dequeue an item and discard it */
959   while (gst_queue_is_filled (queue)) {
960     GstMiniObject *leak;
961
962     leak = gst_queue_locked_dequeue (queue);
963     /* there is nothing to dequeue and the queue is still filled.. This should
964      * not happen */
965     g_assert (leak != NULL);
966
967     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
968         "queue is full, leaking item %p on downstream end", leak);
969     if (GST_IS_EVENT (leak) && GST_EVENT_IS_STICKY (leak)) {
970       GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
971           "Storing sticky event %s on srcpad", GST_EVENT_TYPE_NAME (leak));
972       gst_pad_store_sticky_event (queue->srcpad, GST_EVENT_CAST (leak));
973     }
974
975     if (!GST_IS_QUERY (leak))
976       gst_mini_object_unref (leak);
977
978     /* last buffer needs to get a DISCONT flag */
979     queue->head_needs_discont = TRUE;
980   }
981 }
982
983 static GstFlowReturn
984 gst_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
985 {
986   GstQueue *queue;
987   GstClockTime duration, timestamp;
988
989   queue = GST_QUEUE_CAST (parent);
990
991   /* we have to lock the queue since we span threads */
992   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
993   /* when we received EOS, we refuse any more data */
994   if (queue->eos)
995     goto out_eos;
996   if (queue->unexpected)
997     goto out_unexpected;
998
999   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1000   duration = GST_BUFFER_DURATION (buffer);
1001
1002   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of size %"
1003       G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
1004       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
1005       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
1006
1007   /* We make space available if we're "full" according to whatever
1008    * the user defined as "full". Note that this only applies to buffers.
1009    * We always handle events and they don't count in our statistics. */
1010   while (gst_queue_is_filled (queue)) {
1011     if (!queue->silent) {
1012       GST_QUEUE_MUTEX_UNLOCK (queue);
1013       g_signal_emit (queue, gst_queue_signals[SIGNAL_OVERRUN], 0);
1014       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1015       /* we recheck, the signal could have changed the thresholds */
1016       if (!gst_queue_is_filled (queue))
1017         break;
1018     }
1019
1020     /* how are we going to make space for this buffer? */
1021     switch (queue->leaky) {
1022       case GST_QUEUE_LEAK_UPSTREAM:
1023         /* next buffer needs to get a DISCONT flag */
1024         queue->tail_needs_discont = TRUE;
1025         /* leak current buffer */
1026         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1027             "queue is full, leaking buffer on upstream end");
1028         /* now we can clean up and exit right away */
1029         goto out_unref;
1030       case GST_QUEUE_LEAK_DOWNSTREAM:
1031         gst_queue_leak_downstream (queue);
1032         break;
1033       default:
1034         g_warning ("Unknown leaky type, using default");
1035         /* fall-through */
1036       case GST_QUEUE_NO_LEAK:
1037       {
1038         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1039             "queue is full, waiting for free space");
1040
1041         /* don't leak. Instead, wait for space to be available */
1042         do {
1043           /* for as long as the queue is filled, wait till an item was deleted. */
1044           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
1045         } while (gst_queue_is_filled (queue));
1046
1047         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not full");
1048
1049         if (!queue->silent) {
1050           GST_QUEUE_MUTEX_UNLOCK (queue);
1051           g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
1052           GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1053         }
1054         break;
1055       }
1056     }
1057   }
1058
1059   if (queue->tail_needs_discont) {
1060     GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
1061
1062     if (subbuffer) {
1063       buffer = subbuffer;
1064       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1065     } else {
1066       GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
1067     }
1068     queue->tail_needs_discont = FALSE;
1069   }
1070
1071   /* put buffer in queue now */
1072   gst_queue_locked_enqueue_buffer (queue, buffer);
1073   GST_QUEUE_MUTEX_UNLOCK (queue);
1074
1075   return GST_FLOW_OK;
1076
1077   /* special conditions */
1078 out_unref:
1079   {
1080     GST_QUEUE_MUTEX_UNLOCK (queue);
1081
1082     gst_buffer_unref (buffer);
1083
1084     return GST_FLOW_OK;
1085   }
1086 out_flushing:
1087   {
1088     GstFlowReturn ret = queue->srcresult;
1089
1090     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1091         "exit because task paused, reason: %s", gst_flow_get_name (ret));
1092     GST_QUEUE_MUTEX_UNLOCK (queue);
1093     gst_buffer_unref (buffer);
1094
1095     return ret;
1096   }
1097 out_eos:
1098   {
1099     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1100     GST_QUEUE_MUTEX_UNLOCK (queue);
1101
1102     gst_buffer_unref (buffer);
1103
1104     return GST_FLOW_EOS;
1105   }
1106 out_unexpected:
1107   {
1108     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1109     GST_QUEUE_MUTEX_UNLOCK (queue);
1110
1111     gst_buffer_unref (buffer);
1112
1113     return GST_FLOW_EOS;
1114   }
1115 }
1116
1117 /* dequeue an item from the queue an push it downstream. This functions returns
1118  * the result of the push. */
1119 static GstFlowReturn
1120 gst_queue_push_one (GstQueue * queue)
1121 {
1122   GstFlowReturn result = queue->srcresult;
1123   GstMiniObject *data;
1124
1125   data = gst_queue_locked_dequeue (queue);
1126   if (data == NULL)
1127     goto no_item;
1128
1129 next:
1130   if (GST_IS_BUFFER (data)) {
1131     GstBuffer *buffer;
1132
1133     buffer = GST_BUFFER_CAST (data);
1134
1135     if (queue->head_needs_discont) {
1136       GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
1137
1138       if (subbuffer) {
1139         buffer = subbuffer;
1140         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1141       } else {
1142         GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
1143       }
1144       queue->head_needs_discont = FALSE;
1145     }
1146
1147     GST_QUEUE_MUTEX_UNLOCK (queue);
1148     result = gst_pad_push (queue->srcpad, buffer);
1149
1150     /* need to check for srcresult here as well */
1151     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1152
1153     if (result == GST_FLOW_EOS) {
1154       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
1155       /* stop pushing buffers, we dequeue all items until we see an item that we
1156        * can push again, which is EOS or SEGMENT. If there is nothing in the
1157        * queue we can push, we set a flag to make the sinkpad refuse more
1158        * buffers with an EOS return value. */
1159       while ((data = gst_queue_locked_dequeue (queue))) {
1160         if (GST_IS_BUFFER (data)) {
1161           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1162               "dropping EOS buffer %p", data);
1163           gst_buffer_unref (GST_BUFFER_CAST (data));
1164         } else if (GST_IS_EVENT (data)) {
1165           GstEvent *event = GST_EVENT_CAST (data);
1166           GstEventType type = GST_EVENT_TYPE (event);
1167
1168           if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
1169             /* we found a pushable item in the queue, push it out */
1170             GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1171                 "pushing pushable event %s after EOS",
1172                 GST_EVENT_TYPE_NAME (event));
1173             goto next;
1174           }
1175           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1176               "dropping EOS event %p", event);
1177           gst_event_unref (event);
1178         } else if (GST_IS_QUERY (data)) {
1179           GstQuery *query = GST_QUERY_CAST (data);
1180
1181           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1182               "dropping query %p because of EOS", query);
1183           queue->last_query = FALSE;
1184           g_cond_signal (&queue->query_handled);
1185         }
1186       }
1187       /* no more items in the queue. Set the unexpected flag so that upstream
1188        * make us refuse any more buffers on the sinkpad. Since we will still
1189        * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
1190        * task function does not shut down. */
1191       queue->unexpected = TRUE;
1192       result = GST_FLOW_OK;
1193     }
1194   } else if (GST_IS_EVENT (data)) {
1195     GstEvent *event = GST_EVENT_CAST (data);
1196     GstEventType type = GST_EVENT_TYPE (event);
1197
1198     GST_QUEUE_MUTEX_UNLOCK (queue);
1199
1200     gst_pad_push_event (queue->srcpad, event);
1201
1202     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1203     /* if we're EOS, return EOS so that the task pauses. */
1204     if (type == GST_EVENT_EOS) {
1205       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1206           "pushed EOS event %p, return EOS", event);
1207       result = GST_FLOW_EOS;
1208     }
1209   } else if (GST_IS_QUERY (data)) {
1210     GstQuery *query = GST_QUERY_CAST (data);
1211     gboolean ret;
1212
1213     GST_QUEUE_MUTEX_UNLOCK (queue);
1214     ret = gst_pad_peer_query (queue->srcpad, query);
1215     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing_query);
1216     queue->last_query = ret;
1217     g_cond_signal (&queue->query_handled);
1218     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1219         "did query %p, return %d", query, queue->last_query);
1220   }
1221   return result;
1222
1223   /* ERRORS */
1224 no_item:
1225   {
1226     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1227         "exit because we have no item in the queue");
1228     return GST_FLOW_ERROR;
1229   }
1230 out_flushing:
1231   {
1232     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
1233     return GST_FLOW_FLUSHING;
1234   }
1235 out_flushing_query:
1236   {
1237     queue->last_query = FALSE;
1238     g_cond_signal (&queue->query_handled);
1239     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
1240     return GST_FLOW_FLUSHING;
1241   }
1242 }
1243
1244 static void
1245 gst_queue_loop (GstPad * pad)
1246 {
1247   GstQueue *queue;
1248   GstFlowReturn ret;
1249
1250   queue = (GstQueue *) GST_PAD_PARENT (pad);
1251
1252   /* have to lock for thread-safety */
1253   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1254
1255   while (gst_queue_is_empty (queue)) {
1256     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is empty");
1257     if (!queue->silent) {
1258       GST_QUEUE_MUTEX_UNLOCK (queue);
1259       g_signal_emit (queue, gst_queue_signals[SIGNAL_UNDERRUN], 0);
1260       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1261     }
1262
1263     /* we recheck, the signal could have changed the thresholds */
1264     while (gst_queue_is_empty (queue)) {
1265       GST_QUEUE_WAIT_ADD_CHECK (queue, out_flushing);
1266     }
1267
1268     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not empty");
1269     if (!queue->silent) {
1270       GST_QUEUE_MUTEX_UNLOCK (queue);
1271       g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
1272       g_signal_emit (queue, gst_queue_signals[SIGNAL_PUSHING], 0);
1273       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1274     }
1275   }
1276
1277   ret = gst_queue_push_one (queue);
1278   queue->srcresult = ret;
1279   if (ret != GST_FLOW_OK)
1280     goto out_flushing;
1281
1282   GST_QUEUE_MUTEX_UNLOCK (queue);
1283
1284   return;
1285
1286   /* ERRORS */
1287 out_flushing:
1288   {
1289     gboolean eos = queue->eos;
1290     GstFlowReturn ret = queue->srcresult;
1291
1292     gst_pad_pause_task (queue->srcpad);
1293     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1294         "pause task, reason:  %s", gst_flow_get_name (ret));
1295     if (ret == GST_FLOW_FLUSHING)
1296       gst_queue_locked_flush (queue, FALSE);
1297     else
1298       GST_QUEUE_SIGNAL_DEL (queue);
1299     GST_QUEUE_MUTEX_UNLOCK (queue);
1300     /* let app know about us giving up if upstream is not expected to do so */
1301     /* EOS is already taken care of elsewhere */
1302     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1303       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
1304           (_("Internal data flow error.")),
1305           ("streaming task paused, reason %s (%d)",
1306               gst_flow_get_name (ret), ret));
1307       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
1308     }
1309     return;
1310   }
1311 }
1312
1313 static gboolean
1314 gst_queue_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1315 {
1316   gboolean res = TRUE;
1317   GstQueue *queue = GST_QUEUE (parent);
1318
1319 #ifndef GST_DISABLE_GST_DEBUG
1320   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%d)",
1321       event, GST_EVENT_TYPE (event));
1322 #endif
1323
1324   switch (GST_EVENT_TYPE (event)) {
1325     case GST_EVENT_RECONFIGURE:
1326       GST_QUEUE_MUTEX_LOCK (queue);
1327       if (queue->srcresult == GST_FLOW_NOT_LINKED) {
1328         /* when we got not linked, assume downstream is linked again now and we
1329          * can try to start pushing again */
1330         queue->srcresult = GST_FLOW_OK;
1331         gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad, NULL);
1332       }
1333       GST_QUEUE_MUTEX_UNLOCK (queue);
1334
1335       res = gst_pad_push_event (queue->sinkpad, event);
1336       break;
1337     default:
1338       res = gst_pad_event_default (pad, parent, event);
1339       break;
1340   }
1341
1342
1343   return res;
1344 }
1345
1346 static gboolean
1347 gst_queue_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1348 {
1349   GstQueue *queue = GST_QUEUE (parent);
1350   gboolean res;
1351
1352   switch (GST_QUERY_TYPE (query)) {
1353     case GST_QUERY_SCHEDULING:{
1354       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
1355       res = TRUE;
1356       break;
1357     }
1358     default:
1359       res = gst_pad_query_default (pad, parent, query);
1360       break;
1361   }
1362
1363   if (!res)
1364     return FALSE;
1365
1366   /* Adjust peer response for data contained in queue */
1367   switch (GST_QUERY_TYPE (query)) {
1368     case GST_QUERY_POSITION:
1369     {
1370       gint64 peer_pos;
1371       GstFormat format;
1372
1373       /* get peer position */
1374       gst_query_parse_position (query, &format, &peer_pos);
1375
1376       /* FIXME: this code assumes that there's no discont in the queue */
1377       switch (format) {
1378         case GST_FORMAT_BYTES:
1379           peer_pos -= queue->cur_level.bytes;
1380           break;
1381         case GST_FORMAT_TIME:
1382           peer_pos -= queue->cur_level.time;
1383           break;
1384         default:
1385           GST_DEBUG_OBJECT (queue, "Can't adjust query in %s format, don't "
1386               "know how to adjust value", gst_format_get_name (format));
1387           return TRUE;
1388       }
1389       /* set updated position */
1390       gst_query_set_position (query, format, peer_pos);
1391       break;
1392     }
1393     case GST_QUERY_LATENCY:
1394     {
1395       gboolean live;
1396       GstClockTime min, max;
1397
1398       gst_query_parse_latency (query, &live, &min, &max);
1399
1400       /* we can delay up to the limit of the queue in time. If we have no time
1401        * limit, the best thing we can do is to return an infinite delay. In
1402        * reality a better estimate would be the byte/buffer rate but that is not
1403        * possible right now. */
1404       if (queue->max_size.time > 0 && max != -1)
1405         max += queue->max_size.time;
1406       else
1407         max = -1;
1408
1409       /* adjust for min-threshold */
1410       if (queue->min_threshold.time > 0 && min != -1)
1411         min += queue->min_threshold.time;
1412
1413       gst_query_set_latency (query, live, min, max);
1414       break;
1415     }
1416     default:
1417       /* peer handled other queries */
1418       break;
1419   }
1420
1421   return TRUE;
1422 }
1423
1424 static gboolean
1425 gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1426     gboolean active)
1427 {
1428   gboolean result;
1429   GstQueue *queue;
1430
1431   queue = GST_QUEUE (parent);
1432
1433   switch (mode) {
1434     case GST_PAD_MODE_PUSH:
1435       if (active) {
1436         GST_QUEUE_MUTEX_LOCK (queue);
1437         queue->srcresult = GST_FLOW_OK;
1438         queue->eos = FALSE;
1439         queue->unexpected = FALSE;
1440         GST_QUEUE_MUTEX_UNLOCK (queue);
1441       } else {
1442         /* step 1, unblock chain function */
1443         GST_QUEUE_MUTEX_LOCK (queue);
1444         queue->srcresult = GST_FLOW_FLUSHING;
1445         /* the item del signal will unblock */
1446         g_cond_signal (&queue->item_del);
1447         /* unblock query handler */
1448         queue->last_query = FALSE;
1449         g_cond_signal (&queue->query_handled);
1450         GST_QUEUE_MUTEX_UNLOCK (queue);
1451
1452         /* step 2, wait until streaming thread stopped and flush queue */
1453         GST_PAD_STREAM_LOCK (pad);
1454         GST_QUEUE_MUTEX_LOCK (queue);
1455         gst_queue_locked_flush (queue, TRUE);
1456         GST_QUEUE_MUTEX_UNLOCK (queue);
1457         GST_PAD_STREAM_UNLOCK (pad);
1458       }
1459       result = TRUE;
1460       break;
1461     default:
1462       result = FALSE;
1463       break;
1464   }
1465   return result;
1466 }
1467
1468 static gboolean
1469 gst_queue_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1470     gboolean active)
1471 {
1472   gboolean result;
1473   GstQueue *queue;
1474
1475   queue = GST_QUEUE (parent);
1476
1477   switch (mode) {
1478     case GST_PAD_MODE_PUSH:
1479       if (active) {
1480         GST_QUEUE_MUTEX_LOCK (queue);
1481         queue->srcresult = GST_FLOW_OK;
1482         queue->eos = FALSE;
1483         queue->unexpected = FALSE;
1484         result =
1485             gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad,
1486             NULL);
1487         GST_QUEUE_MUTEX_UNLOCK (queue);
1488       } else {
1489         /* step 1, unblock loop function */
1490         GST_QUEUE_MUTEX_LOCK (queue);
1491         queue->srcresult = GST_FLOW_FLUSHING;
1492         /* the item add signal will unblock */
1493         g_cond_signal (&queue->item_add);
1494         GST_QUEUE_MUTEX_UNLOCK (queue);
1495
1496         /* step 2, make sure streaming finishes */
1497         result = gst_pad_stop_task (pad);
1498       }
1499       break;
1500     default:
1501       result = FALSE;
1502       break;
1503   }
1504   return result;
1505 }
1506
1507 static void
1508 queue_capacity_change (GstQueue * queue)
1509 {
1510   if (queue->leaky == GST_QUEUE_LEAK_DOWNSTREAM) {
1511     gst_queue_leak_downstream (queue);
1512   }
1513
1514   /* changing the capacity of the queue must wake up
1515    * the _chain function, it might have more room now
1516    * to store the buffer/event in the queue */
1517   GST_QUEUE_SIGNAL_DEL (queue);
1518 }
1519
1520 /* Changing the minimum required fill level must
1521  * wake up the _loop function as it might now
1522  * be able to preceed.
1523  */
1524 #define QUEUE_THRESHOLD_CHANGE(q)\
1525   GST_QUEUE_SIGNAL_ADD (q);
1526
1527 static void
1528 gst_queue_set_property (GObject * object,
1529     guint prop_id, const GValue * value, GParamSpec * pspec)
1530 {
1531   GstQueue *queue = GST_QUEUE (object);
1532
1533   /* someone could change levels here, and since this
1534    * affects the get/put funcs, we need to lock for safety. */
1535   GST_QUEUE_MUTEX_LOCK (queue);
1536
1537   switch (prop_id) {
1538     case PROP_MAX_SIZE_BYTES:
1539       queue->max_size.bytes = g_value_get_uint (value);
1540       queue_capacity_change (queue);
1541       break;
1542     case PROP_MAX_SIZE_BUFFERS:
1543       queue->max_size.buffers = g_value_get_uint (value);
1544       queue_capacity_change (queue);
1545       break;
1546     case PROP_MAX_SIZE_TIME:
1547       queue->max_size.time = g_value_get_uint64 (value);
1548       queue_capacity_change (queue);
1549       break;
1550     case PROP_MIN_THRESHOLD_BYTES:
1551       queue->min_threshold.bytes = g_value_get_uint (value);
1552       queue->orig_min_threshold.bytes = queue->min_threshold.bytes;
1553       QUEUE_THRESHOLD_CHANGE (queue);
1554       break;
1555     case PROP_MIN_THRESHOLD_BUFFERS:
1556       queue->min_threshold.buffers = g_value_get_uint (value);
1557       queue->orig_min_threshold.buffers = queue->min_threshold.buffers;
1558       QUEUE_THRESHOLD_CHANGE (queue);
1559       break;
1560     case PROP_MIN_THRESHOLD_TIME:
1561       queue->min_threshold.time = g_value_get_uint64 (value);
1562       queue->orig_min_threshold.time = queue->min_threshold.time;
1563       QUEUE_THRESHOLD_CHANGE (queue);
1564       break;
1565     case PROP_LEAKY:
1566       queue->leaky = g_value_get_enum (value);
1567       break;
1568     case PROP_SILENT:
1569       queue->silent = g_value_get_boolean (value);
1570       break;
1571     case PROP_FLUSH_ON_EOS:
1572       queue->flush_on_eos = g_value_get_boolean (value);
1573       break;
1574     default:
1575       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1576       break;
1577   }
1578
1579   GST_QUEUE_MUTEX_UNLOCK (queue);
1580 }
1581
1582 static void
1583 gst_queue_get_property (GObject * object,
1584     guint prop_id, GValue * value, GParamSpec * pspec)
1585 {
1586   GstQueue *queue = GST_QUEUE (object);
1587
1588   GST_QUEUE_MUTEX_LOCK (queue);
1589
1590   switch (prop_id) {
1591     case PROP_CUR_LEVEL_BYTES:
1592       g_value_set_uint (value, queue->cur_level.bytes);
1593       break;
1594     case PROP_CUR_LEVEL_BUFFERS:
1595       g_value_set_uint (value, queue->cur_level.buffers);
1596       break;
1597     case PROP_CUR_LEVEL_TIME:
1598       g_value_set_uint64 (value, queue->cur_level.time);
1599       break;
1600     case PROP_MAX_SIZE_BYTES:
1601       g_value_set_uint (value, queue->max_size.bytes);
1602       break;
1603     case PROP_MAX_SIZE_BUFFERS:
1604       g_value_set_uint (value, queue->max_size.buffers);
1605       break;
1606     case PROP_MAX_SIZE_TIME:
1607       g_value_set_uint64 (value, queue->max_size.time);
1608       break;
1609     case PROP_MIN_THRESHOLD_BYTES:
1610       g_value_set_uint (value, queue->min_threshold.bytes);
1611       break;
1612     case PROP_MIN_THRESHOLD_BUFFERS:
1613       g_value_set_uint (value, queue->min_threshold.buffers);
1614       break;
1615     case PROP_MIN_THRESHOLD_TIME:
1616       g_value_set_uint64 (value, queue->min_threshold.time);
1617       break;
1618     case PROP_LEAKY:
1619       g_value_set_enum (value, queue->leaky);
1620       break;
1621     case PROP_SILENT:
1622       g_value_set_boolean (value, queue->silent);
1623       break;
1624     case PROP_FLUSH_ON_EOS:
1625       g_value_set_boolean (value, queue->flush_on_eos);
1626       break;
1627     default:
1628       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1629       break;
1630   }
1631
1632   GST_QUEUE_MUTEX_UNLOCK (queue);
1633 }