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