av-merge: Use fetchRange promise properly

This commit is contained in:
Astound 2024-01-26 01:09:12 +08:00
parent 55a8e50d6a
commit 284024433b
Signed by: kaiser
GPG Key ID: 97504AF0027B1A56

View File

@ -204,6 +204,7 @@ Stream.prototype.setup = async function(){
this.url,
this.initRange.start,
this.indexRange.end,
).then(
(buffer) => {
let init_end = this.initRange.end - this.initRange.start + 1;
let index_start = this.indexRange.start - this.initRange.start;
@ -211,22 +212,21 @@ Stream.prototype.setup = async function(){
this.setupInitSegment(buffer.slice(0, init_end));
this.setupSegmentIndex(buffer.slice(index_start, index_end));
}
)
);
} else {
// initialization data
await fetchRange(
this.url,
this.initRange.start,
this.initRange.end,
this.setupInitSegment.bind(this),
);
).then(this.setupInitSegment.bind(this));
// sidx (segment index) table
fetchRange(
this.url,
this.indexRange.start,
this.indexRange.end,
this.setupSegmentIndex.bind(this)
);
).then(this.setupSegmentIndex.bind(this));
}
}
Stream.prototype.setupInitSegment = function(initSegment) {
@ -388,7 +388,7 @@ Stream.prototype.getSegmentIdx = function(videoTime) {
}
index = index + increment;
}
this.reportInfo('Could not find segment index for time', videoTime);
this.reportError('Could not find segment index for time', videoTime);
return 0;
}
Stream.prototype.checkBuffer = async function() {
@ -485,8 +485,7 @@ Stream.prototype.fetchSegment = function(segmentIdx) {
this.url,
entry.start,
entry.end,
this.appendSegment.bind(this, segmentIdx),
);
).then(this.appendSegment.bind(this, segmentIdx));
}
Stream.prototype.fetchSegmentIfNeeded = function(segmentIdx) {
if (segmentIdx < 0 || segmentIdx >= this.sidx.entries.length){
@ -518,22 +517,33 @@ Stream.prototype.reportWarning = function(...args) {
Stream.prototype.reportError = function(...args) {
reportError(String(this.streamType) + ':', ...args);
}
Stream.prototype.reportInfo = function(...args) {
reportInfo(String(this.streamType) + ':', ...args);
}
// Utility functions
function fetchRange(url, start, end, cb) {
// https://gomakethings.com/promise-based-xhr/
// https://stackoverflow.com/a/30008115
function fetchRange(url, start, end) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.responseType = 'arraybuffer';
xhr.setRequestHeader('Range', 'bytes=' + start + '-' + end);
xhr.onload = function() {
//bytesFetched += end - start + 1;
resolve(cb(xhr.response));
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: xhr.status,
statusText: xhr.statusText
});
};
xhr.send();
});
@ -573,9 +583,6 @@ function addEvent(obj, eventName, func) {
return new RegisteredEvent(obj, eventName, func);
}
function reportInfo(...args){
console.info(...args);
}
function reportWarning(...args){
console.warn(...args);
}