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