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