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