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