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