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