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