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