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