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