2 * Copyright (C) 2014 Wim Taymans <wim.taymans@gmail.com>
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.
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.
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.
23 * SECTION:element-downloadbuffer
24 * @title: downloadbuffer
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.
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
37 * The downloadbuffer provides push and pull based scheduling on its source pad
38 * and will efficiently seek in the upstream element when needed.
40 * The temp-location property will be used to notify the application of the
43 * When the downloadbuffer has completely downloaded the media, it will
44 * post an application message named `GstCacheDownloadComplete`
45 * with the following information:
47 * * G_TYPE_STRING `location`: the location of the completely downloaded file.
55 #include "gstdownloadbuffer.h"
56 #include "gstcoreelementselements.h"
58 #include <glib/gstdio.h>
60 #include "gst/gst-i18n-lib.h"
61 #include "gst/glib-compat-private.h"
66 #include <io.h> /* lseek, open, close, read */
68 #define lseek _lseeki64
77 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
82 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
87 GST_DEBUG_CATEGORY_STATIC (downloadbuffer_debug);
88 #define GST_CAT_DEFAULT (downloadbuffer_debug)
96 #define DEFAULT_BUFFER_SIZE 4096
98 /* default property values */
99 #define DEFAULT_MAX_SIZE_BYTES (2 * 1024 * 1024) /* 2 MB */
100 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND /* 2 seconds */
101 #define DEFAULT_LOW_PERCENT 10
102 #define DEFAULT_HIGH_PERCENT 99
103 #define DEFAULT_TEMP_REMOVE TRUE
118 #define GST_DOWNLOAD_BUFFER_CLEAR_LEVEL(l) G_STMT_START { \
123 #define STATUS(elem, pad, msg) \
124 GST_LOG_OBJECT (elem, "(%s:%s) " msg ": %u of %u " \
125 "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
127 GST_DEBUG_PAD_NAME (pad), \
128 elem->cur_level.bytes, \
129 elem->max_level.bytes, \
130 elem->cur_level.time, \
131 elem->max_level.time)
133 #define GST_DOWNLOAD_BUFFER_MUTEX_LOCK(q) G_STMT_START { \
134 g_mutex_lock (&q->qlock); \
137 #define GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START { \
138 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (q); \
139 if (res != GST_FLOW_OK) \
143 #define GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK(q) G_STMT_START { \
144 g_mutex_unlock (&q->qlock); \
147 #define GST_DOWNLOAD_BUFFER_WAIT_ADD_CHECK(q, res, o, label) G_STMT_START { \
148 STATUS (q, q->srcpad, "wait for ADD"); \
149 q->waiting_add = TRUE; \
150 q->waiting_offset = o; \
151 g_cond_wait (&q->item_add, &q->qlock); \
152 q->waiting_add = FALSE; \
153 if (res != GST_FLOW_OK) { \
154 STATUS (q, q->srcpad, "received ADD wakeup"); \
157 STATUS (q, q->srcpad, "received ADD"); \
160 #define GST_DOWNLOAD_BUFFER_SIGNAL_ADD(q, o) G_STMT_START { \
161 if (q->waiting_add && q->waiting_offset <= o) { \
162 STATUS (q, q->sinkpad, "signal ADD"); \
163 g_cond_signal (&q->item_add); \
168 GST_DEBUG_CATEGORY_INIT (downloadbuffer_debug, "downloadbuffer", 0, \
169 "downloadbuffer element");
171 #define gst_download_buffer_parent_class parent_class
172 G_DEFINE_TYPE_WITH_CODE (GstDownloadBuffer, gst_download_buffer,
173 GST_TYPE_ELEMENT, _do_init);
174 GST_ELEMENT_REGISTER_DEFINE (downloadbuffer, "downloadbuffer", GST_RANK_NONE,
175 GST_TYPE_DOWNLOAD_BUFFER);
177 static GstMessage *update_buffering (GstDownloadBuffer * dlbuf);
179 static void gst_download_buffer_finalize (GObject * object);
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);
186 static GstFlowReturn gst_download_buffer_chain (GstPad * pad,
187 GstObject * parent, GstBuffer * buffer);
188 static void gst_download_buffer_loop (GstPad * pad);
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);
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,
202 static GstFlowReturn gst_download_buffer_get_range (GstPad * pad,
203 GstObject * parent, guint64 offset, guint length, GstBuffer ** buffer);
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);
212 /* static guint gst_download_buffer_signals[LAST_SIGNAL] = { 0 }; */
215 gst_download_buffer_class_init (GstDownloadBufferClass * klass)
217 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
218 GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
220 gobject_class->set_property = gst_download_buffer_set_property;
221 gobject_class->get_property = gst_download_buffer_get_property;
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));
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. "
239 "Emits GST_MESSAGE_BUFFERING with a value of 0%",
240 0, 100, DEFAULT_LOW_PERCENT,
241 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
242 g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
243 g_param_spec_int ("high-percent", "High percent",
244 "High threshold for buffering to finish. "
245 "Emits GST_MESSAGE_BUFFERING with a value of 100%",
246 0, 100, DEFAULT_HIGH_PERCENT,
247 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
249 g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
250 g_param_spec_string ("temp-template", "Temporary File Template",
251 "File template to store temporary files in, should contain directory "
252 "and XXXXXX. (NULL == disabled)",
253 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
255 g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
256 g_param_spec_string ("temp-location", "Temporary File Location",
257 "Location to store temporary files in (Only read this property, "
258 "use temp-template to configure the name template)",
259 NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
262 * GstDownloadBuffer:temp-remove
264 * When temp-template is set, remove the temporary file when going to READY.
266 g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
267 g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
268 "Remove the temp-location after use",
269 DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
271 /* set several parent class virtual functions */
272 gobject_class->finalize = gst_download_buffer_finalize;
274 gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
275 gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
277 gst_element_class_set_static_metadata (gstelement_class, "DownloadBuffer",
278 "Generic", "Download Buffer element",
279 "Wim Taymans <wim.taymans@gmail.com>");
281 gstelement_class->change_state =
282 GST_DEBUG_FUNCPTR (gst_download_buffer_change_state);
283 gstelement_class->query =
284 GST_DEBUG_FUNCPTR (gst_download_buffer_handle_query);
288 gst_download_buffer_init (GstDownloadBuffer * dlbuf)
290 dlbuf->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
292 gst_pad_set_chain_function (dlbuf->sinkpad,
293 GST_DEBUG_FUNCPTR (gst_download_buffer_chain));
294 gst_pad_set_activatemode_function (dlbuf->sinkpad,
295 GST_DEBUG_FUNCPTR (gst_download_buffer_sink_activate_mode));
296 gst_pad_set_event_function (dlbuf->sinkpad,
297 GST_DEBUG_FUNCPTR (gst_download_buffer_handle_sink_event));
298 gst_pad_set_query_function (dlbuf->sinkpad,
299 GST_DEBUG_FUNCPTR (gst_download_buffer_handle_sink_query));
300 GST_PAD_SET_PROXY_CAPS (dlbuf->sinkpad);
301 gst_element_add_pad (GST_ELEMENT (dlbuf), dlbuf->sinkpad);
303 dlbuf->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
305 gst_pad_set_activatemode_function (dlbuf->srcpad,
306 GST_DEBUG_FUNCPTR (gst_download_buffer_src_activate_mode));
307 gst_pad_set_getrange_function (dlbuf->srcpad,
308 GST_DEBUG_FUNCPTR (gst_download_buffer_get_range));
309 gst_pad_set_event_function (dlbuf->srcpad,
310 GST_DEBUG_FUNCPTR (gst_download_buffer_handle_src_event));
311 gst_pad_set_query_function (dlbuf->srcpad,
312 GST_DEBUG_FUNCPTR (gst_download_buffer_handle_src_query));
313 GST_PAD_SET_PROXY_CAPS (dlbuf->srcpad);
314 gst_element_add_pad (GST_ELEMENT (dlbuf), dlbuf->srcpad);
317 GST_DOWNLOAD_BUFFER_CLEAR_LEVEL (dlbuf->cur_level);
318 dlbuf->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
319 dlbuf->max_level.time = DEFAULT_MAX_SIZE_TIME;
320 dlbuf->low_percent = DEFAULT_LOW_PERCENT;
321 dlbuf->high_percent = DEFAULT_HIGH_PERCENT;
323 dlbuf->srcresult = GST_FLOW_FLUSHING;
324 dlbuf->sinkresult = GST_FLOW_FLUSHING;
325 dlbuf->in_timer = g_timer_new ();
326 dlbuf->out_timer = g_timer_new ();
328 g_mutex_init (&dlbuf->qlock);
329 dlbuf->waiting_add = FALSE;
330 g_cond_init (&dlbuf->item_add);
332 /* tempfile related */
333 dlbuf->temp_template = NULL;
334 dlbuf->temp_location = NULL;
335 dlbuf->temp_remove = DEFAULT_TEMP_REMOVE;
338 /* called only once, as opposed to dispose */
340 gst_download_buffer_finalize (GObject * object)
342 GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
344 g_mutex_clear (&dlbuf->qlock);
345 g_cond_clear (&dlbuf->item_add);
346 g_timer_destroy (dlbuf->in_timer);
347 g_timer_destroy (dlbuf->out_timer);
349 /* temp_file path cleanup */
350 g_free (dlbuf->temp_template);
351 g_free (dlbuf->temp_location);
353 G_OBJECT_CLASS (parent_class)->finalize (object);
357 reset_positions (GstDownloadBuffer * dlbuf)
359 dlbuf->write_pos = 0;
361 dlbuf->filling = TRUE;
362 dlbuf->buffering_percent = 0;
363 dlbuf->is_buffering = TRUE;
364 dlbuf->seeking = FALSE;
365 GST_DOWNLOAD_BUFFER_CLEAR_LEVEL (dlbuf->cur_level);
369 reset_rate_timer (GstDownloadBuffer * dlbuf)
372 dlbuf->bytes_out = 0;
373 dlbuf->byte_in_rate = 0.0;
374 dlbuf->byte_in_period = 0;
375 dlbuf->byte_out_rate = 0.0;
376 dlbuf->last_in_elapsed = 0.0;
377 dlbuf->last_out_elapsed = 0.0;
378 dlbuf->in_timer_started = FALSE;
379 dlbuf->out_timer_started = FALSE;
382 /* the interval in seconds to recalculate the rate */
383 #define RATE_INTERVAL 0.2
384 /* Tuning for rate estimation. We use a large window for the input rate because
385 * it should be stable when connected to a network. The output rate is less
386 * stable (the elements preroll, queues behind a demuxer fill, ...) and should
387 * therefore adapt more quickly.
388 * However, initial input rate may be subject to a burst, and should therefore
389 * initially also adapt more quickly to changes, and only later on give higher
390 * weight to previous values. */
391 #define AVG_IN(avg,val,w1,w2) ((avg) * (w1) + (val) * (w2)) / ((w1) + (w2))
392 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
395 update_levels (GstDownloadBuffer * dlbuf, guint bytes)
397 dlbuf->cur_level.bytes = bytes;
399 if (dlbuf->byte_in_rate > 0.0) {
400 dlbuf->cur_level.time =
401 dlbuf->cur_level.bytes / dlbuf->byte_in_rate * GST_SECOND;
404 GST_DEBUG ("levels: bytes %u/%u, time %" GST_TIME_FORMAT "/%" GST_TIME_FORMAT,
405 dlbuf->cur_level.bytes, dlbuf->max_level.bytes,
406 GST_TIME_ARGS (dlbuf->cur_level.time),
407 GST_TIME_ARGS (dlbuf->max_level.time));
411 update_in_rates (GstDownloadBuffer * dlbuf)
413 gdouble elapsed, period;
414 gdouble byte_in_rate;
416 if (!dlbuf->in_timer_started) {
417 dlbuf->in_timer_started = TRUE;
418 g_timer_start (dlbuf->in_timer);
422 elapsed = g_timer_elapsed (dlbuf->in_timer, NULL);
424 /* recalc after each interval. */
425 if (dlbuf->last_in_elapsed + RATE_INTERVAL < elapsed) {
426 period = elapsed - dlbuf->last_in_elapsed;
428 GST_DEBUG_OBJECT (dlbuf,
429 "rates: period %f, in %" G_GUINT64_FORMAT ", global period %f",
430 period, dlbuf->bytes_in, dlbuf->byte_in_period);
432 byte_in_rate = dlbuf->bytes_in / period;
434 if (dlbuf->byte_in_rate == 0.0)
435 dlbuf->byte_in_rate = byte_in_rate;
437 dlbuf->byte_in_rate = AVG_IN (dlbuf->byte_in_rate, byte_in_rate,
438 (double) dlbuf->byte_in_period, period);
440 /* another data point, cap at 16 for long time running average */
441 if (dlbuf->byte_in_period < 16 * RATE_INTERVAL)
442 dlbuf->byte_in_period += period;
444 /* reset the values to calculate rate over the next interval */
445 dlbuf->last_in_elapsed = elapsed;
447 GST_DEBUG_OBJECT (dlbuf, "rates: in %f", dlbuf->byte_in_rate);
452 update_out_rates (GstDownloadBuffer * dlbuf)
454 gdouble elapsed, period;
455 gdouble byte_out_rate;
457 if (!dlbuf->out_timer_started) {
458 dlbuf->out_timer_started = TRUE;
459 g_timer_start (dlbuf->out_timer);
463 elapsed = g_timer_elapsed (dlbuf->out_timer, NULL);
465 /* recalc after each interval. */
466 if (dlbuf->last_out_elapsed + RATE_INTERVAL < elapsed) {
467 period = elapsed - dlbuf->last_out_elapsed;
469 GST_DEBUG_OBJECT (dlbuf,
470 "rates: period %f, out %" G_GUINT64_FORMAT, period, dlbuf->bytes_out);
472 byte_out_rate = dlbuf->bytes_out / period;
474 if (dlbuf->byte_out_rate == 0.0)
475 dlbuf->byte_out_rate = byte_out_rate;
477 dlbuf->byte_out_rate = AVG_OUT (dlbuf->byte_out_rate, byte_out_rate);
479 /* reset the values to calculate rate over the next interval */
480 dlbuf->last_out_elapsed = elapsed;
481 dlbuf->bytes_out = 0;
482 GST_DEBUG_OBJECT (dlbuf, "rates: out %f", dlbuf->byte_out_rate);
487 get_buffering_percent (GstDownloadBuffer * dlbuf, gboolean * is_buffering,
492 if (dlbuf->high_percent <= 0) {
496 *is_buffering = FALSE;
500 /* Ensure the variables used to calculate buffering state are up-to-date. */
501 update_in_rates (dlbuf);
502 update_out_rates (dlbuf);
504 /* figure out the percent we are filled, we take the max of all formats. */
505 if (dlbuf->max_level.bytes > 0) {
506 if (dlbuf->cur_level.bytes >= dlbuf->max_level.bytes)
509 perc = dlbuf->cur_level.bytes * 100 / dlbuf->max_level.bytes;
513 if (dlbuf->max_level.time > 0) {
514 if (dlbuf->cur_level.time >= dlbuf->max_level.time)
517 perc = MAX (perc, dlbuf->cur_level.time * 100 / dlbuf->max_level.time);
519 perc = MAX (0, perc);
522 *is_buffering = dlbuf->is_buffering;
524 /* scale to high percent so that it becomes the 100% mark */
525 perc = perc * 100 / dlbuf->high_percent;
533 GST_DEBUG_OBJECT (dlbuf, "buffering %d, percent %d", dlbuf->is_buffering,
540 get_buffering_stats (GstDownloadBuffer * dlbuf, gint percent,
541 GstBufferingMode * mode, gint * avg_in, gint * avg_out,
542 gint64 * buffering_left)
545 *mode = GST_BUFFERING_DOWNLOAD;
548 *avg_in = dlbuf->byte_in_rate;
550 *avg_out = dlbuf->byte_out_rate;
552 if (buffering_left) {
555 *buffering_left = (percent == 100 ? 0 : -1);
557 max = dlbuf->max_level.time;
558 cur = dlbuf->cur_level.time;
560 if (percent != 100 && max > cur)
561 *buffering_left = (max - cur) / 1000000;
566 update_buffering (GstDownloadBuffer * dlbuf)
569 gboolean post = FALSE;
570 GstMessage *message = NULL;
572 if (!get_buffering_percent (dlbuf, NULL, &percent))
575 if (dlbuf->is_buffering) {
577 /* if we were buffering see if we reached the high watermark */
578 if (percent >= dlbuf->high_percent)
579 dlbuf->is_buffering = FALSE;
581 /* we were not buffering, check if we need to start buffering if we drop
582 * below the low threshold */
583 if (percent < dlbuf->low_percent) {
584 dlbuf->is_buffering = TRUE;
590 if (percent == dlbuf->buffering_percent)
593 dlbuf->buffering_percent = percent;
597 GstBufferingMode mode;
598 gint avg_in, avg_out;
599 gint64 buffering_left;
601 get_buffering_stats (dlbuf, percent, &mode, &avg_in, &avg_out,
604 message = gst_message_new_buffering (GST_OBJECT_CAST (dlbuf),
606 gst_message_set_buffering_stats (message, mode,
607 avg_in, avg_out, buffering_left);
614 perform_seek_to_offset (GstDownloadBuffer * dlbuf, guint64 offset)
622 /* until we receive the FLUSH_STOP from this seek, we skip data */
623 dlbuf->seeking = TRUE;
624 dlbuf->write_pos = offset;
625 dlbuf->filling = FALSE;
626 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
628 GST_DEBUG_OBJECT (dlbuf, "Seeking to %" G_GUINT64_FORMAT, offset);
631 gst_event_new_seek (1.0, GST_FORMAT_BYTES,
632 GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
633 GST_SEEK_TYPE_NONE, -1);
635 res = gst_pad_push_event (dlbuf->sinkpad, event);
636 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
641 /* get the threshold for when we decide to seek rather than wait */
643 get_seek_threshold (GstDownloadBuffer * dlbuf)
647 /* FIXME, find a good threshold based on the incoming rate. */
648 threshold = 1024 * 512;
653 /* called with DOWNLOAD_BUFFER_MUTEX */
655 gst_download_buffer_update_upstream_size (GstDownloadBuffer * dlbuf)
657 gint64 upstream_size = 0;
659 if (gst_pad_peer_query_duration (dlbuf->sinkpad, GST_FORMAT_BYTES,
661 GST_INFO_OBJECT (dlbuf, "upstream size: %" G_GINT64_FORMAT, upstream_size);
662 dlbuf->upstream_size = upstream_size;
666 /* called with DOWNLOAD_BUFFER_MUTEX */
668 gst_download_buffer_wait_for_data (GstDownloadBuffer * dlbuf, guint64 offset,
675 GST_DEBUG_OBJECT (dlbuf, "wait for %" G_GUINT64_FORMAT ", length %u",
678 wanted = offset + length;
680 /* pause the timer while we wait. The fact that we are waiting does not mean
681 * the byterate on the output pad is lower */
682 if ((started = dlbuf->out_timer_started))
683 g_timer_stop (dlbuf->out_timer);
685 /* check range before us */
686 if (gst_sparse_file_get_range_before (dlbuf->file, offset, &start, &stop)) {
687 GST_DEBUG_OBJECT (dlbuf,
688 "range before %" G_GSIZE_FORMAT " - %" G_GSIZE_FORMAT, start, stop);
689 if (start <= offset && offset < stop) {
690 GST_DEBUG_OBJECT (dlbuf, "we have the offset");
691 /* we have the range, continue it */
694 guint64 threshold, dist;
696 /* there is a range before us, check how far away it is */
697 threshold = get_seek_threshold (dlbuf);
698 dist = offset - stop;
700 if (dist <= threshold) {
701 GST_DEBUG_OBJECT (dlbuf, "not too far");
702 /* not far away, continue it */
708 if (dlbuf->write_pos != offset) {
709 perform_seek_to_offset (dlbuf, offset);
711 /* perform_seek_to_offset() releases the lock, so we may have been flushed
712 * during the call. */
713 if (dlbuf->srcresult == GST_FLOW_FLUSHING)
717 dlbuf->filling = TRUE;
718 if (dlbuf->write_pos > dlbuf->read_pos)
719 update_levels (dlbuf, dlbuf->write_pos - dlbuf->read_pos);
721 update_levels (dlbuf, 0);
723 /* now wait for more data */
724 GST_DEBUG_OBJECT (dlbuf, "waiting for more data");
725 GST_DOWNLOAD_BUFFER_WAIT_ADD_CHECK (dlbuf, dlbuf->srcresult, wanted,
727 GST_DEBUG_OBJECT (dlbuf, "got more data");
729 /* and continue if we were running before */
731 g_timer_continue (dlbuf->out_timer);
737 GST_DEBUG_OBJECT (dlbuf, "we are flushing");
738 return GST_FLOW_FLUSHING;
742 /* called with DOWNLOAD_BUFFER_MUTEX */
744 check_upstream_size (GstDownloadBuffer * dlbuf, gsize offset, guint * length)
746 gsize stop = offset + *length;
747 /* catch any reads beyond the size of the file here to make sure cache
748 * doesn't send seek events beyond the size of the file upstream, since
749 * that would confuse elements such as souphttpsrc and/or http servers.
750 * Demuxers often just loop until EOS at the end of the file to figure out
751 * when they've read all the end-headers or index chunks. */
752 if (G_UNLIKELY (dlbuf->upstream_size == -1 || stop >= dlbuf->upstream_size)) {
753 gst_download_buffer_update_upstream_size (dlbuf);
756 if (dlbuf->upstream_size != -1) {
757 if (offset >= dlbuf->upstream_size)
760 if (G_UNLIKELY (stop > dlbuf->upstream_size)) {
761 *length = dlbuf->upstream_size - offset;
762 GST_DEBUG_OBJECT (dlbuf, "adjusting length downto %u", *length);
768 /* called with DOWNLOAD_BUFFER_MUTEX */
770 gst_download_buffer_read_buffer (GstDownloadBuffer * dlbuf, guint64 offset,
771 guint length, GstBuffer ** buffer)
775 GstFlowReturn ret = GST_FLOW_OK;
776 gsize res, remaining;
777 GError *error = NULL;
779 length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
780 offset = (offset == -1) ? dlbuf->read_pos : offset;
782 if (!check_upstream_size (dlbuf, offset, &length))
785 /* allocate the output buffer of the requested size */
787 buf = gst_buffer_new_allocate (NULL, length, NULL);
791 if (!gst_buffer_map (buf, &info, GST_MAP_WRITE))
794 GST_DEBUG_OBJECT (dlbuf, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
797 dlbuf->read_pos = offset;
801 gst_sparse_file_read (dlbuf->file, offset, info.data, length,
803 if (G_UNLIKELY (res == 0)) {
804 switch (error->code) {
805 case GST_SPARSE_FILE_IO_ERROR_WOULD_BLOCK:
806 /* we don't have the requested data in the file, decide what to
808 ret = gst_download_buffer_wait_for_data (dlbuf, offset, length);
809 if (ret != GST_FLOW_OK)
815 g_clear_error (&error);
819 gst_buffer_unmap (buf, &info);
820 gst_buffer_resize (buf, 0, res);
822 dlbuf->bytes_out += res;
823 dlbuf->read_pos += res;
825 GST_DEBUG_OBJECT (dlbuf,
826 "Read %" G_GSIZE_FORMAT " bytes, remaining %" G_GSIZE_FORMAT, res,
829 if (dlbuf->read_pos + remaining == dlbuf->upstream_size)
830 update_levels (dlbuf, dlbuf->max_level.bytes);
832 update_levels (dlbuf, remaining);
834 GST_BUFFER_OFFSET (buf) = offset;
835 GST_BUFFER_OFFSET_END (buf) = offset + res;
844 GST_DEBUG_OBJECT (dlbuf, "EOS hit");
849 GST_ELEMENT_ERROR (dlbuf, RESOURCE, BUSY,
850 (_("Failed to map buffer.")), ("failed to map buffer in WRITE mode"));
852 gst_buffer_unref (buf);
853 return GST_FLOW_ERROR;
857 GST_DEBUG_OBJECT (dlbuf, "we are flushing");
858 g_clear_error (&error);
859 gst_buffer_unmap (buf, &info);
861 gst_buffer_unref (buf);
862 return GST_FLOW_FLUSHING;
866 GST_DEBUG_OBJECT (dlbuf, "we have a read error: %s", error->message);
867 g_clear_error (&error);
868 gst_buffer_unmap (buf, &info);
870 gst_buffer_unref (buf);
871 return GST_FLOW_ERROR;
875 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
876 * the temp filename. */
878 gst_download_buffer_open_temp_location_file (GstDownloadBuffer * dlbuf)
886 GST_DEBUG_OBJECT (dlbuf, "opening temp file %s", dlbuf->temp_template);
888 /* If temp_template was set, allocate a filename and open that file */
891 if (dlbuf->temp_template == NULL)
894 /* make copy of the template, we don't want to change this */
895 name = g_strdup (dlbuf->temp_template);
897 fd = g_mkstemp_full (name, O_RDWR | O_LARGEFILE, S_IRUSR | S_IWUSR);
899 fd = g_mkstemp (name);
904 /* open the file for update/writing */
905 dlbuf->file = gst_sparse_file_new ();
906 /* error creating file */
907 if (!gst_sparse_file_set_fd (dlbuf->file, fd))
910 g_free (dlbuf->temp_location);
911 dlbuf->temp_location = name;
913 reset_positions (dlbuf);
915 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
917 /* we can't emit the notify with the lock */
918 g_object_notify (G_OBJECT (dlbuf), "temp-location");
920 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
922 GST_DEBUG_OBJECT (dlbuf, "opened temp file %s", dlbuf->temp_template);
929 GST_DEBUG_OBJECT (dlbuf, "temp file was already open");
934 GST_ELEMENT_ERROR (dlbuf, RESOURCE, NOT_FOUND,
935 (_("No Temp directory specified.")), (NULL));
940 GST_ELEMENT_ERROR (dlbuf, RESOURCE, OPEN_READ,
941 (_("Could not create temp file \"%s\"."), dlbuf->temp_template),
948 GST_ELEMENT_ERROR (dlbuf, RESOURCE, OPEN_READ,
949 (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
958 gst_download_buffer_close_temp_location_file (GstDownloadBuffer * dlbuf)
961 if (dlbuf->file == NULL)
964 GST_DEBUG_OBJECT (dlbuf, "closing sparse file");
966 gst_sparse_file_free (dlbuf->file);
968 /* fd was closed by gst_sparse_file_free's fclose() */
971 if (dlbuf->temp_remove) {
972 if (remove (dlbuf->temp_location) < 0) {
973 GST_WARNING_OBJECT (dlbuf, "Failed to remove temporary file %s: %s",
974 dlbuf->temp_location, g_strerror (errno));
980 gst_download_buffer_flush_temp_file (GstDownloadBuffer * dlbuf)
982 if (dlbuf->file == NULL)
985 GST_DEBUG_OBJECT (dlbuf, "flushing temp file");
987 gst_sparse_file_clear (dlbuf->file);
991 gst_download_buffer_locked_flush (GstDownloadBuffer * dlbuf, gboolean full,
995 gst_download_buffer_flush_temp_file (dlbuf);
996 reset_positions (dlbuf);
997 gst_event_replace (&dlbuf->stream_start_event, NULL);
998 gst_event_replace (&dlbuf->segment_event, NULL);
1002 gst_download_buffer_handle_sink_event (GstPad * pad, GstObject * parent,
1005 gboolean ret = TRUE;
1006 GstDownloadBuffer *dlbuf;
1008 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1010 switch (GST_EVENT_TYPE (event)) {
1011 case GST_EVENT_FLUSH_START:
1013 GST_LOG_OBJECT (dlbuf, "received flush start event");
1014 if (GST_PAD_MODE (dlbuf->srcpad) == GST_PAD_MODE_PUSH) {
1016 ret = gst_pad_push_event (dlbuf->srcpad, event);
1018 /* now unblock the chain function */
1019 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1020 dlbuf->srcresult = GST_FLOW_FLUSHING;
1021 dlbuf->sinkresult = GST_FLOW_FLUSHING;
1022 /* unblock the loop and chain functions */
1023 GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1024 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1026 /* make sure it pauses, this should happen since we sent
1027 * flush_start downstream. */
1028 gst_pad_pause_task (dlbuf->srcpad);
1029 GST_LOG_OBJECT (dlbuf, "loop stopped");
1031 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1032 /* flush the sink pad */
1033 dlbuf->sinkresult = GST_FLOW_FLUSHING;
1034 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1036 gst_event_unref (event);
1040 case GST_EVENT_FLUSH_STOP:
1042 GST_LOG_OBJECT (dlbuf, "received flush stop event");
1044 if (GST_PAD_MODE (dlbuf->srcpad) == GST_PAD_MODE_PUSH) {
1046 ret = gst_pad_push_event (dlbuf->srcpad, event);
1048 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1049 gst_download_buffer_locked_flush (dlbuf, FALSE, TRUE);
1050 dlbuf->srcresult = GST_FLOW_OK;
1051 dlbuf->sinkresult = GST_FLOW_OK;
1052 dlbuf->unexpected = FALSE;
1053 dlbuf->seeking = FALSE;
1054 /* reset rate counters */
1055 reset_rate_timer (dlbuf);
1056 gst_pad_start_task (dlbuf->srcpad,
1057 (GstTaskFunction) gst_download_buffer_loop, dlbuf->srcpad, NULL);
1058 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1060 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1061 dlbuf->unexpected = FALSE;
1062 dlbuf->sinkresult = GST_FLOW_OK;
1063 dlbuf->seeking = FALSE;
1064 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1066 gst_event_unref (event);
1071 if (GST_EVENT_IS_SERIALIZED (event)) {
1072 GstMessage *msg = NULL;
1074 /* serialized events go in the buffer */
1075 GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->sinkresult,
1077 switch (GST_EVENT_TYPE (event)) {
1079 GST_DEBUG_OBJECT (dlbuf, "we have EOS");
1080 /* Zero the thresholds, this makes sure the dlbuf is completely
1081 * filled and we can read all data from the dlbuf. */
1082 /* update the buffering status */
1083 update_levels (dlbuf, dlbuf->max_level.bytes);
1084 /* update the buffering */
1085 msg = update_buffering (dlbuf);
1086 /* wakeup the waiter and let it recheck */
1087 GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1089 case GST_EVENT_SEGMENT:
1090 gst_event_replace (&dlbuf->segment_event, event);
1091 /* a new segment allows us to accept more buffers if we got EOS
1092 * from downstream */
1093 dlbuf->unexpected = FALSE;
1095 case GST_EVENT_STREAM_START:
1096 gst_event_replace (&dlbuf->stream_start_event, event);
1101 gst_event_unref (event);
1102 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1104 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1106 /* non-serialized events are passed upstream. */
1107 ret = gst_pad_push_event (dlbuf->srcpad, event);
1116 GST_DEBUG_OBJECT (dlbuf, "refusing event, we are flushing");
1117 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1118 gst_event_unref (event);
1124 gst_download_buffer_handle_sink_query (GstPad * pad, GstObject * parent,
1127 GstDownloadBuffer *dlbuf;
1130 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1132 switch (GST_QUERY_TYPE (query)) {
1134 if (GST_QUERY_IS_SERIALIZED (query)) {
1135 GST_DEBUG_OBJECT (dlbuf, "refusing serialized query %p", query);
1138 res = gst_pad_query_default (pad, parent, query);
1145 static GstFlowReturn
1146 gst_download_buffer_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1148 GstDownloadBuffer *dlbuf;
1151 gsize res, available;
1152 GError *error = NULL;
1153 GstMessage *msg = NULL;
1155 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1157 GST_LOG_OBJECT (dlbuf, "received buffer %p of "
1158 "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
1159 GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
1160 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1161 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1163 /* we have to lock the dlbuf since we span threads */
1164 GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->sinkresult, out_flushing);
1165 /* when we received unexpected from downstream, refuse more buffers */
1166 if (dlbuf->unexpected)
1169 /* while we didn't receive the newsegment, we're seeking and we skip data */
1173 /* put buffer in dlbuf now */
1174 offset = dlbuf->write_pos;
1177 if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1178 GST_BUFFER_OFFSET (buffer) != offset) {
1179 GST_WARNING_OBJECT (dlbuf, "buffer offset does not match current writing "
1180 "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1181 GST_BUFFER_OFFSET (buffer), offset);
1184 if (!gst_buffer_map (buffer, &info, GST_MAP_READ))
1187 GST_DEBUG_OBJECT (dlbuf, "Writing %" G_GSIZE_FORMAT " bytes to %"
1188 G_GUINT64_FORMAT, info.size, offset);
1191 gst_sparse_file_write (dlbuf->file, offset, info.data, info.size,
1192 &available, &error);
1196 gst_buffer_unmap (buffer, &info);
1197 gst_buffer_unref (buffer);
1199 dlbuf->write_pos = offset + info.size;
1200 dlbuf->bytes_in += info.size;
1202 GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, dlbuf->write_pos + available);
1204 /* we hit the end, see what to do */
1205 if (dlbuf->write_pos + available == dlbuf->upstream_size) {
1208 /* we have everything up to the end, find a region to fill */
1209 if (gst_sparse_file_get_range_after (dlbuf->file, 0, &start, &stop)) {
1210 if (stop < dlbuf->upstream_size) {
1211 /* a hole to fill, seek to its end */
1212 perform_seek_to_offset (dlbuf, stop);
1214 /* we filled all the holes, we are done */
1219 /* see if we need to skip this region or just read it again. The idea
1220 * is that when the region is not big, we want to avoid a seek and just
1222 guint64 threshold = get_seek_threshold (dlbuf);
1224 if (available > threshold) {
1225 /* further than threshold, it's better to skip than to reread */
1226 perform_seek_to_offset (dlbuf, dlbuf->write_pos + available);
1229 if (dlbuf->filling) {
1230 if (dlbuf->write_pos > dlbuf->read_pos)
1231 update_levels (dlbuf, dlbuf->write_pos - dlbuf->read_pos);
1233 update_levels (dlbuf, 0);
1236 /* update the buffering */
1237 msg = update_buffering (dlbuf);
1239 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1242 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1249 GstFlowReturn ret = dlbuf->sinkresult;
1250 GST_LOG_OBJECT (dlbuf,
1251 "exit because task paused, reason: %s", gst_flow_get_name (ret));
1252 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1253 gst_buffer_unref (buffer);
1258 GST_LOG_OBJECT (dlbuf, "exit because we received EOS");
1259 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1260 gst_buffer_unref (buffer);
1261 return GST_FLOW_EOS;
1265 GST_LOG_OBJECT (dlbuf, "exit because we are seeking");
1266 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1267 gst_buffer_unref (buffer);
1272 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1273 gst_buffer_unref (buffer);
1274 GST_ELEMENT_ERROR (dlbuf, RESOURCE, BUSY,
1275 (_("Failed to map buffer.")), ("failed to map buffer in READ mode"));
1276 return GST_FLOW_ERROR;
1280 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1281 gst_buffer_unmap (buffer, &info);
1282 gst_buffer_unref (buffer);
1283 GST_ELEMENT_ERROR (dlbuf, RESOURCE, WRITE,
1284 (_("Error while writing to download file.")), ("%s", error->message));
1285 g_clear_error (&error);
1286 return GST_FLOW_ERROR;
1290 GstMessage *complete_message;
1292 GST_LOG_OBJECT (dlbuf, "we completed the download");
1293 dlbuf->write_pos = dlbuf->upstream_size;
1294 dlbuf->filling = FALSE;
1295 update_levels (dlbuf, dlbuf->max_level.bytes);
1296 msg = update_buffering (dlbuf);
1297 complete_message = gst_message_new_element (GST_OBJECT_CAST (dlbuf),
1298 gst_structure_new ("GstCacheDownloadComplete",
1299 "location", G_TYPE_STRING, dlbuf->temp_location, NULL));
1300 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1302 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), complete_message);
1304 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1306 return GST_FLOW_EOS;
1310 /* called repeatedly with @pad as the source pad. This function should push out
1311 * data to the peer element. */
1313 gst_download_buffer_loop (GstPad * pad)
1315 GstDownloadBuffer *dlbuf;
1317 GstBuffer *buffer = NULL;
1318 GstMessage *msg = NULL;
1320 dlbuf = GST_DOWNLOAD_BUFFER (GST_PAD_PARENT (pad));
1322 /* have to lock for thread-safety */
1323 GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1325 ret = gst_download_buffer_read_buffer (dlbuf, -1, -1, &buffer);
1326 if (ret != GST_FLOW_OK)
1329 if (dlbuf->stream_start_event != NULL) {
1330 gst_pad_push_event (dlbuf->srcpad, dlbuf->stream_start_event);
1331 dlbuf->stream_start_event = NULL;
1333 if (dlbuf->segment_event != NULL) {
1334 gst_pad_push_event (dlbuf->srcpad, dlbuf->segment_event);
1335 dlbuf->segment_event = NULL;
1339 /* update the buffering */
1340 msg = update_buffering (dlbuf);
1342 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1345 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1347 ret = gst_pad_push (dlbuf->srcpad, buffer);
1349 /* need to check for srcresult here as well */
1350 GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1351 dlbuf->srcresult = ret;
1352 dlbuf->sinkresult = ret;
1353 if (ret != GST_FLOW_OK)
1355 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1362 GstFlowReturn ret = dlbuf->srcresult;
1364 gst_pad_pause_task (dlbuf->srcpad);
1365 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1366 GST_LOG_OBJECT (dlbuf, "pause task, reason: %s", gst_flow_get_name (ret));
1367 /* let app know about us giving up if upstream is not expected to do so */
1368 if (ret == GST_FLOW_EOS) {
1369 /* FIXME perform EOS logic, this is really a basesrc operating on a
1371 gst_pad_push_event (dlbuf->srcpad, gst_event_new_eos ());
1372 } else if ((ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1373 GST_ELEMENT_FLOW_ERROR (dlbuf, ret);
1374 gst_pad_push_event (dlbuf->srcpad, gst_event_new_eos ());
1381 gst_download_buffer_handle_src_event (GstPad * pad, GstObject * parent,
1384 gboolean res = TRUE;
1385 GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (parent);
1387 #ifndef GST_DISABLE_GST_DEBUG
1388 GST_DEBUG_OBJECT (dlbuf, "got event %p (%s)",
1389 event, GST_EVENT_TYPE_NAME (event));
1392 switch (GST_EVENT_TYPE (event)) {
1393 case GST_EVENT_FLUSH_START:
1394 /* now unblock the getrange function */
1395 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1396 GST_DEBUG_OBJECT (dlbuf, "flushing");
1397 dlbuf->srcresult = GST_FLOW_FLUSHING;
1398 GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1399 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1401 /* when using a temp file, we eat the event */
1403 gst_event_unref (event);
1405 case GST_EVENT_FLUSH_STOP:
1406 /* now unblock the getrange function */
1407 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1408 dlbuf->srcresult = GST_FLOW_OK;
1409 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1411 /* when using a temp file, we eat the event */
1413 gst_event_unref (event);
1415 case GST_EVENT_RECONFIGURE:
1416 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1417 /* assume downstream is linked now and try to push again */
1418 if (dlbuf->srcresult == GST_FLOW_NOT_LINKED) {
1419 dlbuf->srcresult = GST_FLOW_OK;
1420 dlbuf->sinkresult = GST_FLOW_OK;
1421 if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
1422 gst_pad_start_task (pad, (GstTaskFunction) gst_download_buffer_loop,
1426 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1428 res = gst_pad_push_event (dlbuf->sinkpad, event);
1431 res = gst_pad_push_event (dlbuf->sinkpad, event);
1439 gst_download_buffer_handle_src_query (GstPad * pad, GstObject * parent,
1442 GstDownloadBuffer *dlbuf;
1444 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1446 switch (GST_QUERY_TYPE (query)) {
1447 case GST_QUERY_POSITION:
1452 if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1455 /* get peer position */
1456 gst_query_parse_position (query, &format, &peer_pos);
1458 /* FIXME: this code assumes that there's no discont in the dlbuf */
1460 case GST_FORMAT_BYTES:
1461 peer_pos -= dlbuf->cur_level.bytes;
1462 if (peer_pos < 0) /* Clamp result to 0 */
1465 case GST_FORMAT_TIME:
1466 peer_pos -= dlbuf->cur_level.time;
1467 if (peer_pos < 0) /* Clamp result to 0 */
1471 GST_WARNING_OBJECT (dlbuf, "dropping query in %s format, don't "
1472 "know how to adjust value", gst_format_get_name (format));
1475 /* set updated position */
1476 gst_query_set_position (query, format, peer_pos);
1479 case GST_QUERY_DURATION:
1481 GST_DEBUG_OBJECT (dlbuf, "doing peer query");
1483 if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1486 GST_DEBUG_OBJECT (dlbuf, "peer query success");
1489 case GST_QUERY_BUFFERING:
1492 gboolean is_buffering;
1493 GstBufferingMode mode;
1494 gint avg_in, avg_out;
1495 gint64 buffering_left;
1497 GST_DEBUG_OBJECT (dlbuf, "query buffering");
1499 get_buffering_percent (dlbuf, &is_buffering, &percent);
1500 gst_query_set_buffering_percent (query, is_buffering, percent);
1502 get_buffering_stats (dlbuf, percent, &mode, &avg_in, &avg_out,
1504 gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
1508 /* add ranges for download and ringbuffer buffering */
1512 gint64 estimated_total;
1514 gsize offset, range_start, range_stop;
1516 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1517 write_pos = dlbuf->write_pos;
1519 /* get duration of upstream in bytes */
1520 gst_download_buffer_update_upstream_size (dlbuf);
1521 duration = dlbuf->upstream_size;
1523 GST_DEBUG_OBJECT (dlbuf, "percent %d, duration %" G_GINT64_FORMAT
1524 ", writing %" G_GINT64_FORMAT, percent, duration, write_pos);
1526 gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
1528 /* fill out the buffered ranges */
1531 estimated_total = -1;
1532 while (gst_sparse_file_get_range_after (dlbuf->file, offset,
1533 &range_start, &range_stop)) {
1534 gboolean current_range;
1536 GST_DEBUG_OBJECT (dlbuf,
1537 "range starting at %" G_GSIZE_FORMAT " and finishing at %"
1538 G_GSIZE_FORMAT, range_start, range_stop);
1540 offset = range_stop;
1542 /* find the range we are currently downloading, we'll remember it
1543 * after we convert to the target format */
1544 if (range_start <= write_pos && range_stop >= write_pos) {
1545 current_range = TRUE;
1546 /* calculate remaining and total download time */
1547 if (duration >= range_stop && avg_in > 0.0)
1548 estimated_total = ((duration - range_stop) * 1000) / avg_in;
1550 current_range = FALSE;
1553 case GST_FORMAT_PERCENT:
1554 /* get our available data relative to the duration */
1555 if (duration == -1) {
1559 range_start = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
1560 range_start, duration);
1561 range_stop = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
1562 range_stop, duration);
1565 case GST_FORMAT_BYTES:
1573 if (current_range) {
1574 /* we are currently downloading this range */
1575 start = range_start;
1578 GST_DEBUG_OBJECT (dlbuf,
1579 "range to format: %" G_GSIZE_FORMAT " - %" G_GSIZE_FORMAT,
1580 range_start, range_stop);
1581 if (range_start == range_stop)
1583 gst_query_add_buffering_range (query, range_start, range_stop);
1586 GST_DEBUG_OBJECT (dlbuf, "estimated-total %" G_GINT64_FORMAT,
1589 gst_query_set_buffering_range (query, format, start, stop,
1592 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1596 case GST_QUERY_SCHEDULING:
1598 GstSchedulingFlags flags = 0;
1600 if (!gst_pad_peer_query (dlbuf->sinkpad, query))
1603 gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
1605 /* we can operate in pull mode when we are using a tempfile */
1606 flags |= GST_SCHEDULING_FLAG_SEEKABLE;
1607 gst_query_set_scheduling (query, flags, 0, -1, 0);
1608 gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
1609 gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
1613 /* peer handled other queries */
1614 if (!gst_pad_query_default (pad, parent, query))
1624 GST_DEBUG_OBJECT (dlbuf, "failed peer query");
1630 gst_download_buffer_handle_query (GstElement * element, GstQuery * query)
1632 GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (element);
1634 /* simply forward to the srcpad query function */
1635 return gst_download_buffer_handle_src_query (dlbuf->srcpad,
1636 GST_OBJECT_CAST (element), query);
1639 static GstFlowReturn
1640 gst_download_buffer_get_range (GstPad * pad, GstObject * parent, guint64 offset,
1641 guint length, GstBuffer ** buffer)
1643 GstDownloadBuffer *dlbuf;
1645 GstMessage *msg = NULL;
1647 dlbuf = GST_DOWNLOAD_BUFFER_CAST (parent);
1649 GST_DOWNLOAD_BUFFER_MUTEX_LOCK_CHECK (dlbuf, dlbuf->srcresult, out_flushing);
1650 /* FIXME - function will block when the range is not yet available */
1651 ret = gst_download_buffer_read_buffer (dlbuf, offset, length, buffer);
1652 /* update the buffering */
1653 msg = update_buffering (dlbuf);
1655 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1658 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1665 ret = dlbuf->srcresult;
1667 GST_DEBUG_OBJECT (dlbuf, "we are flushing");
1668 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1673 /* sink currently only operates in push mode */
1675 gst_download_buffer_sink_activate_mode (GstPad * pad, GstObject * parent,
1676 GstPadMode mode, gboolean active)
1679 GstDownloadBuffer *dlbuf;
1681 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1684 case GST_PAD_MODE_PUSH:
1686 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1687 GST_DEBUG_OBJECT (dlbuf, "activating push mode");
1688 dlbuf->srcresult = GST_FLOW_OK;
1689 dlbuf->sinkresult = GST_FLOW_OK;
1690 dlbuf->unexpected = FALSE;
1691 reset_rate_timer (dlbuf);
1692 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1694 /* unblock chain function */
1695 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1696 GST_DEBUG_OBJECT (dlbuf, "deactivating push mode");
1697 dlbuf->srcresult = GST_FLOW_FLUSHING;
1698 dlbuf->sinkresult = GST_FLOW_FLUSHING;
1699 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1701 /* wait until it is unblocked and clean up */
1702 GST_PAD_STREAM_LOCK (pad);
1703 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1704 gst_download_buffer_locked_flush (dlbuf, TRUE, FALSE);
1705 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1706 GST_PAD_STREAM_UNLOCK (pad);
1717 /* src operating in push mode, we start a task on the source pad that pushes out
1718 * buffers from the dlbuf */
1720 gst_download_buffer_src_activate_push (GstPad * pad, GstObject * parent,
1723 gboolean result = FALSE;
1724 GstDownloadBuffer *dlbuf;
1726 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1729 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1730 GST_DEBUG_OBJECT (dlbuf, "activating push mode");
1731 dlbuf->srcresult = GST_FLOW_OK;
1732 dlbuf->sinkresult = GST_FLOW_OK;
1733 dlbuf->unexpected = FALSE;
1735 gst_pad_start_task (pad, (GstTaskFunction) gst_download_buffer_loop,
1737 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1739 /* unblock loop function */
1740 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1741 GST_DEBUG_OBJECT (dlbuf, "deactivating push mode");
1742 dlbuf->srcresult = GST_FLOW_FLUSHING;
1743 dlbuf->sinkresult = GST_FLOW_FLUSHING;
1744 /* the item add signal will unblock */
1745 GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1746 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1748 /* step 2, make sure streaming finishes */
1749 result = gst_pad_stop_task (pad);
1755 /* pull mode, downstream will call our getrange function */
1757 gst_download_buffer_src_activate_pull (GstPad * pad, GstObject * parent,
1761 GstDownloadBuffer *dlbuf;
1763 dlbuf = GST_DOWNLOAD_BUFFER (parent);
1766 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1767 /* open the temp file now */
1768 result = gst_download_buffer_open_temp_location_file (dlbuf);
1769 GST_DEBUG_OBJECT (dlbuf, "activating pull mode");
1770 dlbuf->srcresult = GST_FLOW_OK;
1771 dlbuf->sinkresult = GST_FLOW_OK;
1772 dlbuf->unexpected = FALSE;
1773 dlbuf->upstream_size = 0;
1774 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1776 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1777 GST_DEBUG_OBJECT (dlbuf, "deactivating pull mode");
1778 dlbuf->srcresult = GST_FLOW_FLUSHING;
1779 dlbuf->sinkresult = GST_FLOW_FLUSHING;
1780 /* this will unlock getrange */
1781 GST_DOWNLOAD_BUFFER_SIGNAL_ADD (dlbuf, -1);
1783 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1790 gst_download_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1791 GstPadMode mode, gboolean active)
1796 case GST_PAD_MODE_PULL:
1797 res = gst_download_buffer_src_activate_pull (pad, parent, active);
1799 case GST_PAD_MODE_PUSH:
1800 res = gst_download_buffer_src_activate_push (pad, parent, active);
1803 GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
1810 static GstStateChangeReturn
1811 gst_download_buffer_change_state (GstElement * element,
1812 GstStateChange transition)
1814 GstDownloadBuffer *dlbuf;
1815 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1817 dlbuf = GST_DOWNLOAD_BUFFER (element);
1819 switch (transition) {
1820 case GST_STATE_CHANGE_NULL_TO_READY:
1822 case GST_STATE_CHANGE_READY_TO_PAUSED:
1823 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1824 if (!gst_download_buffer_open_temp_location_file (dlbuf))
1825 ret = GST_STATE_CHANGE_FAILURE;
1826 gst_event_replace (&dlbuf->stream_start_event, NULL);
1827 gst_event_replace (&dlbuf->segment_event, NULL);
1828 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1830 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1836 if (ret == GST_STATE_CHANGE_FAILURE)
1839 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1841 if (ret == GST_STATE_CHANGE_FAILURE)
1844 switch (transition) {
1845 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1847 case GST_STATE_CHANGE_PAUSED_TO_READY:
1848 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1849 gst_download_buffer_close_temp_location_file (dlbuf);
1850 gst_event_replace (&dlbuf->stream_start_event, NULL);
1851 gst_event_replace (&dlbuf->segment_event, NULL);
1852 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1854 case GST_STATE_CHANGE_READY_TO_NULL:
1863 #define CAPACITY_CHANGE(elem) \
1864 update_buffering (elem);
1867 gst_download_buffer_set_temp_template (GstDownloadBuffer * dlbuf,
1868 const gchar * template)
1872 /* the element must be stopped in order to do this */
1873 GST_OBJECT_LOCK (dlbuf);
1874 state = GST_STATE (dlbuf);
1875 if (state != GST_STATE_READY && state != GST_STATE_NULL)
1877 GST_OBJECT_UNLOCK (dlbuf);
1879 /* set new location */
1880 g_free (dlbuf->temp_template);
1881 dlbuf->temp_template = g_strdup (template);
1888 GST_WARNING_OBJECT (dlbuf, "setting temp-template property in wrong state");
1889 GST_OBJECT_UNLOCK (dlbuf);
1894 gst_download_buffer_set_property (GObject * object,
1895 guint prop_id, const GValue * value, GParamSpec * pspec)
1897 GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
1898 GstMessage *msg = NULL;
1900 /* someone could change levels here, and since this
1901 * affects the get/put funcs, we need to lock for safety. */
1902 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1905 case PROP_MAX_SIZE_BYTES:
1906 dlbuf->max_level.bytes = g_value_get_uint (value);
1907 msg = CAPACITY_CHANGE (dlbuf);
1909 case PROP_MAX_SIZE_TIME:
1910 dlbuf->max_level.time = g_value_get_uint64 (value);
1911 msg = CAPACITY_CHANGE (dlbuf);
1913 case PROP_LOW_PERCENT:
1914 dlbuf->low_percent = g_value_get_int (value);
1916 case PROP_HIGH_PERCENT:
1917 dlbuf->high_percent = g_value_get_int (value);
1919 case PROP_TEMP_TEMPLATE:
1920 gst_download_buffer_set_temp_template (dlbuf, g_value_get_string (value));
1922 case PROP_TEMP_REMOVE:
1923 dlbuf->temp_remove = g_value_get_boolean (value);
1926 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1930 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);
1933 gst_element_post_message (GST_ELEMENT_CAST (dlbuf), msg);
1938 gst_download_buffer_get_property (GObject * object,
1939 guint prop_id, GValue * value, GParamSpec * pspec)
1941 GstDownloadBuffer *dlbuf = GST_DOWNLOAD_BUFFER (object);
1943 GST_DOWNLOAD_BUFFER_MUTEX_LOCK (dlbuf);
1946 case PROP_MAX_SIZE_BYTES:
1947 g_value_set_uint (value, dlbuf->max_level.bytes);
1949 case PROP_MAX_SIZE_TIME:
1950 g_value_set_uint64 (value, dlbuf->max_level.time);
1952 case PROP_LOW_PERCENT:
1953 g_value_set_int (value, dlbuf->low_percent);
1955 case PROP_HIGH_PERCENT:
1956 g_value_set_int (value, dlbuf->high_percent);
1958 case PROP_TEMP_TEMPLATE:
1959 g_value_set_string (value, dlbuf->temp_template);
1961 case PROP_TEMP_LOCATION:
1962 g_value_set_string (value, dlbuf->temp_location);
1964 case PROP_TEMP_REMOVE:
1965 g_value_set_boolean (value, dlbuf->temp_remove);
1968 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1972 GST_DOWNLOAD_BUFFER_MUTEX_UNLOCK (dlbuf);