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