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