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