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