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