Dr.Knowitall
Dr.Knowitall

Reputation: 10508

HTML5 Video Buffer Capping Out

I have the following function:

var progress = function(n, v0, derivativeSum) {
    var v1 = stimulus.prop("buffered").end(0);

    if(v0 == null) {
        setTimeout(function() {progress(++n, v1, 0)}, 50);
        return;
    }

    console.log("buffered: " + v1);
    console.log("buff.length " + stimulus.prop("buffered").length);
    derivativeSum += v1 - v0;

    // In seconds
    averageRate = derivativeSum / (n * .05);

    // In seconds
    timeleftToDownload = (duration - v1) / averageRate;

    console.log(timeleftToDownload + " < " + v1);
    console.log("average rate: " + averageRate);

    if (timeleftToDownload < v1 / 20) {
        showPlayButton();
        return;
    }

    // Callback 50 millisecond delay
    setTimeout(function() {progress(++n, v1, derivativeSum)}, 50);
};

This is just test code, so the logic doesn't need to make sense. However I'm trying to just get how many seconds of the video has loaded, since I can compare that to the duration of the video which I'm getting in loadmetadata.

    // Should be the length of the video buffered, example: 2304 seconds
    var v1 = stimulus.prop("buffered").end(0);

However v1 seems to cap out at 128. Since I have a very long video, it should obviously be much longer. What is .end(0) even returning?

Upvotes: 0

Views: 161

Answers (1)

user1693593
user1693593

Reputation:

The buffered object can hold several segments so you need to loop over the start and end properties of each of the segments. There is neither any guarantee that a single segment will represent the entire length.

The latter is more likely with long videos as the browser will try to avoid filling up the client disk, but instead buffer smaller segments as it sees fit, delete old (from disk) and so on.

In any case, to parse the buffered segments you can do -

For example:

var buffered = video.buffered,
    segments = buffered.length,
    totalTime = 0,
    i;

for(i = 0; i < segments; i++) {
    var startTime = buffered.start(i);  // absolute start time for this segment
    var endTime = buffered.end(i);      // absolute end time for this segment
    var diff = endTime - startTime;
    totalTime += diff;
}

Now you can compare the total sum with duration to see if the video has loaded completely, or if only one segment is available see if start(0) equals 0 and end(0) equals duration (unlikely with very long videos), or use the segments to graphically indicate what parts has loaded.

Upvotes: 1

Related Questions