queue2: warn if we can't remove our temporary file
[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       post = TRUE;
898     }
899   }
900
901   if (post) {
902     if (percent == queue->buffering_percent)
903       post = FALSE;
904     else
905       queue->buffering_percent = percent;
906   }
907
908   if (post) {
909     GstMessage *message;
910     GstBufferingMode mode;
911     gint avg_in, avg_out;
912     gint64 buffering_left;
913
914     get_buffering_stats (queue, percent, &mode, &avg_in, &avg_out,
915         &buffering_left);
916
917     message = gst_message_new_buffering (GST_OBJECT_CAST (queue),
918         (gint) percent);
919     gst_message_set_buffering_stats (message, mode,
920         avg_in, avg_out, buffering_left);
921
922     gst_element_post_message (GST_ELEMENT_CAST (queue), message);
923   }
924 }
925
926 static void
927 reset_rate_timer (GstQueue2 * queue)
928 {
929   queue->bytes_in = 0;
930   queue->bytes_out = 0;
931   queue->byte_in_rate = 0.0;
932   queue->byte_in_period = 0;
933   queue->byte_out_rate = 0.0;
934   queue->last_in_elapsed = 0.0;
935   queue->last_out_elapsed = 0.0;
936   queue->in_timer_started = FALSE;
937   queue->out_timer_started = FALSE;
938 }
939
940 /* the interval in seconds to recalculate the rate */
941 #define RATE_INTERVAL    0.2
942 /* Tuning for rate estimation. We use a large window for the input rate because
943  * it should be stable when connected to a network. The output rate is less
944  * stable (the elements preroll, queues behind a demuxer fill, ...) and should
945  * therefore adapt more quickly.
946  * However, initial input rate may be subject to a burst, and should therefore
947  * initially also adapt more quickly to changes, and only later on give higher
948  * weight to previous values. */
949 #define AVG_IN(avg,val,w1,w2)  ((avg) * (w1) + (val) * (w2)) / ((w1) + (w2))
950 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
951
952 static void
953 update_in_rates (GstQueue2 * queue)
954 {
955   gdouble elapsed, period;
956   gdouble byte_in_rate;
957
958   if (!queue->in_timer_started) {
959     queue->in_timer_started = TRUE;
960     g_timer_start (queue->in_timer);
961     return;
962   }
963
964   elapsed = g_timer_elapsed (queue->in_timer, NULL);
965
966   /* recalc after each interval. */
967   if (queue->last_in_elapsed + RATE_INTERVAL < elapsed) {
968     period = elapsed - queue->last_in_elapsed;
969
970     GST_DEBUG_OBJECT (queue,
971         "rates: period %f, in %" G_GUINT64_FORMAT ", global period %f",
972         period, queue->bytes_in, queue->byte_in_period);
973
974     byte_in_rate = queue->bytes_in / period;
975
976     if (queue->byte_in_rate == 0.0)
977       queue->byte_in_rate = byte_in_rate;
978     else
979       queue->byte_in_rate = AVG_IN (queue->byte_in_rate, byte_in_rate,
980           (double) queue->byte_in_period, period);
981
982     /* another data point, cap at 16 for long time running average */
983     if (queue->byte_in_period < 16 * RATE_INTERVAL)
984       queue->byte_in_period += period;
985
986     /* reset the values to calculate rate over the next interval */
987     queue->last_in_elapsed = elapsed;
988     queue->bytes_in = 0;
989   }
990
991   if (queue->byte_in_rate > 0.0) {
992     queue->cur_level.rate_time =
993         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
994   }
995   GST_DEBUG_OBJECT (queue, "rates: in %f, time %" GST_TIME_FORMAT,
996       queue->byte_in_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
997 }
998
999 static void
1000 update_out_rates (GstQueue2 * queue)
1001 {
1002   gdouble elapsed, period;
1003   gdouble byte_out_rate;
1004
1005   if (!queue->out_timer_started) {
1006     queue->out_timer_started = TRUE;
1007     g_timer_start (queue->out_timer);
1008     return;
1009   }
1010
1011   elapsed = g_timer_elapsed (queue->out_timer, NULL);
1012
1013   /* recalc after each interval. */
1014   if (queue->last_out_elapsed + RATE_INTERVAL < elapsed) {
1015     period = elapsed - queue->last_out_elapsed;
1016
1017     GST_DEBUG_OBJECT (queue,
1018         "rates: period %f, out %" G_GUINT64_FORMAT, period, queue->bytes_out);
1019
1020     byte_out_rate = queue->bytes_out / period;
1021
1022     if (queue->byte_out_rate == 0.0)
1023       queue->byte_out_rate = byte_out_rate;
1024     else
1025       queue->byte_out_rate = AVG_OUT (queue->byte_out_rate, byte_out_rate);
1026
1027     /* reset the values to calculate rate over the next interval */
1028     queue->last_out_elapsed = elapsed;
1029     queue->bytes_out = 0;
1030   }
1031   if (queue->byte_in_rate > 0.0) {
1032     queue->cur_level.rate_time =
1033         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1034   }
1035   GST_DEBUG_OBJECT (queue, "rates: out %f, time %" GST_TIME_FORMAT,
1036       queue->byte_out_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1037 }
1038
1039 static void
1040 update_cur_pos (GstQueue2 * queue, GstQueue2Range * range, guint64 pos)
1041 {
1042   guint64 reading_pos, max_reading_pos;
1043
1044   reading_pos = pos;
1045   max_reading_pos = range->max_reading_pos;
1046
1047   max_reading_pos = MAX (max_reading_pos, reading_pos);
1048
1049   GST_DEBUG_OBJECT (queue,
1050       "updating max_reading_pos from %" G_GUINT64_FORMAT " to %"
1051       G_GUINT64_FORMAT, range->max_reading_pos, max_reading_pos);
1052   range->max_reading_pos = max_reading_pos;
1053
1054   update_cur_level (queue, range);
1055 }
1056
1057 static gboolean
1058 perform_seek_to_offset (GstQueue2 * queue, guint64 offset)
1059 {
1060   GstEvent *event;
1061   gboolean res;
1062
1063   /* until we receive the FLUSH_STOP from this seek, we skip data */
1064   queue->seeking = TRUE;
1065   GST_QUEUE2_MUTEX_UNLOCK (queue);
1066
1067   debug_ranges (queue);
1068
1069   GST_DEBUG_OBJECT (queue, "Seeking to %" G_GUINT64_FORMAT, offset);
1070
1071   event =
1072       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1073       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1074       GST_SEEK_TYPE_NONE, -1);
1075
1076   res = gst_pad_push_event (queue->sinkpad, event);
1077   GST_QUEUE2_MUTEX_LOCK (queue);
1078
1079   if (res) {
1080     /* Between us sending the seek event and re-acquiring the lock, the source
1081      * thread might already have pushed data and moved along the range's
1082      * writing_pos beyond the seek offset. In that case we don't want to set
1083      * the writing position back to the requested seek position, as it would
1084      * cause data to be written to the wrong offset in the file or ring buffer.
1085      * We still do the add_range call to switch the current range to the
1086      * requested range, or create one if one doesn't exist yet. */
1087     queue->current = add_range (queue, offset, FALSE);
1088   }
1089
1090   return res;
1091 }
1092
1093 /* get the threshold for when we decide to seek rather than wait */
1094 static guint64
1095 get_seek_threshold (GstQueue2 * queue)
1096 {
1097   guint64 threshold;
1098
1099   /* FIXME, find a good threshold based on the incoming rate. */
1100   threshold = 1024 * 512;
1101
1102   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1103     threshold = MIN (threshold,
1104         QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes);
1105   }
1106   return threshold;
1107 }
1108
1109 /* see if there is enough data in the file to read a full buffer */
1110 static gboolean
1111 gst_queue2_have_data (GstQueue2 * queue, guint64 offset, guint length)
1112 {
1113   GstQueue2Range *range;
1114
1115   GST_DEBUG_OBJECT (queue, "looking for offset %" G_GUINT64_FORMAT ", len %u",
1116       offset, length);
1117
1118   if ((range = find_range (queue, offset))) {
1119     if (queue->current != range) {
1120       GST_DEBUG_OBJECT (queue, "switching ranges, do seek to range position");
1121       perform_seek_to_offset (queue, range->writing_pos);
1122     }
1123
1124     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1125         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1126
1127     /* we have a range for offset */
1128     GST_DEBUG_OBJECT (queue,
1129         "we have a range %p, offset %" G_GUINT64_FORMAT ", writing_pos %"
1130         G_GUINT64_FORMAT, range, range->offset, range->writing_pos);
1131
1132     if (!QUEUE_IS_USING_RING_BUFFER (queue) && queue->is_eos)
1133       return TRUE;
1134
1135     if (offset + length <= range->writing_pos)
1136       return TRUE;
1137     else
1138       GST_DEBUG_OBJECT (queue,
1139           "Need more data (%" G_GUINT64_FORMAT " bytes more)",
1140           (offset + length) - range->writing_pos);
1141
1142   } else {
1143     GST_INFO_OBJECT (queue, "not found in any range off %" G_GUINT64_FORMAT
1144         " len %u", offset, length);
1145     /* we don't have the range, see how far away we are */
1146     if (!queue->is_eos && queue->current) {
1147       guint64 threshold = get_seek_threshold (queue);
1148
1149       if (offset >= queue->current->offset && offset <=
1150           queue->current->writing_pos + threshold) {
1151         GST_INFO_OBJECT (queue,
1152             "requested data is within range, wait for data");
1153         return FALSE;
1154       }
1155     }
1156
1157     /* too far away, do a seek */
1158     perform_seek_to_offset (queue, offset);
1159   }
1160
1161   return FALSE;
1162 }
1163
1164 #ifdef HAVE_FSEEKO
1165 #define FSEEK_FILE(file,offset)  (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1166 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1167 #define FSEEK_FILE(file,offset)  (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1168 #else
1169 #define FSEEK_FILE(file,offset)  (fseek (file, offset, SEEK_SET) != 0)
1170 #endif
1171
1172 static GstFlowReturn
1173 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1174     guint8 * dst, gint64 * read_return)
1175 {
1176   guint8 *ring_buffer;
1177   size_t res;
1178
1179   ring_buffer = queue->ring_buffer;
1180
1181   if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1182     goto seek_failed;
1183
1184   /* this should not block */
1185   GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1186       length, offset);
1187   if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1188     res = fread (dst, 1, length, queue->temp_file);
1189   } else {
1190     memcpy (dst, ring_buffer + offset, length);
1191     res = length;
1192   }
1193
1194   GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1195
1196   if (G_UNLIKELY (res < length)) {
1197     if (!QUEUE_IS_USING_TEMP_FILE (queue))
1198       goto could_not_read;
1199     /* check for errors or EOF */
1200     if (ferror (queue->temp_file))
1201       goto could_not_read;
1202     if (feof (queue->temp_file) && length > 0)
1203       goto eos;
1204   }
1205
1206   *read_return = res;
1207
1208   return GST_FLOW_OK;
1209
1210 seek_failed:
1211   {
1212     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1213     return GST_FLOW_ERROR;
1214   }
1215 could_not_read:
1216   {
1217     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1218     return GST_FLOW_ERROR;
1219   }
1220 eos:
1221   {
1222     GST_DEBUG ("non-regular file hits EOS");
1223     return GST_FLOW_EOS;
1224   }
1225 }
1226
1227 static GstFlowReturn
1228 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1229     GstBuffer ** buffer)
1230 {
1231   GstBuffer *buf;
1232   GstMapInfo info;
1233   guint8 *data;
1234   guint64 file_offset;
1235   guint block_length, remaining, read_length;
1236   guint64 rb_size;
1237   guint64 max_size;
1238   guint64 rpos;
1239   GstFlowReturn ret = GST_FLOW_OK;
1240
1241   /* allocate the output buffer of the requested size */
1242   if (*buffer == NULL)
1243     buf = gst_buffer_new_allocate (NULL, length, NULL);
1244   else
1245     buf = *buffer;
1246
1247   gst_buffer_map (buf, &info, GST_MAP_WRITE);
1248   data = info.data;
1249
1250   GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1251       offset);
1252
1253   rpos = offset;
1254   rb_size = queue->ring_buffer_max_size;
1255   max_size = QUEUE_MAX_BYTES (queue);
1256
1257   remaining = length;
1258   while (remaining > 0) {
1259     /* configure how much/whether to read */
1260     if (!gst_queue2_have_data (queue, rpos, remaining)) {
1261       read_length = 0;
1262
1263       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1264         guint64 level;
1265
1266         /* calculate how far away the offset is */
1267         if (queue->current->writing_pos > rpos)
1268           level = queue->current->writing_pos - rpos;
1269         else
1270           level = 0;
1271
1272         GST_DEBUG_OBJECT (queue,
1273             "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1274             ", level %" G_GUINT64_FORMAT ", max %" G_GUINT64_FORMAT,
1275             rpos, queue->current->writing_pos, level, max_size);
1276
1277         if (level >= max_size) {
1278           /* we don't have the data but if we have a ring buffer that is full, we
1279            * need to read */
1280           GST_DEBUG_OBJECT (queue,
1281               "ring buffer full, reading QUEUE_MAX_BYTES %"
1282               G_GUINT64_FORMAT " bytes", max_size);
1283           read_length = max_size;
1284         } else if (queue->is_eos) {
1285           /* won't get any more data so read any data we have */
1286           if (level) {
1287             GST_DEBUG_OBJECT (queue,
1288                 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1289                 level);
1290             read_length = level;
1291             remaining = level;
1292             length = level;
1293           } else
1294             goto hit_eos;
1295         }
1296       }
1297
1298       if (read_length == 0) {
1299         if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1300           GST_DEBUG_OBJECT (queue,
1301               "update current position [%" G_GUINT64_FORMAT "-%"
1302               G_GUINT64_FORMAT "]", rpos, queue->current->max_reading_pos);
1303           update_cur_pos (queue, queue->current, rpos);
1304           GST_QUEUE2_SIGNAL_DEL (queue);
1305         }
1306
1307         if (queue->use_buffering)
1308           update_buffering (queue);
1309
1310         GST_DEBUG_OBJECT (queue, "waiting for add");
1311         GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1312         continue;
1313       }
1314     } else {
1315       /* we have the requested data so read it */
1316       read_length = remaining;
1317     }
1318
1319     /* set range reading_pos to actual reading position for this read */
1320     queue->current->reading_pos = rpos;
1321
1322     /* configure how much and from where to read */
1323     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1324       file_offset =
1325           (queue->current->rb_offset + (rpos -
1326               queue->current->offset)) % rb_size;
1327       if (file_offset + read_length > rb_size) {
1328         block_length = rb_size - file_offset;
1329       } else {
1330         block_length = read_length;
1331       }
1332     } else {
1333       file_offset = rpos;
1334       block_length = read_length;
1335     }
1336
1337     /* while we still have data to read, we loop */
1338     while (read_length > 0) {
1339       gint64 read_return;
1340
1341       ret =
1342           gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1343           data, &read_return);
1344       if (ret != GST_FLOW_OK)
1345         goto read_error;
1346
1347       file_offset += read_return;
1348       if (QUEUE_IS_USING_RING_BUFFER (queue))
1349         file_offset %= rb_size;
1350
1351       data += read_return;
1352       read_length -= read_return;
1353       block_length = read_length;
1354       remaining -= read_return;
1355
1356       rpos = (queue->current->reading_pos += read_return);
1357       update_cur_pos (queue, queue->current, queue->current->reading_pos);
1358     }
1359     GST_QUEUE2_SIGNAL_DEL (queue);
1360     GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1361   }
1362
1363   gst_buffer_unmap (buf, &info);
1364   gst_buffer_resize (buf, 0, length);
1365
1366   GST_BUFFER_OFFSET (buf) = offset;
1367   GST_BUFFER_OFFSET_END (buf) = offset + length;
1368
1369   *buffer = buf;
1370
1371   return ret;
1372
1373   /* ERRORS */
1374 hit_eos:
1375   {
1376     GST_DEBUG_OBJECT (queue, "EOS hit and we don't have any requested data");
1377     gst_buffer_unmap (buf, &info);
1378     if (*buffer == NULL)
1379       gst_buffer_unref (buf);
1380     return GST_FLOW_EOS;
1381   }
1382 out_flushing:
1383   {
1384     GST_DEBUG_OBJECT (queue, "we are flushing");
1385     gst_buffer_unmap (buf, &info);
1386     if (*buffer == NULL)
1387       gst_buffer_unref (buf);
1388     return GST_FLOW_FLUSHING;
1389   }
1390 read_error:
1391   {
1392     GST_DEBUG_OBJECT (queue, "we have a read error");
1393     gst_buffer_unmap (buf, &info);
1394     if (*buffer == NULL)
1395       gst_buffer_unref (buf);
1396     return ret;
1397   }
1398 }
1399
1400 /* should be called with QUEUE_LOCK */
1401 static GstMiniObject *
1402 gst_queue2_read_item_from_file (GstQueue2 * queue)
1403 {
1404   GstMiniObject *item;
1405
1406   if (queue->stream_start_event != NULL) {
1407     item = GST_MINI_OBJECT_CAST (queue->stream_start_event);
1408     queue->stream_start_event = NULL;
1409   } else if (queue->starting_segment != NULL) {
1410     item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1411     queue->starting_segment = NULL;
1412   } else {
1413     GstFlowReturn ret;
1414     GstBuffer *buffer = NULL;
1415     guint64 reading_pos;
1416
1417     reading_pos = queue->current->reading_pos;
1418
1419     ret =
1420         gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1421         &buffer);
1422
1423     switch (ret) {
1424       case GST_FLOW_OK:
1425         item = GST_MINI_OBJECT_CAST (buffer);
1426         break;
1427       case GST_FLOW_EOS:
1428         item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1429         break;
1430       default:
1431         item = NULL;
1432         break;
1433     }
1434   }
1435   return item;
1436 }
1437
1438 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1439  * the temp filename. */
1440 static gboolean
1441 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1442 {
1443   gint fd = -1;
1444   gchar *name = NULL;
1445
1446   if (queue->temp_file)
1447     goto already_opened;
1448
1449   GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1450
1451   /* If temp_template was set, allocate a filename and open that filen */
1452
1453   /* nothing to do */
1454   if (queue->temp_template == NULL)
1455     goto no_directory;
1456
1457   /* make copy of the template, we don't want to change this */
1458   name = g_strdup (queue->temp_template);
1459   fd = g_mkstemp (name);
1460   if (fd == -1)
1461     goto mkstemp_failed;
1462
1463   /* open the file for update/writing */
1464   queue->temp_file = fdopen (fd, "wb+");
1465   /* error creating file */
1466   if (queue->temp_file == NULL)
1467     goto open_failed;
1468
1469   g_free (queue->temp_location);
1470   queue->temp_location = name;
1471
1472   GST_QUEUE2_MUTEX_UNLOCK (queue);
1473
1474   /* we can't emit the notify with the lock */
1475   g_object_notify (G_OBJECT (queue), "temp-location");
1476
1477   GST_QUEUE2_MUTEX_LOCK (queue);
1478
1479   GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1480
1481   return TRUE;
1482
1483   /* ERRORS */
1484 already_opened:
1485   {
1486     GST_DEBUG_OBJECT (queue, "temp file was already open");
1487     return TRUE;
1488   }
1489 no_directory:
1490   {
1491     GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1492         (_("No Temp directory specified.")), (NULL));
1493     return FALSE;
1494   }
1495 mkstemp_failed:
1496   {
1497     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1498         (_("Could not create temp file \"%s\"."), queue->temp_template),
1499         GST_ERROR_SYSTEM);
1500     g_free (name);
1501     return FALSE;
1502   }
1503 open_failed:
1504   {
1505     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1506         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1507     g_free (name);
1508     if (fd != -1)
1509       close (fd);
1510     return FALSE;
1511   }
1512 }
1513
1514 static void
1515 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1516 {
1517   /* nothing to do */
1518   if (queue->temp_file == NULL)
1519     return;
1520
1521   GST_DEBUG_OBJECT (queue, "closing temp file");
1522
1523   fflush (queue->temp_file);
1524   fclose (queue->temp_file);
1525
1526   if (queue->temp_remove) {
1527     if (remove (queue->temp_location) < 0) {
1528       GST_WARNING_OBJECT (queue, "Failed to remove temporary file %s: %s",
1529           queue->temp_location, strerror (errno));
1530     }
1531   }
1532
1533   queue->temp_file = NULL;
1534   clean_ranges (queue);
1535 }
1536
1537 static void
1538 gst_queue2_flush_temp_file (GstQueue2 * queue)
1539 {
1540   if (queue->temp_file == NULL)
1541     return;
1542
1543   GST_DEBUG_OBJECT (queue, "flushing temp file");
1544
1545   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1546 }
1547
1548 static void
1549 gst_queue2_locked_flush (GstQueue2 * queue, gboolean full, gboolean clear_temp)
1550 {
1551   if (!QUEUE_IS_USING_QUEUE (queue)) {
1552     if (QUEUE_IS_USING_TEMP_FILE (queue) && clear_temp)
1553       gst_queue2_flush_temp_file (queue);
1554     init_ranges (queue);
1555   } else {
1556     while (!g_queue_is_empty (&queue->queue)) {
1557       GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
1558
1559       if (!full && qitem->type == GST_QUEUE2_ITEM_TYPE_EVENT
1560           && GST_EVENT_IS_STICKY (qitem->item)
1561           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_SEGMENT
1562           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_EOS) {
1563         gst_pad_store_sticky_event (queue->srcpad,
1564             GST_EVENT_CAST (qitem->item));
1565       }
1566
1567       /* Then lose another reference because we are supposed to destroy that
1568          data when flushing */
1569       if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
1570         gst_mini_object_unref (qitem->item);
1571       g_slice_free (GstQueue2Item, qitem);
1572     }
1573   }
1574   queue->last_query = FALSE;
1575   g_cond_signal (&queue->query_handled);
1576   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1577   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1578   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1579   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1580   queue->sink_tainted = queue->src_tainted = TRUE;
1581   if (queue->starting_segment != NULL)
1582     gst_event_unref (queue->starting_segment);
1583   queue->starting_segment = NULL;
1584   queue->segment_event_received = FALSE;
1585   gst_event_replace (&queue->stream_start_event, NULL);
1586
1587   /* we deleted a lot of something */
1588   GST_QUEUE2_SIGNAL_DEL (queue);
1589 }
1590
1591 static gboolean
1592 gst_queue2_wait_free_space (GstQueue2 * queue)
1593 {
1594   /* We make space available if we're "full" according to whatever
1595    * the user defined as "full". */
1596   if (gst_queue2_is_filled (queue)) {
1597     gboolean started;
1598
1599     /* pause the timer while we wait. The fact that we are waiting does not mean
1600      * the byterate on the input pad is lower */
1601     if ((started = queue->in_timer_started))
1602       g_timer_stop (queue->in_timer);
1603
1604     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1605         "queue is full, waiting for free space");
1606     do {
1607       /* Wait for space to be available, we could be unlocked because of a flush. */
1608       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1609     }
1610     while (gst_queue2_is_filled (queue));
1611
1612     /* and continue if we were running before */
1613     if (started)
1614       g_timer_continue (queue->in_timer);
1615   }
1616   return TRUE;
1617
1618   /* ERRORS */
1619 out_flushing:
1620   {
1621     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1622     return FALSE;
1623   }
1624 }
1625
1626 static gboolean
1627 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1628 {
1629   GstMapInfo info;
1630   guint8 *data, *ring_buffer;
1631   guint size, rb_size;
1632   guint64 writing_pos, new_writing_pos;
1633   GstQueue2Range *range, *prev, *next;
1634   gboolean do_seek = FALSE;
1635
1636   if (QUEUE_IS_USING_RING_BUFFER (queue))
1637     writing_pos = queue->current->rb_writing_pos;
1638   else
1639     writing_pos = queue->current->writing_pos;
1640   ring_buffer = queue->ring_buffer;
1641   rb_size = queue->ring_buffer_max_size;
1642
1643   gst_buffer_map (buffer, &info, GST_MAP_READ);
1644
1645   size = info.size;
1646   data = info.data;
1647
1648   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1649       writing_pos);
1650
1651   /* sanity check */
1652   if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1653       GST_BUFFER_OFFSET (buffer) != queue->current->writing_pos) {
1654     GST_WARNING_OBJECT (queue, "buffer offset does not match current writing "
1655         "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1656         GST_BUFFER_OFFSET (buffer), queue->current->writing_pos);
1657   }
1658
1659   while (size > 0) {
1660     guint to_write;
1661
1662     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1663       gint64 space;
1664
1665       /* calculate the space in the ring buffer not used by data from
1666        * the current range */
1667       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1668         /* wait until there is some free space */
1669         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1670       }
1671       /* get the amount of space we have */
1672       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1673
1674       /* calculate if we need to split or if we can write the entire
1675        * buffer now */
1676       to_write = MIN (size, space);
1677
1678       /* the writing position in the ring buffer after writing (part
1679        * or all of) the buffer */
1680       new_writing_pos = (writing_pos + to_write) % rb_size;
1681
1682       prev = NULL;
1683       range = queue->ranges;
1684
1685       /* if we need to overwrite data in the ring buffer, we need to
1686        * update the ranges
1687        *
1688        * warning: this code is complicated and includes some
1689        * simplifications - pen, paper and diagrams for the cases
1690        * recommended! */
1691       while (range) {
1692         guint64 range_data_start, range_data_end;
1693         GstQueue2Range *range_to_destroy = NULL;
1694
1695         range_data_start = range->rb_offset;
1696         range_data_end = range->rb_writing_pos;
1697
1698         /* handle the special case where the range has no data in it */
1699         if (range->writing_pos == range->offset) {
1700           if (range != queue->current) {
1701             GST_DEBUG_OBJECT (queue,
1702                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1703                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1704             /* remove range */
1705             range_to_destroy = range;
1706             if (prev)
1707               prev->next = range->next;
1708           }
1709           goto next_range;
1710         }
1711
1712         if (range_data_end > range_data_start) {
1713           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1714             goto next_range;
1715
1716           if (new_writing_pos > range_data_start) {
1717             if (new_writing_pos >= range_data_end) {
1718               GST_DEBUG_OBJECT (queue,
1719                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1720                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1721               /* remove range */
1722               range_to_destroy = range;
1723               if (prev)
1724                 prev->next = range->next;
1725             } else {
1726               GST_DEBUG_OBJECT (queue,
1727                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1728                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1729                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1730                   range->offset + new_writing_pos - range_data_start,
1731                   new_writing_pos);
1732               range->offset += (new_writing_pos - range_data_start);
1733               range->rb_offset = new_writing_pos;
1734             }
1735           }
1736         } else {
1737           guint64 new_wpos_virt = writing_pos + to_write;
1738
1739           if (new_wpos_virt <= range_data_start)
1740             goto next_range;
1741
1742           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1743             GST_DEBUG_OBJECT (queue,
1744                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1745                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1746             /* remove range */
1747             range_to_destroy = range;
1748             if (prev)
1749               prev->next = range->next;
1750           } else {
1751             GST_DEBUG_OBJECT (queue,
1752                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1753                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1754                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1755                 range->offset + new_writing_pos - range_data_start,
1756                 new_writing_pos);
1757             range->offset += (new_wpos_virt - range_data_start);
1758             range->rb_offset = new_writing_pos;
1759           }
1760         }
1761
1762       next_range:
1763         if (!range_to_destroy)
1764           prev = range;
1765
1766         range = range->next;
1767         if (range_to_destroy) {
1768           if (range_to_destroy == queue->ranges)
1769             queue->ranges = range;
1770           g_slice_free (GstQueue2Range, range_to_destroy);
1771           range_to_destroy = NULL;
1772         }
1773       }
1774     } else {
1775       to_write = size;
1776       new_writing_pos = writing_pos + to_write;
1777     }
1778
1779     if (QUEUE_IS_USING_TEMP_FILE (queue)
1780         && FSEEK_FILE (queue->temp_file, writing_pos))
1781       goto seek_failed;
1782
1783     if (new_writing_pos > writing_pos) {
1784       GST_INFO_OBJECT (queue,
1785           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1786           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1787           queue->current->writing_pos, queue->current->rb_writing_pos);
1788       /* either not using ring buffer or no wrapping, just write */
1789       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1790         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1791           goto handle_error;
1792       } else {
1793         memcpy (ring_buffer + writing_pos, data, to_write);
1794       }
1795
1796       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1797         /* try to merge with next range */
1798         while ((next = queue->current->next)) {
1799           GST_INFO_OBJECT (queue,
1800               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1801               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1802           if (new_writing_pos < next->offset)
1803             break;
1804
1805           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1806               next->writing_pos);
1807
1808           /* remove the group */
1809           queue->current->next = next->next;
1810
1811           /* We use the threshold to decide if we want to do a seek or simply
1812            * read the data again. If there is not so much data in the range we
1813            * prefer to avoid to seek and read it again. */
1814           if (next->writing_pos > new_writing_pos + get_seek_threshold (queue)) {
1815             /* the new range had more data than the threshold, it's worth keeping
1816              * it and doing a seek. */
1817             new_writing_pos = next->writing_pos;
1818             do_seek = TRUE;
1819           }
1820           g_slice_free (GstQueue2Range, next);
1821         }
1822         goto update_and_signal;
1823       }
1824     } else {
1825       /* wrapping */
1826       guint block_one, block_two;
1827
1828       block_one = rb_size - writing_pos;
1829       block_two = to_write - block_one;
1830
1831       if (block_one > 0) {
1832         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1833         /* write data to end of ring buffer */
1834         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1835           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1836             goto handle_error;
1837         } else {
1838           memcpy (ring_buffer + writing_pos, data, block_one);
1839         }
1840       }
1841
1842       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1843         goto seek_failed;
1844
1845       if (block_two > 0) {
1846         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
1847         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1848           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
1849             goto handle_error;
1850         } else {
1851           memcpy (ring_buffer, data + block_one, block_two);
1852         }
1853       }
1854     }
1855
1856   update_and_signal:
1857     /* update the writing positions */
1858     size -= to_write;
1859     GST_INFO_OBJECT (queue,
1860         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
1861         to_write, writing_pos, size);
1862
1863     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1864       data += to_write;
1865       queue->current->writing_pos += to_write;
1866       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
1867     } else {
1868       queue->current->writing_pos = writing_pos = new_writing_pos;
1869     }
1870     if (do_seek)
1871       perform_seek_to_offset (queue, new_writing_pos);
1872
1873     update_cur_level (queue, queue->current);
1874
1875     /* update the buffering status */
1876     if (queue->use_buffering)
1877       update_buffering (queue);
1878
1879     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1880         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1881
1882     GST_QUEUE2_SIGNAL_ADD (queue);
1883   }
1884
1885   gst_buffer_unmap (buffer, &info);
1886
1887   return TRUE;
1888
1889   /* ERRORS */
1890 out_flushing:
1891   {
1892     GST_DEBUG_OBJECT (queue, "we are flushing");
1893     gst_buffer_unmap (buffer, &info);
1894     /* FIXME - GST_FLOW_EOS ? */
1895     return FALSE;
1896   }
1897 seek_failed:
1898   {
1899     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1900     gst_buffer_unmap (buffer, &info);
1901     return FALSE;
1902   }
1903 handle_error:
1904   {
1905     switch (errno) {
1906       case ENOSPC:{
1907         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
1908         break;
1909       }
1910       default:{
1911         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
1912             (_("Error while writing to download file.")),
1913             ("%s", g_strerror (errno)));
1914       }
1915     }
1916     gst_buffer_unmap (buffer, &info);
1917     return FALSE;
1918   }
1919 }
1920
1921 static gboolean
1922 buffer_list_create_write (GstBuffer ** buf, guint idx, gpointer q)
1923 {
1924   GstQueue2 *queue = q;
1925
1926   GST_TRACE_OBJECT (queue,
1927       "writing buffer %u of size %" G_GSIZE_FORMAT " bytes", idx,
1928       gst_buffer_get_size (*buf));
1929
1930   if (!gst_queue2_create_write (queue, *buf)) {
1931     GST_INFO_OBJECT (queue, "create_write() returned FALSE, bailing out");
1932     return FALSE;
1933   }
1934   return TRUE;
1935 }
1936
1937 static gboolean
1938 buffer_list_calc_size (GstBuffer ** buf, guint idx, gpointer data)
1939 {
1940   guint *p_size = data;
1941   gsize buf_size;
1942
1943   buf_size = gst_buffer_get_size (*buf);
1944   GST_TRACE ("buffer %u in has size %" G_GSIZE_FORMAT, idx, buf_size);
1945   *p_size += buf_size;
1946   return TRUE;
1947 }
1948
1949 /* enqueue an item an update the level stats */
1950 static void
1951 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item,
1952     GstQueue2ItemType item_type)
1953 {
1954   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
1955     GstBuffer *buffer;
1956     guint size;
1957
1958     buffer = GST_BUFFER_CAST (item);
1959     size = gst_buffer_get_size (buffer);
1960
1961     /* add buffer to the statistics */
1962     if (QUEUE_IS_USING_QUEUE (queue)) {
1963       queue->cur_level.buffers++;
1964       queue->cur_level.bytes += size;
1965     }
1966     queue->bytes_in += size;
1967
1968     /* apply new buffer to segment stats */
1969     apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
1970     /* update the byterate stats */
1971     update_in_rates (queue);
1972
1973     if (!QUEUE_IS_USING_QUEUE (queue)) {
1974       /* FIXME - check return value? */
1975       gst_queue2_create_write (queue, buffer);
1976     }
1977   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
1978     GstBufferList *buffer_list;
1979     guint size = 0;
1980
1981     buffer_list = GST_BUFFER_LIST_CAST (item);
1982
1983     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
1984     GST_LOG_OBJECT (queue, "total size of buffer list: %u bytes", size);
1985
1986     /* add buffer to the statistics */
1987     if (QUEUE_IS_USING_QUEUE (queue)) {
1988       queue->cur_level.buffers++;
1989       queue->cur_level.bytes += size;
1990     }
1991     queue->bytes_in += size;
1992
1993     /* apply new buffer to segment stats */
1994     apply_buffer_list (queue, buffer_list, &queue->sink_segment, TRUE);
1995
1996     /* update the byterate stats */
1997     update_in_rates (queue);
1998
1999     if (!QUEUE_IS_USING_QUEUE (queue)) {
2000       gst_buffer_list_foreach (buffer_list, buffer_list_create_write, queue);
2001     }
2002   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2003     GstEvent *event;
2004
2005     event = GST_EVENT_CAST (item);
2006
2007     switch (GST_EVENT_TYPE (event)) {
2008       case GST_EVENT_EOS:
2009         /* Zero the thresholds, this makes sure the queue is completely
2010          * filled and we can read all data from the queue. */
2011         GST_DEBUG_OBJECT (queue, "we have EOS");
2012         queue->is_eos = TRUE;
2013         break;
2014       case GST_EVENT_SEGMENT:
2015         apply_segment (queue, event, &queue->sink_segment, TRUE);
2016         /* This is our first new segment, we hold it
2017          * as we can't save it on the temp file */
2018         if (!QUEUE_IS_USING_QUEUE (queue)) {
2019           if (queue->segment_event_received)
2020             goto unexpected_event;
2021
2022           queue->segment_event_received = TRUE;
2023           if (queue->starting_segment != NULL)
2024             gst_event_unref (queue->starting_segment);
2025           queue->starting_segment = event;
2026           item = NULL;
2027         }
2028         /* a new segment allows us to accept more buffers if we got EOS
2029          * from downstream */
2030         queue->unexpected = FALSE;
2031         break;
2032       case GST_EVENT_STREAM_START:
2033         if (!QUEUE_IS_USING_QUEUE (queue)) {
2034           gst_event_replace (&queue->stream_start_event, event);
2035           gst_event_unref (event);
2036           item = NULL;
2037         }
2038         break;
2039       case GST_EVENT_CAPS:{
2040         GstCaps *caps;
2041
2042         gst_event_parse_caps (event, &caps);
2043         GST_INFO ("got caps: %" GST_PTR_FORMAT, caps);
2044
2045         if (!QUEUE_IS_USING_QUEUE (queue)) {
2046           GST_LOG ("Dropping caps event, not using queue");
2047           gst_event_unref (event);
2048           item = NULL;
2049         }
2050         break;
2051       }
2052       default:
2053         if (!QUEUE_IS_USING_QUEUE (queue))
2054           goto unexpected_event;
2055         break;
2056     }
2057   } else if (GST_IS_QUERY (item)) {
2058     /* Can't happen as we check that in the caller */
2059     if (!QUEUE_IS_USING_QUEUE (queue))
2060       g_assert_not_reached ();
2061   } else {
2062     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
2063         item, GST_OBJECT_NAME (queue));
2064     /* we can't really unref since we don't know what it is */
2065     item = NULL;
2066   }
2067
2068   if (item) {
2069     /* update the buffering status */
2070     if (queue->use_buffering)
2071       update_buffering (queue);
2072
2073     if (QUEUE_IS_USING_QUEUE (queue)) {
2074       GstQueue2Item *qitem = g_slice_new (GstQueue2Item);
2075       qitem->type = item_type;
2076       qitem->item = item;
2077       g_queue_push_tail (&queue->queue, qitem);
2078     } else {
2079       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
2080     }
2081
2082     GST_QUEUE2_SIGNAL_ADD (queue);
2083   }
2084
2085   return;
2086
2087   /* ERRORS */
2088 unexpected_event:
2089   {
2090     g_warning
2091         ("Unexpected event of kind %s can't be added in temp file of queue %s ",
2092         gst_event_type_get_name (GST_EVENT_TYPE (item)),
2093         GST_OBJECT_NAME (queue));
2094     gst_event_unref (GST_EVENT_CAST (item));
2095     return;
2096   }
2097 }
2098
2099 /* dequeue an item from the queue and update level stats */
2100 static GstMiniObject *
2101 gst_queue2_locked_dequeue (GstQueue2 * queue, GstQueue2ItemType * item_type)
2102 {
2103   GstMiniObject *item;
2104
2105   if (!QUEUE_IS_USING_QUEUE (queue)) {
2106     item = gst_queue2_read_item_from_file (queue);
2107   } else {
2108     GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
2109
2110     if (qitem == NULL)
2111       goto no_item;
2112
2113     item = qitem->item;
2114     g_slice_free (GstQueue2Item, qitem);
2115   }
2116
2117   if (item == NULL)
2118     goto no_item;
2119
2120   if (GST_IS_BUFFER (item)) {
2121     GstBuffer *buffer;
2122     guint size;
2123
2124     buffer = GST_BUFFER_CAST (item);
2125     size = gst_buffer_get_size (buffer);
2126     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER;
2127
2128     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2129         "retrieved buffer %p from queue", buffer);
2130
2131     if (QUEUE_IS_USING_QUEUE (queue)) {
2132       queue->cur_level.buffers--;
2133       queue->cur_level.bytes -= size;
2134     }
2135     queue->bytes_out += size;
2136
2137     apply_buffer (queue, buffer, &queue->src_segment, FALSE);
2138     /* update the byterate stats */
2139     update_out_rates (queue);
2140     /* update the buffering */
2141     if (queue->use_buffering)
2142       update_buffering (queue);
2143
2144   } else if (GST_IS_EVENT (item)) {
2145     GstEvent *event = GST_EVENT_CAST (item);
2146
2147     *item_type = GST_QUEUE2_ITEM_TYPE_EVENT;
2148
2149     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2150         "retrieved event %p from queue", event);
2151
2152     switch (GST_EVENT_TYPE (event)) {
2153       case GST_EVENT_EOS:
2154         /* queue is empty now that we dequeued the EOS */
2155         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
2156         break;
2157       case GST_EVENT_SEGMENT:
2158         apply_segment (queue, event, &queue->src_segment, FALSE);
2159         break;
2160       default:
2161         break;
2162     }
2163   } else if (GST_IS_BUFFER_LIST (item)) {
2164     GstBufferList *buffer_list;
2165     guint size = 0;
2166
2167     buffer_list = GST_BUFFER_LIST_CAST (item);
2168     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2169     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER_LIST;
2170
2171     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2172         "retrieved buffer list %p from queue", buffer_list);
2173
2174     if (QUEUE_IS_USING_QUEUE (queue)) {
2175       queue->cur_level.buffers--;
2176       queue->cur_level.bytes -= size;
2177     }
2178     queue->bytes_out += size;
2179
2180     apply_buffer_list (queue, buffer_list, &queue->src_segment, FALSE);
2181     /* update the byterate stats */
2182     update_out_rates (queue);
2183     /* update the buffering */
2184     if (queue->use_buffering)
2185       update_buffering (queue);
2186   } else if (GST_IS_QUERY (item)) {
2187     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2188         "retrieved query %p from queue", item);
2189     *item_type = GST_QUEUE2_ITEM_TYPE_QUERY;
2190   } else {
2191     g_warning
2192         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
2193         item, GST_OBJECT_NAME (queue));
2194     item = NULL;
2195     *item_type = GST_QUEUE2_ITEM_TYPE_UNKNOWN;
2196   }
2197   GST_QUEUE2_SIGNAL_DEL (queue);
2198
2199   return item;
2200
2201   /* ERRORS */
2202 no_item:
2203   {
2204     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
2205     return NULL;
2206   }
2207 }
2208
2209 static gboolean
2210 gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
2211     GstEvent * event)
2212 {
2213   gboolean ret = TRUE;
2214   GstQueue2 *queue;
2215
2216   queue = GST_QUEUE2 (parent);
2217
2218   switch (GST_EVENT_TYPE (event)) {
2219     case GST_EVENT_FLUSH_START:
2220     {
2221       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
2222       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2223         /* forward event */
2224         ret = gst_pad_push_event (queue->srcpad, event);
2225
2226         /* now unblock the chain function */
2227         GST_QUEUE2_MUTEX_LOCK (queue);
2228         queue->srcresult = GST_FLOW_FLUSHING;
2229         queue->sinkresult = GST_FLOW_FLUSHING;
2230         /* unblock the loop and chain functions */
2231         GST_QUEUE2_SIGNAL_ADD (queue);
2232         GST_QUEUE2_SIGNAL_DEL (queue);
2233         queue->last_query = FALSE;
2234         g_cond_signal (&queue->query_handled);
2235         GST_QUEUE2_MUTEX_UNLOCK (queue);
2236
2237         /* make sure it pauses, this should happen since we sent
2238          * flush_start downstream. */
2239         gst_pad_pause_task (queue->srcpad);
2240         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
2241       } else {
2242         GST_QUEUE2_MUTEX_LOCK (queue);
2243         /* flush the sink pad */
2244         queue->sinkresult = GST_FLOW_FLUSHING;
2245         GST_QUEUE2_SIGNAL_DEL (queue);
2246         queue->last_query = FALSE;
2247         g_cond_signal (&queue->query_handled);
2248         GST_QUEUE2_MUTEX_UNLOCK (queue);
2249
2250         gst_event_unref (event);
2251       }
2252       break;
2253     }
2254     case GST_EVENT_FLUSH_STOP:
2255     {
2256       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2257
2258       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2259         /* forward event */
2260         ret = gst_pad_push_event (queue->srcpad, event);
2261
2262         GST_QUEUE2_MUTEX_LOCK (queue);
2263         gst_queue2_locked_flush (queue, FALSE, TRUE);
2264         queue->srcresult = GST_FLOW_OK;
2265         queue->sinkresult = GST_FLOW_OK;
2266         queue->is_eos = FALSE;
2267         queue->unexpected = FALSE;
2268         queue->seeking = FALSE;
2269         /* reset rate counters */
2270         reset_rate_timer (queue);
2271         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2272             queue->srcpad, NULL);
2273         GST_QUEUE2_MUTEX_UNLOCK (queue);
2274       } else {
2275         GST_QUEUE2_MUTEX_LOCK (queue);
2276         queue->segment_event_received = FALSE;
2277         queue->is_eos = FALSE;
2278         queue->unexpected = FALSE;
2279         queue->sinkresult = GST_FLOW_OK;
2280         queue->seeking = FALSE;
2281         GST_QUEUE2_MUTEX_UNLOCK (queue);
2282
2283         gst_event_unref (event);
2284       }
2285       break;
2286     }
2287     default:
2288       if (GST_EVENT_IS_SERIALIZED (event)) {
2289         /* serialized events go in the queue */
2290         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2291         /* refuse more events on EOS */
2292         if (queue->is_eos)
2293           goto out_eos;
2294         gst_queue2_locked_enqueue (queue, event, GST_QUEUE2_ITEM_TYPE_EVENT);
2295         GST_QUEUE2_MUTEX_UNLOCK (queue);
2296       } else {
2297         /* non-serialized events are passed upstream. */
2298         ret = gst_pad_push_event (queue->srcpad, event);
2299       }
2300       break;
2301   }
2302   return ret;
2303
2304   /* ERRORS */
2305 out_flushing:
2306   {
2307     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2308     GST_QUEUE2_MUTEX_UNLOCK (queue);
2309     gst_event_unref (event);
2310     return FALSE;
2311   }
2312 out_eos:
2313   {
2314     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2315     GST_QUEUE2_MUTEX_UNLOCK (queue);
2316     gst_event_unref (event);
2317     return FALSE;
2318   }
2319 }
2320
2321 static gboolean
2322 gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
2323     GstQuery * query)
2324 {
2325   GstQueue2 *queue;
2326   gboolean res;
2327
2328   queue = GST_QUEUE2 (parent);
2329
2330   switch (GST_QUERY_TYPE (query)) {
2331     default:
2332       if (GST_QUERY_IS_SERIALIZED (query)) {
2333         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received query %p", query);
2334         /* serialized events go in the queue. We need to be certain that we
2335          * don't cause deadlocks waiting for the query return value. We check if
2336          * the queue is empty (nothing is blocking downstream and the query can
2337          * be pushed for sure) or we are not buffering. If we are buffering,
2338          * the pipeline waits to unblock downstream until our queue fills up
2339          * completely, which can not happen if we block on the query..
2340          * Therefore we only potentially block when we are not buffering. */
2341         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2342         if (QUEUE_IS_USING_QUEUE (queue) && !queue->is_buffering) {
2343           gst_queue2_locked_enqueue (queue, query, GST_QUEUE2_ITEM_TYPE_QUERY);
2344
2345           STATUS (queue, queue->sinkpad, "wait for QUERY");
2346           g_cond_wait (&queue->query_handled, &queue->qlock);
2347           if (queue->sinkresult != GST_FLOW_OK)
2348             goto out_flushing;
2349           res = queue->last_query;
2350         } else {
2351           GST_DEBUG_OBJECT (queue,
2352               "refusing query, we are not using the queue");
2353           res = FALSE;
2354         }
2355         GST_QUEUE2_MUTEX_UNLOCK (queue);
2356       } else {
2357         res = gst_pad_query_default (pad, parent, query);
2358       }
2359       break;
2360   }
2361   return res;
2362
2363   /* ERRORS */
2364 out_flushing:
2365   {
2366     GST_DEBUG_OBJECT (queue, "refusing query, we are flushing");
2367     GST_QUEUE2_MUTEX_UNLOCK (queue);
2368     return FALSE;
2369   }
2370 }
2371
2372 static gboolean
2373 gst_queue2_is_empty (GstQueue2 * queue)
2374 {
2375   /* never empty on EOS */
2376   if (queue->is_eos)
2377     return FALSE;
2378
2379   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2380     return queue->current->writing_pos <= queue->current->max_reading_pos;
2381   } else {
2382     if (queue->queue.length == 0)
2383       return TRUE;
2384   }
2385
2386   return FALSE;
2387 }
2388
2389 static gboolean
2390 gst_queue2_is_filled (GstQueue2 * queue)
2391 {
2392   gboolean res;
2393
2394   /* always filled on EOS */
2395   if (queue->is_eos)
2396     return TRUE;
2397
2398 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2399     (queue->cur_level.format) >= ((alt_max) ? \
2400       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2401
2402   /* if using a ring buffer we're filled if all ring buffer space is used
2403    * _by the current range_ */
2404   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2405     guint64 rb_size = queue->ring_buffer_max_size;
2406     GST_DEBUG_OBJECT (queue,
2407         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2408         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2409     return CHECK_FILLED (bytes, rb_size);
2410   }
2411
2412   /* if using file, we're never filled if we don't have EOS */
2413   if (QUEUE_IS_USING_TEMP_FILE (queue))
2414     return FALSE;
2415
2416   /* we are never filled when we have no buffers at all */
2417   if (queue->cur_level.buffers == 0)
2418     return FALSE;
2419
2420   /* we are filled if one of the current levels exceeds the max */
2421   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2422       || CHECK_FILLED (time, 0);
2423
2424   /* if we need to, use the rate estimate to check against the max time we are
2425    * allowed to queue */
2426   if (queue->use_rate_estimate)
2427     res |= CHECK_FILLED (rate_time, 0);
2428
2429 #undef CHECK_FILLED
2430   return res;
2431 }
2432
2433 static GstFlowReturn
2434 gst_queue2_chain_buffer_or_buffer_list (GstQueue2 * queue,
2435     GstMiniObject * item, GstQueue2ItemType item_type)
2436 {
2437   /* we have to lock the queue since we span threads */
2438   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2439   /* when we received EOS, we refuse more data */
2440   if (queue->is_eos)
2441     goto out_eos;
2442   /* when we received unexpected from downstream, refuse more buffers */
2443   if (queue->unexpected)
2444     goto out_unexpected;
2445
2446   /* while we didn't receive the newsegment, we're seeking and we skip data */
2447   if (queue->seeking)
2448     goto out_seeking;
2449
2450   if (!gst_queue2_wait_free_space (queue))
2451     goto out_flushing;
2452
2453   /* put buffer in queue now */
2454   gst_queue2_locked_enqueue (queue, item, item_type);
2455   GST_QUEUE2_MUTEX_UNLOCK (queue);
2456
2457   return GST_FLOW_OK;
2458
2459   /* special conditions */
2460 out_flushing:
2461   {
2462     GstFlowReturn ret = queue->sinkresult;
2463
2464     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2465         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2466     GST_QUEUE2_MUTEX_UNLOCK (queue);
2467     gst_mini_object_unref (item);
2468
2469     return ret;
2470   }
2471 out_eos:
2472   {
2473     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2474     GST_QUEUE2_MUTEX_UNLOCK (queue);
2475     gst_mini_object_unref (item);
2476
2477     return GST_FLOW_EOS;
2478   }
2479 out_seeking:
2480   {
2481     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are seeking");
2482     GST_QUEUE2_MUTEX_UNLOCK (queue);
2483     gst_mini_object_unref (item);
2484
2485     return GST_FLOW_OK;
2486   }
2487 out_unexpected:
2488   {
2489     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2490     GST_QUEUE2_MUTEX_UNLOCK (queue);
2491     gst_mini_object_unref (item);
2492
2493     return GST_FLOW_EOS;
2494   }
2495 }
2496
2497 static GstFlowReturn
2498 gst_queue2_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2499 {
2500   GstQueue2 *queue;
2501
2502   queue = GST_QUEUE2 (parent);
2503
2504   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of "
2505       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
2506       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
2507       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2508       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2509
2510   return gst_queue2_chain_buffer_or_buffer_list (queue,
2511       GST_MINI_OBJECT_CAST (buffer), GST_QUEUE2_ITEM_TYPE_BUFFER);
2512 }
2513
2514 static GstFlowReturn
2515 gst_queue2_chain_list (GstPad * pad, GstObject * parent,
2516     GstBufferList * buffer_list)
2517 {
2518   GstQueue2 *queue;
2519
2520   queue = GST_QUEUE2 (parent);
2521
2522   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2523       "received buffer list %p", buffer_list);
2524
2525   return gst_queue2_chain_buffer_or_buffer_list (queue,
2526       GST_MINI_OBJECT_CAST (buffer_list), GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2527 }
2528
2529 static GstMiniObject *
2530 gst_queue2_dequeue_on_eos (GstQueue2 * queue, GstQueue2ItemType * item_type)
2531 {
2532   GstMiniObject *data;
2533
2534   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
2535
2536   /* stop pushing buffers, we dequeue all items until we see an item that we
2537    * can push again, which is EOS or SEGMENT. If there is nothing in the
2538    * queue we can push, we set a flag to make the sinkpad refuse more
2539    * buffers with an EOS return value until we receive something
2540    * pushable again or we get flushed. */
2541   while ((data = gst_queue2_locked_dequeue (queue, item_type))) {
2542     if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2543       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2544           "dropping EOS buffer %p", data);
2545       gst_buffer_unref (GST_BUFFER_CAST (data));
2546     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2547       GstEvent *event = GST_EVENT_CAST (data);
2548       GstEventType type = GST_EVENT_TYPE (event);
2549
2550       if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
2551         /* we found a pushable item in the queue, push it out */
2552         GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2553             "pushing pushable event %s after EOS", GST_EVENT_TYPE_NAME (event));
2554         return data;
2555       }
2556       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2557           "dropping EOS event %p", event);
2558       gst_event_unref (event);
2559     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2560       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2561           "dropping EOS buffer list %p", data);
2562       gst_buffer_list_unref (GST_BUFFER_LIST_CAST (data));
2563     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2564       queue->last_query = FALSE;
2565       g_cond_signal (&queue->query_handled);
2566       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "dropping EOS query %p", data);
2567     }
2568   }
2569   /* no more items in the queue. Set the unexpected flag so that upstream
2570    * make us refuse any more buffers on the sinkpad. Since we will still
2571    * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
2572    * task function does not shut down. */
2573   queue->unexpected = TRUE;
2574   return NULL;
2575 }
2576
2577 /* dequeue an item from the queue an push it downstream. This functions returns
2578  * the result of the push. */
2579 static GstFlowReturn
2580 gst_queue2_push_one (GstQueue2 * queue)
2581 {
2582   GstFlowReturn result = queue->srcresult;
2583   GstMiniObject *data;
2584   GstQueue2ItemType item_type;
2585
2586   data = gst_queue2_locked_dequeue (queue, &item_type);
2587   if (data == NULL)
2588     goto no_item;
2589
2590 next:
2591   GST_QUEUE2_MUTEX_UNLOCK (queue);
2592
2593   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2594     GstBuffer *buffer;
2595
2596     buffer = GST_BUFFER_CAST (data);
2597
2598     result = gst_pad_push (queue->srcpad, buffer);
2599
2600     /* need to check for srcresult here as well */
2601     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2602     if (result == GST_FLOW_EOS) {
2603       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2604       if (data != NULL)
2605         goto next;
2606       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2607        * to the caller so that the task function does not shut down */
2608       result = GST_FLOW_OK;
2609     }
2610   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2611     GstEvent *event = GST_EVENT_CAST (data);
2612     GstEventType type = GST_EVENT_TYPE (event);
2613
2614     gst_pad_push_event (queue->srcpad, event);
2615
2616     /* if we're EOS, return EOS so that the task pauses. */
2617     if (type == GST_EVENT_EOS) {
2618       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2619           "pushed EOS event %p, return EOS", event);
2620       result = GST_FLOW_EOS;
2621     }
2622
2623     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2624   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2625     GstBufferList *buffer_list;
2626
2627     buffer_list = GST_BUFFER_LIST_CAST (data);
2628
2629     result = gst_pad_push_list (queue->srcpad, buffer_list);
2630
2631     /* need to check for srcresult here as well */
2632     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2633     if (result == GST_FLOW_EOS) {
2634       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2635       if (data != NULL)
2636         goto next;
2637       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2638        * to the caller so that the task function does not shut down */
2639       result = GST_FLOW_OK;
2640     }
2641   } else if (item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2642     GstQuery *query = GST_QUERY_CAST (data);
2643
2644     queue->last_query = gst_pad_peer_query (queue->srcpad, query);
2645     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2646         "did query %p, return %d", query, queue->last_query);
2647     g_cond_signal (&queue->query_handled);
2648     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2649     result = GST_FLOW_OK;
2650   }
2651   return result;
2652
2653   /* ERRORS */
2654 no_item:
2655   {
2656     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2657         "exit because we have no item in the queue");
2658     return GST_FLOW_ERROR;
2659   }
2660 out_flushing:
2661   {
2662     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2663     return GST_FLOW_FLUSHING;
2664   }
2665 }
2666
2667 /* called repeatedly with @pad as the source pad. This function should push out
2668  * data to the peer element. */
2669 static void
2670 gst_queue2_loop (GstPad * pad)
2671 {
2672   GstQueue2 *queue;
2673   GstFlowReturn ret;
2674
2675   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2676
2677   /* have to lock for thread-safety */
2678   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2679
2680   if (gst_queue2_is_empty (queue)) {
2681     gboolean started;
2682
2683     /* pause the timer while we wait. The fact that we are waiting does not mean
2684      * the byterate on the output pad is lower */
2685     if ((started = queue->out_timer_started))
2686       g_timer_stop (queue->out_timer);
2687
2688     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2689         "queue is empty, waiting for new data");
2690     do {
2691       /* Wait for data to be available, we could be unlocked because of a flush. */
2692       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2693     }
2694     while (gst_queue2_is_empty (queue));
2695
2696     /* and continue if we were running before */
2697     if (started)
2698       g_timer_continue (queue->out_timer);
2699   }
2700   ret = gst_queue2_push_one (queue);
2701   queue->srcresult = ret;
2702   queue->sinkresult = ret;
2703   if (ret != GST_FLOW_OK)
2704     goto out_flushing;
2705
2706   GST_QUEUE2_MUTEX_UNLOCK (queue);
2707
2708   return;
2709
2710   /* ERRORS */
2711 out_flushing:
2712   {
2713     gboolean eos = queue->is_eos;
2714     GstFlowReturn ret = queue->srcresult;
2715
2716     gst_pad_pause_task (queue->srcpad);
2717     GST_QUEUE2_MUTEX_UNLOCK (queue);
2718     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2719         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2720     /* let app know about us giving up if upstream is not expected to do so */
2721     /* EOS is already taken care of elsewhere */
2722     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
2723       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2724           (_("Internal data flow error.")),
2725           ("streaming task paused, reason %s (%d)",
2726               gst_flow_get_name (ret), ret));
2727       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2728     }
2729     return;
2730   }
2731 }
2732
2733 static gboolean
2734 gst_queue2_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2735 {
2736   gboolean res = TRUE;
2737   GstQueue2 *queue = GST_QUEUE2 (parent);
2738
2739 #ifndef GST_DISABLE_GST_DEBUG
2740   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
2741       event, GST_EVENT_TYPE_NAME (event));
2742 #endif
2743
2744   switch (GST_EVENT_TYPE (event)) {
2745     case GST_EVENT_FLUSH_START:
2746       if (QUEUE_IS_USING_QUEUE (queue)) {
2747         /* just forward upstream */
2748         res = gst_pad_push_event (queue->sinkpad, event);
2749       } else {
2750         /* now unblock the getrange function */
2751         GST_QUEUE2_MUTEX_LOCK (queue);
2752         GST_DEBUG_OBJECT (queue, "flushing");
2753         queue->srcresult = GST_FLOW_FLUSHING;
2754         GST_QUEUE2_SIGNAL_ADD (queue);
2755         GST_QUEUE2_MUTEX_UNLOCK (queue);
2756
2757         /* when using a temp file, we eat the event */
2758         res = TRUE;
2759         gst_event_unref (event);
2760       }
2761       break;
2762     case GST_EVENT_FLUSH_STOP:
2763       if (QUEUE_IS_USING_QUEUE (queue)) {
2764         /* just forward upstream */
2765         res = gst_pad_push_event (queue->sinkpad, event);
2766       } else {
2767         /* now unblock the getrange function */
2768         GST_QUEUE2_MUTEX_LOCK (queue);
2769         queue->srcresult = GST_FLOW_OK;
2770         GST_QUEUE2_MUTEX_UNLOCK (queue);
2771
2772         /* when using a temp file, we eat the event */
2773         res = TRUE;
2774         gst_event_unref (event);
2775       }
2776       break;
2777     case GST_EVENT_RECONFIGURE:
2778       GST_QUEUE2_MUTEX_LOCK (queue);
2779       /* assume downstream is linked now and try to push again */
2780       if (queue->srcresult == GST_FLOW_NOT_LINKED) {
2781         queue->srcresult = GST_FLOW_OK;
2782         queue->sinkresult = GST_FLOW_OK;
2783         if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
2784           gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad,
2785               NULL);
2786         }
2787       }
2788       GST_QUEUE2_MUTEX_UNLOCK (queue);
2789
2790       res = gst_pad_push_event (queue->sinkpad, event);
2791       break;
2792     default:
2793       res = gst_pad_push_event (queue->sinkpad, event);
2794       break;
2795   }
2796
2797   return res;
2798 }
2799
2800 static gboolean
2801 gst_queue2_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2802 {
2803   GstQueue2 *queue;
2804
2805   queue = GST_QUEUE2 (parent);
2806
2807   switch (GST_QUERY_TYPE (query)) {
2808     case GST_QUERY_POSITION:
2809     {
2810       gint64 peer_pos;
2811       GstFormat format;
2812
2813       if (!gst_pad_peer_query (queue->sinkpad, query))
2814         goto peer_failed;
2815
2816       /* get peer position */
2817       gst_query_parse_position (query, &format, &peer_pos);
2818
2819       /* FIXME: this code assumes that there's no discont in the queue */
2820       switch (format) {
2821         case GST_FORMAT_BYTES:
2822           peer_pos -= queue->cur_level.bytes;
2823           break;
2824         case GST_FORMAT_TIME:
2825           peer_pos -= queue->cur_level.time;
2826           break;
2827         default:
2828           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
2829               "know how to adjust value", gst_format_get_name (format));
2830           return FALSE;
2831       }
2832       /* set updated position */
2833       gst_query_set_position (query, format, peer_pos);
2834       break;
2835     }
2836     case GST_QUERY_DURATION:
2837     {
2838       GST_DEBUG_OBJECT (queue, "doing peer query");
2839
2840       if (!gst_pad_peer_query (queue->sinkpad, query))
2841         goto peer_failed;
2842
2843       GST_DEBUG_OBJECT (queue, "peer query success");
2844       break;
2845     }
2846     case GST_QUERY_BUFFERING:
2847     {
2848       gint percent;
2849       gboolean is_buffering;
2850       GstBufferingMode mode;
2851       gint avg_in, avg_out;
2852       gint64 buffering_left;
2853
2854       GST_DEBUG_OBJECT (queue, "query buffering");
2855
2856       get_buffering_percent (queue, &is_buffering, &percent);
2857       gst_query_set_buffering_percent (query, is_buffering, percent);
2858
2859       get_buffering_stats (queue, percent, &mode, &avg_in, &avg_out,
2860           &buffering_left);
2861       gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
2862           buffering_left);
2863
2864       if (!QUEUE_IS_USING_QUEUE (queue)) {
2865         /* add ranges for download and ringbuffer buffering */
2866         GstFormat format;
2867         gint64 start, stop, range_start, range_stop;
2868         guint64 writing_pos;
2869         gint64 estimated_total;
2870         gint64 duration;
2871         gboolean peer_res, is_eos;
2872         GstQueue2Range *queued_ranges;
2873
2874         /* we need a current download region */
2875         if (queue->current == NULL)
2876           return FALSE;
2877
2878         writing_pos = queue->current->writing_pos;
2879         is_eos = queue->is_eos;
2880
2881         if (is_eos) {
2882           /* we're EOS, we know the duration in bytes now */
2883           peer_res = TRUE;
2884           duration = writing_pos;
2885         } else {
2886           /* get duration of upstream in bytes */
2887           peer_res = gst_pad_peer_query_duration (queue->sinkpad,
2888               GST_FORMAT_BYTES, &duration);
2889         }
2890
2891         GST_DEBUG_OBJECT (queue, "percent %d, duration %" G_GINT64_FORMAT
2892             ", writing %" G_GINT64_FORMAT, percent, duration, writing_pos);
2893
2894         /* calculate remaining and total download time */
2895         if (peer_res && avg_in > 0.0)
2896           estimated_total = ((duration - writing_pos) * 1000) / avg_in;
2897         else
2898           estimated_total = -1;
2899
2900         GST_DEBUG_OBJECT (queue, "estimated-total %" G_GINT64_FORMAT,
2901             estimated_total);
2902
2903         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
2904
2905         switch (format) {
2906           case GST_FORMAT_PERCENT:
2907             /* we need duration */
2908             if (!peer_res)
2909               goto peer_failed;
2910
2911             start = 0;
2912             /* get our available data relative to the duration */
2913             if (duration != -1)
2914               stop =
2915                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX, writing_pos,
2916                   duration);
2917             else
2918               stop = -1;
2919             break;
2920           case GST_FORMAT_BYTES:
2921             start = 0;
2922             stop = writing_pos;
2923             break;
2924           default:
2925             start = -1;
2926             stop = -1;
2927             break;
2928         }
2929
2930         /* fill out the buffered ranges */
2931         for (queued_ranges = queue->ranges; queued_ranges;
2932             queued_ranges = queued_ranges->next) {
2933           switch (format) {
2934             case GST_FORMAT_PERCENT:
2935               if (duration == -1) {
2936                 range_start = 0;
2937                 range_stop = 0;
2938                 break;
2939               }
2940               range_start =
2941                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
2942                   queued_ranges->offset, duration);
2943               range_stop =
2944                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
2945                   queued_ranges->writing_pos, duration);
2946               break;
2947             case GST_FORMAT_BYTES:
2948               range_start = queued_ranges->offset;
2949               range_stop = queued_ranges->writing_pos;
2950               break;
2951             default:
2952               range_start = -1;
2953               range_stop = -1;
2954               break;
2955           }
2956           if (range_start == range_stop)
2957             continue;
2958           GST_DEBUG_OBJECT (queue,
2959               "range starting at %" G_GINT64_FORMAT " and finishing at %"
2960               G_GINT64_FORMAT, range_start, range_stop);
2961           gst_query_add_buffering_range (query, range_start, range_stop);
2962         }
2963
2964         gst_query_set_buffering_range (query, format, start, stop,
2965             estimated_total);
2966       }
2967       break;
2968     }
2969     case GST_QUERY_SCHEDULING:
2970     {
2971       gboolean pull_mode;
2972       GstSchedulingFlags flags = 0;
2973
2974       if (!gst_pad_peer_query (queue->sinkpad, query))
2975         goto peer_failed;
2976
2977       gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
2978
2979       /* we can operate in pull mode when we are using a tempfile */
2980       pull_mode = !QUEUE_IS_USING_QUEUE (queue);
2981
2982       if (pull_mode)
2983         flags |= GST_SCHEDULING_FLAG_SEEKABLE;
2984       gst_query_set_scheduling (query, flags, 0, -1, 0);
2985       if (pull_mode)
2986         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
2987       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
2988       break;
2989     }
2990     default:
2991       /* peer handled other queries */
2992       if (!gst_pad_query_default (pad, parent, query))
2993         goto peer_failed;
2994       break;
2995   }
2996
2997   return TRUE;
2998
2999   /* ERRORS */
3000 peer_failed:
3001   {
3002     GST_DEBUG_OBJECT (queue, "failed peer query");
3003     return FALSE;
3004   }
3005 }
3006
3007 static gboolean
3008 gst_queue2_handle_query (GstElement * element, GstQuery * query)
3009 {
3010   GstQueue2 *queue = GST_QUEUE2 (element);
3011
3012   /* simply forward to the srcpad query function */
3013   return gst_queue2_handle_src_query (queue->srcpad, GST_OBJECT_CAST (element),
3014       query);
3015 }
3016
3017 static void
3018 gst_queue2_update_upstream_size (GstQueue2 * queue)
3019 {
3020   gint64 upstream_size = -1;
3021
3022   if (gst_pad_peer_query_duration (queue->sinkpad, GST_FORMAT_BYTES,
3023           &upstream_size)) {
3024     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
3025     queue->upstream_size = upstream_size;
3026   }
3027 }
3028
3029 static GstFlowReturn
3030 gst_queue2_get_range (GstPad * pad, GstObject * parent, guint64 offset,
3031     guint length, GstBuffer ** buffer)
3032 {
3033   GstQueue2 *queue;
3034   GstFlowReturn ret;
3035
3036   queue = GST_QUEUE2_CAST (parent);
3037
3038   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
3039   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
3040   offset = (offset == -1) ? queue->current->reading_pos : offset;
3041
3042   GST_DEBUG_OBJECT (queue,
3043       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
3044
3045   /* catch any reads beyond the size of the file here to make sure queue2
3046    * doesn't send seek events beyond the size of the file upstream, since
3047    * that would confuse elements such as souphttpsrc and/or http servers.
3048    * Demuxers often just loop until EOS at the end of the file to figure out
3049    * when they've read all the end-headers or index chunks. */
3050   if (G_UNLIKELY (offset >= queue->upstream_size)) {
3051     gst_queue2_update_upstream_size (queue);
3052     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
3053       goto out_unexpected;
3054   }
3055
3056   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
3057     gst_queue2_update_upstream_size (queue);
3058     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
3059       length = queue->upstream_size - offset;
3060       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
3061     }
3062   }
3063
3064   /* FIXME - function will block when the range is not yet available */
3065   ret = gst_queue2_create_read (queue, offset, length, buffer);
3066   GST_QUEUE2_MUTEX_UNLOCK (queue);
3067
3068   return ret;
3069
3070   /* ERRORS */
3071 out_flushing:
3072   {
3073     ret = queue->srcresult;
3074
3075     GST_DEBUG_OBJECT (queue, "we are flushing");
3076     GST_QUEUE2_MUTEX_UNLOCK (queue);
3077     return ret;
3078   }
3079 out_unexpected:
3080   {
3081     GST_DEBUG_OBJECT (queue, "read beyond end of file");
3082     GST_QUEUE2_MUTEX_UNLOCK (queue);
3083     return GST_FLOW_EOS;
3084   }
3085 }
3086
3087 /* sink currently only operates in push mode */
3088 static gboolean
3089 gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
3090     GstPadMode mode, gboolean active)
3091 {
3092   gboolean result;
3093   GstQueue2 *queue;
3094
3095   queue = GST_QUEUE2 (parent);
3096
3097   switch (mode) {
3098     case GST_PAD_MODE_PUSH:
3099       if (active) {
3100         GST_QUEUE2_MUTEX_LOCK (queue);
3101         GST_DEBUG_OBJECT (queue, "activating push mode");
3102         queue->srcresult = GST_FLOW_OK;
3103         queue->sinkresult = GST_FLOW_OK;
3104         queue->is_eos = FALSE;
3105         queue->unexpected = FALSE;
3106         reset_rate_timer (queue);
3107         GST_QUEUE2_MUTEX_UNLOCK (queue);
3108       } else {
3109         /* unblock chain function */
3110         GST_QUEUE2_MUTEX_LOCK (queue);
3111         GST_DEBUG_OBJECT (queue, "deactivating push mode");
3112         queue->srcresult = GST_FLOW_FLUSHING;
3113         queue->sinkresult = GST_FLOW_FLUSHING;
3114         GST_QUEUE2_SIGNAL_DEL (queue);
3115         /* Unblock query handler */
3116         queue->last_query = FALSE;
3117         g_cond_signal (&queue->query_handled);
3118         GST_QUEUE2_MUTEX_UNLOCK (queue);
3119
3120         /* wait until it is unblocked and clean up */
3121         GST_PAD_STREAM_LOCK (pad);
3122         GST_QUEUE2_MUTEX_LOCK (queue);
3123         gst_queue2_locked_flush (queue, TRUE, FALSE);
3124         GST_QUEUE2_MUTEX_UNLOCK (queue);
3125         GST_PAD_STREAM_UNLOCK (pad);
3126       }
3127       result = TRUE;
3128       break;
3129     default:
3130       result = FALSE;
3131       break;
3132   }
3133   return result;
3134 }
3135
3136 /* src operating in push mode, we start a task on the source pad that pushes out
3137  * buffers from the queue */
3138 static gboolean
3139 gst_queue2_src_activate_push (GstPad * pad, GstObject * parent, gboolean active)
3140 {
3141   gboolean result = FALSE;
3142   GstQueue2 *queue;
3143
3144   queue = GST_QUEUE2 (parent);
3145
3146   if (active) {
3147     GST_QUEUE2_MUTEX_LOCK (queue);
3148     GST_DEBUG_OBJECT (queue, "activating push mode");
3149     queue->srcresult = GST_FLOW_OK;
3150     queue->sinkresult = GST_FLOW_OK;
3151     queue->is_eos = FALSE;
3152     queue->unexpected = FALSE;
3153     result =
3154         gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad, NULL);
3155     GST_QUEUE2_MUTEX_UNLOCK (queue);
3156   } else {
3157     /* unblock loop function */
3158     GST_QUEUE2_MUTEX_LOCK (queue);
3159     GST_DEBUG_OBJECT (queue, "deactivating push mode");
3160     queue->srcresult = GST_FLOW_FLUSHING;
3161     queue->sinkresult = GST_FLOW_FLUSHING;
3162     /* the item add signal will unblock */
3163     GST_QUEUE2_SIGNAL_ADD (queue);
3164     GST_QUEUE2_MUTEX_UNLOCK (queue);
3165
3166     /* step 2, make sure streaming finishes */
3167     result = gst_pad_stop_task (pad);
3168   }
3169
3170   return result;
3171 }
3172
3173 /* pull mode, downstream will call our getrange function */
3174 static gboolean
3175 gst_queue2_src_activate_pull (GstPad * pad, GstObject * parent, gboolean active)
3176 {
3177   gboolean result;
3178   GstQueue2 *queue;
3179
3180   queue = GST_QUEUE2 (parent);
3181
3182   if (active) {
3183     GST_QUEUE2_MUTEX_LOCK (queue);
3184     if (!QUEUE_IS_USING_QUEUE (queue)) {
3185       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3186         /* open the temp file now */
3187         result = gst_queue2_open_temp_location_file (queue);
3188       } else if (!queue->ring_buffer) {
3189         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
3190         result = ! !queue->ring_buffer;
3191       } else {
3192         result = TRUE;
3193       }
3194
3195       GST_DEBUG_OBJECT (queue, "activating pull mode");
3196       init_ranges (queue);
3197       queue->srcresult = GST_FLOW_OK;
3198       queue->sinkresult = GST_FLOW_OK;
3199       queue->is_eos = FALSE;
3200       queue->unexpected = FALSE;
3201       queue->upstream_size = 0;
3202     } else {
3203       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
3204       /* this is not allowed, we cannot operate in pull mode without a temp
3205        * file. */
3206       queue->srcresult = GST_FLOW_FLUSHING;
3207       queue->sinkresult = GST_FLOW_FLUSHING;
3208       result = FALSE;
3209     }
3210     GST_QUEUE2_MUTEX_UNLOCK (queue);
3211   } else {
3212     GST_QUEUE2_MUTEX_LOCK (queue);
3213     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
3214     queue->srcresult = GST_FLOW_FLUSHING;
3215     queue->sinkresult = GST_FLOW_FLUSHING;
3216     /* this will unlock getrange */
3217     GST_QUEUE2_SIGNAL_ADD (queue);
3218     result = TRUE;
3219     GST_QUEUE2_MUTEX_UNLOCK (queue);
3220   }
3221
3222   return result;
3223 }
3224
3225 static gboolean
3226 gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
3227     gboolean active)
3228 {
3229   gboolean res;
3230
3231   switch (mode) {
3232     case GST_PAD_MODE_PULL:
3233       res = gst_queue2_src_activate_pull (pad, parent, active);
3234       break;
3235     case GST_PAD_MODE_PUSH:
3236       res = gst_queue2_src_activate_push (pad, parent, active);
3237       break;
3238     default:
3239       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
3240       res = FALSE;
3241       break;
3242   }
3243   return res;
3244 }
3245
3246 static GstStateChangeReturn
3247 gst_queue2_change_state (GstElement * element, GstStateChange transition)
3248 {
3249   GstQueue2 *queue;
3250   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3251
3252   queue = GST_QUEUE2 (element);
3253
3254   switch (transition) {
3255     case GST_STATE_CHANGE_NULL_TO_READY:
3256       break;
3257     case GST_STATE_CHANGE_READY_TO_PAUSED:
3258       GST_QUEUE2_MUTEX_LOCK (queue);
3259       if (!QUEUE_IS_USING_QUEUE (queue)) {
3260         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3261           if (!gst_queue2_open_temp_location_file (queue))
3262             ret = GST_STATE_CHANGE_FAILURE;
3263         } else {
3264           if (queue->ring_buffer) {
3265             g_free (queue->ring_buffer);
3266             queue->ring_buffer = NULL;
3267           }
3268           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
3269             ret = GST_STATE_CHANGE_FAILURE;
3270         }
3271         init_ranges (queue);
3272       }
3273       queue->segment_event_received = FALSE;
3274       queue->starting_segment = NULL;
3275       gst_event_replace (&queue->stream_start_event, NULL);
3276       GST_QUEUE2_MUTEX_UNLOCK (queue);
3277       break;
3278     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3279       break;
3280     default:
3281       break;
3282   }
3283
3284   if (ret == GST_STATE_CHANGE_FAILURE)
3285     return ret;
3286
3287   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3288
3289   if (ret == GST_STATE_CHANGE_FAILURE)
3290     return ret;
3291
3292   switch (transition) {
3293     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3294       break;
3295     case GST_STATE_CHANGE_PAUSED_TO_READY:
3296       GST_QUEUE2_MUTEX_LOCK (queue);
3297       if (!QUEUE_IS_USING_QUEUE (queue)) {
3298         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3299           gst_queue2_close_temp_location_file (queue);
3300         } else if (queue->ring_buffer) {
3301           g_free (queue->ring_buffer);
3302           queue->ring_buffer = NULL;
3303         }
3304         clean_ranges (queue);
3305       }
3306       if (queue->starting_segment != NULL) {
3307         gst_event_unref (queue->starting_segment);
3308         queue->starting_segment = NULL;
3309       }
3310       gst_event_replace (&queue->stream_start_event, NULL);
3311       GST_QUEUE2_MUTEX_UNLOCK (queue);
3312       break;
3313     case GST_STATE_CHANGE_READY_TO_NULL:
3314       break;
3315     default:
3316       break;
3317   }
3318
3319   return ret;
3320 }
3321
3322 /* changing the capacity of the queue must wake up
3323  * the _chain function, it might have more room now
3324  * to store the buffer/event in the queue */
3325 #define QUEUE_CAPACITY_CHANGE(q) \
3326   GST_QUEUE2_SIGNAL_DEL (queue); \
3327   if (queue->use_buffering)      \
3328     update_buffering (queue);
3329
3330 /* Changing the minimum required fill level must
3331  * wake up the _loop function as it might now
3332  * be able to preceed.
3333  */
3334 #define QUEUE_THRESHOLD_CHANGE(q)\
3335   GST_QUEUE2_SIGNAL_ADD (queue);
3336
3337 static void
3338 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
3339 {
3340   GstState state;
3341
3342   /* the element must be stopped in order to do this */
3343   GST_OBJECT_LOCK (queue);
3344   state = GST_STATE (queue);
3345   if (state != GST_STATE_READY && state != GST_STATE_NULL)
3346     goto wrong_state;
3347   GST_OBJECT_UNLOCK (queue);
3348
3349   /* set new location */
3350   g_free (queue->temp_template);
3351   queue->temp_template = g_strdup (template);
3352
3353   return;
3354
3355 /* ERROR */
3356 wrong_state:
3357   {
3358     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
3359     GST_OBJECT_UNLOCK (queue);
3360   }
3361 }
3362
3363 static void
3364 gst_queue2_set_property (GObject * object,
3365     guint prop_id, const GValue * value, GParamSpec * pspec)
3366 {
3367   GstQueue2 *queue = GST_QUEUE2 (object);
3368
3369   /* someone could change levels here, and since this
3370    * affects the get/put funcs, we need to lock for safety. */
3371   GST_QUEUE2_MUTEX_LOCK (queue);
3372
3373   switch (prop_id) {
3374     case PROP_MAX_SIZE_BYTES:
3375       queue->max_level.bytes = g_value_get_uint (value);
3376       QUEUE_CAPACITY_CHANGE (queue);
3377       break;
3378     case PROP_MAX_SIZE_BUFFERS:
3379       queue->max_level.buffers = g_value_get_uint (value);
3380       QUEUE_CAPACITY_CHANGE (queue);
3381       break;
3382     case PROP_MAX_SIZE_TIME:
3383       queue->max_level.time = g_value_get_uint64 (value);
3384       /* set rate_time to the same value. We use an extra field in the level
3385        * structure so that we can easily access and compare it */
3386       queue->max_level.rate_time = queue->max_level.time;
3387       QUEUE_CAPACITY_CHANGE (queue);
3388       break;
3389     case PROP_USE_BUFFERING:
3390       queue->use_buffering = g_value_get_boolean (value);
3391       if (!queue->use_buffering && queue->is_buffering) {
3392         GstMessage *msg = gst_message_new_buffering (GST_OBJECT_CAST (queue),
3393             100);
3394
3395         GST_DEBUG_OBJECT (queue, "Disabled buffering while buffering, "
3396             "posting 100%% message");
3397         queue->is_buffering = FALSE;
3398         gst_element_post_message (GST_ELEMENT_CAST (queue), msg);
3399       }
3400
3401       if (queue->use_buffering) {
3402         queue->is_buffering = TRUE;
3403         update_buffering (queue);
3404       }
3405       break;
3406     case PROP_USE_RATE_ESTIMATE:
3407       queue->use_rate_estimate = g_value_get_boolean (value);
3408       break;
3409     case PROP_LOW_PERCENT:
3410       queue->low_percent = g_value_get_int (value);
3411       break;
3412     case PROP_HIGH_PERCENT:
3413       queue->high_percent = g_value_get_int (value);
3414       break;
3415     case PROP_TEMP_TEMPLATE:
3416       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3417       break;
3418     case PROP_TEMP_REMOVE:
3419       queue->temp_remove = g_value_get_boolean (value);
3420       break;
3421     case PROP_RING_BUFFER_MAX_SIZE:
3422       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3423       break;
3424     default:
3425       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3426       break;
3427   }
3428
3429   GST_QUEUE2_MUTEX_UNLOCK (queue);
3430 }
3431
3432 static void
3433 gst_queue2_get_property (GObject * object,
3434     guint prop_id, GValue * value, GParamSpec * pspec)
3435 {
3436   GstQueue2 *queue = GST_QUEUE2 (object);
3437
3438   GST_QUEUE2_MUTEX_LOCK (queue);
3439
3440   switch (prop_id) {
3441     case PROP_CUR_LEVEL_BYTES:
3442       g_value_set_uint (value, queue->cur_level.bytes);
3443       break;
3444     case PROP_CUR_LEVEL_BUFFERS:
3445       g_value_set_uint (value, queue->cur_level.buffers);
3446       break;
3447     case PROP_CUR_LEVEL_TIME:
3448       g_value_set_uint64 (value, queue->cur_level.time);
3449       break;
3450     case PROP_MAX_SIZE_BYTES:
3451       g_value_set_uint (value, queue->max_level.bytes);
3452       break;
3453     case PROP_MAX_SIZE_BUFFERS:
3454       g_value_set_uint (value, queue->max_level.buffers);
3455       break;
3456     case PROP_MAX_SIZE_TIME:
3457       g_value_set_uint64 (value, queue->max_level.time);
3458       break;
3459     case PROP_USE_BUFFERING:
3460       g_value_set_boolean (value, queue->use_buffering);
3461       break;
3462     case PROP_USE_RATE_ESTIMATE:
3463       g_value_set_boolean (value, queue->use_rate_estimate);
3464       break;
3465     case PROP_LOW_PERCENT:
3466       g_value_set_int (value, queue->low_percent);
3467       break;
3468     case PROP_HIGH_PERCENT:
3469       g_value_set_int (value, queue->high_percent);
3470       break;
3471     case PROP_TEMP_TEMPLATE:
3472       g_value_set_string (value, queue->temp_template);
3473       break;
3474     case PROP_TEMP_LOCATION:
3475       g_value_set_string (value, queue->temp_location);
3476       break;
3477     case PROP_TEMP_REMOVE:
3478       g_value_set_boolean (value, queue->temp_remove);
3479       break;
3480     case PROP_RING_BUFFER_MAX_SIZE:
3481       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3482       break;
3483     default:
3484       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3485       break;
3486   }
3487
3488   GST_QUEUE2_MUTEX_UNLOCK (queue);
3489 }