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