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