-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
media-source-loader.js
110 lines (96 loc) · 3.08 KB
/
media-source-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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
function MediaSourceLoader(url, prefix)
{
this._url = url;
this._prefix = prefix;
this._manifestTimeout = setTimeout(this.loadManifest.bind(this));
this.onload = null;
this.onerror = null;
}
MediaSourceLoader.prototype = {
load: async function()
{
if (this._manifestTimeout) {
clearTimeout(this._manifestTimeout);
this._manifestTimeout = null;
}
return this.loadManifest();
},
loadManifest: async function()
{
try {
let fetchResult = await fetch(this._url);
let manifest = await fetchResult.json();
if (manifest && manifest.url) {
this._manifest = manifest;
return this.loadMediaData();
}
} catch(e) {
}
if (this.onerror)
this.onerror();
return Promise.reject("Failed loading manifest");
},
loadMediaData: async function()
{
try {
let url = (this._prefix ? this._prefix : '') + this._manifest.url;
let fetchResult = await fetch(url);
let arrayBuffer = await fetchResult.arrayBuffer();
this._mediaData = arrayBuffer;
if (this.onload)
this.onload();
return;
} catch(e) {
}
if(this.onerror)
this.onerror();
return Promise.reject("Failed loading media data");
},
type: function()
{
return this._manifest ? this._manifest.type : "";
},
duration: function()
{
return this._manifest ? this._manifest.duration : 0
},
initSegment: function()
{
if (!this._manifest || !this._manifest.init || !this._mediaData)
return null;
var init = this._manifest.init;
return this._mediaData.slice(init.offset, init.offset + init.size);
},
mediaSegmentsLength: function()
{
if (!this._manifest || !this._manifest.media)
return 0;
return this._manifest.media.length;
},
mediaSegment: function(segmentNumber)
{
if (!this._manifest || !this._manifest.media || !this._mediaData || segmentNumber >= this._manifest.media.length)
return null;
var media = this._manifest.media[segmentNumber];
return this._mediaData.slice(media.offset, media.offset + media.size);
},
mediaSegmentEndTime: function(segmentNumber)
{
if (!this._manifest || !this._manifest.media || !this._mediaData || segmentNumber >= this._manifest.media.length)
return 0;
var media = this._manifest.media[segmentNumber];
return media.timestamp + media.duration;
},
concatenateMediaSegments: function(segmentDataList)
{
var totalLength = 0;
segmentDataList.forEach(segment => totalLength += segment.byteLength);
var view = new Uint8Array(totalLength);
var offset = 0;
segmentDataList.forEach(segment => {
view.set(new Uint8Array(segment), offset);
offset += segment.byteLength;
});
return view.buffer;
},
};