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