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