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