basesrc: Downgrade EOS warning
[platform/upstream/gstreamer.git] / plugins / elements / gstdownloadbuffer.c
1 /* GStreamer
2  * Copyright (C) 2014 Wim Taymans <wim.taymans@gmail.com>
3  *
4  * gstdownloadbuffer.c:
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:element-downloadbuffer
24  * @title: downloadbuffer
25  *
26  * The downloadbuffer element provides on-disk buffering and caching of, typically,
27  * a network file. temp-template should be set to a value such as
28  * /tmp/gstreamer-XXXXXX and the element will allocate a random free filename and
29  * buffer the data in the file.
30  *
31  * With max-size-bytes and max-size-time you can configure the buffering limits.
32  * The downloadbuffer element will try to read-ahead these amounts of data. When
33  * the amount of read-ahead data drops below low-percent of the configured max,
34  * the element will start emitting BUFFERING messages until high-percent of max is
35  * reached again.
36  *
37  * The downloadbuffer provides push and pull based scheduling on its source pad
38  * and will efficiently seek in the upstream element when needed.
39  *
40  * The temp-location property will be used to notify the application of the
41  * allocated filename.
42  *
43  * When the downloadbuffer has completely downloaded the media, it will
44  * post an application message named  <classname>&quot;GstCacheDownloadComplete&quot;</classname>
45  * with the following information:
46  *
47  * *
48  *   G_TYPE_STRING
49  *   <classname>&quot;location&quot;</classname>:
50  *   the location of the completely downloaded file.
51  *
52  */
53
54 #ifdef HAVE_CONFIG_H
55 #include "config.h"
56 #endif
57
58 #include "gstdownloadbuffer.h"
59
60 #include <glib/gstdio.h>
61
62 #include "gst/gst-i18n-lib.h"
63 #include "gst/glib-compat-private.h"
64
65 #include <string.h>
66
67 #ifdef G_OS_WIN32
68 #include <io.h>                 /* lseek, open, close, read */
69 #undef lseek
70 #define lseek _lseeki64
71 #else
72 #include <unistd.h>
73 #endif
74
75 #ifdef __BIONIC__
76 #include <fcntl.h>
77 #endif
78
79 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
80     GST_PAD_SINK,
81     GST_PAD_ALWAYS,
82     GST_STATIC_CAPS_ANY);
83
84 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
85     GST_PAD_SRC,
86     GST_PAD_ALWAYS,
87     GST_STATIC_CAPS_ANY);
88
89 GST_DEBUG_CATEGORY_STATIC (downloadbuffer_debug);
90 #define GST_CAT_DEFAULT (downloadbuffer_debug)
91
92 enum
93 {
94   LAST_SIGNAL
95 };
96
97 /* other defines */
98 #define DEFAULT_BUFFER_SIZE 4096
99
100 /* default property values */
101 #define DEFAULT_MAX_SIZE_BYTES     (2 * 1024 * 1024)    /* 2 MB */
102 #define DEFAULT_MAX_SIZE_TIME      2 * GST_SECOND       /* 2 seconds */
103 #define DEFAULT_LOW_PERCENT        10
104 #define DEFAULT_HIGH_PERCENT       99
105 #define DEFAULT_TEMP_REMOVE        TRUE
106
107 enum
108 {
109   PROP_0,
110   PROP_MAX_SIZE_BYTES,
111   PROP_MAX_SIZE_TIME,
112   PROP_LOW_PERCENT,
113   PROP_HIGH_PERCENT,
114   PROP_TEMP_TEMPLATE,
115   PROP_TEMP_LOCATION,
116   PROP_TEMP_REMOVE,
117   PROP_LAST
118 };
119
120 #define GST_DOWNLOAD_BUFFER_CLEAR_LEVEL(l) G_STMT_START {         \
121   l.bytes = 0;                                          \
122   l.time = 0;                                           \
123 } G_STMT_END
124
125 #define STATUS(elem, pad, msg) \
126   GST_LOG_OBJECT (elem, "(%s:%s) " msg ": %u of %u " \
127                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
128                       " ns", \
129                       GST_DEBUG_PAD_NAME (pad), \
130                       elem->cur_level.bytes, \
131                       elem->max_level.bytes, \
132                       elem->cur_level.time, \
133                       elem->max_level.time)
134
135 #define GST_DOWNLOAD_BUFFER_MUTEX_LOCK(q) G_STMT_START {                          \
136   g_mutex_lock (&q->qlock);                                              \
137 } G_STMT_END
138
139 #define GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
140   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (q);                                            \
141   if (res != GST_FLOW_OK)                                               \
142     goto label;                                                         \
143 } G_STMT_END
144
145 #define GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK(q) G_STMT_START {                        \
146   g_mutex_unlock (&q->qlock);                                            \
147 } G_STMT_END
148
149 #define GST_DOWNLOAD_BUFFER_WAIT_ADD_CHECK(q, res, o, label) G_STMT_START {       \
150   STATUS (q, q->srcpad, "wait for ADD");                            \
151   q->waiting_add = TRUE;                                                \
152   q->waiting_offset = o;                                                \
153   g_cond_wait (&q->item_add, &q->qlock);                                \
154   q->waiting_add = FALSE;                                               \
155   if (res != GST_FLOW_OK) {                                             \
156     STATUS (q, q->srcpad, "received ADD wakeup");                   \
157     goto label;                                                         \
158   }                                                                     \
159   STATUS (q, q->srcpad, "received ADD");                            \
160 } G_STMT_END
161
162 #define GST_DOWNLOAD_BUFFER_SIGNAL_ADD(q, o) G_STMT_START {                       \
163   if (q->waiting_add && q->waiting_offset <= o) {                       \
164     STATUS (q, q->sinkpad, "signal ADD");                               \
165     g_cond_signal (&q->item_add);                                       \
166   }                                                                     \
167 } G_STMT_END
168
169 #define _do_init \
170     GST_DEBUG_CATEGORY_INIT (downloadbuffer_debug, "downloadbuffer", 0, \
171         "downloadbuffer element");
172
173 #define gst_download_buffer_parent_class parent_class
174 G_DEFINE_TYPE_WITH_CODE (GstDownloadBuffer, gst_download_buffer,
175     GST_TYPE_ELEMENT, _do_init);
176
177 static GstMessage *update_buffering (GstDownloadBuffer * dlbuf);
178
179 static void gst_download_buffer_finalize (GObject * object);
180
181 static void gst_download_buffer_set_property (GObject * object,
182     guint prop_id, const GValue * value, GParamSpec * pspec);
183 static void gst_download_buffer_get_property (GObject * object,
184     guint prop_id, GValue * value, GParamSpec * pspec);
185
186 static GstFlowReturn gst_download_buffer_chain (GstPad * pad,
187     GstObject * parent, GstBuffer * buffer);
188 static void gst_download_buffer_loop (GstPad * pad);
189
190 static gboolean gst_download_buffer_handle_sink_event (GstPad * pad,
191     GstObject * parent, GstEvent * event);
192 static gboolean gst_download_buffer_handle_sink_query (GstPad * pad,
193     GstObject * parent, GstQuery * query);
194
195 static gboolean gst_download_buffer_handle_src_event (GstPad * pad,
196     GstObject * parent, GstEvent * event);
197 static gboolean gst_download_buffer_handle_src_query (GstPad * pad,
198     GstObject * parent, GstQuery * query);
199 static gboolean gst_download_buffer_handle_query (GstElement * element,
200     GstQuery * query);
201
202 static GstFlowReturn gst_download_buffer_get_range (GstPad * pad,
203     GstObject * parent, guint64 offset, guint length, GstBuffer ** buffer);
204
205 static gboolean gst_download_buffer_src_activate_mode (GstPad * pad,
206     GstObject * parent, GstPadMode mode, gboolean active);
207 static gboolean gst_download_buffer_sink_activate_mode (GstPad * pad,
208     GstObject * parent, GstPadMode mode, gboolean active);
209 static GstStateChangeReturn gst_download_buffer_change_state (GstElement *
210     element, GstStateChange transition);
211
212 /* static guint gst_download_buffer_signals[LAST_SIGNAL] = { 0 }; */
213
214 static void
215 gst_download_buffer_class_init (GstDownloadBufferClass * klass)
216 {
217   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
218   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
219
220   gobject_class->set_property = gst_download_buffer_set_property;
221   gobject_class->get_property = gst_download_buffer_get_property;
222
223   /* properties */
224   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
225       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
226           "Max. amount of data to buffer (bytes, 0=disable)",
227           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
228           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
229           G_PARAM_STATIC_STRINGS));
230   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
231       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
232           "Max. amount of data to buffer (in ns, 0=disable)", 0, G_MAXUINT64,
233           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
234           G_PARAM_STATIC_STRINGS));
235
236   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
237       g_param_spec_int ("low-percent", "Low percent",
238           "Low threshold for buffering to start. Only used if use-buffering is True",
239           0, 100, DEFAULT_LOW_PERCENT,
240           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
241   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
242       g_param_spec_int ("high-percent", "High percent",
243           "High threshold for buffering to finish. Only used if use-buffering is True",
244           0, 100, DEFAULT_HIGH_PERCENT,
245           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
246
247   g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
248       g_param_spec_string ("temp-template", "Temporary File Template",
249           "File template to store temporary files in, should contain directory "
250           "and XXXXXX. (NULL == disabled)",
251           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
252
253   g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
254       g_param_spec_string ("temp-location", "Temporary File Location",
255           "Location to store temporary files in (Only read this property, "
256           "use temp-template to configure the name template)",
257           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
258
259   /**
260    * GstDownloadBuffer:temp-remove
261    *
262    * When temp-template is set, remove the temporary file when going to READY.
263    */
264   g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
265       g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
266           "Remove the temp-location after use",
267           DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
268
269   /* set several parent class virtual functions */
270   gobject_class->finalize = gst_download_buffer_finalize;
271
272   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
273   gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
274
275   gst_element_class_set_static_metadata (gstelement_class, "DownloadBuffer",
276       "Generic", "Download Buffer element",
277       "Wim Taymans <wim.taymans@gmail.com>");
278
279   gstelement_class->change_state =
280       GST_DEBUG_FUNCPTR (gst_download_buffer_change_state);
281   gstelement_class->query =
282       GST_DEBUG_FUNCPTR (gst_download_buffer_handle_query);
283 }
284
285 static void
286 gst_download_buffer_init (GstDownloadBuffer * dlbuf)
287 {
288   dlbuf->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
289
290   gst_pad_set_chain_function (dlbuf->sinkpad,
291       GST_DEBUG_FUNCPTR (gst_download_buffer_chain));
292   gst_pad_set_activatemode_function (dlbuf->sinkpad,
293       GST_DEBUG_FUNCPTR (gst_download_buffer_sink_activate_mode));
294   gst_pad_set_event_function (dlbuf->sinkpad,
295       GST_DEBUG_FUNCPTR (gst_download_buffer_handle_sink_event));
296   gst_pad_set_query_function (dlbuf->sinkpad,
297       GST_DEBUG_FUNCPTR (gst_download_buffer_handle_sink_query));
298   GST_PAD_SET_PROXY_CAPS (dlbuf->sinkpad);
299   gst_element_add_pad (GST_ELEMENT (dlbuf), dlbuf->sinkpad);
300
301   dlbuf->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
302
303   gst_pad_set_activatemode_function (dlbuf->srcpad,
304       GST_DEBUG_FUNCPTR (gst_download_buffer_src_activate_mode));
305   gst_pad_set_getrange_function (dlbuf->srcpad,
306       GST_DEBUG_FUNCPTR (gst_download_buffer_get_range));
307   gst_pad_set_event_function (dlbuf->srcpad,
308       GST_DEBUG_FUNCPTR (gst_download_buffer_handle_src_event));
309   gst_pad_set_query_function (dlbuf->srcpad,
310       GST_DEBUG_FUNCPTR (gst_download_buffer_handle_src_query));
311   GST_PAD_SET_PROXY_CAPS (dlbuf->srcpad);
312   gst_element_add_pad (GST_ELEMENT (dlbuf), dlbuf->srcpad);
313
314   /* levels */
315   GST_DOWNLOAD_BUFFER_CLEAR_LEVEL (dlbuf->cur_level);
316   dlbuf->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
317   dlbuf->max_level.time = DEFAULT_MAX_SIZE_TIME;
318   dlbuf->low_percent = DEFAULT_LOW_PERCENT;
319   dlbuf->high_percent = DEFAULT_HIGH_PERCENT;
320
321   dlbuf->srcresult = GST_FLOW_FLUSHING;
322   dlbuf->sinkresult = GST_FLOW_FLUSHING;
323   dlbuf->in_timer = g_timer_new ();
324   dlbuf->out_timer = g_timer_new ();
325
326   g_mutex_init (&dlbuf->qlock);
327   dlbuf->waiting_add = FALSE;
328   g_cond_init (&dlbuf->item_add);
329
330   /* tempfile related */
331   dlbuf->temp_template = NULL;
332   dlbuf->temp_location = NULL;
333   dlbuf->temp_remove = DEFAULT_TEMP_REMOVE;
334 }
335
336 /* called only once, as opposed to dispose */
337 static void
338 gst_download_buffer_finalize (GObject * object)
339 {
340   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
341
342   g_mutex_clear (&dlbuf->qlock);
343   g_cond_clear (&dlbuf->item_add);
344   g_timer_destroy (dlbuf->in_timer);
345   g_timer_destroy (dlbuf->out_timer);
346
347   /* temp_file path cleanup  */
348   g_free (dlbuf->temp_template);
349   g_free (dlbuf->temp_location);
350
351   G_OBJECT_CLASS (parent_class)->finalize (object);
352 }
353
354 static void
355 reset_positions (GstDownloadBuffer * dlbuf)
356 {
357   dlbuf->write_pos = 0;
358   dlbuf->read_pos = 0;
359   dlbuf->filling = TRUE;
360   dlbuf->buffering_percent = 0;
361   dlbuf->is_buffering = TRUE;
362   dlbuf->seeking = FALSE;
363   GST_DOWNLOAD_BUFFER_CLEAR_LEVEL (dlbuf->cur_level);
364 }
365
366 static void
367 reset_rate_timer (GstDownloadBuffer * dlbuf)
368 {
369   dlbuf->bytes_in = 0;
370   dlbuf->bytes_out = 0;
371   dlbuf->byte_in_rate = 0.0;
372   dlbuf->byte_in_period = 0;
373   dlbuf->byte_out_rate = 0.0;
374   dlbuf->last_in_elapsed = 0.0;
375   dlbuf->last_out_elapsed = 0.0;
376   dlbuf->in_timer_started = FALSE;
377   dlbuf->out_timer_started = FALSE;
378 }
379
380 /* the interval in seconds to recalculate the rate */
381 #define RATE_INTERVAL    0.2
382 /* Tuning for rate estimation. We use a large window for the input rate because
383  * it should be stable when connected to a network. The output rate is less
384  * stable (the elements preroll, queues behind a demuxer fill, ...) and should
385  * therefore adapt more quickly.
386  * However, initial input rate may be subject to a burst, and should therefore
387  * initially also adapt more quickly to changes, and only later on give higher
388  * weight to previous values. */
389 #define AVG_IN(avg,val,w1,w2)  ((avg) * (w1) + (val) * (w2)) / ((w1) + (w2))
390 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
391
392 static void
393 update_levels (GstDownloadBuffer * dlbuf, guint bytes)
394 {
395   dlbuf->cur_level.bytes = bytes;
396
397   if (dlbuf->byte_in_rate > 0.0) {
398     dlbuf->cur_level.time =
399         dlbuf->cur_level.bytes / dlbuf->byte_in_rate * GST_SECOND;
400   }
401
402   GST_DEBUG ("levels: bytes %u/%u, time %" GST_TIME_FORMAT "/%" GST_TIME_FORMAT,
403       dlbuf->cur_level.bytes, dlbuf->max_level.bytes,
404       GST_TIME_ARGS (dlbuf->cur_level.time),
405       GST_TIME_ARGS (dlbuf->max_level.time));
406 }
407
408 static void
409 update_in_rates (GstDownloadBuffer * dlbuf)
410 {
411   gdouble elapsed, period;
412   gdouble byte_in_rate;
413
414   if (!dlbuf->in_timer_started) {
415     dlbuf->in_timer_started = TRUE;
416     g_timer_start (dlbuf->in_timer);
417     return;
418   }
419
420   elapsed = g_timer_elapsed (dlbuf->in_timer, NULL);
421
422   /* recalc after each interval. */
423   if (dlbuf->last_in_elapsed + RATE_INTERVAL < elapsed) {
424     period = elapsed - dlbuf->last_in_elapsed;
425
426     GST_DEBUG_OBJECT (dlbuf,
427         "rates: period %f, in %" G_GUINT64_FORMAT ", global period %f",
428         period, dlbuf->bytes_in, dlbuf->byte_in_period);
429
430     byte_in_rate = dlbuf->bytes_in / period;
431
432     if (dlbuf->byte_in_rate == 0.0)
433       dlbuf->byte_in_rate = byte_in_rate;
434     else
435       dlbuf->byte_in_rate = AVG_IN (dlbuf->byte_in_rate, byte_in_rate,
436           (double) dlbuf->byte_in_period, period);
437
438     /* another data point, cap at 16 for long time running average */
439     if (dlbuf->byte_in_period < 16 * RATE_INTERVAL)
440       dlbuf->byte_in_period += period;
441
442     /* reset the values to calculate rate over the next interval */
443     dlbuf->last_in_elapsed = elapsed;
444     dlbuf->bytes_in = 0;
445     GST_DEBUG_OBJECT (dlbuf, "rates: in %f", dlbuf->byte_in_rate);
446   }
447 }
448
449 static void
450 update_out_rates (GstDownloadBuffer * dlbuf)
451 {
452   gdouble elapsed, period;
453   gdouble byte_out_rate;
454
455   if (!dlbuf->out_timer_started) {
456     dlbuf->out_timer_started = TRUE;
457     g_timer_start (dlbuf->out_timer);
458     return;
459   }
460
461   elapsed = g_timer_elapsed (dlbuf->out_timer, NULL);
462
463   /* recalc after each interval. */
464   if (dlbuf->last_out_elapsed + RATE_INTERVAL < elapsed) {
465     period = elapsed - dlbuf->last_out_elapsed;
466
467     GST_DEBUG_OBJECT (dlbuf,
468         "rates: period %f, out %" G_GUINT64_FORMAT, period, dlbuf->bytes_out);
469
470     byte_out_rate = dlbuf->bytes_out / period;
471
472     if (dlbuf->byte_out_rate == 0.0)
473       dlbuf->byte_out_rate = byte_out_rate;
474     else
475       dlbuf->byte_out_rate = AVG_OUT (dlbuf->byte_out_rate, byte_out_rate);
476
477     /* reset the values to calculate rate over the next interval */
478     dlbuf->last_out_elapsed = elapsed;
479     dlbuf->bytes_out = 0;
480     GST_DEBUG_OBJECT (dlbuf, "rates: out %f", dlbuf->byte_out_rate);
481   }
482 }
483
484 static gboolean
485 get_buffering_percent (GstDownloadBuffer * dlbuf, gboolean * is_buffering,
486     gint * percent)
487 {
488   gint perc;
489
490   if (dlbuf->high_percent <= 0) {
491     if (percent)
492       *percent = 100;
493     if (is_buffering)
494       *is_buffering = FALSE;
495     return FALSE;
496   }
497
498   /* Ensure the variables used to calculate buffering state are up-to-date. */
499   update_in_rates (dlbuf);
500   update_out_rates (dlbuf);
501
502   /* figure out the percent we are filled, we take the max of all formats. */
503   if (dlbuf->max_level.bytes > 0) {
504     if (dlbuf->cur_level.bytes >= dlbuf->max_level.bytes)
505       perc = 100;
506     else
507       perc = dlbuf->cur_level.bytes * 100 / dlbuf->max_level.bytes;
508   } else
509     perc = 0;
510
511   if (dlbuf->max_level.time > 0) {
512     if (dlbuf->cur_level.time >= dlbuf->max_level.time)
513       perc = 100;
514     else
515       perc = MAX (perc, dlbuf->cur_level.time * 100 / dlbuf->max_level.time);
516   } else
517     perc = MAX (0, perc);
518
519   if (is_buffering)
520     *is_buffering = dlbuf->is_buffering;
521
522   /* scale to high percent so that it becomes the 100% mark */
523   perc = perc * 100 / dlbuf->high_percent;
524   /* clip */
525   if (perc > 100)
526     perc = 100;
527
528   if (percent)
529     *percent = perc;
530
531   GST_DEBUG_OBJECT (dlbuf, "buffering %d, percent %d", dlbuf->is_buffering,
532       perc);
533
534   return TRUE;
535 }
536
537 static void
538 get_buffering_stats (GstDownloadBuffer * dlbuf, gint percent,
539     GstBufferingMode * mode, gint * avg_in, gint * avg_out,
540     gint64 * buffering_left)
541 {
542   if (mode)
543     *mode = GST_BUFFERING_DOWNLOAD;
544
545   if (avg_in)
546     *avg_in = dlbuf->byte_in_rate;
547   if (avg_out)
548     *avg_out = dlbuf->byte_out_rate;
549
550   if (buffering_left) {
551     guint64 max, cur;
552
553     *buffering_left = (percent == 100 ? 0 : -1);
554
555     max = dlbuf->max_level.time;
556     cur = dlbuf->cur_level.time;
557
558     if (percent != 100 && max > cur)
559       *buffering_left = (max - cur) / 1000000;
560   }
561 }
562
563 static GstMessage *
564 update_buffering (GstDownloadBuffer * dlbuf)
565 {
566   gint percent;
567   gboolean post = FALSE;
568   GstMessage *message = NULL;
569
570   if (!get_buffering_percent (dlbuf, NULL, &percent))
571     return NULL;
572
573   if (dlbuf->is_buffering) {
574     post = TRUE;
575     /* if we were buffering see if we reached the high watermark */
576     if (percent >= dlbuf->high_percent)
577       dlbuf->is_buffering = FALSE;
578   } else {
579     /* we were not buffering, check if we need to start buffering if we drop
580      * below the low threshold */
581     if (percent < dlbuf->low_percent) {
582       dlbuf->is_buffering = TRUE;
583       post = TRUE;
584     }
585   }
586
587   if (post) {
588     if (percent == dlbuf->buffering_percent)
589       post = FALSE;
590     else
591       dlbuf->buffering_percent = percent;
592   }
593
594   if (post) {
595     GstBufferingMode mode;
596     gint avg_in, avg_out;
597     gint64 buffering_left;
598
599     get_buffering_stats (dlbuf, percent, &mode, &avg_in, &avg_out,
600         &buffering_left);
601
602     message = gst_message_new_buffering (GST_OBJECT_CAST (dlbuf),
603         (gint) percent);
604     gst_message_set_buffering_stats (message, mode,
605         avg_in, avg_out, buffering_left);
606   }
607
608   return message;
609 }
610
611 static gboolean
612 perform_seek_to_offset (GstDownloadBuffer * dlbuf, guint64 offset)
613 {
614   GstEvent *event;
615   gboolean res;
616
617   if (dlbuf->seeking)
618     return TRUE;
619
620   /* until we receive the FLUSH_STOP from this seek, we skip data */
621   dlbuf->seeking = TRUE;
622   dlbuf->write_pos = offset;
623   dlbuf->filling = FALSE;
624   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
625
626   GST_DEBUG_OBJECT (dlbuf, "Seeking to %" G_GUINT64_FORMAT, offset);
627
628   event =
629       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
630       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
631       GST_SEEK_TYPE_NONE, -1);
632
633   res = gst_pad_push_event (dlbuf->sinkpad, event);
634   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
635
636   return res;
637 }
638
639 /* get the threshold for when we decide to seek rather than wait */
640 static guint64
641 get_seek_threshold (GstDownloadBuffer * dlbuf)
642 {
643   guint64 threshold;
644
645   /* FIXME, find a good threshold based on the incoming rate. */
646   threshold = 1024 * 512;
647
648   return threshold;
649 }
650
651 /* called with DOWNLOAD_BUFFER_MUTEX */
652 static void
653 gst_download_buffer_update_upstream_size (GstDownloadBuffer * dlbuf)
654 {
655   gint64 upstream_size = 0;
656
657   if (gst_pad_peer_query_duration (dlbuf->sinkpad, GST_FORMAT_BYTES,
658           &upstream_size)) {
659     GST_INFO_OBJECT (dlbuf, "upstream size: %" G_GINT64_FORMAT, upstream_size);
660     dlbuf->upstream_size = upstream_size;
661   }
662 }
663
664 /* called with DOWNLOAD_BUFFER_MUTEX */
665 static GstFlowReturn
666 gst_download_buffer_wait_for_data (GstDownloadBuffer * dlbuf, guint64 offset,
667     guint length)
668 {
669   gsize start, stop;
670   guint64 wanted;
671   gboolean started;
672
673   GST_DEBUG_OBJECT (dlbuf, "wait for %" G_GUINT64_FORMAT ", length %u",
674       offset, length);
675
676   wanted = offset + length;
677
678   /* pause the timer while we wait. The fact that we are waiting does not mean
679    * the byterate on the output pad is lower */
680   if ((started = dlbuf->out_timer_started))
681     g_timer_stop (dlbuf->out_timer);
682
683   /* check range before us */
684   if (gst_sparse_file_get_range_before (dlbuf->file, offset, &start, &stop)) {
685     GST_DEBUG_OBJECT (dlbuf,
686         "range before %" G_GSIZE_FORMAT " - %" G_GSIZE_FORMAT, start, stop);
687     if (start <= offset && offset < stop) {
688       GST_DEBUG_OBJECT (dlbuf, "we have the offset");
689       /* we have the range, continue it */
690       offset = stop;
691     } else {
692       guint64 threshold, dist;
693
694       /* there is a range before us, check how far away it is */
695       threshold = get_seek_threshold (dlbuf);
696       dist = offset - stop;
697
698       if (dist <= threshold) {
699         GST_DEBUG_OBJECT (dlbuf, "not too far");
700         /* not far away, continue it */
701         offset = stop;
702       }
703     }
704   }
705
706   if (dlbuf->write_pos != offset)
707     perform_seek_to_offset (dlbuf, offset);
708
709   dlbuf->filling = TRUE;
710   if (dlbuf->write_pos > dlbuf->read_pos)
711     update_levels (dlbuf, dlbuf->write_pos - dlbuf->read_pos);
712   else
713     update_levels (dlbuf, 0);
714
715   /* now wait for more data */
716   GST_DEBUG_OBJECT (dlbuf, "waiting for more data");
717   GST_DOWNLOAD_BUFFER_WAIT_ADD_CHECK (dlbuf, dlbuf->srcresult, wanted,
718       out_flushing);
719   GST_DEBUG_OBJECT (dlbuf, "got more data");
720
721   /* and continue if we were running before */
722   if (started)
723     g_timer_continue (dlbuf->out_timer);
724
725   return GST_FLOW_OK;
726
727 out_flushing:
728   {
729     GST_DEBUG_OBJECT (dlbuf, "we are flushing");
730     return GST_FLOW_FLUSHING;
731   }
732 }
733
734 /* called with DOWNLOAD_BUFFER_MUTEX */
735 static gboolean
736 check_upstream_size (GstDownloadBuffer * dlbuf, gsize offset, guint * length)
737 {
738   gsize stop = offset + *length;
739   /* catch any reads beyond the size of the file here to make sure cache
740    * doesn't send seek events beyond the size of the file upstream, since
741    * that would confuse elements such as souphttpsrc and/or http servers.
742    * Demuxers often just loop until EOS at the end of the file to figure out
743    * when they've read all the end-headers or index chunks. */
744   if (G_UNLIKELY (dlbuf->upstream_size == -1 || stop >= dlbuf->upstream_size)) {
745     gst_download_buffer_update_upstream_size (dlbuf);
746   }
747
748   if (dlbuf->upstream_size != -1) {
749     if (offset >= dlbuf->upstream_size)
750       return FALSE;
751
752     if (G_UNLIKELY (stop > dlbuf->upstream_size)) {
753       *length = dlbuf->upstream_size - offset;
754       GST_DEBUG_OBJECT (dlbuf, "adjusting length downto %u", *length);
755     }
756   }
757   return TRUE;
758 }
759
760 /* called with DOWNLOAD_BUFFER_MUTEX */
761 static GstFlowReturn
762 gst_download_buffer_read_buffer (GstDownloadBuffer * dlbuf, guint64 offset,
763     guint length, GstBuffer ** buffer)
764 {
765   GstBuffer *buf;
766   GstMapInfo info;
767   GstFlowReturn ret = GST_FLOW_OK;
768   gsize res, remaining;
769   GError *error = NULL;
770
771   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
772   offset = (offset == -1) ? dlbuf->read_pos : offset;
773
774   if (!check_upstream_size (dlbuf, offset, &length))
775     goto hit_eos;
776
777   /* allocate the output buffer of the requested size */
778   if (*buffer == NULL)
779     buf = gst_buffer_new_allocate (NULL, length, NULL);
780   else
781     buf = *buffer;
782
783   if (!gst_buffer_map (buf, &info, GST_MAP_WRITE))
784     goto map_failed;
785
786   GST_DEBUG_OBJECT (dlbuf, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
787       offset);
788
789   dlbuf->read_pos = offset;
790
791   do {
792     res =
793         gst_sparse_file_read (dlbuf->file, offset, info.data, length,
794         &remaining, &error);
795     if (G_UNLIKELY (res == 0)) {
796       switch (error->code) {
797         case GST_SPARSE_FILE_IO_ERROR_WOULD_BLOCK:
798           /* we don't have the requested data in the file, decide what to
799            * do next. */
800           ret = gst_download_buffer_wait_for_data (dlbuf, offset, length);
801           if (ret != GST_FLOW_OK)
802             goto out_flushing;
803           break;
804         default:
805           goto read_error;
806       }
807       g_clear_error (&error);
808     }
809   } while (res == 0);
810
811   gst_buffer_unmap (buf, &info);
812   gst_buffer_resize (buf, 0, res);
813
814   dlbuf->bytes_out += res;
815   dlbuf->read_pos += res;
816
817   GST_DEBUG_OBJECT (dlbuf,
818       "Read %" G_GSIZE_FORMAT " bytes, remaining %" G_GSIZE_FORMAT, res,
819       remaining);
820
821   if (dlbuf->read_pos + remaining == dlbuf->upstream_size)
822     update_levels (dlbuf, dlbuf->max_level.bytes);
823   else
824     update_levels (dlbuf, remaining);
825
826   GST_BUFFER_OFFSET (buf) = offset;
827   GST_BUFFER_OFFSET_END (buf) = offset + res;
828
829   *buffer = buf;
830
831   return ret;
832
833   /* ERRORS */
834 hit_eos:
835   {
836     GST_DEBUG_OBJECT (dlbuf, "EOS hit");
837     return GST_FLOW_EOS;
838   }
839 map_failed:
840   {
841     GST_ELEMENT_ERROR (dlbuf, RESOURCE, BUSY,
842         (_("Failed to map buffer.")), ("failed to map buffer in WRITE mode"));
843     if (*buffer == NULL)
844       gst_buffer_unref (buf);
845     return GST_FLOW_ERROR;
846   }
847 out_flushing:
848   {
849     GST_DEBUG_OBJECT (dlbuf, "we are flushing");
850     g_clear_error (&error);
851     gst_buffer_unmap (buf, &info);
852     if (*buffer == NULL)
853       gst_buffer_unref (buf);
854     return GST_FLOW_FLUSHING;
855   }
856 read_error:
857   {
858     GST_DEBUG_OBJECT (dlbuf, "we have a read error: %s", error->message);
859     g_clear_error (&error);
860     gst_buffer_unmap (buf, &info);
861     if (*buffer == NULL)
862       gst_buffer_unref (buf);
863     return ret;
864   }
865 }
866
867 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
868  * the temp filename. */
869 static gboolean
870 gst_download_buffer_open_temp_location_file (GstDownloadBuffer * dlbuf)
871 {
872   gint fd = -1;
873   gchar *name = NULL;
874
875   if (dlbuf->file)
876     goto already_opened;
877
878   GST_DEBUG_OBJECT (dlbuf, "opening temp file %s", dlbuf->temp_template);
879
880   /* If temp_template was set, allocate a filename and open that file */
881
882   /* nothing to do */
883   if (dlbuf->temp_template == NULL)
884     goto no_directory;
885
886   /* make copy of the template, we don't want to change this */
887   name = g_strdup (dlbuf->temp_template);
888 #ifdef __BIONIC__
889   fd = g_mkstemp_full (name, O_RDWR | O_LARGEFILE, S_IRUSR | S_IWUSR);
890 #else
891   fd = g_mkstemp (name);
892 #endif
893   if (fd == -1)
894     goto mkstemp_failed;
895
896   /* open the file for update/writing */
897   dlbuf->file = gst_sparse_file_new ();
898   /* error creating file */
899   if (!gst_sparse_file_set_fd (dlbuf->file, fd))
900     goto open_failed;
901
902   g_free (dlbuf->temp_location);
903   dlbuf->temp_location = name;
904   dlbuf->temp_fd = fd;
905   reset_positions (dlbuf);
906
907   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
908
909   /* we can't emit the notify with the lock */
910   g_object_notify (G_OBJECT (dlbuf), "temp-location");
911
912   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
913
914   GST_DEBUG_OBJECT (dlbuf, "opened temp file %s", dlbuf->temp_template);
915
916   return TRUE;
917
918   /* ERRORS */
919 already_opened:
920   {
921     GST_DEBUG_OBJECT (dlbuf, "temp file was already open");
922     return TRUE;
923   }
924 no_directory:
925   {
926     GST_ELEMENT_ERROR (dlbuf, RESOURCE, NOT_FOUND,
927         (_("No Temp directory specified.")), (NULL));
928     return FALSE;
929   }
930 mkstemp_failed:
931   {
932     GST_ELEMENT_ERROR (dlbuf, RESOURCE, OPEN_READ,
933         (_("Could not create temp file \"%s\"."), dlbuf->temp_template),
934         GST_ERROR_SYSTEM);
935     g_free (name);
936     return FALSE;
937   }
938 open_failed:
939   {
940     GST_ELEMENT_ERROR (dlbuf, RESOURCE, OPEN_READ,
941         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
942     g_free (name);
943     if (fd != -1)
944       close (fd);
945     return FALSE;
946   }
947 }
948
949 static void
950 gst_download_buffer_close_temp_location_file (GstDownloadBuffer * dlbuf)
951 {
952   /* nothing to do */
953   if (dlbuf->file == NULL)
954     return;
955
956   GST_DEBUG_OBJECT (dlbuf, "closing sparse file");
957
958   if (dlbuf->temp_remove) {
959     if (remove (dlbuf->temp_location) < 0) {
960       GST_WARNING_OBJECT (dlbuf, "Failed to remove temporary file %s: %s",
961           dlbuf->temp_location, g_strerror (errno));
962     }
963   }
964   gst_sparse_file_free (dlbuf->file);
965   close (dlbuf->temp_fd);
966   dlbuf->file = NULL;
967 }
968
969 static void
970 gst_download_buffer_flush_temp_file (GstDownloadBuffer * dlbuf)
971 {
972   if (dlbuf->file == NULL)
973     return;
974
975   GST_DEBUG_OBJECT (dlbuf, "flushing temp file");
976
977   gst_sparse_file_clear (dlbuf->file);
978 }
979
980 static void
981 gst_download_buffer_locked_flush (GstDownloadBuffer * dlbuf, gboolean full,
982     gboolean clear_temp)
983 {
984   if (clear_temp)
985     gst_download_buffer_flush_temp_file (dlbuf);
986   reset_positions (dlbuf);
987   gst_event_replace (&dlbuf->stream_start_event, NULL);
988   gst_event_replace (&dlbuf->segment_event, NULL);
989 }
990
991 static gboolean
992 gst_download_buffer_handle_sink_event (GstPad * pad, GstObject * parent,
993     GstEvent * event)
994 {
995   gboolean ret = TRUE;
996   GstDownloadBuffer *dlbuf;
997
998   dlbuf = GST_DOWNLOAD_BUFFER (parent);
999
1000   switch (GST_EVENT_TYPE (event)) {
1001     case GST_EVENT_FLUSH_START:
1002     {
1003       GST_LOG_OBJECT (dlbuf, "received flush start event");
1004       if (GST_PAD_MODE (dlbuf->srcpad) == GST_PAD_MODE_PUSH) {
1005         /* forward event */
1006         ret = gst_pad_push_event (dlbuf->srcpad, event);
1007
1008         /* now unblock the chain function */
1009         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1010         dlbuf->srcresult = GST_FLOW_FLUSHING;
1011         dlbuf->sinkresult = GST_FLOW_FLUSHING;
1012         /* unblock the loop and chain functions */
1013         GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1014         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1015
1016         /* make sure it pauses, this should happen since we sent
1017          * flush_start downstream. */
1018         gst_pad_pause_task (dlbuf->srcpad);
1019         GST_LOG_OBJECT (dlbuf, "loop stopped");
1020       } else {
1021         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1022         /* flush the sink pad */
1023         dlbuf->sinkresult = GST_FLOW_FLUSHING;
1024         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1025
1026         gst_event_unref (event);
1027       }
1028       break;
1029     }
1030     case GST_EVENT_FLUSH_STOP:
1031     {
1032       GST_LOG_OBJECT (dlbuf, "received flush stop event");
1033
1034       if (GST_PAD_MODE (dlbuf->srcpad) == GST_PAD_MODE_PUSH) {
1035         /* forward event */
1036         ret = gst_pad_push_event (dlbuf->srcpad, event);
1037
1038         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1039         gst_download_buffer_locked_flush (dlbuf, FALSE, TRUE);
1040         dlbuf->srcresult = GST_FLOW_OK;
1041         dlbuf->sinkresult = GST_FLOW_OK;
1042         dlbuf->unexpected = FALSE;
1043         dlbuf->seeking = FALSE;
1044         /* reset rate counters */
1045         reset_rate_timer (dlbuf);
1046         gst_pad_start_task (dlbuf->srcpad,
1047             (GstTaskFunction) gst_download_buffer_loop, dlbuf->srcpad, NULL);
1048         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1049       } else {
1050         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1051         dlbuf->unexpected = FALSE;
1052         dlbuf->sinkresult = GST_FLOW_OK;
1053         dlbuf->seeking = FALSE;
1054         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1055
1056         gst_event_unref (event);
1057       }
1058       break;
1059     }
1060     default:
1061       if (GST_EVENT_IS_SERIALIZED (event)) {
1062         GstMessage *msg = NULL;
1063
1064         /* serialized events go in the buffer */
1065         GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->sinkresult,
1066             out_flushing);
1067         switch (GST_EVENT_TYPE (event)) {
1068           case GST_EVENT_EOS:
1069             GST_DEBUG_OBJECT (dlbuf, "we have EOS");
1070             /* Zero the thresholds, this makes sure the dlbuf is completely
1071              * filled and we can read all data from the dlbuf. */
1072             /* update the buffering status */
1073             update_levels (dlbuf, dlbuf->max_level.bytes);
1074             /* update the buffering */
1075             msg = update_buffering (dlbuf);
1076             /* wakeup the waiter and let it recheck */
1077             GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1078             break;
1079           case GST_EVENT_SEGMENT:
1080             gst_event_replace (&dlbuf->segment_event, event);
1081             /* a new segment allows us to accept more buffers if we got EOS
1082              * from downstream */
1083             dlbuf->unexpected = FALSE;
1084             break;
1085           case GST_EVENT_STREAM_START:
1086             gst_event_replace (&dlbuf->stream_start_event, event);
1087             break;
1088           default:
1089             break;
1090         }
1091         gst_event_unref (event);
1092         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1093         if (msg != NULL)
1094           gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1095       } else {
1096         /* non-serialized events are passed upstream. */
1097         ret = gst_pad_push_event (dlbuf->srcpad, event);
1098       }
1099       break;
1100   }
1101   return ret;
1102
1103   /* ERRORS */
1104 out_flushing:
1105   {
1106     GST_DEBUG_OBJECT (dlbuf, "refusing event, we are flushing");
1107     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1108     gst_event_unref (event);
1109     return FALSE;
1110   }
1111 }
1112
1113 static gboolean
1114 gst_download_buffer_handle_sink_query (GstPad * pad, GstObject * parent,
1115     GstQuery * query)
1116 {
1117   GstDownloadBuffer *dlbuf;
1118   gboolean res;
1119
1120   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1121
1122   switch (GST_QUERY_TYPE (query)) {
1123     default:
1124       if (GST_QUERY_IS_SERIALIZED (query)) {
1125         GST_DEBUG_OBJECT (dlbuf, "refusing serialized query %p", query);
1126         res = FALSE;
1127       } else {
1128         res = gst_pad_query_default (pad, parent, query);
1129       }
1130       break;
1131   }
1132   return res;
1133 }
1134
1135 static GstFlowReturn
1136 gst_download_buffer_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1137 {
1138   GstDownloadBuffer *dlbuf;
1139   GstMapInfo info;
1140   guint64 offset;
1141   gsize res, available;
1142   GError *error = NULL;
1143   GstMessage *msg = NULL;
1144
1145   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1146
1147   GST_LOG_OBJECT (dlbuf, "received buffer %p of "
1148       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
1149       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
1150       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1151       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1152
1153   /* we have to lock the dlbuf since we span threads */
1154   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->sinkresult, out_flushing);
1155   /* when we received unexpected from downstream, refuse more buffers */
1156   if (dlbuf->unexpected)
1157     goto out_eos;
1158
1159   /* while we didn't receive the newsegment, we're seeking and we skip data */
1160   if (dlbuf->seeking)
1161     goto out_seeking;
1162
1163   /* put buffer in dlbuf now */
1164   offset = dlbuf->write_pos;
1165
1166   /* sanity check */
1167   if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1168       GST_BUFFER_OFFSET (buffer) != offset) {
1169     GST_WARNING_OBJECT (dlbuf, "buffer offset does not match current writing "
1170         "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1171         GST_BUFFER_OFFSET (buffer), offset);
1172   }
1173
1174   if (!gst_buffer_map (buffer, &info, GST_MAP_READ))
1175     goto map_error;
1176
1177   GST_DEBUG_OBJECT (dlbuf, "Writing %" G_GSIZE_FORMAT " bytes to %"
1178       G_GUINT64_FORMAT, info.size, offset);
1179
1180   res =
1181       gst_sparse_file_write (dlbuf->file, offset, info.data, info.size,
1182       &available, &error);
1183   if (res == 0)
1184     goto write_error;
1185
1186   gst_buffer_unmap (buffer, &info);
1187   gst_buffer_unref (buffer);
1188
1189   dlbuf->write_pos = offset + info.size;
1190   dlbuf->bytes_in += info.size;
1191
1192   GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, dlbuf->write_pos + available);
1193
1194   /* we hit the end, see what to do */
1195   if (dlbuf->write_pos + available == dlbuf->upstream_size) {
1196     gsize start, stop;
1197
1198     /* we have everything up to the end, find a region to fill */
1199     if (gst_sparse_file_get_range_after (dlbuf->file, 0, &start, &stop)) {
1200       if (stop < dlbuf->upstream_size) {
1201         /* a hole to fill, seek to its end */
1202         perform_seek_to_offset (dlbuf, stop);
1203       } else {
1204         /* we filled all the holes, we are done */
1205         goto completed;
1206       }
1207     }
1208   } else {
1209     /* see if we need to skip this region or just read it again. The idea
1210      * is that when the region is not big, we want to avoid a seek and just
1211      * let it reread */
1212     guint64 threshold = get_seek_threshold (dlbuf);
1213
1214     if (available > threshold) {
1215       /* further than threshold, it's better to skip than to reread */
1216       perform_seek_to_offset (dlbuf, dlbuf->write_pos + available);
1217     }
1218   }
1219   if (dlbuf->filling) {
1220     if (dlbuf->write_pos > dlbuf->read_pos)
1221       update_levels (dlbuf, dlbuf->write_pos - dlbuf->read_pos);
1222     else
1223       update_levels (dlbuf, 0);
1224   }
1225
1226   /* update the buffering */
1227   msg = update_buffering (dlbuf);
1228
1229   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1230
1231   if (msg != NULL)
1232     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1233
1234   return GST_FLOW_OK;
1235
1236   /* ERRORS */
1237 out_flushing:
1238   {
1239     GstFlowReturn ret = dlbuf->sinkresult;
1240     GST_LOG_OBJECT (dlbuf,
1241         "exit because task paused, reason: %s", gst_flow_get_name (ret));
1242     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1243     gst_buffer_unref (buffer);
1244     return ret;
1245   }
1246 out_eos:
1247   {
1248     GST_LOG_OBJECT (dlbuf, "exit because we received EOS");
1249     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1250     gst_buffer_unref (buffer);
1251     return GST_FLOW_EOS;
1252   }
1253 out_seeking:
1254   {
1255     GST_LOG_OBJECT (dlbuf, "exit because we are seeking");
1256     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1257     gst_buffer_unref (buffer);
1258     return GST_FLOW_OK;
1259   }
1260 map_error:
1261   {
1262     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1263     gst_buffer_unref (buffer);
1264     GST_ELEMENT_ERROR (dlbuf, RESOURCE, BUSY,
1265         (_("Failed to map buffer.")), ("failed to map buffer in READ mode"));
1266     return GST_FLOW_ERROR;
1267   }
1268 write_error:
1269   {
1270     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1271     gst_buffer_unmap (buffer, &info);
1272     gst_buffer_unref (buffer);
1273     GST_ELEMENT_ERROR (dlbuf, RESOURCE, WRITE,
1274         (_("Error while writing to download file.")), ("%s", error->message));
1275     g_clear_error (&error);
1276     return GST_FLOW_ERROR;
1277   }
1278 completed:
1279   {
1280     GstMessage *complete_message;
1281
1282     GST_LOG_OBJECT (dlbuf, "we completed the download");
1283     dlbuf->write_pos = dlbuf->upstream_size;
1284     dlbuf->filling = FALSE;
1285     update_levels (dlbuf, dlbuf->max_level.bytes);
1286     msg = update_buffering (dlbuf);
1287     complete_message = gst_message_new_element (GST_OBJECT_CAST (dlbuf),
1288         gst_structure_new ("GstCacheDownloadComplete",
1289             "location", G_TYPE_STRING, dlbuf->temp_location, NULL));
1290     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1291
1292     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), complete_message);
1293     if (msg != NULL)
1294       gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1295
1296     return GST_FLOW_EOS;
1297   }
1298 }
1299
1300 /* called repeatedly with @pad as the source pad. This function should push out
1301  * data to the peer element. */
1302 static void
1303 gst_download_buffer_loop (GstPad * pad)
1304 {
1305   GstDownloadBuffer *dlbuf;
1306   GstFlowReturn ret;
1307   GstBuffer *buffer = NULL;
1308   GstMessage *msg = NULL;
1309
1310   dlbuf = GST_DOWNLOAD_BUFFER (GST_PAD_PARENT (pad));
1311
1312   /* have to lock for thread-safety */
1313   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1314
1315   if (dlbuf->stream_start_event != NULL) {
1316     gst_pad_push_event (dlbuf->srcpad, dlbuf->stream_start_event);
1317     dlbuf->stream_start_event = NULL;
1318   }
1319   if (dlbuf->segment_event != NULL) {
1320     gst_pad_push_event (dlbuf->srcpad, dlbuf->segment_event);
1321     dlbuf->segment_event = NULL;
1322   }
1323
1324   ret = gst_download_buffer_read_buffer (dlbuf, -1, -1, &buffer);
1325   if (ret != GST_FLOW_OK)
1326     goto out_flushing;
1327
1328   /* update the buffering */
1329   msg = update_buffering (dlbuf);
1330
1331   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1332
1333   if (msg != NULL)
1334     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1335
1336   ret = gst_pad_push (dlbuf->srcpad, buffer);
1337
1338   /* need to check for srcresult here as well */
1339   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1340   dlbuf->srcresult = ret;
1341   dlbuf->sinkresult = ret;
1342   if (ret != GST_FLOW_OK)
1343     goto out_flushing;
1344   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1345
1346   return;
1347
1348   /* ERRORS */
1349 out_flushing:
1350   {
1351     GstFlowReturn ret = dlbuf->srcresult;
1352
1353     gst_pad_pause_task (dlbuf->srcpad);
1354     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1355     GST_LOG_OBJECT (dlbuf, "pause task, reason:  %s", gst_flow_get_name (ret));
1356     /* let app know about us giving up if upstream is not expected to do so */
1357     if (ret == GST_FLOW_EOS) {
1358       /* FIXME perform EOS logic, this is really a basesrc operating on a
1359        * file. */
1360       gst_pad_push_event (dlbuf->srcpad, gst_event_new_eos ());
1361     } else if ((ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1362       GST_ELEMENT_FLOW_ERROR (dlbuf, ret);
1363       gst_pad_push_event (dlbuf->srcpad, gst_event_new_eos ());
1364     }
1365     return;
1366   }
1367 }
1368
1369 static gboolean
1370 gst_download_buffer_handle_src_event (GstPad * pad, GstObject * parent,
1371     GstEvent * event)
1372 {
1373   gboolean res = TRUE;
1374   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (parent);
1375
1376 #ifndef GST_DISABLE_GST_DEBUG
1377   GST_DEBUG_OBJECT (dlbuf, "got event %p (%s)",
1378       event, GST_EVENT_TYPE_NAME (event));
1379 #endif
1380
1381   switch (GST_EVENT_TYPE (event)) {
1382     case GST_EVENT_FLUSH_START:
1383       /* now unblock the getrange function */
1384       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1385       GST_DEBUG_OBJECT (dlbuf, "flushing");
1386       dlbuf->srcresult = GST_FLOW_FLUSHING;
1387       GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1388       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1389
1390       /* when using a temp file, we eat the event */
1391       res = TRUE;
1392       gst_event_unref (event);
1393       break;
1394     case GST_EVENT_FLUSH_STOP:
1395       /* now unblock the getrange function */
1396       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1397       dlbuf->srcresult = GST_FLOW_OK;
1398       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1399
1400       /* when using a temp file, we eat the event */
1401       res = TRUE;
1402       gst_event_unref (event);
1403       break;
1404     case GST_EVENT_RECONFIGURE:
1405       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1406       /* assume downstream is linked now and try to push again */
1407       if (dlbuf->srcresult == GST_FLOW_NOT_LINKED) {
1408         dlbuf->srcresult = GST_FLOW_OK;
1409         dlbuf->sinkresult = GST_FLOW_OK;
1410         if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
1411           gst_pad_start_task (pad, (GstTaskFunction) gst_download_buffer_loop,
1412               pad, NULL);
1413         }
1414       }
1415       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1416
1417       res = gst_pad_push_event (dlbuf->sinkpad, event);
1418       break;
1419     default:
1420       res = gst_pad_push_event (dlbuf->sinkpad, event);
1421       break;
1422   }
1423
1424   return res;
1425 }
1426
1427 static gboolean
1428 gst_download_buffer_handle_src_query (GstPad * pad, GstObject * parent,
1429     GstQuery * query)
1430 {
1431   GstDownloadBuffer *dlbuf;
1432
1433   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1434
1435   switch (GST_QUERY_TYPE (query)) {
1436     case GST_QUERY_POSITION:
1437     {
1438       gint64 peer_pos;
1439       GstFormat format;
1440
1441       if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1442         goto peer_failed;
1443
1444       /* get peer position */
1445       gst_query_parse_position (query, &format, &peer_pos);
1446
1447       /* FIXME: this code assumes that there's no discont in the dlbuf */
1448       switch (format) {
1449         case GST_FORMAT_BYTES:
1450           peer_pos -= dlbuf->cur_level.bytes;
1451           if (peer_pos < 0)     /* Clamp result to 0 */
1452             peer_pos = 0;
1453           break;
1454         case GST_FORMAT_TIME:
1455           peer_pos -= dlbuf->cur_level.time;
1456           if (peer_pos < 0)     /* Clamp result to 0 */
1457             peer_pos = 0;
1458           break;
1459         default:
1460           GST_WARNING_OBJECT (dlbuf, "dropping query in %s format, don't "
1461               "know how to adjust value", gst_format_get_name (format));
1462           return FALSE;
1463       }
1464       /* set updated position */
1465       gst_query_set_position (query, format, peer_pos);
1466       break;
1467     }
1468     case GST_QUERY_DURATION:
1469     {
1470       GST_DEBUG_OBJECT (dlbuf, "doing peer query");
1471
1472       if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1473         goto peer_failed;
1474
1475       GST_DEBUG_OBJECT (dlbuf, "peer query success");
1476       break;
1477     }
1478     case GST_QUERY_BUFFERING:
1479     {
1480       gint percent;
1481       gboolean is_buffering;
1482       GstBufferingMode mode;
1483       gint avg_in, avg_out;
1484       gint64 buffering_left;
1485
1486       GST_DEBUG_OBJECT (dlbuf, "query buffering");
1487
1488       get_buffering_percent (dlbuf, &is_buffering, &percent);
1489       gst_query_set_buffering_percent (query, is_buffering, percent);
1490
1491       get_buffering_stats (dlbuf, percent, &mode, &avg_in, &avg_out,
1492           &buffering_left);
1493       gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
1494           buffering_left);
1495
1496       {
1497         /* add ranges for download and ringbuffer buffering */
1498         GstFormat format;
1499         gint64 start, stop;
1500         guint64 write_pos;
1501         gint64 estimated_total;
1502         gint64 duration;
1503         gsize offset, range_start, range_stop;
1504
1505         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1506         write_pos = dlbuf->write_pos;
1507
1508         /* get duration of upstream in bytes */
1509         gst_download_buffer_update_upstream_size (dlbuf);
1510         duration = dlbuf->upstream_size;
1511
1512         GST_DEBUG_OBJECT (dlbuf, "percent %d, duration %" G_GINT64_FORMAT
1513             ", writing %" G_GINT64_FORMAT, percent, duration, write_pos);
1514
1515         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
1516
1517         /* fill out the buffered ranges */
1518         start = offset = 0;
1519         stop = -1;
1520         estimated_total = -1;
1521         while (gst_sparse_file_get_range_after (dlbuf->file, offset,
1522                 &range_start, &range_stop)) {
1523           gboolean current_range;
1524
1525           GST_DEBUG_OBJECT (dlbuf,
1526               "range starting at %" G_GSIZE_FORMAT " and finishing at %"
1527               G_GSIZE_FORMAT, range_start, range_stop);
1528
1529           offset = range_stop;
1530
1531           /* find the range we are currently downloading, we'll remember it
1532            * after we convert to the target format */
1533           if (range_start <= write_pos && range_stop >= write_pos) {
1534             current_range = TRUE;
1535             /* calculate remaining and total download time */
1536             if (duration >= range_stop && avg_in > 0.0)
1537               estimated_total = ((duration - range_stop) * 1000) / avg_in;
1538           } else
1539             current_range = FALSE;
1540
1541           switch (format) {
1542             case GST_FORMAT_PERCENT:
1543               /* get our available data relative to the duration */
1544               if (duration == -1) {
1545                 range_start = 0;
1546                 range_stop = 0;
1547               } else {
1548                 range_start = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
1549                     range_start, duration);
1550                 range_stop = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
1551                     range_stop, duration);
1552               }
1553               break;
1554             case GST_FORMAT_BYTES:
1555               break;
1556             default:
1557               range_start = -1;
1558               range_stop = -1;
1559               break;
1560           }
1561
1562           if (current_range) {
1563             /* we are currently downloading this range */
1564             start = range_start;
1565             stop = range_stop;
1566           }
1567           GST_DEBUG_OBJECT (dlbuf,
1568               "range to format: %" G_GSIZE_FORMAT " - %" G_GSIZE_FORMAT,
1569               range_start, range_stop);
1570           if (range_start == range_stop)
1571             continue;
1572           gst_query_add_buffering_range (query, range_start, range_stop);
1573         }
1574
1575         GST_DEBUG_OBJECT (dlbuf, "estimated-total %" G_GINT64_FORMAT,
1576             estimated_total);
1577
1578         gst_query_set_buffering_range (query, format, start, stop,
1579             estimated_total);
1580
1581         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1582       }
1583       break;
1584     }
1585     case GST_QUERY_SCHEDULING:
1586     {
1587       GstSchedulingFlags flags = 0;
1588
1589       if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1590         goto peer_failed;
1591
1592       gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
1593
1594       /* we can operate in pull mode when we are using a tempfile */
1595       flags |= GST_SCHEDULING_FLAG_SEEKABLE;
1596       gst_query_set_scheduling (query, flags, 0, -1, 0);
1597       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
1598       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
1599       break;
1600     }
1601     default:
1602       /* peer handled other queries */
1603       if (!gst_pad_query_default (pad, parent, query))
1604         goto peer_failed;
1605       break;
1606   }
1607
1608   return TRUE;
1609
1610   /* ERRORS */
1611 peer_failed:
1612   {
1613     GST_DEBUG_OBJECT (dlbuf, "failed peer query");
1614     return FALSE;
1615   }
1616 }
1617
1618 static gboolean
1619 gst_download_buffer_handle_query (GstElement * element, GstQuery * query)
1620 {
1621   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (element);
1622
1623   /* simply forward to the srcpad query function */
1624   return gst_download_buffer_handle_src_query (dlbuf->srcpad,
1625       GST_OBJECT_CAST (element), query);
1626 }
1627
1628 static GstFlowReturn
1629 gst_download_buffer_get_range (GstPad * pad, GstObject * parent, guint64 offset,
1630     guint length, GstBuffer ** buffer)
1631 {
1632   GstDownloadBuffer *dlbuf;
1633   GstFlowReturn ret;
1634   GstMessage *msg = NULL;
1635
1636   dlbuf = GST_DOWNLOAD_BUFFER_CAST (parent);
1637
1638   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1639   /* FIXME - function will block when the range is not yet available */
1640   ret = gst_download_buffer_read_buffer (dlbuf, offset, length, buffer);
1641   /* update the buffering */
1642   msg = update_buffering (dlbuf);
1643
1644   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1645
1646   if (msg != NULL)
1647     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1648
1649   return ret;
1650
1651   /* ERRORS */
1652 out_flushing:
1653   {
1654     ret = dlbuf->srcresult;
1655
1656     GST_DEBUG_OBJECT (dlbuf, "we are flushing");
1657     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1658     return ret;
1659   }
1660 }
1661
1662 /* sink currently only operates in push mode */
1663 static gboolean
1664 gst_download_buffer_sink_activate_mode (GstPad * pad, GstObject * parent,
1665     GstPadMode mode, gboolean active)
1666 {
1667   gboolean result;
1668   GstDownloadBuffer *dlbuf;
1669
1670   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1671
1672   switch (mode) {
1673     case GST_PAD_MODE_PUSH:
1674       if (active) {
1675         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1676         GST_DEBUG_OBJECT (dlbuf, "activating push mode");
1677         dlbuf->srcresult = GST_FLOW_OK;
1678         dlbuf->sinkresult = GST_FLOW_OK;
1679         dlbuf->unexpected = FALSE;
1680         reset_rate_timer (dlbuf);
1681         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1682       } else {
1683         /* unblock chain function */
1684         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1685         GST_DEBUG_OBJECT (dlbuf, "deactivating push mode");
1686         dlbuf->srcresult = GST_FLOW_FLUSHING;
1687         dlbuf->sinkresult = GST_FLOW_FLUSHING;
1688         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1689
1690         /* wait until it is unblocked and clean up */
1691         GST_PAD_STREAM_LOCK (pad);
1692         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1693         gst_download_buffer_locked_flush (dlbuf, TRUE, FALSE);
1694         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1695         GST_PAD_STREAM_UNLOCK (pad);
1696       }
1697       result = TRUE;
1698       break;
1699     default:
1700       result = FALSE;
1701       break;
1702   }
1703   return result;
1704 }
1705
1706 /* src operating in push mode, we start a task on the source pad that pushes out
1707  * buffers from the dlbuf */
1708 static gboolean
1709 gst_download_buffer_src_activate_push (GstPad * pad, GstObject * parent,
1710     gboolean active)
1711 {
1712   gboolean result = FALSE;
1713   GstDownloadBuffer *dlbuf;
1714
1715   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1716
1717   if (active) {
1718     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1719     GST_DEBUG_OBJECT (dlbuf, "activating push mode");
1720     dlbuf->srcresult = GST_FLOW_OK;
1721     dlbuf->sinkresult = GST_FLOW_OK;
1722     dlbuf->unexpected = FALSE;
1723     result =
1724         gst_pad_start_task (pad, (GstTaskFunction) gst_download_buffer_loop,
1725         pad, NULL);
1726     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1727   } else {
1728     /* unblock loop function */
1729     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1730     GST_DEBUG_OBJECT (dlbuf, "deactivating push mode");
1731     dlbuf->srcresult = GST_FLOW_FLUSHING;
1732     dlbuf->sinkresult = GST_FLOW_FLUSHING;
1733     /* the item add signal will unblock */
1734     GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1735     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1736
1737     /* step 2, make sure streaming finishes */
1738     result = gst_pad_stop_task (pad);
1739   }
1740
1741   return result;
1742 }
1743
1744 /* pull mode, downstream will call our getrange function */
1745 static gboolean
1746 gst_download_buffer_src_activate_pull (GstPad * pad, GstObject * parent,
1747     gboolean active)
1748 {
1749   gboolean result;
1750   GstDownloadBuffer *dlbuf;
1751
1752   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1753
1754   if (active) {
1755     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1756     /* open the temp file now */
1757     result = gst_download_buffer_open_temp_location_file (dlbuf);
1758     GST_DEBUG_OBJECT (dlbuf, "activating pull mode");
1759     dlbuf->srcresult = GST_FLOW_OK;
1760     dlbuf->sinkresult = GST_FLOW_OK;
1761     dlbuf->unexpected = FALSE;
1762     dlbuf->upstream_size = 0;
1763     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1764   } else {
1765     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1766     GST_DEBUG_OBJECT (dlbuf, "deactivating pull mode");
1767     dlbuf->srcresult = GST_FLOW_FLUSHING;
1768     dlbuf->sinkresult = GST_FLOW_FLUSHING;
1769     /* this will unlock getrange */
1770     GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1771     result = TRUE;
1772     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1773   }
1774
1775   return result;
1776 }
1777
1778 static gboolean
1779 gst_download_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1780     GstPadMode mode, gboolean active)
1781 {
1782   gboolean res;
1783
1784   switch (mode) {
1785     case GST_PAD_MODE_PULL:
1786       res = gst_download_buffer_src_activate_pull (pad, parent, active);
1787       break;
1788     case GST_PAD_MODE_PUSH:
1789       res = gst_download_buffer_src_activate_push (pad, parent, active);
1790       break;
1791     default:
1792       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
1793       res = FALSE;
1794       break;
1795   }
1796   return res;
1797 }
1798
1799 static GstStateChangeReturn
1800 gst_download_buffer_change_state (GstElement * element,
1801     GstStateChange transition)
1802 {
1803   GstDownloadBuffer *dlbuf;
1804   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1805
1806   dlbuf = GST_DOWNLOAD_BUFFER (element);
1807
1808   switch (transition) {
1809     case GST_STATE_CHANGE_NULL_TO_READY:
1810       break;
1811     case GST_STATE_CHANGE_READY_TO_PAUSED:
1812       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1813       if (!gst_download_buffer_open_temp_location_file (dlbuf))
1814         ret = GST_STATE_CHANGE_FAILURE;
1815       gst_event_replace (&dlbuf->stream_start_event, NULL);
1816       gst_event_replace (&dlbuf->segment_event, NULL);
1817       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1818       break;
1819     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1820       break;
1821     default:
1822       break;
1823   }
1824
1825   if (ret == GST_STATE_CHANGE_FAILURE)
1826     return ret;
1827
1828   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1829
1830   if (ret == GST_STATE_CHANGE_FAILURE)
1831     return ret;
1832
1833   switch (transition) {
1834     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1835       break;
1836     case GST_STATE_CHANGE_PAUSED_TO_READY:
1837       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1838       gst_download_buffer_close_temp_location_file (dlbuf);
1839       gst_event_replace (&dlbuf->stream_start_event, NULL);
1840       gst_event_replace (&dlbuf->segment_event, NULL);
1841       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1842       break;
1843     case GST_STATE_CHANGE_READY_TO_NULL:
1844       break;
1845     default:
1846       break;
1847   }
1848
1849   return ret;
1850 }
1851
1852 #define CAPACITY_CHANGE(elem) \
1853   update_buffering (elem);
1854
1855 static void
1856 gst_download_buffer_set_temp_template (GstDownloadBuffer * dlbuf,
1857     const gchar * template)
1858 {
1859   GstState state;
1860
1861   /* the element must be stopped in order to do this */
1862   GST_OBJECT_LOCK (dlbuf);
1863   state = GST_STATE (dlbuf);
1864   if (state != GST_STATE_READY && state != GST_STATE_NULL)
1865     goto wrong_state;
1866   GST_OBJECT_UNLOCK (dlbuf);
1867
1868   /* set new location */
1869   g_free (dlbuf->temp_template);
1870   dlbuf->temp_template = g_strdup (template);
1871
1872   return;
1873
1874 /* ERROR */
1875 wrong_state:
1876   {
1877     GST_WARNING_OBJECT (dlbuf, "setting temp-template property in wrong state");
1878     GST_OBJECT_UNLOCK (dlbuf);
1879   }
1880 }
1881
1882 static void
1883 gst_download_buffer_set_property (GObject * object,
1884     guint prop_id, const GValue * value, GParamSpec * pspec)
1885 {
1886   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
1887   GstMessage *msg = NULL;
1888
1889   /* someone could change levels here, and since this
1890    * affects the get/put funcs, we need to lock for safety. */
1891   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1892
1893   switch (prop_id) {
1894     case PROP_MAX_SIZE_BYTES:
1895       dlbuf->max_level.bytes = g_value_get_uint (value);
1896       msg = CAPACITY_CHANGE (dlbuf);
1897       break;
1898     case PROP_MAX_SIZE_TIME:
1899       dlbuf->max_level.time = g_value_get_uint64 (value);
1900       msg = CAPACITY_CHANGE (dlbuf);
1901       break;
1902     case PROP_LOW_PERCENT:
1903       dlbuf->low_percent = g_value_get_int (value);
1904       break;
1905     case PROP_HIGH_PERCENT:
1906       dlbuf->high_percent = g_value_get_int (value);
1907       break;
1908     case PROP_TEMP_TEMPLATE:
1909       gst_download_buffer_set_temp_template (dlbuf, g_value_get_string (value));
1910       break;
1911     case PROP_TEMP_REMOVE:
1912       dlbuf->temp_remove = g_value_get_boolean (value);
1913       break;
1914     default:
1915       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1916       break;
1917   }
1918
1919   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1920
1921   if (msg != NULL)
1922     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1923
1924 }
1925
1926 static void
1927 gst_download_buffer_get_property (GObject * object,
1928     guint prop_id, GValue * value, GParamSpec * pspec)
1929 {
1930   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
1931
1932   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1933
1934   switch (prop_id) {
1935     case PROP_MAX_SIZE_BYTES:
1936       g_value_set_uint (value, dlbuf->max_level.bytes);
1937       break;
1938     case PROP_MAX_SIZE_TIME:
1939       g_value_set_uint64 (value, dlbuf->max_level.time);
1940       break;
1941     case PROP_LOW_PERCENT:
1942       g_value_set_int (value, dlbuf->low_percent);
1943       break;
1944     case PROP_HIGH_PERCENT:
1945       g_value_set_int (value, dlbuf->high_percent);
1946       break;
1947     case PROP_TEMP_TEMPLATE:
1948       g_value_set_string (value, dlbuf->temp_template);
1949       break;
1950     case PROP_TEMP_LOCATION:
1951       g_value_set_string (value, dlbuf->temp_location);
1952       break;
1953     case PROP_TEMP_REMOVE:
1954       g_value_set_boolean (value, dlbuf->temp_remove);
1955       break;
1956     default:
1957       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1958       break;
1959   }
1960
1961   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1962 }