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