f2be83ef by David LaPalomento

Simple buffer management algorithm

On loadedmetadata and timeupdate, check the length of content from the current playhead position to the end of the buffer. If the amount of time buffered is less than a goal size of 5 seconds, download another segment of the video. For this algorithm to work, it requires an update to the video.js swf to expose the bufferLength property on the netstream directly. Added a fix so that once all segments are downloaded, the plugin does not attempt to continue downloading segments.
1 parent 52799413
......@@ -10,109 +10,141 @@
videojs.hls = {};
var init = function(options) {
var
mediaSource = new videojs.MediaSource(),
segmentParser = new videojs.hls.SegmentParser(),
player = this,
url,
fillBuffer,
selectPlaylist;
if (typeof options === 'string') {
url = options;
} else {
url = options.url;
}
// expose the HLS plugin state
player.hls.readyState = function() {
if (!player.hls.manifest) {
return 0; // HAVE_NOTHING
var
// the desired length of video to maintain in the buffer, in seconds
goalBufferLength = 5,
/**
* Initializes the HLS plugin.
* @param options {mixed} the URL to an HLS playlist
*/
init = function(options) {
var
mediaSource = new videojs.MediaSource(),
segmentParser = new videojs.hls.SegmentParser(),
player = this,
url,
fillBuffer,
selectPlaylist;
if (typeof options === 'string') {
url = options;
} else {
url = options.url;
}
return 1; // HAVE_METADATA
};
// load the MediaSource into the player
mediaSource.addEventListener('sourceopen', function() {
// construct the video data buffer and set the appropriate MIME type
var sourceBuffer = mediaSource.addSourceBuffer('video/flv; codecs="vp6,aac"');
player.hls.sourceBuffer = sourceBuffer;
sourceBuffer.appendBuffer(segmentParser.getFlvHeader());
// Chooses the appropriate media playlist based on the current bandwidth
// estimate and the player size
selectPlaylist = function() {
player.hls.currentPlaylist = player.hls.manifest;
player.hls.currentMediaIndex = 0;
// expose the HLS plugin state
player.hls.readyState = function() {
if (!player.hls.manifest) {
return 0; // HAVE_NOTHING
}
return 1; // HAVE_METADATA
};
// download a new segment if one is needed
fillBuffer = function() {
var
xhr = new window.XMLHttpRequest(),
segment = player.hls.currentPlaylist.segments[player.hls.currentMediaIndex],
segmentUri = segment.uri,
startTime;
if (!(/^([A-z]*:)?\/\//).test(segmentUri)) {
// the segment URI is relative to the manifest
segmentUri = url.split('/').slice(0, -1).concat(segmentUri).join('/');
}
xhr.open('GET', segmentUri);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
var elapsed;
if (xhr.readyState === 4) {
// calculate the download bandwidth
elapsed = ((+new Date()) - startTime) * 1000;
player.hls.bandwidth = xhr.response.byteLength / elapsed;
// transmux the segment data from M2TS to FLV
segmentParser.parseSegmentBinaryData(new Uint8Array(xhr.response));
while (segmentParser.tagsAvailable()) {
player.hls.sourceBuffer.appendBuffer(segmentParser.getNextTag().bytes,
player);
}
// load the MediaSource into the player
mediaSource.addEventListener('sourceopen', function() {
// construct the video data buffer and set the appropriate MIME type
var sourceBuffer = mediaSource.addSourceBuffer('video/flv; codecs="vp6,aac"');
player.hls.sourceBuffer = sourceBuffer;
sourceBuffer.appendBuffer(segmentParser.getFlvHeader());
// Chooses the appropriate media playlist based on the current bandwidth
// estimate and the player size
selectPlaylist = function() {
player.hls.currentPlaylist = player.hls.manifest;
player.hls.currentMediaIndex = 0;
};
// update the segment index
player.hls.currentMediaIndex++;
/**
* Determines whether there is enough video data currently in the buffer
* and downloads a new segment if the buffered time is less than the goal.
*/
fillBuffer = function() {
var
buffered = player.buffered(),
bufferedTime = 0,
xhr = new window.XMLHttpRequest(),
segment = player.hls.currentPlaylist.segments[player.hls.currentMediaIndex],
segmentUri,
startTime;
// if the video has finished downloading, stop trying to buffer
if (!segment) {
return;
}
};
startTime = +new Date();
xhr.send(null);
};
player.on('loadedmetadata', fillBuffer);
// download and process the manifest
(function() {
var xhr = new window.XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
var parser;
if (xhr.readyState === 4) {
// readystate DONE
parser = new videojs.m3u8.Parser();
parser.push(xhr.responseText);
player.hls.manifest = parser.manifest;
player.trigger('loadedmanifest');
if (parser.manifest.segments) {
selectPlaylist();
player.trigger('loadedmetadata');
}
if (buffered) {
// assuming a single, contiguous buffer region
bufferedTime = player.buffered().end(0) - player.currentTime();
}
// if there is plenty of content in the buffer, relax for awhile
console.log('bufferedTime:', bufferedTime);
if (bufferedTime >= goalBufferLength) {
return;
}
segmentUri = segment.uri;
if (!(/^([A-z]*:)?\/\//).test(segmentUri)) {
// the segment URI is relative to the manifest
segmentUri = url.split('/').slice(0, -1).concat(segmentUri).join('/');
}
// request the next segment
xhr.open('GET', segmentUri);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
// calculate the download bandwidth
player.hls.segmentRequestTime = (+new Date()) - startTime;
player.hls.bandwidth = xhr.response.byteLength / player.hls.segmentRequestTime;
// transmux the segment data from M2TS to FLV
segmentParser.parseSegmentBinaryData(new Uint8Array(xhr.response));
while (segmentParser.tagsAvailable()) {
player.hls.sourceBuffer.appendBuffer(segmentParser.getNextTag().bytes,
player);
}
player.hls.currentMediaIndex++;
}
};
startTime = +new Date();
xhr.send(null);
};
xhr.send(null);
})();
});
player.src({
src: videojs.URL.createObjectURL(mediaSource),
type: "video/flv"
});
};
player.on('loadedmetadata', fillBuffer);
player.on('timeupdate', fillBuffer);
// download and process the manifest
(function() {
var xhr = new window.XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
var parser;
if (xhr.readyState === 4) {
// readystate DONE
parser = new videojs.m3u8.Parser();
parser.push(xhr.responseText);
player.hls.manifest = parser.manifest;
player.trigger('loadedmanifest');
if (parser.manifest.segments) {
selectPlaylist();
player.trigger('loadedmetadata');
}
}
};
xhr.send(null);
})();
});
player.src({
src: videojs.URL.createObjectURL(mediaSource),
type: "video/flv"
});
};
videojs.plugin('hls', function() {
var initialize = function() {
......
......@@ -20,13 +20,27 @@
throws(block, [expected], [message])
*/
var player, oldXhr, oldSourceBuffer, xhrParams;
var player, oldFlashSupported, oldXhr, oldSourceBuffer, xhrParams;
module('HLS', {
setup: function() {
var video = document.createElement('video');
document.querySelector('#qunit-fixture').appendChild(video);
player = videojs(video);
player = videojs(video, {
flash: {
swf: '../node_modules/video.js/dist/video-js/video-js.swf',
},
techOrder: ['flash']
});
// force Flash support in phantomjs
oldFlashSupported = videojs.Flash.isSupported;
videojs.Flash.isSupported = function() {
return true;
};
player.buffered = function() {
return videojs.createTimeRange(0, 0);
};
// make XHR synchronous
oldXhr = window.XMLHttpRequest;
......@@ -56,6 +70,7 @@ module('HLS', {
};
},
teardown: function() {
videojs.Flash.isSupported = oldFlashSupported;
window.XMLHttpRequest = oldXhr;
window.videojs.SourceBuffer = oldSourceBuffer;
}
......@@ -87,6 +102,9 @@ test('loads the specified manifest URL on init', function() {
test('starts downloading a segment on loadedmetadata', function() {
player.hls('manifest/media.m3u8');
player.buffered = function() {
return videojs.createTimeRange(0, 0);
};
videojs.mediaSources[player.currentSrc()].trigger({
type: 'sourceopen'
});
......@@ -96,6 +114,9 @@ test('starts downloading a segment on loadedmetadata', function() {
test('recognizes absolute URIs and requests them unmodified', function() {
player.hls('manifest/absoluteUris.m3u8');
player.buffered = function() {
return videojs.createTimeRange(0, 0);
};
videojs.mediaSources[player.currentSrc()].trigger({
type: 'sourceopen'
});
......@@ -113,7 +134,6 @@ test('re-initializes the plugin for each source', function() {
secondInit = player.hls;
notStrictEqual(firstInit, secondInit, 'the plugin object is replaced');
});
test('calculates the bandwidth after downloading a segment', function() {
......@@ -125,6 +145,55 @@ test('calculates the bandwidth after downloading a segment', function() {
ok(player.hls.bandwidth, 'bandwidth is calculated');
ok(player.hls.bandwidth > 0,
'bandwidth is positive: ' + player.hls.bandwidth);
ok(player.hls.segmentRequestTime >= 0,
'saves segment request time: ' + player.hls.segmentRequestTime + 's');
});
test('does not download the next segment if the buffer is full', function() {
player.hls('manifest/media.m3u8');
player.currentTime = function() {
return 15;
};
player.buffered = function() {
return videojs.createTimeRange(0, 20);
};
videojs.mediaSources[player.currentSrc()].trigger({
type: 'sourceopen'
});
xhrParams = null;
player.trigger('timeupdate');
strictEqual(xhrParams, null, 'no segment request was made');
});
test('downloads the next segment if the buffer is getting low', function() {
player.hls('manifest/media.m3u8');
videojs.mediaSources[player.currentSrc()].trigger({
type: 'sourceopen'
});
player.currentTime = function() {
return 15;
};
player.buffered = function() {
return videojs.createTimeRange(0, 19.999);
};
xhrParams = null;
player.trigger('timeupdate');
ok(xhrParams, 'made a request');
strictEqual(xhrParams[1], 'manifest/00002.ts', 'made segment request');
});
test('stops downloading segments at the end of the playlist', function() {
player.hls('manifest/media.m3u8');
videojs.mediaSources[player.currentSrc()].trigger({
type: 'sourceopen'
});
xhrParams = null;
player.hls.currentMediaIndex = 4;
player.trigger('timeupdate');
strictEqual(xhrParams, null, 'no request is made');
});
module('segment controller', {
......