queue2: Fix handling of the new stream-start event
[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_details_simple (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_OBJECT_FLAG_SET (queue->sinkpad, GST_PAD_FLAG_PROXY_CAPS);
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_OBJECT_FLAG_SET (queue->srcpad, GST_PAD_FLAG_PROXY_CAPS);
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_WRONG_STATE;
437   queue->sinkresult = GST_FLOW_WRONG_STATE;
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");
1061     /* we don't have the range, see how far away we are, FIXME, find a good
1062      * threshold based on the incoming rate. */
1063     if (!queue->is_eos && queue->current) {
1064       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1065         if (offset < queue->current->offset || offset >
1066             queue->current->writing_pos + QUEUE_MAX_BYTES (queue) -
1067             queue->cur_level.bytes) {
1068           perform_seek_to_offset (queue, offset);
1069         } else {
1070           GST_INFO_OBJECT (queue,
1071               "requested data is within range, wait for data");
1072         }
1073       } else if (offset < queue->current->writing_pos + 200000) {
1074         update_cur_pos (queue, queue->current, offset + length);
1075         GST_INFO_OBJECT (queue, "wait for data");
1076         return FALSE;
1077       }
1078     }
1079
1080     /* too far away, do a seek */
1081     perform_seek_to_offset (queue, offset);
1082   }
1083
1084   return FALSE;
1085 }
1086
1087 #ifdef HAVE_FSEEKO
1088 #define FSEEK_FILE(file,offset)  (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1089 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1090 #define FSEEK_FILE(file,offset)  (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1091 #else
1092 #define FSEEK_FILE(file,offset)  (fseek (file, offset, SEEK_SET) != 0)
1093 #endif
1094
1095 static GstFlowReturn
1096 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1097     guint8 * dst, gint64 * read_return)
1098 {
1099   guint8 *ring_buffer;
1100   size_t res;
1101
1102   ring_buffer = queue->ring_buffer;
1103
1104   if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1105     goto seek_failed;
1106
1107   /* this should not block */
1108   GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1109       length, offset);
1110   if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1111     res = fread (dst, 1, length, queue->temp_file);
1112   } else {
1113     memcpy (dst, ring_buffer + offset, length);
1114     res = length;
1115   }
1116
1117   GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1118
1119   if (G_UNLIKELY (res < length)) {
1120     if (!QUEUE_IS_USING_TEMP_FILE (queue))
1121       goto could_not_read;
1122     /* check for errors or EOF */
1123     if (ferror (queue->temp_file))
1124       goto could_not_read;
1125     if (feof (queue->temp_file) && length > 0)
1126       goto eos;
1127   }
1128
1129   *read_return = res;
1130
1131   return GST_FLOW_OK;
1132
1133 seek_failed:
1134   {
1135     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1136     return GST_FLOW_ERROR;
1137   }
1138 could_not_read:
1139   {
1140     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1141     return GST_FLOW_ERROR;
1142   }
1143 eos:
1144   {
1145     GST_DEBUG ("non-regular file hits EOS");
1146     return GST_FLOW_EOS;
1147   }
1148 }
1149
1150 static GstFlowReturn
1151 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1152     GstBuffer ** buffer)
1153 {
1154   GstBuffer *buf;
1155   GstMapInfo info;
1156   guint8 *data;
1157   guint64 file_offset;
1158   guint block_length, remaining, read_length;
1159   guint64 rb_size;
1160   guint64 rpos;
1161   GstFlowReturn ret = GST_FLOW_OK;
1162
1163   /* allocate the output buffer of the requested size */
1164   buf = gst_buffer_new_allocate (NULL, length, 0);
1165   gst_buffer_map (buf, &info, GST_MAP_WRITE);
1166   data = info.data;
1167
1168   GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1169       offset);
1170
1171   rpos = offset;
1172   rb_size = queue->ring_buffer_max_size;
1173
1174   remaining = length;
1175   while (remaining > 0) {
1176     /* configure how much/whether to read */
1177     if (!gst_queue2_have_data (queue, rpos, remaining)) {
1178       read_length = 0;
1179
1180       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1181         guint64 level;
1182
1183         /* calculate how far away the offset is */
1184         if (queue->current->writing_pos > rpos)
1185           level = queue->current->writing_pos - rpos;
1186         else
1187           level = 0;
1188
1189         GST_DEBUG_OBJECT (queue,
1190             "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1191             ", level %" G_GUINT64_FORMAT,
1192             rpos, queue->current->writing_pos, level);
1193
1194         if (level >= rb_size) {
1195           /* we don't have the data but if we have a ring buffer that is full, we
1196            * need to read */
1197           GST_DEBUG_OBJECT (queue,
1198               "ring buffer full, reading ring-buffer-max-size %"
1199               G_GUINT64_FORMAT " bytes", rb_size);
1200           read_length = rb_size;
1201         } else if (queue->is_eos) {
1202           /* won't get any more data so read any data we have */
1203           if (level) {
1204             GST_DEBUG_OBJECT (queue,
1205                 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1206                 level);
1207             read_length = level;
1208           } else
1209             goto hit_eos;
1210         }
1211       }
1212
1213       if (read_length == 0) {
1214         if (QUEUE_IS_USING_RING_BUFFER (queue)
1215             && queue->current->max_reading_pos > rpos) {
1216           /* protect cached data (data between offset and max_reading_pos)
1217            * and update current level */
1218           GST_DEBUG_OBJECT (queue,
1219               "protecting cached data [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1220               "]", rpos, queue->current->max_reading_pos);
1221           queue->current->max_reading_pos = rpos;
1222           update_cur_level (queue, queue->current);
1223         }
1224         GST_DEBUG_OBJECT (queue, "waiting for add");
1225         GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1226         continue;
1227       }
1228     } else {
1229       /* we have the requested data so read it */
1230       read_length = remaining;
1231     }
1232
1233     /* set range reading_pos to actual reading position for this read */
1234     queue->current->reading_pos = rpos;
1235
1236     /* configure how much and from where to read */
1237     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1238       file_offset =
1239           (queue->current->rb_offset + (rpos -
1240               queue->current->offset)) % rb_size;
1241       if (file_offset + read_length > rb_size) {
1242         block_length = rb_size - file_offset;
1243       } else {
1244         block_length = read_length;
1245       }
1246     } else {
1247       file_offset = rpos;
1248       block_length = read_length;
1249     }
1250
1251     /* while we still have data to read, we loop */
1252     while (read_length > 0) {
1253       gint64 read_return;
1254
1255       ret =
1256           gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1257           data, &read_return);
1258       if (ret != GST_FLOW_OK)
1259         goto read_error;
1260
1261       file_offset += read_return;
1262       if (QUEUE_IS_USING_RING_BUFFER (queue))
1263         file_offset %= rb_size;
1264
1265       data += read_return;
1266       read_length -= read_return;
1267       block_length = read_length;
1268       remaining -= read_return;
1269
1270       rpos = (queue->current->reading_pos += read_return);
1271       update_cur_pos (queue, queue->current, queue->current->reading_pos);
1272     }
1273     GST_QUEUE2_SIGNAL_DEL (queue);
1274     GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1275   }
1276
1277   gst_buffer_unmap (buf, &info);
1278   gst_buffer_resize (buf, 0, length);
1279
1280   GST_BUFFER_OFFSET (buf) = offset;
1281   GST_BUFFER_OFFSET_END (buf) = offset + length;
1282
1283   *buffer = buf;
1284
1285   return ret;
1286
1287   /* ERRORS */
1288 hit_eos:
1289   {
1290     GST_DEBUG_OBJECT (queue, "EOS hit and we don't have any requested data");
1291     gst_buffer_unref (buf);
1292     return GST_FLOW_EOS;
1293   }
1294 out_flushing:
1295   {
1296     GST_DEBUG_OBJECT (queue, "we are flushing");
1297     gst_buffer_unref (buf);
1298     return GST_FLOW_WRONG_STATE;
1299   }
1300 read_error:
1301   {
1302     GST_DEBUG_OBJECT (queue, "we have a read error");
1303     gst_buffer_unmap (buf, &info);
1304     gst_buffer_unref (buf);
1305     return ret;
1306   }
1307 }
1308
1309 /* should be called with QUEUE_LOCK */
1310 static GstMiniObject *
1311 gst_queue2_read_item_from_file (GstQueue2 * queue)
1312 {
1313   GstMiniObject *item;
1314
1315   if (queue->stream_start_event != NULL) {
1316     item = GST_MINI_OBJECT_CAST (queue->stream_start_event);
1317     queue->stream_start_event = NULL;
1318   } else if (queue->starting_segment != NULL) {
1319     item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1320     queue->starting_segment = NULL;
1321   } else {
1322     GstFlowReturn ret;
1323     GstBuffer *buffer;
1324     guint64 reading_pos;
1325
1326     reading_pos = queue->current->reading_pos;
1327
1328     ret =
1329         gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1330         &buffer);
1331
1332     switch (ret) {
1333       case GST_FLOW_OK:
1334         item = GST_MINI_OBJECT_CAST (buffer);
1335         break;
1336       case GST_FLOW_EOS:
1337         item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1338         break;
1339       default:
1340         item = NULL;
1341         break;
1342     }
1343   }
1344   return item;
1345 }
1346
1347 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1348  * the temp filename. */
1349 static gboolean
1350 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1351 {
1352   gint fd = -1;
1353   gchar *name = NULL;
1354
1355   if (queue->temp_file)
1356     goto already_opened;
1357
1358   GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1359
1360   /* we have two cases:
1361    * - temp_location was set to something !NULL (Deprecated). in this case we
1362    *   open the specified filename.
1363    * - temp_template was set, allocate a filename and open that filename
1364    */
1365   if (!queue->temp_location_set) {
1366     /* nothing to do */
1367     if (queue->temp_template == NULL)
1368       goto no_directory;
1369
1370     /* make copy of the template, we don't want to change this */
1371     name = g_strdup (queue->temp_template);
1372     fd = g_mkstemp (name);
1373     if (fd == -1)
1374       goto mkstemp_failed;
1375
1376     /* open the file for update/writing */
1377     queue->temp_file = fdopen (fd, "wb+");
1378     /* error creating file */
1379     if (queue->temp_file == NULL)
1380       goto open_failed;
1381
1382     g_free (queue->temp_location);
1383     queue->temp_location = name;
1384
1385     GST_QUEUE2_MUTEX_UNLOCK (queue);
1386
1387     /* we can't emit the notify with the lock */
1388     g_object_notify (G_OBJECT (queue), "temp-location");
1389
1390     GST_QUEUE2_MUTEX_LOCK (queue);
1391   } else {
1392     /* open the file for update/writing, this is deprecated but we still need to
1393      * support it for API/ABI compatibility */
1394     queue->temp_file = g_fopen (queue->temp_location, "wb+");
1395     /* error creating file */
1396     if (queue->temp_file == NULL)
1397       goto open_failed;
1398   }
1399   GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1400
1401   return TRUE;
1402
1403   /* ERRORS */
1404 already_opened:
1405   {
1406     GST_DEBUG_OBJECT (queue, "temp file was already open");
1407     return TRUE;
1408   }
1409 no_directory:
1410   {
1411     GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1412         (_("No Temp directory specified.")), (NULL));
1413     return FALSE;
1414   }
1415 mkstemp_failed:
1416   {
1417     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1418         (_("Could not create temp file \"%s\"."), queue->temp_template),
1419         GST_ERROR_SYSTEM);
1420     g_free (name);
1421     return FALSE;
1422   }
1423 open_failed:
1424   {
1425     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1426         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1427     g_free (name);
1428     if (fd != -1)
1429       close (fd);
1430     return FALSE;
1431   }
1432 }
1433
1434 static void
1435 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1436 {
1437   /* nothing to do */
1438   if (queue->temp_file == NULL)
1439     return;
1440
1441   GST_DEBUG_OBJECT (queue, "closing temp file");
1442
1443   fflush (queue->temp_file);
1444   fclose (queue->temp_file);
1445
1446   if (queue->temp_remove)
1447     remove (queue->temp_location);
1448
1449   queue->temp_file = NULL;
1450   clean_ranges (queue);
1451 }
1452
1453 static void
1454 gst_queue2_flush_temp_file (GstQueue2 * queue)
1455 {
1456   if (queue->temp_file == NULL)
1457     return;
1458
1459   GST_DEBUG_OBJECT (queue, "flushing temp file");
1460
1461   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1462 }
1463
1464 static void
1465 gst_queue2_locked_flush (GstQueue2 * queue)
1466 {
1467   if (!QUEUE_IS_USING_QUEUE (queue)) {
1468     if (QUEUE_IS_USING_TEMP_FILE (queue))
1469       gst_queue2_flush_temp_file (queue);
1470     init_ranges (queue);
1471   } else {
1472     while (!g_queue_is_empty (&queue->queue)) {
1473       GstMiniObject *data = g_queue_pop_head (&queue->queue);
1474
1475       /* Then lose another reference because we are supposed to destroy that
1476          data when flushing */
1477       gst_mini_object_unref (data);
1478     }
1479   }
1480   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1481   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1482   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1483   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1484   queue->sink_tainted = queue->src_tainted = TRUE;
1485   if (queue->starting_segment != NULL)
1486     gst_event_unref (queue->starting_segment);
1487   queue->starting_segment = NULL;
1488   queue->segment_event_received = FALSE;
1489   gst_event_replace (&queue->stream_start_event, NULL);
1490
1491   /* we deleted a lot of something */
1492   GST_QUEUE2_SIGNAL_DEL (queue);
1493 }
1494
1495 static gboolean
1496 gst_queue2_wait_free_space (GstQueue2 * queue)
1497 {
1498   /* We make space available if we're "full" according to whatever
1499    * the user defined as "full". */
1500   if (gst_queue2_is_filled (queue)) {
1501     gboolean started;
1502
1503     /* pause the timer while we wait. The fact that we are waiting does not mean
1504      * the byterate on the input pad is lower */
1505     if ((started = queue->in_timer_started))
1506       g_timer_stop (queue->in_timer);
1507
1508     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1509         "queue is full, waiting for free space");
1510     do {
1511       /* Wait for space to be available, we could be unlocked because of a flush. */
1512       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1513     }
1514     while (gst_queue2_is_filled (queue));
1515
1516     /* and continue if we were running before */
1517     if (started)
1518       g_timer_continue (queue->in_timer);
1519   }
1520   return TRUE;
1521
1522   /* ERRORS */
1523 out_flushing:
1524   {
1525     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1526     return FALSE;
1527   }
1528 }
1529
1530 static gboolean
1531 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1532 {
1533   GstMapInfo info;
1534   guint8 *data, *ring_buffer;
1535   guint size, rb_size;
1536   guint64 writing_pos, new_writing_pos;
1537   GstQueue2Range *range, *prev, *next;
1538
1539   if (QUEUE_IS_USING_RING_BUFFER (queue))
1540     writing_pos = queue->current->rb_writing_pos;
1541   else
1542     writing_pos = queue->current->writing_pos;
1543   ring_buffer = queue->ring_buffer;
1544   rb_size = queue->ring_buffer_max_size;
1545
1546   gst_buffer_map (buffer, &info, GST_MAP_READ);
1547
1548   size = info.size;
1549   data = info.data;
1550
1551   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1552       GST_BUFFER_OFFSET (buffer));
1553
1554   while (size > 0) {
1555     guint to_write;
1556
1557     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1558       gint64 space;
1559
1560       /* calculate the space in the ring buffer not used by data from
1561        * the current range */
1562       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1563         /* wait until there is some free space */
1564         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1565       }
1566       /* get the amount of space we have */
1567       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1568
1569       /* calculate if we need to split or if we can write the entire
1570        * buffer now */
1571       to_write = MIN (size, space);
1572
1573       /* the writing position in the ring buffer after writing (part
1574        * or all of) the buffer */
1575       new_writing_pos = (writing_pos + to_write) % rb_size;
1576
1577       prev = NULL;
1578       range = queue->ranges;
1579
1580       /* if we need to overwrite data in the ring buffer, we need to
1581        * update the ranges
1582        *
1583        * warning: this code is complicated and includes some
1584        * simplifications - pen, paper and diagrams for the cases
1585        * recommended! */
1586       while (range) {
1587         guint64 range_data_start, range_data_end;
1588         GstQueue2Range *range_to_destroy = NULL;
1589
1590         range_data_start = range->rb_offset;
1591         range_data_end = range->rb_writing_pos;
1592
1593         /* handle the special case where the range has no data in it */
1594         if (range->writing_pos == range->offset) {
1595           if (range != queue->current) {
1596             GST_DEBUG_OBJECT (queue,
1597                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1598                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1599             /* remove range */
1600             range_to_destroy = range;
1601             if (prev)
1602               prev->next = range->next;
1603           }
1604           goto next_range;
1605         }
1606
1607         if (range_data_end > range_data_start) {
1608           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1609             goto next_range;
1610
1611           if (new_writing_pos > range_data_start) {
1612             if (new_writing_pos >= range_data_end) {
1613               GST_DEBUG_OBJECT (queue,
1614                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1615                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1616               /* remove range */
1617               range_to_destroy = range;
1618               if (prev)
1619                 prev->next = range->next;
1620             } else {
1621               GST_DEBUG_OBJECT (queue,
1622                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1623                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1624                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1625                   range->offset + new_writing_pos - range_data_start,
1626                   new_writing_pos);
1627               range->offset += (new_writing_pos - range_data_start);
1628               range->rb_offset = new_writing_pos;
1629             }
1630           }
1631         } else {
1632           guint64 new_wpos_virt = writing_pos + to_write;
1633
1634           if (new_wpos_virt <= range_data_start)
1635             goto next_range;
1636
1637           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1638             GST_DEBUG_OBJECT (queue,
1639                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1640                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1641             /* remove range */
1642             range_to_destroy = range;
1643             if (prev)
1644               prev->next = range->next;
1645           } else {
1646             GST_DEBUG_OBJECT (queue,
1647                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1648                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1649                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1650                 range->offset + new_writing_pos - range_data_start,
1651                 new_writing_pos);
1652             range->offset += (new_wpos_virt - range_data_start);
1653             range->rb_offset = new_writing_pos;
1654           }
1655         }
1656
1657       next_range:
1658         if (!range_to_destroy)
1659           prev = range;
1660
1661         range = range->next;
1662         if (range_to_destroy) {
1663           if (range_to_destroy == queue->ranges)
1664             queue->ranges = range;
1665           g_slice_free (GstQueue2Range, range_to_destroy);
1666           range_to_destroy = NULL;
1667         }
1668       }
1669     } else {
1670       to_write = size;
1671       new_writing_pos = writing_pos + to_write;
1672     }
1673
1674     if (QUEUE_IS_USING_TEMP_FILE (queue)
1675         && FSEEK_FILE (queue->temp_file, writing_pos))
1676       goto seek_failed;
1677
1678     if (new_writing_pos > writing_pos) {
1679       GST_INFO_OBJECT (queue,
1680           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1681           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1682           queue->current->writing_pos, queue->current->rb_writing_pos);
1683       /* either not using ring buffer or no wrapping, just write */
1684       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1685         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1686           goto handle_error;
1687       } else {
1688         memcpy (ring_buffer + writing_pos, data, to_write);
1689       }
1690
1691       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1692         /* try to merge with next range */
1693         while ((next = queue->current->next)) {
1694           GST_INFO_OBJECT (queue,
1695               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1696               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1697           if (new_writing_pos < next->offset)
1698             break;
1699
1700           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1701               next->writing_pos);
1702
1703           /* remove the group, we could choose to not read the data in this range
1704            * again. This would involve us doing a seek to the current writing position
1705            * in the range. FIXME, It would probably make sense to do a seek when there
1706            * is a lot of data in the range we merged with to avoid reading it all
1707            * again. */
1708           queue->current->next = next->next;
1709           g_slice_free (GstQueue2Range, next);
1710
1711           debug_ranges (queue);
1712         }
1713         goto update_and_signal;
1714       }
1715     } else {
1716       /* wrapping */
1717       guint block_one, block_two;
1718
1719       block_one = rb_size - writing_pos;
1720       block_two = to_write - block_one;
1721
1722       if (block_one > 0) {
1723         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1724         /* write data to end of ring buffer */
1725         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1726           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1727             goto handle_error;
1728         } else {
1729           memcpy (ring_buffer + writing_pos, data, block_one);
1730         }
1731       }
1732
1733       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1734         goto seek_failed;
1735
1736       if (block_two > 0) {
1737         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
1738         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1739           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
1740             goto handle_error;
1741         } else {
1742           memcpy (ring_buffer, data + block_one, block_two);
1743         }
1744       }
1745     }
1746
1747   update_and_signal:
1748     /* update the writing positions */
1749     size -= to_write;
1750     GST_INFO_OBJECT (queue,
1751         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
1752         to_write, writing_pos, size);
1753
1754     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1755       data += to_write;
1756       queue->current->writing_pos += to_write;
1757       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
1758     } else {
1759       queue->current->writing_pos = writing_pos = new_writing_pos;
1760     }
1761     update_cur_level (queue, queue->current);
1762
1763     /* update the buffering status */
1764     if (queue->use_buffering)
1765       update_buffering (queue);
1766
1767     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1768         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1769
1770     GST_QUEUE2_SIGNAL_ADD (queue);
1771   }
1772
1773   gst_buffer_unmap (buffer, &info);
1774
1775   return TRUE;
1776
1777   /* ERRORS */
1778 out_flushing:
1779   {
1780     GST_DEBUG_OBJECT (queue, "we are flushing");
1781     gst_buffer_unmap (buffer, &info);
1782     /* FIXME - GST_FLOW_EOS ? */
1783     return FALSE;
1784   }
1785 seek_failed:
1786   {
1787     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1788     gst_buffer_unmap (buffer, &info);
1789     return FALSE;
1790   }
1791 handle_error:
1792   {
1793     switch (errno) {
1794       case ENOSPC:{
1795         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
1796         break;
1797       }
1798       default:{
1799         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
1800             (_("Error while writing to download file.")),
1801             ("%s", g_strerror (errno)));
1802       }
1803     }
1804     gst_buffer_unmap (buffer, &info);
1805     return FALSE;
1806   }
1807 }
1808
1809 static gboolean
1810 buffer_list_create_write (GstBuffer ** buf, guint idx, gpointer q)
1811 {
1812   GstQueue2 *queue = q;
1813
1814   GST_TRACE_OBJECT (queue,
1815       "writing buffer %u of size %" G_GSIZE_FORMAT " bytes", idx,
1816       gst_buffer_get_size (*buf));
1817
1818   if (!gst_queue2_create_write (queue, *buf)) {
1819     GST_INFO_OBJECT (queue, "create_write() returned FALSE, bailing out");
1820     return FALSE;
1821   }
1822   return TRUE;
1823 }
1824
1825 static gboolean
1826 buffer_list_calc_size (GstBuffer ** buf, guint idx, gpointer data)
1827 {
1828   guint *p_size = data;
1829   gsize buf_size;
1830
1831   buf_size = gst_buffer_get_size (*buf);
1832   GST_TRACE ("buffer %u in has size %" G_GSIZE_FORMAT, idx, buf_size);
1833   *p_size += buf_size;
1834   return TRUE;
1835 }
1836
1837 /* enqueue an item an update the level stats */
1838 static void
1839 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item,
1840     GstQueue2ItemType item_type)
1841 {
1842   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
1843     GstBuffer *buffer;
1844     guint size;
1845
1846     buffer = GST_BUFFER_CAST (item);
1847     size = gst_buffer_get_size (buffer);
1848
1849     /* add buffer to the statistics */
1850     if (QUEUE_IS_USING_QUEUE (queue)) {
1851       queue->cur_level.buffers++;
1852       queue->cur_level.bytes += size;
1853     }
1854     queue->bytes_in += size;
1855
1856     /* apply new buffer to segment stats */
1857     apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
1858     /* update the byterate stats */
1859     update_in_rates (queue);
1860
1861     if (!QUEUE_IS_USING_QUEUE (queue)) {
1862       /* FIXME - check return value? */
1863       gst_queue2_create_write (queue, buffer);
1864     }
1865   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
1866     GstBufferList *buffer_list;
1867     guint size = 0;
1868
1869     buffer_list = GST_BUFFER_LIST_CAST (item);
1870
1871     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
1872     GST_LOG_OBJECT (queue, "total size of buffer list: %u bytes", size);
1873
1874     /* add buffer to the statistics */
1875     if (QUEUE_IS_USING_QUEUE (queue)) {
1876       queue->cur_level.buffers++;
1877       queue->cur_level.bytes += size;
1878     }
1879     queue->bytes_in += size;
1880
1881     /* apply new buffer to segment stats */
1882     apply_buffer_list (queue, buffer_list, &queue->sink_segment, TRUE);
1883
1884     /* update the byterate stats */
1885     update_in_rates (queue);
1886
1887     if (!QUEUE_IS_USING_QUEUE (queue)) {
1888       gst_buffer_list_foreach (buffer_list, buffer_list_create_write, queue);
1889     }
1890   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
1891     GstEvent *event;
1892
1893     event = GST_EVENT_CAST (item);
1894
1895     switch (GST_EVENT_TYPE (event)) {
1896       case GST_EVENT_EOS:
1897         /* Zero the thresholds, this makes sure the queue is completely
1898          * filled and we can read all data from the queue. */
1899         GST_DEBUG_OBJECT (queue, "we have EOS");
1900         queue->is_eos = TRUE;
1901         break;
1902       case GST_EVENT_SEGMENT:
1903         apply_segment (queue, event, &queue->sink_segment, TRUE);
1904         /* This is our first new segment, we hold it
1905          * as we can't save it on the temp file */
1906         if (!QUEUE_IS_USING_QUEUE (queue)) {
1907           if (queue->segment_event_received)
1908             goto unexpected_event;
1909
1910           queue->segment_event_received = TRUE;
1911           if (queue->starting_segment != NULL)
1912             gst_event_unref (queue->starting_segment);
1913           queue->starting_segment = event;
1914           item = NULL;
1915         }
1916         /* a new segment allows us to accept more buffers if we got EOS
1917          * from downstream */
1918         queue->unexpected = FALSE;
1919         break;
1920       case GST_EVENT_STREAM_START:
1921         if (!QUEUE_IS_USING_QUEUE (queue)) {
1922           gst_event_replace (&queue->stream_start_event, event);
1923           gst_event_unref (event);
1924           item = NULL;
1925         }
1926         break;
1927       default:
1928         if (!QUEUE_IS_USING_QUEUE (queue))
1929           goto unexpected_event;
1930         break;
1931     }
1932   } else {
1933     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
1934         item, GST_OBJECT_NAME (queue));
1935     /* we can't really unref since we don't know what it is */
1936     item = NULL;
1937   }
1938
1939   if (item) {
1940     /* update the buffering status */
1941     if (queue->use_buffering)
1942       update_buffering (queue);
1943
1944     if (QUEUE_IS_USING_QUEUE (queue)) {
1945       g_queue_push_tail (&queue->queue, item);
1946     } else {
1947       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
1948     }
1949
1950     GST_QUEUE2_SIGNAL_ADD (queue);
1951   }
1952
1953   return;
1954
1955   /* ERRORS */
1956 unexpected_event:
1957   {
1958     g_warning
1959         ("Unexpected event of kind %s can't be added in temp file of queue %s ",
1960         gst_event_type_get_name (GST_EVENT_TYPE (item)),
1961         GST_OBJECT_NAME (queue));
1962     gst_event_unref (GST_EVENT_CAST (item));
1963     return;
1964   }
1965 }
1966
1967 /* dequeue an item from the queue and update level stats */
1968 static GstMiniObject *
1969 gst_queue2_locked_dequeue (GstQueue2 * queue, GstQueue2ItemType * item_type)
1970 {
1971   GstMiniObject *item;
1972
1973   if (!QUEUE_IS_USING_QUEUE (queue))
1974     item = gst_queue2_read_item_from_file (queue);
1975   else
1976     item = g_queue_pop_head (&queue->queue);
1977
1978   if (item == NULL)
1979     goto no_item;
1980
1981   if (GST_IS_BUFFER (item)) {
1982     GstBuffer *buffer;
1983     guint size;
1984
1985     buffer = GST_BUFFER_CAST (item);
1986     size = gst_buffer_get_size (buffer);
1987     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER;
1988
1989     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1990         "retrieved buffer %p from queue", buffer);
1991
1992     if (QUEUE_IS_USING_QUEUE (queue)) {
1993       queue->cur_level.buffers--;
1994       queue->cur_level.bytes -= size;
1995     }
1996     queue->bytes_out += size;
1997
1998     apply_buffer (queue, buffer, &queue->src_segment, FALSE);
1999     /* update the byterate stats */
2000     update_out_rates (queue);
2001     /* update the buffering */
2002     if (queue->use_buffering)
2003       update_buffering (queue);
2004
2005   } else if (GST_IS_EVENT (item)) {
2006     GstEvent *event = GST_EVENT_CAST (item);
2007
2008     *item_type = GST_QUEUE2_ITEM_TYPE_EVENT;
2009
2010     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2011         "retrieved event %p from queue", event);
2012
2013     switch (GST_EVENT_TYPE (event)) {
2014       case GST_EVENT_EOS:
2015         /* queue is empty now that we dequeued the EOS */
2016         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
2017         break;
2018       case GST_EVENT_SEGMENT:
2019         apply_segment (queue, event, &queue->src_segment, FALSE);
2020         break;
2021       default:
2022         break;
2023     }
2024   } else if (GST_IS_BUFFER_LIST (item)) {
2025     GstBufferList *buffer_list;
2026     guint size = 0;
2027
2028     buffer_list = GST_BUFFER_LIST_CAST (item);
2029     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2030     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER_LIST;
2031
2032     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2033         "retrieved buffer list %p from queue", buffer_list);
2034
2035     if (QUEUE_IS_USING_QUEUE (queue)) {
2036       queue->cur_level.buffers--;
2037       queue->cur_level.bytes -= size;
2038     }
2039     queue->bytes_out += size;
2040
2041     apply_buffer_list (queue, buffer_list, &queue->src_segment, FALSE);
2042     /* update the byterate stats */
2043     update_out_rates (queue);
2044     /* update the buffering */
2045     if (queue->use_buffering)
2046       update_buffering (queue);
2047
2048   } else {
2049     g_warning
2050         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
2051         item, GST_OBJECT_NAME (queue));
2052     item = NULL;
2053     *item_type = GST_QUEUE2_ITEM_TYPE_UNKNOWN;
2054   }
2055   GST_QUEUE2_SIGNAL_DEL (queue);
2056
2057   return item;
2058
2059   /* ERRORS */
2060 no_item:
2061   {
2062     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
2063     return NULL;
2064   }
2065 }
2066
2067 static gboolean
2068 gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
2069     GstEvent * event)
2070 {
2071   GstQueue2 *queue;
2072
2073   queue = GST_QUEUE2 (parent);
2074
2075   switch (GST_EVENT_TYPE (event)) {
2076     case GST_EVENT_FLUSH_START:
2077     {
2078       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
2079       if (QUEUE_IS_USING_QUEUE (queue)) {
2080         /* forward event */
2081         gst_pad_push_event (queue->srcpad, event);
2082
2083         /* now unblock the chain function */
2084         GST_QUEUE2_MUTEX_LOCK (queue);
2085         queue->srcresult = GST_FLOW_WRONG_STATE;
2086         queue->sinkresult = GST_FLOW_WRONG_STATE;
2087         /* unblock the loop and chain functions */
2088         GST_QUEUE2_SIGNAL_ADD (queue);
2089         GST_QUEUE2_SIGNAL_DEL (queue);
2090         GST_QUEUE2_MUTEX_UNLOCK (queue);
2091
2092         /* make sure it pauses, this should happen since we sent
2093          * flush_start downstream. */
2094         gst_pad_pause_task (queue->srcpad);
2095         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
2096       } else {
2097         GST_QUEUE2_MUTEX_LOCK (queue);
2098         /* flush the sink pad */
2099         queue->sinkresult = GST_FLOW_WRONG_STATE;
2100         GST_QUEUE2_SIGNAL_DEL (queue);
2101         GST_QUEUE2_MUTEX_UNLOCK (queue);
2102
2103         gst_event_unref (event);
2104       }
2105       goto done;
2106     }
2107     case GST_EVENT_FLUSH_STOP:
2108     {
2109       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2110
2111       if (QUEUE_IS_USING_QUEUE (queue)) {
2112         /* forward event */
2113         gst_pad_push_event (queue->srcpad, event);
2114
2115         GST_QUEUE2_MUTEX_LOCK (queue);
2116         gst_queue2_locked_flush (queue);
2117         queue->srcresult = GST_FLOW_OK;
2118         queue->sinkresult = GST_FLOW_OK;
2119         queue->is_eos = FALSE;
2120         queue->unexpected = FALSE;
2121         /* reset rate counters */
2122         reset_rate_timer (queue);
2123         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2124             queue->srcpad);
2125         GST_QUEUE2_MUTEX_UNLOCK (queue);
2126       } else {
2127         GST_QUEUE2_MUTEX_LOCK (queue);
2128         queue->segment_event_received = FALSE;
2129         queue->is_eos = FALSE;
2130         queue->unexpected = FALSE;
2131         queue->sinkresult = GST_FLOW_OK;
2132         GST_QUEUE2_MUTEX_UNLOCK (queue);
2133
2134         gst_event_unref (event);
2135       }
2136       goto done;
2137     }
2138     default:
2139       if (GST_EVENT_IS_SERIALIZED (event)) {
2140         /* serialized events go in the queue */
2141         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2142         /* refuse more events on EOS */
2143         if (queue->is_eos)
2144           goto out_eos;
2145         gst_queue2_locked_enqueue (queue, event, GST_QUEUE2_ITEM_TYPE_EVENT);
2146         GST_QUEUE2_MUTEX_UNLOCK (queue);
2147       } else {
2148         /* non-serialized events are passed upstream. */
2149         gst_pad_push_event (queue->srcpad, event);
2150       }
2151       break;
2152   }
2153 done:
2154   return TRUE;
2155
2156   /* ERRORS */
2157 out_flushing:
2158   {
2159     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2160     GST_QUEUE2_MUTEX_UNLOCK (queue);
2161     gst_event_unref (event);
2162     return FALSE;
2163   }
2164 out_eos:
2165   {
2166     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2167     GST_QUEUE2_MUTEX_UNLOCK (queue);
2168     gst_event_unref (event);
2169     return FALSE;
2170   }
2171 }
2172
2173 static gboolean
2174 gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
2175     GstQuery * query)
2176 {
2177   gboolean res;
2178
2179   switch (GST_QUERY_TYPE (query)) {
2180     default:
2181       res = gst_pad_query_default (pad, parent, query);
2182       break;
2183   }
2184   return res;
2185 }
2186
2187 static gboolean
2188 gst_queue2_is_empty (GstQueue2 * queue)
2189 {
2190   /* never empty on EOS */
2191   if (queue->is_eos)
2192     return FALSE;
2193
2194   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2195     return queue->current->writing_pos <= queue->current->max_reading_pos;
2196   } else {
2197     if (queue->queue.length == 0)
2198       return TRUE;
2199   }
2200
2201   return FALSE;
2202 }
2203
2204 static gboolean
2205 gst_queue2_is_filled (GstQueue2 * queue)
2206 {
2207   gboolean res;
2208
2209   /* always filled on EOS */
2210   if (queue->is_eos)
2211     return TRUE;
2212
2213 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2214     (queue->cur_level.format) >= ((alt_max) ? \
2215       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2216
2217   /* if using a ring buffer we're filled if all ring buffer space is used
2218    * _by the current range_ */
2219   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2220     guint64 rb_size = queue->ring_buffer_max_size;
2221     GST_DEBUG_OBJECT (queue,
2222         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2223         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2224     return CHECK_FILLED (bytes, rb_size);
2225   }
2226
2227   /* if using file, we're never filled if we don't have EOS */
2228   if (QUEUE_IS_USING_TEMP_FILE (queue))
2229     return FALSE;
2230
2231   /* we are never filled when we have no buffers at all */
2232   if (queue->cur_level.buffers == 0)
2233     return FALSE;
2234
2235   /* we are filled if one of the current levels exceeds the max */
2236   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2237       || CHECK_FILLED (time, 0);
2238
2239   /* if we need to, use the rate estimate to check against the max time we are
2240    * allowed to queue */
2241   if (queue->use_rate_estimate)
2242     res |= CHECK_FILLED (rate_time, 0);
2243
2244 #undef CHECK_FILLED
2245   return res;
2246 }
2247
2248 static GstFlowReturn
2249 gst_queue2_chain_buffer_or_buffer_list (GstQueue2 * queue,
2250     GstMiniObject * item, GstQueue2ItemType item_type)
2251 {
2252   /* we have to lock the queue since we span threads */
2253   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2254   /* when we received EOS, we refuse more data */
2255   if (queue->is_eos)
2256     goto out_eos;
2257   /* when we received unexpected from downstream, refuse more buffers */
2258   if (queue->unexpected)
2259     goto out_unexpected;
2260
2261   if (!gst_queue2_wait_free_space (queue))
2262     goto out_flushing;
2263
2264   /* put buffer in queue now */
2265   gst_queue2_locked_enqueue (queue, item, item_type);
2266   GST_QUEUE2_MUTEX_UNLOCK (queue);
2267
2268   return GST_FLOW_OK;
2269
2270   /* special conditions */
2271 out_flushing:
2272   {
2273     GstFlowReturn ret = queue->sinkresult;
2274
2275     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2276         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2277     GST_QUEUE2_MUTEX_UNLOCK (queue);
2278     gst_mini_object_unref (item);
2279
2280     return ret;
2281   }
2282 out_eos:
2283   {
2284     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2285     GST_QUEUE2_MUTEX_UNLOCK (queue);
2286     gst_mini_object_unref (item);
2287
2288     return GST_FLOW_EOS;
2289   }
2290 out_unexpected:
2291   {
2292     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2293     GST_QUEUE2_MUTEX_UNLOCK (queue);
2294     gst_mini_object_unref (item);
2295
2296     return GST_FLOW_EOS;
2297   }
2298 }
2299
2300 static GstFlowReturn
2301 gst_queue2_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2302 {
2303   GstQueue2 *queue;
2304
2305   queue = GST_QUEUE2 (parent);
2306
2307   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of "
2308       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
2309       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
2310       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2311       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2312
2313   return gst_queue2_chain_buffer_or_buffer_list (queue,
2314       GST_MINI_OBJECT_CAST (buffer), GST_QUEUE2_ITEM_TYPE_BUFFER);
2315 }
2316
2317 static GstFlowReturn
2318 gst_queue2_chain_list (GstPad * pad, GstObject * parent,
2319     GstBufferList * buffer_list)
2320 {
2321   GstQueue2 *queue;
2322
2323   queue = GST_QUEUE2 (parent);
2324
2325   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2326       "received buffer list %p", buffer_list);
2327
2328   return gst_queue2_chain_buffer_or_buffer_list (queue,
2329       GST_MINI_OBJECT_CAST (buffer_list), GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2330 }
2331
2332 static GstMiniObject *
2333 gst_queue2_dequeue_on_eos (GstQueue2 * queue, GstQueue2ItemType * item_type)
2334 {
2335   GstMiniObject *data;
2336
2337   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
2338
2339   /* stop pushing buffers, we dequeue all items until we see an item that we
2340    * can push again, which is EOS or SEGMENT. If there is nothing in the
2341    * queue we can push, we set a flag to make the sinkpad refuse more
2342    * buffers with an EOS return value until we receive something
2343    * pushable again or we get flushed. */
2344   while ((data = gst_queue2_locked_dequeue (queue, item_type))) {
2345     if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2346       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2347           "dropping EOS buffer %p", data);
2348       gst_buffer_unref (GST_BUFFER_CAST (data));
2349     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2350       GstEvent *event = GST_EVENT_CAST (data);
2351       GstEventType type = GST_EVENT_TYPE (event);
2352
2353       if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
2354         /* we found a pushable item in the queue, push it out */
2355         GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2356             "pushing pushable event %s after EOS", GST_EVENT_TYPE_NAME (event));
2357         return data;
2358       }
2359       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2360           "dropping EOS event %p", event);
2361       gst_event_unref (event);
2362     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2363       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2364           "dropping EOS buffer list %p", data);
2365       gst_buffer_list_unref (GST_BUFFER_LIST_CAST (data));
2366     }
2367   }
2368   /* no more items in the queue. Set the unexpected flag so that upstream
2369    * make us refuse any more buffers on the sinkpad. Since we will still
2370    * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
2371    * task function does not shut down. */
2372   queue->unexpected = TRUE;
2373   return NULL;
2374 }
2375
2376 /* dequeue an item from the queue an push it downstream. This functions returns
2377  * the result of the push. */
2378 static GstFlowReturn
2379 gst_queue2_push_one (GstQueue2 * queue)
2380 {
2381   GstFlowReturn result = GST_FLOW_OK;
2382   GstMiniObject *data;
2383   GstQueue2ItemType item_type;
2384
2385   data = gst_queue2_locked_dequeue (queue, &item_type);
2386   if (data == NULL)
2387     goto no_item;
2388
2389 next:
2390   GST_QUEUE2_MUTEX_UNLOCK (queue);
2391
2392   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2393     GstBuffer *buffer;
2394 #if 0
2395     GstCaps *caps;
2396 #endif
2397
2398     buffer = GST_BUFFER_CAST (data);
2399 #if 0
2400     caps = GST_BUFFER_CAPS (buffer);
2401 #endif
2402
2403 #if 0
2404     /* set caps before pushing the buffer so that core does not try to do
2405      * something fancy to check if this is possible. */
2406     if (caps && caps != GST_PAD_CAPS (queue->srcpad))
2407       gst_pad_set_caps (queue->srcpad, caps);
2408 #endif
2409
2410     result = gst_pad_push (queue->srcpad, buffer);
2411
2412     /* need to check for srcresult here as well */
2413     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2414     if (result == GST_FLOW_EOS) {
2415       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2416       if (data != NULL)
2417         goto next;
2418       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2419        * to the caller so that the task function does not shut down */
2420       result = GST_FLOW_OK;
2421     }
2422   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2423     GstEvent *event = GST_EVENT_CAST (data);
2424     GstEventType type = GST_EVENT_TYPE (event);
2425
2426     gst_pad_push_event (queue->srcpad, event);
2427
2428     /* if we're EOS, return EOS so that the task pauses. */
2429     if (type == GST_EVENT_EOS) {
2430       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2431           "pushed EOS event %p, return EOS", event);
2432       result = GST_FLOW_EOS;
2433     }
2434
2435     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2436   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2437     GstBufferList *buffer_list;
2438 #if 0
2439     GstBuffer *first_buf;
2440     GstCaps *caps;
2441 #endif
2442
2443     buffer_list = GST_BUFFER_LIST_CAST (data);
2444
2445 #if 0
2446     first_buf = gst_buffer_list_get (buffer_list, 0);
2447     caps = (first_buf != NULL) ? GST_BUFFER_CAPS (first_buf) : NULL;
2448
2449     /* set caps before pushing the buffer so that core does not try to do
2450      * something fancy to check if this is possible. */
2451     if (caps && caps != GST_PAD_CAPS (queue->srcpad))
2452       gst_pad_set_caps (queue->srcpad, caps);
2453 #endif
2454
2455     result = gst_pad_push_list (queue->srcpad, buffer_list);
2456
2457     /* need to check for srcresult here as well */
2458     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2459     if (result == GST_FLOW_EOS) {
2460       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2461       if (data != NULL)
2462         goto next;
2463       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2464        * to the caller so that the task function does not shut down */
2465       result = GST_FLOW_OK;
2466     }
2467   }
2468   return result;
2469
2470   /* ERRORS */
2471 no_item:
2472   {
2473     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2474         "exit because we have no item in the queue");
2475     return GST_FLOW_ERROR;
2476   }
2477 out_flushing:
2478   {
2479     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2480     return GST_FLOW_WRONG_STATE;
2481   }
2482 }
2483
2484 /* called repeatedly with @pad as the source pad. This function should push out
2485  * data to the peer element. */
2486 static void
2487 gst_queue2_loop (GstPad * pad)
2488 {
2489   GstQueue2 *queue;
2490   GstFlowReturn ret;
2491
2492   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2493
2494   /* have to lock for thread-safety */
2495   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2496
2497   if (gst_queue2_is_empty (queue)) {
2498     gboolean started;
2499
2500     /* pause the timer while we wait. The fact that we are waiting does not mean
2501      * the byterate on the output pad is lower */
2502     if ((started = queue->out_timer_started))
2503       g_timer_stop (queue->out_timer);
2504
2505     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2506         "queue is empty, waiting for new data");
2507     do {
2508       /* Wait for data to be available, we could be unlocked because of a flush. */
2509       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2510     }
2511     while (gst_queue2_is_empty (queue));
2512
2513     /* and continue if we were running before */
2514     if (started)
2515       g_timer_continue (queue->out_timer);
2516   }
2517   ret = gst_queue2_push_one (queue);
2518   queue->srcresult = ret;
2519   queue->sinkresult = ret;
2520   if (ret != GST_FLOW_OK)
2521     goto out_flushing;
2522
2523   GST_QUEUE2_MUTEX_UNLOCK (queue);
2524
2525   return;
2526
2527   /* ERRORS */
2528 out_flushing:
2529   {
2530     gboolean eos = queue->is_eos;
2531     GstFlowReturn ret = queue->srcresult;
2532
2533     gst_pad_pause_task (queue->srcpad);
2534     GST_QUEUE2_MUTEX_UNLOCK (queue);
2535     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2536         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2537     /* let app know about us giving up if upstream is not expected to do so */
2538     /* EOS is already taken care of elsewhere */
2539     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
2540       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2541           (_("Internal data flow error.")),
2542           ("streaming task paused, reason %s (%d)",
2543               gst_flow_get_name (ret), ret));
2544       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2545     }
2546     return;
2547   }
2548 }
2549
2550 static gboolean
2551 gst_queue2_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2552 {
2553   gboolean res = TRUE;
2554   GstQueue2 *queue = GST_QUEUE2 (parent);
2555
2556 #ifndef GST_DISABLE_GST_DEBUG
2557   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
2558       event, GST_EVENT_TYPE_NAME (event));
2559 #endif
2560
2561   switch (GST_EVENT_TYPE (event)) {
2562     case GST_EVENT_FLUSH_START:
2563       if (QUEUE_IS_USING_QUEUE (queue)) {
2564         /* just forward upstream */
2565         res = gst_pad_push_event (queue->sinkpad, event);
2566       } else {
2567         /* now unblock the getrange function */
2568         GST_QUEUE2_MUTEX_LOCK (queue);
2569         GST_DEBUG_OBJECT (queue, "flushing");
2570         queue->srcresult = GST_FLOW_WRONG_STATE;
2571         GST_QUEUE2_SIGNAL_ADD (queue);
2572         GST_QUEUE2_MUTEX_UNLOCK (queue);
2573
2574         /* when using a temp file, we eat the event */
2575         res = TRUE;
2576         gst_event_unref (event);
2577       }
2578       break;
2579     case GST_EVENT_FLUSH_STOP:
2580       if (QUEUE_IS_USING_QUEUE (queue)) {
2581         /* just forward upstream */
2582         res = gst_pad_push_event (queue->sinkpad, event);
2583       } else {
2584         /* now unblock the getrange function */
2585         GST_QUEUE2_MUTEX_LOCK (queue);
2586         queue->srcresult = GST_FLOW_OK;
2587         if (queue->current) {
2588           /* forget the highest read offset, we'll calculate a new one when we
2589            * get the next getrange request. We need to do this in order to reset
2590            * the buffering percentage */
2591           queue->current->max_reading_pos = 0;
2592         }
2593         GST_QUEUE2_MUTEX_UNLOCK (queue);
2594
2595         /* when using a temp file, we eat the event */
2596         res = TRUE;
2597         gst_event_unref (event);
2598       }
2599       break;
2600     default:
2601       res = gst_pad_push_event (queue->sinkpad, event);
2602       break;
2603   }
2604
2605   return res;
2606 }
2607
2608 static gboolean
2609 gst_queue2_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2610 {
2611   GstQueue2 *queue;
2612
2613   queue = GST_QUEUE2 (parent);
2614
2615   switch (GST_QUERY_TYPE (query)) {
2616     case GST_QUERY_POSITION:
2617     {
2618       gint64 peer_pos;
2619       GstFormat format;
2620
2621       if (!gst_pad_peer_query (queue->sinkpad, query))
2622         goto peer_failed;
2623
2624       /* get peer position */
2625       gst_query_parse_position (query, &format, &peer_pos);
2626
2627       /* FIXME: this code assumes that there's no discont in the queue */
2628       switch (format) {
2629         case GST_FORMAT_BYTES:
2630           peer_pos -= queue->cur_level.bytes;
2631           break;
2632         case GST_FORMAT_TIME:
2633           peer_pos -= queue->cur_level.time;
2634           break;
2635         default:
2636           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
2637               "know how to adjust value", gst_format_get_name (format));
2638           return FALSE;
2639       }
2640       /* set updated position */
2641       gst_query_set_position (query, format, peer_pos);
2642       break;
2643     }
2644     case GST_QUERY_DURATION:
2645     {
2646       GST_DEBUG_OBJECT (queue, "doing peer query");
2647
2648       if (!gst_pad_peer_query (queue->sinkpad, query))
2649         goto peer_failed;
2650
2651       GST_DEBUG_OBJECT (queue, "peer query success");
2652       break;
2653     }
2654     case GST_QUERY_BUFFERING:
2655     {
2656       GstFormat format;
2657
2658       GST_DEBUG_OBJECT (queue, "query buffering");
2659
2660       /* FIXME - is this condition correct? what should ring buffer do? */
2661       if (QUEUE_IS_USING_QUEUE (queue)) {
2662         /* no temp file, just forward to the peer */
2663         if (!gst_pad_peer_query (queue->sinkpad, query))
2664           goto peer_failed;
2665         GST_DEBUG_OBJECT (queue, "buffering forwarded to peer");
2666       } else {
2667         gint64 start, stop, range_start, range_stop;
2668         guint64 writing_pos;
2669         gint percent;
2670         gint64 estimated_total, buffering_left;
2671         gint64 duration;
2672         gboolean peer_res, is_buffering, is_eos;
2673         gdouble byte_in_rate, byte_out_rate;
2674         GstQueue2Range *queued_ranges;
2675
2676         /* we need a current download region */
2677         if (queue->current == NULL)
2678           return FALSE;
2679
2680         writing_pos = queue->current->writing_pos;
2681         byte_in_rate = queue->byte_in_rate;
2682         byte_out_rate = queue->byte_out_rate;
2683         is_buffering = queue->is_buffering;
2684         is_eos = queue->is_eos;
2685         percent = queue->buffering_percent;
2686
2687         if (is_eos) {
2688           /* we're EOS, we know the duration in bytes now */
2689           peer_res = TRUE;
2690           duration = writing_pos;
2691         } else {
2692           /* get duration of upstream in bytes */
2693           peer_res = gst_pad_peer_query_duration (queue->sinkpad,
2694               GST_FORMAT_BYTES, &duration);
2695         }
2696
2697         /* calculate remaining and total download time */
2698         if (peer_res && byte_in_rate > 0.0) {
2699           estimated_total = (duration * 1000) / byte_in_rate;
2700           buffering_left = ((duration - writing_pos) * 1000) / byte_in_rate;
2701         } else {
2702           estimated_total = -1;
2703           buffering_left = -1;
2704         }
2705         GST_DEBUG_OBJECT (queue, "estimated %" G_GINT64_FORMAT ", left %"
2706             G_GINT64_FORMAT, estimated_total, buffering_left);
2707
2708         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
2709
2710         switch (format) {
2711           case GST_FORMAT_PERCENT:
2712             /* we need duration */
2713             if (!peer_res)
2714               goto peer_failed;
2715
2716             GST_DEBUG_OBJECT (queue,
2717                 "duration %" G_GINT64_FORMAT ", writing %" G_GINT64_FORMAT,
2718                 duration, writing_pos);
2719
2720             start = 0;
2721             /* get our available data relative to the duration */
2722             if (duration != -1)
2723               stop = GST_FORMAT_PERCENT_MAX * writing_pos / duration;
2724             else
2725               stop = -1;
2726             break;
2727           case GST_FORMAT_BYTES:
2728             start = 0;
2729             stop = writing_pos;
2730             break;
2731           default:
2732             start = -1;
2733             stop = -1;
2734             break;
2735         }
2736
2737         /* fill out the buffered ranges */
2738         for (queued_ranges = queue->ranges; queued_ranges;
2739             queued_ranges = queued_ranges->next) {
2740           switch (format) {
2741             case GST_FORMAT_PERCENT:
2742               if (duration == -1) {
2743                 range_start = 0;
2744                 range_stop = 0;
2745                 break;
2746               }
2747               range_start = 100 * queued_ranges->offset / duration;
2748               range_stop = 100 * queued_ranges->writing_pos / duration;
2749               break;
2750             case GST_FORMAT_BYTES:
2751               range_start = queued_ranges->offset;
2752               range_stop = queued_ranges->writing_pos;
2753               break;
2754             default:
2755               range_start = -1;
2756               range_stop = -1;
2757               break;
2758           }
2759           if (range_start == range_stop)
2760             continue;
2761           GST_DEBUG_OBJECT (queue,
2762               "range starting at %" G_GINT64_FORMAT " and finishing at %"
2763               G_GINT64_FORMAT, range_start, range_stop);
2764           gst_query_add_buffering_range (query, range_start, range_stop);
2765         }
2766
2767         gst_query_set_buffering_percent (query, is_buffering, percent);
2768         gst_query_set_buffering_range (query, format, start, stop,
2769             estimated_total);
2770         gst_query_set_buffering_stats (query, GST_BUFFERING_DOWNLOAD,
2771             byte_in_rate, byte_out_rate, buffering_left);
2772       }
2773       break;
2774     }
2775     case GST_QUERY_SCHEDULING:
2776     {
2777       gboolean pull_mode;
2778       GstSchedulingFlags flags = 0;
2779
2780       /* we can operate in pull mode when we are using a tempfile */
2781       pull_mode = !QUEUE_IS_USING_QUEUE (queue);
2782
2783       if (pull_mode)
2784         flags |= GST_SCHEDULING_FLAG_SEEKABLE;
2785       gst_query_set_scheduling (query, flags, 0, -1, 0);
2786       if (pull_mode)
2787         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
2788       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
2789       break;
2790     }
2791     default:
2792       /* peer handled other queries */
2793       if (!gst_pad_query_default (pad, parent, query))
2794         goto peer_failed;
2795       break;
2796   }
2797
2798   return TRUE;
2799
2800   /* ERRORS */
2801 peer_failed:
2802   {
2803     GST_DEBUG_OBJECT (queue, "failed peer query");
2804     return FALSE;
2805   }
2806 }
2807
2808 static gboolean
2809 gst_queue2_handle_query (GstElement * element, GstQuery * query)
2810 {
2811   GstQueue2 *queue = GST_QUEUE2 (element);
2812
2813   /* simply forward to the srcpad query function */
2814   return gst_queue2_handle_src_query (queue->srcpad, GST_OBJECT_CAST (element),
2815       query);
2816 }
2817
2818 static void
2819 gst_queue2_update_upstream_size (GstQueue2 * queue)
2820 {
2821   gint64 upstream_size = -1;
2822
2823   if (gst_pad_peer_query_duration (queue->sinkpad, GST_FORMAT_BYTES,
2824           &upstream_size)) {
2825     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
2826     queue->upstream_size = upstream_size;
2827   }
2828 }
2829
2830 static GstFlowReturn
2831 gst_queue2_get_range (GstPad * pad, GstObject * parent, guint64 offset,
2832     guint length, GstBuffer ** buffer)
2833 {
2834   GstQueue2 *queue;
2835   GstFlowReturn ret;
2836
2837   queue = GST_QUEUE2_CAST (parent);
2838
2839   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
2840   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2841   offset = (offset == -1) ? queue->current->reading_pos : offset;
2842
2843   GST_DEBUG_OBJECT (queue,
2844       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
2845
2846   /* catch any reads beyond the size of the file here to make sure queue2
2847    * doesn't send seek events beyond the size of the file upstream, since
2848    * that would confuse elements such as souphttpsrc and/or http servers.
2849    * Demuxers often just loop until EOS at the end of the file to figure out
2850    * when they've read all the end-headers or index chunks. */
2851   if (G_UNLIKELY (offset >= queue->upstream_size)) {
2852     gst_queue2_update_upstream_size (queue);
2853     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
2854       goto out_unexpected;
2855   }
2856
2857   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
2858     gst_queue2_update_upstream_size (queue);
2859     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
2860       length = queue->upstream_size - offset;
2861       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
2862     }
2863   }
2864
2865   /* FIXME - function will block when the range is not yet available */
2866   ret = gst_queue2_create_read (queue, offset, length, buffer);
2867   GST_QUEUE2_MUTEX_UNLOCK (queue);
2868
2869   return ret;
2870
2871   /* ERRORS */
2872 out_flushing:
2873   {
2874     ret = queue->srcresult;
2875
2876     GST_DEBUG_OBJECT (queue, "we are flushing");
2877     GST_QUEUE2_MUTEX_UNLOCK (queue);
2878     return ret;
2879   }
2880 out_unexpected:
2881   {
2882     GST_DEBUG_OBJECT (queue, "read beyond end of file");
2883     GST_QUEUE2_MUTEX_UNLOCK (queue);
2884     return GST_FLOW_EOS;
2885   }
2886 }
2887
2888 /* sink currently only operates in push mode */
2889 static gboolean
2890 gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
2891     GstPadMode mode, gboolean active)
2892 {
2893   gboolean result;
2894   GstQueue2 *queue;
2895
2896   queue = GST_QUEUE2 (parent);
2897
2898   switch (mode) {
2899     case GST_PAD_MODE_PUSH:
2900       if (active) {
2901         GST_QUEUE2_MUTEX_LOCK (queue);
2902         GST_DEBUG_OBJECT (queue, "activating push mode");
2903         queue->srcresult = GST_FLOW_OK;
2904         queue->sinkresult = GST_FLOW_OK;
2905         queue->is_eos = FALSE;
2906         queue->unexpected = FALSE;
2907         reset_rate_timer (queue);
2908         GST_QUEUE2_MUTEX_UNLOCK (queue);
2909       } else {
2910         /* unblock chain function */
2911         GST_QUEUE2_MUTEX_LOCK (queue);
2912         GST_DEBUG_OBJECT (queue, "deactivating push mode");
2913         queue->srcresult = GST_FLOW_WRONG_STATE;
2914         queue->sinkresult = GST_FLOW_WRONG_STATE;
2915         gst_queue2_locked_flush (queue);
2916         GST_QUEUE2_MUTEX_UNLOCK (queue);
2917       }
2918       result = TRUE;
2919       break;
2920     default:
2921       result = FALSE;
2922       break;
2923   }
2924   return result;
2925 }
2926
2927 /* src operating in push mode, we start a task on the source pad that pushes out
2928  * buffers from the queue */
2929 static gboolean
2930 gst_queue2_src_activate_push (GstPad * pad, GstObject * parent, gboolean active)
2931 {
2932   gboolean result = FALSE;
2933   GstQueue2 *queue;
2934
2935   queue = GST_QUEUE2 (parent);
2936
2937   if (active) {
2938     GST_QUEUE2_MUTEX_LOCK (queue);
2939     GST_DEBUG_OBJECT (queue, "activating push mode");
2940     queue->srcresult = GST_FLOW_OK;
2941     queue->sinkresult = GST_FLOW_OK;
2942     queue->is_eos = FALSE;
2943     queue->unexpected = FALSE;
2944     result = gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad);
2945     GST_QUEUE2_MUTEX_UNLOCK (queue);
2946   } else {
2947     /* unblock loop function */
2948     GST_QUEUE2_MUTEX_LOCK (queue);
2949     GST_DEBUG_OBJECT (queue, "deactivating push mode");
2950     queue->srcresult = GST_FLOW_WRONG_STATE;
2951     queue->sinkresult = GST_FLOW_WRONG_STATE;
2952     /* the item add signal will unblock */
2953     GST_QUEUE2_SIGNAL_ADD (queue);
2954     GST_QUEUE2_MUTEX_UNLOCK (queue);
2955
2956     /* step 2, make sure streaming finishes */
2957     result = gst_pad_stop_task (pad);
2958   }
2959
2960   return result;
2961 }
2962
2963 /* pull mode, downstream will call our getrange function */
2964 static gboolean
2965 gst_queue2_src_activate_pull (GstPad * pad, GstObject * parent, gboolean active)
2966 {
2967   gboolean result;
2968   GstQueue2 *queue;
2969
2970   queue = GST_QUEUE2 (parent);
2971
2972   if (active) {
2973     GST_QUEUE2_MUTEX_LOCK (queue);
2974     if (!QUEUE_IS_USING_QUEUE (queue)) {
2975       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2976         /* open the temp file now */
2977         result = gst_queue2_open_temp_location_file (queue);
2978       } else if (!queue->ring_buffer) {
2979         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
2980         result = ! !queue->ring_buffer;
2981       } else {
2982         result = TRUE;
2983       }
2984
2985       GST_DEBUG_OBJECT (queue, "activating pull mode");
2986       init_ranges (queue);
2987       queue->srcresult = GST_FLOW_OK;
2988       queue->sinkresult = GST_FLOW_OK;
2989       queue->is_eos = FALSE;
2990       queue->unexpected = FALSE;
2991       queue->upstream_size = 0;
2992     } else {
2993       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
2994       /* this is not allowed, we cannot operate in pull mode without a temp
2995        * file. */
2996       queue->srcresult = GST_FLOW_WRONG_STATE;
2997       queue->sinkresult = GST_FLOW_WRONG_STATE;
2998       result = FALSE;
2999     }
3000     GST_QUEUE2_MUTEX_UNLOCK (queue);
3001   } else {
3002     GST_QUEUE2_MUTEX_LOCK (queue);
3003     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
3004     queue->srcresult = GST_FLOW_WRONG_STATE;
3005     queue->sinkresult = GST_FLOW_WRONG_STATE;
3006     /* this will unlock getrange */
3007     GST_QUEUE2_SIGNAL_ADD (queue);
3008     result = TRUE;
3009     GST_QUEUE2_MUTEX_UNLOCK (queue);
3010   }
3011
3012   return result;
3013 }
3014
3015 static gboolean
3016 gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
3017     gboolean active)
3018 {
3019   gboolean res;
3020
3021   switch (mode) {
3022     case GST_PAD_MODE_PULL:
3023       res = gst_queue2_src_activate_pull (pad, parent, active);
3024       break;
3025     case GST_PAD_MODE_PUSH:
3026       res = gst_queue2_src_activate_push (pad, parent, active);
3027       break;
3028     default:
3029       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
3030       res = FALSE;
3031       break;
3032   }
3033   return res;
3034 }
3035
3036 static GstStateChangeReturn
3037 gst_queue2_change_state (GstElement * element, GstStateChange transition)
3038 {
3039   GstQueue2 *queue;
3040   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3041
3042   queue = GST_QUEUE2 (element);
3043
3044   switch (transition) {
3045     case GST_STATE_CHANGE_NULL_TO_READY:
3046       break;
3047     case GST_STATE_CHANGE_READY_TO_PAUSED:
3048       GST_QUEUE2_MUTEX_LOCK (queue);
3049       if (!QUEUE_IS_USING_QUEUE (queue)) {
3050         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3051           if (!gst_queue2_open_temp_location_file (queue))
3052             ret = GST_STATE_CHANGE_FAILURE;
3053         } else {
3054           if (queue->ring_buffer) {
3055             g_free (queue->ring_buffer);
3056             queue->ring_buffer = NULL;
3057           }
3058           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
3059             ret = GST_STATE_CHANGE_FAILURE;
3060         }
3061         init_ranges (queue);
3062       }
3063       queue->segment_event_received = FALSE;
3064       queue->starting_segment = NULL;
3065       gst_event_replace (&queue->stream_start_event, NULL);
3066       GST_QUEUE2_MUTEX_UNLOCK (queue);
3067       break;
3068     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3069       break;
3070     default:
3071       break;
3072   }
3073
3074   if (ret == GST_STATE_CHANGE_FAILURE)
3075     return ret;
3076
3077   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3078
3079   if (ret == GST_STATE_CHANGE_FAILURE)
3080     return ret;
3081
3082   switch (transition) {
3083     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3084       break;
3085     case GST_STATE_CHANGE_PAUSED_TO_READY:
3086       GST_QUEUE2_MUTEX_LOCK (queue);
3087       if (!QUEUE_IS_USING_QUEUE (queue)) {
3088         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3089           gst_queue2_close_temp_location_file (queue);
3090         } else if (queue->ring_buffer) {
3091           g_free (queue->ring_buffer);
3092           queue->ring_buffer = NULL;
3093         }
3094         clean_ranges (queue);
3095       }
3096       if (queue->starting_segment != NULL) {
3097         gst_event_unref (queue->starting_segment);
3098         queue->starting_segment = NULL;
3099       }
3100       gst_event_replace (&queue->stream_start_event, NULL);
3101       GST_QUEUE2_MUTEX_UNLOCK (queue);
3102       break;
3103     case GST_STATE_CHANGE_READY_TO_NULL:
3104       break;
3105     default:
3106       break;
3107   }
3108
3109   return ret;
3110 }
3111
3112 /* changing the capacity of the queue must wake up
3113  * the _chain function, it might have more room now
3114  * to store the buffer/event in the queue */
3115 #define QUEUE_CAPACITY_CHANGE(q)\
3116   GST_QUEUE2_SIGNAL_DEL (queue);
3117
3118 /* Changing the minimum required fill level must
3119  * wake up the _loop function as it might now
3120  * be able to preceed.
3121  */
3122 #define QUEUE_THRESHOLD_CHANGE(q)\
3123   GST_QUEUE2_SIGNAL_ADD (queue);
3124
3125 static void
3126 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
3127 {
3128   GstState state;
3129
3130   /* the element must be stopped in order to do this */
3131   GST_OBJECT_LOCK (queue);
3132   state = GST_STATE (queue);
3133   if (state != GST_STATE_READY && state != GST_STATE_NULL)
3134     goto wrong_state;
3135   GST_OBJECT_UNLOCK (queue);
3136
3137   /* set new location */
3138   g_free (queue->temp_template);
3139   queue->temp_template = g_strdup (template);
3140
3141   return;
3142
3143 /* ERROR */
3144 wrong_state:
3145   {
3146     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
3147     GST_OBJECT_UNLOCK (queue);
3148   }
3149 }
3150
3151 static void
3152 gst_queue2_set_property (GObject * object,
3153     guint prop_id, const GValue * value, GParamSpec * pspec)
3154 {
3155   GstQueue2 *queue = GST_QUEUE2 (object);
3156
3157   /* someone could change levels here, and since this
3158    * affects the get/put funcs, we need to lock for safety. */
3159   GST_QUEUE2_MUTEX_LOCK (queue);
3160
3161   switch (prop_id) {
3162     case PROP_MAX_SIZE_BYTES:
3163       queue->max_level.bytes = g_value_get_uint (value);
3164       QUEUE_CAPACITY_CHANGE (queue);
3165       break;
3166     case PROP_MAX_SIZE_BUFFERS:
3167       queue->max_level.buffers = g_value_get_uint (value);
3168       QUEUE_CAPACITY_CHANGE (queue);
3169       break;
3170     case PROP_MAX_SIZE_TIME:
3171       queue->max_level.time = g_value_get_uint64 (value);
3172       /* set rate_time to the same value. We use an extra field in the level
3173        * structure so that we can easily access and compare it */
3174       queue->max_level.rate_time = queue->max_level.time;
3175       QUEUE_CAPACITY_CHANGE (queue);
3176       break;
3177     case PROP_USE_BUFFERING:
3178       queue->use_buffering = g_value_get_boolean (value);
3179       break;
3180     case PROP_USE_RATE_ESTIMATE:
3181       queue->use_rate_estimate = g_value_get_boolean (value);
3182       break;
3183     case PROP_LOW_PERCENT:
3184       queue->low_percent = g_value_get_int (value);
3185       break;
3186     case PROP_HIGH_PERCENT:
3187       queue->high_percent = g_value_get_int (value);
3188       break;
3189     case PROP_TEMP_TEMPLATE:
3190       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3191       break;
3192     case PROP_TEMP_LOCATION:
3193       g_free (queue->temp_location);
3194       queue->temp_location = g_value_dup_string (value);
3195       /* you can set the property back to NULL to make it use the temp-tmpl
3196        * property. */
3197       queue->temp_location_set = queue->temp_location != NULL;
3198       break;
3199     case PROP_TEMP_REMOVE:
3200       queue->temp_remove = g_value_get_boolean (value);
3201       break;
3202     case PROP_RING_BUFFER_MAX_SIZE:
3203       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3204       break;
3205     default:
3206       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3207       break;
3208   }
3209
3210   GST_QUEUE2_MUTEX_UNLOCK (queue);
3211 }
3212
3213 static void
3214 gst_queue2_get_property (GObject * object,
3215     guint prop_id, GValue * value, GParamSpec * pspec)
3216 {
3217   GstQueue2 *queue = GST_QUEUE2 (object);
3218
3219   GST_QUEUE2_MUTEX_LOCK (queue);
3220
3221   switch (prop_id) {
3222     case PROP_CUR_LEVEL_BYTES:
3223       g_value_set_uint (value, queue->cur_level.bytes);
3224       break;
3225     case PROP_CUR_LEVEL_BUFFERS:
3226       g_value_set_uint (value, queue->cur_level.buffers);
3227       break;
3228     case PROP_CUR_LEVEL_TIME:
3229       g_value_set_uint64 (value, queue->cur_level.time);
3230       break;
3231     case PROP_MAX_SIZE_BYTES:
3232       g_value_set_uint (value, queue->max_level.bytes);
3233       break;
3234     case PROP_MAX_SIZE_BUFFERS:
3235       g_value_set_uint (value, queue->max_level.buffers);
3236       break;
3237     case PROP_MAX_SIZE_TIME:
3238       g_value_set_uint64 (value, queue->max_level.time);
3239       break;
3240     case PROP_USE_BUFFERING:
3241       g_value_set_boolean (value, queue->use_buffering);
3242       break;
3243     case PROP_USE_RATE_ESTIMATE:
3244       g_value_set_boolean (value, queue->use_rate_estimate);
3245       break;
3246     case PROP_LOW_PERCENT:
3247       g_value_set_int (value, queue->low_percent);
3248       break;
3249     case PROP_HIGH_PERCENT:
3250       g_value_set_int (value, queue->high_percent);
3251       break;
3252     case PROP_TEMP_TEMPLATE:
3253       g_value_set_string (value, queue->temp_template);
3254       break;
3255     case PROP_TEMP_LOCATION:
3256       g_value_set_string (value, queue->temp_location);
3257       break;
3258     case PROP_TEMP_REMOVE:
3259       g_value_set_boolean (value, queue->temp_remove);
3260       break;
3261     case PROP_RING_BUFFER_MAX_SIZE:
3262       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3263       break;
3264     default:
3265       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3266       break;
3267   }
3268
3269   GST_QUEUE2_MUTEX_UNLOCK (queue);
3270 }