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