forked from PearInc/PearPlayer.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
range-loader.js
58 lines (37 loc) · 1.15 KB
/
range-loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Created by xieting on 2018/4/2.
*/
var debug = require('debug')('pear:reporter');
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
module.exports = RangeLoader;
inherits(RangeLoader, EventEmitter);
function RangeLoader(config) {
EventEmitter.call(this);
this.initialDownloaders = config.initialDownloaders;
this.downloaders = [];
this.callback = {};
var self = this;
this.downloaders = this.initialDownloaders.map(function (item){
self._setupHttp(item);
return item;
});
}
RangeLoader.prototype.select = function (start, end, cb) {
var loader = this.downloaders.shift();
loader.select(start, end);
this.downloaders.push(loader);
this.callback[start+'-'+end] = cb;
};
RangeLoader.prototype._setupHttp = function (hd) {
var self = this;
hd.once('error', function (error) {
self.emit('error');
});
hd.on('data',function (buffer, start, end, speed) {
debug('httpDownloader' + hd.uri +' ondata range:'+start+'-'+end);
var cb = self.callback[start+'-'+end];
if (cb) cb(buffer);
});
return hd;
};