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