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