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