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