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