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