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