queue2: if buffering is disabled while buffering, post 100% message
[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     remove (queue->temp_location);
1528
1529   queue->temp_file = NULL;
1530   clean_ranges (queue);
1531 }
1532
1533 static void
1534 gst_queue2_flush_temp_file (GstQueue2 * queue)
1535 {
1536   if (queue->temp_file == NULL)
1537     return;
1538
1539   GST_DEBUG_OBJECT (queue, "flushing temp file");
1540
1541   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1542 }
1543
1544 static void
1545 gst_queue2_locked_flush (GstQueue2 * queue, gboolean full, gboolean clear_temp)
1546 {
1547   if (!QUEUE_IS_USING_QUEUE (queue)) {
1548     if (QUEUE_IS_USING_TEMP_FILE (queue) && clear_temp)
1549       gst_queue2_flush_temp_file (queue);
1550     init_ranges (queue);
1551   } else {
1552     while (!g_queue_is_empty (&queue->queue)) {
1553       GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
1554
1555       if (!full && qitem->type == GST_QUEUE2_ITEM_TYPE_EVENT
1556           && GST_EVENT_IS_STICKY (qitem->item)
1557           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_SEGMENT
1558           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_EOS) {
1559         gst_pad_store_sticky_event (queue->srcpad,
1560             GST_EVENT_CAST (qitem->item));
1561       }
1562
1563       /* Then lose another reference because we are supposed to destroy that
1564          data when flushing */
1565       if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
1566         gst_mini_object_unref (qitem->item);
1567       g_slice_free (GstQueue2Item, qitem);
1568     }
1569   }
1570   queue->last_query = FALSE;
1571   g_cond_signal (&queue->query_handled);
1572   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1573   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1574   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1575   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1576   queue->sink_tainted = queue->src_tainted = TRUE;
1577   if (queue->starting_segment != NULL)
1578     gst_event_unref (queue->starting_segment);
1579   queue->starting_segment = NULL;
1580   queue->segment_event_received = FALSE;
1581   gst_event_replace (&queue->stream_start_event, NULL);
1582
1583   /* we deleted a lot of something */
1584   GST_QUEUE2_SIGNAL_DEL (queue);
1585 }
1586
1587 static gboolean
1588 gst_queue2_wait_free_space (GstQueue2 * queue)
1589 {
1590   /* We make space available if we're "full" according to whatever
1591    * the user defined as "full". */
1592   if (gst_queue2_is_filled (queue)) {
1593     gboolean started;
1594
1595     /* pause the timer while we wait. The fact that we are waiting does not mean
1596      * the byterate on the input pad is lower */
1597     if ((started = queue->in_timer_started))
1598       g_timer_stop (queue->in_timer);
1599
1600     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1601         "queue is full, waiting for free space");
1602     do {
1603       /* Wait for space to be available, we could be unlocked because of a flush. */
1604       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1605     }
1606     while (gst_queue2_is_filled (queue));
1607
1608     /* and continue if we were running before */
1609     if (started)
1610       g_timer_continue (queue->in_timer);
1611   }
1612   return TRUE;
1613
1614   /* ERRORS */
1615 out_flushing:
1616   {
1617     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1618     return FALSE;
1619   }
1620 }
1621
1622 static gboolean
1623 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1624 {
1625   GstMapInfo info;
1626   guint8 *data, *ring_buffer;
1627   guint size, rb_size;
1628   guint64 writing_pos, new_writing_pos;
1629   GstQueue2Range *range, *prev, *next;
1630   gboolean do_seek = FALSE;
1631
1632   if (QUEUE_IS_USING_RING_BUFFER (queue))
1633     writing_pos = queue->current->rb_writing_pos;
1634   else
1635     writing_pos = queue->current->writing_pos;
1636   ring_buffer = queue->ring_buffer;
1637   rb_size = queue->ring_buffer_max_size;
1638
1639   gst_buffer_map (buffer, &info, GST_MAP_READ);
1640
1641   size = info.size;
1642   data = info.data;
1643
1644   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1645       writing_pos);
1646
1647   /* sanity check */
1648   if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1649       GST_BUFFER_OFFSET (buffer) != queue->current->writing_pos) {
1650     GST_WARNING_OBJECT (queue, "buffer offset does not match current writing "
1651         "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1652         GST_BUFFER_OFFSET (buffer), queue->current->writing_pos);
1653   }
1654
1655   while (size > 0) {
1656     guint to_write;
1657
1658     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1659       gint64 space;
1660
1661       /* calculate the space in the ring buffer not used by data from
1662        * the current range */
1663       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1664         /* wait until there is some free space */
1665         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1666       }
1667       /* get the amount of space we have */
1668       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1669
1670       /* calculate if we need to split or if we can write the entire
1671        * buffer now */
1672       to_write = MIN (size, space);
1673
1674       /* the writing position in the ring buffer after writing (part
1675        * or all of) the buffer */
1676       new_writing_pos = (writing_pos + to_write) % rb_size;
1677
1678       prev = NULL;
1679       range = queue->ranges;
1680
1681       /* if we need to overwrite data in the ring buffer, we need to
1682        * update the ranges
1683        *
1684        * warning: this code is complicated and includes some
1685        * simplifications - pen, paper and diagrams for the cases
1686        * recommended! */
1687       while (range) {
1688         guint64 range_data_start, range_data_end;
1689         GstQueue2Range *range_to_destroy = NULL;
1690
1691         range_data_start = range->rb_offset;
1692         range_data_end = range->rb_writing_pos;
1693
1694         /* handle the special case where the range has no data in it */
1695         if (range->writing_pos == range->offset) {
1696           if (range != queue->current) {
1697             GST_DEBUG_OBJECT (queue,
1698                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1699                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1700             /* remove range */
1701             range_to_destroy = range;
1702             if (prev)
1703               prev->next = range->next;
1704           }
1705           goto next_range;
1706         }
1707
1708         if (range_data_end > range_data_start) {
1709           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1710             goto next_range;
1711
1712           if (new_writing_pos > range_data_start) {
1713             if (new_writing_pos >= range_data_end) {
1714               GST_DEBUG_OBJECT (queue,
1715                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1716                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1717               /* remove range */
1718               range_to_destroy = range;
1719               if (prev)
1720                 prev->next = range->next;
1721             } else {
1722               GST_DEBUG_OBJECT (queue,
1723                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1724                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1725                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1726                   range->offset + new_writing_pos - range_data_start,
1727                   new_writing_pos);
1728               range->offset += (new_writing_pos - range_data_start);
1729               range->rb_offset = new_writing_pos;
1730             }
1731           }
1732         } else {
1733           guint64 new_wpos_virt = writing_pos + to_write;
1734
1735           if (new_wpos_virt <= range_data_start)
1736             goto next_range;
1737
1738           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1739             GST_DEBUG_OBJECT (queue,
1740                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1741                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1742             /* remove range */
1743             range_to_destroy = range;
1744             if (prev)
1745               prev->next = range->next;
1746           } else {
1747             GST_DEBUG_OBJECT (queue,
1748                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1749                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1750                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1751                 range->offset + new_writing_pos - range_data_start,
1752                 new_writing_pos);
1753             range->offset += (new_wpos_virt - range_data_start);
1754             range->rb_offset = new_writing_pos;
1755           }
1756         }
1757
1758       next_range:
1759         if (!range_to_destroy)
1760           prev = range;
1761
1762         range = range->next;
1763         if (range_to_destroy) {
1764           if (range_to_destroy == queue->ranges)
1765             queue->ranges = range;
1766           g_slice_free (GstQueue2Range, range_to_destroy);
1767           range_to_destroy = NULL;
1768         }
1769       }
1770     } else {
1771       to_write = size;
1772       new_writing_pos = writing_pos + to_write;
1773     }
1774
1775     if (QUEUE_IS_USING_TEMP_FILE (queue)
1776         && FSEEK_FILE (queue->temp_file, writing_pos))
1777       goto seek_failed;
1778
1779     if (new_writing_pos > writing_pos) {
1780       GST_INFO_OBJECT (queue,
1781           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1782           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1783           queue->current->writing_pos, queue->current->rb_writing_pos);
1784       /* either not using ring buffer or no wrapping, just write */
1785       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1786         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1787           goto handle_error;
1788       } else {
1789         memcpy (ring_buffer + writing_pos, data, to_write);
1790       }
1791
1792       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1793         /* try to merge with next range */
1794         while ((next = queue->current->next)) {
1795           GST_INFO_OBJECT (queue,
1796               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1797               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1798           if (new_writing_pos < next->offset)
1799             break;
1800
1801           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1802               next->writing_pos);
1803
1804           /* remove the group */
1805           queue->current->next = next->next;
1806
1807           /* We use the threshold to decide if we want to do a seek or simply
1808            * read the data again. If there is not so much data in the range we
1809            * prefer to avoid to seek and read it again. */
1810           if (next->writing_pos > new_writing_pos + get_seek_threshold (queue)) {
1811             /* the new range had more data than the threshold, it's worth keeping
1812              * it and doing a seek. */
1813             new_writing_pos = next->writing_pos;
1814             do_seek = TRUE;
1815           }
1816           g_slice_free (GstQueue2Range, next);
1817         }
1818         goto update_and_signal;
1819       }
1820     } else {
1821       /* wrapping */
1822       guint block_one, block_two;
1823
1824       block_one = rb_size - writing_pos;
1825       block_two = to_write - block_one;
1826
1827       if (block_one > 0) {
1828         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1829         /* write data to end of ring buffer */
1830         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1831           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1832             goto handle_error;
1833         } else {
1834           memcpy (ring_buffer + writing_pos, data, block_one);
1835         }
1836       }
1837
1838       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1839         goto seek_failed;
1840
1841       if (block_two > 0) {
1842         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
1843         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1844           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
1845             goto handle_error;
1846         } else {
1847           memcpy (ring_buffer, data + block_one, block_two);
1848         }
1849       }
1850     }
1851
1852   update_and_signal:
1853     /* update the writing positions */
1854     size -= to_write;
1855     GST_INFO_OBJECT (queue,
1856         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
1857         to_write, writing_pos, size);
1858
1859     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1860       data += to_write;
1861       queue->current->writing_pos += to_write;
1862       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
1863     } else {
1864       queue->current->writing_pos = writing_pos = new_writing_pos;
1865     }
1866     if (do_seek)
1867       perform_seek_to_offset (queue, new_writing_pos);
1868
1869     update_cur_level (queue, queue->current);
1870
1871     /* update the buffering status */
1872     if (queue->use_buffering)
1873       update_buffering (queue);
1874
1875     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1876         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1877
1878     GST_QUEUE2_SIGNAL_ADD (queue);
1879   }
1880
1881   gst_buffer_unmap (buffer, &info);
1882
1883   return TRUE;
1884
1885   /* ERRORS */
1886 out_flushing:
1887   {
1888     GST_DEBUG_OBJECT (queue, "we are flushing");
1889     gst_buffer_unmap (buffer, &info);
1890     /* FIXME - GST_FLOW_EOS ? */
1891     return FALSE;
1892   }
1893 seek_failed:
1894   {
1895     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1896     gst_buffer_unmap (buffer, &info);
1897     return FALSE;
1898   }
1899 handle_error:
1900   {
1901     switch (errno) {
1902       case ENOSPC:{
1903         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
1904         break;
1905       }
1906       default:{
1907         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
1908             (_("Error while writing to download file.")),
1909             ("%s", g_strerror (errno)));
1910       }
1911     }
1912     gst_buffer_unmap (buffer, &info);
1913     return FALSE;
1914   }
1915 }
1916
1917 static gboolean
1918 buffer_list_create_write (GstBuffer ** buf, guint idx, gpointer q)
1919 {
1920   GstQueue2 *queue = q;
1921
1922   GST_TRACE_OBJECT (queue,
1923       "writing buffer %u of size %" G_GSIZE_FORMAT " bytes", idx,
1924       gst_buffer_get_size (*buf));
1925
1926   if (!gst_queue2_create_write (queue, *buf)) {
1927     GST_INFO_OBJECT (queue, "create_write() returned FALSE, bailing out");
1928     return FALSE;
1929   }
1930   return TRUE;
1931 }
1932
1933 static gboolean
1934 buffer_list_calc_size (GstBuffer ** buf, guint idx, gpointer data)
1935 {
1936   guint *p_size = data;
1937   gsize buf_size;
1938
1939   buf_size = gst_buffer_get_size (*buf);
1940   GST_TRACE ("buffer %u in has size %" G_GSIZE_FORMAT, idx, buf_size);
1941   *p_size += buf_size;
1942   return TRUE;
1943 }
1944
1945 /* enqueue an item an update the level stats */
1946 static void
1947 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item,
1948     GstQueue2ItemType item_type)
1949 {
1950   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
1951     GstBuffer *buffer;
1952     guint size;
1953
1954     buffer = GST_BUFFER_CAST (item);
1955     size = gst_buffer_get_size (buffer);
1956
1957     /* add buffer to the statistics */
1958     if (QUEUE_IS_USING_QUEUE (queue)) {
1959       queue->cur_level.buffers++;
1960       queue->cur_level.bytes += size;
1961     }
1962     queue->bytes_in += size;
1963
1964     /* apply new buffer to segment stats */
1965     apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
1966     /* update the byterate stats */
1967     update_in_rates (queue);
1968
1969     if (!QUEUE_IS_USING_QUEUE (queue)) {
1970       /* FIXME - check return value? */
1971       gst_queue2_create_write (queue, buffer);
1972     }
1973   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
1974     GstBufferList *buffer_list;
1975     guint size = 0;
1976
1977     buffer_list = GST_BUFFER_LIST_CAST (item);
1978
1979     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
1980     GST_LOG_OBJECT (queue, "total size of buffer list: %u bytes", size);
1981
1982     /* add buffer to the statistics */
1983     if (QUEUE_IS_USING_QUEUE (queue)) {
1984       queue->cur_level.buffers++;
1985       queue->cur_level.bytes += size;
1986     }
1987     queue->bytes_in += size;
1988
1989     /* apply new buffer to segment stats */
1990     apply_buffer_list (queue, buffer_list, &queue->sink_segment, TRUE);
1991
1992     /* update the byterate stats */
1993     update_in_rates (queue);
1994
1995     if (!QUEUE_IS_USING_QUEUE (queue)) {
1996       gst_buffer_list_foreach (buffer_list, buffer_list_create_write, queue);
1997     }
1998   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
1999     GstEvent *event;
2000
2001     event = GST_EVENT_CAST (item);
2002
2003     switch (GST_EVENT_TYPE (event)) {
2004       case GST_EVENT_EOS:
2005         /* Zero the thresholds, this makes sure the queue is completely
2006          * filled and we can read all data from the queue. */
2007         GST_DEBUG_OBJECT (queue, "we have EOS");
2008         queue->is_eos = TRUE;
2009         break;
2010       case GST_EVENT_SEGMENT:
2011         apply_segment (queue, event, &queue->sink_segment, TRUE);
2012         /* This is our first new segment, we hold it
2013          * as we can't save it on the temp file */
2014         if (!QUEUE_IS_USING_QUEUE (queue)) {
2015           if (queue->segment_event_received)
2016             goto unexpected_event;
2017
2018           queue->segment_event_received = TRUE;
2019           if (queue->starting_segment != NULL)
2020             gst_event_unref (queue->starting_segment);
2021           queue->starting_segment = event;
2022           item = NULL;
2023         }
2024         /* a new segment allows us to accept more buffers if we got EOS
2025          * from downstream */
2026         queue->unexpected = FALSE;
2027         break;
2028       case GST_EVENT_STREAM_START:
2029         if (!QUEUE_IS_USING_QUEUE (queue)) {
2030           gst_event_replace (&queue->stream_start_event, event);
2031           gst_event_unref (event);
2032           item = NULL;
2033         }
2034         break;
2035       case GST_EVENT_CAPS:{
2036         GstCaps *caps;
2037
2038         gst_event_parse_caps (event, &caps);
2039         GST_INFO ("got caps: %" GST_PTR_FORMAT, caps);
2040
2041         if (!QUEUE_IS_USING_QUEUE (queue)) {
2042           GST_LOG ("Dropping caps event, not using queue");
2043           gst_event_unref (event);
2044           item = NULL;
2045         }
2046         break;
2047       }
2048       default:
2049         if (!QUEUE_IS_USING_QUEUE (queue))
2050           goto unexpected_event;
2051         break;
2052     }
2053   } else if (GST_IS_QUERY (item)) {
2054     /* Can't happen as we check that in the caller */
2055     if (!QUEUE_IS_USING_QUEUE (queue))
2056       g_assert_not_reached ();
2057   } else {
2058     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
2059         item, GST_OBJECT_NAME (queue));
2060     /* we can't really unref since we don't know what it is */
2061     item = NULL;
2062   }
2063
2064   if (item) {
2065     /* update the buffering status */
2066     if (queue->use_buffering)
2067       update_buffering (queue);
2068
2069     if (QUEUE_IS_USING_QUEUE (queue)) {
2070       GstQueue2Item *qitem = g_slice_new (GstQueue2Item);
2071       qitem->type = item_type;
2072       qitem->item = item;
2073       g_queue_push_tail (&queue->queue, qitem);
2074     } else {
2075       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
2076     }
2077
2078     GST_QUEUE2_SIGNAL_ADD (queue);
2079   }
2080
2081   return;
2082
2083   /* ERRORS */
2084 unexpected_event:
2085   {
2086     g_warning
2087         ("Unexpected event of kind %s can't be added in temp file of queue %s ",
2088         gst_event_type_get_name (GST_EVENT_TYPE (item)),
2089         GST_OBJECT_NAME (queue));
2090     gst_event_unref (GST_EVENT_CAST (item));
2091     return;
2092   }
2093 }
2094
2095 /* dequeue an item from the queue and update level stats */
2096 static GstMiniObject *
2097 gst_queue2_locked_dequeue (GstQueue2 * queue, GstQueue2ItemType * item_type)
2098 {
2099   GstMiniObject *item;
2100
2101   if (!QUEUE_IS_USING_QUEUE (queue)) {
2102     item = gst_queue2_read_item_from_file (queue);
2103   } else {
2104     GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
2105
2106     if (qitem == NULL)
2107       goto no_item;
2108
2109     item = qitem->item;
2110     g_slice_free (GstQueue2Item, qitem);
2111   }
2112
2113   if (item == NULL)
2114     goto no_item;
2115
2116   if (GST_IS_BUFFER (item)) {
2117     GstBuffer *buffer;
2118     guint size;
2119
2120     buffer = GST_BUFFER_CAST (item);
2121     size = gst_buffer_get_size (buffer);
2122     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER;
2123
2124     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2125         "retrieved buffer %p from queue", buffer);
2126
2127     if (QUEUE_IS_USING_QUEUE (queue)) {
2128       queue->cur_level.buffers--;
2129       queue->cur_level.bytes -= size;
2130     }
2131     queue->bytes_out += size;
2132
2133     apply_buffer (queue, buffer, &queue->src_segment, FALSE);
2134     /* update the byterate stats */
2135     update_out_rates (queue);
2136     /* update the buffering */
2137     if (queue->use_buffering)
2138       update_buffering (queue);
2139
2140   } else if (GST_IS_EVENT (item)) {
2141     GstEvent *event = GST_EVENT_CAST (item);
2142
2143     *item_type = GST_QUEUE2_ITEM_TYPE_EVENT;
2144
2145     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2146         "retrieved event %p from queue", event);
2147
2148     switch (GST_EVENT_TYPE (event)) {
2149       case GST_EVENT_EOS:
2150         /* queue is empty now that we dequeued the EOS */
2151         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
2152         break;
2153       case GST_EVENT_SEGMENT:
2154         apply_segment (queue, event, &queue->src_segment, FALSE);
2155         break;
2156       default:
2157         break;
2158     }
2159   } else if (GST_IS_BUFFER_LIST (item)) {
2160     GstBufferList *buffer_list;
2161     guint size = 0;
2162
2163     buffer_list = GST_BUFFER_LIST_CAST (item);
2164     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2165     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER_LIST;
2166
2167     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2168         "retrieved buffer list %p from queue", buffer_list);
2169
2170     if (QUEUE_IS_USING_QUEUE (queue)) {
2171       queue->cur_level.buffers--;
2172       queue->cur_level.bytes -= size;
2173     }
2174     queue->bytes_out += size;
2175
2176     apply_buffer_list (queue, buffer_list, &queue->src_segment, FALSE);
2177     /* update the byterate stats */
2178     update_out_rates (queue);
2179     /* update the buffering */
2180     if (queue->use_buffering)
2181       update_buffering (queue);
2182   } else if (GST_IS_QUERY (item)) {
2183     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2184         "retrieved query %p from queue", item);
2185     *item_type = GST_QUEUE2_ITEM_TYPE_QUERY;
2186   } else {
2187     g_warning
2188         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
2189         item, GST_OBJECT_NAME (queue));
2190     item = NULL;
2191     *item_type = GST_QUEUE2_ITEM_TYPE_UNKNOWN;
2192   }
2193   GST_QUEUE2_SIGNAL_DEL (queue);
2194
2195   return item;
2196
2197   /* ERRORS */
2198 no_item:
2199   {
2200     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
2201     return NULL;
2202   }
2203 }
2204
2205 static gboolean
2206 gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
2207     GstEvent * event)
2208 {
2209   gboolean ret = TRUE;
2210   GstQueue2 *queue;
2211
2212   queue = GST_QUEUE2 (parent);
2213
2214   switch (GST_EVENT_TYPE (event)) {
2215     case GST_EVENT_FLUSH_START:
2216     {
2217       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
2218       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2219         /* forward event */
2220         ret = gst_pad_push_event (queue->srcpad, event);
2221
2222         /* now unblock the chain function */
2223         GST_QUEUE2_MUTEX_LOCK (queue);
2224         queue->srcresult = GST_FLOW_FLUSHING;
2225         queue->sinkresult = GST_FLOW_FLUSHING;
2226         /* unblock the loop and chain functions */
2227         GST_QUEUE2_SIGNAL_ADD (queue);
2228         GST_QUEUE2_SIGNAL_DEL (queue);
2229         queue->last_query = FALSE;
2230         g_cond_signal (&queue->query_handled);
2231         GST_QUEUE2_MUTEX_UNLOCK (queue);
2232
2233         /* make sure it pauses, this should happen since we sent
2234          * flush_start downstream. */
2235         gst_pad_pause_task (queue->srcpad);
2236         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
2237       } else {
2238         GST_QUEUE2_MUTEX_LOCK (queue);
2239         /* flush the sink pad */
2240         queue->sinkresult = GST_FLOW_FLUSHING;
2241         GST_QUEUE2_SIGNAL_DEL (queue);
2242         queue->last_query = FALSE;
2243         g_cond_signal (&queue->query_handled);
2244         GST_QUEUE2_MUTEX_UNLOCK (queue);
2245
2246         gst_event_unref (event);
2247       }
2248       break;
2249     }
2250     case GST_EVENT_FLUSH_STOP:
2251     {
2252       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2253
2254       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2255         /* forward event */
2256         ret = gst_pad_push_event (queue->srcpad, event);
2257
2258         GST_QUEUE2_MUTEX_LOCK (queue);
2259         gst_queue2_locked_flush (queue, FALSE, TRUE);
2260         queue->srcresult = GST_FLOW_OK;
2261         queue->sinkresult = GST_FLOW_OK;
2262         queue->is_eos = FALSE;
2263         queue->unexpected = FALSE;
2264         queue->seeking = FALSE;
2265         /* reset rate counters */
2266         reset_rate_timer (queue);
2267         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2268             queue->srcpad, NULL);
2269         GST_QUEUE2_MUTEX_UNLOCK (queue);
2270       } else {
2271         GST_QUEUE2_MUTEX_LOCK (queue);
2272         queue->segment_event_received = FALSE;
2273         queue->is_eos = FALSE;
2274         queue->unexpected = FALSE;
2275         queue->sinkresult = GST_FLOW_OK;
2276         queue->seeking = FALSE;
2277         GST_QUEUE2_MUTEX_UNLOCK (queue);
2278
2279         gst_event_unref (event);
2280       }
2281       break;
2282     }
2283     default:
2284       if (GST_EVENT_IS_SERIALIZED (event)) {
2285         /* serialized events go in the queue */
2286         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2287         /* refuse more events on EOS */
2288         if (queue->is_eos)
2289           goto out_eos;
2290         gst_queue2_locked_enqueue (queue, event, GST_QUEUE2_ITEM_TYPE_EVENT);
2291         GST_QUEUE2_MUTEX_UNLOCK (queue);
2292       } else {
2293         /* non-serialized events are passed upstream. */
2294         ret = gst_pad_push_event (queue->srcpad, event);
2295       }
2296       break;
2297   }
2298   return ret;
2299
2300   /* ERRORS */
2301 out_flushing:
2302   {
2303     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2304     GST_QUEUE2_MUTEX_UNLOCK (queue);
2305     gst_event_unref (event);
2306     return FALSE;
2307   }
2308 out_eos:
2309   {
2310     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2311     GST_QUEUE2_MUTEX_UNLOCK (queue);
2312     gst_event_unref (event);
2313     return FALSE;
2314   }
2315 }
2316
2317 static gboolean
2318 gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
2319     GstQuery * query)
2320 {
2321   GstQueue2 *queue;
2322   gboolean res;
2323
2324   queue = GST_QUEUE2 (parent);
2325
2326   switch (GST_QUERY_TYPE (query)) {
2327     default:
2328       if (GST_QUERY_IS_SERIALIZED (query)) {
2329         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received query %p", query);
2330         /* serialized events go in the queue. We need to be certain that we
2331          * don't cause deadlocks waiting for the query return value. We check if
2332          * the queue is empty (nothing is blocking downstream and the query can
2333          * be pushed for sure) or we are not buffering. If we are buffering,
2334          * the pipeline waits to unblock downstream until our queue fills up
2335          * completely, which can not happen if we block on the query..
2336          * Therefore we only potentially block when we are not buffering. */
2337         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2338         if (QUEUE_IS_USING_QUEUE (queue) && (gst_queue2_is_empty (queue)
2339                 || !queue->use_buffering)) {
2340           gst_queue2_locked_enqueue (queue, query, GST_QUEUE2_ITEM_TYPE_QUERY);
2341
2342           STATUS (queue, queue->sinkpad, "wait for QUERY");
2343           g_cond_wait (&queue->query_handled, &queue->qlock);
2344           if (queue->sinkresult != GST_FLOW_OK)
2345             goto out_flushing;
2346           res = queue->last_query;
2347         } else {
2348           GST_DEBUG_OBJECT (queue,
2349               "refusing query, we are not using the queue");
2350           res = FALSE;
2351         }
2352         GST_QUEUE2_MUTEX_UNLOCK (queue);
2353       } else {
2354         res = gst_pad_query_default (pad, parent, query);
2355       }
2356       break;
2357   }
2358   return res;
2359
2360   /* ERRORS */
2361 out_flushing:
2362   {
2363     GST_DEBUG_OBJECT (queue, "refusing query, we are flushing");
2364     GST_QUEUE2_MUTEX_UNLOCK (queue);
2365     return FALSE;
2366   }
2367 }
2368
2369 static gboolean
2370 gst_queue2_is_empty (GstQueue2 * queue)
2371 {
2372   /* never empty on EOS */
2373   if (queue->is_eos)
2374     return FALSE;
2375
2376   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2377     return queue->current->writing_pos <= queue->current->max_reading_pos;
2378   } else {
2379     if (queue->queue.length == 0)
2380       return TRUE;
2381   }
2382
2383   return FALSE;
2384 }
2385
2386 static gboolean
2387 gst_queue2_is_filled (GstQueue2 * queue)
2388 {
2389   gboolean res;
2390
2391   /* always filled on EOS */
2392   if (queue->is_eos)
2393     return TRUE;
2394
2395 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2396     (queue->cur_level.format) >= ((alt_max) ? \
2397       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2398
2399   /* if using a ring buffer we're filled if all ring buffer space is used
2400    * _by the current range_ */
2401   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2402     guint64 rb_size = queue->ring_buffer_max_size;
2403     GST_DEBUG_OBJECT (queue,
2404         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2405         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2406     return CHECK_FILLED (bytes, rb_size);
2407   }
2408
2409   /* if using file, we're never filled if we don't have EOS */
2410   if (QUEUE_IS_USING_TEMP_FILE (queue))
2411     return FALSE;
2412
2413   /* we are never filled when we have no buffers at all */
2414   if (queue->cur_level.buffers == 0)
2415     return FALSE;
2416
2417   /* we are filled if one of the current levels exceeds the max */
2418   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2419       || CHECK_FILLED (time, 0);
2420
2421   /* if we need to, use the rate estimate to check against the max time we are
2422    * allowed to queue */
2423   if (queue->use_rate_estimate)
2424     res |= CHECK_FILLED (rate_time, 0);
2425
2426 #undef CHECK_FILLED
2427   return res;
2428 }
2429
2430 static GstFlowReturn
2431 gst_queue2_chain_buffer_or_buffer_list (GstQueue2 * queue,
2432     GstMiniObject * item, GstQueue2ItemType item_type)
2433 {
2434   /* we have to lock the queue since we span threads */
2435   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2436   /* when we received EOS, we refuse more data */
2437   if (queue->is_eos)
2438     goto out_eos;
2439   /* when we received unexpected from downstream, refuse more buffers */
2440   if (queue->unexpected)
2441     goto out_unexpected;
2442
2443   /* while we didn't receive the newsegment, we're seeking and we skip data */
2444   if (queue->seeking)
2445     goto out_seeking;
2446
2447   if (!gst_queue2_wait_free_space (queue))
2448     goto out_flushing;
2449
2450   /* put buffer in queue now */
2451   gst_queue2_locked_enqueue (queue, item, item_type);
2452   GST_QUEUE2_MUTEX_UNLOCK (queue);
2453
2454   return GST_FLOW_OK;
2455
2456   /* special conditions */
2457 out_flushing:
2458   {
2459     GstFlowReturn ret = queue->sinkresult;
2460
2461     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2462         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2463     GST_QUEUE2_MUTEX_UNLOCK (queue);
2464     gst_mini_object_unref (item);
2465
2466     return ret;
2467   }
2468 out_eos:
2469   {
2470     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2471     GST_QUEUE2_MUTEX_UNLOCK (queue);
2472     gst_mini_object_unref (item);
2473
2474     return GST_FLOW_EOS;
2475   }
2476 out_seeking:
2477   {
2478     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are seeking");
2479     GST_QUEUE2_MUTEX_UNLOCK (queue);
2480     gst_mini_object_unref (item);
2481
2482     return GST_FLOW_OK;
2483   }
2484 out_unexpected:
2485   {
2486     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2487     GST_QUEUE2_MUTEX_UNLOCK (queue);
2488     gst_mini_object_unref (item);
2489
2490     return GST_FLOW_EOS;
2491   }
2492 }
2493
2494 static GstFlowReturn
2495 gst_queue2_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2496 {
2497   GstQueue2 *queue;
2498
2499   queue = GST_QUEUE2 (parent);
2500
2501   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of "
2502       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
2503       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
2504       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2505       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2506
2507   return gst_queue2_chain_buffer_or_buffer_list (queue,
2508       GST_MINI_OBJECT_CAST (buffer), GST_QUEUE2_ITEM_TYPE_BUFFER);
2509 }
2510
2511 static GstFlowReturn
2512 gst_queue2_chain_list (GstPad * pad, GstObject * parent,
2513     GstBufferList * buffer_list)
2514 {
2515   GstQueue2 *queue;
2516
2517   queue = GST_QUEUE2 (parent);
2518
2519   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2520       "received buffer list %p", buffer_list);
2521
2522   return gst_queue2_chain_buffer_or_buffer_list (queue,
2523       GST_MINI_OBJECT_CAST (buffer_list), GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2524 }
2525
2526 static GstMiniObject *
2527 gst_queue2_dequeue_on_eos (GstQueue2 * queue, GstQueue2ItemType * item_type)
2528 {
2529   GstMiniObject *data;
2530
2531   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
2532
2533   /* stop pushing buffers, we dequeue all items until we see an item that we
2534    * can push again, which is EOS or SEGMENT. If there is nothing in the
2535    * queue we can push, we set a flag to make the sinkpad refuse more
2536    * buffers with an EOS return value until we receive something
2537    * pushable again or we get flushed. */
2538   while ((data = gst_queue2_locked_dequeue (queue, item_type))) {
2539     if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2540       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2541           "dropping EOS buffer %p", data);
2542       gst_buffer_unref (GST_BUFFER_CAST (data));
2543     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2544       GstEvent *event = GST_EVENT_CAST (data);
2545       GstEventType type = GST_EVENT_TYPE (event);
2546
2547       if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
2548         /* we found a pushable item in the queue, push it out */
2549         GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2550             "pushing pushable event %s after EOS", GST_EVENT_TYPE_NAME (event));
2551         return data;
2552       }
2553       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2554           "dropping EOS event %p", event);
2555       gst_event_unref (event);
2556     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2557       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2558           "dropping EOS buffer list %p", data);
2559       gst_buffer_list_unref (GST_BUFFER_LIST_CAST (data));
2560     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2561       queue->last_query = FALSE;
2562       g_cond_signal (&queue->query_handled);
2563       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "dropping EOS query %p", data);
2564     }
2565   }
2566   /* no more items in the queue. Set the unexpected flag so that upstream
2567    * make us refuse any more buffers on the sinkpad. Since we will still
2568    * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
2569    * task function does not shut down. */
2570   queue->unexpected = TRUE;
2571   return NULL;
2572 }
2573
2574 /* dequeue an item from the queue an push it downstream. This functions returns
2575  * the result of the push. */
2576 static GstFlowReturn
2577 gst_queue2_push_one (GstQueue2 * queue)
2578 {
2579   GstFlowReturn result = queue->srcresult;
2580   GstMiniObject *data;
2581   GstQueue2ItemType item_type;
2582
2583   data = gst_queue2_locked_dequeue (queue, &item_type);
2584   if (data == NULL)
2585     goto no_item;
2586
2587 next:
2588   GST_QUEUE2_MUTEX_UNLOCK (queue);
2589
2590   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2591     GstBuffer *buffer;
2592
2593     buffer = GST_BUFFER_CAST (data);
2594
2595     result = gst_pad_push (queue->srcpad, buffer);
2596
2597     /* need to check for srcresult here as well */
2598     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2599     if (result == GST_FLOW_EOS) {
2600       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2601       if (data != NULL)
2602         goto next;
2603       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2604        * to the caller so that the task function does not shut down */
2605       result = GST_FLOW_OK;
2606     }
2607   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2608     GstEvent *event = GST_EVENT_CAST (data);
2609     GstEventType type = GST_EVENT_TYPE (event);
2610
2611     gst_pad_push_event (queue->srcpad, event);
2612
2613     /* if we're EOS, return EOS so that the task pauses. */
2614     if (type == GST_EVENT_EOS) {
2615       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2616           "pushed EOS event %p, return EOS", event);
2617       result = GST_FLOW_EOS;
2618     }
2619
2620     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2621   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2622     GstBufferList *buffer_list;
2623
2624     buffer_list = GST_BUFFER_LIST_CAST (data);
2625
2626     result = gst_pad_push_list (queue->srcpad, buffer_list);
2627
2628     /* need to check for srcresult here as well */
2629     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2630     if (result == GST_FLOW_EOS) {
2631       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2632       if (data != NULL)
2633         goto next;
2634       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2635        * to the caller so that the task function does not shut down */
2636       result = GST_FLOW_OK;
2637     }
2638   } else if (item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2639     GstQuery *query = GST_QUERY_CAST (data);
2640
2641     queue->last_query = gst_pad_peer_query (queue->srcpad, query);
2642     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2643         "did query %p, return %d", query, queue->last_query);
2644     g_cond_signal (&queue->query_handled);
2645     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2646     result = GST_FLOW_OK;
2647   }
2648   return result;
2649
2650   /* ERRORS */
2651 no_item:
2652   {
2653     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2654         "exit because we have no item in the queue");
2655     return GST_FLOW_ERROR;
2656   }
2657 out_flushing:
2658   {
2659     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2660     return GST_FLOW_FLUSHING;
2661   }
2662 }
2663
2664 /* called repeatedly with @pad as the source pad. This function should push out
2665  * data to the peer element. */
2666 static void
2667 gst_queue2_loop (GstPad * pad)
2668 {
2669   GstQueue2 *queue;
2670   GstFlowReturn ret;
2671
2672   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2673
2674   /* have to lock for thread-safety */
2675   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2676
2677   if (gst_queue2_is_empty (queue)) {
2678     gboolean started;
2679
2680     /* pause the timer while we wait. The fact that we are waiting does not mean
2681      * the byterate on the output pad is lower */
2682     if ((started = queue->out_timer_started))
2683       g_timer_stop (queue->out_timer);
2684
2685     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2686         "queue is empty, waiting for new data");
2687     do {
2688       /* Wait for data to be available, we could be unlocked because of a flush. */
2689       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2690     }
2691     while (gst_queue2_is_empty (queue));
2692
2693     /* and continue if we were running before */
2694     if (started)
2695       g_timer_continue (queue->out_timer);
2696   }
2697   ret = gst_queue2_push_one (queue);
2698   queue->srcresult = ret;
2699   queue->sinkresult = ret;
2700   if (ret != GST_FLOW_OK)
2701     goto out_flushing;
2702
2703   GST_QUEUE2_MUTEX_UNLOCK (queue);
2704
2705   return;
2706
2707   /* ERRORS */
2708 out_flushing:
2709   {
2710     gboolean eos = queue->is_eos;
2711     GstFlowReturn ret = queue->srcresult;
2712
2713     gst_pad_pause_task (queue->srcpad);
2714     GST_QUEUE2_MUTEX_UNLOCK (queue);
2715     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2716         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2717     /* let app know about us giving up if upstream is not expected to do so */
2718     /* EOS is already taken care of elsewhere */
2719     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
2720       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2721           (_("Internal data flow error.")),
2722           ("streaming task paused, reason %s (%d)",
2723               gst_flow_get_name (ret), ret));
2724       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2725     }
2726     return;
2727   }
2728 }
2729
2730 static gboolean
2731 gst_queue2_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2732 {
2733   gboolean res = TRUE;
2734   GstQueue2 *queue = GST_QUEUE2 (parent);
2735
2736 #ifndef GST_DISABLE_GST_DEBUG
2737   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
2738       event, GST_EVENT_TYPE_NAME (event));
2739 #endif
2740
2741   switch (GST_EVENT_TYPE (event)) {
2742     case GST_EVENT_FLUSH_START:
2743       if (QUEUE_IS_USING_QUEUE (queue)) {
2744         /* just forward upstream */
2745         res = gst_pad_push_event (queue->sinkpad, event);
2746       } else {
2747         /* now unblock the getrange function */
2748         GST_QUEUE2_MUTEX_LOCK (queue);
2749         GST_DEBUG_OBJECT (queue, "flushing");
2750         queue->srcresult = GST_FLOW_FLUSHING;
2751         GST_QUEUE2_SIGNAL_ADD (queue);
2752         GST_QUEUE2_MUTEX_UNLOCK (queue);
2753
2754         /* when using a temp file, we eat the event */
2755         res = TRUE;
2756         gst_event_unref (event);
2757       }
2758       break;
2759     case GST_EVENT_FLUSH_STOP:
2760       if (QUEUE_IS_USING_QUEUE (queue)) {
2761         /* just forward upstream */
2762         res = gst_pad_push_event (queue->sinkpad, event);
2763       } else {
2764         /* now unblock the getrange function */
2765         GST_QUEUE2_MUTEX_LOCK (queue);
2766         queue->srcresult = GST_FLOW_OK;
2767         GST_QUEUE2_MUTEX_UNLOCK (queue);
2768
2769         /* when using a temp file, we eat the event */
2770         res = TRUE;
2771         gst_event_unref (event);
2772       }
2773       break;
2774     case GST_EVENT_RECONFIGURE:
2775       GST_QUEUE2_MUTEX_LOCK (queue);
2776       /* assume downstream is linked now and try to push again */
2777       if (queue->srcresult == GST_FLOW_NOT_LINKED) {
2778         queue->srcresult = GST_FLOW_OK;
2779         queue->sinkresult = GST_FLOW_OK;
2780         if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
2781           gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad,
2782               NULL);
2783         }
2784       }
2785       GST_QUEUE2_MUTEX_UNLOCK (queue);
2786
2787       res = gst_pad_push_event (queue->sinkpad, event);
2788       break;
2789     default:
2790       res = gst_pad_push_event (queue->sinkpad, event);
2791       break;
2792   }
2793
2794   return res;
2795 }
2796
2797 static gboolean
2798 gst_queue2_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2799 {
2800   GstQueue2 *queue;
2801
2802   queue = GST_QUEUE2 (parent);
2803
2804   switch (GST_QUERY_TYPE (query)) {
2805     case GST_QUERY_POSITION:
2806     {
2807       gint64 peer_pos;
2808       GstFormat format;
2809
2810       if (!gst_pad_peer_query (queue->sinkpad, query))
2811         goto peer_failed;
2812
2813       /* get peer position */
2814       gst_query_parse_position (query, &format, &peer_pos);
2815
2816       /* FIXME: this code assumes that there's no discont in the queue */
2817       switch (format) {
2818         case GST_FORMAT_BYTES:
2819           peer_pos -= queue->cur_level.bytes;
2820           break;
2821         case GST_FORMAT_TIME:
2822           peer_pos -= queue->cur_level.time;
2823           break;
2824         default:
2825           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
2826               "know how to adjust value", gst_format_get_name (format));
2827           return FALSE;
2828       }
2829       /* set updated position */
2830       gst_query_set_position (query, format, peer_pos);
2831       break;
2832     }
2833     case GST_QUERY_DURATION:
2834     {
2835       GST_DEBUG_OBJECT (queue, "doing peer query");
2836
2837       if (!gst_pad_peer_query (queue->sinkpad, query))
2838         goto peer_failed;
2839
2840       GST_DEBUG_OBJECT (queue, "peer query success");
2841       break;
2842     }
2843     case GST_QUERY_BUFFERING:
2844     {
2845       gint percent;
2846       gboolean is_buffering;
2847       GstBufferingMode mode;
2848       gint avg_in, avg_out;
2849       gint64 buffering_left;
2850
2851       GST_DEBUG_OBJECT (queue, "query buffering");
2852
2853       get_buffering_percent (queue, &is_buffering, &percent);
2854       gst_query_set_buffering_percent (query, is_buffering, percent);
2855
2856       get_buffering_stats (queue, percent, &mode, &avg_in, &avg_out,
2857           &buffering_left);
2858       gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
2859           buffering_left);
2860
2861       if (!QUEUE_IS_USING_QUEUE (queue)) {
2862         /* add ranges for download and ringbuffer buffering */
2863         GstFormat format;
2864         gint64 start, stop, range_start, range_stop;
2865         guint64 writing_pos;
2866         gint64 estimated_total;
2867         gint64 duration;
2868         gboolean peer_res, is_eos;
2869         GstQueue2Range *queued_ranges;
2870
2871         /* we need a current download region */
2872         if (queue->current == NULL)
2873           return FALSE;
2874
2875         writing_pos = queue->current->writing_pos;
2876         is_eos = queue->is_eos;
2877
2878         if (is_eos) {
2879           /* we're EOS, we know the duration in bytes now */
2880           peer_res = TRUE;
2881           duration = writing_pos;
2882         } else {
2883           /* get duration of upstream in bytes */
2884           peer_res = gst_pad_peer_query_duration (queue->sinkpad,
2885               GST_FORMAT_BYTES, &duration);
2886         }
2887
2888         GST_DEBUG_OBJECT (queue, "percent %d, duration %" G_GINT64_FORMAT
2889             ", writing %" G_GINT64_FORMAT, percent, duration, writing_pos);
2890
2891         /* calculate remaining and total download time */
2892         if (peer_res && avg_in > 0.0)
2893           estimated_total = ((duration - writing_pos) * 1000) / avg_in;
2894         else
2895           estimated_total = -1;
2896
2897         GST_DEBUG_OBJECT (queue, "estimated-total %" G_GINT64_FORMAT,
2898             estimated_total);
2899
2900         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
2901
2902         switch (format) {
2903           case GST_FORMAT_PERCENT:
2904             /* we need duration */
2905             if (!peer_res)
2906               goto peer_failed;
2907
2908             start = 0;
2909             /* get our available data relative to the duration */
2910             if (duration != -1)
2911               stop =
2912                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX, writing_pos,
2913                   duration);
2914             else
2915               stop = -1;
2916             break;
2917           case GST_FORMAT_BYTES:
2918             start = 0;
2919             stop = writing_pos;
2920             break;
2921           default:
2922             start = -1;
2923             stop = -1;
2924             break;
2925         }
2926
2927         /* fill out the buffered ranges */
2928         for (queued_ranges = queue->ranges; queued_ranges;
2929             queued_ranges = queued_ranges->next) {
2930           switch (format) {
2931             case GST_FORMAT_PERCENT:
2932               if (duration == -1) {
2933                 range_start = 0;
2934                 range_stop = 0;
2935                 break;
2936               }
2937               range_start =
2938                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
2939                   queued_ranges->offset, duration);
2940               range_stop =
2941                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
2942                   queued_ranges->writing_pos, duration);
2943               break;
2944             case GST_FORMAT_BYTES:
2945               range_start = queued_ranges->offset;
2946               range_stop = queued_ranges->writing_pos;
2947               break;
2948             default:
2949               range_start = -1;
2950               range_stop = -1;
2951               break;
2952           }
2953           if (range_start == range_stop)
2954             continue;
2955           GST_DEBUG_OBJECT (queue,
2956               "range starting at %" G_GINT64_FORMAT " and finishing at %"
2957               G_GINT64_FORMAT, range_start, range_stop);
2958           gst_query_add_buffering_range (query, range_start, range_stop);
2959         }
2960
2961         gst_query_set_buffering_range (query, format, start, stop,
2962             estimated_total);
2963       }
2964       break;
2965     }
2966     case GST_QUERY_SCHEDULING:
2967     {
2968       gboolean pull_mode;
2969       GstSchedulingFlags flags = 0;
2970
2971       if (!gst_pad_peer_query (queue->sinkpad, query))
2972         goto peer_failed;
2973
2974       gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
2975
2976       /* we can operate in pull mode when we are using a tempfile */
2977       pull_mode = !QUEUE_IS_USING_QUEUE (queue);
2978
2979       if (pull_mode)
2980         flags |= GST_SCHEDULING_FLAG_SEEKABLE;
2981       gst_query_set_scheduling (query, flags, 0, -1, 0);
2982       if (pull_mode)
2983         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
2984       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
2985       break;
2986     }
2987     default:
2988       /* peer handled other queries */
2989       if (!gst_pad_query_default (pad, parent, query))
2990         goto peer_failed;
2991       break;
2992   }
2993
2994   return TRUE;
2995
2996   /* ERRORS */
2997 peer_failed:
2998   {
2999     GST_DEBUG_OBJECT (queue, "failed peer query");
3000     return FALSE;
3001   }
3002 }
3003
3004 static gboolean
3005 gst_queue2_handle_query (GstElement * element, GstQuery * query)
3006 {
3007   GstQueue2 *queue = GST_QUEUE2 (element);
3008
3009   /* simply forward to the srcpad query function */
3010   return gst_queue2_handle_src_query (queue->srcpad, GST_OBJECT_CAST (element),
3011       query);
3012 }
3013
3014 static void
3015 gst_queue2_update_upstream_size (GstQueue2 * queue)
3016 {
3017   gint64 upstream_size = -1;
3018
3019   if (gst_pad_peer_query_duration (queue->sinkpad, GST_FORMAT_BYTES,
3020           &upstream_size)) {
3021     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
3022     queue->upstream_size = upstream_size;
3023   }
3024 }
3025
3026 static GstFlowReturn
3027 gst_queue2_get_range (GstPad * pad, GstObject * parent, guint64 offset,
3028     guint length, GstBuffer ** buffer)
3029 {
3030   GstQueue2 *queue;
3031   GstFlowReturn ret;
3032
3033   queue = GST_QUEUE2_CAST (parent);
3034
3035   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
3036   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
3037   offset = (offset == -1) ? queue->current->reading_pos : offset;
3038
3039   GST_DEBUG_OBJECT (queue,
3040       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
3041
3042   /* catch any reads beyond the size of the file here to make sure queue2
3043    * doesn't send seek events beyond the size of the file upstream, since
3044    * that would confuse elements such as souphttpsrc and/or http servers.
3045    * Demuxers often just loop until EOS at the end of the file to figure out
3046    * when they've read all the end-headers or index chunks. */
3047   if (G_UNLIKELY (offset >= queue->upstream_size)) {
3048     gst_queue2_update_upstream_size (queue);
3049     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
3050       goto out_unexpected;
3051   }
3052
3053   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
3054     gst_queue2_update_upstream_size (queue);
3055     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
3056       length = queue->upstream_size - offset;
3057       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
3058     }
3059   }
3060
3061   /* FIXME - function will block when the range is not yet available */
3062   ret = gst_queue2_create_read (queue, offset, length, buffer);
3063   GST_QUEUE2_MUTEX_UNLOCK (queue);
3064
3065   return ret;
3066
3067   /* ERRORS */
3068 out_flushing:
3069   {
3070     ret = queue->srcresult;
3071
3072     GST_DEBUG_OBJECT (queue, "we are flushing");
3073     GST_QUEUE2_MUTEX_UNLOCK (queue);
3074     return ret;
3075   }
3076 out_unexpected:
3077   {
3078     GST_DEBUG_OBJECT (queue, "read beyond end of file");
3079     GST_QUEUE2_MUTEX_UNLOCK (queue);
3080     return GST_FLOW_EOS;
3081   }
3082 }
3083
3084 /* sink currently only operates in push mode */
3085 static gboolean
3086 gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
3087     GstPadMode mode, gboolean active)
3088 {
3089   gboolean result;
3090   GstQueue2 *queue;
3091
3092   queue = GST_QUEUE2 (parent);
3093
3094   switch (mode) {
3095     case GST_PAD_MODE_PUSH:
3096       if (active) {
3097         GST_QUEUE2_MUTEX_LOCK (queue);
3098         GST_DEBUG_OBJECT (queue, "activating push mode");
3099         queue->srcresult = GST_FLOW_OK;
3100         queue->sinkresult = GST_FLOW_OK;
3101         queue->is_eos = FALSE;
3102         queue->unexpected = FALSE;
3103         reset_rate_timer (queue);
3104         GST_QUEUE2_MUTEX_UNLOCK (queue);
3105       } else {
3106         /* unblock chain function */
3107         GST_QUEUE2_MUTEX_LOCK (queue);
3108         GST_DEBUG_OBJECT (queue, "deactivating push mode");
3109         queue->srcresult = GST_FLOW_FLUSHING;
3110         queue->sinkresult = GST_FLOW_FLUSHING;
3111         GST_QUEUE2_SIGNAL_DEL (queue);
3112         /* Unblock query handler */
3113         queue->last_query = FALSE;
3114         g_cond_signal (&queue->query_handled);
3115         GST_QUEUE2_MUTEX_UNLOCK (queue);
3116
3117         /* wait until it is unblocked and clean up */
3118         GST_PAD_STREAM_LOCK (pad);
3119         GST_QUEUE2_MUTEX_LOCK (queue);
3120         gst_queue2_locked_flush (queue, TRUE, FALSE);
3121         GST_QUEUE2_MUTEX_UNLOCK (queue);
3122         GST_PAD_STREAM_UNLOCK (pad);
3123       }
3124       result = TRUE;
3125       break;
3126     default:
3127       result = FALSE;
3128       break;
3129   }
3130   return result;
3131 }
3132
3133 /* src operating in push mode, we start a task on the source pad that pushes out
3134  * buffers from the queue */
3135 static gboolean
3136 gst_queue2_src_activate_push (GstPad * pad, GstObject * parent, gboolean active)
3137 {
3138   gboolean result = FALSE;
3139   GstQueue2 *queue;
3140
3141   queue = GST_QUEUE2 (parent);
3142
3143   if (active) {
3144     GST_QUEUE2_MUTEX_LOCK (queue);
3145     GST_DEBUG_OBJECT (queue, "activating push mode");
3146     queue->srcresult = GST_FLOW_OK;
3147     queue->sinkresult = GST_FLOW_OK;
3148     queue->is_eos = FALSE;
3149     queue->unexpected = FALSE;
3150     result =
3151         gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad, NULL);
3152     GST_QUEUE2_MUTEX_UNLOCK (queue);
3153   } else {
3154     /* unblock loop function */
3155     GST_QUEUE2_MUTEX_LOCK (queue);
3156     GST_DEBUG_OBJECT (queue, "deactivating push mode");
3157     queue->srcresult = GST_FLOW_FLUSHING;
3158     queue->sinkresult = GST_FLOW_FLUSHING;
3159     /* the item add signal will unblock */
3160     GST_QUEUE2_SIGNAL_ADD (queue);
3161     GST_QUEUE2_MUTEX_UNLOCK (queue);
3162
3163     /* step 2, make sure streaming finishes */
3164     result = gst_pad_stop_task (pad);
3165   }
3166
3167   return result;
3168 }
3169
3170 /* pull mode, downstream will call our getrange function */
3171 static gboolean
3172 gst_queue2_src_activate_pull (GstPad * pad, GstObject * parent, gboolean active)
3173 {
3174   gboolean result;
3175   GstQueue2 *queue;
3176
3177   queue = GST_QUEUE2 (parent);
3178
3179   if (active) {
3180     GST_QUEUE2_MUTEX_LOCK (queue);
3181     if (!QUEUE_IS_USING_QUEUE (queue)) {
3182       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3183         /* open the temp file now */
3184         result = gst_queue2_open_temp_location_file (queue);
3185       } else if (!queue->ring_buffer) {
3186         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
3187         result = ! !queue->ring_buffer;
3188       } else {
3189         result = TRUE;
3190       }
3191
3192       GST_DEBUG_OBJECT (queue, "activating pull mode");
3193       init_ranges (queue);
3194       queue->srcresult = GST_FLOW_OK;
3195       queue->sinkresult = GST_FLOW_OK;
3196       queue->is_eos = FALSE;
3197       queue->unexpected = FALSE;
3198       queue->upstream_size = 0;
3199     } else {
3200       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
3201       /* this is not allowed, we cannot operate in pull mode without a temp
3202        * file. */
3203       queue->srcresult = GST_FLOW_FLUSHING;
3204       queue->sinkresult = GST_FLOW_FLUSHING;
3205       result = FALSE;
3206     }
3207     GST_QUEUE2_MUTEX_UNLOCK (queue);
3208   } else {
3209     GST_QUEUE2_MUTEX_LOCK (queue);
3210     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
3211     queue->srcresult = GST_FLOW_FLUSHING;
3212     queue->sinkresult = GST_FLOW_FLUSHING;
3213     /* this will unlock getrange */
3214     GST_QUEUE2_SIGNAL_ADD (queue);
3215     result = TRUE;
3216     GST_QUEUE2_MUTEX_UNLOCK (queue);
3217   }
3218
3219   return result;
3220 }
3221
3222 static gboolean
3223 gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
3224     gboolean active)
3225 {
3226   gboolean res;
3227
3228   switch (mode) {
3229     case GST_PAD_MODE_PULL:
3230       res = gst_queue2_src_activate_pull (pad, parent, active);
3231       break;
3232     case GST_PAD_MODE_PUSH:
3233       res = gst_queue2_src_activate_push (pad, parent, active);
3234       break;
3235     default:
3236       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
3237       res = FALSE;
3238       break;
3239   }
3240   return res;
3241 }
3242
3243 static GstStateChangeReturn
3244 gst_queue2_change_state (GstElement * element, GstStateChange transition)
3245 {
3246   GstQueue2 *queue;
3247   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3248
3249   queue = GST_QUEUE2 (element);
3250
3251   switch (transition) {
3252     case GST_STATE_CHANGE_NULL_TO_READY:
3253       break;
3254     case GST_STATE_CHANGE_READY_TO_PAUSED:
3255       GST_QUEUE2_MUTEX_LOCK (queue);
3256       if (!QUEUE_IS_USING_QUEUE (queue)) {
3257         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3258           if (!gst_queue2_open_temp_location_file (queue))
3259             ret = GST_STATE_CHANGE_FAILURE;
3260         } else {
3261           if (queue->ring_buffer) {
3262             g_free (queue->ring_buffer);
3263             queue->ring_buffer = NULL;
3264           }
3265           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
3266             ret = GST_STATE_CHANGE_FAILURE;
3267         }
3268         init_ranges (queue);
3269       }
3270       queue->segment_event_received = FALSE;
3271       queue->starting_segment = NULL;
3272       gst_event_replace (&queue->stream_start_event, NULL);
3273       GST_QUEUE2_MUTEX_UNLOCK (queue);
3274       break;
3275     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3276       break;
3277     default:
3278       break;
3279   }
3280
3281   if (ret == GST_STATE_CHANGE_FAILURE)
3282     return ret;
3283
3284   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3285
3286   if (ret == GST_STATE_CHANGE_FAILURE)
3287     return ret;
3288
3289   switch (transition) {
3290     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3291       break;
3292     case GST_STATE_CHANGE_PAUSED_TO_READY:
3293       GST_QUEUE2_MUTEX_LOCK (queue);
3294       if (!QUEUE_IS_USING_QUEUE (queue)) {
3295         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3296           gst_queue2_close_temp_location_file (queue);
3297         } else if (queue->ring_buffer) {
3298           g_free (queue->ring_buffer);
3299           queue->ring_buffer = NULL;
3300         }
3301         clean_ranges (queue);
3302       }
3303       if (queue->starting_segment != NULL) {
3304         gst_event_unref (queue->starting_segment);
3305         queue->starting_segment = NULL;
3306       }
3307       gst_event_replace (&queue->stream_start_event, NULL);
3308       GST_QUEUE2_MUTEX_UNLOCK (queue);
3309       break;
3310     case GST_STATE_CHANGE_READY_TO_NULL:
3311       break;
3312     default:
3313       break;
3314   }
3315
3316   return ret;
3317 }
3318
3319 /* changing the capacity of the queue must wake up
3320  * the _chain function, it might have more room now
3321  * to store the buffer/event in the queue */
3322 #define QUEUE_CAPACITY_CHANGE(q) \
3323   GST_QUEUE2_SIGNAL_DEL (queue); \
3324   if (queue->use_buffering)      \
3325     update_buffering (queue);
3326
3327 /* Changing the minimum required fill level must
3328  * wake up the _loop function as it might now
3329  * be able to preceed.
3330  */
3331 #define QUEUE_THRESHOLD_CHANGE(q)\
3332   GST_QUEUE2_SIGNAL_ADD (queue);
3333
3334 static void
3335 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
3336 {
3337   GstState state;
3338
3339   /* the element must be stopped in order to do this */
3340   GST_OBJECT_LOCK (queue);
3341   state = GST_STATE (queue);
3342   if (state != GST_STATE_READY && state != GST_STATE_NULL)
3343     goto wrong_state;
3344   GST_OBJECT_UNLOCK (queue);
3345
3346   /* set new location */
3347   g_free (queue->temp_template);
3348   queue->temp_template = g_strdup (template);
3349
3350   return;
3351
3352 /* ERROR */
3353 wrong_state:
3354   {
3355     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
3356     GST_OBJECT_UNLOCK (queue);
3357   }
3358 }
3359
3360 static void
3361 gst_queue2_set_property (GObject * object,
3362     guint prop_id, const GValue * value, GParamSpec * pspec)
3363 {
3364   GstQueue2 *queue = GST_QUEUE2 (object);
3365
3366   /* someone could change levels here, and since this
3367    * affects the get/put funcs, we need to lock for safety. */
3368   GST_QUEUE2_MUTEX_LOCK (queue);
3369
3370   switch (prop_id) {
3371     case PROP_MAX_SIZE_BYTES:
3372       queue->max_level.bytes = g_value_get_uint (value);
3373       QUEUE_CAPACITY_CHANGE (queue);
3374       break;
3375     case PROP_MAX_SIZE_BUFFERS:
3376       queue->max_level.buffers = g_value_get_uint (value);
3377       QUEUE_CAPACITY_CHANGE (queue);
3378       break;
3379     case PROP_MAX_SIZE_TIME:
3380       queue->max_level.time = g_value_get_uint64 (value);
3381       /* set rate_time to the same value. We use an extra field in the level
3382        * structure so that we can easily access and compare it */
3383       queue->max_level.rate_time = queue->max_level.time;
3384       QUEUE_CAPACITY_CHANGE (queue);
3385       break;
3386     case PROP_USE_BUFFERING:
3387       queue->use_buffering = g_value_get_boolean (value);
3388       if (!queue->use_buffering && queue->is_buffering) {
3389         GstMessage *msg = gst_message_new_buffering (GST_OBJECT_CAST (queue),
3390             100);
3391
3392         GST_DEBUG_OBJECT (queue, "Disabled buffering while buffering, "
3393             "posting 100%% message");
3394         queue->is_buffering = FALSE;
3395         gst_element_post_message (GST_ELEMENT_CAST (queue), msg);
3396       }
3397       break;
3398     case PROP_USE_RATE_ESTIMATE:
3399       queue->use_rate_estimate = g_value_get_boolean (value);
3400       break;
3401     case PROP_LOW_PERCENT:
3402       queue->low_percent = g_value_get_int (value);
3403       break;
3404     case PROP_HIGH_PERCENT:
3405       queue->high_percent = g_value_get_int (value);
3406       break;
3407     case PROP_TEMP_TEMPLATE:
3408       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3409       break;
3410     case PROP_TEMP_REMOVE:
3411       queue->temp_remove = g_value_get_boolean (value);
3412       break;
3413     case PROP_RING_BUFFER_MAX_SIZE:
3414       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3415       break;
3416     default:
3417       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3418       break;
3419   }
3420
3421   GST_QUEUE2_MUTEX_UNLOCK (queue);
3422 }
3423
3424 static void
3425 gst_queue2_get_property (GObject * object,
3426     guint prop_id, GValue * value, GParamSpec * pspec)
3427 {
3428   GstQueue2 *queue = GST_QUEUE2 (object);
3429
3430   GST_QUEUE2_MUTEX_LOCK (queue);
3431
3432   switch (prop_id) {
3433     case PROP_CUR_LEVEL_BYTES:
3434       g_value_set_uint (value, queue->cur_level.bytes);
3435       break;
3436     case PROP_CUR_LEVEL_BUFFERS:
3437       g_value_set_uint (value, queue->cur_level.buffers);
3438       break;
3439     case PROP_CUR_LEVEL_TIME:
3440       g_value_set_uint64 (value, queue->cur_level.time);
3441       break;
3442     case PROP_MAX_SIZE_BYTES:
3443       g_value_set_uint (value, queue->max_level.bytes);
3444       break;
3445     case PROP_MAX_SIZE_BUFFERS:
3446       g_value_set_uint (value, queue->max_level.buffers);
3447       break;
3448     case PROP_MAX_SIZE_TIME:
3449       g_value_set_uint64 (value, queue->max_level.time);
3450       break;
3451     case PROP_USE_BUFFERING:
3452       g_value_set_boolean (value, queue->use_buffering);
3453       break;
3454     case PROP_USE_RATE_ESTIMATE:
3455       g_value_set_boolean (value, queue->use_rate_estimate);
3456       break;
3457     case PROP_LOW_PERCENT:
3458       g_value_set_int (value, queue->low_percent);
3459       break;
3460     case PROP_HIGH_PERCENT:
3461       g_value_set_int (value, queue->high_percent);
3462       break;
3463     case PROP_TEMP_TEMPLATE:
3464       g_value_set_string (value, queue->temp_template);
3465       break;
3466     case PROP_TEMP_LOCATION:
3467       g_value_set_string (value, queue->temp_location);
3468       break;
3469     case PROP_TEMP_REMOVE:
3470       g_value_set_boolean (value, queue->temp_remove);
3471       break;
3472     case PROP_RING_BUFFER_MAX_SIZE:
3473       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3474       break;
3475     default:
3476       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3477       break;
3478   }
3479
3480   GST_QUEUE2_MUTEX_UNLOCK (queue);
3481 }