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