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