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