queue2: signal delete before waiting
[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) && is_sink) {
744       /* start is where we'll be getting from and as such writing next */
745       queue->current = add_range (queue, start);
746     }
747   }
748
749   /* now configure the values, we use these to track timestamps on the
750    * sinkpad. */
751   if (format != GST_FORMAT_TIME) {
752     /* non-time format, pretent the current time segment is closed with a
753      * 0 start and unknown stop time. */
754     update = FALSE;
755     format = GST_FORMAT_TIME;
756     start = 0;
757     stop = -1;
758     time = 0;
759   }
760   gst_segment_set_newsegment_full (segment, update,
761       rate, arate, format, start, stop, time);
762
763   GST_DEBUG_OBJECT (queue,
764       "configured NEWSEGMENT %" GST_SEGMENT_FORMAT, segment);
765
766   if (is_sink)
767     queue->sink_tainted = TRUE;
768   else
769     queue->src_tainted = TRUE;
770
771   /* segment can update the time level of the queue */
772   update_time_level (queue);
773 }
774
775 /* take a buffer and update segment, updating the time level of the queue. */
776 static void
777 apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
778     gboolean is_sink)
779 {
780   GstClockTime duration, timestamp;
781
782   timestamp = GST_BUFFER_TIMESTAMP (buffer);
783   duration = GST_BUFFER_DURATION (buffer);
784
785   /* if no timestamp is set, assume it's continuous with the previous
786    * time */
787   if (timestamp == GST_CLOCK_TIME_NONE)
788     timestamp = segment->last_stop;
789
790   /* add duration */
791   if (duration != GST_CLOCK_TIME_NONE)
792     timestamp += duration;
793
794   GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
795       GST_TIME_ARGS (timestamp));
796
797   gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
798
799   if (is_sink)
800     queue->sink_tainted = TRUE;
801   else
802     queue->src_tainted = TRUE;
803
804   /* calc diff with other end */
805   update_time_level (queue);
806 }
807
808 static GstBufferListItem
809 buffer_list_apply_time (GstBuffer ** buf, guint group, guint idx, gpointer data)
810 {
811   GstClockTime *timestamp = data;
812
813   GST_TRACE ("buffer %u in group %u has ts %" GST_TIME_FORMAT
814       " duration %" GST_TIME_FORMAT, idx, group,
815       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (*buf)),
816       GST_TIME_ARGS (GST_BUFFER_DURATION (*buf)));
817
818   if (GST_BUFFER_TIMESTAMP_IS_VALID (*buf))
819     *timestamp = GST_BUFFER_TIMESTAMP (*buf);
820
821   if (GST_BUFFER_DURATION_IS_VALID (*buf))
822     *timestamp += GST_BUFFER_DURATION (*buf);
823
824   GST_TRACE ("ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (*timestamp));
825   return GST_BUFFER_LIST_CONTINUE;
826 }
827
828 /* take a buffer list and update segment, updating the time level of the queue */
829 static void
830 apply_buffer_list (GstQueue2 * queue, GstBufferList * buffer_list,
831     GstSegment * segment, gboolean is_sink)
832 {
833   GstClockTime timestamp;
834
835   /* if no timestamp is set, assume it's continuous with the previous time */
836   timestamp = segment->last_stop;
837
838   gst_buffer_list_foreach (buffer_list, buffer_list_apply_time, &timestamp);
839
840   GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
841       GST_TIME_ARGS (timestamp));
842
843   gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
844
845   if (is_sink)
846     queue->sink_tainted = TRUE;
847   else
848     queue->src_tainted = TRUE;
849
850   /* calc diff with other end */
851   update_time_level (queue);
852 }
853
854 static void
855 update_buffering (GstQueue2 * queue)
856 {
857   gint64 percent;
858   gboolean post = FALSE;
859
860   if (queue->high_percent <= 0)
861     return;
862
863 #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)
864
865   if (queue->is_eos) {
866     /* on EOS we are always 100% full, we set the var here so that it we can
867      * reuse the logic below to stop buffering */
868     percent = 100;
869     GST_LOG_OBJECT (queue, "we are EOS");
870   } else {
871     /* figure out the percent we are filled, we take the max of all formats. */
872
873     if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
874       percent = GET_PERCENT (bytes, 0);
875     } else {
876       guint64 rb_size = queue->ring_buffer_max_size;
877       percent = GET_PERCENT (bytes, rb_size);
878     }
879     percent = MAX (percent, GET_PERCENT (time, 0));
880     percent = MAX (percent, GET_PERCENT (buffers, 0));
881
882     /* also apply the rate estimate when we need to */
883     if (queue->use_rate_estimate)
884       percent = MAX (percent, GET_PERCENT (rate_time, 0));
885   }
886
887   if (queue->is_buffering) {
888     post = TRUE;
889     /* if we were buffering see if we reached the high watermark */
890     if (percent >= queue->high_percent)
891       queue->is_buffering = FALSE;
892   } else {
893     /* we were not buffering, check if we need to start buffering if we drop
894      * below the low threshold */
895     if (percent < queue->low_percent) {
896       queue->is_buffering = TRUE;
897       queue->buffering_iteration++;
898       post = TRUE;
899     }
900   }
901   if (post) {
902     GstMessage *message;
903     GstBufferingMode mode;
904     gint64 buffering_left = -1;
905
906     /* scale to high percent so that it becomes the 100% mark */
907     percent = percent * 100 / queue->high_percent;
908     /* clip */
909     if (percent > 100)
910       percent = 100;
911
912     if (percent != queue->buffering_percent) {
913       queue->buffering_percent = percent;
914
915       if (!QUEUE_IS_USING_QUEUE (queue)) {
916         GstFormat fmt = GST_FORMAT_BYTES;
917         gint64 duration;
918
919         if (QUEUE_IS_USING_RING_BUFFER (queue))
920           mode = GST_BUFFERING_TIMESHIFT;
921         else
922           mode = GST_BUFFERING_DOWNLOAD;
923
924         if (queue->byte_in_rate > 0) {
925           if (gst_pad_query_peer_duration (queue->sinkpad, &fmt, &duration))
926             buffering_left =
927                 (gdouble) ((duration -
928                     queue->current->writing_pos) * 1000) / queue->byte_in_rate;
929         } else {
930           buffering_left = G_MAXINT64;
931         }
932       } else {
933         mode = GST_BUFFERING_STREAM;
934       }
935
936       GST_DEBUG_OBJECT (queue, "buffering %d percent", (gint) percent);
937       message = gst_message_new_buffering (GST_OBJECT_CAST (queue),
938           (gint) percent);
939       gst_message_set_buffering_stats (message, mode,
940           queue->byte_in_rate, queue->byte_out_rate, buffering_left);
941
942       gst_element_post_message (GST_ELEMENT_CAST (queue), message);
943     }
944   } else {
945     GST_DEBUG_OBJECT (queue, "filled %d percent", (gint) percent);
946   }
947
948 #undef GET_PERCENT
949 }
950
951 static void
952 reset_rate_timer (GstQueue2 * queue)
953 {
954   queue->bytes_in = 0;
955   queue->bytes_out = 0;
956   queue->byte_in_rate = 0.0;
957   queue->byte_in_period = 0;
958   queue->byte_out_rate = 0.0;
959   queue->last_in_elapsed = 0.0;
960   queue->last_out_elapsed = 0.0;
961   queue->in_timer_started = FALSE;
962   queue->out_timer_started = FALSE;
963 }
964
965 /* the interval in seconds to recalculate the rate */
966 #define RATE_INTERVAL    0.2
967 /* Tuning for rate estimation. We use a large window for the input rate because
968  * it should be stable when connected to a network. The output rate is less
969  * stable (the elements preroll, queues behind a demuxer fill, ...) and should
970  * therefore adapt more quickly.
971  * However, initial input rate may be subject to a burst, and should therefore
972  * initially also adapt more quickly to changes, and only later on give higher
973  * weight to previous values. */
974 #define AVG_IN(avg,val,w1,w2)  ((avg) * (w1) + (val) * (w2)) / ((w1) + (w2))
975 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
976
977 static void
978 update_in_rates (GstQueue2 * queue)
979 {
980   gdouble elapsed, period;
981   gdouble byte_in_rate;
982
983   if (!queue->in_timer_started) {
984     queue->in_timer_started = TRUE;
985     g_timer_start (queue->in_timer);
986     return;
987   }
988
989   elapsed = g_timer_elapsed (queue->in_timer, NULL);
990
991   /* recalc after each interval. */
992   if (queue->last_in_elapsed + RATE_INTERVAL < elapsed) {
993     period = elapsed - queue->last_in_elapsed;
994
995     GST_DEBUG_OBJECT (queue,
996         "rates: period %f, in %" G_GUINT64_FORMAT ", global period %f",
997         period, queue->bytes_in, queue->byte_in_period);
998
999     byte_in_rate = queue->bytes_in / period;
1000
1001     if (queue->byte_in_rate == 0.0)
1002       queue->byte_in_rate = byte_in_rate;
1003     else
1004       queue->byte_in_rate = AVG_IN (queue->byte_in_rate, byte_in_rate,
1005           (double) queue->byte_in_period, period);
1006
1007     /* another data point, cap at 16 for long time running average */
1008     if (queue->byte_in_period < 16 * RATE_INTERVAL)
1009       queue->byte_in_period += period;
1010
1011     /* reset the values to calculate rate over the next interval */
1012     queue->last_in_elapsed = elapsed;
1013     queue->bytes_in = 0;
1014   }
1015
1016   if (queue->byte_in_rate > 0.0) {
1017     queue->cur_level.rate_time =
1018         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1019   }
1020   GST_DEBUG_OBJECT (queue, "rates: in %f, time %" GST_TIME_FORMAT,
1021       queue->byte_in_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1022 }
1023
1024 static void
1025 update_out_rates (GstQueue2 * queue)
1026 {
1027   gdouble elapsed, period;
1028   gdouble byte_out_rate;
1029
1030   if (!queue->out_timer_started) {
1031     queue->out_timer_started = TRUE;
1032     g_timer_start (queue->out_timer);
1033     return;
1034   }
1035
1036   elapsed = g_timer_elapsed (queue->out_timer, NULL);
1037
1038   /* recalc after each interval. */
1039   if (queue->last_out_elapsed + RATE_INTERVAL < elapsed) {
1040     period = elapsed - queue->last_out_elapsed;
1041
1042     GST_DEBUG_OBJECT (queue,
1043         "rates: period %f, out %" G_GUINT64_FORMAT, period, queue->bytes_out);
1044
1045     byte_out_rate = queue->bytes_out / period;
1046
1047     if (queue->byte_out_rate == 0.0)
1048       queue->byte_out_rate = byte_out_rate;
1049     else
1050       queue->byte_out_rate = AVG_OUT (queue->byte_out_rate, byte_out_rate);
1051
1052     /* reset the values to calculate rate over the next interval */
1053     queue->last_out_elapsed = elapsed;
1054     queue->bytes_out = 0;
1055   }
1056   if (queue->byte_in_rate > 0.0) {
1057     queue->cur_level.rate_time =
1058         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1059   }
1060   GST_DEBUG_OBJECT (queue, "rates: out %f, time %" GST_TIME_FORMAT,
1061       queue->byte_out_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1062 }
1063
1064 static void
1065 update_cur_pos (GstQueue2 * queue, GstQueue2Range * range, guint64 pos)
1066 {
1067   guint64 reading_pos, max_reading_pos;
1068
1069   reading_pos = pos;
1070   max_reading_pos = range->max_reading_pos;
1071
1072   max_reading_pos = MAX (max_reading_pos, reading_pos);
1073
1074   GST_DEBUG_OBJECT (queue,
1075       "updating max_reading_pos from %" G_GUINT64_FORMAT " to %"
1076       G_GUINT64_FORMAT, range->max_reading_pos, max_reading_pos);
1077   range->max_reading_pos = max_reading_pos;
1078
1079   update_cur_level (queue, range);
1080 }
1081
1082 static gboolean
1083 perform_seek_to_offset (GstQueue2 * queue, guint64 offset)
1084 {
1085   GstEvent *event;
1086   gboolean res;
1087
1088   /* until we receive the FLUSH_STOP from this seek, we skip data */
1089   queue->seeking = TRUE;
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   res = gst_pad_push_event (queue->sinkpad, event);
1100   GST_QUEUE2_MUTEX_LOCK (queue);
1101
1102   if (res)
1103     queue->current = add_range (queue, offset);
1104
1105   return res;
1106 }
1107
1108 /* see if there is enough data in the file to read a full buffer */
1109 static gboolean
1110 gst_queue2_have_data (GstQueue2 * queue, guint64 offset, guint length)
1111 {
1112   GstQueue2Range *range;
1113
1114   GST_DEBUG_OBJECT (queue, "looking for offset %" G_GUINT64_FORMAT ", len %u",
1115       offset, length);
1116
1117   if ((range = find_range (queue, offset))) {
1118     if (queue->current != range) {
1119       GST_DEBUG_OBJECT (queue, "switching ranges, do seek to range position");
1120       perform_seek_to_offset (queue, range->writing_pos);
1121     }
1122
1123     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1124         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1125
1126     /* we have a range for offset */
1127     GST_DEBUG_OBJECT (queue,
1128         "we have a range %p, offset %" G_GUINT64_FORMAT ", writing_pos %"
1129         G_GUINT64_FORMAT, range, range->offset, range->writing_pos);
1130
1131     if (!QUEUE_IS_USING_RING_BUFFER (queue) && queue->is_eos)
1132       return TRUE;
1133
1134     if (offset + length <= range->writing_pos)
1135       return TRUE;
1136     else
1137       GST_DEBUG_OBJECT (queue,
1138           "Need more data (%" G_GUINT64_FORMAT " bytes more)",
1139           (offset + length) - range->writing_pos);
1140
1141   } else {
1142     GST_INFO_OBJECT (queue, "not found in any range off %" G_GUINT64_FORMAT
1143         " len %u", offset, length);
1144     /* we don't have the range, see how far away we are */
1145     if (!queue->is_eos && queue->current) {
1146       /* FIXME, find a good threshold based on the incoming rate. */
1147       guint64 threshold = 1024 * 512;
1148
1149       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1150         guint64 distance;
1151
1152         distance = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1153         /* don't wait for the complete buffer to fill */
1154         distance = MIN (distance, threshold);
1155
1156         if (offset >= queue->current->offset && offset <=
1157             queue->current->writing_pos + distance) {
1158           GST_INFO_OBJECT (queue,
1159               "requested data is within range, wait for data");
1160           return FALSE;
1161         }
1162       } else if (offset < queue->current->writing_pos + threshold) {
1163         update_cur_pos (queue, queue->current, offset + length);
1164         GST_INFO_OBJECT (queue, "wait for data");
1165         return FALSE;
1166       }
1167     }
1168
1169     /* too far away, do a seek */
1170     perform_seek_to_offset (queue, offset);
1171   }
1172
1173   return FALSE;
1174 }
1175
1176 #ifdef HAVE_FSEEKO
1177 #define FSEEK_FILE(file,offset)  (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1178 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1179 #define FSEEK_FILE(file,offset)  (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1180 #else
1181 #define FSEEK_FILE(file,offset)  (fseek (file, offset, SEEK_SET) != 0)
1182 #endif
1183
1184 static gint64
1185 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1186     guint8 * dst)
1187 {
1188   guint8 *ring_buffer;
1189   size_t res;
1190
1191   ring_buffer = queue->ring_buffer;
1192
1193   if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1194     goto seek_failed;
1195
1196   /* this should not block */
1197   GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1198       length, offset);
1199   if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1200     res = fread (dst, 1, length, queue->temp_file);
1201   } else {
1202     memcpy (dst, ring_buffer + offset, length);
1203     res = length;
1204   }
1205
1206   GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1207
1208   if (G_UNLIKELY (res < length)) {
1209     if (!QUEUE_IS_USING_TEMP_FILE (queue))
1210       goto could_not_read;
1211     /* check for errors or EOF */
1212     if (ferror (queue->temp_file))
1213       goto could_not_read;
1214     if (feof (queue->temp_file) && length > 0)
1215       goto eos;
1216   }
1217
1218   return res;
1219
1220 seek_failed:
1221   {
1222     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1223     return GST_FLOW_ERROR;
1224   }
1225 could_not_read:
1226   {
1227     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1228     return GST_FLOW_ERROR;
1229   }
1230 eos:
1231   {
1232     GST_DEBUG ("non-regular file hits EOS");
1233     return GST_FLOW_UNEXPECTED;
1234   }
1235 }
1236
1237 static GstFlowReturn
1238 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1239     GstBuffer ** buffer)
1240 {
1241   GstBuffer *buf;
1242   guint8 *data;
1243   guint64 file_offset;
1244   guint block_length, remaining, read_length;
1245   gint64 read_return;
1246   guint64 rb_size;
1247   guint64 max_size;
1248   guint64 rpos;
1249
1250   /* allocate the output buffer of the requested size */
1251   buf = gst_buffer_new_and_alloc (length);
1252   data = GST_BUFFER_DATA (buf);
1253
1254   GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1255       offset);
1256
1257   rpos = offset;
1258   rb_size = queue->ring_buffer_max_size;
1259   max_size = QUEUE_MAX_BYTES (queue);
1260
1261   remaining = length;
1262   while (remaining > 0) {
1263     /* configure how much/whether to read */
1264     if (!gst_queue2_have_data (queue, rpos, remaining)) {
1265       read_length = 0;
1266
1267       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1268         guint64 level;
1269
1270         /* calculate how far away the offset is */
1271         if (queue->current->writing_pos > rpos)
1272           level = queue->current->writing_pos - rpos;
1273         else
1274           level = 0;
1275
1276         GST_DEBUG_OBJECT (queue,
1277             "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1278             ", level %" G_GUINT64_FORMAT ", max %" G_GUINT64_FORMAT,
1279             rpos, queue->current->writing_pos, level, max_size);
1280
1281         if (level >= max_size) {
1282           /* we don't have the data but if we have a ring buffer that is full, we
1283            * need to read */
1284           GST_DEBUG_OBJECT (queue,
1285               "ring buffer full, reading QUEUE_MAX_BYTES %"
1286               G_GUINT64_FORMAT " bytes", max_size);
1287           read_length = max_size;
1288         } else if (queue->is_eos) {
1289           /* won't get any more data so read any data we have */
1290           if (level) {
1291             GST_DEBUG_OBJECT (queue,
1292                 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1293                 level);
1294             read_length = level;
1295             remaining = level;
1296             length = level;
1297           } else {
1298             GST_DEBUG_OBJECT (queue,
1299                 "EOS hit and we don't have any requested data");
1300             gst_buffer_unref (buf);
1301             return GST_FLOW_UNEXPECTED;
1302           }
1303         }
1304       }
1305
1306       if (read_length == 0) {
1307         if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1308           GST_DEBUG_OBJECT (queue,
1309               "update current position [%" G_GUINT64_FORMAT "-%"
1310               G_GUINT64_FORMAT "]", rpos, queue->current->max_reading_pos);
1311           update_cur_pos (queue, queue->current, rpos);
1312           GST_QUEUE2_SIGNAL_DEL (queue);
1313         }
1314         GST_DEBUG_OBJECT (queue, "waiting for add");
1315         GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1316         continue;
1317       }
1318     } else {
1319       /* we have the requested data so read it */
1320       read_length = remaining;
1321     }
1322
1323     /* set range reading_pos to actual reading position for this read */
1324     queue->current->reading_pos = rpos;
1325
1326     /* configure how much and from where to read */
1327     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1328       file_offset =
1329           (queue->current->rb_offset + (rpos -
1330               queue->current->offset)) % rb_size;
1331       if (file_offset + read_length > rb_size) {
1332         block_length = rb_size - file_offset;
1333       } else {
1334         block_length = read_length;
1335       }
1336     } else {
1337       file_offset = rpos;
1338       block_length = read_length;
1339     }
1340
1341     /* while we still have data to read, we loop */
1342     while (read_length > 0) {
1343       read_return =
1344           gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1345           data);
1346       if (read_return < 0)
1347         goto read_error;
1348
1349       file_offset += read_return;
1350       if (QUEUE_IS_USING_RING_BUFFER (queue))
1351         file_offset %= rb_size;
1352
1353       data += read_return;
1354       read_length -= read_return;
1355       block_length = read_length;
1356       remaining -= read_return;
1357
1358       rpos = (queue->current->reading_pos += read_return);
1359       update_cur_pos (queue, queue->current, queue->current->reading_pos);
1360     }
1361     GST_QUEUE2_SIGNAL_DEL (queue);
1362     GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1363   }
1364
1365   GST_BUFFER_SIZE (buf) = length;
1366   GST_BUFFER_OFFSET (buf) = offset;
1367   GST_BUFFER_OFFSET_END (buf) = offset + length;
1368
1369   *buffer = buf;
1370
1371   return GST_FLOW_OK;
1372
1373   /* ERRORS */
1374 out_flushing:
1375   {
1376     GST_DEBUG_OBJECT (queue, "we are flushing");
1377     gst_buffer_unref (buf);
1378     return GST_FLOW_WRONG_STATE;
1379   }
1380 read_error:
1381   {
1382     GST_DEBUG_OBJECT (queue, "we have a read error");
1383     gst_buffer_unref (buf);
1384     return read_return;
1385   }
1386 }
1387
1388 /* should be called with QUEUE_LOCK */
1389 static GstMiniObject *
1390 gst_queue2_read_item_from_file (GstQueue2 * queue)
1391 {
1392   GstMiniObject *item;
1393
1394   if (queue->starting_segment != NULL) {
1395     item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1396     queue->starting_segment = NULL;
1397   } else {
1398     GstFlowReturn ret;
1399     GstBuffer *buffer;
1400     guint64 reading_pos;
1401
1402     reading_pos = queue->current->reading_pos;
1403
1404     ret =
1405         gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1406         &buffer);
1407
1408     switch (ret) {
1409       case GST_FLOW_OK:
1410         item = GST_MINI_OBJECT_CAST (buffer);
1411         break;
1412       case GST_FLOW_UNEXPECTED:
1413         item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1414         break;
1415       default:
1416         item = NULL;
1417         break;
1418     }
1419   }
1420   return item;
1421 }
1422
1423 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1424  * the temp filename. */
1425 static gboolean
1426 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1427 {
1428   gint fd = -1;
1429   gchar *name = NULL;
1430
1431   if (queue->temp_file)
1432     goto already_opened;
1433
1434   GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1435
1436   /* we have two cases:
1437    * - temp_location was set to something !NULL (Deprecated). in this case we
1438    *   open the specified filename.
1439    * - temp_template was set, allocate a filename and open that filename
1440    */
1441   if (!queue->temp_location_set) {
1442     /* nothing to do */
1443     if (queue->temp_template == NULL)
1444       goto no_directory;
1445
1446     /* make copy of the template, we don't want to change this */
1447     name = g_strdup (queue->temp_template);
1448     fd = g_mkstemp (name);
1449     if (fd == -1)
1450       goto mkstemp_failed;
1451
1452     /* open the file for update/writing */
1453     queue->temp_file = fdopen (fd, "wb+");
1454     /* error creating file */
1455     if (queue->temp_file == NULL)
1456       goto open_failed;
1457
1458     g_free (queue->temp_location);
1459     queue->temp_location = name;
1460
1461     GST_QUEUE2_MUTEX_UNLOCK (queue);
1462
1463     /* we can't emit the notify with the lock */
1464     g_object_notify (G_OBJECT (queue), "temp-location");
1465
1466     GST_QUEUE2_MUTEX_LOCK (queue);
1467   } else {
1468     /* open the file for update/writing, this is deprecated but we still need to
1469      * support it for API/ABI compatibility */
1470     queue->temp_file = g_fopen (queue->temp_location, "wb+");
1471     /* error creating file */
1472     if (queue->temp_file == NULL)
1473       goto open_failed;
1474   }
1475   GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1476
1477   return TRUE;
1478
1479   /* ERRORS */
1480 already_opened:
1481   {
1482     GST_DEBUG_OBJECT (queue, "temp file was already open");
1483     return TRUE;
1484   }
1485 no_directory:
1486   {
1487     GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1488         (_("No Temp directory specified.")), (NULL));
1489     return FALSE;
1490   }
1491 mkstemp_failed:
1492   {
1493     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1494         (_("Could not create temp file \"%s\"."), queue->temp_template),
1495         GST_ERROR_SYSTEM);
1496     g_free (name);
1497     return FALSE;
1498   }
1499 open_failed:
1500   {
1501     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1502         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1503     g_free (name);
1504     if (fd != -1)
1505       close (fd);
1506     return FALSE;
1507   }
1508 }
1509
1510 static void
1511 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1512 {
1513   /* nothing to do */
1514   if (queue->temp_file == NULL)
1515     return;
1516
1517   GST_DEBUG_OBJECT (queue, "closing temp file");
1518
1519   fflush (queue->temp_file);
1520   fclose (queue->temp_file);
1521
1522   if (queue->temp_remove)
1523     remove (queue->temp_location);
1524
1525   queue->temp_file = NULL;
1526   clean_ranges (queue);
1527 }
1528
1529 static void
1530 gst_queue2_flush_temp_file (GstQueue2 * queue)
1531 {
1532   if (queue->temp_file == NULL)
1533     return;
1534
1535   GST_DEBUG_OBJECT (queue, "flushing temp file");
1536
1537   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1538 }
1539
1540 static void
1541 gst_queue2_locked_flush (GstQueue2 * queue)
1542 {
1543   if (!QUEUE_IS_USING_QUEUE (queue)) {
1544     if (QUEUE_IS_USING_TEMP_FILE (queue))
1545       gst_queue2_flush_temp_file (queue);
1546     init_ranges (queue);
1547   } else {
1548     while (!g_queue_is_empty (&queue->queue)) {
1549       GstMiniObject *data = g_queue_pop_head (&queue->queue);
1550
1551       /* Then lose another reference because we are supposed to destroy that
1552          data when flushing */
1553       gst_mini_object_unref (data);
1554     }
1555   }
1556   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1557   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1558   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1559   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1560   queue->sink_tainted = queue->src_tainted = TRUE;
1561   if (queue->starting_segment != NULL)
1562     gst_event_unref (queue->starting_segment);
1563   queue->starting_segment = NULL;
1564   queue->segment_event_received = FALSE;
1565
1566   /* we deleted a lot of something */
1567   GST_QUEUE2_SIGNAL_DEL (queue);
1568 }
1569
1570 static gboolean
1571 gst_queue2_wait_free_space (GstQueue2 * queue)
1572 {
1573   /* We make space available if we're "full" according to whatever
1574    * the user defined as "full". */
1575   if (gst_queue2_is_filled (queue)) {
1576     gboolean started;
1577
1578     /* pause the timer while we wait. The fact that we are waiting does not mean
1579      * the byterate on the input pad is lower */
1580     if ((started = queue->in_timer_started))
1581       g_timer_stop (queue->in_timer);
1582
1583     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1584         "queue is full, waiting for free space");
1585     do {
1586       /* Wait for space to be available, we could be unlocked because of a flush. */
1587       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1588     }
1589     while (gst_queue2_is_filled (queue));
1590
1591     /* and continue if we were running before */
1592     if (started)
1593       g_timer_continue (queue->in_timer);
1594   }
1595   return TRUE;
1596
1597   /* ERRORS */
1598 out_flushing:
1599   {
1600     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1601     return FALSE;
1602   }
1603 }
1604
1605 static gboolean
1606 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1607 {
1608   guint8 *data, *ring_buffer;
1609   guint size, rb_size;
1610   guint64 writing_pos, new_writing_pos;
1611   GstQueue2Range *range, *prev, *next;
1612
1613   if (QUEUE_IS_USING_RING_BUFFER (queue))
1614     writing_pos = queue->current->rb_writing_pos;
1615   else
1616     writing_pos = queue->current->writing_pos;
1617   ring_buffer = queue->ring_buffer;
1618   rb_size = queue->ring_buffer_max_size;
1619
1620   size = GST_BUFFER_SIZE (buffer);
1621   data = GST_BUFFER_DATA (buffer);
1622
1623   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1624       writing_pos);
1625
1626   while (size > 0) {
1627     guint to_write;
1628
1629     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1630       gint64 space;
1631
1632       /* calculate the space in the ring buffer not used by data from
1633        * the current range */
1634       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1635         /* wait until there is some free space */
1636         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1637       }
1638       /* get the amount of space we have */
1639       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1640
1641       /* calculate if we need to split or if we can write the entire
1642        * buffer now */
1643       to_write = MIN (size, space);
1644
1645       /* the writing position in the ring buffer after writing (part
1646        * or all of) the buffer */
1647       new_writing_pos = (writing_pos + to_write) % rb_size;
1648
1649       prev = NULL;
1650       range = queue->ranges;
1651
1652       /* if we need to overwrite data in the ring buffer, we need to
1653        * update the ranges
1654        *
1655        * warning: this code is complicated and includes some
1656        * simplifications - pen, paper and diagrams for the cases
1657        * recommended! */
1658       while (range) {
1659         guint64 range_data_start, range_data_end;
1660         GstQueue2Range *range_to_destroy = NULL;
1661
1662         range_data_start = range->rb_offset;
1663         range_data_end = range->rb_writing_pos;
1664
1665         /* handle the special case where the range has no data in it */
1666         if (range->writing_pos == range->offset) {
1667           if (range != queue->current) {
1668             GST_DEBUG_OBJECT (queue,
1669                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1670                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1671             /* remove range */
1672             range_to_destroy = range;
1673             if (prev)
1674               prev->next = range->next;
1675           }
1676           goto next_range;
1677         }
1678
1679         if (range_data_end > range_data_start) {
1680           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1681             goto next_range;
1682
1683           if (new_writing_pos > range_data_start) {
1684             if (new_writing_pos >= range_data_end) {
1685               GST_DEBUG_OBJECT (queue,
1686                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1687                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1688               /* remove range */
1689               range_to_destroy = range;
1690               if (prev)
1691                 prev->next = range->next;
1692             } else {
1693               GST_DEBUG_OBJECT (queue,
1694                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1695                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1696                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1697                   range->offset + new_writing_pos - range_data_start,
1698                   new_writing_pos);
1699               range->offset += (new_writing_pos - range_data_start);
1700               range->rb_offset = new_writing_pos;
1701             }
1702           }
1703         } else {
1704           guint64 new_wpos_virt = writing_pos + to_write;
1705
1706           if (new_wpos_virt <= range_data_start)
1707             goto next_range;
1708
1709           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1710             GST_DEBUG_OBJECT (queue,
1711                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1712                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1713             /* remove range */
1714             range_to_destroy = range;
1715             if (prev)
1716               prev->next = range->next;
1717           } else {
1718             GST_DEBUG_OBJECT (queue,
1719                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1720                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1721                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1722                 range->offset + new_writing_pos - range_data_start,
1723                 new_writing_pos);
1724             range->offset += (new_wpos_virt - range_data_start);
1725             range->rb_offset = new_writing_pos;
1726           }
1727         }
1728
1729       next_range:
1730         if (!range_to_destroy)
1731           prev = range;
1732
1733         range = range->next;
1734         if (range_to_destroy) {
1735           if (range_to_destroy == queue->ranges)
1736             queue->ranges = range;
1737           g_slice_free (GstQueue2Range, range_to_destroy);
1738           range_to_destroy = NULL;
1739         }
1740       }
1741     } else {
1742       to_write = size;
1743       new_writing_pos = writing_pos + to_write;
1744     }
1745
1746     if (QUEUE_IS_USING_TEMP_FILE (queue)
1747         && FSEEK_FILE (queue->temp_file, writing_pos))
1748       goto seek_failed;
1749
1750     if (new_writing_pos > writing_pos) {
1751       GST_INFO_OBJECT (queue,
1752           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1753           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1754           queue->current->writing_pos, queue->current->rb_writing_pos);
1755       /* either not using ring buffer or no wrapping, just write */
1756       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1757         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1758           goto handle_error;
1759       } else {
1760         memcpy (ring_buffer + writing_pos, data, to_write);
1761       }
1762
1763       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1764         /* try to merge with next range */
1765         while ((next = queue->current->next)) {
1766           GST_INFO_OBJECT (queue,
1767               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1768               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1769           if (new_writing_pos < next->offset)
1770             break;
1771
1772           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1773               next->writing_pos);
1774
1775           /* remove the group, we could choose to not read the data in this range
1776            * again. This would involve us doing a seek to the current writing position
1777            * in the range. FIXME, It would probably make sense to do a seek when there
1778            * is a lot of data in the range we merged with to avoid reading it all
1779            * again. */
1780           queue->current->next = next->next;
1781           g_slice_free (GstQueue2Range, next);
1782
1783           debug_ranges (queue);
1784         }
1785         goto update_and_signal;
1786       }
1787     } else {
1788       /* wrapping */
1789       guint block_one, block_two;
1790
1791       block_one = rb_size - writing_pos;
1792       block_two = to_write - block_one;
1793
1794       if (block_one > 0) {
1795         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1796         /* write data to end of ring buffer */
1797         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1798           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1799             goto handle_error;
1800         } else {
1801           memcpy (ring_buffer + writing_pos, data, block_one);
1802         }
1803       }
1804
1805       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1806         goto seek_failed;
1807
1808       if (block_two > 0) {
1809         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
1810         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1811           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
1812             goto handle_error;
1813         } else {
1814           memcpy (ring_buffer, data + block_one, block_two);
1815         }
1816       }
1817     }
1818
1819   update_and_signal:
1820     /* update the writing positions */
1821     size -= to_write;
1822     GST_INFO_OBJECT (queue,
1823         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
1824         to_write, writing_pos, size);
1825
1826     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1827       data += to_write;
1828       queue->current->writing_pos += to_write;
1829       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
1830     } else {
1831       queue->current->writing_pos = writing_pos = new_writing_pos;
1832     }
1833     update_cur_level (queue, queue->current);
1834
1835     /* update the buffering status */
1836     if (queue->use_buffering)
1837       update_buffering (queue);
1838
1839     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1840         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1841
1842     GST_QUEUE2_SIGNAL_ADD (queue);
1843   };
1844
1845   return TRUE;
1846
1847   /* ERRORS */
1848 out_flushing:
1849   {
1850     GST_DEBUG_OBJECT (queue, "we are flushing");
1851     /* FIXME - GST_FLOW_UNEXPECTED ? */
1852     return FALSE;
1853   }
1854 seek_failed:
1855   {
1856     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1857     return FALSE;
1858   }
1859 handle_error:
1860   {
1861     switch (errno) {
1862       case ENOSPC:{
1863         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
1864         break;
1865       }
1866       default:{
1867         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
1868             (_("Error while writing to download file.")),
1869             ("%s", g_strerror (errno)));
1870       }
1871     }
1872     return FALSE;
1873   }
1874 }
1875
1876 static GstBufferListItem
1877 buffer_list_create_write (GstBuffer ** buf, guint group, guint idx, gpointer q)
1878 {
1879   GstQueue2 *queue = q;
1880
1881   GST_TRACE_OBJECT (queue, "writing buffer %u in group %u of size %u bytes",
1882       idx, group, GST_BUFFER_SIZE (*buf));
1883
1884   if (!gst_queue2_create_write (queue, *buf)) {
1885     GST_INFO_OBJECT (queue, "create_write() returned FALSE, bailing out");
1886     return GST_BUFFER_LIST_END;
1887   }
1888
1889   return GST_BUFFER_LIST_CONTINUE;
1890 }
1891
1892 static GstBufferListItem
1893 buffer_list_calc_size (GstBuffer ** buf, guint group, guint idx, gpointer data)
1894 {
1895   guint *p_size = data;
1896   guint buf_size;
1897
1898   buf_size = GST_BUFFER_SIZE (*buf);
1899   GST_TRACE ("buffer %u in group %u has size %u", idx, group, buf_size);
1900   *p_size += buf_size;
1901
1902   return GST_BUFFER_LIST_CONTINUE;
1903 }
1904
1905 /* enqueue an item an update the level stats */
1906 static void
1907 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item,
1908     GstQueue2ItemType item_type)
1909 {
1910   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
1911     GstBuffer *buffer;
1912     guint size;
1913
1914     buffer = GST_BUFFER_CAST (item);
1915     size = GST_BUFFER_SIZE (buffer);
1916
1917     /* add buffer to the statistics */
1918     if (QUEUE_IS_USING_QUEUE (queue)) {
1919       queue->cur_level.buffers++;
1920       queue->cur_level.bytes += size;
1921     }
1922     queue->bytes_in += size;
1923
1924     /* apply new buffer to segment stats */
1925     apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
1926     /* update the byterate stats */
1927     update_in_rates (queue);
1928
1929     if (!QUEUE_IS_USING_QUEUE (queue)) {
1930       /* FIXME - check return value? */
1931       gst_queue2_create_write (queue, buffer);
1932     }
1933   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
1934     GstBufferList *buffer_list;
1935     guint size = 0;
1936
1937     buffer_list = GST_BUFFER_LIST_CAST (item);
1938
1939     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
1940     GST_LOG_OBJECT (queue, "total size of buffer list: %u bytes", size);
1941
1942     /* add buffer to the statistics */
1943     if (QUEUE_IS_USING_QUEUE (queue)) {
1944       queue->cur_level.buffers++;
1945       queue->cur_level.bytes += size;
1946     }
1947     queue->bytes_in += size;
1948
1949     /* apply new buffer to segment stats */
1950     apply_buffer_list (queue, buffer_list, &queue->sink_segment, TRUE);
1951
1952     /* update the byterate stats */
1953     update_in_rates (queue);
1954
1955     if (!QUEUE_IS_USING_QUEUE (queue)) {
1956       gst_buffer_list_foreach (buffer_list, buffer_list_create_write, queue);
1957     }
1958   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
1959     GstEvent *event;
1960
1961     event = GST_EVENT_CAST (item);
1962
1963     switch (GST_EVENT_TYPE (event)) {
1964       case GST_EVENT_EOS:
1965         /* Zero the thresholds, this makes sure the queue is completely
1966          * filled and we can read all data from the queue. */
1967         GST_DEBUG_OBJECT (queue, "we have EOS");
1968         queue->is_eos = TRUE;
1969         break;
1970       case GST_EVENT_NEWSEGMENT:
1971         apply_segment (queue, event, &queue->sink_segment, TRUE);
1972         /* This is our first new segment, we hold it
1973          * as we can't save it on the temp file */
1974         if (!QUEUE_IS_USING_QUEUE (queue)) {
1975           if (queue->segment_event_received)
1976             goto unexpected_event;
1977
1978           queue->segment_event_received = TRUE;
1979           if (queue->starting_segment != NULL)
1980             gst_event_unref (queue->starting_segment);
1981           queue->starting_segment = event;
1982           item = NULL;
1983         }
1984         /* a new segment allows us to accept more buffers if we got UNEXPECTED
1985          * from downstream */
1986         queue->unexpected = FALSE;
1987         break;
1988       default:
1989         if (!QUEUE_IS_USING_QUEUE (queue))
1990           goto unexpected_event;
1991         break;
1992     }
1993   } else {
1994     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
1995         item, GST_OBJECT_NAME (queue));
1996     /* we can't really unref since we don't know what it is */
1997     item = NULL;
1998   }
1999
2000   if (item) {
2001     /* update the buffering status */
2002     if (queue->use_buffering)
2003       update_buffering (queue);
2004
2005     if (QUEUE_IS_USING_QUEUE (queue)) {
2006       g_queue_push_tail (&queue->queue, item);
2007     } else {
2008       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
2009     }
2010
2011     GST_QUEUE2_SIGNAL_ADD (queue);
2012   }
2013
2014   return;
2015
2016   /* ERRORS */
2017 unexpected_event:
2018   {
2019     g_warning
2020         ("Unexpected event of kind %s can't be added in temp file of queue %s ",
2021         gst_event_type_get_name (GST_EVENT_TYPE (item)),
2022         GST_OBJECT_NAME (queue));
2023     gst_event_unref (GST_EVENT_CAST (item));
2024     return;
2025   }
2026 }
2027
2028 /* dequeue an item from the queue and update level stats */
2029 static GstMiniObject *
2030 gst_queue2_locked_dequeue (GstQueue2 * queue, GstQueue2ItemType * item_type)
2031 {
2032   GstMiniObject *item;
2033
2034   if (!QUEUE_IS_USING_QUEUE (queue))
2035     item = gst_queue2_read_item_from_file (queue);
2036   else
2037     item = g_queue_pop_head (&queue->queue);
2038
2039   if (item == NULL)
2040     goto no_item;
2041
2042   if (GST_IS_BUFFER (item)) {
2043     GstBuffer *buffer;
2044     guint size;
2045
2046     buffer = GST_BUFFER_CAST (item);
2047     size = GST_BUFFER_SIZE (buffer);
2048     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER;
2049
2050     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2051         "retrieved buffer %p from queue", buffer);
2052
2053     if (QUEUE_IS_USING_QUEUE (queue)) {
2054       queue->cur_level.buffers--;
2055       queue->cur_level.bytes -= size;
2056     }
2057     queue->bytes_out += size;
2058
2059     apply_buffer (queue, buffer, &queue->src_segment, FALSE);
2060     /* update the byterate stats */
2061     update_out_rates (queue);
2062     /* update the buffering */
2063     if (queue->use_buffering)
2064       update_buffering (queue);
2065
2066   } else if (GST_IS_EVENT (item)) {
2067     GstEvent *event = GST_EVENT_CAST (item);
2068
2069     *item_type = GST_QUEUE2_ITEM_TYPE_EVENT;
2070
2071     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2072         "retrieved event %p from queue", event);
2073
2074     switch (GST_EVENT_TYPE (event)) {
2075       case GST_EVENT_EOS:
2076         /* queue is empty now that we dequeued the EOS */
2077         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
2078         break;
2079       case GST_EVENT_NEWSEGMENT:
2080         apply_segment (queue, event, &queue->src_segment, FALSE);
2081         break;
2082       default:
2083         break;
2084     }
2085   } else if (GST_IS_BUFFER_LIST (item)) {
2086     GstBufferList *buffer_list;
2087     guint size = 0;
2088
2089     buffer_list = GST_BUFFER_LIST_CAST (item);
2090     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2091     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER_LIST;
2092
2093     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2094         "retrieved buffer list %p from queue", buffer_list);
2095
2096     if (QUEUE_IS_USING_QUEUE (queue)) {
2097       queue->cur_level.buffers--;
2098       queue->cur_level.bytes -= size;
2099     }
2100     queue->bytes_out += size;
2101
2102     apply_buffer_list (queue, buffer_list, &queue->src_segment, FALSE);
2103     /* update the byterate stats */
2104     update_out_rates (queue);
2105     /* update the buffering */
2106     if (queue->use_buffering)
2107       update_buffering (queue);
2108
2109   } else {
2110     g_warning
2111         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
2112         item, GST_OBJECT_NAME (queue));
2113     item = NULL;
2114     *item_type = GST_QUEUE2_ITEM_TYPE_UNKNOWN;
2115   }
2116   GST_QUEUE2_SIGNAL_DEL (queue);
2117
2118   return item;
2119
2120   /* ERRORS */
2121 no_item:
2122   {
2123     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
2124     return NULL;
2125   }
2126 }
2127
2128 static gboolean
2129 gst_queue2_handle_sink_event (GstPad * pad, GstEvent * event)
2130 {
2131   GstQueue2 *queue;
2132
2133   queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
2134
2135   switch (GST_EVENT_TYPE (event)) {
2136     case GST_EVENT_FLUSH_START:
2137     {
2138       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
2139       if (queue->srcpad->mode == GST_ACTIVATE_PUSH) {
2140         /* forward event */
2141         gst_pad_push_event (queue->srcpad, event);
2142
2143         /* now unblock the chain function */
2144         GST_QUEUE2_MUTEX_LOCK (queue);
2145         queue->srcresult = GST_FLOW_WRONG_STATE;
2146         queue->sinkresult = GST_FLOW_WRONG_STATE;
2147         /* unblock the loop and chain functions */
2148         GST_QUEUE2_SIGNAL_ADD (queue);
2149         GST_QUEUE2_SIGNAL_DEL (queue);
2150         GST_QUEUE2_MUTEX_UNLOCK (queue);
2151
2152         /* make sure it pauses, this should happen since we sent
2153          * flush_start downstream. */
2154         gst_pad_pause_task (queue->srcpad);
2155         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
2156       } else {
2157         GST_QUEUE2_MUTEX_LOCK (queue);
2158         /* flush the sink pad */
2159         queue->sinkresult = GST_FLOW_WRONG_STATE;
2160         GST_QUEUE2_SIGNAL_DEL (queue);
2161         GST_QUEUE2_MUTEX_UNLOCK (queue);
2162
2163         gst_event_unref (event);
2164       }
2165       goto done;
2166     }
2167     case GST_EVENT_FLUSH_STOP:
2168     {
2169       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2170
2171       if (queue->srcpad->mode == GST_ACTIVATE_PUSH) {
2172         /* forward event */
2173         gst_pad_push_event (queue->srcpad, event);
2174
2175         GST_QUEUE2_MUTEX_LOCK (queue);
2176         gst_queue2_locked_flush (queue);
2177         queue->srcresult = GST_FLOW_OK;
2178         queue->sinkresult = GST_FLOW_OK;
2179         queue->is_eos = FALSE;
2180         queue->unexpected = FALSE;
2181         queue->seeking = FALSE;
2182         /* reset rate counters */
2183         reset_rate_timer (queue);
2184         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2185             queue->srcpad);
2186         GST_QUEUE2_MUTEX_UNLOCK (queue);
2187       } else {
2188         GST_QUEUE2_MUTEX_LOCK (queue);
2189         queue->segment_event_received = FALSE;
2190         queue->is_eos = FALSE;
2191         queue->unexpected = FALSE;
2192         queue->sinkresult = GST_FLOW_OK;
2193         queue->seeking = FALSE;
2194         GST_QUEUE2_MUTEX_UNLOCK (queue);
2195
2196         gst_event_unref (event);
2197       }
2198       goto done;
2199     }
2200     default:
2201       if (GST_EVENT_IS_SERIALIZED (event)) {
2202         /* serialized events go in the queue */
2203         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2204         /* refuse more events on EOS */
2205         if (queue->is_eos)
2206           goto out_eos;
2207         gst_queue2_locked_enqueue (queue, event, GST_QUEUE2_ITEM_TYPE_EVENT);
2208         GST_QUEUE2_MUTEX_UNLOCK (queue);
2209       } else {
2210         /* non-serialized events are passed upstream. */
2211         gst_pad_push_event (queue->srcpad, event);
2212       }
2213       break;
2214   }
2215 done:
2216   return TRUE;
2217
2218   /* ERRORS */
2219 out_flushing:
2220   {
2221     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2222     GST_QUEUE2_MUTEX_UNLOCK (queue);
2223     gst_event_unref (event);
2224     return FALSE;
2225   }
2226 out_eos:
2227   {
2228     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2229     GST_QUEUE2_MUTEX_UNLOCK (queue);
2230     gst_event_unref (event);
2231     return FALSE;
2232   }
2233 }
2234
2235 static gboolean
2236 gst_queue2_is_empty (GstQueue2 * queue)
2237 {
2238   /* never empty on EOS */
2239   if (queue->is_eos)
2240     return FALSE;
2241
2242   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2243     return queue->current->writing_pos <= queue->current->max_reading_pos;
2244   } else {
2245     if (queue->queue.length == 0)
2246       return TRUE;
2247   }
2248
2249   return FALSE;
2250 }
2251
2252 static gboolean
2253 gst_queue2_is_filled (GstQueue2 * queue)
2254 {
2255   gboolean res;
2256
2257   /* always filled on EOS */
2258   if (queue->is_eos)
2259     return TRUE;
2260
2261 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2262     (queue->cur_level.format) >= ((alt_max) ? \
2263       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2264
2265   /* if using a ring buffer we're filled if all ring buffer space is used
2266    * _by the current range_ */
2267   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2268     guint64 rb_size = queue->ring_buffer_max_size;
2269     GST_DEBUG_OBJECT (queue,
2270         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2271         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2272     return CHECK_FILLED (bytes, rb_size);
2273   }
2274
2275   /* if using file, we're never filled if we don't have EOS */
2276   if (QUEUE_IS_USING_TEMP_FILE (queue))
2277     return FALSE;
2278
2279   /* we are never filled when we have no buffers at all */
2280   if (queue->cur_level.buffers == 0)
2281     return FALSE;
2282
2283   /* we are filled if one of the current levels exceeds the max */
2284   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2285       || CHECK_FILLED (time, 0);
2286
2287   /* if we need to, use the rate estimate to check against the max time we are
2288    * allowed to queue */
2289   if (queue->use_rate_estimate)
2290     res |= CHECK_FILLED (rate_time, 0);
2291
2292 #undef CHECK_FILLED
2293   return res;
2294 }
2295
2296 static GstFlowReturn
2297 gst_queue2_chain_buffer_or_buffer_list (GstQueue2 * queue,
2298     GstMiniObject * item, GstQueue2ItemType item_type)
2299 {
2300   /* we have to lock the queue since we span threads */
2301   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2302   /* when we received EOS, we refuse more data */
2303   if (queue->is_eos)
2304     goto out_eos;
2305   /* when we received unexpected from downstream, refuse more buffers */
2306   if (queue->unexpected)
2307     goto out_unexpected;
2308
2309   /* while we didn't receive the newsegment, we're seeking and we skip data */
2310   if (queue->seeking)
2311     goto out_seeking;
2312
2313   if (!gst_queue2_wait_free_space (queue))
2314     goto out_flushing;
2315
2316   /* put buffer in queue now */
2317   gst_queue2_locked_enqueue (queue, item, item_type);
2318   GST_QUEUE2_MUTEX_UNLOCK (queue);
2319
2320   return GST_FLOW_OK;
2321
2322   /* special conditions */
2323 out_flushing:
2324   {
2325     GstFlowReturn ret = queue->sinkresult;
2326
2327     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2328         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2329     GST_QUEUE2_MUTEX_UNLOCK (queue);
2330     gst_mini_object_unref (item);
2331
2332     return ret;
2333   }
2334 out_eos:
2335   {
2336     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2337     GST_QUEUE2_MUTEX_UNLOCK (queue);
2338     gst_mini_object_unref (item);
2339
2340     return GST_FLOW_UNEXPECTED;
2341   }
2342 out_seeking:
2343   {
2344     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are seeking");
2345     GST_QUEUE2_MUTEX_UNLOCK (queue);
2346     gst_mini_object_unref (item);
2347
2348     return GST_FLOW_OK;
2349   }
2350 out_unexpected:
2351   {
2352     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2353         "exit because we received UNEXPECTED");
2354     GST_QUEUE2_MUTEX_UNLOCK (queue);
2355     gst_mini_object_unref (item);
2356
2357     return GST_FLOW_UNEXPECTED;
2358   }
2359 }
2360
2361 static GstFlowReturn
2362 gst_queue2_chain (GstPad * pad, GstBuffer * buffer)
2363 {
2364   GstQueue2 *queue;
2365
2366   queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
2367
2368   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2369       "received buffer %p of size %d, time %" GST_TIME_FORMAT ", duration %"
2370       GST_TIME_FORMAT, buffer, GST_BUFFER_SIZE (buffer),
2371       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2372       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2373
2374   return gst_queue2_chain_buffer_or_buffer_list (queue,
2375       GST_MINI_OBJECT_CAST (buffer), GST_QUEUE2_ITEM_TYPE_BUFFER);
2376 }
2377
2378 static GstFlowReturn
2379 gst_queue2_chain_list (GstPad * pad, GstBufferList * buffer_list)
2380 {
2381   GstQueue2 *queue;
2382
2383   queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
2384
2385   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2386       "received buffer list %p", buffer_list);
2387
2388   return gst_queue2_chain_buffer_or_buffer_list (queue,
2389       GST_MINI_OBJECT_CAST (buffer_list), GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2390 }
2391
2392 static GstMiniObject *
2393 gst_queue2_dequeue_on_unexpected (GstQueue2 * queue,
2394     GstQueue2ItemType * item_type)
2395 {
2396   GstMiniObject *data;
2397
2398   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got UNEXPECTED from downstream");
2399
2400   /* stop pushing buffers, we dequeue all items until we see an item that we
2401    * can push again, which is EOS or NEWSEGMENT. If there is nothing in the
2402    * queue we can push, we set a flag to make the sinkpad refuse more
2403    * buffers with an UNEXPECTED return value until we receive something
2404    * pushable again or we get flushed. */
2405   while ((data = gst_queue2_locked_dequeue (queue, item_type))) {
2406     if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2407       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2408           "dropping UNEXPECTED buffer %p", data);
2409       gst_buffer_unref (GST_BUFFER_CAST (data));
2410     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2411       GstEvent *event = GST_EVENT_CAST (data);
2412       GstEventType type = GST_EVENT_TYPE (event);
2413
2414       if (type == GST_EVENT_EOS || type == GST_EVENT_NEWSEGMENT) {
2415         /* we found a pushable item in the queue, push it out */
2416         GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2417             "pushing pushable event %s after UNEXPECTED",
2418             GST_EVENT_TYPE_NAME (event));
2419         return data;
2420       }
2421       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2422           "dropping UNEXPECTED event %p", event);
2423       gst_event_unref (event);
2424     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2425       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2426           "dropping UNEXPECTED buffer list %p", data);
2427       gst_buffer_list_unref (GST_BUFFER_LIST_CAST (data));
2428     }
2429   }
2430   /* no more items in the queue. Set the unexpected flag so that upstream
2431    * make us refuse any more buffers on the sinkpad. Since we will still
2432    * accept EOS and NEWSEGMENT we return _FLOW_OK to the caller so that the
2433    * task function does not shut down. */
2434   queue->unexpected = TRUE;
2435   return NULL;
2436 }
2437
2438 /* dequeue an item from the queue an push it downstream. This functions returns
2439  * the result of the push. */
2440 static GstFlowReturn
2441 gst_queue2_push_one (GstQueue2 * queue)
2442 {
2443   GstFlowReturn result = GST_FLOW_OK;
2444   GstMiniObject *data;
2445   GstQueue2ItemType item_type;
2446
2447   data = gst_queue2_locked_dequeue (queue, &item_type);
2448   if (data == NULL)
2449     goto no_item;
2450
2451 next:
2452   GST_QUEUE2_MUTEX_UNLOCK (queue);
2453
2454   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2455     GstBuffer *buffer;
2456     GstCaps *caps;
2457
2458     buffer = GST_BUFFER_CAST (data);
2459     caps = GST_BUFFER_CAPS (buffer);
2460
2461     /* set caps before pushing the buffer so that core does not try to do
2462      * something fancy to check if this is possible. */
2463     if (caps && caps != GST_PAD_CAPS (queue->srcpad))
2464       gst_pad_set_caps (queue->srcpad, caps);
2465
2466     result = gst_pad_push (queue->srcpad, buffer);
2467
2468     /* need to check for srcresult here as well */
2469     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2470     if (result == GST_FLOW_UNEXPECTED) {
2471       data = gst_queue2_dequeue_on_unexpected (queue, &item_type);
2472       if (data != NULL)
2473         goto next;
2474       /* Since we will still accept EOS and NEWSEGMENT we return _FLOW_OK
2475        * to the caller so that the task function does not shut down */
2476       result = GST_FLOW_OK;
2477     }
2478   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2479     GstEvent *event = GST_EVENT_CAST (data);
2480     GstEventType type = GST_EVENT_TYPE (event);
2481
2482     gst_pad_push_event (queue->srcpad, event);
2483
2484     /* if we're EOS, return UNEXPECTED so that the task pauses. */
2485     if (type == GST_EVENT_EOS) {
2486       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2487           "pushed EOS event %p, return UNEXPECTED", event);
2488       result = GST_FLOW_UNEXPECTED;
2489     }
2490
2491     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2492   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2493     GstBufferList *buffer_list;
2494     GstBuffer *first_buf;
2495     GstCaps *caps;
2496
2497     buffer_list = GST_BUFFER_LIST_CAST (data);
2498
2499     first_buf = gst_buffer_list_get (buffer_list, 0, 0);
2500     caps = (first_buf != NULL) ? GST_BUFFER_CAPS (first_buf) : NULL;
2501
2502     /* set caps before pushing the buffer so that core does not try to do
2503      * something fancy to check if this is possible. */
2504     if (caps && caps != GST_PAD_CAPS (queue->srcpad))
2505       gst_pad_set_caps (queue->srcpad, caps);
2506
2507     result = gst_pad_push_list (queue->srcpad, buffer_list);
2508
2509     /* need to check for srcresult here as well */
2510     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2511     if (result == GST_FLOW_UNEXPECTED) {
2512       data = gst_queue2_dequeue_on_unexpected (queue, &item_type);
2513       if (data != NULL)
2514         goto next;
2515       /* Since we will still accept EOS and NEWSEGMENT we return _FLOW_OK
2516        * to the caller so that the task function does not shut down */
2517       result = GST_FLOW_OK;
2518     }
2519   }
2520   return result;
2521
2522   /* ERRORS */
2523 no_item:
2524   {
2525     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2526         "exit because we have no item in the queue");
2527     return GST_FLOW_ERROR;
2528   }
2529 out_flushing:
2530   {
2531     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2532     return GST_FLOW_WRONG_STATE;
2533   }
2534 }
2535
2536 /* called repeatedly with @pad as the source pad. This function should push out
2537  * data to the peer element. */
2538 static void
2539 gst_queue2_loop (GstPad * pad)
2540 {
2541   GstQueue2 *queue;
2542   GstFlowReturn ret;
2543
2544   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2545
2546   /* have to lock for thread-safety */
2547   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2548
2549   if (gst_queue2_is_empty (queue)) {
2550     gboolean started;
2551
2552     /* pause the timer while we wait. The fact that we are waiting does not mean
2553      * the byterate on the output pad is lower */
2554     if ((started = queue->out_timer_started))
2555       g_timer_stop (queue->out_timer);
2556
2557     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2558         "queue is empty, waiting for new data");
2559     do {
2560       /* Wait for data to be available, we could be unlocked because of a flush. */
2561       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2562     }
2563     while (gst_queue2_is_empty (queue));
2564
2565     /* and continue if we were running before */
2566     if (started)
2567       g_timer_continue (queue->out_timer);
2568   }
2569   ret = gst_queue2_push_one (queue);
2570   queue->srcresult = ret;
2571   queue->sinkresult = ret;
2572   if (ret != GST_FLOW_OK)
2573     goto out_flushing;
2574
2575   GST_QUEUE2_MUTEX_UNLOCK (queue);
2576
2577   return;
2578
2579   /* ERRORS */
2580 out_flushing:
2581   {
2582     gboolean eos = queue->is_eos;
2583     GstFlowReturn ret = queue->srcresult;
2584
2585     gst_pad_pause_task (queue->srcpad);
2586     GST_QUEUE2_MUTEX_UNLOCK (queue);
2587     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2588         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2589     /* let app know about us giving up if upstream is not expected to do so */
2590     /* UNEXPECTED is already taken care of elsewhere */
2591     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED)) {
2592       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2593           (_("Internal data flow error.")),
2594           ("streaming task paused, reason %s (%d)",
2595               gst_flow_get_name (ret), ret));
2596       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2597     }
2598     return;
2599   }
2600 }
2601
2602 static gboolean
2603 gst_queue2_handle_src_event (GstPad * pad, GstEvent * event)
2604 {
2605   gboolean res = TRUE;
2606   GstQueue2 *queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2607
2608   if (G_UNLIKELY (queue == NULL)) {
2609     gst_event_unref (event);
2610     return FALSE;
2611   }
2612 #ifndef GST_DISABLE_GST_DEBUG
2613   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
2614       event, GST_EVENT_TYPE_NAME (event));
2615 #endif
2616
2617   switch (GST_EVENT_TYPE (event)) {
2618     case GST_EVENT_FLUSH_START:
2619       if (QUEUE_IS_USING_QUEUE (queue)) {
2620         /* just forward upstream */
2621         res = gst_pad_push_event (queue->sinkpad, event);
2622       } else {
2623         /* now unblock the getrange function */
2624         GST_QUEUE2_MUTEX_LOCK (queue);
2625         GST_DEBUG_OBJECT (queue, "flushing");
2626         queue->srcresult = GST_FLOW_WRONG_STATE;
2627         GST_QUEUE2_SIGNAL_ADD (queue);
2628         GST_QUEUE2_MUTEX_UNLOCK (queue);
2629
2630         /* when using a temp file, we eat the event */
2631         res = TRUE;
2632         gst_event_unref (event);
2633       }
2634       break;
2635     case GST_EVENT_FLUSH_STOP:
2636       if (QUEUE_IS_USING_QUEUE (queue)) {
2637         /* just forward upstream */
2638         res = gst_pad_push_event (queue->sinkpad, event);
2639       } else {
2640         /* now unblock the getrange function */
2641         GST_QUEUE2_MUTEX_LOCK (queue);
2642         queue->srcresult = GST_FLOW_OK;
2643         GST_QUEUE2_MUTEX_UNLOCK (queue);
2644
2645         /* when using a temp file, we eat the event */
2646         res = TRUE;
2647         gst_event_unref (event);
2648       }
2649       break;
2650     default:
2651       res = gst_pad_push_event (queue->sinkpad, event);
2652       break;
2653   }
2654
2655   gst_object_unref (queue);
2656   return res;
2657 }
2658
2659 static gboolean
2660 gst_queue2_peer_query (GstQueue2 * queue, GstPad * pad, GstQuery * query)
2661 {
2662   gboolean ret = FALSE;
2663   GstPad *peer;
2664
2665   if ((peer = gst_pad_get_peer (pad))) {
2666     ret = gst_pad_query (peer, query);
2667     gst_object_unref (peer);
2668   }
2669   return ret;
2670 }
2671
2672 static gboolean
2673 gst_queue2_handle_src_query (GstPad * pad, GstQuery * query)
2674 {
2675   GstQueue2 *queue;
2676
2677   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2678   if (G_UNLIKELY (queue == NULL))
2679     return FALSE;
2680
2681   switch (GST_QUERY_TYPE (query)) {
2682     case GST_QUERY_POSITION:
2683     {
2684       gint64 peer_pos;
2685       GstFormat format;
2686
2687       if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2688         goto peer_failed;
2689
2690       /* get peer position */
2691       gst_query_parse_position (query, &format, &peer_pos);
2692
2693       /* FIXME: this code assumes that there's no discont in the queue */
2694       switch (format) {
2695         case GST_FORMAT_BYTES:
2696           peer_pos -= queue->cur_level.bytes;
2697           break;
2698         case GST_FORMAT_TIME:
2699           peer_pos -= queue->cur_level.time;
2700           break;
2701         default:
2702           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
2703               "know how to adjust value", gst_format_get_name (format));
2704           return FALSE;
2705       }
2706       /* set updated position */
2707       gst_query_set_position (query, format, peer_pos);
2708       break;
2709     }
2710     case GST_QUERY_DURATION:
2711     {
2712       GST_DEBUG_OBJECT (queue, "doing peer query");
2713
2714       if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2715         goto peer_failed;
2716
2717       GST_DEBUG_OBJECT (queue, "peer query success");
2718       break;
2719     }
2720     case GST_QUERY_BUFFERING:
2721     {
2722       GstFormat format;
2723
2724       GST_DEBUG_OBJECT (queue, "query buffering");
2725
2726       /* FIXME - is this condition correct? what should ring buffer do? */
2727       if (QUEUE_IS_USING_QUEUE (queue)) {
2728         /* no temp file, just forward to the peer */
2729         if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2730           goto peer_failed;
2731         GST_DEBUG_OBJECT (queue, "buffering forwarded to peer");
2732       } else {
2733         gint64 start, stop, range_start, range_stop;
2734         guint64 writing_pos;
2735         gint percent;
2736         gint64 estimated_total, buffering_left;
2737         GstFormat peer_fmt;
2738         gint64 duration;
2739         gboolean peer_res, is_buffering, is_eos;
2740         gdouble byte_in_rate, byte_out_rate;
2741         GstQueue2Range *queued_ranges;
2742
2743         /* we need a current download region */
2744         if (queue->current == NULL)
2745           return FALSE;
2746
2747         writing_pos = queue->current->writing_pos;
2748         byte_in_rate = queue->byte_in_rate;
2749         byte_out_rate = queue->byte_out_rate;
2750         is_buffering = queue->is_buffering;
2751         is_eos = queue->is_eos;
2752         percent = queue->buffering_percent;
2753
2754         if (is_eos) {
2755           /* we're EOS, we know the duration in bytes now */
2756           peer_res = TRUE;
2757           duration = writing_pos;
2758         } else {
2759           /* get duration of upstream in bytes */
2760           peer_fmt = GST_FORMAT_BYTES;
2761           peer_res = gst_pad_query_peer_duration (queue->sinkpad, &peer_fmt,
2762               &duration);
2763         }
2764
2765         /* calculate remaining and total download time */
2766         if (peer_res && byte_in_rate > 0.0) {
2767           estimated_total = (duration * 1000) / byte_in_rate;
2768           buffering_left = ((duration - writing_pos) * 1000) / byte_in_rate;
2769         } else {
2770           estimated_total = -1;
2771           buffering_left = -1;
2772         }
2773         GST_DEBUG_OBJECT (queue, "estimated %" G_GINT64_FORMAT ", left %"
2774             G_GINT64_FORMAT, estimated_total, buffering_left);
2775
2776         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
2777
2778         switch (format) {
2779           case GST_FORMAT_PERCENT:
2780             /* we need duration */
2781             if (!peer_res)
2782               goto peer_failed;
2783
2784             GST_DEBUG_OBJECT (queue,
2785                 "duration %" G_GINT64_FORMAT ", writing %" G_GINT64_FORMAT,
2786                 duration, writing_pos);
2787
2788             start = 0;
2789             /* get our available data relative to the duration */
2790             if (duration != -1)
2791               stop = GST_FORMAT_PERCENT_MAX * writing_pos / duration;
2792             else
2793               stop = -1;
2794             break;
2795           case GST_FORMAT_BYTES:
2796             start = 0;
2797             stop = writing_pos;
2798             break;
2799           default:
2800             start = -1;
2801             stop = -1;
2802             break;
2803         }
2804
2805         /* fill out the buffered ranges */
2806         for (queued_ranges = queue->ranges; queued_ranges;
2807             queued_ranges = queued_ranges->next) {
2808           switch (format) {
2809             case GST_FORMAT_PERCENT:
2810               if (duration == -1) {
2811                 range_start = 0;
2812                 range_stop = 0;
2813                 break;
2814               }
2815               range_start = 100 * queued_ranges->offset / duration;
2816               range_stop = 100 * queued_ranges->writing_pos / duration;
2817               break;
2818             case GST_FORMAT_BYTES:
2819               range_start = queued_ranges->offset;
2820               range_stop = queued_ranges->writing_pos;
2821               break;
2822             default:
2823               range_start = -1;
2824               range_stop = -1;
2825               break;
2826           }
2827           if (range_start == range_stop)
2828             continue;
2829           GST_DEBUG_OBJECT (queue,
2830               "range starting at %" G_GINT64_FORMAT " and finishing at %"
2831               G_GINT64_FORMAT, range_start, range_stop);
2832           gst_query_add_buffering_range (query, range_start, range_stop);
2833         }
2834
2835         gst_query_set_buffering_percent (query, is_buffering, percent);
2836         gst_query_set_buffering_range (query, format, start, stop,
2837             estimated_total);
2838         gst_query_set_buffering_stats (query, GST_BUFFERING_DOWNLOAD,
2839             byte_in_rate, byte_out_rate, buffering_left);
2840       }
2841       break;
2842     }
2843     default:
2844       /* peer handled other queries */
2845       if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2846         goto peer_failed;
2847       break;
2848   }
2849
2850   gst_object_unref (queue);
2851   return TRUE;
2852
2853   /* ERRORS */
2854 peer_failed:
2855   {
2856     GST_DEBUG_OBJECT (queue, "failed peer query");
2857     gst_object_unref (queue);
2858     return FALSE;
2859   }
2860 }
2861
2862 static gboolean
2863 gst_queue2_handle_query (GstElement * element, GstQuery * query)
2864 {
2865   /* simply forward to the srcpad query function */
2866   return gst_queue2_handle_src_query (GST_QUEUE2_CAST (element)->srcpad, query);
2867 }
2868
2869 static void
2870 gst_queue2_update_upstream_size (GstQueue2 * queue)
2871 {
2872   GstFormat fmt = GST_FORMAT_BYTES;
2873   gint64 upstream_size = -1;
2874
2875   if (gst_pad_query_peer_duration (queue->sinkpad, &fmt, &upstream_size)) {
2876     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
2877     queue->upstream_size = upstream_size;
2878   }
2879 }
2880
2881 static GstFlowReturn
2882 gst_queue2_get_range (GstPad * pad, guint64 offset, guint length,
2883     GstBuffer ** buffer)
2884 {
2885   GstQueue2 *queue;
2886   GstFlowReturn ret;
2887
2888   queue = GST_QUEUE2_CAST (gst_pad_get_parent (pad));
2889
2890   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
2891   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2892   offset = (offset == -1) ? queue->current->reading_pos : offset;
2893
2894   GST_DEBUG_OBJECT (queue,
2895       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
2896
2897   /* catch any reads beyond the size of the file here to make sure queue2
2898    * doesn't send seek events beyond the size of the file upstream, since
2899    * that would confuse elements such as souphttpsrc and/or http servers.
2900    * Demuxers often just loop until EOS at the end of the file to figure out
2901    * when they've read all the end-headers or index chunks. */
2902   if (G_UNLIKELY (offset >= queue->upstream_size)) {
2903     gst_queue2_update_upstream_size (queue);
2904     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
2905       goto out_unexpected;
2906   }
2907
2908   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
2909     gst_queue2_update_upstream_size (queue);
2910     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
2911       length = queue->upstream_size - offset;
2912       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
2913     }
2914   }
2915
2916   /* FIXME - function will block when the range is not yet available */
2917   ret = gst_queue2_create_read (queue, offset, length, buffer);
2918   GST_QUEUE2_MUTEX_UNLOCK (queue);
2919
2920   gst_object_unref (queue);
2921
2922   return ret;
2923
2924   /* ERRORS */
2925 out_flushing:
2926   {
2927     ret = queue->srcresult;
2928
2929     GST_DEBUG_OBJECT (queue, "we are flushing");
2930     GST_QUEUE2_MUTEX_UNLOCK (queue);
2931     gst_object_unref (queue);
2932     return ret;
2933   }
2934 out_unexpected:
2935   {
2936     GST_DEBUG_OBJECT (queue, "read beyond end of file");
2937     GST_QUEUE2_MUTEX_UNLOCK (queue);
2938     gst_object_unref (queue);
2939     return GST_FLOW_UNEXPECTED;
2940   }
2941 }
2942
2943 static gboolean
2944 gst_queue2_src_checkgetrange_function (GstPad * pad)
2945 {
2946   GstQueue2 *queue;
2947   gboolean ret;
2948
2949   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2950
2951   /* we can operate in pull mode when we are using a tempfile */
2952   ret = !QUEUE_IS_USING_QUEUE (queue);
2953
2954   gst_object_unref (GST_OBJECT (queue));
2955
2956   return ret;
2957 }
2958
2959 /* sink currently only operates in push mode */
2960 static gboolean
2961 gst_queue2_sink_activate_push (GstPad * pad, gboolean active)
2962 {
2963   gboolean result = TRUE;
2964   GstQueue2 *queue;
2965
2966   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2967
2968   if (active) {
2969     GST_QUEUE2_MUTEX_LOCK (queue);
2970     GST_DEBUG_OBJECT (queue, "activating push mode");
2971     queue->srcresult = GST_FLOW_OK;
2972     queue->sinkresult = GST_FLOW_OK;
2973     queue->is_eos = FALSE;
2974     queue->unexpected = FALSE;
2975     reset_rate_timer (queue);
2976     GST_QUEUE2_MUTEX_UNLOCK (queue);
2977   } else {
2978     /* unblock chain function */
2979     GST_QUEUE2_MUTEX_LOCK (queue);
2980     GST_DEBUG_OBJECT (queue, "deactivating push mode");
2981     queue->srcresult = GST_FLOW_WRONG_STATE;
2982     queue->sinkresult = GST_FLOW_WRONG_STATE;
2983     gst_queue2_locked_flush (queue);
2984     GST_QUEUE2_MUTEX_UNLOCK (queue);
2985   }
2986
2987   gst_object_unref (queue);
2988
2989   return result;
2990 }
2991
2992 /* src operating in push mode, we start a task on the source pad that pushes out
2993  * buffers from the queue */
2994 static gboolean
2995 gst_queue2_src_activate_push (GstPad * pad, gboolean active)
2996 {
2997   gboolean result = FALSE;
2998   GstQueue2 *queue;
2999
3000   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
3001
3002   if (active) {
3003     GST_QUEUE2_MUTEX_LOCK (queue);
3004     GST_DEBUG_OBJECT (queue, "activating push mode");
3005     queue->srcresult = GST_FLOW_OK;
3006     queue->sinkresult = GST_FLOW_OK;
3007     queue->is_eos = FALSE;
3008     queue->unexpected = FALSE;
3009     result = gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad);
3010     GST_QUEUE2_MUTEX_UNLOCK (queue);
3011   } else {
3012     /* unblock loop function */
3013     GST_QUEUE2_MUTEX_LOCK (queue);
3014     GST_DEBUG_OBJECT (queue, "deactivating push mode");
3015     queue->srcresult = GST_FLOW_WRONG_STATE;
3016     queue->sinkresult = GST_FLOW_WRONG_STATE;
3017     /* the item add signal will unblock */
3018     GST_QUEUE2_SIGNAL_ADD (queue);
3019     GST_QUEUE2_MUTEX_UNLOCK (queue);
3020
3021     /* step 2, make sure streaming finishes */
3022     result = gst_pad_stop_task (pad);
3023   }
3024
3025   gst_object_unref (queue);
3026
3027   return result;
3028 }
3029
3030 /* pull mode, downstream will call our getrange function */
3031 static gboolean
3032 gst_queue2_src_activate_pull (GstPad * pad, gboolean active)
3033 {
3034   gboolean result;
3035   GstQueue2 *queue;
3036
3037   queue = GST_QUEUE2 (gst_pad_get_parent (pad));
3038
3039   if (active) {
3040     GST_QUEUE2_MUTEX_LOCK (queue);
3041     if (!QUEUE_IS_USING_QUEUE (queue)) {
3042       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3043         /* open the temp file now */
3044         result = gst_queue2_open_temp_location_file (queue);
3045       } else if (!queue->ring_buffer) {
3046         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
3047         result = ! !queue->ring_buffer;
3048       } else {
3049         result = TRUE;
3050       }
3051
3052       GST_DEBUG_OBJECT (queue, "activating pull mode");
3053       init_ranges (queue);
3054       queue->srcresult = GST_FLOW_OK;
3055       queue->sinkresult = GST_FLOW_OK;
3056       queue->is_eos = FALSE;
3057       queue->unexpected = FALSE;
3058       queue->upstream_size = 0;
3059     } else {
3060       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
3061       /* this is not allowed, we cannot operate in pull mode without a temp
3062        * file. */
3063       queue->srcresult = GST_FLOW_WRONG_STATE;
3064       queue->sinkresult = GST_FLOW_WRONG_STATE;
3065       result = FALSE;
3066     }
3067     GST_QUEUE2_MUTEX_UNLOCK (queue);
3068   } else {
3069     GST_QUEUE2_MUTEX_LOCK (queue);
3070     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
3071     queue->srcresult = GST_FLOW_WRONG_STATE;
3072     queue->sinkresult = GST_FLOW_WRONG_STATE;
3073     /* this will unlock getrange */
3074     GST_QUEUE2_SIGNAL_ADD (queue);
3075     result = TRUE;
3076     GST_QUEUE2_MUTEX_UNLOCK (queue);
3077   }
3078   gst_object_unref (queue);
3079
3080   return result;
3081 }
3082
3083 static GstStateChangeReturn
3084 gst_queue2_change_state (GstElement * element, GstStateChange transition)
3085 {
3086   GstQueue2 *queue;
3087   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3088
3089   queue = GST_QUEUE2 (element);
3090
3091   switch (transition) {
3092     case GST_STATE_CHANGE_NULL_TO_READY:
3093       break;
3094     case GST_STATE_CHANGE_READY_TO_PAUSED:
3095       GST_QUEUE2_MUTEX_LOCK (queue);
3096       if (!QUEUE_IS_USING_QUEUE (queue)) {
3097         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3098           if (!gst_queue2_open_temp_location_file (queue))
3099             ret = GST_STATE_CHANGE_FAILURE;
3100         } else {
3101           if (queue->ring_buffer) {
3102             g_free (queue->ring_buffer);
3103             queue->ring_buffer = NULL;
3104           }
3105           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
3106             ret = GST_STATE_CHANGE_FAILURE;
3107         }
3108         init_ranges (queue);
3109       }
3110       queue->segment_event_received = FALSE;
3111       queue->starting_segment = NULL;
3112       GST_QUEUE2_MUTEX_UNLOCK (queue);
3113       break;
3114     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3115       break;
3116     default:
3117       break;
3118   }
3119
3120   if (ret == GST_STATE_CHANGE_FAILURE)
3121     return ret;
3122
3123   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3124
3125   if (ret == GST_STATE_CHANGE_FAILURE)
3126     return ret;
3127
3128   switch (transition) {
3129     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3130       break;
3131     case GST_STATE_CHANGE_PAUSED_TO_READY:
3132       GST_QUEUE2_MUTEX_LOCK (queue);
3133       if (!QUEUE_IS_USING_QUEUE (queue)) {
3134         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3135           gst_queue2_close_temp_location_file (queue);
3136         } else if (queue->ring_buffer) {
3137           g_free (queue->ring_buffer);
3138           queue->ring_buffer = NULL;
3139         }
3140         clean_ranges (queue);
3141       }
3142       if (queue->starting_segment != NULL) {
3143         gst_event_unref (queue->starting_segment);
3144         queue->starting_segment = NULL;
3145       }
3146       GST_QUEUE2_MUTEX_UNLOCK (queue);
3147       break;
3148     case GST_STATE_CHANGE_READY_TO_NULL:
3149       break;
3150     default:
3151       break;
3152   }
3153
3154   return ret;
3155 }
3156
3157 /* changing the capacity of the queue must wake up
3158  * the _chain function, it might have more room now
3159  * to store the buffer/event in the queue */
3160 #define QUEUE_CAPACITY_CHANGE(q)\
3161   GST_QUEUE2_SIGNAL_DEL (queue);
3162
3163 /* Changing the minimum required fill level must
3164  * wake up the _loop function as it might now
3165  * be able to preceed.
3166  */
3167 #define QUEUE_THRESHOLD_CHANGE(q)\
3168   GST_QUEUE2_SIGNAL_ADD (queue);
3169
3170 static void
3171 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
3172 {
3173   GstState state;
3174
3175   /* the element must be stopped in order to do this */
3176   GST_OBJECT_LOCK (queue);
3177   state = GST_STATE (queue);
3178   if (state != GST_STATE_READY && state != GST_STATE_NULL)
3179     goto wrong_state;
3180   GST_OBJECT_UNLOCK (queue);
3181
3182   /* set new location */
3183   g_free (queue->temp_template);
3184   queue->temp_template = g_strdup (template);
3185
3186   return;
3187
3188 /* ERROR */
3189 wrong_state:
3190   {
3191     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
3192     GST_OBJECT_UNLOCK (queue);
3193   }
3194 }
3195
3196 static void
3197 gst_queue2_set_property (GObject * object,
3198     guint prop_id, const GValue * value, GParamSpec * pspec)
3199 {
3200   GstQueue2 *queue = GST_QUEUE2 (object);
3201
3202   /* someone could change levels here, and since this
3203    * affects the get/put funcs, we need to lock for safety. */
3204   GST_QUEUE2_MUTEX_LOCK (queue);
3205
3206   switch (prop_id) {
3207     case PROP_MAX_SIZE_BYTES:
3208       queue->max_level.bytes = g_value_get_uint (value);
3209       QUEUE_CAPACITY_CHANGE (queue);
3210       break;
3211     case PROP_MAX_SIZE_BUFFERS:
3212       queue->max_level.buffers = g_value_get_uint (value);
3213       QUEUE_CAPACITY_CHANGE (queue);
3214       break;
3215     case PROP_MAX_SIZE_TIME:
3216       queue->max_level.time = g_value_get_uint64 (value);
3217       /* set rate_time to the same value. We use an extra field in the level
3218        * structure so that we can easily access and compare it */
3219       queue->max_level.rate_time = queue->max_level.time;
3220       QUEUE_CAPACITY_CHANGE (queue);
3221       break;
3222     case PROP_USE_BUFFERING:
3223       queue->use_buffering = g_value_get_boolean (value);
3224       break;
3225     case PROP_USE_RATE_ESTIMATE:
3226       queue->use_rate_estimate = g_value_get_boolean (value);
3227       break;
3228     case PROP_LOW_PERCENT:
3229       queue->low_percent = g_value_get_int (value);
3230       break;
3231     case PROP_HIGH_PERCENT:
3232       queue->high_percent = g_value_get_int (value);
3233       break;
3234     case PROP_TEMP_TEMPLATE:
3235       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3236       break;
3237     case PROP_TEMP_LOCATION:
3238       g_free (queue->temp_location);
3239       queue->temp_location = g_value_dup_string (value);
3240       /* you can set the property back to NULL to make it use the temp-tmpl
3241        * property. */
3242       queue->temp_location_set = queue->temp_location != NULL;
3243       break;
3244     case PROP_TEMP_REMOVE:
3245       queue->temp_remove = g_value_get_boolean (value);
3246       break;
3247     case PROP_RING_BUFFER_MAX_SIZE:
3248       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3249       break;
3250     default:
3251       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3252       break;
3253   }
3254
3255   GST_QUEUE2_MUTEX_UNLOCK (queue);
3256 }
3257
3258 static void
3259 gst_queue2_get_property (GObject * object,
3260     guint prop_id, GValue * value, GParamSpec * pspec)
3261 {
3262   GstQueue2 *queue = GST_QUEUE2 (object);
3263
3264   GST_QUEUE2_MUTEX_LOCK (queue);
3265
3266   switch (prop_id) {
3267     case PROP_CUR_LEVEL_BYTES:
3268       g_value_set_uint (value, queue->cur_level.bytes);
3269       break;
3270     case PROP_CUR_LEVEL_BUFFERS:
3271       g_value_set_uint (value, queue->cur_level.buffers);
3272       break;
3273     case PROP_CUR_LEVEL_TIME:
3274       g_value_set_uint64 (value, queue->cur_level.time);
3275       break;
3276     case PROP_MAX_SIZE_BYTES:
3277       g_value_set_uint (value, queue->max_level.bytes);
3278       break;
3279     case PROP_MAX_SIZE_BUFFERS:
3280       g_value_set_uint (value, queue->max_level.buffers);
3281       break;
3282     case PROP_MAX_SIZE_TIME:
3283       g_value_set_uint64 (value, queue->max_level.time);
3284       break;
3285     case PROP_USE_BUFFERING:
3286       g_value_set_boolean (value, queue->use_buffering);
3287       break;
3288     case PROP_USE_RATE_ESTIMATE:
3289       g_value_set_boolean (value, queue->use_rate_estimate);
3290       break;
3291     case PROP_LOW_PERCENT:
3292       g_value_set_int (value, queue->low_percent);
3293       break;
3294     case PROP_HIGH_PERCENT:
3295       g_value_set_int (value, queue->high_percent);
3296       break;
3297     case PROP_TEMP_TEMPLATE:
3298       g_value_set_string (value, queue->temp_template);
3299       break;
3300     case PROP_TEMP_LOCATION:
3301       g_value_set_string (value, queue->temp_location);
3302       break;
3303     case PROP_TEMP_REMOVE:
3304       g_value_set_boolean (value, queue->temp_remove);
3305       break;
3306     case PROP_RING_BUFFER_MAX_SIZE:
3307       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3308       break;
3309     default:
3310       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3311       break;
3312   }
3313
3314   GST_QUEUE2_MUTEX_UNLOCK (queue);
3315 }