query: allow _make_writable on query handlers
[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., 59 Temple Place - Suite 330,
23  * Boston, MA 02111-1307, 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-tmpl 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  * Since 0.10.24, setting the temp-location property with a filename is deprecated
50  * because it's impossible to securely open a temporary file in this way. The
51  * property will still be used to notify the application of the allocated
52  * filename, though.
53  *
54  * Last reviewed on 2009-07-10 (0.10.24)
55  */
56
57 #ifdef HAVE_CONFIG_H
58 #include "config.h"
59 #endif
60
61 #include "gstqueue2.h"
62
63 #include <glib/gstdio.h>
64
65 #include "gst/gst-i18n-lib.h"
66
67 #include <string.h>
68
69 #ifdef G_OS_WIN32
70 #include <io.h>                 /* lseek, open, close, read */
71 #undef lseek
72 #define lseek _lseeki64
73 #undef off_t
74 #define off_t guint64
75 #else
76 #include <unistd.h>
77 #endif
78
79 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
80     GST_PAD_SINK,
81     GST_PAD_ALWAYS,
82     GST_STATIC_CAPS_ANY);
83
84 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
85     GST_PAD_SRC,
86     GST_PAD_ALWAYS,
87     GST_STATIC_CAPS_ANY);
88
89 GST_DEBUG_CATEGORY_STATIC (queue_debug);
90 #define GST_CAT_DEFAULT (queue_debug)
91 GST_DEBUG_CATEGORY_STATIC (queue_dataflow);
92
93 enum
94 {
95   LAST_SIGNAL
96 };
97
98 /* other defines */
99 #define DEFAULT_BUFFER_SIZE 4096
100 #define QUEUE_IS_USING_TEMP_FILE(queue) ((queue)->temp_location_set || (queue)->temp_template != NULL)
101 #define QUEUE_IS_USING_RING_BUFFER(queue) ((queue)->ring_buffer_max_size != 0)  /* for consistency with the above macro */
102 #define QUEUE_IS_USING_QUEUE(queue) (!QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER (queue))
103
104 #define QUEUE_MAX_BYTES(queue) MIN((queue)->max_level.bytes, (queue)->ring_buffer_max_size)
105
106 /* default property values */
107 #define DEFAULT_MAX_SIZE_BUFFERS   100  /* 100 buffers */
108 #define DEFAULT_MAX_SIZE_BYTES     (2 * 1024 * 1024)    /* 2 MB */
109 #define DEFAULT_MAX_SIZE_TIME      2 * GST_SECOND       /* 2 seconds */
110 #define DEFAULT_USE_BUFFERING      FALSE
111 #define DEFAULT_USE_RATE_ESTIMATE  TRUE
112 #define DEFAULT_LOW_PERCENT        10
113 #define DEFAULT_HIGH_PERCENT       99
114 #define DEFAULT_TEMP_REMOVE        TRUE
115 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
116
117 enum
118 {
119   PROP_0,
120   PROP_CUR_LEVEL_BUFFERS,
121   PROP_CUR_LEVEL_BYTES,
122   PROP_CUR_LEVEL_TIME,
123   PROP_MAX_SIZE_BUFFERS,
124   PROP_MAX_SIZE_BYTES,
125   PROP_MAX_SIZE_TIME,
126   PROP_USE_BUFFERING,
127   PROP_USE_RATE_ESTIMATE,
128   PROP_LOW_PERCENT,
129   PROP_HIGH_PERCENT,
130   PROP_TEMP_TEMPLATE,
131   PROP_TEMP_LOCATION,
132   PROP_TEMP_REMOVE,
133   PROP_RING_BUFFER_MAX_SIZE,
134   PROP_LAST
135 };
136
137 #define GST_QUEUE2_CLEAR_LEVEL(l) G_STMT_START {         \
138   l.buffers = 0;                                        \
139   l.bytes = 0;                                          \
140   l.time = 0;                                           \
141   l.rate_time = 0;                                      \
142 } G_STMT_END
143
144 #define STATUS(queue, pad, msg) \
145   GST_CAT_LOG_OBJECT (queue_dataflow, queue, \
146                       "(%s:%s) " msg ": %u of %u buffers, %u of %u " \
147                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
148                       " ns, %"G_GUINT64_FORMAT" items", \
149                       GST_DEBUG_PAD_NAME (pad), \
150                       queue->cur_level.buffers, \
151                       queue->max_level.buffers, \
152                       queue->cur_level.bytes, \
153                       queue->max_level.bytes, \
154                       queue->cur_level.time, \
155                       queue->max_level.time, \
156                       (guint64) (!QUEUE_IS_USING_QUEUE(queue) ? \
157                         queue->current->writing_pos - queue->current->max_reading_pos : \
158                         queue->queue->length))
159
160 #define GST_QUEUE2_MUTEX_LOCK(q) G_STMT_START {                          \
161   g_mutex_lock (q->qlock);                                              \
162 } G_STMT_END
163
164 #define GST_QUEUE2_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
165   GST_QUEUE2_MUTEX_LOCK (q);                                            \
166   if (res != GST_FLOW_OK)                                               \
167     goto label;                                                         \
168 } G_STMT_END
169
170 #define GST_QUEUE2_MUTEX_UNLOCK(q) G_STMT_START {                        \
171   g_mutex_unlock (q->qlock);                                            \
172 } G_STMT_END
173
174 #define GST_QUEUE2_WAIT_DEL_CHECK(q, res, label) G_STMT_START {         \
175   STATUS (queue, q->sinkpad, "wait for DEL");                           \
176   q->waiting_del = TRUE;                                                \
177   g_cond_wait (q->item_del, queue->qlock);                              \
178   q->waiting_del = FALSE;                                               \
179   if (res != GST_FLOW_OK) {                                             \
180     STATUS (queue, q->srcpad, "received DEL wakeup");                   \
181     goto label;                                                         \
182   }                                                                     \
183   STATUS (queue, q->sinkpad, "received DEL");                           \
184 } G_STMT_END
185
186 #define GST_QUEUE2_WAIT_ADD_CHECK(q, res, label) G_STMT_START {         \
187   STATUS (queue, q->srcpad, "wait for ADD");                            \
188   q->waiting_add = TRUE;                                                \
189   g_cond_wait (q->item_add, q->qlock);                                  \
190   q->waiting_add = FALSE;                                               \
191   if (res != GST_FLOW_OK) {                                             \
192     STATUS (queue, q->srcpad, "received ADD wakeup");                   \
193     goto label;                                                         \
194   }                                                                     \
195   STATUS (queue, q->srcpad, "received ADD");                            \
196 } G_STMT_END
197
198 #define GST_QUEUE2_SIGNAL_DEL(q) G_STMT_START {                          \
199   if (q->waiting_del) {                                                 \
200     STATUS (q, q->srcpad, "signal DEL");                                \
201     g_cond_signal (q->item_del);                                        \
202   }                                                                     \
203 } G_STMT_END
204
205 #define GST_QUEUE2_SIGNAL_ADD(q) G_STMT_START {                          \
206   if (q->waiting_add) {                                                 \
207     STATUS (q, q->sinkpad, "signal ADD");                               \
208     g_cond_signal (q->item_add);                                        \
209   }                                                                     \
210 } G_STMT_END
211
212 #define _do_init \
213     GST_DEBUG_CATEGORY_INIT (queue_debug, "queue2", 0, "queue element"); \
214     GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue2_dataflow", 0, \
215         "dataflow inside the queue element");
216 #define gst_queue2_parent_class parent_class
217 G_DEFINE_TYPE_WITH_CODE (GstQueue2, gst_queue2, GST_TYPE_ELEMENT, _do_init);
218
219 static void gst_queue2_finalize (GObject * object);
220
221 static void gst_queue2_set_property (GObject * object,
222     guint prop_id, const GValue * value, GParamSpec * pspec);
223 static void gst_queue2_get_property (GObject * object,
224     guint prop_id, GValue * value, GParamSpec * pspec);
225
226 static GstFlowReturn gst_queue2_chain (GstPad * pad, GstBuffer * buffer);
227 static GstFlowReturn gst_queue2_push_one (GstQueue2 * queue);
228 static void gst_queue2_loop (GstPad * pad);
229
230 static gboolean gst_queue2_handle_sink_event (GstPad * pad, GstEvent * event);
231
232 static gboolean gst_queue2_handle_src_event (GstPad * pad, GstEvent * event);
233 static gboolean gst_queue2_handle_src_query (GstPad * pad, GstQuery ** query);
234 static gboolean gst_queue2_handle_query (GstElement * element,
235     GstQuery ** query);
236
237 static GstCaps *gst_queue2_getcaps (GstPad * pad);
238 static gboolean gst_queue2_acceptcaps (GstPad * pad, GstCaps * caps);
239
240 static GstFlowReturn gst_queue2_get_range (GstPad * pad, guint64 offset,
241     guint length, GstBuffer ** buffer);
242 static gboolean gst_queue2_src_checkgetrange_function (GstPad * pad);
243
244 static gboolean gst_queue2_src_activate_pull (GstPad * pad, gboolean active);
245 static gboolean gst_queue2_src_activate_push (GstPad * pad, gboolean active);
246 static gboolean gst_queue2_sink_activate_push (GstPad * pad, gboolean active);
247 static GstStateChangeReturn gst_queue2_change_state (GstElement * element,
248     GstStateChange transition);
249
250 static gboolean gst_queue2_is_empty (GstQueue2 * queue);
251 static gboolean gst_queue2_is_filled (GstQueue2 * queue);
252
253 static void update_cur_level (GstQueue2 * queue, GstQueue2Range * range);
254
255 /* static guint gst_queue2_signals[LAST_SIGNAL] = { 0 }; */
256
257 static void
258 gst_queue2_class_init (GstQueue2Class * klass)
259 {
260   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
261   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
262
263   gobject_class->set_property = gst_queue2_set_property;
264   gobject_class->get_property = gst_queue2_get_property;
265
266   /* properties */
267   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
268       g_param_spec_uint ("current-level-bytes", "Current level (kB)",
269           "Current amount of data in the queue (bytes)",
270           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
271   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
272       g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
273           "Current number of buffers in the queue",
274           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
275   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
276       g_param_spec_uint64 ("current-level-time", "Current level (ns)",
277           "Current amount of data in the queue (in ns)",
278           0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
279
280   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
281       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
282           "Max. amount of data in the queue (bytes, 0=disable)",
283           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
284           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
285   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
286       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
287           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
288           DEFAULT_MAX_SIZE_BUFFERS,
289           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
290   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
291       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
292           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
293           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
294
295   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
296       g_param_spec_boolean ("use-buffering", "Use buffering",
297           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
298           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
299   g_object_class_install_property (gobject_class, PROP_USE_RATE_ESTIMATE,
300       g_param_spec_boolean ("use-rate-estimate", "Use Rate Estimate",
301           "Estimate the bitrate of the stream to calculate time level",
302           DEFAULT_USE_RATE_ESTIMATE,
303           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
304   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
305       g_param_spec_int ("low-percent", "Low percent",
306           "Low threshold for buffering to start. Only used if use-buffering is True",
307           0, 100, DEFAULT_LOW_PERCENT,
308           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
309   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
310       g_param_spec_int ("high-percent", "High percent",
311           "High threshold for buffering to finish. Only used if use-buffering is True",
312           0, 100, DEFAULT_HIGH_PERCENT,
313           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
314
315   g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
316       g_param_spec_string ("temp-template", "Temporary File Template",
317           "File template to store temporary files in, should contain directory "
318           "and XXXXXX. (NULL == disabled)",
319           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
320
321   g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
322       g_param_spec_string ("temp-location", "Temporary File Location",
323           "Location to store temporary files in (Deprecated: Only read this "
324           "property, use temp-template to configure the name template)",
325           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
326
327   /**
328    * GstQueue2:temp-remove
329    *
330    * When temp-template is set, remove the temporary file when going to READY.
331    *
332    * Since: 0.10.26
333    */
334   g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
335       g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
336           "Remove the temp-location after use",
337           DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338
339   /**
340    * GstQueue2:ring-buffer-max-size
341    *
342    * The maximum size of the ring buffer in bytes. If set to 0, the ring
343    * buffer is disabled. Default 0.
344    *
345    * Since: 0.10.31
346    */
347   g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
348       g_param_spec_uint64 ("ring-buffer-max-size",
349           "Max. ring buffer size (bytes)",
350           "Max. amount of data in the ring buffer (bytes, 0 = disabled)",
351           0, G_MAXUINT64, DEFAULT_RING_BUFFER_MAX_SIZE,
352           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
353
354   /* set several parent class virtual functions */
355   gobject_class->finalize = gst_queue2_finalize;
356
357   gst_element_class_add_pad_template (gstelement_class,
358       gst_static_pad_template_get (&srctemplate));
359   gst_element_class_add_pad_template (gstelement_class,
360       gst_static_pad_template_get (&sinktemplate));
361
362   gst_element_class_set_details_simple (gstelement_class, "Queue 2",
363       "Generic",
364       "Simple data queue",
365       "Erik Walthinsen <omega@cse.ogi.edu>, "
366       "Wim Taymans <wim.taymans@gmail.com>");
367
368   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_queue2_change_state);
369   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_queue2_handle_query);
370 }
371
372 static void
373 gst_queue2_init (GstQueue2 * queue)
374 {
375   queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
376
377   gst_pad_set_chain_function (queue->sinkpad,
378       GST_DEBUG_FUNCPTR (gst_queue2_chain));
379   gst_pad_set_activatepush_function (queue->sinkpad,
380       GST_DEBUG_FUNCPTR (gst_queue2_sink_activate_push));
381   gst_pad_set_event_function (queue->sinkpad,
382       GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_event));
383   gst_pad_set_getcaps_function (queue->sinkpad,
384       GST_DEBUG_FUNCPTR (gst_queue2_getcaps));
385   gst_pad_set_acceptcaps_function (queue->sinkpad,
386       GST_DEBUG_FUNCPTR (gst_queue2_acceptcaps));
387   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
388
389   queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
390
391   gst_pad_set_activatepull_function (queue->srcpad,
392       GST_DEBUG_FUNCPTR (gst_queue2_src_activate_pull));
393   gst_pad_set_activatepush_function (queue->srcpad,
394       GST_DEBUG_FUNCPTR (gst_queue2_src_activate_push));
395   gst_pad_set_getrange_function (queue->srcpad,
396       GST_DEBUG_FUNCPTR (gst_queue2_get_range));
397   gst_pad_set_checkgetrange_function (queue->srcpad,
398       GST_DEBUG_FUNCPTR (gst_queue2_src_checkgetrange_function));
399   gst_pad_set_getcaps_function (queue->srcpad,
400       GST_DEBUG_FUNCPTR (gst_queue2_getcaps));
401   gst_pad_set_acceptcaps_function (queue->srcpad,
402       GST_DEBUG_FUNCPTR (gst_queue2_acceptcaps));
403   gst_pad_set_event_function (queue->srcpad,
404       GST_DEBUG_FUNCPTR (gst_queue2_handle_src_event));
405   gst_pad_set_query_function (queue->srcpad,
406       GST_DEBUG_FUNCPTR (gst_queue2_handle_src_query));
407   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
408
409   /* levels */
410   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
411   queue->max_level.buffers = DEFAULT_MAX_SIZE_BUFFERS;
412   queue->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
413   queue->max_level.time = DEFAULT_MAX_SIZE_TIME;
414   queue->max_level.rate_time = DEFAULT_MAX_SIZE_TIME;
415   queue->use_buffering = DEFAULT_USE_BUFFERING;
416   queue->use_rate_estimate = DEFAULT_USE_RATE_ESTIMATE;
417   queue->low_percent = DEFAULT_LOW_PERCENT;
418   queue->high_percent = DEFAULT_HIGH_PERCENT;
419
420   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
421   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
422
423   queue->sinktime = GST_CLOCK_TIME_NONE;
424   queue->srctime = GST_CLOCK_TIME_NONE;
425   queue->sink_tainted = TRUE;
426   queue->src_tainted = TRUE;
427
428   queue->srcresult = GST_FLOW_WRONG_STATE;
429   queue->sinkresult = GST_FLOW_WRONG_STATE;
430   queue->is_eos = FALSE;
431   queue->in_timer = g_timer_new ();
432   queue->out_timer = g_timer_new ();
433
434   queue->qlock = g_mutex_new ();
435   queue->waiting_add = FALSE;
436   queue->item_add = g_cond_new ();
437   queue->waiting_del = FALSE;
438   queue->item_del = g_cond_new ();
439   queue->queue = g_queue_new ();
440
441   queue->buffering_percent = 100;
442
443   /* tempfile related */
444   queue->temp_template = NULL;
445   queue->temp_location = NULL;
446   queue->temp_location_set = FALSE;
447   queue->temp_remove = DEFAULT_TEMP_REMOVE;
448
449   queue->ring_buffer = NULL;
450   queue->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
451
452   GST_DEBUG_OBJECT (queue,
453       "initialized queue's not_empty & not_full conditions");
454 }
455
456 /* called only once, as opposed to dispose */
457 static void
458 gst_queue2_finalize (GObject * object)
459 {
460   GstQueue2 *queue = GST_QUEUE2 (object);
461
462   GST_DEBUG_OBJECT (queue, "finalizing queue");
463
464   while (!g_queue_is_empty (queue->queue)) {
465     GstMiniObject *data = g_queue_pop_head (queue->queue);
466
467     gst_mini_object_unref (data);
468   }
469
470   g_queue_free (queue->queue);
471   g_mutex_free (queue->qlock);
472   g_cond_free (queue->item_add);
473   g_cond_free (queue->item_del);
474   g_timer_destroy (queue->in_timer);
475   g_timer_destroy (queue->out_timer);
476
477   /* temp_file path cleanup  */
478   g_free (queue->temp_template);
479   g_free (queue->temp_location);
480
481   G_OBJECT_CLASS (parent_class)->finalize (object);
482 }
483
484 static void
485 debug_ranges (GstQueue2 * queue)
486 {
487   GstQueue2Range *walk;
488
489   for (walk = queue->ranges; walk; walk = walk->next) {
490     GST_DEBUG_OBJECT (queue,
491         "range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "] (rb [%"
492         G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "]), reading %" G_GUINT64_FORMAT
493         " current range? %s", walk->offset, walk->writing_pos, walk->rb_offset,
494         walk->rb_writing_pos, walk->reading_pos,
495         walk == queue->current ? "**y**" : "  n  ");
496   }
497 }
498
499 /* clear all the downloaded ranges */
500 static void
501 clean_ranges (GstQueue2 * queue)
502 {
503   GST_DEBUG_OBJECT (queue, "clean queue ranges");
504
505   g_slice_free_chain (GstQueue2Range, queue->ranges, next);
506   queue->ranges = NULL;
507   queue->current = NULL;
508 }
509
510 /* find a range that contains @offset or NULL when nothing does */
511 static GstQueue2Range *
512 find_range (GstQueue2 * queue, guint64 offset)
513 {
514   GstQueue2Range *range = NULL;
515   GstQueue2Range *walk;
516
517   /* first do a quick check for the current range */
518   for (walk = queue->ranges; walk; walk = walk->next) {
519     if (offset >= walk->offset && offset <= walk->writing_pos) {
520       /* we can reuse an existing range */
521       range = walk;
522       break;
523     }
524   }
525   if (range) {
526     GST_DEBUG_OBJECT (queue,
527         "found range for %" G_GUINT64_FORMAT ": [%" G_GUINT64_FORMAT "-%"
528         G_GUINT64_FORMAT "]", offset, range->offset, range->writing_pos);
529   } else {
530     GST_DEBUG_OBJECT (queue, "no range for %" G_GUINT64_FORMAT, offset);
531   }
532   return range;
533 }
534
535 static void
536 update_cur_level (GstQueue2 * queue, GstQueue2Range * range)
537 {
538   guint64 max_reading_pos, writing_pos;
539
540   writing_pos = range->writing_pos;
541   max_reading_pos = range->max_reading_pos;
542
543   if (writing_pos > max_reading_pos)
544     queue->cur_level.bytes = writing_pos - max_reading_pos;
545   else
546     queue->cur_level.bytes = 0;
547 }
548
549 /* make a new range for @offset or reuse an existing range */
550 static GstQueue2Range *
551 add_range (GstQueue2 * queue, guint64 offset)
552 {
553   GstQueue2Range *range, *prev, *next;
554
555   GST_DEBUG_OBJECT (queue, "find range for %" G_GUINT64_FORMAT, offset);
556
557   if ((range = find_range (queue, offset))) {
558     GST_DEBUG_OBJECT (queue,
559         "reusing range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, range->offset,
560         range->writing_pos);
561     range->writing_pos = offset;
562   } else {
563     GST_DEBUG_OBJECT (queue,
564         "new range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, offset);
565
566     range = g_slice_new0 (GstQueue2Range);
567     range->offset = offset;
568     /* we want to write to the next location in the ring buffer */
569     range->rb_offset = queue->current ? queue->current->rb_writing_pos : 0;
570     range->writing_pos = offset;
571     range->rb_writing_pos = range->rb_offset;
572     range->reading_pos = offset;
573     range->max_reading_pos = offset;
574
575     /* insert sorted */
576     prev = NULL;
577     next = queue->ranges;
578     while (next) {
579       if (next->offset > offset) {
580         /* insert before next */
581         GST_DEBUG_OBJECT (queue,
582             "insert before range %p, offset %" G_GUINT64_FORMAT, next,
583             next->offset);
584         break;
585       }
586       /* try next */
587       prev = next;
588       next = next->next;
589     }
590     range->next = next;
591     if (prev)
592       prev->next = range;
593     else
594       queue->ranges = range;
595   }
596   debug_ranges (queue);
597
598   /* update the stats for this range */
599   update_cur_level (queue, range);
600
601   return range;
602 }
603
604
605 /* clear and init the download ranges for offset 0 */
606 static void
607 init_ranges (GstQueue2 * queue)
608 {
609   GST_DEBUG_OBJECT (queue, "init queue ranges");
610
611   /* get rid of all the current ranges */
612   clean_ranges (queue);
613   /* make a range for offset 0 */
614   queue->current = add_range (queue, 0);
615 }
616
617 static gboolean
618 gst_queue2_acceptcaps (GstPad * pad, GstCaps * caps)
619 {
620   GstQueue2 *queue;
621   GstPad *otherpad;
622   gboolean result;
623
624   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
625
626   otherpad = (pad == queue->srcpad ? queue->sinkpad : queue->srcpad);
627   result = gst_pad_peer_accept_caps (otherpad, caps);
628
629   return result;
630 }
631
632 static GstCaps *
633 gst_queue2_getcaps (GstPad * pad)
634 {
635   GstQueue2 *queue;
636   GstPad *otherpad;
637   GstCaps *result;
638
639   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
640   if (G_UNLIKELY (queue == NULL))
641     return gst_caps_new_any ();
642
643   otherpad = (pad == queue->srcpad ? queue->sinkpad : queue->srcpad);
644   result = gst_pad_peer_get_caps (otherpad);
645   if (result == NULL)
646     result = gst_caps_new_any ();
647
648   gst_object_unref (queue);
649
650   return result;
651 }
652
653 /* calculate the diff between running time on the sink and src of the queue.
654  * This is the total amount of time in the queue. */
655 static void
656 update_time_level (GstQueue2 * queue)
657 {
658   if (queue->sink_tainted) {
659     queue->sinktime =
660         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
661         queue->sink_segment.last_stop);
662     queue->sink_tainted = FALSE;
663   }
664
665   if (queue->src_tainted) {
666     queue->srctime =
667         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
668         queue->src_segment.last_stop);
669     queue->src_tainted = FALSE;
670   }
671
672   GST_DEBUG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
673       GST_TIME_ARGS (queue->sinktime), GST_TIME_ARGS (queue->srctime));
674
675   if (queue->sinktime != GST_CLOCK_TIME_NONE
676       && queue->srctime != GST_CLOCK_TIME_NONE
677       && queue->sinktime >= queue->srctime)
678     queue->cur_level.time = queue->sinktime - queue->srctime;
679   else
680     queue->cur_level.time = 0;
681 }
682
683 /* take a NEWSEGMENT event and apply the values to segment, updating the time
684  * level of queue. */
685 static void
686 apply_segment (GstQueue2 * queue, GstEvent * event, GstSegment * segment,
687     gboolean is_sink)
688 {
689   gboolean update;
690   GstFormat format;
691   gdouble rate, arate;
692   gint64 start, stop, time;
693
694   gst_event_parse_new_segment (event, &update, &rate, &arate,
695       &format, &start, &stop, &time);
696
697   GST_DEBUG_OBJECT (queue,
698       "received NEWSEGMENT update %d, rate %lf, applied rate %lf, "
699       "format %d, "
700       "%" G_GINT64_FORMAT " -- %" G_GINT64_FORMAT ", time %"
701       G_GINT64_FORMAT, update, rate, arate, format, start, stop, time);
702
703   if (format == GST_FORMAT_BYTES) {
704     if (QUEUE_IS_USING_TEMP_FILE (queue)) {
705       /* start is where we'll be getting from and as such writing next */
706       queue->current = add_range (queue, start);
707       /* update the stats for this range */
708       update_cur_level (queue, queue->current);
709     }
710   }
711
712   /* now configure the values, we use these to track timestamps on the
713    * sinkpad. */
714   if (format != GST_FORMAT_TIME) {
715     /* non-time format, pretent the current time segment is closed with a
716      * 0 start and unknown stop time. */
717     update = FALSE;
718     format = GST_FORMAT_TIME;
719     start = 0;
720     stop = -1;
721     time = 0;
722   }
723   gst_segment_set_newsegment (segment, update,
724       rate, arate, format, start, stop, time);
725
726   GST_DEBUG_OBJECT (queue,
727       "configured NEWSEGMENT %" GST_SEGMENT_FORMAT, segment);
728
729   if (is_sink)
730     queue->sink_tainted = TRUE;
731   else
732     queue->src_tainted = TRUE;
733
734   /* segment can update the time level of the queue */
735   update_time_level (queue);
736 }
737
738 /* take a buffer and update segment, updating the time level of the queue. */
739 static void
740 apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
741     gboolean is_sink)
742 {
743   GstClockTime duration, timestamp;
744
745   timestamp = GST_BUFFER_TIMESTAMP (buffer);
746   duration = GST_BUFFER_DURATION (buffer);
747
748   /* if no timestamp is set, assume it's continuous with the previous
749    * time */
750   if (timestamp == GST_CLOCK_TIME_NONE)
751     timestamp = segment->last_stop;
752
753   /* add duration */
754   if (duration != GST_CLOCK_TIME_NONE)
755     timestamp += duration;
756
757   GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
758       GST_TIME_ARGS (timestamp));
759
760   gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
761
762   if (is_sink)
763     queue->sink_tainted = TRUE;
764   else
765     queue->src_tainted = TRUE;
766
767   /* calc diff with other end */
768   update_time_level (queue);
769 }
770
771 static void
772 update_buffering (GstQueue2 * queue)
773 {
774   gint64 percent;
775   gboolean post = FALSE;
776
777   if (queue->high_percent <= 0)
778     return;
779
780 #define GET_PERCENT(format,alt_max) ((queue->max_level.format) > 0 ? (queue->cur_level.format) * 100 / ((alt_max) > 0 ? MIN ((alt_max), (queue->max_level.format)) : (queue->max_level.format)) : 0)
781
782   if (queue->is_eos) {
783     /* on EOS we are always 100% full, we set the var here so that it we can
784      * reuse the logic below to stop buffering */
785     percent = 100;
786     GST_LOG_OBJECT (queue, "we are EOS");
787   } else {
788     /* figure out the percent we are filled, we take the max of all formats. */
789
790     if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
791       percent = GET_PERCENT (bytes, 0);
792     } else {
793       guint64 rb_size = queue->ring_buffer_max_size;
794       percent = GET_PERCENT (bytes, rb_size);
795     }
796     percent = MAX (percent, GET_PERCENT (time, 0));
797     percent = MAX (percent, GET_PERCENT (buffers, 0));
798
799     /* also apply the rate estimate when we need to */
800     if (queue->use_rate_estimate)
801       percent = MAX (percent, GET_PERCENT (rate_time, 0));
802   }
803
804   if (queue->is_buffering) {
805     post = TRUE;
806     /* if we were buffering see if we reached the high watermark */
807     if (percent >= queue->high_percent)
808       queue->is_buffering = FALSE;
809   } else {
810     /* we were not buffering, check if we need to start buffering if we drop
811      * below the low threshold */
812     if (percent < queue->low_percent) {
813       queue->is_buffering = TRUE;
814       queue->buffering_iteration++;
815       post = TRUE;
816     }
817   }
818   if (post) {
819     GstMessage *message;
820     GstBufferingMode mode;
821     gint64 buffering_left = -1;
822
823     /* scale to high percent so that it becomes the 100% mark */
824     percent = percent * 100 / queue->high_percent;
825     /* clip */
826     if (percent > 100)
827       percent = 100;
828
829     if (percent != queue->buffering_percent) {
830       queue->buffering_percent = percent;
831
832       if (!QUEUE_IS_USING_QUEUE (queue)) {
833         GstFormat fmt = GST_FORMAT_BYTES;
834         gint64 duration;
835
836         if (QUEUE_IS_USING_RING_BUFFER (queue))
837           mode = GST_BUFFERING_TIMESHIFT;
838         else
839           mode = GST_BUFFERING_DOWNLOAD;
840
841         if (queue->byte_in_rate > 0) {
842           if (gst_pad_query_peer_duration (queue->sinkpad, &fmt, &duration))
843             buffering_left =
844                 (gdouble) ((duration -
845                     queue->current->writing_pos) * 1000) / queue->byte_in_rate;
846         } else {
847           buffering_left = G_MAXINT64;
848         }
849       } else {
850         mode = GST_BUFFERING_STREAM;
851       }
852
853       GST_DEBUG_OBJECT (queue, "buffering %d percent", (gint) percent);
854       message = gst_message_new_buffering (GST_OBJECT_CAST (queue),
855           (gint) percent);
856       gst_message_set_buffering_stats (message, mode,
857           queue->byte_in_rate, queue->byte_out_rate, buffering_left);
858
859       gst_element_post_message (GST_ELEMENT_CAST (queue), message);
860     }
861   } else {
862     GST_DEBUG_OBJECT (queue, "filled %d percent", (gint) percent);
863   }
864
865 #undef GET_PERCENT
866 }
867
868 static void
869 reset_rate_timer (GstQueue2 * queue)
870 {
871   queue->bytes_in = 0;
872   queue->bytes_out = 0;
873   queue->byte_in_rate = 0.0;
874   queue->byte_out_rate = 0.0;
875   queue->last_in_elapsed = 0.0;
876   queue->last_out_elapsed = 0.0;
877   queue->in_timer_started = FALSE;
878   queue->out_timer_started = FALSE;
879 }
880
881 /* the interval in seconds to recalculate the rate */
882 #define RATE_INTERVAL    0.2
883 /* Tuning for rate estimation. We use a large window for the input rate because
884  * it should be stable when connected to a network. The output rate is less
885  * stable (the elements preroll, queues behind a demuxer fill, ...) and should
886  * therefore adapt more quickly. */
887 #define AVG_IN(avg,val)  ((avg) * 15.0 + (val)) / 16.0
888 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
889
890 static void
891 update_in_rates (GstQueue2 * queue)
892 {
893   gdouble elapsed, period;
894   gdouble byte_in_rate;
895
896   if (!queue->in_timer_started) {
897     queue->in_timer_started = TRUE;
898     g_timer_start (queue->in_timer);
899     return;
900   }
901
902   elapsed = g_timer_elapsed (queue->in_timer, NULL);
903
904   /* recalc after each interval. */
905   if (queue->last_in_elapsed + RATE_INTERVAL < elapsed) {
906     period = elapsed - queue->last_in_elapsed;
907
908     GST_DEBUG_OBJECT (queue,
909         "rates: period %f, in %" G_GUINT64_FORMAT, period, queue->bytes_in);
910
911     byte_in_rate = queue->bytes_in / period;
912
913     if (queue->byte_in_rate == 0.0)
914       queue->byte_in_rate = byte_in_rate;
915     else
916       queue->byte_in_rate = AVG_IN (queue->byte_in_rate, byte_in_rate);
917
918     /* reset the values to calculate rate over the next interval */
919     queue->last_in_elapsed = elapsed;
920     queue->bytes_in = 0;
921   }
922
923   if (queue->byte_in_rate > 0.0) {
924     queue->cur_level.rate_time =
925         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
926   }
927   GST_DEBUG_OBJECT (queue, "rates: in %f, time %" GST_TIME_FORMAT,
928       queue->byte_in_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
929 }
930
931 static void
932 update_out_rates (GstQueue2 * queue)
933 {
934   gdouble elapsed, period;
935   gdouble byte_out_rate;
936
937   if (!queue->out_timer_started) {
938     queue->out_timer_started = TRUE;
939     g_timer_start (queue->out_timer);
940     return;
941   }
942
943   elapsed = g_timer_elapsed (queue->out_timer, NULL);
944
945   /* recalc after each interval. */
946   if (queue->last_out_elapsed + RATE_INTERVAL < elapsed) {
947     period = elapsed - queue->last_out_elapsed;
948
949     GST_DEBUG_OBJECT (queue,
950         "rates: period %f, out %" G_GUINT64_FORMAT, period, queue->bytes_out);
951
952     byte_out_rate = queue->bytes_out / period;
953
954     if (queue->byte_out_rate == 0.0)
955       queue->byte_out_rate = byte_out_rate;
956     else
957       queue->byte_out_rate = AVG_OUT (queue->byte_out_rate, byte_out_rate);
958
959     /* reset the values to calculate rate over the next interval */
960     queue->last_out_elapsed = elapsed;
961     queue->bytes_out = 0;
962   }
963   if (queue->byte_in_rate > 0.0) {
964     queue->cur_level.rate_time =
965         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
966   }
967   GST_DEBUG_OBJECT (queue, "rates: out %f, time %" GST_TIME_FORMAT,
968       queue->byte_out_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
969 }
970
971 static void
972 update_cur_pos (GstQueue2 * queue, GstQueue2Range * range, guint64 pos)
973 {
974   guint64 reading_pos, max_reading_pos;
975
976   reading_pos = pos;
977   max_reading_pos = range->max_reading_pos;
978
979   max_reading_pos = MAX (max_reading_pos, reading_pos);
980
981   GST_DEBUG_OBJECT (queue,
982       "updating max_reading_pos from %" G_GUINT64_FORMAT " to %"
983       G_GUINT64_FORMAT, range->max_reading_pos, max_reading_pos);
984   range->max_reading_pos = max_reading_pos;
985
986   update_cur_level (queue, range);
987 }
988
989 static gboolean
990 perform_seek_to_offset (GstQueue2 * queue, guint64 offset)
991 {
992   GstEvent *event;
993   gboolean res;
994
995   GST_QUEUE2_MUTEX_UNLOCK (queue);
996
997   GST_DEBUG_OBJECT (queue, "Seeking to %" G_GUINT64_FORMAT, offset);
998
999   event =
1000       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1001       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1002       GST_SEEK_TYPE_NONE, -1);
1003
1004   res = gst_pad_push_event (queue->sinkpad, event);
1005   GST_QUEUE2_MUTEX_LOCK (queue);
1006
1007   if (res)
1008     queue->current = add_range (queue, offset);
1009
1010   return res;
1011 }
1012
1013 /* see if there is enough data in the file to read a full buffer */
1014 static gboolean
1015 gst_queue2_have_data (GstQueue2 * queue, guint64 offset, guint length)
1016 {
1017   GstQueue2Range *range;
1018
1019   GST_DEBUG_OBJECT (queue, "looking for offset %" G_GUINT64_FORMAT ", len %u",
1020       offset, length);
1021
1022   if ((range = find_range (queue, offset))) {
1023     if (queue->current != range) {
1024       GST_DEBUG_OBJECT (queue, "switching ranges, do seek to range position");
1025       perform_seek_to_offset (queue, range->writing_pos);
1026     }
1027
1028     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1029         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1030
1031     /* we have a range for offset */
1032     GST_DEBUG_OBJECT (queue,
1033         "we have a range %p, offset %" G_GUINT64_FORMAT ", writing_pos %"
1034         G_GUINT64_FORMAT, range, range->offset, range->writing_pos);
1035
1036     if (!QUEUE_IS_USING_RING_BUFFER (queue) && queue->is_eos)
1037       return TRUE;
1038
1039     if (offset + length <= range->writing_pos)
1040       return TRUE;
1041     else
1042       GST_DEBUG_OBJECT (queue,
1043           "Need more data (%" G_GUINT64_FORMAT " bytes more)",
1044           (offset + length) - range->writing_pos);
1045
1046   } else {
1047     GST_INFO_OBJECT (queue, "not found in any range");
1048     /* we don't have the range, see how far away we are, FIXME, find a good
1049      * threshold based on the incomming rate. */
1050     if (!queue->is_eos && queue->current) {
1051       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1052         if (offset < queue->current->offset || offset >
1053             queue->current->writing_pos + QUEUE_MAX_BYTES (queue) -
1054             queue->cur_level.bytes) {
1055           perform_seek_to_offset (queue, offset);
1056         } else {
1057           GST_INFO_OBJECT (queue,
1058               "requested data is within range, wait for data");
1059         }
1060       } else if (offset < queue->current->writing_pos + 200000) {
1061         update_cur_pos (queue, queue->current, offset + length);
1062         GST_INFO_OBJECT (queue, "wait for data");
1063         return FALSE;
1064       }
1065     }
1066
1067     /* too far away, do a seek */
1068     perform_seek_to_offset (queue, offset);
1069   }
1070
1071   return FALSE;
1072 }
1073
1074 #ifdef HAVE_FSEEKO
1075 #define FSEEK_FILE(file,offset)  (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1076 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1077 #define FSEEK_FILE(file,offset)  (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1078 #else
1079 #define FSEEK_FILE(file,offset)  (fseek (file, offset, SEEK_SET) != 0)
1080 #endif
1081
1082 static GstFlowReturn
1083 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1084     guint8 * dst, gint64 * read_return)
1085 {
1086   guint8 *ring_buffer;
1087   size_t res;
1088
1089   ring_buffer = queue->ring_buffer;
1090
1091   if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1092     goto seek_failed;
1093
1094   /* this should not block */
1095   GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1096       length, offset);
1097   if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1098     res = fread (dst, 1, length, queue->temp_file);
1099   } else {
1100     memcpy (dst, ring_buffer + offset, length);
1101     res = length;
1102   }
1103
1104   GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1105
1106   if (G_UNLIKELY (res < length)) {
1107     if (!QUEUE_IS_USING_TEMP_FILE (queue))
1108       goto could_not_read;
1109     /* check for errors or EOF */
1110     if (ferror (queue->temp_file))
1111       goto could_not_read;
1112     if (feof (queue->temp_file) && length > 0)
1113       goto eos;
1114   }
1115
1116   *read_return = res;
1117
1118   return GST_FLOW_OK;
1119
1120 seek_failed:
1121   {
1122     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1123     return GST_FLOW_ERROR;
1124   }
1125 could_not_read:
1126   {
1127     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1128     return GST_FLOW_ERROR;
1129   }
1130 eos:
1131   {
1132     GST_DEBUG ("non-regular file hits EOS");
1133     return GST_FLOW_UNEXPECTED;
1134   }
1135 }
1136
1137 static GstFlowReturn
1138 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1139     GstBuffer ** buffer)
1140 {
1141   GstBuffer *buf;
1142   guint8 *data;
1143   guint64 file_offset;
1144   guint block_length, remaining, read_length;
1145   guint64 rb_size;
1146   guint64 rpos;
1147   GstFlowReturn ret = GST_FLOW_OK;
1148
1149   /* allocate the output buffer of the requested size */
1150   buf = gst_buffer_new_and_alloc (length);
1151   data = gst_buffer_map (buf, NULL, NULL, GST_MAP_WRITE);
1152
1153   GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1154       offset);
1155
1156   rpos = offset;
1157   rb_size = queue->ring_buffer_max_size;
1158
1159   remaining = length;
1160   while (remaining > 0) {
1161     /* configure how much/whether to read */
1162     if (!gst_queue2_have_data (queue, rpos, remaining)) {
1163       read_length = 0;
1164
1165       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1166         guint64 level;
1167
1168         /* calculate how far away the offset is */
1169         if (queue->current->writing_pos > rpos)
1170           level = queue->current->writing_pos - rpos;
1171         else
1172           level = 0;
1173
1174         GST_DEBUG_OBJECT (queue,
1175             "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1176             ", level %" G_GUINT64_FORMAT,
1177             rpos, queue->current->writing_pos, level);
1178
1179         if (level >= rb_size) {
1180           /* we don't have the data but if we have a ring buffer that is full, we
1181            * need to read */
1182           GST_DEBUG_OBJECT (queue,
1183               "ring buffer full, reading ring-buffer-max-size %"
1184               G_GUINT64_FORMAT " bytes", rb_size);
1185           read_length = rb_size;
1186         } else if (queue->is_eos) {
1187           /* won't get any more data so read any data we have */
1188           if (level) {
1189             GST_DEBUG_OBJECT (queue,
1190                 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1191                 level);
1192             read_length = level;
1193           } else
1194             goto hit_eos;
1195         }
1196       }
1197
1198       if (read_length == 0) {
1199         if (QUEUE_IS_USING_RING_BUFFER (queue)
1200             && queue->current->max_reading_pos > rpos) {
1201           /* protect cached data (data between offset and max_reading_pos)
1202            * and update current level */
1203           GST_DEBUG_OBJECT (queue,
1204               "protecting cached data [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1205               "]", rpos, queue->current->max_reading_pos);
1206           queue->current->max_reading_pos = rpos;
1207           update_cur_level (queue, queue->current);
1208         }
1209         GST_DEBUG_OBJECT (queue, "waiting for add");
1210         GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1211         continue;
1212       }
1213     } else {
1214       /* we have the requested data so read it */
1215       read_length = remaining;
1216     }
1217
1218     /* set range reading_pos to actual reading position for this read */
1219     queue->current->reading_pos = rpos;
1220
1221     /* congfigure how much and from where to read */
1222     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1223       file_offset =
1224           (queue->current->rb_offset + (rpos -
1225               queue->current->offset)) % rb_size;
1226       if (file_offset + read_length > rb_size) {
1227         block_length = rb_size - file_offset;
1228       } else {
1229         block_length = read_length;
1230       }
1231     } else {
1232       file_offset = rpos;
1233       block_length = read_length;
1234     }
1235
1236     /* while we still have data to read, we loop */
1237     while (read_length > 0) {
1238       gint64 read_return;
1239
1240       ret =
1241           gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1242           data, &read_return);
1243       if (ret != GST_FLOW_OK)
1244         goto read_error;
1245
1246       file_offset += read_return;
1247       if (QUEUE_IS_USING_RING_BUFFER (queue))
1248         file_offset %= rb_size;
1249
1250       data += read_return;
1251       read_length -= read_return;
1252       block_length = read_length;
1253       remaining -= read_return;
1254
1255       rpos = (queue->current->reading_pos += read_return);
1256       update_cur_pos (queue, queue->current, queue->current->reading_pos);
1257     }
1258     GST_QUEUE2_SIGNAL_DEL (queue);
1259     GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1260   }
1261
1262   gst_buffer_unmap (buf, data, length);
1263
1264   GST_BUFFER_OFFSET (buf) = offset;
1265   GST_BUFFER_OFFSET_END (buf) = offset + length;
1266
1267   *buffer = buf;
1268
1269   return ret;
1270
1271   /* ERRORS */
1272 hit_eos:
1273   {
1274     GST_DEBUG_OBJECT (queue, "EOS hit and we don't have any requested data");
1275     gst_buffer_unref (buf);
1276     return GST_FLOW_UNEXPECTED;
1277   }
1278 out_flushing:
1279   {
1280     GST_DEBUG_OBJECT (queue, "we are flushing");
1281     gst_buffer_unref (buf);
1282     return GST_FLOW_WRONG_STATE;
1283   }
1284 read_error:
1285   {
1286     GST_DEBUG_OBJECT (queue, "we have a read error");
1287     gst_buffer_unmap (buf, data, 0);
1288     gst_buffer_unref (buf);
1289     return ret;
1290   }
1291 }
1292
1293 /* should be called with QUEUE_LOCK */
1294 static GstMiniObject *
1295 gst_queue2_read_item_from_file (GstQueue2 * queue)
1296 {
1297   GstMiniObject *item;
1298
1299   if (queue->starting_segment != NULL) {
1300     item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1301     queue->starting_segment = NULL;
1302   } else {
1303     GstFlowReturn ret;
1304     GstBuffer *buffer;
1305     guint64 reading_pos;
1306
1307     reading_pos = queue->current->reading_pos;
1308
1309     ret =
1310         gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1311         &buffer);
1312
1313     switch (ret) {
1314       case GST_FLOW_OK:
1315         item = GST_MINI_OBJECT_CAST (buffer);
1316         break;
1317       case GST_FLOW_UNEXPECTED:
1318         item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1319         break;
1320       default:
1321         item = NULL;
1322         break;
1323     }
1324   }
1325   return item;
1326 }
1327
1328 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1329  * the temp filename. */
1330 static gboolean
1331 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1332 {
1333   gint fd = -1;
1334   gchar *name = NULL;
1335
1336   if (queue->temp_file)
1337     goto already_opened;
1338
1339   GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1340
1341   /* we have two cases:
1342    * - temp_location was set to something !NULL (Deprecated). in this case we
1343    *   open the specified filename.
1344    * - temp_template was set, allocate a filename and open that filename
1345    */
1346   if (!queue->temp_location_set) {
1347     /* nothing to do */
1348     if (queue->temp_template == NULL)
1349       goto no_directory;
1350
1351     /* make copy of the template, we don't want to change this */
1352     name = g_strdup (queue->temp_template);
1353     fd = g_mkstemp (name);
1354     if (fd == -1)
1355       goto mkstemp_failed;
1356
1357     /* open the file for update/writing */
1358     queue->temp_file = fdopen (fd, "wb+");
1359     /* error creating file */
1360     if (queue->temp_file == NULL)
1361       goto open_failed;
1362
1363     g_free (queue->temp_location);
1364     queue->temp_location = name;
1365
1366     GST_QUEUE2_MUTEX_UNLOCK (queue);
1367
1368     /* we can't emit the notify with the lock */
1369     g_object_notify (G_OBJECT (queue), "temp-location");
1370
1371     GST_QUEUE2_MUTEX_LOCK (queue);
1372   } else {
1373     /* open the file for update/writing, this is deprecated but we still need to
1374      * support it for API/ABI compatibility */
1375     queue->temp_file = g_fopen (queue->temp_location, "wb+");
1376     /* error creating file */
1377     if (queue->temp_file == NULL)
1378       goto open_failed;
1379   }
1380   GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1381
1382   return TRUE;
1383
1384   /* ERRORS */
1385 already_opened:
1386   {
1387     GST_DEBUG_OBJECT (queue, "temp file was already open");
1388     return TRUE;
1389   }
1390 no_directory:
1391   {
1392     GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1393         (_("No Temp directory specified.")), (NULL));
1394     return FALSE;
1395   }
1396 mkstemp_failed:
1397   {
1398     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1399         (_("Could not create temp file \"%s\"."), queue->temp_template),
1400         GST_ERROR_SYSTEM);
1401     g_free (name);
1402     return FALSE;
1403   }
1404 open_failed:
1405   {
1406     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1407         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1408     g_free (name);
1409     if (fd != -1)
1410       close (fd);
1411     return FALSE;
1412   }
1413 }
1414
1415 static void
1416 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1417 {
1418   /* nothing to do */
1419   if (queue->temp_file == NULL)
1420     return;
1421
1422   GST_DEBUG_OBJECT (queue, "closing temp file");
1423
1424   fflush (queue->temp_file);
1425   fclose (queue->temp_file);
1426
1427   if (queue->temp_remove)
1428     remove (queue->temp_location);
1429
1430   queue->temp_file = NULL;
1431   clean_ranges (queue);
1432 }
1433
1434 static void
1435 gst_queue2_flush_temp_file (GstQueue2 * queue)
1436 {
1437   if (queue->temp_file == NULL)
1438     return;
1439
1440   GST_DEBUG_OBJECT (queue, "flushing temp file");
1441
1442   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1443 }
1444
1445 static void
1446 gst_queue2_locked_flush (GstQueue2 * queue)
1447 {
1448   if (!QUEUE_IS_USING_QUEUE (queue)) {
1449     if (QUEUE_IS_USING_TEMP_FILE (queue))
1450       gst_queue2_flush_temp_file (queue);
1451     init_ranges (queue);
1452   } else {
1453     while (!g_queue_is_empty (queue->queue)) {
1454       GstMiniObject *data = g_queue_pop_head (queue->queue);
1455
1456       /* Then lose another reference because we are supposed to destroy that
1457          data when flushing */
1458       gst_mini_object_unref (data);
1459     }
1460   }
1461   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1462   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1463   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1464   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1465   queue->sink_tainted = queue->src_tainted = TRUE;
1466   if (queue->starting_segment != NULL)
1467     gst_event_unref (queue->starting_segment);
1468   queue->starting_segment = NULL;
1469   queue->segment_event_received = FALSE;
1470
1471   /* we deleted a lot of something */
1472   GST_QUEUE2_SIGNAL_DEL (queue);
1473 }
1474
1475 static gboolean
1476 gst_queue2_wait_free_space (GstQueue2 * queue)
1477 {
1478   /* We make space available if we're "full" according to whatever
1479    * the user defined as "full". */
1480   if (gst_queue2_is_filled (queue)) {
1481     gboolean started;
1482
1483     /* pause the timer while we wait. The fact that we are waiting does not mean
1484      * the byterate on the input pad is lower */
1485     if ((started = queue->in_timer_started))
1486       g_timer_stop (queue->in_timer);
1487
1488     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1489         "queue is full, waiting for free space");
1490     do {
1491       /* Wait for space to be available, we could be unlocked because of a flush. */
1492       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1493     }
1494     while (gst_queue2_is_filled (queue));
1495
1496     /* and continue if we were running before */
1497     if (started)
1498       g_timer_continue (queue->in_timer);
1499   }
1500   return TRUE;
1501
1502   /* ERRORS */
1503 out_flushing:
1504   {
1505     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1506     return FALSE;
1507   }
1508 }
1509
1510 static gboolean
1511 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1512 {
1513   guint8 *odata, *data, *ring_buffer;
1514   guint size, rb_size;
1515   gsize osize;
1516   guint64 writing_pos, new_writing_pos;
1517   GstQueue2Range *range, *prev, *next;
1518
1519   if (QUEUE_IS_USING_RING_BUFFER (queue))
1520     writing_pos = queue->current->rb_writing_pos;
1521   else
1522     writing_pos = queue->current->writing_pos;
1523   ring_buffer = queue->ring_buffer;
1524   rb_size = queue->ring_buffer_max_size;
1525
1526   odata = gst_buffer_map (buffer, &osize, NULL, GST_MAP_READ);
1527
1528   size = osize;
1529   data = odata;
1530
1531   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1532       GST_BUFFER_OFFSET (buffer));
1533
1534   while (size > 0) {
1535     guint to_write;
1536
1537     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1538       gint64 space;
1539
1540       /* calculate the space in the ring buffer not used by data from
1541        * the current range */
1542       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1543         /* wait until there is some free space */
1544         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1545       }
1546       /* get the amount of space we have */
1547       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1548
1549       /* calculate if we need to split or if we can write the entire
1550        * buffer now */
1551       to_write = MIN (size, space);
1552
1553       /* the writing position in the ring buffer after writing (part
1554        * or all of) the buffer */
1555       new_writing_pos = (writing_pos + to_write) % rb_size;
1556
1557       prev = NULL;
1558       range = queue->ranges;
1559
1560       /* if we need to overwrite data in the ring buffer, we need to
1561        * update the ranges
1562        *
1563        * warning: this code is complicated and includes some
1564        * simplifications - pen, paper and diagrams for the cases
1565        * recommended! */
1566       while (range) {
1567         guint64 range_data_start, range_data_end;
1568         GstQueue2Range *range_to_destroy = NULL;
1569
1570         range_data_start = range->rb_offset;
1571         range_data_end = range->rb_writing_pos;
1572
1573         /* handle the special case where the range has no data in it */
1574         if (range->writing_pos == range->offset) {
1575           if (range != queue->current) {
1576             GST_DEBUG_OBJECT (queue,
1577                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1578                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1579             /* remove range */
1580             range_to_destroy = range;
1581             if (prev)
1582               prev->next = range->next;
1583           }
1584           goto next_range;
1585         }
1586
1587         if (range_data_end > range_data_start) {
1588           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1589             goto next_range;
1590
1591           if (new_writing_pos > range_data_start) {
1592             if (new_writing_pos >= range_data_end) {
1593               GST_DEBUG_OBJECT (queue,
1594                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1595                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1596               /* remove range */
1597               range_to_destroy = range;
1598               if (prev)
1599                 prev->next = range->next;
1600             } else {
1601               GST_DEBUG_OBJECT (queue,
1602                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1603                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1604                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1605                   range->offset + new_writing_pos - range_data_start,
1606                   new_writing_pos);
1607               range->offset += (new_writing_pos - range_data_start);
1608               range->rb_offset = new_writing_pos;
1609             }
1610           }
1611         } else {
1612           guint64 new_wpos_virt = writing_pos + to_write;
1613
1614           if (new_wpos_virt <= range_data_start)
1615             goto next_range;
1616
1617           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1618             GST_DEBUG_OBJECT (queue,
1619                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1620                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1621             /* remove range */
1622             range_to_destroy = range;
1623             if (prev)
1624               prev->next = range->next;
1625           } else {
1626             GST_DEBUG_OBJECT (queue,
1627                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1628                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1629                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1630                 range->offset + new_writing_pos - range_data_start,
1631                 new_writing_pos);
1632             range->offset += (new_wpos_virt - range_data_start);
1633             range->rb_offset = new_writing_pos;
1634           }
1635         }
1636
1637       next_range:
1638         if (!range_to_destroy)
1639           prev = range;
1640
1641         range = range->next;
1642         if (range_to_destroy) {
1643           if (range_to_destroy == queue->ranges)
1644             queue->ranges = range;
1645           g_slice_free (GstQueue2Range, range_to_destroy);
1646           range_to_destroy = NULL;
1647         }
1648       }
1649     } else {
1650       to_write = size;
1651       new_writing_pos = writing_pos + to_write;
1652     }
1653
1654     if (QUEUE_IS_USING_TEMP_FILE (queue)
1655         && FSEEK_FILE (queue->temp_file, writing_pos))
1656       goto seek_failed;
1657
1658     if (new_writing_pos > writing_pos) {
1659       GST_INFO_OBJECT (queue,
1660           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1661           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1662           queue->current->writing_pos, queue->current->rb_writing_pos);
1663       /* either not using ring buffer or no wrapping, just write */
1664       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1665         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1666           goto handle_error;
1667       } else {
1668         memcpy (ring_buffer + writing_pos, data, to_write);
1669       }
1670
1671       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1672         /* try to merge with next range */
1673         while ((next = queue->current->next)) {
1674           GST_INFO_OBJECT (queue,
1675               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1676               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1677           if (new_writing_pos < next->offset)
1678             break;
1679
1680           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1681               next->writing_pos);
1682
1683           /* remove the group, we could choose to not read the data in this range
1684            * again. This would involve us doing a seek to the current writing position
1685            * in the range. FIXME, It would probably make sense to do a seek when there
1686            * is a lot of data in the range we merged with to avoid reading it all
1687            * again. */
1688           queue->current->next = next->next;
1689           g_slice_free (GstQueue2Range, next);
1690
1691           debug_ranges (queue);
1692         }
1693         goto update_and_signal;
1694       }
1695     } else {
1696       /* wrapping */
1697       guint block_one, block_two;
1698
1699       block_one = rb_size - writing_pos;
1700       block_two = to_write - block_one;
1701
1702       if (block_one > 0) {
1703         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1704         /* write data to end of ring buffer */
1705         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1706           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1707             goto handle_error;
1708         } else {
1709           memcpy (ring_buffer + writing_pos, data, block_one);
1710         }
1711       }
1712
1713       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1714         goto seek_failed;
1715
1716       if (block_two > 0) {
1717         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
1718         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1719           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
1720             goto handle_error;
1721         } else {
1722           memcpy (ring_buffer, data + block_one, block_two);
1723         }
1724       }
1725     }
1726
1727   update_and_signal:
1728     /* update the writing positions */
1729     size -= to_write;
1730     GST_INFO_OBJECT (queue,
1731         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
1732         to_write, writing_pos, size);
1733
1734     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1735       data += to_write;
1736       queue->current->writing_pos += to_write;
1737       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
1738     } else {
1739       queue->current->writing_pos = writing_pos = new_writing_pos;
1740     }
1741     update_cur_level (queue, queue->current);
1742
1743     /* update the buffering status */
1744     if (queue->use_buffering)
1745       update_buffering (queue);
1746
1747     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1748         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1749
1750     GST_QUEUE2_SIGNAL_ADD (queue);
1751   }
1752
1753   gst_buffer_unmap (buffer, odata, osize);
1754
1755   return TRUE;
1756
1757   /* ERRORS */
1758 out_flushing:
1759   {
1760     GST_DEBUG_OBJECT (queue, "we are flushing");
1761     gst_buffer_unmap (buffer, odata, osize);
1762     /* FIXME - GST_FLOW_UNEXPECTED ? */
1763     return FALSE;
1764   }
1765 seek_failed:
1766   {
1767     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1768     gst_buffer_unmap (buffer, odata, osize);
1769     return FALSE;
1770   }
1771 handle_error:
1772   {
1773     switch (errno) {
1774       case ENOSPC:{
1775         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
1776         break;
1777       }
1778       default:{
1779         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
1780             (_("Error while writing to download file.")),
1781             ("%s", g_strerror (errno)));
1782       }
1783     }
1784     gst_buffer_unmap (buffer, odata, osize);
1785     return FALSE;
1786   }
1787 }
1788
1789 /* enqueue an item an update the level stats */
1790 static void
1791 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item, gboolean isbuffer)
1792 {
1793   if (isbuffer) {
1794     GstBuffer *buffer;
1795     guint size;
1796
1797     buffer = GST_BUFFER_CAST (item);
1798     size = gst_buffer_get_size (buffer);
1799
1800     /* add buffer to the statistics */
1801     if (QUEUE_IS_USING_QUEUE (queue)) {
1802       queue->cur_level.buffers++;
1803       queue->cur_level.bytes += size;
1804     }
1805     queue->bytes_in += size;
1806
1807     /* apply new buffer to segment stats */
1808     apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
1809     /* update the byterate stats */
1810     update_in_rates (queue);
1811
1812     if (!QUEUE_IS_USING_QUEUE (queue)) {
1813       /* FIXME - check return value? */
1814       gst_queue2_create_write (queue, buffer);
1815     }
1816   } else if (GST_IS_EVENT (item)) {
1817     GstEvent *event;
1818
1819     event = GST_EVENT_CAST (item);
1820
1821     switch (GST_EVENT_TYPE (event)) {
1822       case GST_EVENT_EOS:
1823         /* Zero the thresholds, this makes sure the queue is completely
1824          * filled and we can read all data from the queue. */
1825         GST_DEBUG_OBJECT (queue, "we have EOS");
1826         queue->is_eos = TRUE;
1827         break;
1828       case GST_EVENT_NEWSEGMENT:
1829         apply_segment (queue, event, &queue->sink_segment, TRUE);
1830         /* This is our first new segment, we hold it
1831          * as we can't save it on the temp file */
1832         if (!QUEUE_IS_USING_QUEUE (queue)) {
1833           if (queue->segment_event_received)
1834             goto unexpected_event;
1835
1836           queue->segment_event_received = TRUE;
1837           if (queue->starting_segment != NULL)
1838             gst_event_unref (queue->starting_segment);
1839           queue->starting_segment = event;
1840           item = NULL;
1841         }
1842         /* a new segment allows us to accept more buffers if we got UNEXPECTED
1843          * from downstream */
1844         queue->unexpected = FALSE;
1845         break;
1846       default:
1847         if (!QUEUE_IS_USING_QUEUE (queue))
1848           goto unexpected_event;
1849         break;
1850     }
1851   } else {
1852     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
1853         item, GST_OBJECT_NAME (queue));
1854     /* we can't really unref since we don't know what it is */
1855     item = NULL;
1856   }
1857
1858   if (item) {
1859     /* update the buffering status */
1860     if (queue->use_buffering)
1861       update_buffering (queue);
1862
1863     if (QUEUE_IS_USING_QUEUE (queue)) {
1864       g_queue_push_tail (queue->queue, item);
1865     } else {
1866       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
1867     }
1868
1869     GST_QUEUE2_SIGNAL_ADD (queue);
1870   }
1871
1872   return;
1873
1874   /* ERRORS */
1875 unexpected_event:
1876   {
1877     g_warning
1878         ("Unexpected event of kind %s can't be added in temp file of queue %s ",
1879         gst_event_type_get_name (GST_EVENT_TYPE (item)),
1880         GST_OBJECT_NAME (queue));
1881     gst_event_unref (GST_EVENT_CAST (item));
1882     return;
1883   }
1884 }
1885
1886 /* dequeue an item from the queue and update level stats */
1887 static GstMiniObject *
1888 gst_queue2_locked_dequeue (GstQueue2 * queue, gboolean * is_buffer)
1889 {
1890   GstMiniObject *item;
1891
1892   if (!QUEUE_IS_USING_QUEUE (queue))
1893     item = gst_queue2_read_item_from_file (queue);
1894   else
1895     item = g_queue_pop_head (queue->queue);
1896
1897   if (item == NULL)
1898     goto no_item;
1899
1900   if (GST_IS_BUFFER (item)) {
1901     GstBuffer *buffer;
1902     guint size;
1903
1904     buffer = GST_BUFFER_CAST (item);
1905     size = gst_buffer_get_size (buffer);
1906     *is_buffer = TRUE;
1907
1908     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1909         "retrieved buffer %p from queue", buffer);
1910
1911     if (QUEUE_IS_USING_QUEUE (queue)) {
1912       queue->cur_level.buffers--;
1913       queue->cur_level.bytes -= size;
1914     }
1915     queue->bytes_out += size;
1916
1917     apply_buffer (queue, buffer, &queue->src_segment, FALSE);
1918     /* update the byterate stats */
1919     update_out_rates (queue);
1920     /* update the buffering */
1921     if (queue->use_buffering)
1922       update_buffering (queue);
1923
1924   } else if (GST_IS_EVENT (item)) {
1925     GstEvent *event = GST_EVENT_CAST (item);
1926
1927     *is_buffer = FALSE;
1928
1929     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1930         "retrieved event %p from queue", event);
1931
1932     switch (GST_EVENT_TYPE (event)) {
1933       case GST_EVENT_EOS:
1934         /* queue is empty now that we dequeued the EOS */
1935         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1936         break;
1937       case GST_EVENT_NEWSEGMENT:
1938         apply_segment (queue, event, &queue->src_segment, FALSE);
1939         break;
1940       default:
1941         break;
1942     }
1943   } else {
1944     g_warning
1945         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
1946         item, GST_OBJECT_NAME (queue));
1947     item = NULL;
1948   }
1949   GST_QUEUE2_SIGNAL_DEL (queue);
1950
1951   return item;
1952
1953   /* ERRORS */
1954 no_item:
1955   {
1956     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
1957     return NULL;
1958   }
1959 }
1960
1961 static gboolean
1962 gst_queue2_handle_sink_event (GstPad * pad, GstEvent * event)
1963 {
1964   GstQueue2 *queue;
1965
1966   queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
1967
1968   switch (GST_EVENT_TYPE (event)) {
1969     case GST_EVENT_FLUSH_START:
1970     {
1971       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
1972       if (QUEUE_IS_USING_QUEUE (queue)) {
1973         /* forward event */
1974         gst_pad_push_event (queue->srcpad, event);
1975
1976         /* now unblock the chain function */
1977         GST_QUEUE2_MUTEX_LOCK (queue);
1978         queue->srcresult = GST_FLOW_WRONG_STATE;
1979         queue->sinkresult = GST_FLOW_WRONG_STATE;
1980         /* unblock the loop and chain functions */
1981         GST_QUEUE2_SIGNAL_ADD (queue);
1982         GST_QUEUE2_SIGNAL_DEL (queue);
1983         GST_QUEUE2_MUTEX_UNLOCK (queue);
1984
1985         /* make sure it pauses, this should happen since we sent
1986          * flush_start downstream. */
1987         gst_pad_pause_task (queue->srcpad);
1988         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
1989       } else {
1990         GST_QUEUE2_MUTEX_LOCK (queue);
1991         /* flush the sink pad */
1992         queue->sinkresult = GST_FLOW_WRONG_STATE;
1993         GST_QUEUE2_SIGNAL_DEL (queue);
1994         GST_QUEUE2_MUTEX_UNLOCK (queue);
1995
1996         gst_event_unref (event);
1997       }
1998       goto done;
1999     }
2000     case GST_EVENT_FLUSH_STOP:
2001     {
2002       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2003
2004       if (QUEUE_IS_USING_QUEUE (queue)) {
2005         /* forward event */
2006         gst_pad_push_event (queue->srcpad, event);
2007
2008         GST_QUEUE2_MUTEX_LOCK (queue);
2009         gst_queue2_locked_flush (queue);
2010         queue->srcresult = GST_FLOW_OK;
2011         queue->sinkresult = GST_FLOW_OK;
2012         queue->is_eos = FALSE;
2013         queue->unexpected = FALSE;
2014         /* reset rate counters */
2015         reset_rate_timer (queue);
2016         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2017             queue->srcpad);
2018         GST_QUEUE2_MUTEX_UNLOCK (queue);
2019       } else {
2020         GST_QUEUE2_MUTEX_LOCK (queue);
2021         queue->segment_event_received = FALSE;
2022         queue->is_eos = FALSE;
2023         queue->unexpected = FALSE;
2024         queue->sinkresult = GST_FLOW_OK;
2025         GST_QUEUE2_MUTEX_UNLOCK (queue);
2026
2027         gst_event_unref (event);
2028       }
2029       goto done;
2030     }
2031     default:
2032       if (GST_EVENT_IS_SERIALIZED (event)) {
2033         /* serialized events go in the queue */
2034         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2035         /* refuse more events on EOS */
2036         if (queue->is_eos)
2037           goto out_eos;
2038         gst_queue2_locked_enqueue (queue, event, FALSE);
2039         GST_QUEUE2_MUTEX_UNLOCK (queue);
2040       } else {
2041         /* non-serialized events are passed upstream. */
2042         gst_pad_push_event (queue->srcpad, event);
2043       }
2044       break;
2045   }
2046 done:
2047   return TRUE;
2048
2049   /* ERRORS */
2050 out_flushing:
2051   {
2052     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2053     GST_QUEUE2_MUTEX_UNLOCK (queue);
2054     gst_event_unref (event);
2055     return FALSE;
2056   }
2057 out_eos:
2058   {
2059     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2060     GST_QUEUE2_MUTEX_UNLOCK (queue);
2061     gst_event_unref (event);
2062     return FALSE;
2063   }
2064 }
2065
2066 static gboolean
2067 gst_queue2_is_empty (GstQueue2 * queue)
2068 {
2069   /* never empty on EOS */
2070   if (queue->is_eos)
2071     return FALSE;
2072
2073   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2074     return queue->current->writing_pos <= queue->current->max_reading_pos;
2075   } else {
2076     if (queue->queue->length == 0)
2077       return TRUE;
2078   }
2079
2080   return FALSE;
2081 }
2082
2083 static gboolean
2084 gst_queue2_is_filled (GstQueue2 * queue)
2085 {
2086   gboolean res;
2087
2088   /* always filled on EOS */
2089   if (queue->is_eos)
2090     return TRUE;
2091
2092 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2093     (queue->cur_level.format) >= ((alt_max) ? \
2094       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2095
2096   /* if using a ring buffer we're filled if all ring buffer space is used
2097    * _by the current range_ */
2098   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2099     guint64 rb_size = queue->ring_buffer_max_size;
2100     GST_DEBUG_OBJECT (queue,
2101         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2102         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2103     return CHECK_FILLED (bytes, rb_size);
2104   }
2105
2106   /* if using file, we're never filled if we don't have EOS */
2107   if (QUEUE_IS_USING_TEMP_FILE (queue))
2108     return FALSE;
2109
2110   /* we are never filled when we have no buffers at all */
2111   if (queue->cur_level.buffers == 0)
2112     return FALSE;
2113
2114   /* we are filled if one of the current levels exceeds the max */
2115   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2116       || CHECK_FILLED (time, 0);
2117
2118   /* if we need to, use the rate estimate to check against the max time we are
2119    * allowed to queue */
2120   if (queue->use_rate_estimate)
2121     res |= CHECK_FILLED (rate_time, 0);
2122
2123 #undef CHECK_FILLED
2124   return res;
2125 }
2126
2127 static GstFlowReturn
2128 gst_queue2_chain (GstPad * pad, GstBuffer * buffer)
2129 {
2130   GstQueue2 *queue;
2131
2132   queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
2133
2134   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2135       "received buffer %p of size %d, time %" GST_TIME_FORMAT ", duration %"
2136       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
2137       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2138       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2139
2140   /* we have to lock the queue since we span threads */
2141   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2142   /* when we received EOS, we refuse more data */
2143   if (queue->is_eos)
2144     goto out_eos;
2145   /* when we received unexpected from downstream, refuse more buffers */
2146   if (queue->unexpected)
2147     goto out_unexpected;
2148
2149   if (!gst_queue2_wait_free_space (queue))
2150     goto out_flushing;
2151
2152   /* put buffer in queue now */
2153   gst_queue2_locked_enqueue (queue, buffer, TRUE);
2154   GST_QUEUE2_MUTEX_UNLOCK (queue);
2155
2156   return GST_FLOW_OK;
2157
2158   /* special conditions */
2159 out_flushing:
2160   {
2161     GstFlowReturn ret = queue->sinkresult;
2162
2163     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2164         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2165     GST_QUEUE2_MUTEX_UNLOCK (queue);
2166     gst_buffer_unref (buffer);
2167
2168     return ret;
2169   }
2170 out_eos:
2171   {
2172     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2173     GST_QUEUE2_MUTEX_UNLOCK (queue);
2174     gst_buffer_unref (buffer);
2175
2176     return GST_FLOW_UNEXPECTED;
2177   }
2178 out_unexpected:
2179   {
2180     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2181         "exit because we received UNEXPECTED");
2182     GST_QUEUE2_MUTEX_UNLOCK (queue);
2183     gst_buffer_unref (buffer);
2184
2185     return GST_FLOW_UNEXPECTED;
2186   }
2187 }
2188
2189 /* dequeue an item from the queue an push it downstream. This functions returns
2190  * the result of the push. */
2191 static GstFlowReturn
2192 gst_queue2_push_one (GstQueue2 * queue)
2193 {
2194   GstFlowReturn result = GST_FLOW_OK;
2195   GstMiniObject *data;
2196   gboolean is_buffer = FALSE;
2197
2198   data = gst_queue2_locked_dequeue (queue, &is_buffer);
2199   if (data == NULL)
2200     goto no_item;
2201
2202 next:
2203   GST_QUEUE2_MUTEX_UNLOCK (queue);
2204
2205   if (is_buffer) {
2206     GstBuffer *buffer;
2207 #if 0
2208     GstCaps *caps;
2209 #endif
2210
2211     buffer = GST_BUFFER_CAST (data);
2212 #if 0
2213     caps = GST_BUFFER_CAPS (buffer);
2214 #endif
2215
2216 #if 0
2217     /* set caps before pushing the buffer so that core does not try to do
2218      * something fancy to check if this is possible. */
2219     if (caps && caps != GST_PAD_CAPS (queue->srcpad))
2220       gst_pad_set_caps (queue->srcpad, caps);
2221 #endif
2222
2223     result = gst_pad_push (queue->srcpad, buffer);
2224
2225     /* need to check for srcresult here as well */
2226     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2227     if (result == GST_FLOW_UNEXPECTED) {
2228       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2229           "got UNEXPECTED from downstream");
2230       /* stop pushing buffers, we dequeue all items until we see an item that we
2231        * can push again, which is EOS or NEWSEGMENT. If there is nothing in the
2232        * queue we can push, we set a flag to make the sinkpad refuse more
2233        * buffers with an UNEXPECTED return value until we receive something
2234        * pushable again or we get flushed. */
2235       while ((data = gst_queue2_locked_dequeue (queue, &is_buffer))) {
2236         if (is_buffer) {
2237           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2238               "dropping UNEXPECTED buffer %p", data);
2239           gst_buffer_unref (GST_BUFFER_CAST (data));
2240         } else if (GST_IS_EVENT (data)) {
2241           GstEvent *event = GST_EVENT_CAST (data);
2242           GstEventType type = GST_EVENT_TYPE (event);
2243
2244           if (type == GST_EVENT_EOS || type == GST_EVENT_NEWSEGMENT) {
2245             /* we found a pushable item in the queue, push it out */
2246             GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2247                 "pushing pushable event %s after UNEXPECTED",
2248                 GST_EVENT_TYPE_NAME (event));
2249             goto next;
2250           }
2251           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2252               "dropping UNEXPECTED event %p", event);
2253           gst_event_unref (event);
2254         }
2255       }
2256       /* no more items in the queue. Set the unexpected flag so that upstream
2257        * make us refuse any more buffers on the sinkpad. Since we will still
2258        * accept EOS and NEWSEGMENT we return _FLOW_OK to the caller so that the
2259        * task function does not shut down. */
2260       queue->unexpected = TRUE;
2261       result = GST_FLOW_OK;
2262     }
2263   } else if (GST_IS_EVENT (data)) {
2264     GstEvent *event = GST_EVENT_CAST (data);
2265     GstEventType type = GST_EVENT_TYPE (event);
2266
2267     gst_pad_push_event (queue->srcpad, event);
2268
2269     /* if we're EOS, return UNEXPECTED so that the task pauses. */
2270     if (type == GST_EVENT_EOS) {
2271       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2272           "pushed EOS event %p, return UNEXPECTED", event);
2273       result = GST_FLOW_UNEXPECTED;
2274     }
2275
2276     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2277   }
2278   return result;
2279
2280   /* ERRORS */
2281 no_item:
2282   {
2283     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2284         "exit because we have no item in the queue");
2285     return GST_FLOW_ERROR;
2286   }
2287 out_flushing:
2288   {
2289     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2290     return GST_FLOW_WRONG_STATE;
2291   }
2292 }
2293
2294 /* called repeadedly with @pad as the source pad. This function should push out
2295  * data to the peer element. */
2296 static void
2297 gst_queue2_loop (GstPad * pad)
2298 {
2299   GstQueue2 *queue;
2300   GstFlowReturn ret;
2301
2302   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2303
2304   /* have to lock for thread-safety */
2305   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2306
2307   if (gst_queue2_is_empty (queue)) {
2308     gboolean started;
2309
2310     /* pause the timer while we wait. The fact that we are waiting does not mean
2311      * the byterate on the output pad is lower */
2312     if ((started = queue->out_timer_started))
2313       g_timer_stop (queue->out_timer);
2314
2315     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2316         "queue is empty, waiting for new data");
2317     do {
2318       /* Wait for data to be available, we could be unlocked because of a flush. */
2319       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2320     }
2321     while (gst_queue2_is_empty (queue));
2322
2323     /* and continue if we were running before */
2324     if (started)
2325       g_timer_continue (queue->out_timer);
2326   }
2327   ret = gst_queue2_push_one (queue);
2328   queue->srcresult = ret;
2329   queue->sinkresult = ret;
2330   if (ret != GST_FLOW_OK)
2331     goto out_flushing;
2332
2333   GST_QUEUE2_MUTEX_UNLOCK (queue);
2334
2335   return;
2336
2337   /* ERRORS */
2338 out_flushing:
2339   {
2340     gboolean eos = queue->is_eos;
2341     GstFlowReturn ret = queue->srcresult;
2342
2343     gst_pad_pause_task (queue->srcpad);
2344     GST_QUEUE2_MUTEX_UNLOCK (queue);
2345     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2346         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2347     /* let app know about us giving up if upstream is not expected to do so */
2348     /* UNEXPECTED is already taken care of elsewhere */
2349     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED)) {
2350       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2351           (_("Internal data flow error.")),
2352           ("streaming task paused, reason %s (%d)",
2353               gst_flow_get_name (ret), ret));
2354       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2355     }
2356     return;
2357   }
2358 }
2359
2360 static gboolean
2361 gst_queue2_handle_src_event (GstPad * pad, GstEvent * event)
2362 {
2363   gboolean res = TRUE;
2364   GstQueue2 *queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2365
2366   if (G_UNLIKELY (queue == NULL)) {
2367     gst_event_unref (event);
2368     return FALSE;
2369   }
2370 #ifndef GST_DISABLE_GST_DEBUG
2371   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
2372       event, GST_EVENT_TYPE_NAME (event));
2373 #endif
2374
2375   switch (GST_EVENT_TYPE (event)) {
2376     case GST_EVENT_FLUSH_START:
2377       if (QUEUE_IS_USING_QUEUE (queue)) {
2378         /* just forward upstream */
2379         res = gst_pad_push_event (queue->sinkpad, event);
2380       } else {
2381         /* now unblock the getrange function */
2382         GST_QUEUE2_MUTEX_LOCK (queue);
2383         GST_DEBUG_OBJECT (queue, "flushing");
2384         queue->srcresult = GST_FLOW_WRONG_STATE;
2385         GST_QUEUE2_SIGNAL_ADD (queue);
2386         GST_QUEUE2_MUTEX_UNLOCK (queue);
2387
2388         /* when using a temp file, we eat the event */
2389         res = TRUE;
2390         gst_event_unref (event);
2391       }
2392       break;
2393     case GST_EVENT_FLUSH_STOP:
2394       if (QUEUE_IS_USING_QUEUE (queue)) {
2395         /* just forward upstream */
2396         res = gst_pad_push_event (queue->sinkpad, event);
2397       } else {
2398         /* now unblock the getrange function */
2399         GST_QUEUE2_MUTEX_LOCK (queue);
2400         queue->srcresult = GST_FLOW_OK;
2401         if (queue->current) {
2402           /* forget the highest read offset, we'll calculate a new one when we
2403            * get the next getrange request. We need to do this in order to reset
2404            * the buffering percentage */
2405           queue->current->max_reading_pos = 0;
2406         }
2407         GST_QUEUE2_MUTEX_UNLOCK (queue);
2408
2409         /* when using a temp file, we eat the event */
2410         res = TRUE;
2411         gst_event_unref (event);
2412       }
2413       break;
2414     default:
2415       res = gst_pad_push_event (queue->sinkpad, event);
2416       break;
2417   }
2418
2419   gst_object_unref (queue);
2420   return res;
2421 }
2422
2423 static gboolean
2424 gst_queue2_peer_query (GstQueue2 * queue, GstPad * pad, GstQuery ** query)
2425 {
2426   gboolean ret = FALSE;
2427   GstPad *peer;
2428
2429   if ((peer = gst_pad_get_peer (pad))) {
2430     ret = gst_pad_query (peer, query);
2431     gst_object_unref (peer);
2432   }
2433   return ret;
2434 }
2435
2436 static gboolean
2437 gst_queue2_handle_src_query (GstPad * pad, GstQuery ** query)
2438 {
2439   GstQueue2 *queue;
2440
2441   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2442   if (G_UNLIKELY (queue == NULL))
2443     return FALSE;
2444
2445   switch (GST_QUERY_TYPE (*query)) {
2446     case GST_QUERY_POSITION:
2447     {
2448       gint64 peer_pos;
2449       GstFormat format;
2450
2451       if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2452         goto peer_failed;
2453
2454       /* get peer position */
2455       gst_query_parse_position (*query, &format, &peer_pos);
2456
2457       /* FIXME: this code assumes that there's no discont in the queue */
2458       switch (format) {
2459         case GST_FORMAT_BYTES:
2460           peer_pos -= queue->cur_level.bytes;
2461           break;
2462         case GST_FORMAT_TIME:
2463           peer_pos -= queue->cur_level.time;
2464           break;
2465         default:
2466           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
2467               "know how to adjust value", gst_format_get_name (format));
2468           return FALSE;
2469       }
2470       /* set updated position */
2471       gst_query_set_position (*query, format, peer_pos);
2472       break;
2473     }
2474     case GST_QUERY_DURATION:
2475     {
2476       GST_DEBUG_OBJECT (queue, "doing peer query");
2477
2478       if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2479         goto peer_failed;
2480
2481       GST_DEBUG_OBJECT (queue, "peer query success");
2482       break;
2483     }
2484     case GST_QUERY_BUFFERING:
2485     {
2486       GstFormat format;
2487
2488       GST_DEBUG_OBJECT (queue, "query buffering");
2489
2490       /* FIXME - is this condition correct? what should ring buffer do? */
2491       if (QUEUE_IS_USING_QUEUE (queue)) {
2492         /* no temp file, just forward to the peer */
2493         if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2494           goto peer_failed;
2495         GST_DEBUG_OBJECT (queue, "buffering forwarded to peer");
2496       } else {
2497         gint64 start, stop, range_start, range_stop;
2498         guint64 writing_pos;
2499         gint percent;
2500         gint64 estimated_total, buffering_left;
2501         GstFormat peer_fmt;
2502         gint64 duration;
2503         gboolean peer_res, is_buffering, is_eos;
2504         gdouble byte_in_rate, byte_out_rate;
2505         GstQueue2Range *queued_ranges;
2506
2507         /* we need a current download region */
2508         if (queue->current == NULL)
2509           return FALSE;
2510
2511         writing_pos = queue->current->writing_pos;
2512         byte_in_rate = queue->byte_in_rate;
2513         byte_out_rate = queue->byte_out_rate;
2514         is_buffering = queue->is_buffering;
2515         is_eos = queue->is_eos;
2516         percent = queue->buffering_percent;
2517
2518         if (is_eos) {
2519           /* we're EOS, we know the duration in bytes now */
2520           peer_res = TRUE;
2521           duration = writing_pos;
2522         } else {
2523           /* get duration of upstream in bytes */
2524           peer_fmt = GST_FORMAT_BYTES;
2525           peer_res = gst_pad_query_peer_duration (queue->sinkpad, &peer_fmt,
2526               &duration);
2527         }
2528
2529         /* calculate remaining and total download time */
2530         if (peer_res && byte_in_rate > 0.0) {
2531           estimated_total = (duration * 1000) / byte_in_rate;
2532           buffering_left = ((duration - writing_pos) * 1000) / byte_in_rate;
2533         } else {
2534           estimated_total = -1;
2535           buffering_left = -1;
2536         }
2537         GST_DEBUG_OBJECT (queue, "estimated %" G_GINT64_FORMAT ", left %"
2538             G_GINT64_FORMAT, estimated_total, buffering_left);
2539
2540         gst_query_parse_buffering_range (*query, &format, NULL, NULL, NULL);
2541
2542         switch (format) {
2543           case GST_FORMAT_PERCENT:
2544             /* we need duration */
2545             if (!peer_res)
2546               goto peer_failed;
2547
2548             GST_DEBUG_OBJECT (queue,
2549                 "duration %" G_GINT64_FORMAT ", writing %" G_GINT64_FORMAT,
2550                 duration, writing_pos);
2551
2552             start = 0;
2553             /* get our available data relative to the duration */
2554             if (duration != -1)
2555               stop = GST_FORMAT_PERCENT_MAX * writing_pos / duration;
2556             else
2557               stop = -1;
2558             break;
2559           case GST_FORMAT_BYTES:
2560             start = 0;
2561             stop = writing_pos;
2562             break;
2563           default:
2564             start = -1;
2565             stop = -1;
2566             break;
2567         }
2568
2569         /* fill out the buffered ranges */
2570         for (queued_ranges = queue->ranges; queued_ranges;
2571             queued_ranges = queued_ranges->next) {
2572           switch (format) {
2573             case GST_FORMAT_PERCENT:
2574               if (duration == -1) {
2575                 range_start = 0;
2576                 range_stop = 0;
2577                 break;
2578               }
2579               range_start = 100 * queued_ranges->offset / duration;
2580               range_stop = 100 * queued_ranges->writing_pos / duration;
2581               break;
2582             case GST_FORMAT_BYTES:
2583               range_start = queued_ranges->offset;
2584               range_stop = queued_ranges->writing_pos;
2585               break;
2586             default:
2587               range_start = -1;
2588               range_stop = -1;
2589               break;
2590           }
2591           if (range_start == range_stop)
2592             continue;
2593           GST_DEBUG_OBJECT (queue,
2594               "range starting at %" G_GINT64_FORMAT " and finishing at %"
2595               G_GINT64_FORMAT, range_start, range_stop);
2596           gst_query_add_buffering_range (*query, range_start, range_stop);
2597         }
2598
2599         gst_query_set_buffering_percent (*query, is_buffering, percent);
2600         gst_query_set_buffering_range (*query, format, start, stop,
2601             estimated_total);
2602         gst_query_set_buffering_stats (*query, GST_BUFFERING_DOWNLOAD,
2603             byte_in_rate, byte_out_rate, buffering_left);
2604       }
2605       break;
2606     }
2607     default:
2608       /* peer handled other queries */
2609       if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2610         goto peer_failed;
2611       break;
2612   }
2613
2614   gst_object_unref (queue);
2615   return TRUE;
2616
2617   /* ERRORS */
2618 peer_failed:
2619   {
2620     GST_DEBUG_OBJECT (queue, "failed peer query");
2621     gst_object_unref (queue);
2622     return FALSE;
2623   }
2624 }
2625
2626 static gboolean
2627 gst_queue2_handle_query (GstElement * element, GstQuery ** query)
2628 {
2629   /* simply forward to the srcpad query function */
2630   return gst_queue2_handle_src_query (GST_QUEUE2_CAST (element)->srcpad, query);
2631 }
2632
2633 static void
2634 gst_queue2_update_upstream_size (GstQueue2 * queue)
2635 {
2636   GstFormat fmt = GST_FORMAT_BYTES;
2637   gint64 upstream_size = -1;
2638
2639   if (gst_pad_query_peer_duration (queue->sinkpad, &fmt, &upstream_size)) {
2640     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
2641     queue->upstream_size = upstream_size;
2642   }
2643 }
2644
2645 static GstFlowReturn
2646 gst_queue2_get_range (GstPad * pad, guint64 offset, guint length,
2647     GstBuffer ** buffer)
2648 {
2649   GstQueue2 *queue;
2650   GstFlowReturn ret;
2651
2652   queue = GST_QUEUE2_CAST (gst_pad_get_parent (pad));
2653
2654   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
2655   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2656   offset = (offset == -1) ? queue->current->reading_pos : offset;
2657
2658   GST_DEBUG_OBJECT (queue,
2659       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
2660
2661   /* catch any reads beyond the size of the file here to make sure queue2
2662    * doesn't send seek events beyond the size of the file upstream, since
2663    * that would confuse elements such as souphttpsrc and/or http servers.
2664    * Demuxers often just loop until EOS at the end of the file to figure out
2665    * when they've read all the end-headers or index chunks. */
2666   if (G_UNLIKELY (offset >= queue->upstream_size)) {
2667     gst_queue2_update_upstream_size (queue);
2668     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
2669       goto out_unexpected;
2670   }
2671
2672   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
2673     gst_queue2_update_upstream_size (queue);
2674     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
2675       length = queue->upstream_size - offset;
2676       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
2677     }
2678   }
2679
2680   /* FIXME - function will block when the range is not yet available */
2681   ret = gst_queue2_create_read (queue, offset, length, buffer);
2682   GST_QUEUE2_MUTEX_UNLOCK (queue);
2683
2684   gst_object_unref (queue);
2685
2686   return ret;
2687
2688   /* ERRORS */
2689 out_flushing:
2690   {
2691     ret = queue->srcresult;
2692
2693     GST_DEBUG_OBJECT (queue, "we are flushing");
2694     GST_QUEUE2_MUTEX_UNLOCK (queue);
2695     gst_object_unref (queue);
2696     return ret;
2697   }
2698 out_unexpected:
2699   {
2700     GST_DEBUG_OBJECT (queue, "read beyond end of file");
2701     GST_QUEUE2_MUTEX_UNLOCK (queue);
2702     gst_object_unref (queue);
2703     return GST_FLOW_UNEXPECTED;
2704   }
2705 }
2706
2707 static gboolean
2708 gst_queue2_src_checkgetrange_function (GstPad * pad)
2709 {
2710   GstQueue2 *queue;
2711   gboolean ret;
2712
2713   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2714
2715   /* we can operate in pull mode when we are using a tempfile */
2716   ret = !QUEUE_IS_USING_QUEUE (queue);
2717
2718   gst_object_unref (GST_OBJECT (queue));
2719
2720   return ret;
2721 }
2722
2723 /* sink currently only operates in push mode */
2724 static gboolean
2725 gst_queue2_sink_activate_push (GstPad * pad, gboolean active)
2726 {
2727   gboolean result = TRUE;
2728   GstQueue2 *queue;
2729
2730   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2731
2732   if (active) {
2733     GST_QUEUE2_MUTEX_LOCK (queue);
2734     GST_DEBUG_OBJECT (queue, "activating push mode");
2735     queue->srcresult = GST_FLOW_OK;
2736     queue->sinkresult = GST_FLOW_OK;
2737     queue->is_eos = FALSE;
2738     queue->unexpected = FALSE;
2739     reset_rate_timer (queue);
2740     GST_QUEUE2_MUTEX_UNLOCK (queue);
2741   } else {
2742     /* unblock chain function */
2743     GST_QUEUE2_MUTEX_LOCK (queue);
2744     GST_DEBUG_OBJECT (queue, "deactivating push mode");
2745     queue->srcresult = GST_FLOW_WRONG_STATE;
2746     queue->sinkresult = GST_FLOW_WRONG_STATE;
2747     gst_queue2_locked_flush (queue);
2748     GST_QUEUE2_MUTEX_UNLOCK (queue);
2749   }
2750
2751   gst_object_unref (queue);
2752
2753   return result;
2754 }
2755
2756 /* src operating in push mode, we start a task on the source pad that pushes out
2757  * buffers from the queue */
2758 static gboolean
2759 gst_queue2_src_activate_push (GstPad * pad, gboolean active)
2760 {
2761   gboolean result = FALSE;
2762   GstQueue2 *queue;
2763
2764   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2765
2766   if (active) {
2767     GST_QUEUE2_MUTEX_LOCK (queue);
2768     GST_DEBUG_OBJECT (queue, "activating push mode");
2769     queue->srcresult = GST_FLOW_OK;
2770     queue->sinkresult = GST_FLOW_OK;
2771     queue->is_eos = FALSE;
2772     queue->unexpected = FALSE;
2773     result = gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad);
2774     GST_QUEUE2_MUTEX_UNLOCK (queue);
2775   } else {
2776     /* unblock loop function */
2777     GST_QUEUE2_MUTEX_LOCK (queue);
2778     GST_DEBUG_OBJECT (queue, "deactivating push mode");
2779     queue->srcresult = GST_FLOW_WRONG_STATE;
2780     queue->sinkresult = GST_FLOW_WRONG_STATE;
2781     /* the item add signal will unblock */
2782     GST_QUEUE2_SIGNAL_ADD (queue);
2783     GST_QUEUE2_MUTEX_UNLOCK (queue);
2784
2785     /* step 2, make sure streaming finishes */
2786     result = gst_pad_stop_task (pad);
2787   }
2788
2789   gst_object_unref (queue);
2790
2791   return result;
2792 }
2793
2794 /* pull mode, downstream will call our getrange function */
2795 static gboolean
2796 gst_queue2_src_activate_pull (GstPad * pad, gboolean active)
2797 {
2798   gboolean result;
2799   GstQueue2 *queue;
2800
2801   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2802
2803   if (active) {
2804     GST_QUEUE2_MUTEX_LOCK (queue);
2805     if (!QUEUE_IS_USING_QUEUE (queue)) {
2806       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2807         /* open the temp file now */
2808         result = gst_queue2_open_temp_location_file (queue);
2809       } else if (!queue->ring_buffer) {
2810         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
2811         result = !!queue->ring_buffer;
2812       } else {
2813         result = TRUE;
2814       }
2815
2816       GST_DEBUG_OBJECT (queue, "activating pull mode");
2817       init_ranges (queue);
2818       queue->srcresult = GST_FLOW_OK;
2819       queue->sinkresult = GST_FLOW_OK;
2820       queue->is_eos = FALSE;
2821       queue->unexpected = FALSE;
2822       queue->upstream_size = 0;
2823       GST_QUEUE2_MUTEX_UNLOCK (queue);
2824     } else {
2825       GST_QUEUE2_MUTEX_LOCK (queue);
2826       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
2827       /* this is not allowed, we cannot operate in pull mode without a temp
2828        * file. */
2829       queue->srcresult = GST_FLOW_WRONG_STATE;
2830       queue->sinkresult = GST_FLOW_WRONG_STATE;
2831       result = FALSE;
2832       GST_QUEUE2_MUTEX_UNLOCK (queue);
2833     }
2834   } else {
2835     GST_QUEUE2_MUTEX_LOCK (queue);
2836     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
2837     queue->srcresult = GST_FLOW_WRONG_STATE;
2838     queue->sinkresult = GST_FLOW_WRONG_STATE;
2839     /* this will unlock getrange */
2840     GST_QUEUE2_SIGNAL_ADD (queue);
2841     result = TRUE;
2842     GST_QUEUE2_MUTEX_UNLOCK (queue);
2843   }
2844   gst_object_unref (queue);
2845
2846   return result;
2847 }
2848
2849 static GstStateChangeReturn
2850 gst_queue2_change_state (GstElement * element, GstStateChange transition)
2851 {
2852   GstQueue2 *queue;
2853   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2854
2855   queue = GST_QUEUE2 (element);
2856
2857   switch (transition) {
2858     case GST_STATE_CHANGE_NULL_TO_READY:
2859       break;
2860     case GST_STATE_CHANGE_READY_TO_PAUSED:
2861       GST_QUEUE2_MUTEX_LOCK (queue);
2862       if (!QUEUE_IS_USING_QUEUE (queue)) {
2863         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2864           if (!gst_queue2_open_temp_location_file (queue))
2865             ret = GST_STATE_CHANGE_FAILURE;
2866         } else {
2867           if (queue->ring_buffer) {
2868             g_free (queue->ring_buffer);
2869             queue->ring_buffer = NULL;
2870           }
2871           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
2872             ret = GST_STATE_CHANGE_FAILURE;
2873         }
2874         init_ranges (queue);
2875       }
2876       queue->segment_event_received = FALSE;
2877       queue->starting_segment = NULL;
2878       GST_QUEUE2_MUTEX_UNLOCK (queue);
2879       break;
2880     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2881       break;
2882     default:
2883       break;
2884   }
2885
2886   if (ret == GST_STATE_CHANGE_FAILURE)
2887     return ret;
2888
2889   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2890
2891   if (ret == GST_STATE_CHANGE_FAILURE)
2892     return ret;
2893
2894   switch (transition) {
2895     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2896       break;
2897     case GST_STATE_CHANGE_PAUSED_TO_READY:
2898       GST_QUEUE2_MUTEX_LOCK (queue);
2899       if (!QUEUE_IS_USING_QUEUE (queue)) {
2900         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2901           gst_queue2_close_temp_location_file (queue);
2902         } else if (queue->ring_buffer) {
2903           g_free (queue->ring_buffer);
2904           queue->ring_buffer = NULL;
2905         }
2906         clean_ranges (queue);
2907       }
2908       if (queue->starting_segment != NULL) {
2909         gst_event_unref (queue->starting_segment);
2910         queue->starting_segment = NULL;
2911       }
2912       GST_QUEUE2_MUTEX_UNLOCK (queue);
2913       break;
2914     case GST_STATE_CHANGE_READY_TO_NULL:
2915       break;
2916     default:
2917       break;
2918   }
2919
2920   return ret;
2921 }
2922
2923 /* changing the capacity of the queue must wake up
2924  * the _chain function, it might have more room now
2925  * to store the buffer/event in the queue */
2926 #define QUEUE_CAPACITY_CHANGE(q)\
2927   GST_QUEUE2_SIGNAL_DEL (queue);
2928
2929 /* Changing the minimum required fill level must
2930  * wake up the _loop function as it might now
2931  * be able to preceed.
2932  */
2933 #define QUEUE_THRESHOLD_CHANGE(q)\
2934   GST_QUEUE2_SIGNAL_ADD (queue);
2935
2936 static void
2937 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
2938 {
2939   GstState state;
2940
2941   /* the element must be stopped in order to do this */
2942   GST_OBJECT_LOCK (queue);
2943   state = GST_STATE (queue);
2944   if (state != GST_STATE_READY && state != GST_STATE_NULL)
2945     goto wrong_state;
2946   GST_OBJECT_UNLOCK (queue);
2947
2948   /* set new location */
2949   g_free (queue->temp_template);
2950   queue->temp_template = g_strdup (template);
2951
2952   return;
2953
2954 /* ERROR */
2955 wrong_state:
2956   {
2957     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
2958     GST_OBJECT_UNLOCK (queue);
2959   }
2960 }
2961
2962 static void
2963 gst_queue2_set_property (GObject * object,
2964     guint prop_id, const GValue * value, GParamSpec * pspec)
2965 {
2966   GstQueue2 *queue = GST_QUEUE2 (object);
2967
2968   /* someone could change levels here, and since this
2969    * affects the get/put funcs, we need to lock for safety. */
2970   GST_QUEUE2_MUTEX_LOCK (queue);
2971
2972   switch (prop_id) {
2973     case PROP_MAX_SIZE_BYTES:
2974       queue->max_level.bytes = g_value_get_uint (value);
2975       QUEUE_CAPACITY_CHANGE (queue);
2976       break;
2977     case PROP_MAX_SIZE_BUFFERS:
2978       queue->max_level.buffers = g_value_get_uint (value);
2979       QUEUE_CAPACITY_CHANGE (queue);
2980       break;
2981     case PROP_MAX_SIZE_TIME:
2982       queue->max_level.time = g_value_get_uint64 (value);
2983       /* set rate_time to the same value. We use an extra field in the level
2984        * structure so that we can easily access and compare it */
2985       queue->max_level.rate_time = queue->max_level.time;
2986       QUEUE_CAPACITY_CHANGE (queue);
2987       break;
2988     case PROP_USE_BUFFERING:
2989       queue->use_buffering = g_value_get_boolean (value);
2990       break;
2991     case PROP_USE_RATE_ESTIMATE:
2992       queue->use_rate_estimate = g_value_get_boolean (value);
2993       break;
2994     case PROP_LOW_PERCENT:
2995       queue->low_percent = g_value_get_int (value);
2996       break;
2997     case PROP_HIGH_PERCENT:
2998       queue->high_percent = g_value_get_int (value);
2999       break;
3000     case PROP_TEMP_TEMPLATE:
3001       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3002       break;
3003     case PROP_TEMP_LOCATION:
3004       g_free (queue->temp_location);
3005       queue->temp_location = g_value_dup_string (value);
3006       /* you can set the property back to NULL to make it use the temp-tmpl
3007        * property. */
3008       queue->temp_location_set = queue->temp_location != NULL;
3009       break;
3010     case PROP_TEMP_REMOVE:
3011       queue->temp_remove = g_value_get_boolean (value);
3012       break;
3013     case PROP_RING_BUFFER_MAX_SIZE:
3014       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3015       break;
3016     default:
3017       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3018       break;
3019   }
3020
3021   GST_QUEUE2_MUTEX_UNLOCK (queue);
3022 }
3023
3024 static void
3025 gst_queue2_get_property (GObject * object,
3026     guint prop_id, GValue * value, GParamSpec * pspec)
3027 {
3028   GstQueue2 *queue = GST_QUEUE2 (object);
3029
3030   GST_QUEUE2_MUTEX_LOCK (queue);
3031
3032   switch (prop_id) {
3033     case PROP_CUR_LEVEL_BYTES:
3034       g_value_set_uint (value, queue->cur_level.bytes);
3035       break;
3036     case PROP_CUR_LEVEL_BUFFERS:
3037       g_value_set_uint (value, queue->cur_level.buffers);
3038       break;
3039     case PROP_CUR_LEVEL_TIME:
3040       g_value_set_uint64 (value, queue->cur_level.time);
3041       break;
3042     case PROP_MAX_SIZE_BYTES:
3043       g_value_set_uint (value, queue->max_level.bytes);
3044       break;
3045     case PROP_MAX_SIZE_BUFFERS:
3046       g_value_set_uint (value, queue->max_level.buffers);
3047       break;
3048     case PROP_MAX_SIZE_TIME:
3049       g_value_set_uint64 (value, queue->max_level.time);
3050       break;
3051     case PROP_USE_BUFFERING:
3052       g_value_set_boolean (value, queue->use_buffering);
3053       break;
3054     case PROP_USE_RATE_ESTIMATE:
3055       g_value_set_boolean (value, queue->use_rate_estimate);
3056       break;
3057     case PROP_LOW_PERCENT:
3058       g_value_set_int (value, queue->low_percent);
3059       break;
3060     case PROP_HIGH_PERCENT:
3061       g_value_set_int (value, queue->high_percent);
3062       break;
3063     case PROP_TEMP_TEMPLATE:
3064       g_value_set_string (value, queue->temp_template);
3065       break;
3066     case PROP_TEMP_LOCATION:
3067       g_value_set_string (value, queue->temp_location);
3068       break;
3069     case PROP_TEMP_REMOVE:
3070       g_value_set_boolean (value, queue->temp_remove);
3071       break;
3072     case PROP_RING_BUFFER_MAX_SIZE:
3073       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3074       break;
3075     default:
3076       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3077       break;
3078   }
3079
3080   GST_QUEUE2_MUTEX_UNLOCK (queue);
3081 }