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