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