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