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