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