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