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