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