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