queue2: fix crash deleting current region for small ring buffers
[platform/upstream/gstreamer.git] / plugins / elements / gstqueue2.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2003 Colin Walters <cwalters@gnome.org>
4  *                    2000,2005,2007 Wim Taymans <wim.taymans@gmail.com>
5  *                    2007 Thiago Sousa Santos <thiagoss@lcc.ufcg.edu.br>
6  *                 SA 2010 ST-Ericsson <benjamin.gaignard@stericsson.com>
7  *
8  * gstqueue2.c:
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 /**
27  * SECTION:element-queue2
28  *
29  * Data is queued until one of the limits specified by the
30  * #GstQueue2:max-size-buffers, #GstQueue2:max-size-bytes and/or
31  * #GstQueue2:max-size-time properties has been reached. Any attempt to push
32  * more buffers into the queue will block the pushing thread until more space
33  * becomes available.
34  *
35  * The queue will create a new thread on the source pad to decouple the
36  * processing on sink and source pad.
37  *
38  * You can query how many buffers are queued by reading the
39  * #GstQueue2:current-level-buffers property.
40  *
41  * The default queue size limits are 100 buffers, 2MB of data, or
42  * two seconds worth of data, whichever is reached first.
43  *
44  * If you set temp-template to a value such as /tmp/gstreamer-XXXXXX, the element
45  * will allocate a random free filename and buffer data in the file.
46  * By using this, it will buffer the entire stream data on the file independently
47  * of the queue size limits, they will only be used for buffering statistics.
48  *
49  * The temp-location property will be used to notify the application of the
50  * allocated filename.
51  */
52
53 #ifdef HAVE_CONFIG_H
54 #include "config.h"
55 #endif
56
57 #include "gstqueue2.h"
58
59 #include <glib/gstdio.h>
60
61 #include "gst/gst-i18n-lib.h"
62 #include "gst/glib-compat-private.h"
63
64 #include <string.h>
65
66 #ifdef G_OS_WIN32
67 #include <io.h>                 /* lseek, open, close, read */
68 #undef lseek
69 #define lseek _lseeki64
70 #undef off_t
71 #define off_t guint64
72 #else
73 #include <unistd.h>
74 #endif
75
76 #ifdef __BIONIC__               /* Android */
77 #undef lseek
78 #define lseek lseek64
79 #undef off_t
80 #define off_t guint64
81 #include <fcntl.h>
82 #endif
83
84 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
85     GST_PAD_SINK,
86     GST_PAD_ALWAYS,
87     GST_STATIC_CAPS_ANY);
88
89 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
90     GST_PAD_SRC,
91     GST_PAD_ALWAYS,
92     GST_STATIC_CAPS_ANY);
93
94 GST_DEBUG_CATEGORY_STATIC (queue_debug);
95 #define GST_CAT_DEFAULT (queue_debug)
96 GST_DEBUG_CATEGORY_STATIC (queue_dataflow);
97
98 enum
99 {
100   LAST_SIGNAL
101 };
102
103 /* other defines */
104 #define DEFAULT_BUFFER_SIZE 4096
105 #define QUEUE_IS_USING_TEMP_FILE(queue) ((queue)->temp_template != NULL)
106 #define QUEUE_IS_USING_RING_BUFFER(queue) ((queue)->ring_buffer_max_size != 0)  /* for consistency with the above macro */
107 #define QUEUE_IS_USING_QUEUE(queue) (!QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER (queue))
108
109 #define QUEUE_MAX_BYTES(queue) MIN((queue)->max_level.bytes, (queue)->ring_buffer_max_size)
110
111 /* default property values */
112 #define DEFAULT_MAX_SIZE_BUFFERS   100  /* 100 buffers */
113 #define DEFAULT_MAX_SIZE_BYTES     (2 * 1024 * 1024)    /* 2 MB */
114 #define DEFAULT_MAX_SIZE_TIME      2 * GST_SECOND       /* 2 seconds */
115 #define DEFAULT_USE_BUFFERING      FALSE
116 #define DEFAULT_USE_TAGS_BITRATE   FALSE
117 #define DEFAULT_USE_RATE_ESTIMATE  TRUE
118 #define DEFAULT_LOW_PERCENT        10
119 #define DEFAULT_HIGH_PERCENT       99
120 #define DEFAULT_TEMP_REMOVE        TRUE
121 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
122
123 enum
124 {
125   PROP_0,
126   PROP_CUR_LEVEL_BUFFERS,
127   PROP_CUR_LEVEL_BYTES,
128   PROP_CUR_LEVEL_TIME,
129   PROP_MAX_SIZE_BUFFERS,
130   PROP_MAX_SIZE_BYTES,
131   PROP_MAX_SIZE_TIME,
132   PROP_USE_BUFFERING,
133   PROP_USE_TAGS_BITRATE,
134   PROP_USE_RATE_ESTIMATE,
135   PROP_LOW_PERCENT,
136   PROP_HIGH_PERCENT,
137   PROP_TEMP_TEMPLATE,
138   PROP_TEMP_LOCATION,
139   PROP_TEMP_REMOVE,
140   PROP_RING_BUFFER_MAX_SIZE,
141   PROP_AVG_IN_RATE,
142   PROP_LAST
143 };
144
145 #define GST_QUEUE2_CLEAR_LEVEL(l) G_STMT_START {         \
146   l.buffers = 0;                                        \
147   l.bytes = 0;                                          \
148   l.time = 0;                                           \
149   l.rate_time = 0;                                      \
150 } G_STMT_END
151
152 #define STATUS(queue, pad, msg) \
153   GST_CAT_LOG_OBJECT (queue_dataflow, queue, \
154                       "(%s:%s) " msg ": %u of %u buffers, %u of %u " \
155                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
156                       " ns, %"G_GUINT64_FORMAT" items", \
157                       GST_DEBUG_PAD_NAME (pad), \
158                       queue->cur_level.buffers, \
159                       queue->max_level.buffers, \
160                       queue->cur_level.bytes, \
161                       queue->max_level.bytes, \
162                       queue->cur_level.time, \
163                       queue->max_level.time, \
164                       (guint64) (!QUEUE_IS_USING_QUEUE(queue) ? \
165                         queue->current->writing_pos - queue->current->max_reading_pos : \
166                         queue->queue.length))
167
168 #define GST_QUEUE2_MUTEX_LOCK(q) G_STMT_START {                          \
169   g_mutex_lock (&q->qlock);                                              \
170 } G_STMT_END
171
172 #define GST_QUEUE2_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
173   GST_QUEUE2_MUTEX_LOCK (q);                                            \
174   if (res != GST_FLOW_OK)                                               \
175     goto label;                                                         \
176 } G_STMT_END
177
178 #define GST_QUEUE2_MUTEX_UNLOCK(q) G_STMT_START {                        \
179   g_mutex_unlock (&q->qlock);                                            \
180 } G_STMT_END
181
182 #define GST_QUEUE2_WAIT_DEL_CHECK(q, res, label) G_STMT_START {         \
183   STATUS (queue, q->sinkpad, "wait for DEL");                           \
184   q->waiting_del = TRUE;                                                \
185   g_cond_wait (&q->item_del, &queue->qlock);                              \
186   q->waiting_del = FALSE;                                               \
187   if (res != GST_FLOW_OK) {                                             \
188     STATUS (queue, q->srcpad, "received DEL wakeup");                   \
189     goto label;                                                         \
190   }                                                                     \
191   STATUS (queue, q->sinkpad, "received DEL");                           \
192 } G_STMT_END
193
194 #define GST_QUEUE2_WAIT_ADD_CHECK(q, res, label) G_STMT_START {         \
195   STATUS (queue, q->srcpad, "wait for ADD");                            \
196   q->waiting_add = TRUE;                                                \
197   g_cond_wait (&q->item_add, &q->qlock);                                  \
198   q->waiting_add = FALSE;                                               \
199   if (res != GST_FLOW_OK) {                                             \
200     STATUS (queue, q->srcpad, "received ADD wakeup");                   \
201     goto label;                                                         \
202   }                                                                     \
203   STATUS (queue, q->srcpad, "received ADD");                            \
204 } G_STMT_END
205
206 #define GST_QUEUE2_SIGNAL_DEL(q) G_STMT_START {                          \
207   if (q->waiting_del) {                                                 \
208     STATUS (q, q->srcpad, "signal DEL");                                \
209     g_cond_signal (&q->item_del);                                        \
210   }                                                                     \
211 } G_STMT_END
212
213 #define GST_QUEUE2_SIGNAL_ADD(q) G_STMT_START {                          \
214   if (q->waiting_add) {                                                 \
215     STATUS (q, q->sinkpad, "signal ADD");                               \
216     g_cond_signal (&q->item_add);                                        \
217   }                                                                     \
218 } G_STMT_END
219
220 #define SET_PERCENT(q, perc) G_STMT_START {                              \
221   if (perc != q->buffering_percent) {                                    \
222     q->buffering_percent = perc;                                         \
223     q->percent_changed = TRUE;                                           \
224     GST_DEBUG_OBJECT (q, "buffering %d percent", perc);                  \
225     get_buffering_stats (q, perc, &q->mode, &q->avg_in, &q->avg_out,     \
226         &q->buffering_left);                                             \
227   }                                                                      \
228 } G_STMT_END
229
230 #define _do_init \
231     GST_DEBUG_CATEGORY_INIT (queue_debug, "queue2", 0, "queue element"); \
232     GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue2_dataflow", 0, \
233         "dataflow inside the queue element");
234 #define gst_queue2_parent_class parent_class
235 G_DEFINE_TYPE_WITH_CODE (GstQueue2, gst_queue2, GST_TYPE_ELEMENT, _do_init);
236
237 static void gst_queue2_finalize (GObject * object);
238
239 static void gst_queue2_set_property (GObject * object,
240     guint prop_id, const GValue * value, GParamSpec * pspec);
241 static void gst_queue2_get_property (GObject * object,
242     guint prop_id, GValue * value, GParamSpec * pspec);
243
244 static GstFlowReturn gst_queue2_chain (GstPad * pad, GstObject * parent,
245     GstBuffer * buffer);
246 static GstFlowReturn gst_queue2_chain_list (GstPad * pad, GstObject * parent,
247     GstBufferList * buffer_list);
248 static GstFlowReturn gst_queue2_push_one (GstQueue2 * queue);
249 static void gst_queue2_loop (GstPad * pad);
250
251 static gboolean gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
252     GstEvent * event);
253 static gboolean gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
254     GstQuery * query);
255
256 static gboolean gst_queue2_handle_src_event (GstPad * pad, GstObject * parent,
257     GstEvent * event);
258 static gboolean gst_queue2_handle_src_query (GstPad * pad, GstObject * parent,
259     GstQuery * query);
260 static gboolean gst_queue2_handle_query (GstElement * element,
261     GstQuery * query);
262
263 static GstFlowReturn gst_queue2_get_range (GstPad * pad, GstObject * parent,
264     guint64 offset, guint length, GstBuffer ** buffer);
265
266 static gboolean gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent,
267     GstPadMode mode, gboolean active);
268 static gboolean gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
269     GstPadMode mode, gboolean active);
270 static GstStateChangeReturn gst_queue2_change_state (GstElement * element,
271     GstStateChange transition);
272
273 static gboolean gst_queue2_is_empty (GstQueue2 * queue);
274 static gboolean gst_queue2_is_filled (GstQueue2 * queue);
275
276 static void update_cur_level (GstQueue2 * queue, GstQueue2Range * range);
277 static void update_in_rates (GstQueue2 * queue);
278 static void gst_queue2_post_buffering (GstQueue2 * queue);
279
280 typedef enum
281 {
282   GST_QUEUE2_ITEM_TYPE_UNKNOWN = 0,
283   GST_QUEUE2_ITEM_TYPE_BUFFER,
284   GST_QUEUE2_ITEM_TYPE_BUFFER_LIST,
285   GST_QUEUE2_ITEM_TYPE_EVENT,
286   GST_QUEUE2_ITEM_TYPE_QUERY
287 } GstQueue2ItemType;
288
289 typedef struct
290 {
291   GstQueue2ItemType type;
292   GstMiniObject *item;
293 } GstQueue2Item;
294
295 /* static guint gst_queue2_signals[LAST_SIGNAL] = { 0 }; */
296
297 static void
298 gst_queue2_class_init (GstQueue2Class * klass)
299 {
300   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
301   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
302
303   gobject_class->set_property = gst_queue2_set_property;
304   gobject_class->get_property = gst_queue2_get_property;
305
306   /* properties */
307   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
308       g_param_spec_uint ("current-level-bytes", "Current level (kB)",
309           "Current amount of data in the queue (bytes)",
310           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
311   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
312       g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
313           "Current number of buffers in the queue",
314           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
315   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
316       g_param_spec_uint64 ("current-level-time", "Current level (ns)",
317           "Current amount of data in the queue (in ns)",
318           0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
319
320   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
321       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
322           "Max. amount of data in the queue (bytes, 0=disable)",
323           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
324           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
325           G_PARAM_STATIC_STRINGS));
326   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
327       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
328           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
329           DEFAULT_MAX_SIZE_BUFFERS,
330           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
331           G_PARAM_STATIC_STRINGS));
332   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
333       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
334           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
335           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
336           G_PARAM_STATIC_STRINGS));
337
338   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
339       g_param_spec_boolean ("use-buffering", "Use buffering",
340           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
341           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
342           G_PARAM_STATIC_STRINGS));
343   g_object_class_install_property (gobject_class, PROP_USE_TAGS_BITRATE,
344       g_param_spec_boolean ("use-tags-bitrate", "Use bitrate from tags",
345           "Use a bitrate from upstream tags to estimate buffer duration if not provided",
346           DEFAULT_USE_TAGS_BITRATE,
347           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
348           G_PARAM_STATIC_STRINGS));
349   g_object_class_install_property (gobject_class, PROP_USE_RATE_ESTIMATE,
350       g_param_spec_boolean ("use-rate-estimate", "Use Rate Estimate",
351           "Estimate the bitrate of the stream to calculate time level",
352           DEFAULT_USE_RATE_ESTIMATE,
353           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
354   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
355       g_param_spec_int ("low-percent", "Low percent",
356           "Low threshold for buffering to start. Only used if use-buffering is True",
357           0, 100, DEFAULT_LOW_PERCENT,
358           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
359   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
360       g_param_spec_int ("high-percent", "High percent",
361           "High threshold for buffering to finish. Only used if use-buffering is True",
362           0, 100, DEFAULT_HIGH_PERCENT,
363           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
364
365   g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
366       g_param_spec_string ("temp-template", "Temporary File Template",
367           "File template to store temporary files in, should contain directory "
368           "and XXXXXX. (NULL == disabled)",
369           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
370
371   g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
372       g_param_spec_string ("temp-location", "Temporary File Location",
373           "Location to store temporary files in (Only read this property, "
374           "use temp-template to configure the name template)",
375           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
376
377   /**
378    * GstQueue2:temp-remove
379    *
380    * When temp-template is set, remove the temporary file when going to READY.
381    */
382   g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
383       g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
384           "Remove the temp-location after use",
385           DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
386
387   /**
388    * GstQueue2:ring-buffer-max-size
389    *
390    * The maximum size of the ring buffer in bytes. If set to 0, the ring
391    * buffer is disabled. Default 0.
392    */
393   g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
394       g_param_spec_uint64 ("ring-buffer-max-size",
395           "Max. ring buffer size (bytes)",
396           "Max. amount of data in the ring buffer (bytes, 0 = disabled)",
397           0, G_MAXUINT64, DEFAULT_RING_BUFFER_MAX_SIZE,
398           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
399
400   /**
401    * GstQueue2:avg-in-rate
402    *
403    * The average input data rate.
404    */
405   g_object_class_install_property (gobject_class, PROP_AVG_IN_RATE,
406       g_param_spec_int64 ("avg-in-rate", "Input data rate (bytes/s)",
407           "Average input data rate (bytes/s)",
408           0, G_MAXINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
409
410   /* set several parent class virtual functions */
411   gobject_class->finalize = gst_queue2_finalize;
412
413   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
414   gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
415
416   gst_element_class_set_static_metadata (gstelement_class, "Queue 2",
417       "Generic",
418       "Simple data queue",
419       "Erik Walthinsen <omega@cse.ogi.edu>, "
420       "Wim Taymans <wim.taymans@gmail.com>");
421
422   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_queue2_change_state);
423   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_queue2_handle_query);
424 }
425
426 static void
427 gst_queue2_init (GstQueue2 * queue)
428 {
429   queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
430
431   gst_pad_set_chain_function (queue->sinkpad,
432       GST_DEBUG_FUNCPTR (gst_queue2_chain));
433   gst_pad_set_chain_list_function (queue->sinkpad,
434       GST_DEBUG_FUNCPTR (gst_queue2_chain_list));
435   gst_pad_set_activatemode_function (queue->sinkpad,
436       GST_DEBUG_FUNCPTR (gst_queue2_sink_activate_mode));
437   gst_pad_set_event_function (queue->sinkpad,
438       GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_event));
439   gst_pad_set_query_function (queue->sinkpad,
440       GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_query));
441   GST_PAD_SET_PROXY_CAPS (queue->sinkpad);
442   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
443
444   queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
445
446   gst_pad_set_activatemode_function (queue->srcpad,
447       GST_DEBUG_FUNCPTR (gst_queue2_src_activate_mode));
448   gst_pad_set_getrange_function (queue->srcpad,
449       GST_DEBUG_FUNCPTR (gst_queue2_get_range));
450   gst_pad_set_event_function (queue->srcpad,
451       GST_DEBUG_FUNCPTR (gst_queue2_handle_src_event));
452   gst_pad_set_query_function (queue->srcpad,
453       GST_DEBUG_FUNCPTR (gst_queue2_handle_src_query));
454   GST_PAD_SET_PROXY_CAPS (queue->srcpad);
455   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
456
457   /* levels */
458   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
459   queue->max_level.buffers = DEFAULT_MAX_SIZE_BUFFERS;
460   queue->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
461   queue->max_level.time = DEFAULT_MAX_SIZE_TIME;
462   queue->max_level.rate_time = DEFAULT_MAX_SIZE_TIME;
463   queue->use_buffering = DEFAULT_USE_BUFFERING;
464   queue->use_rate_estimate = DEFAULT_USE_RATE_ESTIMATE;
465   queue->low_percent = DEFAULT_LOW_PERCENT;
466   queue->high_percent = DEFAULT_HIGH_PERCENT;
467
468   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
469   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
470
471   queue->sinktime = GST_CLOCK_TIME_NONE;
472   queue->srctime = GST_CLOCK_TIME_NONE;
473   queue->sink_tainted = TRUE;
474   queue->src_tainted = TRUE;
475
476   queue->srcresult = GST_FLOW_FLUSHING;
477   queue->sinkresult = GST_FLOW_FLUSHING;
478   queue->is_eos = FALSE;
479   queue->in_timer = g_timer_new ();
480   queue->out_timer = g_timer_new ();
481
482   g_mutex_init (&queue->qlock);
483   queue->waiting_add = FALSE;
484   g_cond_init (&queue->item_add);
485   queue->waiting_del = FALSE;
486   g_cond_init (&queue->item_del);
487   g_queue_init (&queue->queue);
488
489   g_cond_init (&queue->query_handled);
490   queue->last_query = FALSE;
491
492   g_mutex_init (&queue->buffering_post_lock);
493   queue->buffering_percent = 100;
494
495   /* tempfile related */
496   queue->temp_template = NULL;
497   queue->temp_location = NULL;
498   queue->temp_remove = DEFAULT_TEMP_REMOVE;
499
500   queue->ring_buffer = NULL;
501   queue->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
502
503   GST_DEBUG_OBJECT (queue,
504       "initialized queue's not_empty & not_full conditions");
505 }
506
507 /* called only once, as opposed to dispose */
508 static void
509 gst_queue2_finalize (GObject * object)
510 {
511   GstQueue2 *queue = GST_QUEUE2 (object);
512
513   GST_DEBUG_OBJECT (queue, "finalizing queue");
514
515   while (!g_queue_is_empty (&queue->queue)) {
516     GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
517
518     if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
519       gst_mini_object_unref (qitem->item);
520     g_slice_free (GstQueue2Item, qitem);
521   }
522
523   queue->last_query = FALSE;
524   g_queue_clear (&queue->queue);
525   g_mutex_clear (&queue->qlock);
526   g_mutex_clear (&queue->buffering_post_lock);
527   g_cond_clear (&queue->item_add);
528   g_cond_clear (&queue->item_del);
529   g_cond_clear (&queue->query_handled);
530   g_timer_destroy (queue->in_timer);
531   g_timer_destroy (queue->out_timer);
532
533   /* temp_file path cleanup  */
534   g_free (queue->temp_template);
535   g_free (queue->temp_location);
536
537   G_OBJECT_CLASS (parent_class)->finalize (object);
538 }
539
540 static void
541 debug_ranges (GstQueue2 * queue)
542 {
543   GstQueue2Range *walk;
544
545   for (walk = queue->ranges; walk; walk = walk->next) {
546     GST_DEBUG_OBJECT (queue,
547         "range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "] (rb [%"
548         G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "]), reading %" G_GUINT64_FORMAT
549         " current range? %s", walk->offset, walk->writing_pos, walk->rb_offset,
550         walk->rb_writing_pos, walk->reading_pos,
551         walk == queue->current ? "**y**" : "  n  ");
552   }
553 }
554
555 /* clear all the downloaded ranges */
556 static void
557 clean_ranges (GstQueue2 * queue)
558 {
559   GST_DEBUG_OBJECT (queue, "clean queue ranges");
560
561   g_slice_free_chain (GstQueue2Range, queue->ranges, next);
562   queue->ranges = NULL;
563   queue->current = NULL;
564 }
565
566 /* find a range that contains @offset or NULL when nothing does */
567 static GstQueue2Range *
568 find_range (GstQueue2 * queue, guint64 offset)
569 {
570   GstQueue2Range *range = NULL;
571   GstQueue2Range *walk;
572
573   /* first do a quick check for the current range */
574   for (walk = queue->ranges; walk; walk = walk->next) {
575     if (offset >= walk->offset && offset <= walk->writing_pos) {
576       /* we can reuse an existing range */
577       range = walk;
578       break;
579     }
580   }
581   if (range) {
582     GST_DEBUG_OBJECT (queue,
583         "found range for %" G_GUINT64_FORMAT ": [%" G_GUINT64_FORMAT "-%"
584         G_GUINT64_FORMAT "]", offset, range->offset, range->writing_pos);
585   } else {
586     GST_DEBUG_OBJECT (queue, "no range for %" G_GUINT64_FORMAT, offset);
587   }
588   return range;
589 }
590
591 static void
592 update_cur_level (GstQueue2 * queue, GstQueue2Range * range)
593 {
594   guint64 max_reading_pos, writing_pos;
595
596   writing_pos = range->writing_pos;
597   max_reading_pos = range->max_reading_pos;
598
599   if (writing_pos > max_reading_pos)
600     queue->cur_level.bytes = writing_pos - max_reading_pos;
601   else
602     queue->cur_level.bytes = 0;
603 }
604
605 /* make a new range for @offset or reuse an existing range */
606 static GstQueue2Range *
607 add_range (GstQueue2 * queue, guint64 offset, gboolean update_existing)
608 {
609   GstQueue2Range *range, *prev, *next;
610
611   GST_DEBUG_OBJECT (queue, "find range for %" G_GUINT64_FORMAT, offset);
612
613   if ((range = find_range (queue, offset))) {
614     GST_DEBUG_OBJECT (queue,
615         "reusing range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, range->offset,
616         range->writing_pos);
617     if (update_existing && range->writing_pos != offset) {
618       GST_DEBUG_OBJECT (queue, "updating range writing position to "
619           "%" G_GUINT64_FORMAT, offset);
620       range->writing_pos = offset;
621     }
622   } else {
623     GST_DEBUG_OBJECT (queue,
624         "new range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, offset);
625
626     range = g_slice_new0 (GstQueue2Range);
627     range->offset = offset;
628     /* we want to write to the next location in the ring buffer */
629     range->rb_offset = queue->current ? queue->current->rb_writing_pos : 0;
630     range->writing_pos = offset;
631     range->rb_writing_pos = range->rb_offset;
632     range->reading_pos = offset;
633     range->max_reading_pos = offset;
634
635     /* insert sorted */
636     prev = NULL;
637     next = queue->ranges;
638     while (next) {
639       if (next->offset > offset) {
640         /* insert before next */
641         GST_DEBUG_OBJECT (queue,
642             "insert before range %p, offset %" G_GUINT64_FORMAT, next,
643             next->offset);
644         break;
645       }
646       /* try next */
647       prev = next;
648       next = next->next;
649     }
650     range->next = next;
651     if (prev)
652       prev->next = range;
653     else
654       queue->ranges = range;
655   }
656   debug_ranges (queue);
657
658   /* update the stats for this range */
659   update_cur_level (queue, range);
660
661   return range;
662 }
663
664
665 /* clear and init the download ranges for offset 0 */
666 static void
667 init_ranges (GstQueue2 * queue)
668 {
669   GST_DEBUG_OBJECT (queue, "init queue ranges");
670
671   /* get rid of all the current ranges */
672   clean_ranges (queue);
673   /* make a range for offset 0 */
674   queue->current = add_range (queue, 0, TRUE);
675 }
676
677 /* calculate the diff between running time on the sink and src of the queue.
678  * This is the total amount of time in the queue. */
679 static void
680 update_time_level (GstQueue2 * queue)
681 {
682   if (queue->sink_tainted) {
683     queue->sinktime =
684         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
685         queue->sink_segment.position);
686     queue->sink_tainted = FALSE;
687   }
688
689   if (queue->src_tainted) {
690     queue->srctime =
691         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
692         queue->src_segment.position);
693     queue->src_tainted = FALSE;
694   }
695
696   GST_DEBUG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
697       GST_TIME_ARGS (queue->sinktime), GST_TIME_ARGS (queue->srctime));
698
699   if (queue->sinktime != GST_CLOCK_TIME_NONE
700       && queue->srctime != GST_CLOCK_TIME_NONE
701       && queue->sinktime >= queue->srctime)
702     queue->cur_level.time = queue->sinktime - queue->srctime;
703   else
704     queue->cur_level.time = 0;
705 }
706
707 /* take a SEGMENT event and apply the values to segment, updating the time
708  * level of queue. */
709 static void
710 apply_segment (GstQueue2 * queue, GstEvent * event, GstSegment * segment,
711     gboolean is_sink)
712 {
713   gst_event_copy_segment (event, segment);
714
715   if (segment->format == GST_FORMAT_BYTES) {
716     if (!QUEUE_IS_USING_QUEUE (queue) && is_sink) {
717       /* start is where we'll be getting from and as such writing next */
718       queue->current = add_range (queue, segment->start, TRUE);
719     }
720   }
721
722   /* now configure the values, we use these to track timestamps on the
723    * sinkpad. */
724   if (segment->format != GST_FORMAT_TIME) {
725     /* non-time format, pretend the current time segment is closed with a
726      * 0 start and unknown stop time. */
727     segment->format = GST_FORMAT_TIME;
728     segment->start = 0;
729     segment->stop = -1;
730     segment->time = 0;
731   }
732
733   GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
734
735   if (is_sink)
736     queue->sink_tainted = TRUE;
737   else
738     queue->src_tainted = TRUE;
739
740   /* segment can update the time level of the queue */
741   update_time_level (queue);
742 }
743
744 static void
745 apply_gap (GstQueue2 * queue, GstEvent * event,
746     GstSegment * segment, gboolean is_sink)
747 {
748   GstClockTime timestamp;
749   GstClockTime duration;
750
751   gst_event_parse_gap (event, &timestamp, &duration);
752
753   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
754
755     if (GST_CLOCK_TIME_IS_VALID (duration)) {
756       timestamp += duration;
757     }
758
759     segment->position = timestamp;
760
761     if (is_sink)
762       queue->sink_tainted = TRUE;
763     else
764       queue->src_tainted = TRUE;
765
766     /* calc diff with other end */
767     update_time_level (queue);
768   }
769 }
770
771 /* take a buffer and update segment, updating the time level of the queue. */
772 static void
773 apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
774     guint64 size, gboolean is_sink)
775 {
776   GstClockTime duration, timestamp;
777
778   timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
779   duration = GST_BUFFER_DURATION (buffer);
780
781   /* If we have no duration, pick one from the bitrate if we can */
782   if (duration == GST_CLOCK_TIME_NONE && queue->use_tags_bitrate) {
783     guint bitrate =
784         is_sink ? queue->sink_tags_bitrate : queue->src_tags_bitrate;
785     if (bitrate)
786       duration = gst_util_uint64_scale (size, 8 * GST_SECOND, bitrate);
787   }
788
789   /* if no timestamp is set, assume it's continuous with the previous
790    * time */
791   if (timestamp == GST_CLOCK_TIME_NONE)
792     timestamp = segment->position;
793
794   /* add duration */
795   if (duration != GST_CLOCK_TIME_NONE)
796     timestamp += duration;
797
798   GST_DEBUG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
799       GST_TIME_ARGS (timestamp));
800
801   segment->position = timestamp;
802
803   if (is_sink)
804     queue->sink_tainted = TRUE;
805   else
806     queue->src_tainted = TRUE;
807
808   /* calc diff with other end */
809   update_time_level (queue);
810 }
811
812 struct BufListData
813 {
814   GstClockTime timestamp;
815   guint bitrate;
816 };
817
818 static gboolean
819 buffer_list_apply_time (GstBuffer ** buf, guint idx, gpointer data)
820 {
821   struct BufListData *bld = data;
822   GstClockTime *timestamp = &bld->timestamp;
823   GstClockTime btime;
824
825   GST_TRACE ("buffer %u has pts %" GST_TIME_FORMAT " dts %" GST_TIME_FORMAT
826       " duration %" GST_TIME_FORMAT, idx,
827       GST_TIME_ARGS (GST_BUFFER_PTS (*buf)),
828       GST_TIME_ARGS (GST_BUFFER_DTS (*buf)),
829       GST_TIME_ARGS (GST_BUFFER_DURATION (*buf)));
830
831   btime = GST_BUFFER_DTS_OR_PTS (*buf);
832   if (GST_CLOCK_TIME_IS_VALID (btime))
833     *timestamp = btime;
834
835   if (GST_BUFFER_DURATION_IS_VALID (*buf))
836     *timestamp += GST_BUFFER_DURATION (*buf);
837   else if (bld->bitrate != 0) {
838     guint64 size = gst_buffer_get_size (*buf);
839
840     /* If we have no duration, pick one from the bitrate if we can */
841     *timestamp += gst_util_uint64_scale (bld->bitrate, 8 * GST_SECOND, size);
842   }
843
844
845   GST_TRACE ("ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (*timestamp));
846   return TRUE;
847 }
848
849 /* take a buffer list and update segment, updating the time level of the queue */
850 static void
851 apply_buffer_list (GstQueue2 * queue, GstBufferList * buffer_list,
852     GstSegment * segment, gboolean is_sink)
853 {
854   struct BufListData bld;
855
856   /* if no timestamp is set, assume it's continuous with the previous time */
857   bld.timestamp = segment->position;
858
859   if (queue->use_tags_bitrate) {
860     if (is_sink)
861       bld.bitrate = queue->sink_tags_bitrate;
862     else
863       bld.bitrate = queue->src_tags_bitrate;
864   } else
865     bld.bitrate = 0;
866
867   gst_buffer_list_foreach (buffer_list, buffer_list_apply_time, &bld);
868
869   GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
870       GST_TIME_ARGS (bld.timestamp));
871
872   segment->position = bld.timestamp;
873
874   if (is_sink)
875     queue->sink_tainted = TRUE;
876   else
877     queue->src_tainted = TRUE;
878
879   /* calc diff with other end */
880   update_time_level (queue);
881 }
882
883 static inline gint
884 get_percent (guint64 cur_level, guint64 max_level, guint64 alt_max)
885 {
886   guint64 p;
887
888   if (max_level == 0)
889     return 0;
890
891   if (alt_max > 0)
892     p = gst_util_uint64_scale (cur_level, 100, MIN (max_level, alt_max));
893   else
894     p = gst_util_uint64_scale (cur_level, 100, max_level);
895
896   return MIN (p, 100);
897 }
898
899 static gboolean
900 get_buffering_percent (GstQueue2 * queue, gboolean * is_buffering,
901     gint * percent)
902 {
903   gint perc, perc2;
904
905   if (queue->high_percent <= 0) {
906     if (percent)
907       *percent = 100;
908     if (is_buffering)
909       *is_buffering = FALSE;
910     return FALSE;
911   }
912 #define GET_PERCENT(format,alt_max) \
913     get_percent(queue->cur_level.format,queue->max_level.format,(alt_max))
914
915   if (queue->is_eos) {
916     /* on EOS we are always 100% full, we set the var here so that it we can
917      * reuse the logic below to stop buffering */
918     perc = 100;
919     GST_LOG_OBJECT (queue, "we are EOS");
920   } else {
921     GST_LOG_OBJECT (queue,
922         "Cur level bytes/time/buffers %u/%" GST_TIME_FORMAT "/%u",
923         queue->cur_level.bytes, GST_TIME_ARGS (queue->cur_level.time),
924         queue->cur_level.buffers);
925
926     /* figure out the percent we are filled, we take the max of all formats. */
927     if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
928       perc = GET_PERCENT (bytes, 0);
929     } else {
930       guint64 rb_size = queue->ring_buffer_max_size;
931       perc = GET_PERCENT (bytes, rb_size);
932     }
933
934     perc2 = GET_PERCENT (time, 0);
935     perc = MAX (perc, perc2);
936
937     perc2 = GET_PERCENT (buffers, 0);
938     perc = MAX (perc, perc2);
939
940     /* also apply the rate estimate when we need to */
941     if (queue->use_rate_estimate) {
942       perc2 = GET_PERCENT (rate_time, 0);
943       perc = MAX (perc, perc2);
944     }
945
946     /* Don't get to 0% unless we're really empty */
947     if (queue->cur_level.bytes > 0)
948       perc = MAX (1, perc);
949   }
950 #undef GET_PERCENT
951
952   if (is_buffering)
953     *is_buffering = queue->is_buffering;
954
955   /* scale to high percent so that it becomes the 100% mark */
956   perc = perc * 100 / queue->high_percent;
957   /* clip */
958   if (perc > 100)
959     perc = 100;
960
961   if (percent)
962     *percent = perc;
963
964   GST_DEBUG_OBJECT (queue, "buffering %d, percent %d", queue->is_buffering,
965       perc);
966
967   return TRUE;
968 }
969
970 static void
971 get_buffering_stats (GstQueue2 * queue, gint percent, GstBufferingMode * mode,
972     gint * avg_in, gint * avg_out, gint64 * buffering_left)
973 {
974   if (mode) {
975     if (!QUEUE_IS_USING_QUEUE (queue)) {
976       if (QUEUE_IS_USING_RING_BUFFER (queue))
977         *mode = GST_BUFFERING_TIMESHIFT;
978       else
979         *mode = GST_BUFFERING_DOWNLOAD;
980     } else {
981       *mode = GST_BUFFERING_STREAM;
982     }
983   }
984
985   if (avg_in)
986     *avg_in = queue->byte_in_rate;
987   if (avg_out)
988     *avg_out = queue->byte_out_rate;
989
990   if (buffering_left) {
991     *buffering_left = (percent == 100 ? 0 : -1);
992
993     if (queue->use_rate_estimate) {
994       guint64 max, cur;
995
996       max = queue->max_level.rate_time;
997       cur = queue->cur_level.rate_time;
998
999       if (percent != 100 && max > cur)
1000         *buffering_left = (max - cur) / 1000000;
1001     }
1002   }
1003 }
1004
1005 static void
1006 gst_queue2_post_buffering (GstQueue2 * queue)
1007 {
1008   GstMessage *msg = NULL;
1009
1010   g_mutex_lock (&queue->buffering_post_lock);
1011   GST_QUEUE2_MUTEX_LOCK (queue);
1012   if (queue->percent_changed) {
1013     gint percent = queue->buffering_percent;
1014
1015     queue->percent_changed = FALSE;
1016
1017     GST_DEBUG_OBJECT (queue, "Going to post buffering: %d%%", percent);
1018     msg = gst_message_new_buffering (GST_OBJECT_CAST (queue), percent);
1019
1020     gst_message_set_buffering_stats (msg, queue->mode, queue->avg_in,
1021         queue->avg_out, queue->buffering_left);
1022   }
1023   GST_QUEUE2_MUTEX_UNLOCK (queue);
1024
1025   if (msg != NULL)
1026     gst_element_post_message (GST_ELEMENT_CAST (queue), msg);
1027
1028   g_mutex_unlock (&queue->buffering_post_lock);
1029 }
1030
1031 static void
1032 update_buffering (GstQueue2 * queue)
1033 {
1034   gint percent;
1035
1036   /* Ensure the variables used to calculate buffering state are up-to-date. */
1037   if (queue->current)
1038     update_cur_level (queue, queue->current);
1039   update_in_rates (queue);
1040
1041   if (!get_buffering_percent (queue, NULL, &percent))
1042     return;
1043
1044   if (queue->is_buffering) {
1045     /* if we were buffering see if we reached the high watermark */
1046     if (percent >= 100)
1047       queue->is_buffering = FALSE;
1048
1049     SET_PERCENT (queue, percent);
1050   } else {
1051     /* we were not buffering, check if we need to start buffering if we drop
1052      * below the low threshold */
1053     if (percent < queue->low_percent) {
1054       queue->is_buffering = TRUE;
1055       SET_PERCENT (queue, percent);
1056     }
1057   }
1058 }
1059
1060 static void
1061 reset_rate_timer (GstQueue2 * queue)
1062 {
1063   queue->bytes_in = 0;
1064   queue->bytes_out = 0;
1065   queue->byte_in_rate = 0.0;
1066   queue->byte_in_period = 0;
1067   queue->byte_out_rate = 0.0;
1068   queue->last_update_in_rates_elapsed = 0.0;
1069   queue->last_in_elapsed = 0.0;
1070   queue->last_out_elapsed = 0.0;
1071   queue->in_timer_started = FALSE;
1072   queue->out_timer_started = FALSE;
1073 }
1074
1075 /* the interval in seconds to recalculate the rate */
1076 #define RATE_INTERVAL    0.2
1077 /* Tuning for rate estimation. We use a large window for the input rate because
1078  * it should be stable when connected to a network. The output rate is less
1079  * stable (the elements preroll, queues behind a demuxer fill, ...) and should
1080  * therefore adapt more quickly.
1081  * However, initial input rate may be subject to a burst, and should therefore
1082  * initially also adapt more quickly to changes, and only later on give higher
1083  * weight to previous values. */
1084 #define AVG_IN(avg,val,w1,w2)  ((avg) * (w1) + (val) * (w2)) / ((w1) + (w2))
1085 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
1086
1087 static void
1088 update_in_rates (GstQueue2 * queue)
1089 {
1090   gdouble elapsed, period;
1091   gdouble byte_in_rate;
1092
1093   if (!queue->in_timer_started) {
1094     queue->in_timer_started = TRUE;
1095     g_timer_start (queue->in_timer);
1096     return;
1097   }
1098
1099   queue->last_update_in_rates_elapsed = elapsed =
1100       g_timer_elapsed (queue->in_timer, NULL);
1101
1102   /* recalc after each interval. */
1103   if (queue->last_in_elapsed + RATE_INTERVAL < elapsed) {
1104     period = elapsed - queue->last_in_elapsed;
1105
1106     GST_DEBUG_OBJECT (queue,
1107         "rates: period %f, in %" G_GUINT64_FORMAT ", global period %f",
1108         period, queue->bytes_in, queue->byte_in_period);
1109
1110     byte_in_rate = queue->bytes_in / period;
1111
1112     if (queue->byte_in_rate == 0.0)
1113       queue->byte_in_rate = byte_in_rate;
1114     else
1115       queue->byte_in_rate = AVG_IN (queue->byte_in_rate, byte_in_rate,
1116           (double) queue->byte_in_period, period);
1117
1118     /* another data point, cap at 16 for long time running average */
1119     if (queue->byte_in_period < 16 * RATE_INTERVAL)
1120       queue->byte_in_period += period;
1121
1122     /* reset the values to calculate rate over the next interval */
1123     queue->last_in_elapsed = elapsed;
1124     queue->bytes_in = 0;
1125   }
1126
1127   if (queue->byte_in_rate > 0.0) {
1128     queue->cur_level.rate_time =
1129         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1130   }
1131   GST_DEBUG_OBJECT (queue, "rates: in %f, time %" GST_TIME_FORMAT,
1132       queue->byte_in_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1133 }
1134
1135 static void
1136 update_out_rates (GstQueue2 * queue)
1137 {
1138   gdouble elapsed, period;
1139   gdouble byte_out_rate;
1140
1141   if (!queue->out_timer_started) {
1142     queue->out_timer_started = TRUE;
1143     g_timer_start (queue->out_timer);
1144     return;
1145   }
1146
1147   elapsed = g_timer_elapsed (queue->out_timer, NULL);
1148
1149   /* recalc after each interval. */
1150   if (queue->last_out_elapsed + RATE_INTERVAL < elapsed) {
1151     period = elapsed - queue->last_out_elapsed;
1152
1153     GST_DEBUG_OBJECT (queue,
1154         "rates: period %f, out %" G_GUINT64_FORMAT, period, queue->bytes_out);
1155
1156     byte_out_rate = queue->bytes_out / period;
1157
1158     if (queue->byte_out_rate == 0.0)
1159       queue->byte_out_rate = byte_out_rate;
1160     else
1161       queue->byte_out_rate = AVG_OUT (queue->byte_out_rate, byte_out_rate);
1162
1163     /* reset the values to calculate rate over the next interval */
1164     queue->last_out_elapsed = elapsed;
1165     queue->bytes_out = 0;
1166   }
1167   if (queue->byte_in_rate > 0.0) {
1168     queue->cur_level.rate_time =
1169         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1170   }
1171   GST_DEBUG_OBJECT (queue, "rates: out %f, time %" GST_TIME_FORMAT,
1172       queue->byte_out_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1173 }
1174
1175 static void
1176 update_cur_pos (GstQueue2 * queue, GstQueue2Range * range, guint64 pos)
1177 {
1178   guint64 reading_pos, max_reading_pos;
1179
1180   reading_pos = pos;
1181   max_reading_pos = range->max_reading_pos;
1182
1183   max_reading_pos = MAX (max_reading_pos, reading_pos);
1184
1185   GST_DEBUG_OBJECT (queue,
1186       "updating max_reading_pos from %" G_GUINT64_FORMAT " to %"
1187       G_GUINT64_FORMAT, range->max_reading_pos, max_reading_pos);
1188   range->max_reading_pos = max_reading_pos;
1189
1190   update_cur_level (queue, range);
1191 }
1192
1193 static gboolean
1194 perform_seek_to_offset (GstQueue2 * queue, guint64 offset)
1195 {
1196   GstEvent *event;
1197   gboolean res;
1198
1199   /* until we receive the FLUSH_STOP from this seek, we skip data */
1200   queue->seeking = TRUE;
1201   GST_QUEUE2_MUTEX_UNLOCK (queue);
1202
1203   debug_ranges (queue);
1204
1205   GST_DEBUG_OBJECT (queue, "Seeking to %" G_GUINT64_FORMAT, offset);
1206
1207   event =
1208       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1209       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1210       GST_SEEK_TYPE_NONE, -1);
1211
1212   res = gst_pad_push_event (queue->sinkpad, event);
1213   GST_QUEUE2_MUTEX_LOCK (queue);
1214
1215   if (res) {
1216     /* Between us sending the seek event and re-acquiring the lock, the source
1217      * thread might already have pushed data and moved along the range's
1218      * writing_pos beyond the seek offset. In that case we don't want to set
1219      * the writing position back to the requested seek position, as it would
1220      * cause data to be written to the wrong offset in the file or ring buffer.
1221      * We still do the add_range call to switch the current range to the
1222      * requested range, or create one if one doesn't exist yet. */
1223     queue->current = add_range (queue, offset, FALSE);
1224   }
1225
1226   return res;
1227 }
1228
1229 /* get the threshold for when we decide to seek rather than wait */
1230 static guint64
1231 get_seek_threshold (GstQueue2 * queue)
1232 {
1233   guint64 threshold;
1234
1235   /* FIXME, find a good threshold based on the incoming rate. */
1236   threshold = 1024 * 512;
1237
1238   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1239     threshold = MIN (threshold,
1240         QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes);
1241   }
1242   return threshold;
1243 }
1244
1245 /* see if there is enough data in the file to read a full buffer */
1246 static gboolean
1247 gst_queue2_have_data (GstQueue2 * queue, guint64 offset, guint length)
1248 {
1249   GstQueue2Range *range;
1250
1251   GST_DEBUG_OBJECT (queue, "looking for offset %" G_GUINT64_FORMAT ", len %u",
1252       offset, length);
1253
1254   if ((range = find_range (queue, offset))) {
1255     if (queue->current != range) {
1256       GST_DEBUG_OBJECT (queue, "switching ranges, do seek to range position");
1257       perform_seek_to_offset (queue, range->writing_pos);
1258     }
1259
1260     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1261         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1262
1263     /* we have a range for offset */
1264     GST_DEBUG_OBJECT (queue,
1265         "we have a range %p, offset %" G_GUINT64_FORMAT ", writing_pos %"
1266         G_GUINT64_FORMAT, range, range->offset, range->writing_pos);
1267
1268     if (!QUEUE_IS_USING_RING_BUFFER (queue) && queue->is_eos)
1269       return TRUE;
1270
1271     if (offset + length <= range->writing_pos)
1272       return TRUE;
1273     else
1274       GST_DEBUG_OBJECT (queue,
1275           "Need more data (%" G_GUINT64_FORMAT " bytes more)",
1276           (offset + length) - range->writing_pos);
1277
1278   } else {
1279     GST_INFO_OBJECT (queue, "not found in any range off %" G_GUINT64_FORMAT
1280         " len %u", offset, length);
1281     /* we don't have the range, see how far away we are */
1282     if (!queue->is_eos && queue->current) {
1283       guint64 threshold = get_seek_threshold (queue);
1284
1285       if (offset >= queue->current->offset && offset <=
1286           queue->current->writing_pos + threshold) {
1287         GST_INFO_OBJECT (queue,
1288             "requested data is within range, wait for data");
1289         return FALSE;
1290       }
1291     }
1292
1293     /* too far away, do a seek */
1294     perform_seek_to_offset (queue, offset);
1295   }
1296
1297   return FALSE;
1298 }
1299
1300 #ifdef HAVE_FSEEKO
1301 #define FSEEK_FILE(file,offset)  (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1302 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1303 #define FSEEK_FILE(file,offset)  (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1304 #else
1305 #define FSEEK_FILE(file,offset)  (fseek (file, offset, SEEK_SET) != 0)
1306 #endif
1307
1308 static GstFlowReturn
1309 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1310     guint8 * dst, gint64 * read_return)
1311 {
1312   guint8 *ring_buffer;
1313   size_t res;
1314
1315   ring_buffer = queue->ring_buffer;
1316
1317   if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1318     goto seek_failed;
1319
1320   /* this should not block */
1321   GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1322       length, offset);
1323   if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1324     res = fread (dst, 1, length, queue->temp_file);
1325   } else {
1326     memcpy (dst, ring_buffer + offset, length);
1327     res = length;
1328   }
1329
1330   GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1331
1332   if (G_UNLIKELY (res < length)) {
1333     if (!QUEUE_IS_USING_TEMP_FILE (queue))
1334       goto could_not_read;
1335     /* check for errors or EOF */
1336     if (ferror (queue->temp_file))
1337       goto could_not_read;
1338     if (feof (queue->temp_file) && length > 0)
1339       goto eos;
1340   }
1341
1342   *read_return = res;
1343
1344   return GST_FLOW_OK;
1345
1346 seek_failed:
1347   {
1348     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1349     return GST_FLOW_ERROR;
1350   }
1351 could_not_read:
1352   {
1353     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1354     return GST_FLOW_ERROR;
1355   }
1356 eos:
1357   {
1358     GST_DEBUG ("non-regular file hits EOS");
1359     return GST_FLOW_EOS;
1360   }
1361 }
1362
1363 static GstFlowReturn
1364 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1365     GstBuffer ** buffer)
1366 {
1367   GstBuffer *buf;
1368   GstMapInfo info;
1369   guint8 *data;
1370   guint64 file_offset;
1371   guint block_length, remaining, read_length;
1372   guint64 rb_size;
1373   guint64 max_size;
1374   guint64 rpos;
1375   GstFlowReturn ret = GST_FLOW_OK;
1376
1377   /* allocate the output buffer of the requested size */
1378   if (*buffer == NULL)
1379     buf = gst_buffer_new_allocate (NULL, length, NULL);
1380   else
1381     buf = *buffer;
1382
1383   if (!gst_buffer_map (buf, &info, GST_MAP_WRITE))
1384     goto buffer_write_fail;
1385   data = info.data;
1386
1387   GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1388       offset);
1389
1390   rpos = offset;
1391   rb_size = queue->ring_buffer_max_size;
1392   max_size = QUEUE_MAX_BYTES (queue);
1393
1394   remaining = length;
1395   while (remaining > 0) {
1396     /* configure how much/whether to read */
1397     if (!gst_queue2_have_data (queue, rpos, remaining)) {
1398       read_length = 0;
1399
1400       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1401         guint64 level;
1402
1403         /* calculate how far away the offset is */
1404         if (queue->current->writing_pos > rpos)
1405           level = queue->current->writing_pos - rpos;
1406         else
1407           level = 0;
1408
1409         GST_DEBUG_OBJECT (queue,
1410             "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1411             ", level %" G_GUINT64_FORMAT ", max %" G_GUINT64_FORMAT,
1412             rpos, queue->current->writing_pos, level, max_size);
1413
1414         if (level >= max_size) {
1415           /* we don't have the data but if we have a ring buffer that is full, we
1416            * need to read */
1417           GST_DEBUG_OBJECT (queue,
1418               "ring buffer full, reading QUEUE_MAX_BYTES %"
1419               G_GUINT64_FORMAT " bytes", max_size);
1420           read_length = max_size;
1421         } else if (queue->is_eos) {
1422           /* won't get any more data so read any data we have */
1423           if (level) {
1424             GST_DEBUG_OBJECT (queue,
1425                 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1426                 level);
1427             read_length = level;
1428             remaining = level;
1429             length = level;
1430           } else
1431             goto hit_eos;
1432         }
1433       }
1434
1435       if (read_length == 0) {
1436         if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1437           GST_DEBUG_OBJECT (queue,
1438               "update current position [%" G_GUINT64_FORMAT "-%"
1439               G_GUINT64_FORMAT "]", rpos, queue->current->max_reading_pos);
1440           update_cur_pos (queue, queue->current, rpos);
1441           GST_QUEUE2_SIGNAL_DEL (queue);
1442         }
1443
1444         if (queue->use_buffering)
1445           update_buffering (queue);
1446
1447         GST_DEBUG_OBJECT (queue, "waiting for add");
1448         GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1449         continue;
1450       }
1451     } else {
1452       /* we have the requested data so read it */
1453       read_length = remaining;
1454     }
1455
1456     /* set range reading_pos to actual reading position for this read */
1457     queue->current->reading_pos = rpos;
1458
1459     /* configure how much and from where to read */
1460     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1461       file_offset =
1462           (queue->current->rb_offset + (rpos -
1463               queue->current->offset)) % rb_size;
1464       if (file_offset + read_length > rb_size) {
1465         block_length = rb_size - file_offset;
1466       } else {
1467         block_length = read_length;
1468       }
1469     } else {
1470       file_offset = rpos;
1471       block_length = read_length;
1472     }
1473
1474     /* while we still have data to read, we loop */
1475     while (read_length > 0) {
1476       gint64 read_return;
1477
1478       ret =
1479           gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1480           data, &read_return);
1481       if (ret != GST_FLOW_OK)
1482         goto read_error;
1483
1484       file_offset += read_return;
1485       if (QUEUE_IS_USING_RING_BUFFER (queue))
1486         file_offset %= rb_size;
1487
1488       data += read_return;
1489       read_length -= read_return;
1490       block_length = read_length;
1491       remaining -= read_return;
1492
1493       rpos = (queue->current->reading_pos += read_return);
1494       update_cur_pos (queue, queue->current, queue->current->reading_pos);
1495     }
1496     GST_QUEUE2_SIGNAL_DEL (queue);
1497     GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1498   }
1499
1500   gst_buffer_unmap (buf, &info);
1501   gst_buffer_resize (buf, 0, length);
1502
1503   GST_BUFFER_OFFSET (buf) = offset;
1504   GST_BUFFER_OFFSET_END (buf) = offset + length;
1505
1506   *buffer = buf;
1507
1508   return ret;
1509
1510   /* ERRORS */
1511 hit_eos:
1512   {
1513     GST_DEBUG_OBJECT (queue, "EOS hit and we don't have any requested data");
1514     gst_buffer_unmap (buf, &info);
1515     if (*buffer == NULL)
1516       gst_buffer_unref (buf);
1517     return GST_FLOW_EOS;
1518   }
1519 out_flushing:
1520   {
1521     GST_DEBUG_OBJECT (queue, "we are flushing");
1522     gst_buffer_unmap (buf, &info);
1523     if (*buffer == NULL)
1524       gst_buffer_unref (buf);
1525     return GST_FLOW_FLUSHING;
1526   }
1527 read_error:
1528   {
1529     GST_DEBUG_OBJECT (queue, "we have a read error");
1530     gst_buffer_unmap (buf, &info);
1531     if (*buffer == NULL)
1532       gst_buffer_unref (buf);
1533     return ret;
1534   }
1535 buffer_write_fail:
1536   {
1537     GST_ELEMENT_ERROR (queue, RESOURCE, WRITE, (NULL),
1538         ("Can't write to buffer"));
1539     if (*buffer == NULL)
1540       gst_buffer_unref (buf);
1541     return GST_FLOW_ERROR;
1542   }
1543 }
1544
1545 /* should be called with QUEUE_LOCK */
1546 static GstMiniObject *
1547 gst_queue2_read_item_from_file (GstQueue2 * queue)
1548 {
1549   GstMiniObject *item;
1550
1551   if (queue->stream_start_event != NULL) {
1552     item = GST_MINI_OBJECT_CAST (queue->stream_start_event);
1553     queue->stream_start_event = NULL;
1554   } else if (queue->starting_segment != NULL) {
1555     item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1556     queue->starting_segment = NULL;
1557   } else {
1558     GstFlowReturn ret;
1559     GstBuffer *buffer = NULL;
1560     guint64 reading_pos;
1561
1562     reading_pos = queue->current->reading_pos;
1563
1564     ret =
1565         gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1566         &buffer);
1567
1568     switch (ret) {
1569       case GST_FLOW_OK:
1570         item = GST_MINI_OBJECT_CAST (buffer);
1571         break;
1572       case GST_FLOW_EOS:
1573         item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1574         break;
1575       default:
1576         item = NULL;
1577         break;
1578     }
1579   }
1580   return item;
1581 }
1582
1583 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1584  * the temp filename. */
1585 static gboolean
1586 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1587 {
1588   gint fd = -1;
1589   gchar *name = NULL;
1590
1591   if (queue->temp_file)
1592     goto already_opened;
1593
1594   GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1595
1596   /* If temp_template was set, allocate a filename and open that file */
1597
1598   /* nothing to do */
1599   if (queue->temp_template == NULL)
1600     goto no_directory;
1601
1602   /* make copy of the template, we don't want to change this */
1603   name = g_strdup (queue->temp_template);
1604
1605 #ifdef __BIONIC__
1606   fd = g_mkstemp_full (name, O_RDWR | O_LARGEFILE, S_IRUSR | S_IWUSR);
1607 #else
1608   fd = g_mkstemp (name);
1609 #endif
1610
1611   if (fd == -1)
1612     goto mkstemp_failed;
1613
1614   /* open the file for update/writing */
1615   queue->temp_file = fdopen (fd, "wb+");
1616   /* error creating file */
1617   if (queue->temp_file == NULL)
1618     goto open_failed;
1619
1620   g_free (queue->temp_location);
1621   queue->temp_location = name;
1622
1623   GST_QUEUE2_MUTEX_UNLOCK (queue);
1624
1625   /* we can't emit the notify with the lock */
1626   g_object_notify (G_OBJECT (queue), "temp-location");
1627
1628   GST_QUEUE2_MUTEX_LOCK (queue);
1629
1630   GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1631
1632   return TRUE;
1633
1634   /* ERRORS */
1635 already_opened:
1636   {
1637     GST_DEBUG_OBJECT (queue, "temp file was already open");
1638     return TRUE;
1639   }
1640 no_directory:
1641   {
1642     GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1643         (_("No Temp directory specified.")), (NULL));
1644     return FALSE;
1645   }
1646 mkstemp_failed:
1647   {
1648     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1649         (_("Could not create temp file \"%s\"."), queue->temp_template),
1650         GST_ERROR_SYSTEM);
1651     g_free (name);
1652     return FALSE;
1653   }
1654 open_failed:
1655   {
1656     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1657         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1658     g_free (name);
1659     if (fd != -1)
1660       close (fd);
1661     return FALSE;
1662   }
1663 }
1664
1665 static void
1666 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1667 {
1668   /* nothing to do */
1669   if (queue->temp_file == NULL)
1670     return;
1671
1672   GST_DEBUG_OBJECT (queue, "closing temp file");
1673
1674   fflush (queue->temp_file);
1675   fclose (queue->temp_file);
1676
1677   if (queue->temp_remove) {
1678     if (remove (queue->temp_location) < 0) {
1679       GST_WARNING_OBJECT (queue, "Failed to remove temporary file %s: %s",
1680           queue->temp_location, g_strerror (errno));
1681     }
1682   }
1683
1684   queue->temp_file = NULL;
1685   clean_ranges (queue);
1686 }
1687
1688 static void
1689 gst_queue2_flush_temp_file (GstQueue2 * queue)
1690 {
1691   if (queue->temp_file == NULL)
1692     return;
1693
1694   GST_DEBUG_OBJECT (queue, "flushing temp file");
1695
1696   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1697 }
1698
1699 static void
1700 gst_queue2_locked_flush (GstQueue2 * queue, gboolean full, gboolean clear_temp)
1701 {
1702   if (!QUEUE_IS_USING_QUEUE (queue)) {
1703     if (QUEUE_IS_USING_TEMP_FILE (queue) && clear_temp)
1704       gst_queue2_flush_temp_file (queue);
1705     init_ranges (queue);
1706   } else {
1707     while (!g_queue_is_empty (&queue->queue)) {
1708       GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
1709
1710       if (!full && qitem->type == GST_QUEUE2_ITEM_TYPE_EVENT
1711           && GST_EVENT_IS_STICKY (qitem->item)
1712           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_SEGMENT
1713           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_EOS) {
1714         gst_pad_store_sticky_event (queue->srcpad,
1715             GST_EVENT_CAST (qitem->item));
1716       }
1717
1718       /* Then lose another reference because we are supposed to destroy that
1719          data when flushing */
1720       if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
1721         gst_mini_object_unref (qitem->item);
1722       g_slice_free (GstQueue2Item, qitem);
1723     }
1724   }
1725   queue->last_query = FALSE;
1726   g_cond_signal (&queue->query_handled);
1727   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1728   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1729   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1730   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1731   queue->sink_tainted = queue->src_tainted = TRUE;
1732   if (queue->starting_segment != NULL)
1733     gst_event_unref (queue->starting_segment);
1734   queue->starting_segment = NULL;
1735   queue->segment_event_received = FALSE;
1736   gst_event_replace (&queue->stream_start_event, NULL);
1737
1738   /* we deleted a lot of something */
1739   GST_QUEUE2_SIGNAL_DEL (queue);
1740 }
1741
1742 static gboolean
1743 gst_queue2_wait_free_space (GstQueue2 * queue)
1744 {
1745   /* We make space available if we're "full" according to whatever
1746    * the user defined as "full". */
1747   if (gst_queue2_is_filled (queue)) {
1748     gboolean started;
1749
1750     /* pause the timer while we wait. The fact that we are waiting does not mean
1751      * the byterate on the input pad is lower */
1752     if ((started = queue->in_timer_started))
1753       g_timer_stop (queue->in_timer);
1754
1755     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1756         "queue is full, waiting for free space");
1757     do {
1758       /* Wait for space to be available, we could be unlocked because of a flush. */
1759       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1760     }
1761     while (gst_queue2_is_filled (queue));
1762
1763     /* and continue if we were running before */
1764     if (started)
1765       g_timer_continue (queue->in_timer);
1766   }
1767   return TRUE;
1768
1769   /* ERRORS */
1770 out_flushing:
1771   {
1772     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1773     return FALSE;
1774   }
1775 }
1776
1777 static gboolean
1778 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1779 {
1780   GstMapInfo info;
1781   guint8 *data, *ring_buffer;
1782   guint size, rb_size;
1783   guint64 writing_pos, new_writing_pos;
1784   GstQueue2Range *range, *prev, *next;
1785   gboolean do_seek = FALSE;
1786
1787   if (QUEUE_IS_USING_RING_BUFFER (queue))
1788     writing_pos = queue->current->rb_writing_pos;
1789   else
1790     writing_pos = queue->current->writing_pos;
1791   ring_buffer = queue->ring_buffer;
1792   rb_size = queue->ring_buffer_max_size;
1793
1794   if (!gst_buffer_map (buffer, &info, GST_MAP_READ))
1795     goto buffer_read_error;
1796
1797   size = info.size;
1798   data = info.data;
1799
1800   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1801       writing_pos);
1802
1803   /* sanity check */
1804   if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1805       GST_BUFFER_OFFSET (buffer) != queue->current->writing_pos) {
1806     GST_WARNING_OBJECT (queue, "buffer offset does not match current writing "
1807         "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1808         GST_BUFFER_OFFSET (buffer), queue->current->writing_pos);
1809   }
1810
1811   while (size > 0) {
1812     guint to_write;
1813
1814     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1815       gint64 space;
1816
1817       /* calculate the space in the ring buffer not used by data from
1818        * the current range */
1819       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1820         /* wait until there is some free space */
1821         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1822       }
1823       /* get the amount of space we have */
1824       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1825
1826       /* calculate if we need to split or if we can write the entire
1827        * buffer now */
1828       to_write = MIN (size, space);
1829
1830       /* the writing position in the ring buffer after writing (part
1831        * or all of) the buffer */
1832       new_writing_pos = (writing_pos + to_write) % rb_size;
1833
1834       prev = NULL;
1835       range = queue->ranges;
1836
1837       /* if we need to overwrite data in the ring buffer, we need to
1838        * update the ranges
1839        *
1840        * warning: this code is complicated and includes some
1841        * simplifications - pen, paper and diagrams for the cases
1842        * recommended! */
1843       while (range) {
1844         guint64 range_data_start, range_data_end;
1845         GstQueue2Range *range_to_destroy = NULL;
1846
1847         if (range == queue->current)
1848           goto next_range;
1849
1850         range_data_start = range->rb_offset;
1851         range_data_end = range->rb_writing_pos;
1852
1853         /* handle the special case where the range has no data in it */
1854         if (range->writing_pos == range->offset) {
1855           if (range != queue->current) {
1856             GST_DEBUG_OBJECT (queue,
1857                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1858                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1859             /* remove range */
1860             range_to_destroy = range;
1861             if (prev)
1862               prev->next = range->next;
1863           }
1864           goto next_range;
1865         }
1866
1867         if (range_data_end > range_data_start) {
1868           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1869             goto next_range;
1870
1871           if (new_writing_pos > range_data_start) {
1872             if (new_writing_pos >= range_data_end) {
1873               GST_DEBUG_OBJECT (queue,
1874                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1875                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1876               /* remove range */
1877               range_to_destroy = range;
1878               if (prev)
1879                 prev->next = range->next;
1880             } else {
1881               GST_DEBUG_OBJECT (queue,
1882                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1883                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1884                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1885                   range->offset + new_writing_pos - range_data_start,
1886                   new_writing_pos);
1887               range->offset += (new_writing_pos - range_data_start);
1888               range->rb_offset = new_writing_pos;
1889             }
1890           }
1891         } else {
1892           guint64 new_wpos_virt = writing_pos + to_write;
1893
1894           if (new_wpos_virt <= range_data_start)
1895             goto next_range;
1896
1897           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1898             GST_DEBUG_OBJECT (queue,
1899                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1900                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1901             /* remove range */
1902             range_to_destroy = range;
1903             if (prev)
1904               prev->next = range->next;
1905           } else {
1906             GST_DEBUG_OBJECT (queue,
1907                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1908                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1909                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1910                 range->offset + new_writing_pos - range_data_start,
1911                 new_writing_pos);
1912             range->offset += (new_wpos_virt - range_data_start);
1913             range->rb_offset = new_writing_pos;
1914           }
1915         }
1916
1917       next_range:
1918         if (!range_to_destroy)
1919           prev = range;
1920
1921         range = range->next;
1922         if (range_to_destroy) {
1923           if (range_to_destroy == queue->ranges)
1924             queue->ranges = range;
1925           g_slice_free (GstQueue2Range, range_to_destroy);
1926           range_to_destroy = NULL;
1927         }
1928       }
1929     } else {
1930       to_write = size;
1931       new_writing_pos = writing_pos + to_write;
1932     }
1933
1934     if (QUEUE_IS_USING_TEMP_FILE (queue)
1935         && FSEEK_FILE (queue->temp_file, writing_pos))
1936       goto seek_failed;
1937
1938     if (new_writing_pos > writing_pos) {
1939       GST_INFO_OBJECT (queue,
1940           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1941           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1942           queue->current->writing_pos, queue->current->rb_writing_pos);
1943       /* either not using ring buffer or no wrapping, just write */
1944       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1945         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1946           goto handle_error;
1947       } else {
1948         memcpy (ring_buffer + writing_pos, data, to_write);
1949       }
1950
1951       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1952         /* try to merge with next range */
1953         while ((next = queue->current->next)) {
1954           GST_INFO_OBJECT (queue,
1955               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1956               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1957           if (new_writing_pos < next->offset)
1958             break;
1959
1960           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1961               next->writing_pos);
1962
1963           /* remove the group */
1964           queue->current->next = next->next;
1965
1966           /* We use the threshold to decide if we want to do a seek or simply
1967            * read the data again. If there is not so much data in the range we
1968            * prefer to avoid to seek and read it again. */
1969           if (next->writing_pos > new_writing_pos + get_seek_threshold (queue)) {
1970             /* the new range had more data than the threshold, it's worth keeping
1971              * it and doing a seek. */
1972             new_writing_pos = next->writing_pos;
1973             do_seek = TRUE;
1974           }
1975           g_slice_free (GstQueue2Range, next);
1976         }
1977         goto update_and_signal;
1978       }
1979     } else {
1980       /* wrapping */
1981       guint block_one, block_two;
1982
1983       block_one = rb_size - writing_pos;
1984       block_two = to_write - block_one;
1985
1986       if (block_one > 0) {
1987         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1988         /* write data to end of ring buffer */
1989         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1990           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1991             goto handle_error;
1992         } else {
1993           memcpy (ring_buffer + writing_pos, data, block_one);
1994         }
1995       }
1996
1997       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1998         goto seek_failed;
1999
2000       if (block_two > 0) {
2001         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
2002         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2003           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
2004             goto handle_error;
2005         } else {
2006           memcpy (ring_buffer, data + block_one, block_two);
2007         }
2008       }
2009     }
2010
2011   update_and_signal:
2012     /* update the writing positions */
2013     size -= to_write;
2014     GST_INFO_OBJECT (queue,
2015         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
2016         to_write, writing_pos, size);
2017
2018     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2019       data += to_write;
2020       queue->current->writing_pos += to_write;
2021       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
2022     } else {
2023       queue->current->writing_pos = writing_pos = new_writing_pos;
2024     }
2025     if (do_seek)
2026       perform_seek_to_offset (queue, new_writing_pos);
2027
2028     update_cur_level (queue, queue->current);
2029
2030     /* update the buffering status */
2031     if (queue->use_buffering)
2032       update_buffering (queue);
2033
2034     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
2035         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
2036
2037     GST_QUEUE2_SIGNAL_ADD (queue);
2038   }
2039
2040   gst_buffer_unmap (buffer, &info);
2041
2042   return TRUE;
2043
2044   /* ERRORS */
2045 out_flushing:
2046   {
2047     GST_DEBUG_OBJECT (queue, "we are flushing");
2048     gst_buffer_unmap (buffer, &info);
2049     /* FIXME - GST_FLOW_EOS ? */
2050     return FALSE;
2051   }
2052 seek_failed:
2053   {
2054     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
2055     gst_buffer_unmap (buffer, &info);
2056     return FALSE;
2057   }
2058 handle_error:
2059   {
2060     switch (errno) {
2061       case ENOSPC:{
2062         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
2063         break;
2064       }
2065       default:{
2066         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
2067             (_("Error while writing to download file.")),
2068             ("%s", g_strerror (errno)));
2069       }
2070     }
2071     gst_buffer_unmap (buffer, &info);
2072     return FALSE;
2073   }
2074 buffer_read_error:
2075   {
2076     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL),
2077         ("Can't read from buffer"));
2078     return FALSE;
2079   }
2080 }
2081
2082 static gboolean
2083 buffer_list_create_write (GstBuffer ** buf, guint idx, gpointer q)
2084 {
2085   GstQueue2 *queue = q;
2086
2087   GST_TRACE_OBJECT (queue,
2088       "writing buffer %u of size %" G_GSIZE_FORMAT " bytes", idx,
2089       gst_buffer_get_size (*buf));
2090
2091   if (!gst_queue2_create_write (queue, *buf)) {
2092     GST_INFO_OBJECT (queue, "create_write() returned FALSE, bailing out");
2093     return FALSE;
2094   }
2095   return TRUE;
2096 }
2097
2098 static gboolean
2099 buffer_list_calc_size (GstBuffer ** buf, guint idx, gpointer data)
2100 {
2101   guint *p_size = data;
2102   gsize buf_size;
2103
2104   buf_size = gst_buffer_get_size (*buf);
2105   GST_TRACE ("buffer %u in has size %" G_GSIZE_FORMAT, idx, buf_size);
2106   *p_size += buf_size;
2107   return TRUE;
2108 }
2109
2110 /* enqueue an item an update the level stats */
2111 static void
2112 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item,
2113     GstQueue2ItemType item_type)
2114 {
2115   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2116     GstBuffer *buffer;
2117     guint size;
2118
2119     buffer = GST_BUFFER_CAST (item);
2120     size = gst_buffer_get_size (buffer);
2121
2122     /* add buffer to the statistics */
2123     if (QUEUE_IS_USING_QUEUE (queue)) {
2124       queue->cur_level.buffers++;
2125       queue->cur_level.bytes += size;
2126     }
2127     queue->bytes_in += size;
2128
2129     /* apply new buffer to segment stats */
2130     apply_buffer (queue, buffer, &queue->sink_segment, size, TRUE);
2131     /* update the byterate stats */
2132     update_in_rates (queue);
2133
2134     if (!QUEUE_IS_USING_QUEUE (queue)) {
2135       /* FIXME - check return value? */
2136       gst_queue2_create_write (queue, buffer);
2137     }
2138   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2139     GstBufferList *buffer_list;
2140     guint size = 0;
2141
2142     buffer_list = GST_BUFFER_LIST_CAST (item);
2143
2144     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2145     GST_LOG_OBJECT (queue, "total size of buffer list: %u bytes", size);
2146
2147     /* add buffer to the statistics */
2148     if (QUEUE_IS_USING_QUEUE (queue)) {
2149       queue->cur_level.buffers += gst_buffer_list_length (buffer_list);
2150       queue->cur_level.bytes += size;
2151     }
2152     queue->bytes_in += size;
2153
2154     /* apply new buffer to segment stats */
2155     apply_buffer_list (queue, buffer_list, &queue->sink_segment, TRUE);
2156
2157     /* update the byterate stats */
2158     update_in_rates (queue);
2159
2160     if (!QUEUE_IS_USING_QUEUE (queue)) {
2161       gst_buffer_list_foreach (buffer_list, buffer_list_create_write, queue);
2162     }
2163   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2164     GstEvent *event;
2165
2166     event = GST_EVENT_CAST (item);
2167
2168     switch (GST_EVENT_TYPE (event)) {
2169       case GST_EVENT_EOS:
2170         /* Zero the thresholds, this makes sure the queue is completely
2171          * filled and we can read all data from the queue. */
2172         GST_DEBUG_OBJECT (queue, "we have EOS");
2173         queue->is_eos = TRUE;
2174         break;
2175       case GST_EVENT_SEGMENT:
2176         apply_segment (queue, event, &queue->sink_segment, TRUE);
2177         /* This is our first new segment, we hold it
2178          * as we can't save it on the temp file */
2179         if (!QUEUE_IS_USING_QUEUE (queue)) {
2180           if (queue->segment_event_received)
2181             goto unexpected_event;
2182
2183           queue->segment_event_received = TRUE;
2184           if (queue->starting_segment != NULL)
2185             gst_event_unref (queue->starting_segment);
2186           queue->starting_segment = event;
2187           item = NULL;
2188         }
2189         /* a new segment allows us to accept more buffers if we got EOS
2190          * from downstream */
2191         queue->unexpected = FALSE;
2192         break;
2193       case GST_EVENT_GAP:
2194         apply_gap (queue, event, &queue->sink_segment, TRUE);
2195         break;
2196       case GST_EVENT_STREAM_START:
2197         if (!QUEUE_IS_USING_QUEUE (queue)) {
2198           gst_event_replace (&queue->stream_start_event, event);
2199           gst_event_unref (event);
2200           item = NULL;
2201         }
2202         break;
2203       case GST_EVENT_CAPS:{
2204         GstCaps *caps;
2205
2206         gst_event_parse_caps (event, &caps);
2207         GST_INFO ("got caps: %" GST_PTR_FORMAT, caps);
2208
2209         if (!QUEUE_IS_USING_QUEUE (queue)) {
2210           GST_LOG ("Dropping caps event, not using queue");
2211           gst_event_unref (event);
2212           item = NULL;
2213         }
2214         break;
2215       }
2216       default:
2217         if (!QUEUE_IS_USING_QUEUE (queue))
2218           goto unexpected_event;
2219         break;
2220     }
2221   } else if (GST_IS_QUERY (item)) {
2222     /* Can't happen as we check that in the caller */
2223     if (!QUEUE_IS_USING_QUEUE (queue))
2224       g_assert_not_reached ();
2225   } else {
2226     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
2227         item, GST_OBJECT_NAME (queue));
2228     /* we can't really unref since we don't know what it is */
2229     item = NULL;
2230   }
2231
2232   if (item) {
2233     /* update the buffering status */
2234     if (queue->use_buffering)
2235       update_buffering (queue);
2236
2237     if (QUEUE_IS_USING_QUEUE (queue)) {
2238       GstQueue2Item *qitem = g_slice_new (GstQueue2Item);
2239       qitem->type = item_type;
2240       qitem->item = item;
2241       g_queue_push_tail (&queue->queue, qitem);
2242     } else {
2243       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
2244     }
2245
2246     GST_QUEUE2_SIGNAL_ADD (queue);
2247   }
2248
2249   return;
2250
2251   /* ERRORS */
2252 unexpected_event:
2253   {
2254     gboolean is_custom = GST_EVENT_TYPE (item) < GST_EVENT_CUSTOM_UPSTREAM;
2255
2256     GST_WARNING_OBJECT (queue, "%s%s event can't be added to temp file: "
2257         "%" GST_PTR_FORMAT, is_custom ? "Unexpected " : "",
2258         GST_EVENT_TYPE_NAME (item), GST_EVENT_CAST (item));
2259     gst_event_unref (GST_EVENT_CAST (item));
2260     return;
2261   }
2262 }
2263
2264 /* dequeue an item from the queue and update level stats */
2265 static GstMiniObject *
2266 gst_queue2_locked_dequeue (GstQueue2 * queue, GstQueue2ItemType * item_type)
2267 {
2268   GstMiniObject *item;
2269
2270   if (!QUEUE_IS_USING_QUEUE (queue)) {
2271     item = gst_queue2_read_item_from_file (queue);
2272   } else {
2273     GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
2274
2275     if (qitem == NULL)
2276       goto no_item;
2277
2278     item = qitem->item;
2279     g_slice_free (GstQueue2Item, qitem);
2280   }
2281
2282   if (item == NULL)
2283     goto no_item;
2284
2285   if (GST_IS_BUFFER (item)) {
2286     GstBuffer *buffer;
2287     guint size;
2288
2289     buffer = GST_BUFFER_CAST (item);
2290     size = gst_buffer_get_size (buffer);
2291     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER;
2292
2293     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2294         "retrieved buffer %p from queue", buffer);
2295
2296     if (QUEUE_IS_USING_QUEUE (queue)) {
2297       queue->cur_level.buffers--;
2298       queue->cur_level.bytes -= size;
2299     }
2300     queue->bytes_out += size;
2301
2302     apply_buffer (queue, buffer, &queue->src_segment, size, FALSE);
2303     /* update the byterate stats */
2304     update_out_rates (queue);
2305     /* update the buffering */
2306     if (queue->use_buffering)
2307       update_buffering (queue);
2308
2309   } else if (GST_IS_EVENT (item)) {
2310     GstEvent *event = GST_EVENT_CAST (item);
2311
2312     *item_type = GST_QUEUE2_ITEM_TYPE_EVENT;
2313
2314     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2315         "retrieved event %p from queue", event);
2316
2317     switch (GST_EVENT_TYPE (event)) {
2318       case GST_EVENT_EOS:
2319         /* queue is empty now that we dequeued the EOS */
2320         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
2321         break;
2322       case GST_EVENT_SEGMENT:
2323         apply_segment (queue, event, &queue->src_segment, FALSE);
2324         break;
2325       case GST_EVENT_GAP:
2326         apply_gap (queue, event, &queue->src_segment, FALSE);
2327         break;
2328       default:
2329         break;
2330     }
2331   } else if (GST_IS_BUFFER_LIST (item)) {
2332     GstBufferList *buffer_list;
2333     guint size = 0;
2334
2335     buffer_list = GST_BUFFER_LIST_CAST (item);
2336     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2337     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER_LIST;
2338
2339     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2340         "retrieved buffer list %p from queue", buffer_list);
2341
2342     if (QUEUE_IS_USING_QUEUE (queue)) {
2343       queue->cur_level.buffers -= gst_buffer_list_length (buffer_list);
2344       queue->cur_level.bytes -= size;
2345     }
2346     queue->bytes_out += size;
2347
2348     apply_buffer_list (queue, buffer_list, &queue->src_segment, FALSE);
2349     /* update the byterate stats */
2350     update_out_rates (queue);
2351     /* update the buffering */
2352     if (queue->use_buffering)
2353       update_buffering (queue);
2354   } else if (GST_IS_QUERY (item)) {
2355     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2356         "retrieved query %p from queue", item);
2357     *item_type = GST_QUEUE2_ITEM_TYPE_QUERY;
2358   } else {
2359     g_warning
2360         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
2361         item, GST_OBJECT_NAME (queue));
2362     item = NULL;
2363     *item_type = GST_QUEUE2_ITEM_TYPE_UNKNOWN;
2364   }
2365   GST_QUEUE2_SIGNAL_DEL (queue);
2366
2367   return item;
2368
2369   /* ERRORS */
2370 no_item:
2371   {
2372     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
2373     return NULL;
2374   }
2375 }
2376
2377 static gboolean
2378 gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
2379     GstEvent * event)
2380 {
2381   gboolean ret = TRUE;
2382   GstQueue2 *queue;
2383
2384   queue = GST_QUEUE2 (parent);
2385
2386   switch (GST_EVENT_TYPE (event)) {
2387     case GST_EVENT_FLUSH_START:
2388     {
2389       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
2390       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2391         /* forward event */
2392         ret = gst_pad_push_event (queue->srcpad, event);
2393
2394         /* now unblock the chain function */
2395         GST_QUEUE2_MUTEX_LOCK (queue);
2396         queue->srcresult = GST_FLOW_FLUSHING;
2397         queue->sinkresult = GST_FLOW_FLUSHING;
2398         /* unblock the loop and chain functions */
2399         GST_QUEUE2_SIGNAL_ADD (queue);
2400         GST_QUEUE2_SIGNAL_DEL (queue);
2401         GST_QUEUE2_MUTEX_UNLOCK (queue);
2402
2403         /* make sure it pauses, this should happen since we sent
2404          * flush_start downstream. */
2405         gst_pad_pause_task (queue->srcpad);
2406         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
2407
2408         GST_QUEUE2_MUTEX_LOCK (queue);
2409         queue->last_query = FALSE;
2410         g_cond_signal (&queue->query_handled);
2411         GST_QUEUE2_MUTEX_UNLOCK (queue);
2412       } else {
2413         GST_QUEUE2_MUTEX_LOCK (queue);
2414         /* flush the sink pad */
2415         queue->sinkresult = GST_FLOW_FLUSHING;
2416         GST_QUEUE2_SIGNAL_DEL (queue);
2417         queue->last_query = FALSE;
2418         g_cond_signal (&queue->query_handled);
2419         GST_QUEUE2_MUTEX_UNLOCK (queue);
2420
2421         gst_event_unref (event);
2422       }
2423       break;
2424     }
2425     case GST_EVENT_FLUSH_STOP:
2426     {
2427       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2428
2429       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2430         /* forward event */
2431         ret = gst_pad_push_event (queue->srcpad, event);
2432
2433         GST_QUEUE2_MUTEX_LOCK (queue);
2434         gst_queue2_locked_flush (queue, FALSE, TRUE);
2435         queue->srcresult = GST_FLOW_OK;
2436         queue->sinkresult = GST_FLOW_OK;
2437         queue->is_eos = FALSE;
2438         queue->unexpected = FALSE;
2439         queue->seeking = FALSE;
2440         queue->src_tags_bitrate = queue->sink_tags_bitrate = 0;
2441         /* reset rate counters */
2442         reset_rate_timer (queue);
2443         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2444             queue->srcpad, NULL);
2445         GST_QUEUE2_MUTEX_UNLOCK (queue);
2446       } else {
2447         GST_QUEUE2_MUTEX_LOCK (queue);
2448         queue->segment_event_received = FALSE;
2449         queue->is_eos = FALSE;
2450         queue->unexpected = FALSE;
2451         queue->sinkresult = GST_FLOW_OK;
2452         queue->seeking = FALSE;
2453         queue->src_tags_bitrate = queue->sink_tags_bitrate = 0;
2454         GST_QUEUE2_MUTEX_UNLOCK (queue);
2455
2456         gst_event_unref (event);
2457       }
2458       break;
2459     }
2460     case GST_EVENT_TAG:{
2461       if (queue->use_tags_bitrate) {
2462         GstTagList *tags;
2463         guint bitrate;
2464
2465         gst_event_parse_tag (event, &tags);
2466         if (gst_tag_list_get_uint (tags, GST_TAG_BITRATE, &bitrate) ||
2467             gst_tag_list_get_uint (tags, GST_TAG_NOMINAL_BITRATE, &bitrate)) {
2468           GST_QUEUE2_MUTEX_LOCK (queue);
2469           queue->sink_tags_bitrate = bitrate;
2470           GST_QUEUE2_MUTEX_UNLOCK (queue);
2471           GST_LOG_OBJECT (queue, "Sink pad bitrate from tags now %u", bitrate);
2472         }
2473       }
2474       /* Fall-through */
2475     }
2476     default:
2477       if (GST_EVENT_IS_SERIALIZED (event)) {
2478         /* serialized events go in the queue */
2479         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2480         if (queue->srcresult != GST_FLOW_OK) {
2481           /* Errors in sticky event pushing are no problem and ignored here
2482            * as they will cause more meaningful errors during data flow.
2483            * For EOS events, that are not followed by data flow, we still
2484            * return FALSE here though and report an error.
2485            */
2486           if (!GST_EVENT_IS_STICKY (event)) {
2487             goto out_flow_error;
2488           } else if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
2489             if (queue->srcresult == GST_FLOW_NOT_LINKED
2490                 || queue->srcresult < GST_FLOW_EOS) {
2491               GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2492                   (_("Internal data flow error.")),
2493                   ("streaming task paused, reason %s (%d)",
2494                       gst_flow_get_name (queue->srcresult), queue->srcresult));
2495             }
2496             goto out_flow_error;
2497           }
2498         }
2499         /* refuse more events on EOS */
2500         if (queue->is_eos)
2501           goto out_eos;
2502         gst_queue2_locked_enqueue (queue, event, GST_QUEUE2_ITEM_TYPE_EVENT);
2503         GST_QUEUE2_MUTEX_UNLOCK (queue);
2504         gst_queue2_post_buffering (queue);
2505       } else {
2506         /* non-serialized events are passed upstream. */
2507         ret = gst_pad_push_event (queue->srcpad, event);
2508       }
2509       break;
2510   }
2511   return ret;
2512
2513   /* ERRORS */
2514 out_flushing:
2515   {
2516     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2517     GST_QUEUE2_MUTEX_UNLOCK (queue);
2518     gst_event_unref (event);
2519     return FALSE;
2520   }
2521 out_eos:
2522   {
2523     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2524     GST_QUEUE2_MUTEX_UNLOCK (queue);
2525     gst_event_unref (event);
2526     return FALSE;
2527   }
2528 out_flow_error:
2529   {
2530     GST_LOG_OBJECT (queue,
2531         "refusing event, we have a downstream flow error: %s",
2532         gst_flow_get_name (queue->srcresult));
2533     GST_QUEUE2_MUTEX_UNLOCK (queue);
2534     gst_event_unref (event);
2535     return FALSE;
2536   }
2537 }
2538
2539 static gboolean
2540 gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
2541     GstQuery * query)
2542 {
2543   GstQueue2 *queue;
2544   gboolean res;
2545
2546   queue = GST_QUEUE2 (parent);
2547
2548   switch (GST_QUERY_TYPE (query)) {
2549     default:
2550       if (GST_QUERY_IS_SERIALIZED (query)) {
2551         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received query %p", query);
2552         /* serialized events go in the queue. We need to be certain that we
2553          * don't cause deadlocks waiting for the query return value. We check if
2554          * the queue is empty (nothing is blocking downstream and the query can
2555          * be pushed for sure) or we are not buffering. If we are buffering,
2556          * the pipeline waits to unblock downstream until our queue fills up
2557          * completely, which can not happen if we block on the query..
2558          * Therefore we only potentially block when we are not buffering. */
2559         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2560         if (QUEUE_IS_USING_QUEUE (queue) && (gst_queue2_is_empty (queue)
2561                 || !queue->use_buffering)) {
2562           if (!g_atomic_int_get (&queue->downstream_may_block)) {
2563             gst_queue2_locked_enqueue (queue, query,
2564                 GST_QUEUE2_ITEM_TYPE_QUERY);
2565
2566             STATUS (queue, queue->sinkpad, "wait for QUERY");
2567             g_cond_wait (&queue->query_handled, &queue->qlock);
2568             if (queue->sinkresult != GST_FLOW_OK)
2569               goto out_flushing;
2570             res = queue->last_query;
2571           } else {
2572             GST_DEBUG_OBJECT (queue, "refusing query, downstream might block");
2573             res = FALSE;
2574           }
2575         } else {
2576           GST_DEBUG_OBJECT (queue,
2577               "refusing query, we are not using the queue");
2578           res = FALSE;
2579         }
2580         GST_QUEUE2_MUTEX_UNLOCK (queue);
2581         gst_queue2_post_buffering (queue);
2582       } else {
2583         res = gst_pad_query_default (pad, parent, query);
2584       }
2585       break;
2586   }
2587   return res;
2588
2589   /* ERRORS */
2590 out_flushing:
2591   {
2592     GST_DEBUG_OBJECT (queue, "refusing query, we are flushing");
2593     GST_QUEUE2_MUTEX_UNLOCK (queue);
2594     return FALSE;
2595   }
2596 }
2597
2598 static gboolean
2599 gst_queue2_is_empty (GstQueue2 * queue)
2600 {
2601   /* never empty on EOS */
2602   if (queue->is_eos)
2603     return FALSE;
2604
2605   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2606     return queue->current->writing_pos <= queue->current->max_reading_pos;
2607   } else {
2608     if (queue->queue.length == 0)
2609       return TRUE;
2610   }
2611
2612   return FALSE;
2613 }
2614
2615 static gboolean
2616 gst_queue2_is_filled (GstQueue2 * queue)
2617 {
2618   gboolean res;
2619
2620   /* always filled on EOS */
2621   if (queue->is_eos)
2622     return TRUE;
2623
2624 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2625     (queue->cur_level.format) >= ((alt_max) ? \
2626       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2627
2628   /* if using a ring buffer we're filled if all ring buffer space is used
2629    * _by the current range_ */
2630   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2631     guint64 rb_size = queue->ring_buffer_max_size;
2632     GST_DEBUG_OBJECT (queue,
2633         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2634         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2635     return CHECK_FILLED (bytes, rb_size);
2636   }
2637
2638   /* if using file, we're never filled if we don't have EOS */
2639   if (QUEUE_IS_USING_TEMP_FILE (queue))
2640     return FALSE;
2641
2642   /* we are never filled when we have no buffers at all */
2643   if (queue->cur_level.buffers == 0)
2644     return FALSE;
2645
2646   /* we are filled if one of the current levels exceeds the max */
2647   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2648       || CHECK_FILLED (time, 0);
2649
2650   /* if we need to, use the rate estimate to check against the max time we are
2651    * allowed to queue */
2652   if (queue->use_rate_estimate)
2653     res |= CHECK_FILLED (rate_time, 0);
2654
2655 #undef CHECK_FILLED
2656   return res;
2657 }
2658
2659 static GstFlowReturn
2660 gst_queue2_chain_buffer_or_buffer_list (GstQueue2 * queue,
2661     GstMiniObject * item, GstQueue2ItemType item_type)
2662 {
2663   /* we have to lock the queue since we span threads */
2664   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2665   /* when we received EOS, we refuse more data */
2666   if (queue->is_eos)
2667     goto out_eos;
2668   /* when we received unexpected from downstream, refuse more buffers */
2669   if (queue->unexpected)
2670     goto out_unexpected;
2671
2672   /* while we didn't receive the newsegment, we're seeking and we skip data */
2673   if (queue->seeking)
2674     goto out_seeking;
2675
2676   if (!gst_queue2_wait_free_space (queue))
2677     goto out_flushing;
2678
2679   /* put buffer in queue now */
2680   gst_queue2_locked_enqueue (queue, item, item_type);
2681   GST_QUEUE2_MUTEX_UNLOCK (queue);
2682   gst_queue2_post_buffering (queue);
2683
2684   return GST_FLOW_OK;
2685
2686   /* special conditions */
2687 out_flushing:
2688   {
2689     GstFlowReturn ret = queue->sinkresult;
2690
2691     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2692         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2693     GST_QUEUE2_MUTEX_UNLOCK (queue);
2694     gst_mini_object_unref (item);
2695
2696     return ret;
2697   }
2698 out_eos:
2699   {
2700     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2701     GST_QUEUE2_MUTEX_UNLOCK (queue);
2702     gst_mini_object_unref (item);
2703
2704     return GST_FLOW_EOS;
2705   }
2706 out_seeking:
2707   {
2708     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are seeking");
2709     GST_QUEUE2_MUTEX_UNLOCK (queue);
2710     gst_mini_object_unref (item);
2711
2712     return GST_FLOW_OK;
2713   }
2714 out_unexpected:
2715   {
2716     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2717     GST_QUEUE2_MUTEX_UNLOCK (queue);
2718     gst_mini_object_unref (item);
2719
2720     return GST_FLOW_EOS;
2721   }
2722 }
2723
2724 static GstFlowReturn
2725 gst_queue2_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2726 {
2727   GstQueue2 *queue;
2728
2729   queue = GST_QUEUE2 (parent);
2730
2731   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of "
2732       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
2733       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
2734       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2735       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2736
2737   return gst_queue2_chain_buffer_or_buffer_list (queue,
2738       GST_MINI_OBJECT_CAST (buffer), GST_QUEUE2_ITEM_TYPE_BUFFER);
2739 }
2740
2741 static GstFlowReturn
2742 gst_queue2_chain_list (GstPad * pad, GstObject * parent,
2743     GstBufferList * buffer_list)
2744 {
2745   GstQueue2 *queue;
2746
2747   queue = GST_QUEUE2 (parent);
2748
2749   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2750       "received buffer list %p", buffer_list);
2751
2752   return gst_queue2_chain_buffer_or_buffer_list (queue,
2753       GST_MINI_OBJECT_CAST (buffer_list), GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2754 }
2755
2756 static GstMiniObject *
2757 gst_queue2_dequeue_on_eos (GstQueue2 * queue, GstQueue2ItemType * item_type)
2758 {
2759   GstMiniObject *data;
2760
2761   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
2762
2763   /* stop pushing buffers, we dequeue all items until we see an item that we
2764    * can push again, which is EOS or SEGMENT. If there is nothing in the
2765    * queue we can push, we set a flag to make the sinkpad refuse more
2766    * buffers with an EOS return value until we receive something
2767    * pushable again or we get flushed. */
2768   while ((data = gst_queue2_locked_dequeue (queue, item_type))) {
2769     if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2770       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2771           "dropping EOS buffer %p", data);
2772       gst_buffer_unref (GST_BUFFER_CAST (data));
2773     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2774       GstEvent *event = GST_EVENT_CAST (data);
2775       GstEventType type = GST_EVENT_TYPE (event);
2776
2777       if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
2778         /* we found a pushable item in the queue, push it out */
2779         GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2780             "pushing pushable event %s after EOS", GST_EVENT_TYPE_NAME (event));
2781         return data;
2782       }
2783       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2784           "dropping EOS event %p", event);
2785       gst_event_unref (event);
2786     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2787       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2788           "dropping EOS buffer list %p", data);
2789       gst_buffer_list_unref (GST_BUFFER_LIST_CAST (data));
2790     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2791       queue->last_query = FALSE;
2792       g_cond_signal (&queue->query_handled);
2793       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "dropping EOS query %p", data);
2794     }
2795   }
2796   /* no more items in the queue. Set the unexpected flag so that upstream
2797    * make us refuse any more buffers on the sinkpad. Since we will still
2798    * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
2799    * task function does not shut down. */
2800   queue->unexpected = TRUE;
2801   return NULL;
2802 }
2803
2804 /* dequeue an item from the queue an push it downstream. This functions returns
2805  * the result of the push. */
2806 static GstFlowReturn
2807 gst_queue2_push_one (GstQueue2 * queue)
2808 {
2809   GstFlowReturn result = queue->srcresult;
2810   GstMiniObject *data;
2811   GstQueue2ItemType item_type;
2812
2813   data = gst_queue2_locked_dequeue (queue, &item_type);
2814   if (data == NULL)
2815     goto no_item;
2816
2817 next:
2818   STATUS (queue, queue->srcpad, "We have something dequeud");
2819   g_atomic_int_set (&queue->downstream_may_block,
2820       item_type == GST_QUEUE2_ITEM_TYPE_BUFFER ||
2821       item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2822   GST_QUEUE2_MUTEX_UNLOCK (queue);
2823   gst_queue2_post_buffering (queue);
2824
2825   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2826     GstBuffer *buffer;
2827
2828     buffer = GST_BUFFER_CAST (data);
2829
2830     result = gst_pad_push (queue->srcpad, buffer);
2831     g_atomic_int_set (&queue->downstream_may_block, 0);
2832
2833     /* need to check for srcresult here as well */
2834     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2835     if (result == GST_FLOW_EOS) {
2836       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2837       if (data != NULL)
2838         goto next;
2839       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2840        * to the caller so that the task function does not shut down */
2841       result = GST_FLOW_OK;
2842     }
2843   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2844     GstEvent *event = GST_EVENT_CAST (data);
2845     GstEventType type = GST_EVENT_TYPE (event);
2846
2847     if (type == GST_EVENT_TAG) {
2848       if (queue->use_tags_bitrate) {
2849         GstTagList *tags;
2850         guint bitrate;
2851
2852         gst_event_parse_tag (event, &tags);
2853         if (gst_tag_list_get_uint (tags, GST_TAG_BITRATE, &bitrate) ||
2854             gst_tag_list_get_uint (tags, GST_TAG_NOMINAL_BITRATE, &bitrate)) {
2855           GST_QUEUE2_MUTEX_LOCK (queue);
2856           queue->src_tags_bitrate = bitrate;
2857           GST_QUEUE2_MUTEX_UNLOCK (queue);
2858           GST_LOG_OBJECT (queue, "src pad bitrate from tags now %u", bitrate);
2859         }
2860       }
2861     }
2862
2863     gst_pad_push_event (queue->srcpad, event);
2864
2865     /* if we're EOS, return EOS so that the task pauses. */
2866     if (type == GST_EVENT_EOS) {
2867       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2868           "pushed EOS event %p, return EOS", event);
2869       result = GST_FLOW_EOS;
2870     }
2871
2872     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2873   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2874     GstBufferList *buffer_list;
2875
2876     buffer_list = GST_BUFFER_LIST_CAST (data);
2877
2878     result = gst_pad_push_list (queue->srcpad, buffer_list);
2879     g_atomic_int_set (&queue->downstream_may_block, 0);
2880
2881     /* need to check for srcresult here as well */
2882     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2883     if (result == GST_FLOW_EOS) {
2884       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2885       if (data != NULL)
2886         goto next;
2887       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2888        * to the caller so that the task function does not shut down */
2889       result = GST_FLOW_OK;
2890     }
2891   } else if (item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2892     GstQuery *query = GST_QUERY_CAST (data);
2893
2894     GST_LOG_OBJECT (queue->srcpad, "Peering query %p", query);
2895     queue->last_query = gst_pad_peer_query (queue->srcpad, query);
2896     GST_LOG_OBJECT (queue->srcpad, "Peered query");
2897     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2898         "did query %p, return %d", query, queue->last_query);
2899     g_cond_signal (&queue->query_handled);
2900     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2901     result = GST_FLOW_OK;
2902   }
2903   return result;
2904
2905   /* ERRORS */
2906 no_item:
2907   {
2908     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2909         "exit because we have no item in the queue");
2910     return GST_FLOW_ERROR;
2911   }
2912 out_flushing:
2913   {
2914     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2915     return GST_FLOW_FLUSHING;
2916   }
2917 }
2918
2919 /* called repeatedly with @pad as the source pad. This function should push out
2920  * data to the peer element. */
2921 static void
2922 gst_queue2_loop (GstPad * pad)
2923 {
2924   GstQueue2 *queue;
2925   GstFlowReturn ret;
2926
2927   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2928
2929   /* have to lock for thread-safety */
2930   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2931
2932   if (gst_queue2_is_empty (queue)) {
2933     gboolean started;
2934
2935     /* pause the timer while we wait. The fact that we are waiting does not mean
2936      * the byterate on the output pad is lower */
2937     if ((started = queue->out_timer_started))
2938       g_timer_stop (queue->out_timer);
2939
2940     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2941         "queue is empty, waiting for new data");
2942     do {
2943       /* Wait for data to be available, we could be unlocked because of a flush. */
2944       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2945     }
2946     while (gst_queue2_is_empty (queue));
2947
2948     /* and continue if we were running before */
2949     if (started)
2950       g_timer_continue (queue->out_timer);
2951   }
2952   ret = gst_queue2_push_one (queue);
2953   queue->srcresult = ret;
2954   queue->sinkresult = ret;
2955   if (ret != GST_FLOW_OK)
2956     goto out_flushing;
2957
2958   GST_QUEUE2_MUTEX_UNLOCK (queue);
2959   gst_queue2_post_buffering (queue);
2960
2961   return;
2962
2963   /* ERRORS */
2964 out_flushing:
2965   {
2966     gboolean eos = queue->is_eos;
2967     GstFlowReturn ret = queue->srcresult;
2968
2969     gst_pad_pause_task (queue->srcpad);
2970     if (ret == GST_FLOW_FLUSHING) {
2971       gst_queue2_locked_flush (queue, FALSE, FALSE);
2972     } else {
2973       GST_QUEUE2_SIGNAL_DEL (queue);
2974       queue->last_query = FALSE;
2975       g_cond_signal (&queue->query_handled);
2976     }
2977     GST_QUEUE2_MUTEX_UNLOCK (queue);
2978     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2979         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2980     /* let app know about us giving up if upstream is not expected to do so */
2981     /* EOS is already taken care of elsewhere */
2982     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
2983       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2984           (_("Internal data flow error.")),
2985           ("streaming task paused, reason %s (%d)",
2986               gst_flow_get_name (ret), ret));
2987       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2988     }
2989     return;
2990   }
2991 }
2992
2993 static gboolean
2994 gst_queue2_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2995 {
2996   gboolean res = TRUE;
2997   GstQueue2 *queue = GST_QUEUE2 (parent);
2998
2999 #ifndef GST_DISABLE_GST_DEBUG
3000   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
3001       event, GST_EVENT_TYPE_NAME (event));
3002 #endif
3003
3004   switch (GST_EVENT_TYPE (event)) {
3005     case GST_EVENT_FLUSH_START:
3006       if (QUEUE_IS_USING_QUEUE (queue)) {
3007         /* just forward upstream */
3008         res = gst_pad_push_event (queue->sinkpad, event);
3009       } else {
3010         /* now unblock the getrange function */
3011         GST_QUEUE2_MUTEX_LOCK (queue);
3012         GST_DEBUG_OBJECT (queue, "flushing");
3013         queue->srcresult = GST_FLOW_FLUSHING;
3014         GST_QUEUE2_SIGNAL_ADD (queue);
3015         GST_QUEUE2_MUTEX_UNLOCK (queue);
3016
3017         /* when using a temp file, we eat the event */
3018         res = TRUE;
3019         gst_event_unref (event);
3020       }
3021       break;
3022     case GST_EVENT_FLUSH_STOP:
3023       if (QUEUE_IS_USING_QUEUE (queue)) {
3024         /* just forward upstream */
3025         res = gst_pad_push_event (queue->sinkpad, event);
3026       } else {
3027         /* now unblock the getrange function */
3028         GST_QUEUE2_MUTEX_LOCK (queue);
3029         queue->srcresult = GST_FLOW_OK;
3030         GST_QUEUE2_MUTEX_UNLOCK (queue);
3031
3032         /* when using a temp file, we eat the event */
3033         res = TRUE;
3034         gst_event_unref (event);
3035       }
3036       break;
3037     case GST_EVENT_RECONFIGURE:
3038       GST_QUEUE2_MUTEX_LOCK (queue);
3039       /* assume downstream is linked now and try to push again */
3040       if (queue->srcresult == GST_FLOW_NOT_LINKED) {
3041         queue->srcresult = GST_FLOW_OK;
3042         queue->sinkresult = GST_FLOW_OK;
3043         if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
3044           gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad,
3045               NULL);
3046         }
3047       }
3048       GST_QUEUE2_MUTEX_UNLOCK (queue);
3049
3050       res = gst_pad_push_event (queue->sinkpad, event);
3051       break;
3052     default:
3053       res = gst_pad_push_event (queue->sinkpad, event);
3054       break;
3055   }
3056
3057   return res;
3058 }
3059
3060 static gboolean
3061 gst_queue2_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3062 {
3063   GstQueue2 *queue;
3064
3065   queue = GST_QUEUE2 (parent);
3066
3067   switch (GST_QUERY_TYPE (query)) {
3068     case GST_QUERY_POSITION:
3069     {
3070       gint64 peer_pos;
3071       GstFormat format;
3072
3073       if (!gst_pad_peer_query (queue->sinkpad, query))
3074         goto peer_failed;
3075
3076       /* get peer position */
3077       gst_query_parse_position (query, &format, &peer_pos);
3078
3079       /* FIXME: this code assumes that there's no discont in the queue */
3080       switch (format) {
3081         case GST_FORMAT_BYTES:
3082           peer_pos -= queue->cur_level.bytes;
3083           break;
3084         case GST_FORMAT_TIME:
3085           peer_pos -= queue->cur_level.time;
3086           break;
3087         default:
3088           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
3089               "know how to adjust value", gst_format_get_name (format));
3090           return FALSE;
3091       }
3092       /* set updated position */
3093       gst_query_set_position (query, format, peer_pos);
3094       break;
3095     }
3096     case GST_QUERY_DURATION:
3097     {
3098       GST_DEBUG_OBJECT (queue, "doing peer query");
3099
3100       if (!gst_pad_peer_query (queue->sinkpad, query))
3101         goto peer_failed;
3102
3103       GST_DEBUG_OBJECT (queue, "peer query success");
3104       break;
3105     }
3106     case GST_QUERY_BUFFERING:
3107     {
3108       gint percent;
3109       gboolean is_buffering;
3110       GstBufferingMode mode;
3111       gint avg_in, avg_out;
3112       gint64 buffering_left;
3113
3114       GST_DEBUG_OBJECT (queue, "query buffering");
3115
3116       get_buffering_percent (queue, &is_buffering, &percent);
3117       gst_query_set_buffering_percent (query, is_buffering, percent);
3118
3119       get_buffering_stats (queue, percent, &mode, &avg_in, &avg_out,
3120           &buffering_left);
3121       gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
3122           buffering_left);
3123
3124       if (!QUEUE_IS_USING_QUEUE (queue)) {
3125         /* add ranges for download and ringbuffer buffering */
3126         GstFormat format;
3127         gint64 start, stop, range_start, range_stop;
3128         guint64 writing_pos;
3129         gint64 estimated_total;
3130         gint64 duration;
3131         gboolean peer_res, is_eos;
3132         GstQueue2Range *queued_ranges;
3133
3134         /* we need a current download region */
3135         if (queue->current == NULL)
3136           return FALSE;
3137
3138         writing_pos = queue->current->writing_pos;
3139         is_eos = queue->is_eos;
3140
3141         if (is_eos) {
3142           /* we're EOS, we know the duration in bytes now */
3143           peer_res = TRUE;
3144           duration = writing_pos;
3145         } else {
3146           /* get duration of upstream in bytes */
3147           peer_res = gst_pad_peer_query_duration (queue->sinkpad,
3148               GST_FORMAT_BYTES, &duration);
3149         }
3150
3151         GST_DEBUG_OBJECT (queue, "percent %d, duration %" G_GINT64_FORMAT
3152             ", writing %" G_GINT64_FORMAT, percent, duration, writing_pos);
3153
3154         /* calculate remaining and total download time */
3155         if (peer_res && avg_in > 0.0)
3156           estimated_total = ((duration - writing_pos) * 1000) / avg_in;
3157         else
3158           estimated_total = -1;
3159
3160         GST_DEBUG_OBJECT (queue, "estimated-total %" G_GINT64_FORMAT,
3161             estimated_total);
3162
3163         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
3164
3165         switch (format) {
3166           case GST_FORMAT_PERCENT:
3167             /* we need duration */
3168             if (!peer_res)
3169               goto peer_failed;
3170
3171             start = 0;
3172             /* get our available data relative to the duration */
3173             if (duration != -1)
3174               stop =
3175                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX, writing_pos,
3176                   duration);
3177             else
3178               stop = -1;
3179             break;
3180           case GST_FORMAT_BYTES:
3181             start = 0;
3182             stop = writing_pos;
3183             break;
3184           default:
3185             start = -1;
3186             stop = -1;
3187             break;
3188         }
3189
3190         /* fill out the buffered ranges */
3191         for (queued_ranges = queue->ranges; queued_ranges;
3192             queued_ranges = queued_ranges->next) {
3193           switch (format) {
3194             case GST_FORMAT_PERCENT:
3195               if (duration == -1) {
3196                 range_start = 0;
3197                 range_stop = 0;
3198                 break;
3199               }
3200               range_start =
3201                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
3202                   queued_ranges->offset, duration);
3203               range_stop =
3204                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
3205                   queued_ranges->writing_pos, duration);
3206               break;
3207             case GST_FORMAT_BYTES:
3208               range_start = queued_ranges->offset;
3209               range_stop = queued_ranges->writing_pos;
3210               break;
3211             default:
3212               range_start = -1;
3213               range_stop = -1;
3214               break;
3215           }
3216           if (range_start == range_stop)
3217             continue;
3218           GST_DEBUG_OBJECT (queue,
3219               "range starting at %" G_GINT64_FORMAT " and finishing at %"
3220               G_GINT64_FORMAT, range_start, range_stop);
3221           gst_query_add_buffering_range (query, range_start, range_stop);
3222         }
3223
3224         gst_query_set_buffering_range (query, format, start, stop,
3225             estimated_total);
3226       }
3227       break;
3228     }
3229     case GST_QUERY_SCHEDULING:
3230     {
3231       gboolean pull_mode;
3232       GstSchedulingFlags flags = 0;
3233
3234       if (!gst_pad_peer_query (queue->sinkpad, query))
3235         goto peer_failed;
3236
3237       gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
3238
3239       /* we can operate in pull mode when we are using a tempfile */
3240       pull_mode = !QUEUE_IS_USING_QUEUE (queue);
3241
3242       if (pull_mode)
3243         flags |= GST_SCHEDULING_FLAG_SEEKABLE;
3244       gst_query_set_scheduling (query, flags, 0, -1, 0);
3245       if (pull_mode)
3246         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
3247       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
3248       break;
3249     }
3250     default:
3251       /* peer handled other queries */
3252       if (!gst_pad_query_default (pad, parent, query))
3253         goto peer_failed;
3254       break;
3255   }
3256
3257   return TRUE;
3258
3259   /* ERRORS */
3260 peer_failed:
3261   {
3262     GST_DEBUG_OBJECT (queue, "failed peer query");
3263     return FALSE;
3264   }
3265 }
3266
3267 static gboolean
3268 gst_queue2_handle_query (GstElement * element, GstQuery * query)
3269 {
3270   GstQueue2 *queue = GST_QUEUE2 (element);
3271
3272   /* simply forward to the srcpad query function */
3273   return gst_queue2_handle_src_query (queue->srcpad, GST_OBJECT_CAST (element),
3274       query);
3275 }
3276
3277 static void
3278 gst_queue2_update_upstream_size (GstQueue2 * queue)
3279 {
3280   gint64 upstream_size = -1;
3281
3282   if (gst_pad_peer_query_duration (queue->sinkpad, GST_FORMAT_BYTES,
3283           &upstream_size)) {
3284     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
3285
3286     /* upstream_size can be negative but queue->upstream_size is unsigned.
3287      * Prevent setting negative values to it (the query can return -1) */
3288     if (upstream_size >= 0)
3289       queue->upstream_size = upstream_size;
3290     else
3291       queue->upstream_size = 0;
3292   }
3293 }
3294
3295 static GstFlowReturn
3296 gst_queue2_get_range (GstPad * pad, GstObject * parent, guint64 offset,
3297     guint length, GstBuffer ** buffer)
3298 {
3299   GstQueue2 *queue;
3300   GstFlowReturn ret;
3301
3302   queue = GST_QUEUE2_CAST (parent);
3303
3304   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
3305   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
3306   offset = (offset == -1) ? queue->current->reading_pos : offset;
3307
3308   GST_DEBUG_OBJECT (queue,
3309       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
3310
3311   /* catch any reads beyond the size of the file here to make sure queue2
3312    * doesn't send seek events beyond the size of the file upstream, since
3313    * that would confuse elements such as souphttpsrc and/or http servers.
3314    * Demuxers often just loop until EOS at the end of the file to figure out
3315    * when they've read all the end-headers or index chunks. */
3316   if (G_UNLIKELY (offset >= queue->upstream_size)) {
3317     gst_queue2_update_upstream_size (queue);
3318     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
3319       goto out_unexpected;
3320   }
3321
3322   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
3323     gst_queue2_update_upstream_size (queue);
3324     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
3325       length = queue->upstream_size - offset;
3326       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
3327     }
3328   }
3329
3330   /* FIXME - function will block when the range is not yet available */
3331   ret = gst_queue2_create_read (queue, offset, length, buffer);
3332   GST_QUEUE2_MUTEX_UNLOCK (queue);
3333   gst_queue2_post_buffering (queue);
3334
3335   return ret;
3336
3337   /* ERRORS */
3338 out_flushing:
3339   {
3340     ret = queue->srcresult;
3341
3342     GST_DEBUG_OBJECT (queue, "we are flushing");
3343     GST_QUEUE2_MUTEX_UNLOCK (queue);
3344     return ret;
3345   }
3346 out_unexpected:
3347   {
3348     GST_DEBUG_OBJECT (queue, "read beyond end of file");
3349     GST_QUEUE2_MUTEX_UNLOCK (queue);
3350     return GST_FLOW_EOS;
3351   }
3352 }
3353
3354 /* sink currently only operates in push mode */
3355 static gboolean
3356 gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
3357     GstPadMode mode, gboolean active)
3358 {
3359   gboolean result;
3360   GstQueue2 *queue;
3361
3362   queue = GST_QUEUE2 (parent);
3363
3364   switch (mode) {
3365     case GST_PAD_MODE_PUSH:
3366       if (active) {
3367         GST_QUEUE2_MUTEX_LOCK (queue);
3368         GST_DEBUG_OBJECT (queue, "activating push mode");
3369         queue->srcresult = GST_FLOW_OK;
3370         queue->sinkresult = GST_FLOW_OK;
3371         queue->is_eos = FALSE;
3372         queue->unexpected = FALSE;
3373         reset_rate_timer (queue);
3374         GST_QUEUE2_MUTEX_UNLOCK (queue);
3375       } else {
3376         /* unblock chain function */
3377         GST_QUEUE2_MUTEX_LOCK (queue);
3378         GST_DEBUG_OBJECT (queue, "deactivating push mode");
3379         queue->srcresult = GST_FLOW_FLUSHING;
3380         queue->sinkresult = GST_FLOW_FLUSHING;
3381         GST_QUEUE2_SIGNAL_DEL (queue);
3382         GST_QUEUE2_MUTEX_UNLOCK (queue);
3383
3384         /* wait until it is unblocked and clean up */
3385         GST_PAD_STREAM_LOCK (pad);
3386         GST_QUEUE2_MUTEX_LOCK (queue);
3387         gst_queue2_locked_flush (queue, TRUE, FALSE);
3388         GST_QUEUE2_MUTEX_UNLOCK (queue);
3389         GST_PAD_STREAM_UNLOCK (pad);
3390       }
3391       result = TRUE;
3392       break;
3393     default:
3394       result = FALSE;
3395       break;
3396   }
3397   return result;
3398 }
3399
3400 /* src operating in push mode, we start a task on the source pad that pushes out
3401  * buffers from the queue */
3402 static gboolean
3403 gst_queue2_src_activate_push (GstPad * pad, GstObject * parent, gboolean active)
3404 {
3405   gboolean result = FALSE;
3406   GstQueue2 *queue;
3407
3408   queue = GST_QUEUE2 (parent);
3409
3410   if (active) {
3411     GST_QUEUE2_MUTEX_LOCK (queue);
3412     GST_DEBUG_OBJECT (queue, "activating push mode");
3413     queue->srcresult = GST_FLOW_OK;
3414     queue->sinkresult = GST_FLOW_OK;
3415     queue->is_eos = FALSE;
3416     queue->unexpected = FALSE;
3417     result =
3418         gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad, NULL);
3419     GST_QUEUE2_MUTEX_UNLOCK (queue);
3420   } else {
3421     /* unblock loop function */
3422     GST_QUEUE2_MUTEX_LOCK (queue);
3423     GST_DEBUG_OBJECT (queue, "deactivating push mode");
3424     queue->srcresult = GST_FLOW_FLUSHING;
3425     queue->sinkresult = GST_FLOW_FLUSHING;
3426     /* the item add signal will unblock */
3427     GST_QUEUE2_SIGNAL_ADD (queue);
3428     GST_QUEUE2_MUTEX_UNLOCK (queue);
3429
3430     /* step 2, make sure streaming finishes */
3431     result = gst_pad_stop_task (pad);
3432   }
3433
3434   return result;
3435 }
3436
3437 /* pull mode, downstream will call our getrange function */
3438 static gboolean
3439 gst_queue2_src_activate_pull (GstPad * pad, GstObject * parent, gboolean active)
3440 {
3441   gboolean result;
3442   GstQueue2 *queue;
3443
3444   queue = GST_QUEUE2 (parent);
3445
3446   if (active) {
3447     GST_QUEUE2_MUTEX_LOCK (queue);
3448     if (!QUEUE_IS_USING_QUEUE (queue)) {
3449       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3450         /* open the temp file now */
3451         result = gst_queue2_open_temp_location_file (queue);
3452       } else if (!queue->ring_buffer) {
3453         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
3454         result = ! !queue->ring_buffer;
3455       } else {
3456         result = TRUE;
3457       }
3458
3459       GST_DEBUG_OBJECT (queue, "activating pull mode");
3460       init_ranges (queue);
3461       queue->srcresult = GST_FLOW_OK;
3462       queue->sinkresult = GST_FLOW_OK;
3463       queue->is_eos = FALSE;
3464       queue->unexpected = FALSE;
3465       queue->upstream_size = 0;
3466     } else {
3467       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
3468       /* this is not allowed, we cannot operate in pull mode without a temp
3469        * file. */
3470       queue->srcresult = GST_FLOW_FLUSHING;
3471       queue->sinkresult = GST_FLOW_FLUSHING;
3472       result = FALSE;
3473     }
3474     GST_QUEUE2_MUTEX_UNLOCK (queue);
3475   } else {
3476     GST_QUEUE2_MUTEX_LOCK (queue);
3477     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
3478     queue->srcresult = GST_FLOW_FLUSHING;
3479     queue->sinkresult = GST_FLOW_FLUSHING;
3480     /* this will unlock getrange */
3481     GST_QUEUE2_SIGNAL_ADD (queue);
3482     result = TRUE;
3483     GST_QUEUE2_MUTEX_UNLOCK (queue);
3484   }
3485
3486   return result;
3487 }
3488
3489 static gboolean
3490 gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
3491     gboolean active)
3492 {
3493   gboolean res;
3494
3495   switch (mode) {
3496     case GST_PAD_MODE_PULL:
3497       res = gst_queue2_src_activate_pull (pad, parent, active);
3498       break;
3499     case GST_PAD_MODE_PUSH:
3500       res = gst_queue2_src_activate_push (pad, parent, active);
3501       break;
3502     default:
3503       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
3504       res = FALSE;
3505       break;
3506   }
3507   return res;
3508 }
3509
3510 static GstStateChangeReturn
3511 gst_queue2_change_state (GstElement * element, GstStateChange transition)
3512 {
3513   GstQueue2 *queue;
3514   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3515
3516   queue = GST_QUEUE2 (element);
3517
3518   switch (transition) {
3519     case GST_STATE_CHANGE_NULL_TO_READY:
3520       break;
3521     case GST_STATE_CHANGE_READY_TO_PAUSED:
3522       GST_QUEUE2_MUTEX_LOCK (queue);
3523       if (!QUEUE_IS_USING_QUEUE (queue)) {
3524         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3525           if (!gst_queue2_open_temp_location_file (queue))
3526             ret = GST_STATE_CHANGE_FAILURE;
3527         } else {
3528           if (queue->ring_buffer) {
3529             g_free (queue->ring_buffer);
3530             queue->ring_buffer = NULL;
3531           }
3532           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
3533             ret = GST_STATE_CHANGE_FAILURE;
3534         }
3535         init_ranges (queue);
3536       }
3537       queue->segment_event_received = FALSE;
3538       queue->starting_segment = NULL;
3539       gst_event_replace (&queue->stream_start_event, NULL);
3540       GST_QUEUE2_MUTEX_UNLOCK (queue);
3541       break;
3542     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3543       break;
3544     default:
3545       break;
3546   }
3547
3548   if (ret == GST_STATE_CHANGE_FAILURE)
3549     return ret;
3550
3551   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3552
3553   if (ret == GST_STATE_CHANGE_FAILURE)
3554     return ret;
3555
3556   switch (transition) {
3557     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3558       break;
3559     case GST_STATE_CHANGE_PAUSED_TO_READY:
3560       GST_QUEUE2_MUTEX_LOCK (queue);
3561       if (!QUEUE_IS_USING_QUEUE (queue)) {
3562         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3563           gst_queue2_close_temp_location_file (queue);
3564         } else if (queue->ring_buffer) {
3565           g_free (queue->ring_buffer);
3566           queue->ring_buffer = NULL;
3567         }
3568         clean_ranges (queue);
3569       }
3570       if (queue->starting_segment != NULL) {
3571         gst_event_unref (queue->starting_segment);
3572         queue->starting_segment = NULL;
3573       }
3574       gst_event_replace (&queue->stream_start_event, NULL);
3575       GST_QUEUE2_MUTEX_UNLOCK (queue);
3576       break;
3577     case GST_STATE_CHANGE_READY_TO_NULL:
3578       break;
3579     default:
3580       break;
3581   }
3582
3583   return ret;
3584 }
3585
3586 /* changing the capacity of the queue must wake up
3587  * the _chain function, it might have more room now
3588  * to store the buffer/event in the queue */
3589 #define QUEUE_CAPACITY_CHANGE(q) \
3590   GST_QUEUE2_SIGNAL_DEL (queue); \
3591   if (queue->use_buffering)      \
3592     update_buffering (queue);
3593
3594 /* Changing the minimum required fill level must
3595  * wake up the _loop function as it might now
3596  * be able to preceed.
3597  */
3598 #define QUEUE_THRESHOLD_CHANGE(q)\
3599   GST_QUEUE2_SIGNAL_ADD (queue);
3600
3601 static void
3602 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
3603 {
3604   GstState state;
3605
3606   /* the element must be stopped in order to do this */
3607   GST_OBJECT_LOCK (queue);
3608   state = GST_STATE (queue);
3609   if (state != GST_STATE_READY && state != GST_STATE_NULL)
3610     goto wrong_state;
3611   GST_OBJECT_UNLOCK (queue);
3612
3613   /* set new location */
3614   g_free (queue->temp_template);
3615   queue->temp_template = g_strdup (template);
3616
3617   return;
3618
3619 /* ERROR */
3620 wrong_state:
3621   {
3622     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
3623     GST_OBJECT_UNLOCK (queue);
3624   }
3625 }
3626
3627 static void
3628 gst_queue2_set_property (GObject * object,
3629     guint prop_id, const GValue * value, GParamSpec * pspec)
3630 {
3631   GstQueue2 *queue = GST_QUEUE2 (object);
3632
3633   /* someone could change levels here, and since this
3634    * affects the get/put funcs, we need to lock for safety. */
3635   GST_QUEUE2_MUTEX_LOCK (queue);
3636
3637   switch (prop_id) {
3638     case PROP_MAX_SIZE_BYTES:
3639       queue->max_level.bytes = g_value_get_uint (value);
3640       QUEUE_CAPACITY_CHANGE (queue);
3641       break;
3642     case PROP_MAX_SIZE_BUFFERS:
3643       queue->max_level.buffers = g_value_get_uint (value);
3644       QUEUE_CAPACITY_CHANGE (queue);
3645       break;
3646     case PROP_MAX_SIZE_TIME:
3647       queue->max_level.time = g_value_get_uint64 (value);
3648       /* set rate_time to the same value. We use an extra field in the level
3649        * structure so that we can easily access and compare it */
3650       queue->max_level.rate_time = queue->max_level.time;
3651       QUEUE_CAPACITY_CHANGE (queue);
3652       break;
3653     case PROP_USE_BUFFERING:
3654       queue->use_buffering = g_value_get_boolean (value);
3655       if (!queue->use_buffering && queue->is_buffering) {
3656         GST_DEBUG_OBJECT (queue, "Disabled buffering while buffering, "
3657             "posting 100%% message");
3658         SET_PERCENT (queue, 100);
3659         queue->is_buffering = FALSE;
3660       }
3661
3662       if (queue->use_buffering) {
3663         queue->is_buffering = TRUE;
3664         update_buffering (queue);
3665       }
3666       break;
3667     case PROP_USE_TAGS_BITRATE:
3668       queue->use_tags_bitrate = g_value_get_boolean (value);
3669       break;
3670     case PROP_USE_RATE_ESTIMATE:
3671       queue->use_rate_estimate = g_value_get_boolean (value);
3672       break;
3673     case PROP_LOW_PERCENT:
3674       queue->low_percent = g_value_get_int (value);
3675       break;
3676     case PROP_HIGH_PERCENT:
3677       queue->high_percent = g_value_get_int (value);
3678       break;
3679     case PROP_TEMP_TEMPLATE:
3680       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3681       break;
3682     case PROP_TEMP_REMOVE:
3683       queue->temp_remove = g_value_get_boolean (value);
3684       break;
3685     case PROP_RING_BUFFER_MAX_SIZE:
3686       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3687       break;
3688     default:
3689       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3690       break;
3691   }
3692
3693   GST_QUEUE2_MUTEX_UNLOCK (queue);
3694   gst_queue2_post_buffering (queue);
3695 }
3696
3697 static void
3698 gst_queue2_get_property (GObject * object,
3699     guint prop_id, GValue * value, GParamSpec * pspec)
3700 {
3701   GstQueue2 *queue = GST_QUEUE2 (object);
3702
3703   GST_QUEUE2_MUTEX_LOCK (queue);
3704
3705   switch (prop_id) {
3706     case PROP_CUR_LEVEL_BYTES:
3707       g_value_set_uint (value, queue->cur_level.bytes);
3708       break;
3709     case PROP_CUR_LEVEL_BUFFERS:
3710       g_value_set_uint (value, queue->cur_level.buffers);
3711       break;
3712     case PROP_CUR_LEVEL_TIME:
3713       g_value_set_uint64 (value, queue->cur_level.time);
3714       break;
3715     case PROP_MAX_SIZE_BYTES:
3716       g_value_set_uint (value, queue->max_level.bytes);
3717       break;
3718     case PROP_MAX_SIZE_BUFFERS:
3719       g_value_set_uint (value, queue->max_level.buffers);
3720       break;
3721     case PROP_MAX_SIZE_TIME:
3722       g_value_set_uint64 (value, queue->max_level.time);
3723       break;
3724     case PROP_USE_BUFFERING:
3725       g_value_set_boolean (value, queue->use_buffering);
3726       break;
3727     case PROP_USE_TAGS_BITRATE:
3728       g_value_set_boolean (value, queue->use_tags_bitrate);
3729       break;
3730     case PROP_USE_RATE_ESTIMATE:
3731       g_value_set_boolean (value, queue->use_rate_estimate);
3732       break;
3733     case PROP_LOW_PERCENT:
3734       g_value_set_int (value, queue->low_percent);
3735       break;
3736     case PROP_HIGH_PERCENT:
3737       g_value_set_int (value, queue->high_percent);
3738       break;
3739     case PROP_TEMP_TEMPLATE:
3740       g_value_set_string (value, queue->temp_template);
3741       break;
3742     case PROP_TEMP_LOCATION:
3743       g_value_set_string (value, queue->temp_location);
3744       break;
3745     case PROP_TEMP_REMOVE:
3746       g_value_set_boolean (value, queue->temp_remove);
3747       break;
3748     case PROP_RING_BUFFER_MAX_SIZE:
3749       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3750       break;
3751     case PROP_AVG_IN_RATE:
3752     {
3753       gdouble in_rate = queue->byte_in_rate;
3754
3755       /* During the first RATE_INTERVAL, byte_in_rate will not have been
3756        * calculated, so calculate it here. */
3757       if (in_rate == 0.0 && queue->bytes_in
3758           && queue->last_update_in_rates_elapsed > 0.0)
3759         in_rate = queue->bytes_in / queue->last_update_in_rates_elapsed;
3760
3761       g_value_set_int64 (value, (gint64) in_rate);
3762       break;
3763     }
3764     default:
3765       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3766       break;
3767   }
3768
3769   GST_QUEUE2_MUTEX_UNLOCK (queue);
3770 }