xgplayer-streaming-shared
Advanced tools
Comparing version 3.0.0-alpha.5-18 to 3.0.0-alpha.5-19
@@ -0,1 +1,393 @@ | ||
function ownKeys(object, enumerableOnly) { | ||
var keys = Object.keys(object); | ||
if (Object.getOwnPropertySymbols) { | ||
var symbols = Object.getOwnPropertySymbols(object); | ||
enumerableOnly && (symbols = symbols.filter(function(sym) { | ||
return Object.getOwnPropertyDescriptor(object, sym).enumerable; | ||
})), keys.push.apply(keys, symbols); | ||
} | ||
return keys; | ||
} | ||
function _objectSpread2(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = null != arguments[i] ? arguments[i] : {}; | ||
i % 2 ? ownKeys(Object(source), true).forEach(function(key) { | ||
_defineProperty(target, key, source[key]); | ||
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
return target; | ||
} | ||
function _regeneratorRuntime() { | ||
_regeneratorRuntime = function() { | ||
return exports; | ||
}; | ||
var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; | ||
function define(obj, key, value) { | ||
return Object.defineProperty(obj, key, { | ||
value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}), obj[key]; | ||
} | ||
try { | ||
define({}, ""); | ||
} catch (err) { | ||
define = function(obj, key, value) { | ||
return obj[key] = value; | ||
}; | ||
} | ||
function wrap(innerFn, outerFn, self, tryLocsList) { | ||
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); | ||
return generator._invoke = function(innerFn2, self2, context2) { | ||
var state = "suspendedStart"; | ||
return function(method, arg) { | ||
if ("executing" === state) | ||
throw new Error("Generator is already running"); | ||
if ("completed" === state) { | ||
if ("throw" === method) | ||
throw arg; | ||
return doneResult(); | ||
} | ||
for (context2.method = method, context2.arg = arg; ; ) { | ||
var delegate = context2.delegate; | ||
if (delegate) { | ||
var delegateResult = maybeInvokeDelegate(delegate, context2); | ||
if (delegateResult) { | ||
if (delegateResult === ContinueSentinel) | ||
continue; | ||
return delegateResult; | ||
} | ||
} | ||
if ("next" === context2.method) | ||
context2.sent = context2._sent = context2.arg; | ||
else if ("throw" === context2.method) { | ||
if ("suspendedStart" === state) | ||
throw state = "completed", context2.arg; | ||
context2.dispatchException(context2.arg); | ||
} else | ||
"return" === context2.method && context2.abrupt("return", context2.arg); | ||
state = "executing"; | ||
var record = tryCatch(innerFn2, self2, context2); | ||
if ("normal" === record.type) { | ||
if (state = context2.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) | ||
continue; | ||
return { | ||
value: record.arg, | ||
done: context2.done | ||
}; | ||
} | ||
"throw" === record.type && (state = "completed", context2.method = "throw", context2.arg = record.arg); | ||
} | ||
}; | ||
}(innerFn, self, context), generator; | ||
} | ||
function tryCatch(fn, obj, arg) { | ||
try { | ||
return { | ||
type: "normal", | ||
arg: fn.call(obj, arg) | ||
}; | ||
} catch (err) { | ||
return { | ||
type: "throw", | ||
arg: err | ||
}; | ||
} | ||
} | ||
exports.wrap = wrap; | ||
var ContinueSentinel = {}; | ||
function Generator() { | ||
} | ||
function GeneratorFunction() { | ||
} | ||
function GeneratorFunctionPrototype() { | ||
} | ||
var IteratorPrototype = {}; | ||
define(IteratorPrototype, iteratorSymbol, function() { | ||
return this; | ||
}); | ||
var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); | ||
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); | ||
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); | ||
function defineIteratorMethods(prototype) { | ||
["next", "throw", "return"].forEach(function(method) { | ||
define(prototype, method, function(arg) { | ||
return this._invoke(method, arg); | ||
}); | ||
}); | ||
} | ||
function AsyncIterator(generator, PromiseImpl) { | ||
function invoke(method, arg, resolve, reject) { | ||
var record = tryCatch(generator[method], generator, arg); | ||
if ("throw" !== record.type) { | ||
var result = record.arg, value = result.value; | ||
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function(value2) { | ||
invoke("next", value2, resolve, reject); | ||
}, function(err) { | ||
invoke("throw", err, resolve, reject); | ||
}) : PromiseImpl.resolve(value).then(function(unwrapped) { | ||
result.value = unwrapped, resolve(result); | ||
}, function(error) { | ||
return invoke("throw", error, resolve, reject); | ||
}); | ||
} | ||
reject(record.arg); | ||
} | ||
var previousPromise; | ||
this._invoke = function(method, arg) { | ||
function callInvokeWithMethodAndArg() { | ||
return new PromiseImpl(function(resolve, reject) { | ||
invoke(method, arg, resolve, reject); | ||
}); | ||
} | ||
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); | ||
}; | ||
} | ||
function maybeInvokeDelegate(delegate, context) { | ||
var method = delegate.iterator[context.method]; | ||
if (void 0 === method) { | ||
if (context.delegate = null, "throw" === context.method) { | ||
if (delegate.iterator.return && (context.method = "return", context.arg = void 0, maybeInvokeDelegate(delegate, context), "throw" === context.method)) | ||
return ContinueSentinel; | ||
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); | ||
} | ||
return ContinueSentinel; | ||
} | ||
var record = tryCatch(method, delegate.iterator, context.arg); | ||
if ("throw" === record.type) | ||
return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; | ||
var info = record.arg; | ||
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = void 0), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); | ||
} | ||
function pushTryEntry(locs) { | ||
var entry = { | ||
tryLoc: locs[0] | ||
}; | ||
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); | ||
} | ||
function resetTryEntry(entry) { | ||
var record = entry.completion || {}; | ||
record.type = "normal", delete record.arg, entry.completion = record; | ||
} | ||
function Context(tryLocsList) { | ||
this.tryEntries = [{ | ||
tryLoc: "root" | ||
}], tryLocsList.forEach(pushTryEntry, this), this.reset(true); | ||
} | ||
function values(iterable) { | ||
if (iterable) { | ||
var iteratorMethod = iterable[iteratorSymbol]; | ||
if (iteratorMethod) | ||
return iteratorMethod.call(iterable); | ||
if ("function" == typeof iterable.next) | ||
return iterable; | ||
if (!isNaN(iterable.length)) { | ||
var i = -1, next = function next2() { | ||
for (; ++i < iterable.length; ) | ||
if (hasOwn.call(iterable, i)) | ||
return next2.value = iterable[i], next2.done = false, next2; | ||
return next2.value = void 0, next2.done = true, next2; | ||
}; | ||
return next.next = next; | ||
} | ||
} | ||
return { | ||
next: doneResult | ||
}; | ||
} | ||
function doneResult() { | ||
return { | ||
value: void 0, | ||
done: true | ||
}; | ||
} | ||
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function(genFun) { | ||
var ctor = "function" == typeof genFun && genFun.constructor; | ||
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); | ||
}, exports.mark = function(genFun) { | ||
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; | ||
}, exports.awrap = function(arg) { | ||
return { | ||
__await: arg | ||
}; | ||
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function() { | ||
return this; | ||
}), exports.AsyncIterator = AsyncIterator, exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { | ||
void 0 === PromiseImpl && (PromiseImpl = Promise); | ||
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); | ||
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function(result) { | ||
return result.done ? result.value : iter.next(); | ||
}); | ||
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function() { | ||
return this; | ||
}), define(Gp, "toString", function() { | ||
return "[object Generator]"; | ||
}), exports.keys = function(object) { | ||
var keys = []; | ||
for (var key in object) | ||
keys.push(key); | ||
return keys.reverse(), function next() { | ||
for (; keys.length; ) { | ||
var key2 = keys.pop(); | ||
if (key2 in object) | ||
return next.value = key2, next.done = false, next; | ||
} | ||
return next.done = true, next; | ||
}; | ||
}, exports.values = values, Context.prototype = { | ||
constructor: Context, | ||
reset: function(skipTempReset) { | ||
if (this.prev = 0, this.next = 0, this.sent = this._sent = void 0, this.done = false, this.delegate = null, this.method = "next", this.arg = void 0, this.tryEntries.forEach(resetTryEntry), !skipTempReset) | ||
for (var name in this) | ||
"t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = void 0); | ||
}, | ||
stop: function() { | ||
this.done = true; | ||
var rootRecord = this.tryEntries[0].completion; | ||
if ("throw" === rootRecord.type) | ||
throw rootRecord.arg; | ||
return this.rval; | ||
}, | ||
dispatchException: function(exception) { | ||
if (this.done) | ||
throw exception; | ||
var context = this; | ||
function handle(loc, caught) { | ||
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = void 0), !!caught; | ||
} | ||
for (var i = this.tryEntries.length - 1; i >= 0; --i) { | ||
var entry = this.tryEntries[i], record = entry.completion; | ||
if ("root" === entry.tryLoc) | ||
return handle("end"); | ||
if (entry.tryLoc <= this.prev) { | ||
var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); | ||
if (hasCatch && hasFinally) { | ||
if (this.prev < entry.catchLoc) | ||
return handle(entry.catchLoc, true); | ||
if (this.prev < entry.finallyLoc) | ||
return handle(entry.finallyLoc); | ||
} else if (hasCatch) { | ||
if (this.prev < entry.catchLoc) | ||
return handle(entry.catchLoc, true); | ||
} else { | ||
if (!hasFinally) | ||
throw new Error("try statement without catch or finally"); | ||
if (this.prev < entry.finallyLoc) | ||
return handle(entry.finallyLoc); | ||
} | ||
} | ||
} | ||
}, | ||
abrupt: function(type, arg) { | ||
for (var i = this.tryEntries.length - 1; i >= 0; --i) { | ||
var entry = this.tryEntries[i]; | ||
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { | ||
var finallyEntry = entry; | ||
break; | ||
} | ||
} | ||
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); | ||
var record = finallyEntry ? finallyEntry.completion : {}; | ||
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); | ||
}, | ||
complete: function(record, afterLoc) { | ||
if ("throw" === record.type) | ||
throw record.arg; | ||
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; | ||
}, | ||
finish: function(finallyLoc) { | ||
for (var i = this.tryEntries.length - 1; i >= 0; --i) { | ||
var entry = this.tryEntries[i]; | ||
if (entry.finallyLoc === finallyLoc) | ||
return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; | ||
} | ||
}, | ||
catch: function(tryLoc) { | ||
for (var i = this.tryEntries.length - 1; i >= 0; --i) { | ||
var entry = this.tryEntries[i]; | ||
if (entry.tryLoc === tryLoc) { | ||
var record = entry.completion; | ||
if ("throw" === record.type) { | ||
var thrown = record.arg; | ||
resetTryEntry(entry); | ||
} | ||
return thrown; | ||
} | ||
} | ||
throw new Error("illegal catch attempt"); | ||
}, | ||
delegateYield: function(iterable, resultName, nextLoc) { | ||
return this.delegate = { | ||
iterator: values(iterable), | ||
resultName, | ||
nextLoc | ||
}, "next" === this.method && (this.arg = void 0), ContinueSentinel; | ||
} | ||
}, exports; | ||
} | ||
function _typeof(obj) { | ||
"@babel/helpers - typeof"; | ||
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { | ||
return typeof obj2; | ||
} : function(obj2) { | ||
return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; | ||
}, _typeof(obj); | ||
} | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function() { | ||
var self = this, args = arguments; | ||
return new Promise(function(resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(void 0); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
} | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) | ||
descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) | ||
_defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) | ||
_defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
function _defineProperty(obj, key, value) { | ||
@@ -14,2 +406,227 @@ if (key in obj) { | ||
} | ||
export { _defineProperty as defineProperty }; | ||
function _inherits(subClass, superClass) { | ||
if (typeof superClass !== "function" && superClass !== null) { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
subClass.prototype = Object.create(superClass && superClass.prototype, { | ||
constructor: { | ||
value: subClass, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
Object.defineProperty(subClass, "prototype", { | ||
writable: false | ||
}); | ||
if (superClass) | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) { | ||
return o2.__proto__ || Object.getPrototypeOf(o2); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { | ||
o2.__proto__ = p2; | ||
return o2; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) | ||
return false; | ||
if (Reflect.construct.sham) | ||
return false; | ||
if (typeof Proxy === "function") | ||
return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { | ||
})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct.bind(); | ||
} else { | ||
_construct = function _construct2(Parent2, args2, Class2) { | ||
var a = [null]; | ||
a.push.apply(a, args2); | ||
var Constructor = Function.bind.apply(Parent2, a); | ||
var instance = new Constructor(); | ||
if (Class2) | ||
_setPrototypeOf(instance, Class2.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0; | ||
_wrapNativeSuper = function _wrapNativeSuper2(Class2) { | ||
if (Class2 === null || !_isNativeFunction(Class2)) | ||
return Class2; | ||
if (typeof Class2 !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class2)) | ||
return _cache.get(Class2); | ||
_cache.set(Class2, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class2, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class2.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class2); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) | ||
return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) | ||
continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
function _objectWithoutProperties(source, excluded) { | ||
if (source == null) | ||
return {}; | ||
var target = _objectWithoutPropertiesLoose(source, excluded); | ||
var key, i; | ||
if (Object.getOwnPropertySymbols) { | ||
var sourceSymbolKeys = Object.getOwnPropertySymbols(source); | ||
for (i = 0; i < sourceSymbolKeys.length; i++) { | ||
key = sourceSymbolKeys[i]; | ||
if (excluded.indexOf(key) >= 0) | ||
continue; | ||
if (!Object.prototype.propertyIsEnumerable.call(source, key)) | ||
continue; | ||
target[key] = source[key]; | ||
} | ||
} | ||
return target; | ||
} | ||
function _assertThisInitialized(self) { | ||
if (self === void 0) { | ||
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | ||
} | ||
return self; | ||
} | ||
function _possibleConstructorReturn(self, call) { | ||
if (call && (typeof call === "object" || typeof call === "function")) { | ||
return call; | ||
} else if (call !== void 0) { | ||
throw new TypeError("Derived constructors may only return object or undefined"); | ||
} | ||
return _assertThisInitialized(self); | ||
} | ||
function _createSuper(Derived) { | ||
var hasNativeReflectConstruct = _isNativeReflectConstruct(); | ||
return function _createSuperInternal() { | ||
var Super = _getPrototypeOf(Derived), result; | ||
if (hasNativeReflectConstruct) { | ||
var NewTarget = _getPrototypeOf(this).constructor; | ||
result = Reflect.construct(Super, arguments, NewTarget); | ||
} else { | ||
result = Super.apply(this, arguments); | ||
} | ||
return _possibleConstructorReturn(this, result); | ||
}; | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) | ||
return; | ||
if (typeof o === "string") | ||
return _arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) | ||
n = o.constructor.name; | ||
if (n === "Map" || n === "Set") | ||
return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) | ||
return _arrayLikeToArray(o, minLen); | ||
} | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) | ||
len = arr.length; | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) | ||
arr2[i] = arr[i]; | ||
return arr2; | ||
} | ||
function _createForOfIteratorHelper(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (!it) { | ||
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) | ||
o = it; | ||
var i = 0; | ||
var F = function() { | ||
}; | ||
return { | ||
s: F, | ||
n: function() { | ||
if (i >= o.length) | ||
return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}, | ||
e: function(e) { | ||
throw e; | ||
}, | ||
f: F | ||
}; | ||
} | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
var normalCompletion = true, didErr = false, err; | ||
return { | ||
s: function() { | ||
it = it.call(o); | ||
}, | ||
n: function() { | ||
var step = it.next(); | ||
normalCompletion = step.done; | ||
return step; | ||
}, | ||
e: function(e) { | ||
didErr = true; | ||
err = e; | ||
}, | ||
f: function() { | ||
try { | ||
if (!normalCompletion && it.return != null) | ||
it.return(); | ||
} finally { | ||
if (didErr) | ||
throw err; | ||
} | ||
} | ||
}; | ||
} | ||
export { _arrayLikeToArray as arrayLikeToArray, _assertThisInitialized as assertThisInitialized, _asyncToGenerator as asyncToGenerator, _classCallCheck as classCallCheck, _construct as construct, _createClass as createClass, _createForOfIteratorHelper as createForOfIteratorHelper, _createSuper as createSuper, _defineProperty as defineProperty, _getPrototypeOf as getPrototypeOf, _inherits as inherits, _isNativeFunction as isNativeFunction, _isNativeReflectConstruct as isNativeReflectConstruct, _objectSpread2 as objectSpread2, _objectWithoutProperties as objectWithoutProperties, _objectWithoutPropertiesLoose as objectWithoutPropertiesLoose, _possibleConstructorReturn as possibleConstructorReturn, _regeneratorRuntime as regeneratorRuntime, _setPrototypeOf as setPrototypeOf, _typeof as typeof, _unsupportedIterableToArray as unsupportedIterableToArray, _wrapNativeSuper as wrapNativeSuper }; |
206
es/buffer.js
@@ -1,101 +0,125 @@ | ||
class Buffer { | ||
static start(buf) { | ||
if (!buf || !buf.length) | ||
return 0; | ||
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6) | ||
return 0; | ||
if (buf.length === 1 && buf.start(0) < 0) | ||
return 0; | ||
return buf.start(0); | ||
import { createClass as _createClass, classCallCheck as _classCallCheck } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.array.push.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
var Buffer = /* @__PURE__ */ function() { | ||
function Buffer2() { | ||
_classCallCheck(this, Buffer2); | ||
} | ||
static end(buf) { | ||
if (!buf || !buf.length) | ||
return 0; | ||
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6) | ||
return 0; | ||
return buf.end(buf.length - 1); | ||
} | ||
static get(b) { | ||
if (!b) | ||
return; | ||
try { | ||
return b.buffered; | ||
} catch (error) { | ||
_createClass(Buffer2, null, [{ | ||
key: "start", | ||
value: function start(buf) { | ||
if (!buf || !buf.length) | ||
return 0; | ||
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6) | ||
return 0; | ||
if (buf.length === 1 && buf.start(0) < 0) | ||
return 0; | ||
return buf.start(0); | ||
} | ||
} | ||
static buffers(buf, maxHole) { | ||
if (!buf || !buf.length) | ||
return []; | ||
const buffers = []; | ||
for (let i = 0, l = buf.length; i < l; i++) { | ||
const bufLen = buffers.length; | ||
if (!bufLen || !maxHole) { | ||
buffers.push([buf.start(i), buf.end(i)]); | ||
} else { | ||
const last = buffers[bufLen - 1]; | ||
const lastEnd = last[1]; | ||
const start = buf.start(i); | ||
if (start - lastEnd <= maxHole) { | ||
const end = buf.end(i); | ||
if (end > lastEnd) { | ||
last[1] = end; | ||
}, { | ||
key: "end", | ||
value: function end(buf) { | ||
if (!buf || !buf.length) | ||
return 0; | ||
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6) | ||
return 0; | ||
return buf.end(buf.length - 1); | ||
} | ||
}, { | ||
key: "get", | ||
value: function get(b) { | ||
if (!b) | ||
return; | ||
try { | ||
return b.buffered; | ||
} catch (error) { | ||
} | ||
} | ||
}, { | ||
key: "buffers", | ||
value: function buffers(buf, maxHole) { | ||
if (!buf || !buf.length) | ||
return []; | ||
var buffers2 = []; | ||
for (var i = 0, l = buf.length; i < l; i++) { | ||
var bufLen = buffers2.length; | ||
if (!bufLen || !maxHole) { | ||
buffers2.push([buf.start(i), buf.end(i)]); | ||
} else { | ||
var last = buffers2[bufLen - 1]; | ||
var lastEnd = last[1]; | ||
var start = buf.start(i); | ||
if (start - lastEnd <= maxHole) { | ||
var end = buf.end(i); | ||
if (end > lastEnd) { | ||
last[1] = end; | ||
} | ||
} else { | ||
buffers2.push([buf.start(i), buf.end(i)]); | ||
} | ||
} else { | ||
buffers.push([buf.start(i), buf.end(i)]); | ||
} | ||
} | ||
return buffers2; | ||
} | ||
return buffers; | ||
} | ||
static length(buffers) { | ||
if (!buffers || !buffers.length) | ||
return 0; | ||
return buffers.reduce((a, c) => a += c[1] - c[0], 0); | ||
} | ||
static info(buf, pos = 0, maxHole = 0) { | ||
if (!buf || !buf.length) | ||
}, { | ||
key: "length", | ||
value: function length(buffers) { | ||
if (!buffers || !buffers.length) | ||
return 0; | ||
return buffers.reduce(function(a, c) { | ||
return a += c[1] - c[0]; | ||
}, 0); | ||
} | ||
}, { | ||
key: "info", | ||
value: function info(buf) { | ||
var pos = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; | ||
var maxHole = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; | ||
if (!buf || !buf.length) | ||
return { | ||
start: 0, | ||
end: 0, | ||
buffers: [] | ||
}; | ||
var start = 0; | ||
var end = 0; | ||
var index = 0; | ||
var nextStart = 0; | ||
var nextEnd = 0; | ||
var prevStart = 0; | ||
var prevEnd = 0; | ||
var buffers = Buffer2.buffers(buf, maxHole); | ||
for (var i = 0, l = buffers.length; i < l; i++) { | ||
var item = buffers[i]; | ||
if (pos + maxHole >= item[0] && pos < item[1]) { | ||
start = item[0]; | ||
end = item[1]; | ||
index = i; | ||
} else if (pos + maxHole < item[0]) { | ||
nextStart = item[0]; | ||
nextEnd = item[1]; | ||
break; | ||
} else if (pos + maxHole > item[1]) { | ||
prevStart = item[0]; | ||
prevEnd = item[1]; | ||
} | ||
} | ||
return { | ||
start: 0, | ||
end: 0, | ||
buffers: [] | ||
start, | ||
end, | ||
index, | ||
buffers, | ||
nextStart, | ||
nextEnd, | ||
prevStart, | ||
prevEnd, | ||
currentTime: pos, | ||
behind: pos - start, | ||
remaining: end ? end - pos : 0, | ||
length: Buffer2.length && Buffer2.length(buffers) | ||
}; | ||
let start = 0; | ||
let end = 0; | ||
let index = 0; | ||
let nextStart = 0; | ||
let nextEnd = 0; | ||
let prevStart = 0; | ||
let prevEnd = 0; | ||
const buffers = Buffer.buffers(buf, maxHole); | ||
for (let i = 0, l = buffers.length; i < l; i++) { | ||
const item = buffers[i]; | ||
if (pos + maxHole >= item[0] && pos < item[1]) { | ||
start = item[0]; | ||
end = item[1]; | ||
index = i; | ||
} else if (pos + maxHole < item[0]) { | ||
nextStart = item[0]; | ||
nextEnd = item[1]; | ||
break; | ||
} else if (pos + maxHole > item[1]) { | ||
prevStart = item[0]; | ||
prevEnd = item[1]; | ||
} | ||
} | ||
return { | ||
start, | ||
end, | ||
index, | ||
buffers, | ||
nextStart, | ||
nextEnd, | ||
prevStart, | ||
prevEnd, | ||
currentTime: pos, | ||
behind: pos - start, | ||
remaining: end ? end - pos : 0, | ||
length: Buffer.length && Buffer.length(buffers) | ||
}; | ||
} | ||
} | ||
}]); | ||
return Buffer2; | ||
}(); | ||
export { Buffer }; |
@@ -1,2 +0,2 @@ | ||
const isBrowser = typeof window !== "undefined"; | ||
var isBrowser = typeof window !== "undefined"; | ||
export { isBrowser }; |
113
es/error.js
@@ -0,3 +1,5 @@ | ||
import { defineProperty as _defineProperty, inherits as _inherits, createSuper as _createSuper, createClass as _createClass, classCallCheck as _classCallCheck, wrapNativeSuper as _wrapNativeSuper } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.error.cause.js"; | ||
const ERR = { | ||
var _ERR_CODE; | ||
var ERR = { | ||
MANIFEST: "manifest", | ||
@@ -22,58 +24,61 @@ NETWORK: "network", | ||
}; | ||
const ERR_CODE = { | ||
[ERR.MANIFEST]: { | ||
HLS: 1100 | ||
}, | ||
[ERR.NETWORK]: 2100, | ||
[ERR.NETWORK_TIMEOUT]: 2101, | ||
[ERR.DEMUX]: { | ||
FLV: 3100, | ||
HLS: 3200, | ||
MP4: 3300, | ||
FMP4: 3400 | ||
}, | ||
[ERR.REMUX]: { | ||
FMP4: 4100, | ||
MP4: 4200 | ||
}, | ||
[ERR.MEDIA]: { | ||
MSE_ADD_SB: 5200, | ||
MSE_APPEND_BUFFER: 5201, | ||
MSE_OTHER: 5202 | ||
}, | ||
[ERR.OTHER]: 8e3 | ||
}; | ||
class StreamingError extends Error { | ||
constructor(type, subType, origin, payload, msg) { | ||
super(msg || (origin == null ? void 0 : origin.message)); | ||
this.errorType = type === ERR.NETWORK_TIMEOUT ? ERR.NETWORK : type; | ||
this.originError = origin; | ||
this.ext = payload; | ||
this.errorCode = ERR_CODE[type][subType] || ERR_CODE[type]; | ||
this.errorMessage = this.message; | ||
if (!this.errorCode) { | ||
this.errorType = ERR.OTHER; | ||
this.errorCode = ERR_CODE[this.errorType]; | ||
var ERR_CODE = (_ERR_CODE = {}, _defineProperty(_ERR_CODE, ERR.MANIFEST, { | ||
HLS: 1100 | ||
}), _defineProperty(_ERR_CODE, ERR.NETWORK, 2100), _defineProperty(_ERR_CODE, ERR.NETWORK_TIMEOUT, 2101), _defineProperty(_ERR_CODE, ERR.DEMUX, { | ||
FLV: 3100, | ||
HLS: 3200, | ||
MP4: 3300, | ||
FMP4: 3400 | ||
}), _defineProperty(_ERR_CODE, ERR.REMUX, { | ||
FMP4: 4100, | ||
MP4: 4200 | ||
}), _defineProperty(_ERR_CODE, ERR.MEDIA, { | ||
MSE_ADD_SB: 5200, | ||
MSE_APPEND_BUFFER: 5201, | ||
MSE_OTHER: 5202 | ||
}), _defineProperty(_ERR_CODE, ERR.OTHER, 8e3), _ERR_CODE); | ||
var StreamingError = /* @__PURE__ */ function(_Error) { | ||
_inherits(StreamingError2, _Error); | ||
var _super = _createSuper(StreamingError2); | ||
function StreamingError2(type, subType, origin, payload, msg) { | ||
var _this; | ||
_classCallCheck(this, StreamingError2); | ||
_this = _super.call(this, msg || (origin === null || origin === void 0 ? void 0 : origin.message)); | ||
_this.errorType = type === ERR.NETWORK_TIMEOUT ? ERR.NETWORK : type; | ||
_this.originError = origin; | ||
_this.ext = payload; | ||
_this.errorCode = ERR_CODE[type][subType] || ERR_CODE[type]; | ||
_this.errorMessage = _this.message; | ||
if (!_this.errorCode) { | ||
_this.errorType = ERR.OTHER; | ||
_this.errorCode = ERR_CODE[_this.errorType]; | ||
} | ||
return _this; | ||
} | ||
static create(type, subType, origin, payload, msg) { | ||
if (type instanceof StreamingError) { | ||
return type; | ||
} else if (type instanceof Error) { | ||
origin = type; | ||
type = ""; | ||
_createClass(StreamingError2, null, [{ | ||
key: "create", | ||
value: function create(type, subType, origin, payload, msg) { | ||
if (type instanceof StreamingError2) { | ||
return type; | ||
} else if (type instanceof Error) { | ||
origin = type; | ||
type = ""; | ||
} | ||
if (!type) | ||
type = ERR.OTHER; | ||
return new StreamingError2(type, subType, origin, payload, msg); | ||
} | ||
if (!type) | ||
type = ERR.OTHER; | ||
return new StreamingError(type, subType, origin, payload, msg); | ||
} | ||
static network(error) { | ||
var _a; | ||
return new StreamingError((error == null ? void 0 : error.isTimeout) ? ERR.NETWORK_TIMEOUT : ERR.NETWORK, error, null, { | ||
url: error == null ? void 0 : error.url, | ||
response: error == null ? void 0 : error.response, | ||
httpCode: (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status | ||
}); | ||
} | ||
} | ||
}, { | ||
key: "network", | ||
value: function network(error) { | ||
var _error$response; | ||
return new StreamingError2(error !== null && error !== void 0 && error.isTimeout ? ERR.NETWORK_TIMEOUT : ERR.NETWORK, error, null, { | ||
url: error === null || error === void 0 ? void 0 : error.url, | ||
response: error === null || error === void 0 ? void 0 : error.response, | ||
httpCode: error === null || error === void 0 ? void 0 : (_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status | ||
}); | ||
} | ||
}]); | ||
return StreamingError2; | ||
}(/* @__PURE__ */ _wrapNativeSuper(Error)); | ||
export { ERR, ERR_CODE, StreamingError }; |
@@ -1,2 +0,2 @@ | ||
const EVENT = { | ||
var EVENT = { | ||
ERROR: "error", | ||
@@ -3,0 +3,0 @@ TTFB: "core.ttfb", |
11
es/is.js
@@ -1,4 +0,9 @@ | ||
const toString = Object.prototype.toString; | ||
import { typeof as _typeof } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.object.get-prototype-of.js"; | ||
import "core-js/modules/es.number.is-nan.js"; | ||
import "core-js/modules/es.number.constructor.js"; | ||
var toString = Object.prototype.toString; | ||
function isObject(a) { | ||
return a !== null && typeof a === "object"; | ||
return a !== null && _typeof(a) === "object"; | ||
} | ||
@@ -9,3 +14,3 @@ function isPlainObject(val) { | ||
} | ||
const prototype = Object.getPrototypeOf(val); | ||
var prototype = Object.getPrototypeOf(val); | ||
return prototype === null || prototype === Object.prototype; | ||
@@ -12,0 +17,0 @@ } |
113
es/logger.js
@@ -1,42 +0,79 @@ | ||
import { defineProperty as _defineProperty } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
class Logger { | ||
constructor(name) { | ||
import { defineProperty as _defineProperty, createClass as _createClass, classCallCheck as _classCallCheck } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.function.name.js"; | ||
import "core-js/modules/es.array.concat.js"; | ||
import "core-js/modules/esnext.array.group.js"; | ||
var Logger = /* @__PURE__ */ function() { | ||
function Logger2(name) { | ||
_classCallCheck(this, Logger2); | ||
this.name = name || ""; | ||
this._prefix = `[${this.name}]`; | ||
this._prefix = "[".concat(this.name, "]"); | ||
} | ||
debug(...args) { | ||
if (Logger.disabled) | ||
return; | ||
console.debug(this._prefix, ...args); | ||
} | ||
log(...args) { | ||
if (Logger.disabled) | ||
return; | ||
console.log(this._prefix, ...args); | ||
} | ||
warn(...args) { | ||
if (Logger.disabled) | ||
return; | ||
console.warn(this._prefix, ...args); | ||
} | ||
error(...args) { | ||
if (Logger.disabled) | ||
return; | ||
console.error(this._prefix, ...args); | ||
} | ||
table(...args) { | ||
if (Logger.disabled) | ||
return; | ||
console.group(this._prefix); | ||
console.table(...args); | ||
console.groupEnd(); | ||
} | ||
static enable() { | ||
Logger.disabled = false; | ||
} | ||
static disable() { | ||
Logger.disabled = true; | ||
} | ||
} | ||
_createClass(Logger2, [{ | ||
key: "debug", | ||
value: function debug() { | ||
var _console; | ||
if (Logger2.disabled) | ||
return; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
(_console = console).debug.apply(_console, [this._prefix].concat(args)); | ||
} | ||
}, { | ||
key: "log", | ||
value: function log() { | ||
var _console2; | ||
if (Logger2.disabled) | ||
return; | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
(_console2 = console).log.apply(_console2, [this._prefix].concat(args)); | ||
} | ||
}, { | ||
key: "warn", | ||
value: function warn() { | ||
var _console3; | ||
if (Logger2.disabled) | ||
return; | ||
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | ||
args[_key3] = arguments[_key3]; | ||
} | ||
(_console3 = console).warn.apply(_console3, [this._prefix].concat(args)); | ||
} | ||
}, { | ||
key: "error", | ||
value: function error() { | ||
var _console4; | ||
if (Logger2.disabled) | ||
return; | ||
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | ||
args[_key4] = arguments[_key4]; | ||
} | ||
(_console4 = console).error.apply(_console4, [this._prefix].concat(args)); | ||
} | ||
}, { | ||
key: "table", | ||
value: function table() { | ||
var _console5; | ||
if (Logger2.disabled) | ||
return; | ||
console.group(this._prefix); | ||
(_console5 = console).table.apply(_console5, arguments); | ||
console.groupEnd(); | ||
} | ||
}], [{ | ||
key: "enable", | ||
value: function enable() { | ||
Logger2.disabled = false; | ||
} | ||
}, { | ||
key: "disable", | ||
value: function disable() { | ||
Logger2.disabled = true; | ||
} | ||
}]); | ||
return Logger2; | ||
}(); | ||
_defineProperty(Logger, "disabled", true); | ||
export { Logger }; |
649
es/mse.js
@@ -1,3 +0,14 @@ | ||
import { defineProperty as _defineProperty } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
import { defineProperty as _defineProperty, inherits as _inherits, createSuper as _createSuper, createClass as _createClass, classCallCheck as _classCallCheck, wrapNativeSuper as _wrapNativeSuper, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "./_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.error.cause.js"; | ||
import "core-js/modules/es.array.iterator.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.string.iterator.js"; | ||
import "core-js/modules/web.dom-collections.iterator.js"; | ||
import "core-js/modules/web.url.js"; | ||
import "core-js/modules/web.url-search-params.js"; | ||
import "core-js/modules/web.dom-collections.for-each.js"; | ||
import "core-js/modules/es.object.keys.js"; | ||
import "core-js/modules/es.promise.js"; | ||
import "core-js/modules/es.array.push.js"; | ||
import "core-js/modules/es.regexp.exec.js"; | ||
import { createPublicPromise } from "./utils.js"; | ||
@@ -13,15 +24,23 @@ import { Buffer } from "./buffer.js"; | ||
} | ||
const MediaSource = getMediaSource(); | ||
const MSEErrorType = { | ||
var MediaSource = getMediaSource(); | ||
var MSEErrorType = { | ||
UPDATE_ERROR: "updateError" | ||
}; | ||
class MSEError extends Error { | ||
constructor(type, msg) { | ||
super(msg || type); | ||
this.type = type; | ||
this.msg = msg; | ||
var MSEError = /* @__PURE__ */ function(_Error) { | ||
_inherits(MSEError2, _Error); | ||
var _super = _createSuper(MSEError2); | ||
function MSEError2(type, msg) { | ||
var _this; | ||
_classCallCheck(this, MSEError2); | ||
_this = _super.call(this, msg || type); | ||
_this.type = type; | ||
_this.msg = msg; | ||
return _this; | ||
} | ||
} | ||
class MSE { | ||
constructor(media) { | ||
return _createClass(MSEError2); | ||
}(/* @__PURE__ */ _wrapNativeSuper(Error)); | ||
var MSE = /* @__PURE__ */ function() { | ||
function MSE2(media) { | ||
var _this2 = this; | ||
_classCallCheck(this, MSE2); | ||
_defineProperty(this, "media", null); | ||
@@ -32,16 +51,16 @@ _defineProperty(this, "mediaSource", null); | ||
_defineProperty(this, "_sourceBuffer", /* @__PURE__ */ Object.create(null)); | ||
_defineProperty(this, "_onSBUpdateEnd", (type) => { | ||
const queue = this._queue[type]; | ||
_defineProperty(this, "_onSBUpdateEnd", function(type) { | ||
var queue = _this2._queue[type]; | ||
if (queue) { | ||
const op = queue.shift(); | ||
var op = queue.shift(); | ||
if (op) { | ||
op.promise.resolve(); | ||
this._startQueue(type); | ||
_this2._startQueue(type); | ||
} | ||
} | ||
}); | ||
_defineProperty(this, "_onSBUpdateError", (type, event) => { | ||
const queue = this._queue[type]; | ||
_defineProperty(this, "_onSBUpdateError", function(type, event) { | ||
var queue = _this2._queue[type]; | ||
if (queue) { | ||
const op = queue[0]; | ||
var op = queue[0]; | ||
if (op) { | ||
@@ -55,264 +74,392 @@ op.promise.reject(new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_APPEND_BUFFER, event)); | ||
} | ||
get isOpened() { | ||
var _a; | ||
return ((_a = this.mediaSource) == null ? void 0 : _a.readyState) === "open"; | ||
} | ||
get duration() { | ||
var _a; | ||
return ((_a = this.mediaSource) == null ? void 0 : _a.duration) || -1; | ||
} | ||
updateDuration(duration) { | ||
return this._enqueueBlockingOp(() => { | ||
if (this.mediaSource) | ||
this.mediaSource.duration = duration; | ||
}); | ||
} | ||
open() { | ||
if (this._openPromise.used && !this.isOpened && this.mediaSource) { | ||
const ms = this.mediaSource; | ||
const onOpen = () => { | ||
ms.removeEventListener("sourceopen", onOpen); | ||
this._openPromise.resolve(); | ||
}; | ||
ms.addEventListener("sourceopen", onOpen); | ||
this._openPromise = createPublicPromise(); | ||
_createClass(MSE2, [{ | ||
key: "isOpened", | ||
get: function get() { | ||
var _this$mediaSource; | ||
return ((_this$mediaSource = this.mediaSource) === null || _this$mediaSource === void 0 ? void 0 : _this$mediaSource.readyState) === "open"; | ||
} | ||
return this._openPromise; | ||
} | ||
async bindMedia(media) { | ||
if (this.mediaSource || this.media) | ||
await this.unbindMedia(); | ||
if (!media || !MediaSource) | ||
throw new Error("Param media or MediaSource does not exist"); | ||
this.media = media; | ||
const ms = this.mediaSource = new MediaSource(); | ||
media.src = URL.createObjectURL(ms); | ||
const onOpen = () => { | ||
ms.removeEventListener("sourceopen", onOpen); | ||
URL.revokeObjectURL(media.src); | ||
this._openPromise.resolve(); | ||
}; | ||
ms.addEventListener("sourceopen", onOpen); | ||
return this._openPromise; | ||
} | ||
async unbindMedia() { | ||
if (!this._openPromise.used) | ||
this._openPromise.resolve(); | ||
const ms = this.mediaSource; | ||
if (ms) { | ||
Object.keys(this._queue).forEach((t) => { | ||
const queue = this._queue[t]; | ||
if (queue) { | ||
queue.forEach((x) => x.promise.resolve); | ||
} | ||
}, { | ||
key: "duration", | ||
get: function get() { | ||
var _this$mediaSource2; | ||
return ((_this$mediaSource2 = this.mediaSource) === null || _this$mediaSource2 === void 0 ? void 0 : _this$mediaSource2.duration) || -1; | ||
} | ||
}, { | ||
key: "updateDuration", | ||
value: function updateDuration(duration) { | ||
var _this3 = this; | ||
return this._enqueueBlockingOp(function() { | ||
if (_this3.mediaSource) | ||
_this3.mediaSource.duration = duration; | ||
}); | ||
const hasMetadata = !!this.media && this.media.readyState >= 1; | ||
const mseOpen = ms.readyState === "open"; | ||
if (hasMetadata && mseOpen) { | ||
try { | ||
ms.endOfStream(); | ||
} catch (error) { | ||
} | ||
} | ||
}, { | ||
key: "open", | ||
value: function open() { | ||
var _this4 = this; | ||
if (this._openPromise.used && !this.isOpened && this.mediaSource) { | ||
var ms = this.mediaSource; | ||
var onOpen = function onOpen2() { | ||
ms.removeEventListener("sourceopen", onOpen2); | ||
_this4._openPromise.resolve(); | ||
}; | ||
ms.addEventListener("sourceopen", onOpen); | ||
this._openPromise = createPublicPromise(); | ||
} | ||
Object.keys(this._sourceBuffer).forEach((k) => { | ||
try { | ||
ms.removeSourceBuffer(this._sourceBuffer[k]); | ||
} catch (error) { | ||
} | ||
}); | ||
return this._openPromise; | ||
} | ||
if (this.media) { | ||
this.media.removeAttribute("src"); | ||
}, { | ||
key: "bindMedia", | ||
value: function() { | ||
var _bindMedia = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee(media) { | ||
var _this5 = this; | ||
var ms, onOpen; | ||
return _regeneratorRuntime().wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
if (!(this.mediaSource || this.media)) { | ||
_context.next = 3; | ||
break; | ||
} | ||
_context.next = 3; | ||
return this.unbindMedia(); | ||
case 3: | ||
if (!(!media || !MediaSource)) { | ||
_context.next = 5; | ||
break; | ||
} | ||
throw new Error("Param media or MediaSource does not exist"); | ||
case 5: | ||
this.media = media; | ||
ms = this.mediaSource = new MediaSource(); | ||
media.src = URL.createObjectURL(ms); | ||
onOpen = function onOpen2() { | ||
ms.removeEventListener("sourceopen", onOpen2); | ||
URL.revokeObjectURL(media.src); | ||
_this5._openPromise.resolve(); | ||
}; | ||
ms.addEventListener("sourceopen", onOpen); | ||
return _context.abrupt("return", this._openPromise); | ||
case 11: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this); | ||
})); | ||
function bindMedia(_x) { | ||
return _bindMedia.apply(this, arguments); | ||
} | ||
return bindMedia; | ||
}() | ||
}, { | ||
key: "unbindMedia", | ||
value: function() { | ||
var _unbindMedia = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee2() { | ||
var _this6 = this; | ||
var ms, hasMetadata, mseOpen; | ||
return _regeneratorRuntime().wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
if (!this._openPromise.used) | ||
this._openPromise.resolve(); | ||
ms = this.mediaSource; | ||
if (ms) { | ||
Object.keys(this._queue).forEach(function(t) { | ||
var queue = _this6._queue[t]; | ||
if (queue) { | ||
queue.forEach(function(x) { | ||
return x.promise.resolve; | ||
}); | ||
} | ||
}); | ||
hasMetadata = !!this.media && this.media.readyState >= 1; | ||
mseOpen = ms.readyState === "open"; | ||
if (hasMetadata && mseOpen) { | ||
try { | ||
ms.endOfStream(); | ||
} catch (error) { | ||
} | ||
} | ||
Object.keys(this._sourceBuffer).forEach(function(k) { | ||
try { | ||
ms.removeSourceBuffer(_this6._sourceBuffer[k]); | ||
} catch (error) { | ||
} | ||
}); | ||
} | ||
if (this.media) { | ||
this.media.removeAttribute("src"); | ||
try { | ||
this.media.load(); | ||
} catch (error) { | ||
} | ||
this.media = null; | ||
} | ||
this.mediaSource = null; | ||
this._openPromise = createPublicPromise(); | ||
this._queue = /* @__PURE__ */ Object.create(null); | ||
this._sourceBuffer = /* @__PURE__ */ Object.create(null); | ||
case 8: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this); | ||
})); | ||
function unbindMedia() { | ||
return _unbindMedia.apply(this, arguments); | ||
} | ||
return unbindMedia; | ||
}() | ||
}, { | ||
key: "createSource", | ||
value: function createSource(type, mimeType) { | ||
if (this._sourceBuffer[type] || !this.mediaSource) | ||
return; | ||
var sb; | ||
try { | ||
this.media.load(); | ||
sb = this._sourceBuffer[type] = this.mediaSource.addSourceBuffer(mimeType); | ||
} catch (error) { | ||
throw new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_ADD_SB, error); | ||
} | ||
this.media = null; | ||
sb.mimeType = mimeType; | ||
sb.addEventListener("updateend", this._onSBUpdateEnd.bind(this, type)); | ||
sb.addEventListener("error", this._onSBUpdateError.bind(this, type)); | ||
} | ||
this.mediaSource = null; | ||
this._openPromise = createPublicPromise(); | ||
this._queue = /* @__PURE__ */ Object.create(null); | ||
this._sourceBuffer = /* @__PURE__ */ Object.create(null); | ||
} | ||
createSource(type, mimeType) { | ||
if (this._sourceBuffer[type] || !this.mediaSource) | ||
return; | ||
let sb; | ||
try { | ||
sb = this._sourceBuffer[type] = this.mediaSource.addSourceBuffer(mimeType); | ||
} catch (error) { | ||
throw new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_ADD_SB, error); | ||
}, { | ||
key: "changeType", | ||
value: function changeType(type, mimeType) { | ||
var sb = this._sourceBuffer[type]; | ||
if (!this.mediaSource || !sb || sb.mimeType === mimeType || typeof sb.changeType !== "function") | ||
return Promise.resolve(); | ||
return this._enqueueOp(function() { | ||
sb.changeType(mimeType); | ||
}); | ||
} | ||
sb.mimeType = mimeType; | ||
sb.addEventListener("updateend", this._onSBUpdateEnd.bind(this, type)); | ||
sb.addEventListener("error", this._onSBUpdateError.bind(this, type)); | ||
} | ||
changeType(type, mimeType) { | ||
const sb = this._sourceBuffer[type]; | ||
if (!this.mediaSource || !sb || sb.mimeType === mimeType || typeof sb.changeType !== "function") | ||
return Promise.resolve(); | ||
return this._enqueueOp(() => { | ||
sb.changeType(mimeType); | ||
}); | ||
} | ||
createOrChangeSource(type, mimeType) { | ||
this.createSource(type, mimeType); | ||
return this.changeType(type, mimeType); | ||
} | ||
append(type, buffer) { | ||
if (!buffer || !buffer.byteLength) { | ||
return Promise.resolve(); | ||
}, { | ||
key: "createOrChangeSource", | ||
value: function createOrChangeSource(type, mimeType) { | ||
this.createSource(type, mimeType); | ||
return this.changeType(type, mimeType); | ||
} | ||
if (!this._sourceBuffer[type]) | ||
return Promise.resolve(); | ||
return this._enqueueOp(type, () => { | ||
var _a; | ||
if (!this.mediaSource) | ||
return; | ||
(_a = this._sourceBuffer[type]) == null ? void 0 : _a.appendBuffer(buffer); | ||
}); | ||
} | ||
remove(type, startTime, endTime) { | ||
if (Object.keys(this._sourceBuffer).length === 1) | ||
return Promise.resolve(); | ||
return this._enqueueOp(type, () => { | ||
if (!this.mediaSource) | ||
return; | ||
const sb = this._sourceBuffer[type]; | ||
if (startTime >= endTime || !sb) { | ||
this._onSBUpdateEnd(type); | ||
return; | ||
}, { | ||
key: "append", | ||
value: function append(type, buffer) { | ||
var _this7 = this; | ||
if (!buffer || !buffer.byteLength) { | ||
return Promise.resolve(); | ||
} | ||
sb.remove(startTime, endTime); | ||
}); | ||
} | ||
clearBuffer(startTime, endTime) { | ||
let p; | ||
Object.keys(this._sourceBuffer).forEach((k) => { | ||
p = this._enqueueOp(k, () => { | ||
if (!this.mediaSource) | ||
if (!this._sourceBuffer[type]) | ||
return Promise.resolve(); | ||
return this._enqueueOp(type, function() { | ||
var _this7$_sourceBuffer$; | ||
if (!_this7.mediaSource) | ||
return; | ||
const sb = this._sourceBuffer[k]; | ||
(_this7$_sourceBuffer$ = _this7._sourceBuffer[type]) === null || _this7$_sourceBuffer$ === void 0 ? void 0 : _this7$_sourceBuffer$.appendBuffer(buffer); | ||
}); | ||
} | ||
}, { | ||
key: "remove", | ||
value: function remove(type, startTime, endTime) { | ||
var _this8 = this; | ||
if (Object.keys(this._sourceBuffer).length === 1) | ||
return Promise.resolve(); | ||
return this._enqueueOp(type, function() { | ||
if (!_this8.mediaSource) | ||
return; | ||
var sb = _this8._sourceBuffer[type]; | ||
if (startTime >= endTime || !sb) { | ||
_this8._onSBUpdateEnd(type); | ||
return; | ||
} | ||
sb.remove(startTime, endTime); | ||
}); | ||
}); | ||
return p; | ||
} | ||
clearAllBuffer() { | ||
let p; | ||
Object.keys(this._sourceBuffer).forEach((k) => { | ||
p = this._enqueueOp(k, () => { | ||
if (!this.mediaSource) | ||
} | ||
}, { | ||
key: "clearBuffer", | ||
value: function clearBuffer(startTime, endTime) { | ||
var _this9 = this; | ||
var p; | ||
Object.keys(this._sourceBuffer).forEach(function(k) { | ||
p = _this9._enqueueOp(k, function() { | ||
if (!_this9.mediaSource) | ||
return; | ||
var sb = _this9._sourceBuffer[k]; | ||
sb.remove(startTime, endTime); | ||
}); | ||
}); | ||
return p; | ||
} | ||
}, { | ||
key: "clearAllBuffer", | ||
value: function clearAllBuffer() { | ||
var _this10 = this; | ||
var p; | ||
Object.keys(this._sourceBuffer).forEach(function(k) { | ||
p = _this10._enqueueOp(k, function() { | ||
if (!_this10.mediaSource) | ||
return; | ||
var sb = _this10._sourceBuffer[k]; | ||
sb.remove(0, Buffer.end(Buffer.get(sb))); | ||
}); | ||
}); | ||
return p; | ||
} | ||
}, { | ||
key: "endOfStream", | ||
value: function endOfStream(reason) { | ||
var _this11 = this; | ||
if (!this.mediaSource || this.mediaSource.readyState !== "open") | ||
return Promise.resolve(); | ||
return this._enqueueBlockingOp(function() { | ||
var ms = _this11.mediaSource; | ||
if (!ms || ms.readyState !== "open") | ||
return; | ||
const sb = this._sourceBuffer[k]; | ||
sb.remove(0, Buffer.end(Buffer.get(sb))); | ||
if (reason) { | ||
ms.endOfStream(reason); | ||
} else { | ||
ms.endOfStream(); | ||
} | ||
}); | ||
}); | ||
return p; | ||
} | ||
endOfStream(reason) { | ||
if (!this.mediaSource || this.mediaSource.readyState !== "open") | ||
return Promise.resolve(); | ||
return this._enqueueBlockingOp(() => { | ||
const ms = this.mediaSource; | ||
if (!ms || ms.readyState !== "open") | ||
} | ||
}, { | ||
key: "setLiveSeekableRange", | ||
value: function setLiveSeekableRange(start, end) { | ||
var ms = this.mediaSource; | ||
if (start < 0 || end < start || !(ms !== null && ms !== void 0 && ms.setLiveSeekableRange) || ms.readyState !== "open") | ||
return; | ||
if (reason) { | ||
ms.endOfStream(reason); | ||
} else { | ||
ms.endOfStream(); | ||
} | ||
}); | ||
} | ||
setLiveSeekableRange(start, end) { | ||
const ms = this.mediaSource; | ||
if (start < 0 || end < start || !(ms == null ? void 0 : ms.setLiveSeekableRange) || ms.readyState !== "open") | ||
return; | ||
ms.setLiveSeekableRange(start, end); | ||
} | ||
buffered(type) { | ||
return Buffer.get(this._sourceBuffer[type]); | ||
} | ||
bufferStart(type) { | ||
return Buffer.start(this.buffered(type)); | ||
} | ||
bufferEnd(type) { | ||
return Buffer.end(this.buffered(type)); | ||
} | ||
_enqueueOp(type, exec) { | ||
if (!this.mediaSource) | ||
return Promise.resolve(); | ||
const queue = this._queue[type] = this._queue[type] || []; | ||
const op = { | ||
exec, | ||
promise: createPublicPromise() | ||
}; | ||
queue.push(op); | ||
if (queue.length === 1) { | ||
this._startQueue(type); | ||
ms.setLiveSeekableRange(start, end); | ||
} | ||
return op.promise; | ||
} | ||
async _enqueueBlockingOp(exec) { | ||
if (!this.mediaSource) | ||
return Promise.resolve(); | ||
const types = Object.keys(this._sourceBuffer); | ||
if (!types.length) { | ||
return exec(); | ||
}, { | ||
key: "buffered", | ||
value: function buffered(type) { | ||
return Buffer.get(this._sourceBuffer[type]); | ||
} | ||
const waiters = []; | ||
types.forEach((t) => { | ||
const queue = this._queue[t]; | ||
const prom = createPublicPromise(); | ||
waiters.push(prom); | ||
queue.push({ | ||
exec: () => prom.resolve(), | ||
promise: prom | ||
}); | ||
}, { | ||
key: "bufferStart", | ||
value: function bufferStart(type) { | ||
return Buffer.start(this.buffered(type)); | ||
} | ||
}, { | ||
key: "bufferEnd", | ||
value: function bufferEnd(type) { | ||
return Buffer.end(this.buffered(type)); | ||
} | ||
}, { | ||
key: "_enqueueOp", | ||
value: function _enqueueOp(type, exec) { | ||
if (!this.mediaSource) | ||
return Promise.resolve(); | ||
var queue = this._queue[type] = this._queue[type] || []; | ||
var op = { | ||
exec, | ||
promise: createPublicPromise() | ||
}; | ||
queue.push(op); | ||
if (queue.length === 1) { | ||
this._startQueue(t); | ||
this._startQueue(type); | ||
} | ||
}); | ||
return Promise.all(waiters).then(() => { | ||
try { | ||
return exec(); | ||
} finally { | ||
types.forEach((t) => { | ||
const queue = this._queue[t]; | ||
const sb = this._sourceBuffer[t]; | ||
queue == null ? void 0 : queue.shift(); | ||
if (!sb || !sb.updating) { | ||
this._startQueue(t); | ||
return op.promise; | ||
} | ||
}, { | ||
key: "_enqueueBlockingOp", | ||
value: function() { | ||
var _enqueueBlockingOp2 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee3(exec) { | ||
var _this12 = this; | ||
var types, waiters; | ||
return _regeneratorRuntime().wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
if (this.mediaSource) { | ||
_context3.next = 2; | ||
break; | ||
} | ||
return _context3.abrupt("return", Promise.resolve()); | ||
case 2: | ||
types = Object.keys(this._sourceBuffer); | ||
if (types.length) { | ||
_context3.next = 5; | ||
break; | ||
} | ||
return _context3.abrupt("return", exec()); | ||
case 5: | ||
waiters = []; | ||
types.forEach(function(t) { | ||
var queue = _this12._queue[t]; | ||
var prom = createPublicPromise(); | ||
waiters.push(prom); | ||
queue.push({ | ||
exec: function exec2() { | ||
return prom.resolve(); | ||
}, | ||
promise: prom | ||
}); | ||
if (queue.length === 1) { | ||
_this12._startQueue(t); | ||
} | ||
}); | ||
return _context3.abrupt("return", Promise.all(waiters).then(function() { | ||
try { | ||
return exec(); | ||
} finally { | ||
types.forEach(function(t) { | ||
var queue = _this12._queue[t]; | ||
var sb = _this12._sourceBuffer[t]; | ||
queue === null || queue === void 0 ? void 0 : queue.shift(); | ||
if (!sb || !sb.updating) { | ||
_this12._startQueue(t); | ||
} | ||
}); | ||
} | ||
})); | ||
case 8: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}); | ||
}, _callee3, this); | ||
})); | ||
function _enqueueBlockingOp(_x2) { | ||
return _enqueueBlockingOp2.apply(this, arguments); | ||
} | ||
}); | ||
} | ||
_startQueue(type) { | ||
const queue = this._queue[type]; | ||
if (queue) { | ||
const op = queue[0]; | ||
if (op) { | ||
try { | ||
op.exec(); | ||
} catch (error) { | ||
op.promise.reject(new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_OTHER, error)); | ||
queue.shift(); | ||
this._startQueue(type); | ||
return _enqueueBlockingOp; | ||
}() | ||
}, { | ||
key: "_startQueue", | ||
value: function _startQueue(type) { | ||
var queue = this._queue[type]; | ||
if (queue) { | ||
var op = queue[0]; | ||
if (op) { | ||
try { | ||
op.exec(); | ||
} catch (error) { | ||
op.promise.reject(new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_OTHER, error)); | ||
queue.shift(); | ||
this._startQueue(type); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
static isSupported(mime = 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"') { | ||
if (!MediaSource) | ||
return false; | ||
try { | ||
return MediaSource.isTypeSupported(mime); | ||
} catch (error) { | ||
return false; | ||
}], [{ | ||
key: "isSupported", | ||
value: function isSupported() { | ||
var mime = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"'; | ||
if (!MediaSource) | ||
return false; | ||
try { | ||
return MediaSource.isTypeSupported(mime); | ||
} catch (error) { | ||
return false; | ||
} | ||
} | ||
} | ||
} | ||
}]); | ||
return MSE2; | ||
}(); | ||
_defineProperty(MSE, "VIDEO", "video"); | ||
_defineProperty(MSE, "AUDIO", "audio"); | ||
export { MSE, MSEError, MSEErrorType }; |
@@ -0,4 +1,5 @@ | ||
import { objectSpread2 as _objectSpread2 } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { LoaderType, ResponseType } from "./types.js"; | ||
function getConfig(cfg) { | ||
return { | ||
return _objectSpread2({ | ||
loaderType: LoaderType.FETCH, | ||
@@ -29,5 +30,5 @@ retry: 0, | ||
integrity: void 0, | ||
...cfg | ||
}; | ||
onProcessMinLen: 1 | ||
}, cfg); | ||
} | ||
export { getConfig }; |
@@ -1,17 +0,23 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { inherits as _inherits, createSuper as _createSuper, classCallCheck as _classCallCheck, defineProperty as _defineProperty, assertThisInitialized as _assertThisInitialized, createClass as _createClass, wrapNativeSuper as _wrapNativeSuper } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.error.cause.js"; | ||
import { LoaderType } from "./types.js"; | ||
class NetError extends Error { | ||
constructor(url, request, response, msg) { | ||
super(msg); | ||
_defineProperty(this, "retryCount", 0); | ||
_defineProperty(this, "isTimeout", false); | ||
_defineProperty(this, "loaderType", LoaderType.FETCH); | ||
_defineProperty(this, "startTime", 0); | ||
_defineProperty(this, "endTime", 0); | ||
this.url = url; | ||
this.request = request; | ||
this.response = response; | ||
var NetError = /* @__PURE__ */ function(_Error) { | ||
_inherits(NetError2, _Error); | ||
var _super = _createSuper(NetError2); | ||
function NetError2(url, request, response, msg) { | ||
var _this; | ||
_classCallCheck(this, NetError2); | ||
_this = _super.call(this, msg); | ||
_defineProperty(_assertThisInitialized(_this), "retryCount", 0); | ||
_defineProperty(_assertThisInitialized(_this), "isTimeout", false); | ||
_defineProperty(_assertThisInitialized(_this), "loaderType", LoaderType.FETCH); | ||
_defineProperty(_assertThisInitialized(_this), "startTime", 0); | ||
_defineProperty(_assertThisInitialized(_this), "endTime", 0); | ||
_this.url = url; | ||
_this.request = request; | ||
_this.response = response; | ||
return _this; | ||
} | ||
} | ||
return _createClass(NetError2); | ||
}(/* @__PURE__ */ _wrapNativeSuper(Error)); | ||
export { NetError }; |
@@ -14,3 +14,4 @@ export class FetchLoader { | ||
_vid: string; | ||
load({ url, vid, timeout, responseType, onProgress, index, onTimeout, range, transformResponse, request, params, logger, method, headers, body, mode, credentials, cache, redirect, referrer, referrerPolicy }: { | ||
_onProcessMinLen: number; | ||
load({ url, vid, timeout, responseType, onProgress, index, onTimeout, range, transformResponse, request, params, logger, method, headers, body, mode, credentials, cache, redirect, referrer, referrerPolicy, onProcessMinLen, }: { | ||
url: any; | ||
@@ -37,2 +38,3 @@ vid: any; | ||
referrerPolicy: any; | ||
onProcessMinLen: any; | ||
}): any; | ||
@@ -43,2 +45,4 @@ resolve: any; | ||
_loadChunk(response: any, onProgress: any, st: any, firstByteTime: any): void; | ||
_cache: any; | ||
_writeIdx: number; | ||
get receiveLen(): number; | ||
@@ -45,0 +49,0 @@ set running(arg: boolean); |
@@ -1,5 +0,36 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.promise.js"; | ||
import "core-js/modules/es.array.iterator.js"; | ||
import "core-js/modules/es.typed-array.uint8-array.js"; | ||
import "core-js/modules/es.typed-array.at.js"; | ||
import "core-js/modules/esnext.typed-array.find-last.js"; | ||
import "core-js/modules/esnext.typed-array.find-last-index.js"; | ||
import "core-js/modules/es.typed-array.copy-within.js"; | ||
import "core-js/modules/es.typed-array.every.js"; | ||
import "core-js/modules/es.typed-array.fill.js"; | ||
import "core-js/modules/es.typed-array.filter.js"; | ||
import "core-js/modules/es.typed-array.find.js"; | ||
import "core-js/modules/es.typed-array.find-index.js"; | ||
import "core-js/modules/es.typed-array.find-last.js"; | ||
import "core-js/modules/es.typed-array.find-last-index.js"; | ||
import "core-js/modules/es.typed-array.for-each.js"; | ||
import "core-js/modules/es.typed-array.includes.js"; | ||
import "core-js/modules/es.typed-array.index-of.js"; | ||
import "core-js/modules/es.typed-array.iterator.js"; | ||
import "core-js/modules/es.typed-array.join.js"; | ||
import "core-js/modules/es.typed-array.last-index-of.js"; | ||
import "core-js/modules/es.typed-array.map.js"; | ||
import "core-js/modules/es.typed-array.reduce.js"; | ||
import "core-js/modules/es.typed-array.reduce-right.js"; | ||
import "core-js/modules/es.typed-array.reverse.js"; | ||
import "core-js/modules/es.typed-array.set.js"; | ||
import "core-js/modules/es.typed-array.slice.js"; | ||
import "core-js/modules/es.typed-array.some.js"; | ||
import "core-js/modules/es.typed-array.sort.js"; | ||
import "core-js/modules/es.typed-array.subarray.js"; | ||
import "core-js/modules/es.typed-array.to-locale-string.js"; | ||
import "core-js/modules/es.typed-array.to-string.js"; | ||
import "core-js/modules/esnext.typed-array.to-reversed.js"; | ||
import "core-js/modules/esnext.typed-array.to-sorted.js"; | ||
import "core-js/modules/esnext.typed-array.with.js"; | ||
import "core-js/modules/es.array.slice.js"; | ||
import { NetError } from "./error.js"; | ||
@@ -9,4 +40,6 @@ import { setUrlParams, getRangeValue, createResponse } from "./helper.js"; | ||
import SpeedSampler from "./speed-sampler.js"; | ||
class FetchLoader { | ||
constructor() { | ||
var CACHESIZE = 2 * 1024 * 1024; | ||
var FetchLoader = /* @__PURE__ */ function() { | ||
function FetchLoader2() { | ||
_classCallCheck(this, FetchLoader2); | ||
_defineProperty(this, "_abortController", null); | ||
@@ -23,226 +56,352 @@ _defineProperty(this, "_timeoutTimer", null); | ||
_defineProperty(this, "_vid", ""); | ||
_defineProperty(this, "_onProcessMinLen", 0); | ||
} | ||
load({ | ||
url, | ||
vid, | ||
timeout, | ||
responseType, | ||
onProgress, | ||
index, | ||
onTimeout, | ||
range, | ||
transformResponse, | ||
request, | ||
params, | ||
logger, | ||
method, | ||
headers, | ||
body, | ||
mode, | ||
credentials, | ||
cache, | ||
redirect, | ||
referrer, | ||
referrerPolicy | ||
}) { | ||
var _a; | ||
this._logger = logger; | ||
this._aborted = false; | ||
this._abortController = typeof AbortController !== "undefined" && new AbortController(); | ||
this._running = true; | ||
this._index = index; | ||
this._range = range || [0, 0]; | ||
this._vid = vid || url; | ||
const init = { | ||
method, | ||
headers, | ||
body, | ||
mode, | ||
credentials, | ||
cache, | ||
redirect, | ||
referrer, | ||
referrerPolicy, | ||
signal: (_a = this._abortController) == null ? void 0 : _a.signal | ||
}; | ||
let isTimeout = false; | ||
clearTimeout(this._timeoutTimer); | ||
url = setUrlParams(url, params); | ||
const rangeValue = getRangeValue(range); | ||
if (rangeValue) { | ||
if (request) { | ||
headers = request.headers; | ||
} else { | ||
headers = init.headers = init.headers || new Headers(); | ||
} | ||
if (headers instanceof Headers) { | ||
headers.append("Range", rangeValue); | ||
} else { | ||
headers.Range = rangeValue; | ||
} | ||
} | ||
if (timeout) { | ||
this._timeoutTimer = setTimeout(() => { | ||
isTimeout = true; | ||
this.cancel(); | ||
if (onTimeout) { | ||
const error = new NetError(url, init); | ||
error.isTimeout = true; | ||
onTimeout(error); | ||
_createClass(FetchLoader2, [{ | ||
key: "load", | ||
value: function load(_ref) { | ||
var _this$_abortControlle, _this = this; | ||
var url = _ref.url, vid = _ref.vid, timeout = _ref.timeout, responseType = _ref.responseType, onProgress = _ref.onProgress, index = _ref.index, onTimeout = _ref.onTimeout, range = _ref.range, transformResponse = _ref.transformResponse, request = _ref.request, params = _ref.params, logger = _ref.logger, method = _ref.method, headers = _ref.headers, body = _ref.body, mode = _ref.mode, credentials = _ref.credentials, cache = _ref.cache, redirect = _ref.redirect, referrer = _ref.referrer, referrerPolicy = _ref.referrerPolicy, onProcessMinLen = _ref.onProcessMinLen; | ||
this._logger = logger; | ||
this._aborted = false; | ||
this._onProcessMinLen = onProcessMinLen; | ||
this._abortController = typeof AbortController !== "undefined" && new AbortController(); | ||
this._running = true; | ||
this._index = index; | ||
this._range = range || [0, 0]; | ||
this._vid = vid || url; | ||
var init = { | ||
method, | ||
headers, | ||
body, | ||
mode, | ||
credentials, | ||
cache, | ||
redirect, | ||
referrer, | ||
referrerPolicy, | ||
signal: (_this$_abortControlle = this._abortController) === null || _this$_abortControlle === void 0 ? void 0 : _this$_abortControlle.signal | ||
}; | ||
var isTimeout = false; | ||
clearTimeout(this._timeoutTimer); | ||
url = setUrlParams(url, params); | ||
var rangeValue = getRangeValue(range); | ||
if (rangeValue) { | ||
if (request) { | ||
headers = request.headers; | ||
} else { | ||
headers = init.headers = init.headers || new Headers(); | ||
} | ||
}, timeout); | ||
} | ||
const startTime = Date.now(); | ||
this._logger.debug("[fetch load start], index,", index, ",range,", range); | ||
return new Promise((resolve, reject) => { | ||
fetch(request || url, request ? void 0 : init).then(async (response) => { | ||
clearTimeout(this._timeoutTimer); | ||
this._response = response; | ||
if (this._aborted || !this._running) | ||
return; | ||
if (transformResponse) { | ||
response = transformResponse(response, url) || response; | ||
} | ||
if (!response.ok) { | ||
throw new NetError(url, init, response, "bad network response"); | ||
} | ||
const firstByteTime = Date.now(); | ||
let data; | ||
if (responseType === ResponseType.TEXT) { | ||
data = await response.text(); | ||
this._running = false; | ||
} else if (responseType === ResponseType.JSON) { | ||
data = await response.json(); | ||
this._running = false; | ||
if (headers instanceof Headers) { | ||
headers.append("Range", rangeValue); | ||
} else { | ||
if (onProgress) { | ||
this.resolve = resolve; | ||
this.reject = reject; | ||
this._loadChunk(response, onProgress, startTime, firstByteTime); | ||
return; | ||
} else { | ||
data = await response.arrayBuffer(); | ||
data = new Uint8Array(data); | ||
this._running = false; | ||
const costTime = Date.now() - startTime; | ||
SpeedSampler.netSampling({ | ||
mTime: costTime, | ||
mBytes: data.byteLength, | ||
mSpeedInbPS: data.byteLength * 8 / (costTime / 1e3), | ||
mRTT: firstByteTime - startTime | ||
}); | ||
} | ||
headers.Range = rangeValue; | ||
} | ||
this._logger.debug("[fetch load end], index,", index, ",range,", range); | ||
resolve(createResponse(data, true, response, response.headers.get("Content-Length"), response.headers.get("age"), startTime, firstByteTime, index, range, this._vid)); | ||
}).catch((error) => { | ||
clearTimeout(this._timeoutTimer); | ||
this._running = false; | ||
if (this._aborted && !isTimeout) | ||
return; | ||
error = error instanceof NetError ? error : new NetError(url, init); | ||
error.startTime = startTime; | ||
error.endTime = Date.now(); | ||
error.isTimeout = isTimeout; | ||
reject(error); | ||
}); | ||
}); | ||
} | ||
async cancel() { | ||
if (this._aborted) | ||
return; | ||
this._aborted = true; | ||
this._running = false; | ||
if (this._response) { | ||
try { | ||
if (this._reader) { | ||
await this._reader.cancel(); | ||
} | ||
} catch (error) { | ||
} | ||
this._response = this._reader = null; | ||
} | ||
if (this._abortController) { | ||
try { | ||
this._abortController.abort(); | ||
} catch (error) { | ||
if (timeout) { | ||
this._timeoutTimer = setTimeout(function() { | ||
isTimeout = true; | ||
_this.cancel(); | ||
if (onTimeout) { | ||
var error = new NetError(url, init); | ||
error.isTimeout = true; | ||
onTimeout(error); | ||
} | ||
}, timeout); | ||
} | ||
this._abortController = null; | ||
var startTime = Date.now(); | ||
this._logger.debug("[fetch load start], index,", index, ",range,", range); | ||
return new Promise(function(resolve, reject) { | ||
fetch(request || url, request ? void 0 : init).then(/* @__PURE__ */ function() { | ||
var _ref2 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee(response) { | ||
var firstByteTime, data, costTime; | ||
return _regeneratorRuntime().wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
clearTimeout(_this._timeoutTimer); | ||
_this._response = response; | ||
if (!(_this._aborted || !_this._running)) { | ||
_context.next = 4; | ||
break; | ||
} | ||
return _context.abrupt("return"); | ||
case 4: | ||
if (transformResponse) { | ||
response = transformResponse(response, url) || response; | ||
} | ||
if (response.ok) { | ||
_context.next = 7; | ||
break; | ||
} | ||
throw new NetError(url, init, response, "bad network response"); | ||
case 7: | ||
firstByteTime = Date.now(); | ||
if (!(responseType === ResponseType.TEXT)) { | ||
_context.next = 15; | ||
break; | ||
} | ||
_context.next = 11; | ||
return response.text(); | ||
case 11: | ||
data = _context.sent; | ||
_this._running = false; | ||
_context.next = 36; | ||
break; | ||
case 15: | ||
if (!(responseType === ResponseType.JSON)) { | ||
_context.next = 22; | ||
break; | ||
} | ||
_context.next = 18; | ||
return response.json(); | ||
case 18: | ||
data = _context.sent; | ||
_this._running = false; | ||
_context.next = 36; | ||
break; | ||
case 22: | ||
if (!onProgress) { | ||
_context.next = 29; | ||
break; | ||
} | ||
_this.resolve = resolve; | ||
_this.reject = reject; | ||
_this._loadChunk(response, onProgress, startTime, firstByteTime); | ||
return _context.abrupt("return"); | ||
case 29: | ||
_context.next = 31; | ||
return response.arrayBuffer(); | ||
case 31: | ||
data = _context.sent; | ||
data = new Uint8Array(data); | ||
_this._running = false; | ||
costTime = Date.now() - startTime; | ||
SpeedSampler.netSampling({ | ||
mTime: costTime, | ||
mBytes: data.byteLength, | ||
mSpeedInbPS: data.byteLength * 8 / (costTime / 1e3), | ||
mRTT: firstByteTime - startTime | ||
}); | ||
case 36: | ||
_this._logger.debug("[fetch load end], index,", index, ",range,", range); | ||
resolve(createResponse(data, true, response, response.headers.get("Content-Length"), response.headers.get("age"), startTime, firstByteTime, index, range, _this._vid)); | ||
case 38: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee); | ||
})); | ||
return function(_x) { | ||
return _ref2.apply(this, arguments); | ||
}; | ||
}()).catch(function(error) { | ||
clearTimeout(_this._timeoutTimer); | ||
_this._running = false; | ||
if (_this._aborted && !isTimeout) | ||
return; | ||
error = error instanceof NetError ? error : new NetError(url, init); | ||
error.startTime = startTime; | ||
error.endTime = Date.now(); | ||
error.isTimeout = isTimeout; | ||
reject(error); | ||
}); | ||
}); | ||
} | ||
} | ||
_loadChunk(response, onProgress, st, firstByteTime) { | ||
if (!response.body || !response.body.getReader) { | ||
this._running = false; | ||
this.reject(NetError(response.url, "", response, "onProgress of bad response.body.getReader")); | ||
return; | ||
} | ||
const reader = this._reader = response.body.getReader(); | ||
let data; | ||
let startTime; | ||
let endTime; | ||
const pump = async () => { | ||
startTime = Date.now(); | ||
try { | ||
data = await reader.read(); | ||
endTime = Date.now(); | ||
} catch (e) { | ||
endTime = Date.now(); | ||
if (!this._aborted) { | ||
this._running = false; | ||
this.reject(e); | ||
} | ||
return; | ||
}, { | ||
key: "cancel", | ||
value: function() { | ||
var _cancel = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee2() { | ||
return _regeneratorRuntime().wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
if (!this._aborted) { | ||
_context2.next = 2; | ||
break; | ||
} | ||
return _context2.abrupt("return"); | ||
case 2: | ||
this._aborted = true; | ||
this._running = false; | ||
if (!this._response) { | ||
_context2.next = 14; | ||
break; | ||
} | ||
_context2.prev = 5; | ||
if (!this._reader) { | ||
_context2.next = 9; | ||
break; | ||
} | ||
_context2.next = 9; | ||
return this._reader.cancel(); | ||
case 9: | ||
_context2.next = 13; | ||
break; | ||
case 11: | ||
_context2.prev = 11; | ||
_context2.t0 = _context2["catch"](5); | ||
case 13: | ||
this._response = this._reader = null; | ||
case 14: | ||
if (this._abortController) { | ||
try { | ||
this._abortController.abort(); | ||
} catch (error) { | ||
} | ||
this._abortController = null; | ||
} | ||
case 15: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this, [[5, 11]]); | ||
})); | ||
function cancel() { | ||
return _cancel.apply(this, arguments); | ||
} | ||
const startByte = this._range[0] + this._receivedLength; | ||
if (this._aborted) { | ||
return cancel; | ||
}() | ||
}, { | ||
key: "_loadChunk", | ||
value: function _loadChunk(response, onProgress, st, firstByteTime) { | ||
var _this2 = this; | ||
if (!response.body || !response.body.getReader) { | ||
this._running = false; | ||
onProgress(void 0, false, { | ||
range: [startByte, startByte], | ||
vid: this._vid, | ||
index: this._index, | ||
startTime, | ||
endTime | ||
}, response); | ||
this.reject(NetError(response.url, "", response, "onProgress of bad response.body.getReader")); | ||
return; | ||
} | ||
this._receivedLength += data.value ? data.value.byteLength : 0; | ||
this._logger.debug("\u3010fetchLoader,onProgress call\u3011,task,", this._range, ", start,", startByte, ", end,", this._range[0] + this._receivedLength, ", done,", data.done); | ||
onProgress(data.value, data.done, { | ||
range: [startByte, this._range[0] + this._receivedLength], | ||
vid: this._vid, | ||
index: this._index, | ||
startTime, | ||
endTime | ||
}, response); | ||
const costTime = Date.now() - st; | ||
this._logger.debug("[fetchLoader SPEED], fetch speed(b/s),", this._receivedLength * 8 / (costTime / 1e3)); | ||
SpeedSampler.netSampling({ | ||
mTime: costTime, | ||
mBytes: this._receivedLength, | ||
mSpeedInbPS: this._receivedLength * 8 / (costTime / 1e3), | ||
mRTT: firstByteTime - st | ||
}); | ||
if (!data.done) { | ||
pump(); | ||
} else { | ||
this._running = false; | ||
this._logger.debug("[fetchLoader onProgress end],task,", this._range, ",done,", data.done); | ||
this.resolve(createResponse(data, true, response, response.headers.get("Content-Length"), response.headers.get("age"), startTime, firstByteTime, this._index, this._range, this._vid)); | ||
if (this._onProcessMinLen > 0) { | ||
this._cache = new Uint8Array(CACHESIZE); | ||
this._writeIdx = 0; | ||
} | ||
}; | ||
pump(); | ||
} | ||
get receiveLen() { | ||
return this._receivedLength; | ||
} | ||
get running() { | ||
return this._running; | ||
} | ||
set running(status) { | ||
this._running = status; | ||
} | ||
static isSupported() { | ||
return !!(typeof fetch !== "undefined"); | ||
} | ||
} | ||
var reader = this._reader = response.body.getReader(); | ||
var data; | ||
var startTime; | ||
var endTime; | ||
var pump = /* @__PURE__ */ function() { | ||
var _ref3 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee3() { | ||
var startByte, curLen, retData, temp, costTime; | ||
return _regeneratorRuntime().wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
startTime = Date.now(); | ||
_context3.prev = 1; | ||
_context3.next = 4; | ||
return reader.read(); | ||
case 4: | ||
data = _context3.sent; | ||
endTime = Date.now(); | ||
_context3.next = 13; | ||
break; | ||
case 8: | ||
_context3.prev = 8; | ||
_context3.t0 = _context3["catch"](1); | ||
endTime = Date.now(); | ||
if (!_this2._aborted) { | ||
_this2._running = false; | ||
_this2.reject(_context3.t0); | ||
} | ||
return _context3.abrupt("return"); | ||
case 13: | ||
startByte = _this2._range[0] + _this2._receivedLength; | ||
if (!_this2._aborted) { | ||
_context3.next = 18; | ||
break; | ||
} | ||
_this2._running = false; | ||
onProgress(void 0, false, { | ||
range: [startByte, startByte], | ||
vid: _this2._vid, | ||
index: _this2._index, | ||
startTime, | ||
endTime | ||
}, response); | ||
return _context3.abrupt("return"); | ||
case 18: | ||
curLen = data.value ? data.value.byteLength : 0; | ||
_this2._receivedLength += curLen; | ||
_this2._logger.debug("\u3010fetchLoader,onProgress call\u3011,task,", _this2._range, ", start,", startByte, ", end,", _this2._range[0] + _this2._receivedLength, ", done,", data.done); | ||
if (_this2._writeIdx + curLen >= _this2._onProcessMinLen || data.done) { | ||
retData = new Uint8Array(_this2._writeIdx + curLen); | ||
retData.set(_this2._cache.slice(0, _this2._writeIdx), 0); | ||
curLen > 0 && retData.set(data.value, _this2._writeIdx); | ||
_this2._writeIdx = 0; | ||
_this2._logger.debug("\u3010fetchLoader,onProgress enough\u3011,done,", data.done, ",len,", retData.byteLength, ", writeIdx,", _this2._writeIdx); | ||
} else { | ||
if (curLen > 0 && _this2._writeIdx + curLen < CACHESIZE) { | ||
_this2._cache.set(data.value, _this2._writeIdx); | ||
_this2._writeIdx += curLen; | ||
_this2._logger.debug("\u3010fetchLoader,onProgress cache\u3011,len,", curLen, ", writeIdx,", _this2._writeIdx); | ||
} else if (curLen > 0) { | ||
temp = new Uint8Array(_this2._writeIdx + curLen + 2048); | ||
_this2._logger.debug("\u3010fetchLoader,onProgress extra start\u3011,size,", _this2._writeIdx + curLen + 2048, ", datalen,", curLen, ", writeIdx,", _this2._writeIdx); | ||
temp.set(_this2._cache.slice(0, _this2._writeIdx), 0); | ||
curLen > 0 && temp.set(data.value, _this2._writeIdx); | ||
_this2._writeIdx += curLen; | ||
delete _this2._cache; | ||
_this2._cache = temp; | ||
_this2._logger.debug("\u3010fetchLoader,onProgress extra end\u3011,len,", curLen, ", writeIdx,", _this2._writeIdx); | ||
} | ||
} | ||
if (retData && retData.byteLength > 0 || data.done) { | ||
onProgress(retData, data.done, { | ||
range: [_this2._range[0] + _this2._receivedLength - retData.byteLength, _this2._range[0] + _this2._receivedLength], | ||
vid: _this2._vid, | ||
index: _this2._index, | ||
startTime, | ||
endTime | ||
}, response); | ||
} | ||
costTime = Date.now() - st; | ||
_this2._logger.debug("[fetchLoader SPEED], fetch speed(b/s),", _this2._receivedLength * 8 / (costTime / 1e3)); | ||
SpeedSampler.netSampling({ | ||
mTime: costTime, | ||
mBytes: _this2._receivedLength, | ||
mSpeedInbPS: _this2._receivedLength * 8 / (costTime / 1e3), | ||
mRTT: firstByteTime - st | ||
}); | ||
if (!data.done) { | ||
pump(); | ||
} else { | ||
_this2._running = false; | ||
_this2._logger.debug("[fetchLoader onProgress end],task,", _this2._range, ",done,", data.done); | ||
_this2.resolve(createResponse(data, true, response, response.headers.get("Content-Length"), response.headers.get("age"), startTime, firstByteTime, _this2._index, _this2._range, _this2._vid)); | ||
} | ||
case 27: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3, null, [[1, 8]]); | ||
})); | ||
return function pump2() { | ||
return _ref3.apply(this, arguments); | ||
}; | ||
}(); | ||
pump(); | ||
} | ||
}, { | ||
key: "receiveLen", | ||
get: function get() { | ||
return this._receivedLength; | ||
} | ||
}, { | ||
key: "running", | ||
get: function get() { | ||
return this._running; | ||
}, | ||
set: function set(status) { | ||
this._running = status; | ||
} | ||
}], [{ | ||
key: "isSupported", | ||
value: function isSupported() { | ||
return !!(typeof fetch !== "undefined"); | ||
} | ||
}]); | ||
return FetchLoader2; | ||
}(); | ||
export { FetchLoader }; |
@@ -0,1 +1,13 @@ | ||
import "core-js/modules/es.regexp.exec.js"; | ||
import "core-js/modules/es.string.replace.js"; | ||
import "core-js/modules/es.array.join.js"; | ||
import "core-js/modules/es.array.filter.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.array.map.js"; | ||
import "core-js/modules/es.object.keys.js"; | ||
import "core-js/modules/es.json.stringify.js"; | ||
import "core-js/modules/es.array.concat.js"; | ||
import "core-js/modules/es.array.slice.js"; | ||
import "core-js/modules/es.number.is-nan.js"; | ||
import "core-js/modules/es.number.constructor.js"; | ||
import { isDate, isObject } from "../is.js"; | ||
@@ -6,3 +18,3 @@ function getRangeValue(value) { | ||
} | ||
let ret = "bytes=" + value[0] + "-"; | ||
var ret = "bytes=" + value[0] + "-"; | ||
if (value[1]) | ||
@@ -20,4 +32,4 @@ ret += value[1]; | ||
return url; | ||
let v; | ||
const str = Object.keys(params).map((k) => { | ||
var v; | ||
var str = Object.keys(params).map(function(k) { | ||
v = params[k]; | ||
@@ -31,3 +43,3 @@ if (v === null || v === void 0) | ||
} | ||
return v.map((x) => { | ||
return v.map(function(x) { | ||
if (isDate(x)) { | ||
@@ -38,7 +50,7 @@ x = x.toISOString(); | ||
} | ||
return `${encode(k)}=${encode(x)}`; | ||
return "".concat(encode(k), "=").concat(encode(x)); | ||
}).join("&"); | ||
}).filter(Boolean).join("&"); | ||
if (str) { | ||
const hashIndex = url.indexOf("#"); | ||
var hashIndex = url.indexOf("#"); | ||
if (hashIndex !== -1) { | ||
@@ -56,3 +68,3 @@ url = url.slice(0, hashIndex); | ||
contentLength = 0; | ||
const option = { | ||
var option = { | ||
range, | ||
@@ -59,0 +71,0 @@ vid, |
@@ -1,2 +0,13 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.object.assign.js"; | ||
import "core-js/modules/es.array.push.js"; | ||
import "core-js/modules/es.array.concat.js"; | ||
import "core-js/modules/es.array.map.js"; | ||
import "core-js/modules/es.array.iterator.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.promise.js"; | ||
import "core-js/modules/es.string.iterator.js"; | ||
import "core-js/modules/web.dom-collections.iterator.js"; | ||
import "core-js/modules/es.promise.finally.js"; | ||
import "core-js/modules/es.regexp.exec.js"; | ||
import { FetchLoader } from "./fetch.js"; | ||
@@ -10,4 +21,5 @@ import { LoaderType } from "./types.js"; | ||
import SpeedSampler from "./speed-sampler.js"; | ||
class NetLoader { | ||
constructor(cfg) { | ||
var NetLoader = /* @__PURE__ */ function() { | ||
function NetLoader2(cfg) { | ||
_classCallCheck(this, NetLoader2); | ||
_defineProperty(this, "type", LoaderType.FETCH); | ||
@@ -23,64 +35,108 @@ _defineProperty(this, "_queue", []); | ||
} | ||
isFetch() { | ||
return this.type === LoaderType.FETCH; | ||
} | ||
static isFetchSupport() { | ||
return FetchLoader.isSupported(); | ||
} | ||
load(url, config = {}) { | ||
if (typeof url === "string" || !url) { | ||
config.url = url || config.url || this._config.url; | ||
} else { | ||
config = url; | ||
_createClass(NetLoader2, [{ | ||
key: "isFetch", | ||
value: function isFetch() { | ||
return this.type === LoaderType.FETCH; | ||
} | ||
config = Object.assign({}, this._config, config); | ||
if (config.params) | ||
config.params = Object.assign({}, config.params); | ||
if (config.headers && isPlainObject(config.headers)) | ||
config.headers = Object.assign({}, config.headers); | ||
if (config.body && isPlainObject(config.body)) | ||
config.body = Object.assign({}, config.body); | ||
if (config.transformRequest) { | ||
config = config.transformRequest(config) || config; | ||
}, { | ||
key: "load", | ||
value: function load(url) { | ||
var config = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | ||
if (typeof url === "string" || !url) { | ||
config.url = url || config.url || this._config.url; | ||
} else { | ||
config = url; | ||
} | ||
config = Object.assign({}, this._config, config); | ||
if (config.params) | ||
config.params = Object.assign({}, config.params); | ||
if (config.headers && isPlainObject(config.headers)) | ||
config.headers = Object.assign({}, config.headers); | ||
if (config.body && isPlainObject(config.body)) | ||
config.body = Object.assign({}, config.body); | ||
if (config.transformRequest) { | ||
config = config.transformRequest(config) || config; | ||
} | ||
config.logger = this.log; | ||
var task = new Task(this.type, config); | ||
this._queue.push(task); | ||
if (this._queue.length === 1 && (!this._currentTask || !this._currentTask.running)) { | ||
this._processTask(); | ||
} | ||
return task.promise; | ||
} | ||
config.logger = this.log; | ||
const task = new Task(this.type, config); | ||
this._queue.push(task); | ||
if (this._queue.length === 1 && (!this._currentTask || !this._currentTask.running)) { | ||
this._processTask(); | ||
}, { | ||
key: "cancel", | ||
value: function() { | ||
var _cancel = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee() { | ||
var cancels; | ||
return _regeneratorRuntime().wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
cancels = this._queue.map(function(t) { | ||
return t.cancel(); | ||
}).concat(this._alive.map(function(t) { | ||
return t.cancel(); | ||
})); | ||
if (this._currentTask) { | ||
cancels.push(this._currentTask.cancel()); | ||
} | ||
this._queue = []; | ||
this._alive = []; | ||
_context.next = 6; | ||
return Promise.all(cancels); | ||
case 6: | ||
_context.next = 8; | ||
return sleep(); | ||
case 8: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this); | ||
})); | ||
function cancel() { | ||
return _cancel.apply(this, arguments); | ||
} | ||
return cancel; | ||
}() | ||
}, { | ||
key: "_processTask", | ||
value: function _processTask() { | ||
var _this = this; | ||
this._currentTask = this._queue.shift(); | ||
if (!this._currentTask) | ||
return; | ||
if (this._currentTask.alive) { | ||
this._alive.push(this._currentTask); | ||
} | ||
this._currentTask.exec().catch(function(e) { | ||
}).finally(function() { | ||
_this._processTask(); | ||
}); | ||
} | ||
return task.promise; | ||
} | ||
async cancel() { | ||
const cancels = this._queue.map((t) => t.cancel()).concat(this._alive.map((t) => t.cancel())); | ||
if (this._currentTask) { | ||
cancels.push(this._currentTask.cancel()); | ||
}], [{ | ||
key: "isFetchSupport", | ||
value: function isFetchSupport() { | ||
return FetchLoader.isSupported(); | ||
} | ||
this._queue = []; | ||
this._alive = []; | ||
await Promise.all(cancels); | ||
await sleep(); | ||
} | ||
_processTask() { | ||
this._currentTask = this._queue.shift(); | ||
if (!this._currentTask) | ||
return; | ||
if (this._currentTask.alive) { | ||
this._alive.push(this._currentTask); | ||
}, { | ||
key: "getSpeed", | ||
value: function getSpeed() { | ||
return SpeedSampler.getSpeed(); | ||
} | ||
this._currentTask.exec().catch((e) => { | ||
}).finally(() => { | ||
this._processTask(); | ||
}); | ||
} | ||
static getSpeed() { | ||
return SpeedSampler.getSpeed(); | ||
} | ||
static getRealTimeSpeed() { | ||
return SpeedSampler.getRealTimeSpeed(); | ||
} | ||
static getRTT() { | ||
return SpeedSampler.getRTT(); | ||
} | ||
} | ||
}, { | ||
key: "getRealTimeSpeed", | ||
value: function getRealTimeSpeed() { | ||
return SpeedSampler.getRealTimeSpeed(); | ||
} | ||
}, { | ||
key: "getRTT", | ||
value: function getRTT() { | ||
return SpeedSampler.getRTT(); | ||
} | ||
}]); | ||
return NetLoader2; | ||
}(); | ||
export { NetLoader }; |
@@ -1,6 +0,11 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
const MaxQueueCapacity = 10; | ||
const INVALID_SPEED = 0; | ||
class SpeedSampler { | ||
constructor() { | ||
import { defineProperty as _defineProperty, createClass as _createClass, classCallCheck as _classCallCheck } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.array.map.js"; | ||
import "core-js/modules/es.array.push.js"; | ||
import "core-js/modules/es.array.sort.js"; | ||
import "core-js/modules/es.array.splice.js"; | ||
var MaxQueueCapacity = 10; | ||
var INVALID_SPEED = 0; | ||
var SpeedSampler = /* @__PURE__ */ function() { | ||
function SpeedSampler2() { | ||
_classCallCheck(this, SpeedSampler2); | ||
this._firstCheckpoint = 0; | ||
@@ -18,95 +23,117 @@ this._lastCheckpoint = 0; | ||
} | ||
reset() { | ||
this._firstCheckpoint = this._lastCheckpoint = 0; | ||
this._totalBytes = this._intervalBytes = 0; | ||
this._lastSecondBytes = 0; | ||
} | ||
addBytes(bytes) { | ||
if (this._firstCheckpoint === 0) { | ||
this._firstCheckpoint = this._now(); | ||
this._lastCheckpoint = this._firstCheckpoint; | ||
this._intervalBytes += bytes; | ||
this._totalBytes += bytes; | ||
} else if (this._now() - this._lastCheckpoint < 1e3) { | ||
this._intervalBytes += bytes; | ||
this._totalBytes += bytes; | ||
} else { | ||
this._lastSecondBytes = this._intervalBytes; | ||
this._intervalBytes = bytes; | ||
this._totalBytes += bytes; | ||
this._lastCheckpoint = this._now(); | ||
_createClass(SpeedSampler2, [{ | ||
key: "reset", | ||
value: function reset() { | ||
this._firstCheckpoint = this._lastCheckpoint = 0; | ||
this._totalBytes = this._intervalBytes = 0; | ||
this._lastSecondBytes = 0; | ||
} | ||
} | ||
get currentKBps() { | ||
this.addBytes(0); | ||
let durationSeconds = (this._now() - this._lastCheckpoint) / 1e3; | ||
if (durationSeconds === 0) | ||
durationSeconds = 1; | ||
return this._intervalBytes / durationSeconds / 1024; | ||
} | ||
get lastSecondKBps() { | ||
this.addBytes(0); | ||
if (this._lastSecondBytes !== 0) { | ||
return this._lastSecondBytes / 1024; | ||
} else { | ||
if (this._now() - this._lastCheckpoint >= 500) { | ||
return this.currentKBps; | ||
}, { | ||
key: "addBytes", | ||
value: function addBytes(bytes) { | ||
if (this._firstCheckpoint === 0) { | ||
this._firstCheckpoint = this._now(); | ||
this._lastCheckpoint = this._firstCheckpoint; | ||
this._intervalBytes += bytes; | ||
this._totalBytes += bytes; | ||
} else if (this._now() - this._lastCheckpoint < 1e3) { | ||
this._intervalBytes += bytes; | ||
this._totalBytes += bytes; | ||
} else { | ||
return 0; | ||
this._lastSecondBytes = this._intervalBytes; | ||
this._intervalBytes = bytes; | ||
this._totalBytes += bytes; | ||
this._lastCheckpoint = this._now(); | ||
} | ||
} | ||
} | ||
static getSpeed() { | ||
let speed = INVALID_SPEED; | ||
if (this._netRecords.length < 1) { | ||
return speed; | ||
}, { | ||
key: "currentKBps", | ||
get: function get() { | ||
this.addBytes(0); | ||
var durationSeconds = (this._now() - this._lastCheckpoint) / 1e3; | ||
if (durationSeconds === 0) | ||
durationSeconds = 1; | ||
return this._intervalBytes / durationSeconds / 1024; | ||
} | ||
const _recordsCopy = []; | ||
this._netRecords.map((item) => { | ||
_recordsCopy.push(item); | ||
}); | ||
_recordsCopy.sort((a, b) => a.mSpeedInbPS - b.mSpeedInbPS); | ||
const _len = _recordsCopy.length; | ||
let targetWeight = 0; | ||
for (let i = 0; i < _len; i++) { | ||
targetWeight += _recordsCopy[i].mBytes; | ||
}, { | ||
key: "lastSecondKBps", | ||
get: function get() { | ||
this.addBytes(0); | ||
if (this._lastSecondBytes !== 0) { | ||
return this._lastSecondBytes / 1024; | ||
} else { | ||
if (this._now() - this._lastCheckpoint >= 500) { | ||
return this.currentKBps; | ||
} else { | ||
return 0; | ||
} | ||
} | ||
} | ||
targetWeight /= 2; | ||
for (let i = 0; i < _len; i++) { | ||
targetWeight -= _recordsCopy[i].mBytes; | ||
if (targetWeight <= 0) { | ||
speed = _recordsCopy[i].mSpeedInbPS; | ||
break; | ||
}], [{ | ||
key: "getSpeed", | ||
value: function getSpeed() { | ||
var speed = INVALID_SPEED; | ||
if (this._netRecords.length < 1) { | ||
return speed; | ||
} | ||
var _recordsCopy = []; | ||
this._netRecords.map(function(item) { | ||
_recordsCopy.push(item); | ||
}); | ||
_recordsCopy.sort(function(a, b) { | ||
return a.mSpeedInbPS - b.mSpeedInbPS; | ||
}); | ||
var _len = _recordsCopy.length; | ||
var targetWeight = 0; | ||
for (var i = 0; i < _len; i++) { | ||
targetWeight += _recordsCopy[i].mBytes; | ||
} | ||
targetWeight /= 2; | ||
for (var _i = 0; _i < _len; _i++) { | ||
targetWeight -= _recordsCopy[_i].mBytes; | ||
if (targetWeight <= 0) { | ||
speed = _recordsCopy[_i].mSpeedInbPS; | ||
break; | ||
} | ||
} | ||
return speed < 0 ? INVALID_SPEED : speed; | ||
} | ||
return speed < 0 ? INVALID_SPEED : speed; | ||
} | ||
static getRealTimeSpeed() { | ||
return this._realTimeSpeed; | ||
} | ||
static getRTT() { | ||
if (this._netRecords.length < 1) { | ||
return 0; | ||
}, { | ||
key: "getRealTimeSpeed", | ||
value: function getRealTimeSpeed() { | ||
return this._realTimeSpeed; | ||
} | ||
const _recordsRTT = []; | ||
this._netRecords.map((item) => { | ||
_recordsRTT.push(item.mRTT); | ||
}); | ||
_recordsRTT.sort((a, b) => a - b); | ||
const _len = _recordsRTT.length; | ||
if (_len % 2 === 0) { | ||
return (_recordsRTT[_len / 2 - 1] + _recordsRTT[_len / 2]) / 2; | ||
} else { | ||
return _recordsRTT[Math.floor(_len / 2)]; | ||
}, { | ||
key: "getRTT", | ||
value: function getRTT() { | ||
if (this._netRecords.length < 1) { | ||
return 0; | ||
} | ||
var _recordsRTT = []; | ||
this._netRecords.map(function(item) { | ||
_recordsRTT.push(item.mRTT); | ||
}); | ||
_recordsRTT.sort(function(a, b) { | ||
return a - b; | ||
}); | ||
var _len = _recordsRTT.length; | ||
if (_len % 2 === 0) { | ||
return (_recordsRTT[_len / 2 - 1] + _recordsRTT[_len / 2]) / 2; | ||
} else { | ||
return _recordsRTT[Math.floor(_len / 2)]; | ||
} | ||
} | ||
} | ||
static netSampling(record) { | ||
this._netRecords.push(record); | ||
this._realTimeSpeed = record.mSpeedInbPS; | ||
if (this._netRecords.length > MaxQueueCapacity) { | ||
this._netRecords.splice(0, 1); | ||
}, { | ||
key: "netSampling", | ||
value: function netSampling(record) { | ||
this._netRecords.push(record); | ||
this._realTimeSpeed = record.mSpeedInbPS; | ||
if (this._netRecords.length > MaxQueueCapacity) { | ||
this._netRecords.splice(0, 1); | ||
} | ||
} | ||
} | ||
} | ||
}]); | ||
return SpeedSampler2; | ||
}(); | ||
_defineProperty(SpeedSampler, "_netRecords", []); | ||
export { SpeedSampler as default }; |
@@ -0,1 +1,2 @@ | ||
import { createClass as _createClass, objectWithoutProperties as _objectWithoutProperties, classCallCheck as _classCallCheck, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { FetchLoader } from "./fetch.js"; | ||
@@ -6,4 +7,6 @@ import { XhrLoader } from "./xhr.js"; | ||
import { Logger } from "../logger.js"; | ||
class Task { | ||
constructor(type, config) { | ||
var _excluded = ["retry", "retryDelay", "onRetryError", "transformError"]; | ||
var Task = /* @__PURE__ */ function() { | ||
function Task2(type, config) { | ||
_classCallCheck(this, Task2); | ||
this.promise = createPublicPromise(); | ||
@@ -20,54 +23,105 @@ this.alive = !!config.onProgress; | ||
} | ||
exec() { | ||
const { | ||
retry, | ||
retryDelay, | ||
onRetryError, | ||
transformError, | ||
...rest | ||
} = this._config; | ||
const request = async () => { | ||
try { | ||
const response = await this._loader.load(rest); | ||
this.promise.resolve(response); | ||
} catch (e) { | ||
this._loader.running = false; | ||
this._logger.debug("[task request catch err]", e); | ||
if (this._canceled) | ||
return; | ||
if (e.response && e.response.status >= 400 && e.response.status <= 599) { | ||
this.promise.reject(e); | ||
return; | ||
} | ||
e.loaderType = this._loaderType; | ||
e.retryCount = this._retryCount; | ||
let error = e; | ||
if (transformError) { | ||
error = transformError(error) || error; | ||
} | ||
if (onRetryError && this._retryCount > 0) | ||
onRetryError(error, this._retryCount, retry); | ||
this._retryCount++; | ||
if (this._retryCount <= retry) { | ||
clearTimeout(this._retryTimer); | ||
this._logger.debug("[task request setTimeout],retry", this._retryCount, ",retry range,", rest.range); | ||
this._retryTimer = setTimeout(request, retryDelay); | ||
return; | ||
} | ||
this.promise.reject(error); | ||
_createClass(Task2, [{ | ||
key: "exec", | ||
value: function exec() { | ||
var _this = this; | ||
var _this$_config = this._config, retry = _this$_config.retry, retryDelay = _this$_config.retryDelay, onRetryError = _this$_config.onRetryError, transformError = _this$_config.transformError, rest = _objectWithoutProperties(_this$_config, _excluded); | ||
var request = /* @__PURE__ */ function() { | ||
var _ref = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee() { | ||
var response, error; | ||
return _regeneratorRuntime().wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_context.prev = 0; | ||
_context.next = 3; | ||
return _this._loader.load(rest); | ||
case 3: | ||
response = _context.sent; | ||
_this.promise.resolve(response); | ||
_context.next = 28; | ||
break; | ||
case 7: | ||
_context.prev = 7; | ||
_context.t0 = _context["catch"](0); | ||
_this._loader.running = false; | ||
_this._logger.debug("[task request catch err]", _context.t0); | ||
if (!_this._canceled) { | ||
_context.next = 13; | ||
break; | ||
} | ||
return _context.abrupt("return"); | ||
case 13: | ||
if (!(_context.t0.response && _context.t0.response.status >= 400 && _context.t0.response.status <= 599)) { | ||
_context.next = 16; | ||
break; | ||
} | ||
_this.promise.reject(_context.t0); | ||
return _context.abrupt("return"); | ||
case 16: | ||
_context.t0.loaderType = _this._loaderType; | ||
_context.t0.retryCount = _this._retryCount; | ||
error = _context.t0; | ||
if (transformError) { | ||
error = transformError(error) || error; | ||
} | ||
if (onRetryError && _this._retryCount > 0) | ||
onRetryError(error, _this._retryCount, retry); | ||
_this._retryCount++; | ||
if (!(_this._retryCount <= retry)) { | ||
_context.next = 27; | ||
break; | ||
} | ||
clearTimeout(_this._retryTimer); | ||
_this._logger.debug("[task request setTimeout],retry", _this._retryCount, ",retry range,", rest.range); | ||
_this._retryTimer = setTimeout(request, retryDelay); | ||
return _context.abrupt("return"); | ||
case 27: | ||
_this.promise.reject(error); | ||
case 28: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, null, [[0, 7]]); | ||
})); | ||
return function request2() { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}(); | ||
request(); | ||
return this.promise; | ||
} | ||
}, { | ||
key: "cancel", | ||
value: function() { | ||
var _cancel = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee2() { | ||
return _regeneratorRuntime().wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
clearTimeout(this._retryTimer); | ||
this._canceled = true; | ||
this._loader.running = false; | ||
return _context2.abrupt("return", this._loader.cancel()); | ||
case 4: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this); | ||
})); | ||
function cancel() { | ||
return _cancel.apply(this, arguments); | ||
} | ||
}; | ||
request(); | ||
return this.promise; | ||
} | ||
async cancel() { | ||
clearTimeout(this._retryTimer); | ||
this._canceled = true; | ||
this._loader.running = false; | ||
return this._loader.cancel(); | ||
} | ||
get running() { | ||
return this._loader && this._loader.running; | ||
} | ||
} | ||
return cancel; | ||
}() | ||
}, { | ||
key: "running", | ||
get: function get() { | ||
return this._loader && this._loader.running; | ||
} | ||
}]); | ||
return Task2; | ||
}(); | ||
export { Task }; |
@@ -1,6 +0,6 @@ | ||
const LoaderType = { | ||
var LoaderType = { | ||
FETCH: "fetch", | ||
XHR: "xhr" | ||
}; | ||
const ResponseType = { | ||
var ResponseType = { | ||
ARRAY_BUFFER: "arraybuffer", | ||
@@ -7,0 +7,0 @@ TEXT: "text", |
@@ -1,5 +0,40 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { createClass as _createClass, objectSpread2 as _objectSpread2, createForOfIteratorHelper as _createForOfIteratorHelper, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.promise.js"; | ||
import "core-js/modules/web.dom-collections.for-each.js"; | ||
import "core-js/modules/es.object.keys.js"; | ||
import "core-js/modules/es.array.iterator.js"; | ||
import "core-js/modules/es.typed-array.uint8-array.js"; | ||
import "core-js/modules/es.typed-array.at.js"; | ||
import "core-js/modules/esnext.typed-array.find-last.js"; | ||
import "core-js/modules/esnext.typed-array.find-last-index.js"; | ||
import "core-js/modules/es.typed-array.copy-within.js"; | ||
import "core-js/modules/es.typed-array.every.js"; | ||
import "core-js/modules/es.typed-array.fill.js"; | ||
import "core-js/modules/es.typed-array.filter.js"; | ||
import "core-js/modules/es.typed-array.find.js"; | ||
import "core-js/modules/es.typed-array.find-index.js"; | ||
import "core-js/modules/es.typed-array.find-last.js"; | ||
import "core-js/modules/es.typed-array.find-last-index.js"; | ||
import "core-js/modules/es.typed-array.for-each.js"; | ||
import "core-js/modules/es.typed-array.includes.js"; | ||
import "core-js/modules/es.typed-array.index-of.js"; | ||
import "core-js/modules/es.typed-array.iterator.js"; | ||
import "core-js/modules/es.typed-array.join.js"; | ||
import "core-js/modules/es.typed-array.last-index-of.js"; | ||
import "core-js/modules/es.typed-array.map.js"; | ||
import "core-js/modules/es.typed-array.reduce.js"; | ||
import "core-js/modules/es.typed-array.reduce-right.js"; | ||
import "core-js/modules/es.typed-array.reverse.js"; | ||
import "core-js/modules/es.typed-array.set.js"; | ||
import "core-js/modules/es.typed-array.slice.js"; | ||
import "core-js/modules/es.typed-array.some.js"; | ||
import "core-js/modules/es.typed-array.sort.js"; | ||
import "core-js/modules/es.typed-array.subarray.js"; | ||
import "core-js/modules/es.typed-array.to-locale-string.js"; | ||
import "core-js/modules/es.typed-array.to-string.js"; | ||
import "core-js/modules/esnext.typed-array.to-reversed.js"; | ||
import "core-js/modules/esnext.typed-array.to-sorted.js"; | ||
import "core-js/modules/esnext.typed-array.with.js"; | ||
import "core-js/modules/es.string.trim.js"; | ||
import "core-js/modules/es.array.join.js"; | ||
import "core-js/modules/es.array.slice.js"; | ||
import { NetError } from "./error.js"; | ||
@@ -9,4 +44,5 @@ import { setUrlParams, getRangeValue, createResponse } from "./helper.js"; | ||
import SpeedSampler from "./speed-sampler.js"; | ||
class XhrLoader { | ||
constructor() { | ||
var XhrLoader = /* @__PURE__ */ function() { | ||
function XhrLoader2() { | ||
_classCallCheck(this, XhrLoader2); | ||
_defineProperty(this, "_xhr", null); | ||
@@ -42,231 +78,264 @@ _defineProperty(this, "_aborted", false); | ||
} | ||
load(req) { | ||
clearTimeout(this._timeoutTimer); | ||
this._logger = req.logger; | ||
this._range = req.range || [0, 0]; | ||
this._onProgress = req.onProgress; | ||
this._index = req.index; | ||
this._headers = req.headers; | ||
this._withCredentials = req.credentials === "include" || req.credentials === "same-origin"; | ||
this._timeout = req.timeout || null; | ||
this._runing = true; | ||
this._vid = req.vid || req.url; | ||
this._responseType = req.responseType; | ||
this._firstRtt = -1; | ||
this._onTimeout = req.onTimeout; | ||
this._request = req.request; | ||
this._credentials = req.credentials; | ||
this._logger.debug("\u3010xhrLoader task\u3011, range", this._range); | ||
this._url = setUrlParams(req.url, req.params); | ||
const startTime = Date.now(); | ||
return new Promise((resolve, reject) => { | ||
this._loadCompleteResolve = resolve; | ||
this._loadCompleteReject = reject; | ||
this._startLoad(); | ||
}).catch((error) => { | ||
_createClass(XhrLoader2, [{ | ||
key: "load", | ||
value: function load(req) { | ||
var _this = this; | ||
clearTimeout(this._timeoutTimer); | ||
this._runing = false; | ||
if (this._aborted) | ||
return; | ||
error = error instanceof NetError ? error : new NetError(this._url, this._request); | ||
error.startTime = startTime; | ||
error.endTime = Date.now(); | ||
throw error; | ||
}); | ||
} | ||
_startLoad() { | ||
let range = null; | ||
if (this._range && this._range.length > 1) { | ||
if (this._onProgress) { | ||
this._subRangeStartTime = Date.now(); | ||
this._firstRtt = -1; | ||
const chunkSize = this._currentChunkSizeKB * 1024; | ||
const from = this._range[0] + this._receivedLength; | ||
let to = this._range[1]; | ||
if (chunkSize < this._range[1] - from) { | ||
to = from + chunkSize; | ||
this._logger = req.logger; | ||
this._range = req.range || [0, 0]; | ||
this._onProgress = req.onProgress; | ||
this._index = req.index; | ||
this._headers = req.headers; | ||
this._withCredentials = req.credentials === "include" || req.credentials === "same-origin"; | ||
this._timeout = req.timeout || null; | ||
this._runing = true; | ||
this._vid = req.vid || req.url; | ||
this._responseType = req.responseType; | ||
this._firstRtt = -1; | ||
this._onTimeout = req.onTimeout; | ||
this._request = req.request; | ||
this._credentials = req.credentials; | ||
this._logger.debug("\u3010xhrLoader task\u3011, range", this._range); | ||
this._url = setUrlParams(req.url, req.params); | ||
var startTime = Date.now(); | ||
return new Promise(function(resolve, reject) { | ||
_this._loadCompleteResolve = resolve; | ||
_this._loadCompleteReject = reject; | ||
_this._startLoad(); | ||
}).catch(function(error) { | ||
clearTimeout(_this._timeoutTimer); | ||
_this._runing = false; | ||
if (_this._aborted) | ||
return; | ||
error = error instanceof NetError ? error : new NetError(_this._url, _this._request); | ||
error.startTime = startTime; | ||
error.endTime = Date.now(); | ||
throw error; | ||
}); | ||
} | ||
}, { | ||
key: "_startLoad", | ||
value: function _startLoad() { | ||
var range = null; | ||
if (this._range && this._range.length > 1) { | ||
if (this._onProgress) { | ||
this._subRangeStartTime = Date.now(); | ||
this._firstRtt = -1; | ||
var chunkSize = this._currentChunkSizeKB * 1024; | ||
var from = this._range[0] + this._receivedLength; | ||
var to = this._range[1]; | ||
if (chunkSize < this._range[1] - from) { | ||
to = from + chunkSize; | ||
} | ||
range = [from, to]; | ||
this._logger.debug("[xhr_loader->],tast :", this._range, ", SubRange, ", range); | ||
} else { | ||
range = this._range; | ||
this._logger.debug("[xhr_loader->],tast :", this._range, ", allRange, ", range); | ||
} | ||
range = [from, to]; | ||
this._logger.debug("[xhr_loader->],tast :", this._range, ", SubRange, ", range); | ||
} else { | ||
range = this._range; | ||
this._logger.debug("[xhr_loader->],tast :", this._range, ", allRange, ", range); | ||
} | ||
this._internalOpen(range); | ||
} | ||
this._internalOpen(range); | ||
} | ||
_internalOpen(range) { | ||
try { | ||
this._startTime = Date.now(); | ||
const xhr = this._xhr = new XMLHttpRequest(); | ||
xhr.open(this._method || "GET", this._url, true); | ||
xhr.responseType = this._responseType; | ||
this._timeout && (xhr.timeout = this._timeout); | ||
xhr.withCredentials = this._credentials; | ||
xhr.onload = this._onLoad.bind(this); | ||
xhr.onreadystatechange = this._onReadyStatechange.bind(this); | ||
xhr.onerror = (event) => { | ||
this._running = false; | ||
this._loadCompleteReject(event); | ||
}; | ||
xhr.ontimeout = (event) => { | ||
this.cancel(); | ||
if (this._onTimeout) { | ||
const error = new NetError(this._url, this._request); | ||
error.isTimeout = true; | ||
this._onTimeout(error); | ||
}, { | ||
key: "_internalOpen", | ||
value: function _internalOpen(range) { | ||
var _this2 = this; | ||
try { | ||
this._startTime = Date.now(); | ||
var xhr = this._xhr = new XMLHttpRequest(); | ||
xhr.open(this._method || "GET", this._url, true); | ||
xhr.responseType = this._responseType; | ||
this._timeout && (xhr.timeout = this._timeout); | ||
xhr.withCredentials = this._credentials; | ||
xhr.onload = this._onLoad.bind(this); | ||
xhr.onreadystatechange = this._onReadyStatechange.bind(this); | ||
xhr.onerror = function(event) { | ||
_this2._running = false; | ||
_this2._loadCompleteReject(event); | ||
}; | ||
xhr.ontimeout = function(event) { | ||
_this2.cancel(); | ||
if (_this2._onTimeout) { | ||
var error = new NetError(_this2._url, _this2._request); | ||
error.isTimeout = true; | ||
_this2._onTimeout(error); | ||
} | ||
_this2._loadCompleteReject(event); | ||
}; | ||
var rangeValue = getRangeValue(range); | ||
var headers = null; | ||
if (rangeValue) { | ||
headers = this._headers || {}; | ||
headers.Range = rangeValue; | ||
} | ||
this._loadCompleteReject(event); | ||
}; | ||
const rangeValue = getRangeValue(range); | ||
let headers = null; | ||
if (rangeValue) { | ||
headers = this._headers || {}; | ||
headers.Range = rangeValue; | ||
if (headers) { | ||
Object.keys(headers).forEach(function(k) { | ||
xhr.setRequestHeader(k, headers[k]); | ||
}); | ||
} | ||
this._logger.debug("[xhr.send->] tast,", this._range, ",load sub range, ", range); | ||
xhr.send(); | ||
} catch (e) { | ||
this._loadCompleteReject(e); | ||
} | ||
if (headers) { | ||
Object.keys(headers).forEach((k) => { | ||
xhr.setRequestHeader(k, headers[k]); | ||
}); | ||
} | ||
this._logger.debug("[xhr.send->] tast,", this._range, ",load sub range, ", range); | ||
xhr.send(); | ||
} catch (e) { | ||
this._loadCompleteReject(e); | ||
} | ||
} | ||
_onReadyStatechange(e) { | ||
const xhr = e.target; | ||
if (xhr.readyState === 2) { | ||
this._firstRtt < 0 && (this._firstRtt = Date.now()); | ||
} | ||
} | ||
_onLoad(e) { | ||
const status = e.target.status; | ||
if (status < 200 || status > 299) { | ||
return this._loadCompleteReject(new NetError(this._url, null, { | ||
...e.target.response, | ||
status | ||
}, "bad response,status:" + status)); | ||
} | ||
let KBps = this._speedSampler.lastSecondKBps; | ||
if (KBps === 0) { | ||
this._zeroSpeedChunkCount++; | ||
if (this._zeroSpeedChunkCount >= 3) { | ||
KBps = this._speedSampler.currentKBps; | ||
}, { | ||
key: "_onReadyStatechange", | ||
value: function _onReadyStatechange(e) { | ||
var xhr = e.target; | ||
if (xhr.readyState === 2) { | ||
this._firstRtt < 0 && (this._firstRtt = Date.now()); | ||
} | ||
} | ||
if (KBps !== 0) { | ||
const normalized = this._normalizeSpeed(KBps); | ||
if (this._currentSpeedNormalized !== normalized) { | ||
this._currentSpeedNormalized = normalized; | ||
this._currentChunkSizeKB = normalized; | ||
}, { | ||
key: "_onLoad", | ||
value: function _onLoad(e) { | ||
var status = e.target.status; | ||
if (status < 200 || status > 299) { | ||
return this._loadCompleteReject(new NetError(this._url, null, _objectSpread2(_objectSpread2({}, e.target.response), {}, { | ||
status | ||
}), "bad response,status:" + status)); | ||
} | ||
} | ||
let data = null; | ||
let done = false; | ||
let byteStart; | ||
if (this._responseType === ResponseType.ARRAY_BUFFER) { | ||
const chunk = new Uint8Array(e.target.response); | ||
byteStart = this._range[0] + this._receivedLength; | ||
if (chunk && chunk.byteLength > 0) { | ||
this._receivedLength += chunk.byteLength; | ||
const costTime = Date.now() - this._subRangeStartTime; | ||
this._speedSampler.addBytes(chunk.byteLength); | ||
SpeedSampler.netSampling({ | ||
mTime: costTime, | ||
mBytes: this._receivedLength, | ||
mSpeedInbPS: this._receivedLength * 8 / (costTime / 1e3), | ||
mRTT: this._firstRtt - this._subRangeStartTime | ||
}); | ||
var KBps = this._speedSampler.lastSecondKBps; | ||
if (KBps === 0) { | ||
this._zeroSpeedChunkCount++; | ||
if (this._zeroSpeedChunkCount >= 3) { | ||
KBps = this._speedSampler.currentKBps; | ||
} | ||
} | ||
data = chunk; | ||
if (this._range.length > 1 && this._range[1] && this._receivedLength < this._range[1] - this._range[0]) { | ||
done = false; | ||
if (KBps !== 0) { | ||
var normalized = this._normalizeSpeed(KBps); | ||
if (this._currentSpeedNormalized !== normalized) { | ||
this._currentSpeedNormalized = normalized; | ||
this._currentChunkSizeKB = normalized; | ||
} | ||
} | ||
var data = null; | ||
var done = false; | ||
var byteStart; | ||
if (this._responseType === ResponseType.ARRAY_BUFFER) { | ||
var chunk = new Uint8Array(e.target.response); | ||
byteStart = this._range[0] + this._receivedLength; | ||
if (chunk && chunk.byteLength > 0) { | ||
this._receivedLength += chunk.byteLength; | ||
var costTime = Date.now() - this._subRangeStartTime; | ||
this._speedSampler.addBytes(chunk.byteLength); | ||
SpeedSampler.netSampling({ | ||
mTime: costTime, | ||
mBytes: this._receivedLength, | ||
mSpeedInbPS: this._receivedLength * 8 / (costTime / 1e3), | ||
mRTT: this._firstRtt - this._subRangeStartTime | ||
}); | ||
} | ||
data = chunk; | ||
if (this._range.length > 1 && this._range[1] && this._receivedLength < this._range[1] - this._range[0]) { | ||
done = false; | ||
} else { | ||
done = true; | ||
} | ||
this._logger.debug("[xhr load done->], tast :", this._range, ", start", byteStart, "end ", this._range[0] + this._receivedLength, ",dataLen,", chunk ? chunk.byteLength : 0, ",receivedLength", this._receivedLength, ",index,", this._index, ", done,", done); | ||
} else { | ||
done = true; | ||
data = e.target.response; | ||
} | ||
this._logger.debug("[xhr load done->], tast :", this._range, ", start", byteStart, "end ", this._range[0] + this._receivedLength, ",dataLen,", chunk ? chunk.byteLength : 0, ",receivedLength", this._receivedLength, ",index,", this._index, ", done,", done); | ||
} else { | ||
done = true; | ||
data = e.target.response; | ||
var response = { | ||
ok: status >= 200 && status < 300, | ||
status, | ||
statusText: this._xhr.statusText, | ||
url: this._xhr.responseURL, | ||
headers: this._getHeaders(this._xhr), | ||
body: this._xhr.response | ||
}; | ||
if (this._transformResponse) { | ||
response = this._transformResponse(response, this._url) || response; | ||
} | ||
if (this._onProgress) { | ||
this._onProgress(data, done, { | ||
index: this._index, | ||
vid: this._vid, | ||
range: [byteStart, this._range[0] + this._receivedLength], | ||
startTime: this._startTime, | ||
endTime: Date.now() | ||
}, response); | ||
} | ||
if (!done) { | ||
this._startLoad(); | ||
} else { | ||
this._runing = false; | ||
this._loadCompleteResolve && this._loadCompleteResolve(createResponse(this._onProgress ? null : data, done, response, response.headers["content-length"], response.headers.age, this._startTime, -1, this._index, this._range, this._vid)); | ||
} | ||
} | ||
let response = { | ||
ok: status >= 200 && status < 300, | ||
status, | ||
statusText: this._xhr.statusText, | ||
url: this._xhr.responseURL, | ||
headers: this._getHeaders(this._xhr), | ||
body: this._xhr.response | ||
}; | ||
if (this._transformResponse) { | ||
response = this._transformResponse(response, this._url) || response; | ||
}, { | ||
key: "_normalizeSpeed", | ||
value: function _normalizeSpeed(input) { | ||
var list = this._chunkSizeKBList; | ||
var last = list.length - 1; | ||
var mid = 0; | ||
var lbound = 0; | ||
var ubound = last; | ||
if (input < list[0]) { | ||
return list[0]; | ||
} | ||
while (lbound <= ubound) { | ||
mid = lbound + Math.floor((ubound - lbound) / 2); | ||
if (mid === last || input >= list[mid] && input < list[mid + 1]) { | ||
return list[mid]; | ||
} else if (list[mid] < input) { | ||
lbound = mid + 1; | ||
} else { | ||
ubound = mid - 1; | ||
} | ||
} | ||
} | ||
if (this._onProgress) { | ||
this._onProgress(data, done, { | ||
index: this._index, | ||
vid: this._vid, | ||
range: [byteStart, this._range[0] + this._receivedLength], | ||
startTime: this._startTime, | ||
endTime: Date.now() | ||
}, response); | ||
} | ||
if (!done) { | ||
this._startLoad(); | ||
} else { | ||
}, { | ||
key: "cancel", | ||
value: function cancel() { | ||
if (this._aborted) | ||
return; | ||
this._aborted = true; | ||
this._runing = false; | ||
this._loadCompleteResolve && this._loadCompleteResolve(createResponse(this._onProgress ? null : data, done, response, response.headers["content-length"], response.headers.age, this._startTime, -1, this._index, this._range, this._vid)); | ||
if (this._xhr) { | ||
return this._xhr.abort(); | ||
} | ||
} | ||
} | ||
_normalizeSpeed(input) { | ||
const list = this._chunkSizeKBList; | ||
const last = list.length - 1; | ||
let mid = 0; | ||
let lbound = 0; | ||
let ubound = last; | ||
if (input < list[0]) { | ||
return list[0]; | ||
}, { | ||
key: "receiveLen", | ||
get: function get() { | ||
return this._receivedLength; | ||
} | ||
while (lbound <= ubound) { | ||
mid = lbound + Math.floor((ubound - lbound) / 2); | ||
if (mid === last || input >= list[mid] && input < list[mid + 1]) { | ||
return list[mid]; | ||
} else if (list[mid] < input) { | ||
lbound = mid + 1; | ||
} else { | ||
ubound = mid - 1; | ||
}, { | ||
key: "running", | ||
get: function get() { | ||
return this._running; | ||
}, | ||
set: function set(status) { | ||
this._running = status; | ||
} | ||
}, { | ||
key: "_getHeaders", | ||
value: function _getHeaders(xhr) { | ||
var headerLines = xhr.getAllResponseHeaders().trim().split("\r\n"); | ||
var headers = {}; | ||
var _iterator = _createForOfIteratorHelper(headerLines), _step; | ||
try { | ||
for (_iterator.s(); !(_step = _iterator.n()).done; ) { | ||
var header = _step.value; | ||
var parts = header.split(": "); | ||
headers[parts[0].toLowerCase()] = parts.slice(1).join(": "); | ||
} | ||
} catch (err) { | ||
_iterator.e(err); | ||
} finally { | ||
_iterator.f(); | ||
} | ||
return headers; | ||
} | ||
} | ||
cancel() { | ||
if (this._aborted) | ||
return; | ||
this._aborted = true; | ||
this._runing = false; | ||
if (this._xhr) { | ||
return this._xhr.abort(); | ||
}], [{ | ||
key: "isSupported", | ||
value: function isSupported() { | ||
return typeof XMLHttpRequest !== "undefined"; | ||
} | ||
} | ||
static isSupported() { | ||
return typeof XMLHttpRequest !== "undefined"; | ||
} | ||
get receiveLen() { | ||
return this._receivedLength; | ||
} | ||
get running() { | ||
return this._running; | ||
} | ||
set running(status) { | ||
this._running = status; | ||
} | ||
_getHeaders(xhr) { | ||
const headerLines = xhr.getAllResponseHeaders().trim().split("\r\n"); | ||
const headers = {}; | ||
for (const header of headerLines) { | ||
const parts = header.split(": "); | ||
headers[parts[0].toLowerCase()] = parts.slice(1).join(": "); | ||
} | ||
return headers; | ||
} | ||
} | ||
}]); | ||
return XhrLoader2; | ||
}(); | ||
export { XhrLoader }; |
@@ -1,40 +0,60 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
class BandwidthService { | ||
constructor() { | ||
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.array.push.js"; | ||
import "core-js/modules/es.array.slice.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
var BandwidthService = /* @__PURE__ */ function() { | ||
function BandwidthService2() { | ||
_classCallCheck(this, BandwidthService2); | ||
_defineProperty(this, "_chunkSpeeds", []); | ||
_defineProperty(this, "_speeds", []); | ||
} | ||
addRecord(totalByte, ms) { | ||
if (!totalByte || !ms) | ||
return; | ||
this._speeds.push(8e3 * totalByte / ms); | ||
this._speeds = this._speeds.slice(-3); | ||
} | ||
addChunkRecord(totalByte, ms) { | ||
if (!totalByte || !ms) | ||
return; | ||
this._chunkSpeeds.push(8e3 * totalByte / ms); | ||
this._chunkSpeeds = this._chunkSpeeds.slice(-100); | ||
} | ||
getAvgSpeed() { | ||
if (!this._chunkSpeeds.length && !this._speeds.length) | ||
return 0; | ||
if (this._speeds.length) { | ||
return this._speeds.reduce((a, c) => a += c) / this._speeds.length; | ||
_createClass(BandwidthService2, [{ | ||
key: "addRecord", | ||
value: function addRecord(totalByte, ms) { | ||
if (!totalByte || !ms) | ||
return; | ||
this._speeds.push(8e3 * totalByte / ms); | ||
this._speeds = this._speeds.slice(-3); | ||
} | ||
return this._chunkSpeeds.reduce((a, c) => a += c) / this._chunkSpeeds.length; | ||
} | ||
getLatestSpeed() { | ||
if (!this._chunkSpeeds.length && !this._speeds.length) | ||
return 0; | ||
if (this._speeds.length) { | ||
return this._speeds[this._speeds.length - 1]; | ||
}, { | ||
key: "addChunkRecord", | ||
value: function addChunkRecord(totalByte, ms) { | ||
if (!totalByte || !ms) | ||
return; | ||
this._chunkSpeeds.push(8e3 * totalByte / ms); | ||
this._chunkSpeeds = this._chunkSpeeds.slice(-100); | ||
} | ||
return this._chunkSpeeds[this._chunkSpeeds.length - 1]; | ||
} | ||
reset() { | ||
this._chunkSpeeds = []; | ||
this._speeds = []; | ||
} | ||
} | ||
}, { | ||
key: "getAvgSpeed", | ||
value: function getAvgSpeed() { | ||
if (!this._chunkSpeeds.length && !this._speeds.length) | ||
return 0; | ||
if (this._speeds.length) { | ||
return this._speeds.reduce(function(a, c) { | ||
return a += c; | ||
}) / this._speeds.length; | ||
} | ||
return this._chunkSpeeds.reduce(function(a, c) { | ||
return a += c; | ||
}) / this._chunkSpeeds.length; | ||
} | ||
}, { | ||
key: "getLatestSpeed", | ||
value: function getLatestSpeed() { | ||
if (!this._chunkSpeeds.length && !this._speeds.length) | ||
return 0; | ||
if (this._speeds.length) { | ||
return this._speeds[this._speeds.length - 1]; | ||
} | ||
return this._chunkSpeeds[this._chunkSpeeds.length - 1]; | ||
} | ||
}, { | ||
key: "reset", | ||
value: function reset() { | ||
this._chunkSpeeds = []; | ||
this._speeds = []; | ||
} | ||
}]); | ||
return BandwidthService2; | ||
}(); | ||
export { BandwidthService }; |
@@ -1,28 +0,36 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { Buffer } from "../buffer.js"; | ||
class GapService { | ||
constructor() { | ||
var GapService = /* @__PURE__ */ function() { | ||
function GapService2() { | ||
_classCallCheck(this, GapService2); | ||
_defineProperty(this, "_prevCurrentTime", 0); | ||
} | ||
do(media, maxJumpDistance = 3, isLive, seekThreshold = 1) { | ||
if (!media) | ||
return; | ||
const currentTime = media.currentTime; | ||
let jumpTo = 0; | ||
if (this._prevCurrentTime === currentTime) { | ||
const info = Buffer.info(Buffer.get(media), currentTime); | ||
if (!info.buffers.length) | ||
_createClass(GapService2, [{ | ||
key: "do", | ||
value: function _do(media) { | ||
var maxJumpDistance = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 3; | ||
var isLive = arguments.length > 2 ? arguments[2] : void 0; | ||
var seekThreshold = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1; | ||
if (!media) | ||
return; | ||
if (isLive && info.nextStart || info.nextStart && info.nextStart - currentTime < maxJumpDistance) { | ||
jumpTo = info.nextStart + 0.1; | ||
} else if (info.end && info.end - currentTime > seekThreshold && !media.seeking) { | ||
jumpTo = currentTime + 0.1; | ||
var currentTime = media.currentTime; | ||
var jumpTo = 0; | ||
if (this._prevCurrentTime === currentTime) { | ||
var info = Buffer.info(Buffer.get(media), currentTime); | ||
if (!info.buffers.length) | ||
return; | ||
if (isLive && info.nextStart || info.nextStart && info.nextStart - currentTime < maxJumpDistance) { | ||
jumpTo = info.nextStart + 0.1; | ||
} else if (info.end && info.end - currentTime > seekThreshold && !media.seeking) { | ||
jumpTo = currentTime + 0.1; | ||
} | ||
} | ||
this._prevCurrentTime = currentTime; | ||
if (jumpTo && currentTime !== jumpTo) { | ||
media.currentTime = jumpTo; | ||
} | ||
} | ||
this._prevCurrentTime = currentTime; | ||
if (jumpTo && currentTime !== jumpTo) { | ||
media.currentTime = jumpTo; | ||
} | ||
} | ||
} | ||
}]); | ||
return GapService2; | ||
}(); | ||
export { GapService }; |
@@ -1,32 +0,48 @@ | ||
import { defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js"; | ||
import "core-js/modules/es.array.iterator.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.set.js"; | ||
import "core-js/modules/es.string.iterator.js"; | ||
import "core-js/modules/web.dom-collections.iterator.js"; | ||
import "core-js/modules/web.dom-collections.for-each.js"; | ||
import "core-js/modules/es.array.push.js"; | ||
import { EVENT } from "../event.js"; | ||
class SeiService { | ||
constructor(emitter) { | ||
var SeiService = /* @__PURE__ */ function() { | ||
function SeiService2(emitter) { | ||
var _this = this; | ||
_classCallCheck(this, SeiService2); | ||
_defineProperty(this, "_seiSet", /* @__PURE__ */ new Set()); | ||
this.emitter = emitter; | ||
emitter.on(EVENT.SEI, (sei) => { | ||
emitter.on(EVENT.SEI, function(sei) { | ||
if (sei) | ||
this._seiSet.add(sei); | ||
_this._seiSet.add(sei); | ||
}); | ||
} | ||
throw(currentTime) { | ||
if (currentTime === null || currentTime === void 0 || !this._seiSet.size) | ||
return; | ||
const min = currentTime - 0.2; | ||
const max = currentTime + 0.2; | ||
const toThrow = []; | ||
this._seiSet.forEach((sei) => { | ||
if (sei.time >= min && sei.time <= max) { | ||
toThrow.push(sei); | ||
} | ||
}); | ||
toThrow.forEach((sei) => { | ||
this._seiSet.delete(sei); | ||
this.emitter.emit(EVENT.SEI_IN_TIME, sei); | ||
}); | ||
} | ||
reset() { | ||
this._seiSet.clear(); | ||
} | ||
} | ||
_createClass(SeiService2, [{ | ||
key: "throw", | ||
value: function _throw(currentTime) { | ||
var _this2 = this; | ||
if (currentTime === null || currentTime === void 0 || !this._seiSet.size) | ||
return; | ||
var min = currentTime - 0.2; | ||
var max = currentTime + 0.2; | ||
var toThrow = []; | ||
this._seiSet.forEach(function(sei) { | ||
if (sei.time >= min && sei.time <= max) { | ||
toThrow.push(sei); | ||
} | ||
}); | ||
toThrow.forEach(function(sei) { | ||
_this2._seiSet.delete(sei); | ||
_this2.emitter.emit(EVENT.SEI_IN_TIME, sei); | ||
}); | ||
} | ||
}, { | ||
key: "reset", | ||
value: function reset() { | ||
this._seiSet.clear(); | ||
} | ||
}]); | ||
return SeiService2; | ||
}(); | ||
export { SeiService }; |
@@ -0,4 +1,36 @@ | ||
import "core-js/modules/es.array.filter.js"; | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.array.iterator.js"; | ||
import "core-js/modules/es.typed-array.uint8-array.js"; | ||
import "core-js/modules/es.typed-array.at.js"; | ||
import "core-js/modules/esnext.typed-array.find-last.js"; | ||
import "core-js/modules/esnext.typed-array.find-last-index.js"; | ||
import "core-js/modules/es.typed-array.copy-within.js"; | ||
import "core-js/modules/es.typed-array.every.js"; | ||
import "core-js/modules/es.typed-array.fill.js"; | ||
import "core-js/modules/es.typed-array.filter.js"; | ||
import "core-js/modules/es.typed-array.find.js"; | ||
import "core-js/modules/es.typed-array.find-index.js"; | ||
import "core-js/modules/es.typed-array.find-last.js"; | ||
import "core-js/modules/es.typed-array.find-last-index.js"; | ||
import "core-js/modules/es.typed-array.for-each.js"; | ||
import "core-js/modules/es.typed-array.includes.js"; | ||
import "core-js/modules/es.typed-array.index-of.js"; | ||
import "core-js/modules/es.typed-array.iterator.js"; | ||
import "core-js/modules/es.typed-array.join.js"; | ||
import "core-js/modules/es.typed-array.last-index-of.js"; | ||
import "core-js/modules/es.typed-array.map.js"; | ||
import "core-js/modules/es.typed-array.reduce.js"; | ||
import "core-js/modules/es.typed-array.reduce-right.js"; | ||
import "core-js/modules/es.typed-array.reverse.js"; | ||
import "core-js/modules/es.typed-array.set.js"; | ||
import "core-js/modules/es.typed-array.slice.js"; | ||
import "core-js/modules/es.typed-array.some.js"; | ||
import "core-js/modules/es.typed-array.sort.js"; | ||
import "core-js/modules/es.typed-array.subarray.js"; | ||
import "core-js/modules/es.typed-array.to-locale-string.js"; | ||
import "core-js/modules/es.typed-array.to-string.js"; | ||
import "core-js/modules/esnext.typed-array.to-reversed.js"; | ||
import "core-js/modules/esnext.typed-array.to-sorted.js"; | ||
import "core-js/modules/esnext.typed-array.with.js"; | ||
import "core-js/modules/web.dom-collections.for-each.js"; | ||
import "core-js/modules/es.promise.js"; | ||
function isMediaPlaying(media) { | ||
@@ -11,3 +43,3 @@ return media && !media.paused && !media.ended && media.playbackRate !== 0 && media.readyState !== 0; | ||
if (typeof video.getVideoPlaybackQuality === "function") { | ||
const info = video.getVideoPlaybackQuality(); | ||
var info = video.getVideoPlaybackQuality(); | ||
return { | ||
@@ -25,9 +57,14 @@ droppedVideoFrames: info.droppedVideoFrames || info.corruptedVideoFrames, | ||
} | ||
function concatUint8Array(...arr) { | ||
function concatUint8Array() { | ||
for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) { | ||
arr[_key] = arguments[_key]; | ||
} | ||
arr = arr.filter(Boolean); | ||
if (arr.length < 2) | ||
return arr[0]; | ||
const data = new Uint8Array(arr.reduce((p, c) => p + c.byteLength, 0)); | ||
let prevLen = 0; | ||
arr.forEach((d) => { | ||
var data = new Uint8Array(arr.reduce(function(p, c) { | ||
return p + c.byteLength; | ||
}, 0)); | ||
var prevLen = 0; | ||
arr.forEach(function(d) { | ||
data.set(d, prevLen); | ||
@@ -38,5 +75,8 @@ prevLen += d.byteLength; | ||
} | ||
function sleep(t = 0) { | ||
return new Promise((resolve) => setTimeout(resolve, t)); | ||
function sleep() { | ||
var t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0; | ||
return new Promise(function(resolve) { | ||
return setTimeout(resolve, t); | ||
}); | ||
} | ||
export { concatUint8Array, getVideoPlaybackQuality, isMediaPlaying, sleep }; |
@@ -0,4 +1,6 @@ | ||
import "core-js/modules/es.object.to-string.js"; | ||
import "core-js/modules/es.promise.js"; | ||
function createPublicPromise() { | ||
let res, rej; | ||
const promise = new Promise((resolve, reject) => { | ||
var res, rej; | ||
var promise = new Promise(function(resolve, reject) { | ||
res = resolve; | ||
@@ -8,9 +10,9 @@ rej = reject; | ||
promise.used = false; | ||
promise.resolve = (...args) => { | ||
promise.resolve = function() { | ||
promise.used = true; | ||
return res(...args); | ||
return res.apply(void 0, arguments); | ||
}; | ||
promise.reject = (...args) => { | ||
promise.reject = function() { | ||
promise.used = true; | ||
return rej(...args); | ||
return rej.apply(void 0, arguments); | ||
}; | ||
@@ -17,0 +19,0 @@ return promise; |
{ | ||
"name": "xgplayer-streaming-shared", | ||
"version": "3.0.0-alpha.5-18", | ||
"version": "3.0.0-alpha.5-19", | ||
"main": "dist/index.min.js", | ||
@@ -5,0 +5,0 @@ "module": "es/index.js", |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
857874
4160