fakesink, identity: print metas attached to buffer in silent=false mode
[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 emitting 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 #else
74 #include <unistd.h>
75 #endif
76
77 #ifdef __BIONIC__
78 #include <fcntl.h>
79 #endif
80
81 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
82     GST_PAD_SINK,
83     GST_PAD_ALWAYS,
84     GST_STATIC_CAPS_ANY);
85
86 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
87     GST_PAD_SRC,
88     GST_PAD_ALWAYS,
89     GST_STATIC_CAPS_ANY);
90
91 GST_DEBUG_CATEGORY_STATIC (downloadbuffer_debug);
92 #define GST_CAT_DEFAULT (downloadbuffer_debug)
93
94 enum
95 {
96   LAST_SIGNAL
97 };
98
99 /* other defines */
100 #define DEFAULT_BUFFER_SIZE 4096
101
102 /* default property values */
103 #define DEFAULT_MAX_SIZE_BYTES     (2 * 1024 * 1024)    /* 2 MB */
104 #define DEFAULT_MAX_SIZE_TIME      2 * GST_SECOND       /* 2 seconds */
105 #define DEFAULT_LOW_PERCENT        10
106 #define DEFAULT_HIGH_PERCENT       99
107 #define DEFAULT_TEMP_REMOVE        TRUE
108
109 enum
110 {
111   PROP_0,
112   PROP_MAX_SIZE_BYTES,
113   PROP_MAX_SIZE_TIME,
114   PROP_LOW_PERCENT,
115   PROP_HIGH_PERCENT,
116   PROP_TEMP_TEMPLATE,
117   PROP_TEMP_LOCATION,
118   PROP_TEMP_REMOVE,
119   PROP_LAST
120 };
121
122 #define GST_DOWNLOAD_BUFFER_CLEAR_LEVEL(l) G_STMT_START {         \
123   l.bytes = 0;                                          \
124   l.time = 0;                                           \
125 } G_STMT_END
126
127 #define STATUS(elem, pad, msg) \
128   GST_LOG_OBJECT (elem, "(%s:%s) " msg ": %u of %u " \
129                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
130                       " ns", \
131                       GST_DEBUG_PAD_NAME (pad), \
132                       elem->cur_level.bytes, \
133                       elem->max_level.bytes, \
134                       elem->cur_level.time, \
135                       elem->max_level.time)
136
137 #define GST_DOWNLOAD_BUFFER_MUTEX_LOCK(q) G_STMT_START {                          \
138   g_mutex_lock (&q->qlock);                                              \
139 } G_STMT_END
140
141 #define GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
142   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (q);                                            \
143   if (res != GST_FLOW_OK)                                               \
144     goto label;                                                         \
145 } G_STMT_END
146
147 #define GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK(q) G_STMT_START {                        \
148   g_mutex_unlock (&q->qlock);                                            \
149 } G_STMT_END
150
151 #define GST_DOWNLOAD_BUFFER_WAIT_ADD_CHECK(q, res, o, label) G_STMT_START {       \
152   STATUS (q, q->srcpad, "wait for ADD");                            \
153   q->waiting_add = TRUE;                                                \
154   q->waiting_offset = o;                                                \
155   g_cond_wait (&q->item_add, &q->qlock);                                \
156   q->waiting_add = FALSE;                                               \
157   if (res != GST_FLOW_OK) {                                             \
158     STATUS (q, q->srcpad, "received ADD wakeup");                   \
159     goto label;                                                         \
160   }                                                                     \
161   STATUS (q, q->srcpad, "received ADD");                            \
162 } G_STMT_END
163
164 #define GST_DOWNLOAD_BUFFER_SIGNAL_ADD(q, o) G_STMT_START {                       \
165   if (q->waiting_add && q->waiting_offset <= o) {                       \
166     STATUS (q, q->sinkpad, "signal ADD");                               \
167     g_cond_signal (&q->item_add);                                       \
168   }                                                                     \
169 } G_STMT_END
170
171 #define _do_init \
172     GST_DEBUG_CATEGORY_INIT (downloadbuffer_debug, "downloadbuffer", 0, \
173         "downloadbuffer element");
174
175 #define gst_download_buffer_parent_class parent_class
176 G_DEFINE_TYPE_WITH_CODE (GstDownloadBuffer, gst_download_buffer,
177     GST_TYPE_ELEMENT, _do_init);
178
179 static GstMessage *update_buffering (GstDownloadBuffer * dlbuf);
180
181 static void gst_download_buffer_finalize (GObject * object);
182
183 static void gst_download_buffer_set_property (GObject * object,
184     guint prop_id, const GValue * value, GParamSpec * pspec);
185 static void gst_download_buffer_get_property (GObject * object,
186     guint prop_id, GValue * value, GParamSpec * pspec);
187
188 static GstFlowReturn gst_download_buffer_chain (GstPad * pad,
189     GstObject * parent, GstBuffer * buffer);
190 static void gst_download_buffer_loop (GstPad * pad);
191
192 static gboolean gst_download_buffer_handle_sink_event (GstPad * pad,
193     GstObject * parent, GstEvent * event);
194 static gboolean gst_download_buffer_handle_sink_query (GstPad * pad,
195     GstObject * parent, GstQuery * query);
196
197 static gboolean gst_download_buffer_handle_src_event (GstPad * pad,
198     GstObject * parent, GstEvent * event);
199 static gboolean gst_download_buffer_handle_src_query (GstPad * pad,
200     GstObject * parent, GstQuery * query);
201 static gboolean gst_download_buffer_handle_query (GstElement * element,
202     GstQuery * query);
203
204 static GstFlowReturn gst_download_buffer_get_range (GstPad * pad,
205     GstObject * parent, guint64 offset, guint length, GstBuffer ** buffer);
206
207 static gboolean gst_download_buffer_src_activate_mode (GstPad * pad,
208     GstObject * parent, GstPadMode mode, gboolean active);
209 static gboolean gst_download_buffer_sink_activate_mode (GstPad * pad,
210     GstObject * parent, GstPadMode mode, gboolean active);
211 static GstStateChangeReturn gst_download_buffer_change_state (GstElement *
212     element, GstStateChange transition);
213
214 /* static guint gst_download_buffer_signals[LAST_SIGNAL] = { 0 }; */
215
216 static void
217 gst_download_buffer_class_init (GstDownloadBufferClass * klass)
218 {
219   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
220   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
221
222   gobject_class->set_property = gst_download_buffer_set_property;
223   gobject_class->get_property = gst_download_buffer_get_property;
224
225   /* properties */
226   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
227       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
228           "Max. amount of data to buffer (bytes, 0=disable)",
229           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
230           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
231           G_PARAM_STATIC_STRINGS));
232   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
233       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
234           "Max. amount of data to buffer (in ns, 0=disable)", 0, G_MAXUINT64,
235           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
236           G_PARAM_STATIC_STRINGS));
237
238   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
239       g_param_spec_int ("low-percent", "Low percent",
240           "Low threshold for buffering to start. Only used if use-buffering is True",
241           0, 100, DEFAULT_LOW_PERCENT,
242           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
243   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
244       g_param_spec_int ("high-percent", "High percent",
245           "High threshold for buffering to finish. Only used if use-buffering is True",
246           0, 100, DEFAULT_HIGH_PERCENT,
247           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
248
249   g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
250       g_param_spec_string ("temp-template", "Temporary File Template",
251           "File template to store temporary files in, should contain directory "
252           "and XXXXXX. (NULL == disabled)",
253           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
254
255   g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
256       g_param_spec_string ("temp-location", "Temporary File Location",
257           "Location to store temporary files in (Only read this property, "
258           "use temp-template to configure the name template)",
259           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
260
261   /**
262    * GstDownloadBuffer:temp-remove
263    *
264    * When temp-template is set, remove the temporary file when going to READY.
265    */
266   g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
267       g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
268           "Remove the temp-location after use",
269           DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
270
271   /* set several parent class virtual functions */
272   gobject_class->finalize = gst_download_buffer_finalize;
273
274   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
275   gst_element_class_add_static_pad_template (gstelement_class, &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 file */
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 #ifdef __BIONIC__
882   fd = g_mkstemp_full (name, O_RDWR | O_LARGEFILE, S_IRUSR | S_IWUSR);
883 #else
884   fd = g_mkstemp (name);
885 #endif
886   if (fd == -1)
887     goto mkstemp_failed;
888
889   /* open the file for update/writing */
890   dlbuf->file = gst_sparse_file_new ();
891   /* error creating file */
892   if (!gst_sparse_file_set_fd (dlbuf->file, fd))
893     goto open_failed;
894
895   g_free (dlbuf->temp_location);
896   dlbuf->temp_location = name;
897   dlbuf->temp_fd = fd;
898   reset_positions (dlbuf);
899
900   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
901
902   /* we can't emit the notify with the lock */
903   g_object_notify (G_OBJECT (dlbuf), "temp-location");
904
905   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
906
907   GST_DEBUG_OBJECT (dlbuf, "opened temp file %s", dlbuf->temp_template);
908
909   return TRUE;
910
911   /* ERRORS */
912 already_opened:
913   {
914     GST_DEBUG_OBJECT (dlbuf, "temp file was already open");
915     return TRUE;
916   }
917 no_directory:
918   {
919     GST_ELEMENT_ERROR (dlbuf, RESOURCE, NOT_FOUND,
920         (_("No Temp directory specified.")), (NULL));
921     return FALSE;
922   }
923 mkstemp_failed:
924   {
925     GST_ELEMENT_ERROR (dlbuf, RESOURCE, OPEN_READ,
926         (_("Could not create temp file \"%s\"."), dlbuf->temp_template),
927         GST_ERROR_SYSTEM);
928     g_free (name);
929     return FALSE;
930   }
931 open_failed:
932   {
933     GST_ELEMENT_ERROR (dlbuf, RESOURCE, OPEN_READ,
934         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
935     g_free (name);
936     if (fd != -1)
937       close (fd);
938     return FALSE;
939   }
940 }
941
942 static void
943 gst_download_buffer_close_temp_location_file (GstDownloadBuffer * dlbuf)
944 {
945   /* nothing to do */
946   if (dlbuf->file == NULL)
947     return;
948
949   GST_DEBUG_OBJECT (dlbuf, "closing sparse file");
950
951   if (dlbuf->temp_remove) {
952     if (remove (dlbuf->temp_location) < 0) {
953       GST_WARNING_OBJECT (dlbuf, "Failed to remove temporary file %s: %s",
954           dlbuf->temp_location, g_strerror (errno));
955     }
956   }
957   gst_sparse_file_free (dlbuf->file);
958   close (dlbuf->temp_fd);
959   dlbuf->file = NULL;
960 }
961
962 static void
963 gst_download_buffer_flush_temp_file (GstDownloadBuffer * dlbuf)
964 {
965   if (dlbuf->file == NULL)
966     return;
967
968   GST_DEBUG_OBJECT (dlbuf, "flushing temp file");
969
970   gst_sparse_file_clear (dlbuf->file);
971 }
972
973 static void
974 gst_download_buffer_locked_flush (GstDownloadBuffer * dlbuf, gboolean full,
975     gboolean clear_temp)
976 {
977   if (clear_temp)
978     gst_download_buffer_flush_temp_file (dlbuf);
979   reset_positions (dlbuf);
980   gst_event_replace (&dlbuf->stream_start_event, NULL);
981   gst_event_replace (&dlbuf->segment_event, NULL);
982 }
983
984 static gboolean
985 gst_download_buffer_handle_sink_event (GstPad * pad, GstObject * parent,
986     GstEvent * event)
987 {
988   gboolean ret = TRUE;
989   GstDownloadBuffer *dlbuf;
990
991   dlbuf = GST_DOWNLOAD_BUFFER (parent);
992
993   switch (GST_EVENT_TYPE (event)) {
994     case GST_EVENT_FLUSH_START:
995     {
996       GST_LOG_OBJECT (dlbuf, "received flush start event");
997       if (GST_PAD_MODE (dlbuf->srcpad) == GST_PAD_MODE_PUSH) {
998         /* forward event */
999         ret = gst_pad_push_event (dlbuf->srcpad, event);
1000
1001         /* now unblock the chain function */
1002         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1003         dlbuf->srcresult = GST_FLOW_FLUSHING;
1004         dlbuf->sinkresult = GST_FLOW_FLUSHING;
1005         /* unblock the loop and chain functions */
1006         GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1007         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1008
1009         /* make sure it pauses, this should happen since we sent
1010          * flush_start downstream. */
1011         gst_pad_pause_task (dlbuf->srcpad);
1012         GST_LOG_OBJECT (dlbuf, "loop stopped");
1013       } else {
1014         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1015         /* flush the sink pad */
1016         dlbuf->sinkresult = GST_FLOW_FLUSHING;
1017         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1018
1019         gst_event_unref (event);
1020       }
1021       break;
1022     }
1023     case GST_EVENT_FLUSH_STOP:
1024     {
1025       GST_LOG_OBJECT (dlbuf, "received flush stop event");
1026
1027       if (GST_PAD_MODE (dlbuf->srcpad) == GST_PAD_MODE_PUSH) {
1028         /* forward event */
1029         ret = gst_pad_push_event (dlbuf->srcpad, event);
1030
1031         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1032         gst_download_buffer_locked_flush (dlbuf, FALSE, TRUE);
1033         dlbuf->srcresult = GST_FLOW_OK;
1034         dlbuf->sinkresult = GST_FLOW_OK;
1035         dlbuf->unexpected = FALSE;
1036         dlbuf->seeking = FALSE;
1037         /* reset rate counters */
1038         reset_rate_timer (dlbuf);
1039         gst_pad_start_task (dlbuf->srcpad,
1040             (GstTaskFunction) gst_download_buffer_loop, dlbuf->srcpad, NULL);
1041         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1042       } else {
1043         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1044         dlbuf->unexpected = FALSE;
1045         dlbuf->sinkresult = GST_FLOW_OK;
1046         dlbuf->seeking = FALSE;
1047         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1048
1049         gst_event_unref (event);
1050       }
1051       break;
1052     }
1053     default:
1054       if (GST_EVENT_IS_SERIALIZED (event)) {
1055         GstMessage *msg = NULL;
1056
1057         /* serialized events go in the buffer */
1058         GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->sinkresult,
1059             out_flushing);
1060         switch (GST_EVENT_TYPE (event)) {
1061           case GST_EVENT_EOS:
1062             GST_DEBUG_OBJECT (dlbuf, "we have EOS");
1063             /* Zero the thresholds, this makes sure the dlbuf is completely
1064              * filled and we can read all data from the dlbuf. */
1065             /* update the buffering status */
1066             update_levels (dlbuf, dlbuf->max_level.bytes);
1067             /* update the buffering */
1068             msg = update_buffering (dlbuf);
1069             /* wakeup the waiter and let it recheck */
1070             GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1071             break;
1072           case GST_EVENT_SEGMENT:
1073             gst_event_replace (&dlbuf->segment_event, event);
1074             /* a new segment allows us to accept more buffers if we got EOS
1075              * from downstream */
1076             dlbuf->unexpected = FALSE;
1077             break;
1078           case GST_EVENT_STREAM_START:
1079             gst_event_replace (&dlbuf->stream_start_event, event);
1080             break;
1081           default:
1082             break;
1083         }
1084         gst_event_unref (event);
1085         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1086         if (msg != NULL)
1087           gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1088       } else {
1089         /* non-serialized events are passed upstream. */
1090         ret = gst_pad_push_event (dlbuf->srcpad, event);
1091       }
1092       break;
1093   }
1094   return ret;
1095
1096   /* ERRORS */
1097 out_flushing:
1098   {
1099     GST_DEBUG_OBJECT (dlbuf, "refusing event, we are flushing");
1100     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1101     gst_event_unref (event);
1102     return FALSE;
1103   }
1104 }
1105
1106 static gboolean
1107 gst_download_buffer_handle_sink_query (GstPad * pad, GstObject * parent,
1108     GstQuery * query)
1109 {
1110   GstDownloadBuffer *dlbuf;
1111   gboolean res;
1112
1113   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1114
1115   switch (GST_QUERY_TYPE (query)) {
1116     default:
1117       if (GST_QUERY_IS_SERIALIZED (query)) {
1118         GST_LOG_OBJECT (dlbuf, "received query %p", query);
1119         GST_DEBUG_OBJECT (dlbuf, "refusing query, we are not using the dlbuf");
1120         res = FALSE;
1121       } else {
1122         res = gst_pad_query_default (pad, parent, query);
1123       }
1124       break;
1125   }
1126   return res;
1127 }
1128
1129 static GstFlowReturn
1130 gst_download_buffer_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1131 {
1132   GstDownloadBuffer *dlbuf;
1133   GstMapInfo info;
1134   guint64 offset;
1135   gsize res, available;
1136   GError *error = NULL;
1137   GstMessage *msg = NULL;
1138
1139   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1140
1141   GST_LOG_OBJECT (dlbuf, "received buffer %p of "
1142       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
1143       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
1144       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1145       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1146
1147   /* we have to lock the dlbuf since we span threads */
1148   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->sinkresult, out_flushing);
1149   /* when we received unexpected from downstream, refuse more buffers */
1150   if (dlbuf->unexpected)
1151     goto out_eos;
1152
1153   /* while we didn't receive the newsegment, we're seeking and we skip data */
1154   if (dlbuf->seeking)
1155     goto out_seeking;
1156
1157   /* put buffer in dlbuf now */
1158   offset = dlbuf->write_pos;
1159
1160   /* sanity check */
1161   if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1162       GST_BUFFER_OFFSET (buffer) != offset) {
1163     GST_WARNING_OBJECT (dlbuf, "buffer offset does not match current writing "
1164         "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1165         GST_BUFFER_OFFSET (buffer), offset);
1166   }
1167
1168   gst_buffer_map (buffer, &info, GST_MAP_READ);
1169
1170   GST_DEBUG_OBJECT (dlbuf, "Writing %" G_GSIZE_FORMAT " bytes to %"
1171       G_GUINT64_FORMAT, info.size, offset);
1172
1173   res =
1174       gst_sparse_file_write (dlbuf->file, offset, info.data, info.size,
1175       &available, &error);
1176   if (res == 0)
1177     goto write_error;
1178
1179   gst_buffer_unmap (buffer, &info);
1180   gst_buffer_unref (buffer);
1181
1182   dlbuf->write_pos = offset + info.size;
1183   dlbuf->bytes_in += info.size;
1184
1185   GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, dlbuf->write_pos + available);
1186
1187   /* we hit the end, see what to do */
1188   if (dlbuf->write_pos + available == dlbuf->upstream_size) {
1189     gsize start, stop;
1190
1191     /* we have everything up to the end, find a region to fill */
1192     if (gst_sparse_file_get_range_after (dlbuf->file, 0, &start, &stop)) {
1193       if (stop < dlbuf->upstream_size) {
1194         /* a hole to fill, seek to its end */
1195         perform_seek_to_offset (dlbuf, stop);
1196       } else {
1197         /* we filled all the holes, we are done */
1198         goto completed;
1199       }
1200     }
1201   } else {
1202     /* see if we need to skip this region or just read it again. The idea
1203      * is that when the region is not big, we want to avoid a seek and just
1204      * let it reread */
1205     guint64 threshold = get_seek_threshold (dlbuf);
1206
1207     if (available > threshold) {
1208       /* further than threshold, it's better to skip than to reread */
1209       perform_seek_to_offset (dlbuf, dlbuf->write_pos + available);
1210     }
1211   }
1212   if (dlbuf->filling) {
1213     if (dlbuf->write_pos > dlbuf->read_pos)
1214       update_levels (dlbuf, dlbuf->write_pos - dlbuf->read_pos);
1215     else
1216       update_levels (dlbuf, 0);
1217   }
1218
1219   /* update the buffering */
1220   msg = update_buffering (dlbuf);
1221
1222   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1223
1224   if (msg != NULL)
1225     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1226
1227   return GST_FLOW_OK;
1228
1229   /* ERRORS */
1230 out_flushing:
1231   {
1232     GstFlowReturn ret = dlbuf->sinkresult;
1233     GST_LOG_OBJECT (dlbuf,
1234         "exit because task paused, reason: %s", gst_flow_get_name (ret));
1235     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1236     gst_buffer_unref (buffer);
1237     return ret;
1238   }
1239 out_eos:
1240   {
1241     GST_LOG_OBJECT (dlbuf, "exit because we received EOS");
1242     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1243     gst_buffer_unref (buffer);
1244     return GST_FLOW_EOS;
1245   }
1246 out_seeking:
1247   {
1248     GST_LOG_OBJECT (dlbuf, "exit because we are seeking");
1249     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1250     gst_buffer_unref (buffer);
1251     return GST_FLOW_OK;
1252   }
1253 write_error:
1254   {
1255     gst_buffer_unmap (buffer, &info);
1256     gst_buffer_unref (buffer);
1257     GST_ELEMENT_ERROR (dlbuf, RESOURCE, WRITE,
1258         (_("Error while writing to download file.")), ("%s", error->message));
1259     g_clear_error (&error);
1260     return GST_FLOW_ERROR;
1261   }
1262 completed:
1263   {
1264     GST_LOG_OBJECT (dlbuf, "we completed the download");
1265     dlbuf->write_pos = dlbuf->upstream_size;
1266     dlbuf->filling = FALSE;
1267     update_levels (dlbuf, dlbuf->max_level.bytes);
1268     msg = update_buffering (dlbuf);
1269
1270     gst_element_post_message (GST_ELEMENT_CAST (dlbuf),
1271         gst_message_new_element (GST_OBJECT_CAST (dlbuf),
1272             gst_structure_new ("GstCacheDownloadComplete",
1273                 "location", G_TYPE_STRING, dlbuf->temp_location, NULL)));
1274
1275     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1276
1277     if (msg != NULL)
1278       gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1279
1280     return GST_FLOW_EOS;
1281   }
1282 }
1283
1284 /* called repeatedly with @pad as the source pad. This function should push out
1285  * data to the peer element. */
1286 static void
1287 gst_download_buffer_loop (GstPad * pad)
1288 {
1289   GstDownloadBuffer *dlbuf;
1290   GstFlowReturn ret;
1291   GstBuffer *buffer = NULL;
1292   GstMessage *msg = NULL;
1293
1294   dlbuf = GST_DOWNLOAD_BUFFER (GST_PAD_PARENT (pad));
1295
1296   /* have to lock for thread-safety */
1297   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1298
1299   if (dlbuf->stream_start_event != NULL) {
1300     gst_pad_push_event (dlbuf->srcpad, dlbuf->stream_start_event);
1301     dlbuf->stream_start_event = NULL;
1302   }
1303   if (dlbuf->segment_event != NULL) {
1304     gst_pad_push_event (dlbuf->srcpad, dlbuf->segment_event);
1305     dlbuf->segment_event = NULL;
1306   }
1307
1308   ret = gst_download_buffer_read_buffer (dlbuf, -1, -1, &buffer);
1309   if (ret != GST_FLOW_OK)
1310     goto out_flushing;
1311
1312   /* update the buffering */
1313   msg = update_buffering (dlbuf);
1314
1315   g_atomic_int_set (&dlbuf->downstream_may_block, 1);
1316   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1317
1318   if (msg != NULL)
1319     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1320
1321   ret = gst_pad_push (dlbuf->srcpad, buffer);
1322   g_atomic_int_set (&dlbuf->downstream_may_block, 0);
1323
1324   /* need to check for srcresult here as well */
1325   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1326   dlbuf->srcresult = ret;
1327   dlbuf->sinkresult = ret;
1328   if (ret != GST_FLOW_OK)
1329     goto out_flushing;
1330   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1331
1332   return;
1333
1334   /* ERRORS */
1335 out_flushing:
1336   {
1337     GstFlowReturn ret = dlbuf->srcresult;
1338
1339     gst_pad_pause_task (dlbuf->srcpad);
1340     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1341     GST_LOG_OBJECT (dlbuf, "pause task, reason:  %s", gst_flow_get_name (ret));
1342     /* let app know about us giving up if upstream is not expected to do so */
1343     if (ret == GST_FLOW_EOS) {
1344       /* FIXME perform EOS logic, this is really a basesrc operating on a
1345        * file. */
1346       gst_pad_push_event (dlbuf->srcpad, gst_event_new_eos ());
1347     } else if ((ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1348       GST_ELEMENT_FLOW_ERROR (dlbuf, ret);
1349       gst_pad_push_event (dlbuf->srcpad, gst_event_new_eos ());
1350     }
1351     return;
1352   }
1353 }
1354
1355 static gboolean
1356 gst_download_buffer_handle_src_event (GstPad * pad, GstObject * parent,
1357     GstEvent * event)
1358 {
1359   gboolean res = TRUE;
1360   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (parent);
1361
1362 #ifndef GST_DISABLE_GST_DEBUG
1363   GST_DEBUG_OBJECT (dlbuf, "got event %p (%s)",
1364       event, GST_EVENT_TYPE_NAME (event));
1365 #endif
1366
1367   switch (GST_EVENT_TYPE (event)) {
1368     case GST_EVENT_FLUSH_START:
1369       /* now unblock the getrange function */
1370       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1371       GST_DEBUG_OBJECT (dlbuf, "flushing");
1372       dlbuf->srcresult = GST_FLOW_FLUSHING;
1373       GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1374       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1375
1376       /* when using a temp file, we eat the event */
1377       res = TRUE;
1378       gst_event_unref (event);
1379       break;
1380     case GST_EVENT_FLUSH_STOP:
1381       /* now unblock the getrange function */
1382       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1383       dlbuf->srcresult = GST_FLOW_OK;
1384       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1385
1386       /* when using a temp file, we eat the event */
1387       res = TRUE;
1388       gst_event_unref (event);
1389       break;
1390     case GST_EVENT_RECONFIGURE:
1391       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1392       /* assume downstream is linked now and try to push again */
1393       if (dlbuf->srcresult == GST_FLOW_NOT_LINKED) {
1394         dlbuf->srcresult = GST_FLOW_OK;
1395         dlbuf->sinkresult = GST_FLOW_OK;
1396         if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
1397           gst_pad_start_task (pad, (GstTaskFunction) gst_download_buffer_loop,
1398               pad, NULL);
1399         }
1400       }
1401       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1402
1403       res = gst_pad_push_event (dlbuf->sinkpad, event);
1404       break;
1405     default:
1406       res = gst_pad_push_event (dlbuf->sinkpad, event);
1407       break;
1408   }
1409
1410   return res;
1411 }
1412
1413 static gboolean
1414 gst_download_buffer_handle_src_query (GstPad * pad, GstObject * parent,
1415     GstQuery * query)
1416 {
1417   GstDownloadBuffer *dlbuf;
1418
1419   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1420
1421   switch (GST_QUERY_TYPE (query)) {
1422     case GST_QUERY_POSITION:
1423     {
1424       gint64 peer_pos;
1425       GstFormat format;
1426
1427       if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1428         goto peer_failed;
1429
1430       /* get peer position */
1431       gst_query_parse_position (query, &format, &peer_pos);
1432
1433       /* FIXME: this code assumes that there's no discont in the dlbuf */
1434       switch (format) {
1435         case GST_FORMAT_BYTES:
1436           peer_pos -= dlbuf->cur_level.bytes;
1437           if (peer_pos < 0)     /* Clamp result to 0 */
1438             peer_pos = 0;
1439           break;
1440         case GST_FORMAT_TIME:
1441           peer_pos -= dlbuf->cur_level.time;
1442           if (peer_pos < 0)     /* Clamp result to 0 */
1443             peer_pos = 0;
1444           break;
1445         default:
1446           GST_WARNING_OBJECT (dlbuf, "dropping query in %s format, don't "
1447               "know how to adjust value", gst_format_get_name (format));
1448           return FALSE;
1449       }
1450       /* set updated position */
1451       gst_query_set_position (query, format, peer_pos);
1452       break;
1453     }
1454     case GST_QUERY_DURATION:
1455     {
1456       GST_DEBUG_OBJECT (dlbuf, "doing peer query");
1457
1458       if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1459         goto peer_failed;
1460
1461       GST_DEBUG_OBJECT (dlbuf, "peer query success");
1462       break;
1463     }
1464     case GST_QUERY_BUFFERING:
1465     {
1466       gint percent;
1467       gboolean is_buffering;
1468       GstBufferingMode mode;
1469       gint avg_in, avg_out;
1470       gint64 buffering_left;
1471
1472       GST_DEBUG_OBJECT (dlbuf, "query buffering");
1473
1474       get_buffering_percent (dlbuf, &is_buffering, &percent);
1475       gst_query_set_buffering_percent (query, is_buffering, percent);
1476
1477       get_buffering_stats (dlbuf, percent, &mode, &avg_in, &avg_out,
1478           &buffering_left);
1479       gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
1480           buffering_left);
1481
1482       {
1483         /* add ranges for download and ringbuffer buffering */
1484         GstFormat format;
1485         gint64 start, stop;
1486         guint64 write_pos;
1487         gint64 estimated_total;
1488         gint64 duration;
1489         gsize offset, range_start, range_stop;
1490
1491         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1492         write_pos = dlbuf->write_pos;
1493
1494         /* get duration of upstream in bytes */
1495         gst_download_buffer_update_upstream_size (dlbuf);
1496         duration = dlbuf->upstream_size;
1497
1498         GST_DEBUG_OBJECT (dlbuf, "percent %d, duration %" G_GINT64_FORMAT
1499             ", writing %" G_GINT64_FORMAT, percent, duration, write_pos);
1500
1501         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
1502
1503         /* fill out the buffered ranges */
1504         start = offset = 0;
1505         stop = -1;
1506         estimated_total = -1;
1507         while (gst_sparse_file_get_range_after (dlbuf->file, offset,
1508                 &range_start, &range_stop)) {
1509           gboolean current_range;
1510
1511           GST_DEBUG_OBJECT (dlbuf,
1512               "range starting at %" G_GSIZE_FORMAT " and finishing at %"
1513               G_GSIZE_FORMAT, range_start, range_stop);
1514
1515           offset = range_stop;
1516
1517           /* find the range we are currently downloading, we'll remember it
1518            * after we convert to the target format */
1519           if (range_start <= write_pos && range_stop >= write_pos) {
1520             current_range = TRUE;
1521             /* calculate remaining and total download time */
1522             if (duration >= range_stop && avg_in > 0.0)
1523               estimated_total = ((duration - range_stop) * 1000) / avg_in;
1524           } else
1525             current_range = FALSE;
1526
1527           switch (format) {
1528             case GST_FORMAT_PERCENT:
1529               /* get our available data relative to the duration */
1530               if (duration == -1) {
1531                 range_start = 0;
1532                 range_stop = 0;
1533               } else {
1534                 range_start = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
1535                     range_start, duration);
1536                 range_stop = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
1537                     range_stop, duration);
1538               }
1539               break;
1540             case GST_FORMAT_BYTES:
1541               break;
1542             default:
1543               range_start = -1;
1544               range_stop = -1;
1545               break;
1546           }
1547
1548           if (current_range) {
1549             /* we are currently downloading this range */
1550             start = range_start;
1551             stop = range_stop;
1552           }
1553           GST_DEBUG_OBJECT (dlbuf,
1554               "range to format: %" G_GSIZE_FORMAT " - %" G_GSIZE_FORMAT,
1555               range_start, range_stop);
1556           if (range_start == range_stop)
1557             continue;
1558           gst_query_add_buffering_range (query, range_start, range_stop);
1559         }
1560
1561         GST_DEBUG_OBJECT (dlbuf, "estimated-total %" G_GINT64_FORMAT,
1562             estimated_total);
1563
1564         gst_query_set_buffering_range (query, format, start, stop,
1565             estimated_total);
1566
1567         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1568       }
1569       break;
1570     }
1571     case GST_QUERY_SCHEDULING:
1572     {
1573       GstSchedulingFlags flags = 0;
1574
1575       if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1576         goto peer_failed;
1577
1578       gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
1579
1580       /* we can operate in pull mode when we are using a tempfile */
1581       flags |= GST_SCHEDULING_FLAG_SEEKABLE;
1582       gst_query_set_scheduling (query, flags, 0, -1, 0);
1583       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
1584       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
1585       break;
1586     }
1587     default:
1588       /* peer handled other queries */
1589       if (!gst_pad_query_default (pad, parent, query))
1590         goto peer_failed;
1591       break;
1592   }
1593
1594   return TRUE;
1595
1596   /* ERRORS */
1597 peer_failed:
1598   {
1599     GST_DEBUG_OBJECT (dlbuf, "failed peer query");
1600     return FALSE;
1601   }
1602 }
1603
1604 static gboolean
1605 gst_download_buffer_handle_query (GstElement * element, GstQuery * query)
1606 {
1607   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (element);
1608
1609   /* simply forward to the srcpad query function */
1610   return gst_download_buffer_handle_src_query (dlbuf->srcpad,
1611       GST_OBJECT_CAST (element), query);
1612 }
1613
1614 static GstFlowReturn
1615 gst_download_buffer_get_range (GstPad * pad, GstObject * parent, guint64 offset,
1616     guint length, GstBuffer ** buffer)
1617 {
1618   GstDownloadBuffer *dlbuf;
1619   GstFlowReturn ret;
1620   GstMessage *msg = NULL;
1621
1622   dlbuf = GST_DOWNLOAD_BUFFER_CAST (parent);
1623
1624   GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1625   /* FIXME - function will block when the range is not yet available */
1626   ret = gst_download_buffer_read_buffer (dlbuf, offset, length, buffer);
1627   /* update the buffering */
1628   msg = update_buffering (dlbuf);
1629
1630   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1631
1632   if (msg != NULL)
1633     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1634
1635   return ret;
1636
1637   /* ERRORS */
1638 out_flushing:
1639   {
1640     ret = dlbuf->srcresult;
1641
1642     GST_DEBUG_OBJECT (dlbuf, "we are flushing");
1643     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1644     return ret;
1645   }
1646 }
1647
1648 /* sink currently only operates in push mode */
1649 static gboolean
1650 gst_download_buffer_sink_activate_mode (GstPad * pad, GstObject * parent,
1651     GstPadMode mode, gboolean active)
1652 {
1653   gboolean result;
1654   GstDownloadBuffer *dlbuf;
1655
1656   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1657
1658   switch (mode) {
1659     case GST_PAD_MODE_PUSH:
1660       if (active) {
1661         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1662         GST_DEBUG_OBJECT (dlbuf, "activating push mode");
1663         dlbuf->srcresult = GST_FLOW_OK;
1664         dlbuf->sinkresult = GST_FLOW_OK;
1665         dlbuf->unexpected = FALSE;
1666         reset_rate_timer (dlbuf);
1667         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1668       } else {
1669         /* unblock chain function */
1670         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1671         GST_DEBUG_OBJECT (dlbuf, "deactivating push mode");
1672         dlbuf->srcresult = GST_FLOW_FLUSHING;
1673         dlbuf->sinkresult = GST_FLOW_FLUSHING;
1674         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1675
1676         /* wait until it is unblocked and clean up */
1677         GST_PAD_STREAM_LOCK (pad);
1678         GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1679         gst_download_buffer_locked_flush (dlbuf, TRUE, FALSE);
1680         GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1681         GST_PAD_STREAM_UNLOCK (pad);
1682       }
1683       result = TRUE;
1684       break;
1685     default:
1686       result = FALSE;
1687       break;
1688   }
1689   return result;
1690 }
1691
1692 /* src operating in push mode, we start a task on the source pad that pushes out
1693  * buffers from the dlbuf */
1694 static gboolean
1695 gst_download_buffer_src_activate_push (GstPad * pad, GstObject * parent,
1696     gboolean active)
1697 {
1698   gboolean result = FALSE;
1699   GstDownloadBuffer *dlbuf;
1700
1701   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1702
1703   if (active) {
1704     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1705     GST_DEBUG_OBJECT (dlbuf, "activating push mode");
1706     dlbuf->srcresult = GST_FLOW_OK;
1707     dlbuf->sinkresult = GST_FLOW_OK;
1708     dlbuf->unexpected = FALSE;
1709     result =
1710         gst_pad_start_task (pad, (GstTaskFunction) gst_download_buffer_loop,
1711         pad, NULL);
1712     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1713   } else {
1714     /* unblock loop function */
1715     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1716     GST_DEBUG_OBJECT (dlbuf, "deactivating push mode");
1717     dlbuf->srcresult = GST_FLOW_FLUSHING;
1718     dlbuf->sinkresult = GST_FLOW_FLUSHING;
1719     /* the item add signal will unblock */
1720     GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1721     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1722
1723     /* step 2, make sure streaming finishes */
1724     result = gst_pad_stop_task (pad);
1725   }
1726
1727   return result;
1728 }
1729
1730 /* pull mode, downstream will call our getrange function */
1731 static gboolean
1732 gst_download_buffer_src_activate_pull (GstPad * pad, GstObject * parent,
1733     gboolean active)
1734 {
1735   gboolean result;
1736   GstDownloadBuffer *dlbuf;
1737
1738   dlbuf = GST_DOWNLOAD_BUFFER (parent);
1739
1740   if (active) {
1741     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1742     /* open the temp file now */
1743     result = gst_download_buffer_open_temp_location_file (dlbuf);
1744     GST_DEBUG_OBJECT (dlbuf, "activating pull mode");
1745     dlbuf->srcresult = GST_FLOW_OK;
1746     dlbuf->sinkresult = GST_FLOW_OK;
1747     dlbuf->unexpected = FALSE;
1748     dlbuf->upstream_size = 0;
1749     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1750   } else {
1751     GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1752     GST_DEBUG_OBJECT (dlbuf, "deactivating pull mode");
1753     dlbuf->srcresult = GST_FLOW_FLUSHING;
1754     dlbuf->sinkresult = GST_FLOW_FLUSHING;
1755     /* this will unlock getrange */
1756     GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1757     result = TRUE;
1758     GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1759   }
1760
1761   return result;
1762 }
1763
1764 static gboolean
1765 gst_download_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1766     GstPadMode mode, gboolean active)
1767 {
1768   gboolean res;
1769
1770   switch (mode) {
1771     case GST_PAD_MODE_PULL:
1772       res = gst_download_buffer_src_activate_pull (pad, parent, active);
1773       break;
1774     case GST_PAD_MODE_PUSH:
1775       res = gst_download_buffer_src_activate_push (pad, parent, active);
1776       break;
1777     default:
1778       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
1779       res = FALSE;
1780       break;
1781   }
1782   return res;
1783 }
1784
1785 static GstStateChangeReturn
1786 gst_download_buffer_change_state (GstElement * element,
1787     GstStateChange transition)
1788 {
1789   GstDownloadBuffer *dlbuf;
1790   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1791
1792   dlbuf = GST_DOWNLOAD_BUFFER (element);
1793
1794   switch (transition) {
1795     case GST_STATE_CHANGE_NULL_TO_READY:
1796       break;
1797     case GST_STATE_CHANGE_READY_TO_PAUSED:
1798       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1799       if (!gst_download_buffer_open_temp_location_file (dlbuf))
1800         ret = GST_STATE_CHANGE_FAILURE;
1801       gst_event_replace (&dlbuf->stream_start_event, NULL);
1802       gst_event_replace (&dlbuf->segment_event, NULL);
1803       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1804       break;
1805     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1806       break;
1807     default:
1808       break;
1809   }
1810
1811   if (ret == GST_STATE_CHANGE_FAILURE)
1812     return ret;
1813
1814   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1815
1816   if (ret == GST_STATE_CHANGE_FAILURE)
1817     return ret;
1818
1819   switch (transition) {
1820     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1821       break;
1822     case GST_STATE_CHANGE_PAUSED_TO_READY:
1823       GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1824       gst_download_buffer_close_temp_location_file (dlbuf);
1825       gst_event_replace (&dlbuf->stream_start_event, NULL);
1826       gst_event_replace (&dlbuf->segment_event, NULL);
1827       GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1828       break;
1829     case GST_STATE_CHANGE_READY_TO_NULL:
1830       break;
1831     default:
1832       break;
1833   }
1834
1835   return ret;
1836 }
1837
1838 #define CAPACITY_CHANGE(elem) \
1839   update_buffering (elem);
1840
1841 static void
1842 gst_download_buffer_set_temp_template (GstDownloadBuffer * dlbuf,
1843     const gchar * template)
1844 {
1845   GstState state;
1846
1847   /* the element must be stopped in order to do this */
1848   GST_OBJECT_LOCK (dlbuf);
1849   state = GST_STATE (dlbuf);
1850   if (state != GST_STATE_READY && state != GST_STATE_NULL)
1851     goto wrong_state;
1852   GST_OBJECT_UNLOCK (dlbuf);
1853
1854   /* set new location */
1855   g_free (dlbuf->temp_template);
1856   dlbuf->temp_template = g_strdup (template);
1857
1858   return;
1859
1860 /* ERROR */
1861 wrong_state:
1862   {
1863     GST_WARNING_OBJECT (dlbuf, "setting temp-template property in wrong state");
1864     GST_OBJECT_UNLOCK (dlbuf);
1865   }
1866 }
1867
1868 static void
1869 gst_download_buffer_set_property (GObject * object,
1870     guint prop_id, const GValue * value, GParamSpec * pspec)
1871 {
1872   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
1873   GstMessage *msg = NULL;
1874
1875   /* someone could change levels here, and since this
1876    * affects the get/put funcs, we need to lock for safety. */
1877   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1878
1879   switch (prop_id) {
1880     case PROP_MAX_SIZE_BYTES:
1881       dlbuf->max_level.bytes = g_value_get_uint (value);
1882       msg = CAPACITY_CHANGE (dlbuf);
1883       break;
1884     case PROP_MAX_SIZE_TIME:
1885       dlbuf->max_level.time = g_value_get_uint64 (value);
1886       msg = CAPACITY_CHANGE (dlbuf);
1887       break;
1888     case PROP_LOW_PERCENT:
1889       dlbuf->low_percent = g_value_get_int (value);
1890       break;
1891     case PROP_HIGH_PERCENT:
1892       dlbuf->high_percent = g_value_get_int (value);
1893       break;
1894     case PROP_TEMP_TEMPLATE:
1895       gst_download_buffer_set_temp_template (dlbuf, g_value_get_string (value));
1896       break;
1897     case PROP_TEMP_REMOVE:
1898       dlbuf->temp_remove = g_value_get_boolean (value);
1899       break;
1900     default:
1901       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1902       break;
1903   }
1904
1905   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1906
1907   if (msg != NULL)
1908     gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1909
1910 }
1911
1912 static void
1913 gst_download_buffer_get_property (GObject * object,
1914     guint prop_id, GValue * value, GParamSpec * pspec)
1915 {
1916   GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
1917
1918   GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1919
1920   switch (prop_id) {
1921     case PROP_MAX_SIZE_BYTES:
1922       g_value_set_uint (value, dlbuf->max_level.bytes);
1923       break;
1924     case PROP_MAX_SIZE_TIME:
1925       g_value_set_uint64 (value, dlbuf->max_level.time);
1926       break;
1927     case PROP_LOW_PERCENT:
1928       g_value_set_int (value, dlbuf->low_percent);
1929       break;
1930     case PROP_HIGH_PERCENT:
1931       g_value_set_int (value, dlbuf->high_percent);
1932       break;
1933     case PROP_TEMP_TEMPLATE:
1934       g_value_set_string (value, dlbuf->temp_template);
1935       break;
1936     case PROP_TEMP_LOCATION:
1937       g_value_set_string (value, dlbuf->temp_location);
1938       break;
1939     case PROP_TEMP_REMOVE:
1940       g_value_set_boolean (value, dlbuf->temp_remove);
1941       break;
1942     default:
1943       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1944       break;
1945   }
1946
1947   GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1948 }