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