From e011857cec8f1ab3d93ad10fb1a1c7b6b22683ea Mon Sep 17 00:00:00 2001 From: toxic-johann <353904974@qq.com> Date: Sat, 29 Jul 2017 19:37:13 +0800 Subject: [PATCH] [build] 0.2.0 what: why: how: --- lib/index.browser.js | 24702 +++-------------------------------------- lib/index.js | 2249 ++-- lib/index.min.js | 2 +- lib/index.mjs | 2253 ++-- package.json | 2 +- 5 files changed, 4070 insertions(+), 25138 deletions(-) diff --git a/lib/index.browser.js b/lib/index.browser.js index 4397f483..4aa3ba3a 100644 --- a/lib/index.browser.js +++ b/lib/index.browser.js @@ -1,6 +1,6 @@ /** - * chimee v0.1.3 + * chimee v0.2.0 * (c) 2017 toxic-johann * Released under MIT */ @@ -287,6 +287,104 @@ module.exports = { "default": getOwnPropertyDescriptor$1, __esModule: true }; var _Object$getOwnPropertyDescriptor = unwrapExports(getOwnPropertyDescriptor); +// 7.1.13 ToObject(argument) + +var _toObject = function(it){ + return Object(_defined(it)); +}; + +var SHARED = '__core-js_shared__'; +var store = _global[SHARED] || (_global[SHARED] = {}); +var _shared = function(key){ + return store[key] || (store[key] = {}); +}; + +var id = 0; +var px = Math.random(); +var _uid = function(key){ + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; + +var shared = _shared('keys'); +var _sharedKey = function(key){ + return shared[key] || (shared[key] = _uid(key)); +}; + +// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) +var IE_PROTO = _sharedKey('IE_PROTO'); +var ObjectProto = Object.prototype; + +var _objectGpo = Object.getPrototypeOf || function(O){ + O = _toObject(O); + if(_has(O, IE_PROTO))return O[IE_PROTO]; + if(typeof O.constructor == 'function' && O instanceof O.constructor){ + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; +}; + +// 19.1.2.9 Object.getPrototypeOf(O) + + +_objectSap('getPrototypeOf', function(){ + return function getPrototypeOf(it){ + return _objectGpo(_toObject(it)); + }; +}); + +var getPrototypeOf$1 = _core.Object.getPrototypeOf; + +var getPrototypeOf = createCommonjsModule(function (module) { +module.exports = { "default": getPrototypeOf$1, __esModule: true }; +}); + +var _Object$getPrototypeOf = unwrapExports(getPrototypeOf); + +var classCallCheck = createCommonjsModule(function (module, exports) { +"use strict"; + +exports.__esModule = true; + +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; +}); + +var _classCallCheck = unwrapExports(classCallCheck); + +var createClass = createCommonjsModule(function (module, exports) { +"use strict"; + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = 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; + (0, _defineProperty2.default)(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; +}(); +}); + +var _createClass = unwrapExports(createClass); + // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; @@ -349,32 +447,15 @@ var _arrayIncludes = function(IS_INCLUDES){ }; }; -var SHARED = '__core-js_shared__'; -var store = _global[SHARED] || (_global[SHARED] = {}); -var _shared = function(key){ - return store[key] || (store[key] = {}); -}; - -var id = 0; -var px = Math.random(); -var _uid = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; - -var shared = _shared('keys'); -var _sharedKey = function(key){ - return shared[key] || (shared[key] = _uid(key)); -}; - var arrayIndexOf = _arrayIncludes(false); -var IE_PROTO$1 = _sharedKey('IE_PROTO'); +var IE_PROTO$2 = _sharedKey('IE_PROTO'); var _objectKeysInternal = function(object, names){ var O = _toIobject(object) , i = 0 , result = [] , key; - for(key in O)if(key != IE_PROTO$1)_has(O, key) && result.push(key); + for(key in O)if(key != IE_PROTO$2)_has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(_has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); @@ -407,7 +488,7 @@ var _objectDps = _descriptors ? Object.defineProperties : function definePropert var _html = _global.document && document.documentElement; // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) -var IE_PROTO = _sharedKey('IE_PROTO'); +var IE_PROTO$1 = _sharedKey('IE_PROTO'); var Empty = function(){ /* empty */ }; var PROTOTYPE$1 = 'prototype'; @@ -440,7 +521,7 @@ var _objectCreate = Object.create || function create(O, Properties){ result = new Empty; Empty[PROTOTYPE$1] = null; // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; + result[IE_PROTO$1] = O; } else result = createDict(); return Properties === undefined ? result : _objectDps(result, Properties); }; @@ -475,24 +556,6 @@ var _iterCreate = function(Constructor, NAME, next){ _setToStringTag(Constructor, NAME + ' Iterator'); }; -// 7.1.13 ToObject(argument) - -var _toObject = function(it){ - return Object(_defined(it)); -}; - -// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) -var IE_PROTO$2 = _sharedKey('IE_PROTO'); -var ObjectProto = Object.prototype; - -var _objectGpo = Object.getPrototypeOf || function(O){ - O = _toObject(O); - if(_has(O, IE_PROTO$2))return O[IE_PROTO$2]; - if(typeof O.constructor == 'function' && O instanceof O.constructor){ - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; -}; - var ITERATOR = _wks('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); var FF_ITERATOR = '@@iterator'; @@ -571,271 +634,69 @@ _iterDefine(String, 'String', function(iterated){ return {value: point, done: false}; }); -// call something on iterator step with safe closing on error +var _addToUnscopables = function(){ /* empty */ }; -var _iterCall = function(iterator, fn, value, entries){ - try { - return entries ? fn(_anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch(e){ - var ret = iterator['return']; - if(ret !== undefined)_anObject(ret.call(iterator)); - throw e; - } +var _iterStep = function(done, value){ + return {value: value, done: !!done}; }; -// check on default Array iterator -var ITERATOR$1 = _wks('iterator'); -var ArrayProto = Array.prototype; +// 22.1.3.4 Array.prototype.entries() +// 22.1.3.13 Array.prototype.keys() +// 22.1.3.29 Array.prototype.values() +// 22.1.3.30 Array.prototype[@@iterator]() +var es6_array_iterator = _iterDefine(Array, 'Array', function(iterated, kind){ + this._t = _toIobject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function(){ + var O = this._t + , kind = this._k + , index = this._i++; + if(!O || index >= O.length){ + this._t = undefined; + return _iterStep(1); + } + if(kind == 'keys' )return _iterStep(0, index); + if(kind == 'values')return _iterStep(0, O[index]); + return _iterStep(0, [index, O[index]]); +}, 'values'); -var _isArrayIter = function(it){ - return it !== undefined && (_iterators.Array === it || ArrayProto[ITERATOR$1] === it); -}; +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +_iterators.Arguments = _iterators.Array; -var _createProperty = function(object, index, value){ - if(index in object)_objectDp.f(object, index, _propertyDesc(0, value)); - else object[index] = value; -}; +_addToUnscopables('keys'); +_addToUnscopables('values'); +_addToUnscopables('entries'); -// getting tag from 19.1.3.6 Object.prototype.toString() -var TAG$1 = _wks('toStringTag'); -var ARG = _cof(function(){ return arguments; }()) == 'Arguments'; +var TO_STRING_TAG = _wks('toStringTag'); -// fallback for IE11 Script Access Denied error -var tryGet = function(it, key){ - try { - return it[key]; - } catch(e){ /* empty */ } -}; +for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ + var NAME = collections[i] + , Collection = _global[NAME] + , proto = Collection && Collection.prototype; + if(proto && !proto[TO_STRING_TAG])_hide(proto, TO_STRING_TAG, NAME); + _iterators[NAME] = _iterators.Array; +} -var _classof = function(it){ - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG$1)) == 'string' ? T - // builtinTag case - : ARG ? _cof(O) - // ES3 arguments fallback - : (B = _cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; -}; +var f$3 = _wks; -var ITERATOR$2 = _wks('iterator'); -var core_getIteratorMethod = _core.getIteratorMethod = function(it){ - if(it != undefined)return it[ITERATOR$2] - || it['@@iterator'] - || _iterators[_classof(it)]; +var _wksExt = { + f: f$3 }; -var ITERATOR$3 = _wks('iterator'); -var SAFE_CLOSING = false; +var iterator$2 = _wksExt.f('iterator'); -try { - var riter = [7][ITERATOR$3](); - riter['return'] = function(){ SAFE_CLOSING = true; }; - Array.from(riter, function(){ throw 2; }); -} catch(e){ /* empty */ } +var iterator = createCommonjsModule(function (module) { +module.exports = { "default": iterator$2, __esModule: true }; +}); -var _iterDetect = function(exec, skipClosing){ - if(!skipClosing && !SAFE_CLOSING)return false; - var safe = false; - try { - var arr = [7] - , iter = arr[ITERATOR$3](); - iter.next = function(){ return {done: safe = true}; }; - arr[ITERATOR$3] = function(){ return iter; }; - exec(arr); - } catch(e){ /* empty */ } - return safe; -}; - -_export(_export.S + _export.F * !_iterDetect(function(iter){ Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ - var O = _toObject(arrayLike) - , C = typeof this == 'function' ? this : Array - , aLen = arguments.length - , mapfn = aLen > 1 ? arguments[1] : undefined - , mapping = mapfn !== undefined - , index = 0 - , iterFn = core_getIteratorMethod(O) - , length, result, step, iterator; - if(mapping)mapfn = _ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if(iterFn != undefined && !(C == Array && _isArrayIter(iterFn))){ - for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ - _createProperty(result, index, mapping ? _iterCall(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = _toLength(O.length); - for(result = new C(length); length > index; index++){ - _createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } -}); - -var from$1 = _core.Array.from; - -var from = createCommonjsModule(function (module) { -module.exports = { "default": from$1, __esModule: true }; -}); - -var _Array$from = unwrapExports(from); - -var toConsumableArray = createCommonjsModule(function (module, exports) { -"use strict"; - -exports.__esModule = true; - - - -var _from2 = _interopRequireDefault(from); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } else { - return (0, _from2.default)(arr); - } -}; -}); - -var _toConsumableArray = unwrapExports(toConsumableArray); - -// 19.1.2.9 Object.getPrototypeOf(O) - - -_objectSap('getPrototypeOf', function(){ - return function getPrototypeOf(it){ - return _objectGpo(_toObject(it)); - }; -}); - -var getPrototypeOf$1 = _core.Object.getPrototypeOf; - -var getPrototypeOf = createCommonjsModule(function (module) { -module.exports = { "default": getPrototypeOf$1, __esModule: true }; -}); - -var _Object$getPrototypeOf = unwrapExports(getPrototypeOf); - -var classCallCheck = createCommonjsModule(function (module, exports) { -"use strict"; - -exports.__esModule = true; - -exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; -}); - -var _classCallCheck = unwrapExports(classCallCheck); - -var createClass = createCommonjsModule(function (module, exports) { -"use strict"; - -exports.__esModule = true; - - - -var _defineProperty2 = _interopRequireDefault(defineProperty); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = 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; - (0, _defineProperty2.default)(target, descriptor.key, descriptor); - } - } - - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; -}(); -}); - -var _createClass = unwrapExports(createClass); - -var _addToUnscopables = function(){ /* empty */ }; - -var _iterStep = function(done, value){ - return {value: value, done: !!done}; -}; - -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -var es6_array_iterator = _iterDefine(Array, 'Array', function(iterated, kind){ - this._t = _toIobject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function(){ - var O = this._t - , kind = this._k - , index = this._i++; - if(!O || index >= O.length){ - this._t = undefined; - return _iterStep(1); - } - if(kind == 'keys' )return _iterStep(0, index); - if(kind == 'values')return _iterStep(0, O[index]); - return _iterStep(0, [index, O[index]]); -}, 'values'); - -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -_iterators.Arguments = _iterators.Array; - -_addToUnscopables('keys'); -_addToUnscopables('values'); -_addToUnscopables('entries'); - -var TO_STRING_TAG = _wks('toStringTag'); - -for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ - var NAME = collections[i] - , Collection = _global[NAME] - , proto = Collection && Collection.prototype; - if(proto && !proto[TO_STRING_TAG])_hide(proto, TO_STRING_TAG, NAME); - _iterators[NAME] = _iterators.Array; -} - -var f$3 = _wks; - -var _wksExt = { - f: f$3 -}; - -var iterator$2 = _wksExt.f('iterator'); - -var iterator = createCommonjsModule(function (module) { -module.exports = { "default": iterator$2, __esModule: true }; -}); - -var _meta = createCommonjsModule(function (module) { -var META = _uid('meta') - , setDesc = _objectDp.f - , id = 0; -var isExtensible = Object.isExtensible || function(){ - return true; +var _meta = createCommonjsModule(function (module) { +var META = _uid('meta') + , setDesc = _objectDp.f + , id = 0; +var isExtensible = Object.isExtensible || function(){ + return true; }; var FREEZE = !_fails(function(){ return isExtensible(Object.preventExtensions({})); @@ -1228,7 +1089,7 @@ exports.default = function (self, call) { var _possibleConstructorReturn = unwrapExports(possibleConstructorReturn); -var get$1 = createCommonjsModule(function (module, exports) { +var get = createCommonjsModule(function (module, exports) { "use strict"; exports.__esModule = true; @@ -1269,7 +1130,7 @@ exports.default = function get(object, property, receiver) { }; }); -var _get = unwrapExports(get$1); +var _get = unwrapExports(get); // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ @@ -1358,12 +1219,62 @@ exports.default = function (subClass, superClass) { var _inherits = unwrapExports(inherits); +// getting tag from 19.1.3.6 Object.prototype.toString() +var TAG$1 = _wks('toStringTag'); +var ARG = _cof(function(){ return arguments; }()) == 'Arguments'; + +// fallback for IE11 Script Access Denied error +var tryGet = function(it, key){ + try { + return it[key]; + } catch(e){ /* empty */ } +}; + +var _classof = function(it){ + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG$1)) == 'string' ? T + // builtinTag case + : ARG ? _cof(O) + // ES3 arguments fallback + : (B = _cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; +}; + var _anInstance = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; +// call something on iterator step with safe closing on error + +var _iterCall = function(iterator, fn, value, entries){ + try { + return entries ? fn(_anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch(e){ + var ret = iterator['return']; + if(ret !== undefined)_anObject(ret.call(iterator)); + throw e; + } +}; + +// check on default Array iterator +var ITERATOR$1 = _wks('iterator'); +var ArrayProto = Array.prototype; + +var _isArrayIter = function(it){ + return it !== undefined && (_iterators.Array === it || ArrayProto[ITERATOR$1] === it); +}; + +var ITERATOR$2 = _wks('iterator'); +var core_getIteratorMethod = _core.getIteratorMethod = function(it){ + if(it != undefined)return it[ITERATOR$2] + || it['@@iterator'] + || _iterators[_classof(it)]; +}; + var _forOf = createCommonjsModule(function (module) { var BREAK = {} , RETURN = {}; @@ -1568,6 +1479,28 @@ var _setSpecies = function(KEY){ }); }; +var ITERATOR$3 = _wks('iterator'); +var SAFE_CLOSING = false; + +try { + var riter = [7][ITERATOR$3](); + riter['return'] = function(){ SAFE_CLOSING = true; }; + Array.from(riter, function(){ throw 2; }); +} catch(e){ /* empty */ } + +var _iterDetect = function(exec, skipClosing){ + if(!skipClosing && !SAFE_CLOSING)return false; + var safe = false; + try { + var arr = [7] + , iter = arr[ITERATOR$3](); + iter.next = function(){ return {done: safe = true}; }; + arr[ITERATOR$3] = function(){ return iter; }; + exec(arr); + } catch(e){ /* empty */ } + return safe; +}; + var task = _task.set; var microtask = _microtask(); var PROMISE = 'Promise'; @@ -1951,6 +1884,8 @@ var _parseFloat = createCommonjsModule(function (module) { module.exports = { "default": _parseFloat$1, __esModule: true }; }); +var _Number$parseFloat = unwrapExports(_parseFloat); + /** * toxic-predicate-functions v0.1.2 * (c) 2017 toxic-johann @@ -2000,6 +1935,14 @@ function isObject$1(obj) { function isNumber(obj) { return typeof obj === 'number'; } +/** + * to tell you if the val can be transfer into data + * @param {Anything} obj [description] + * @return {Boolean} [description] + */ +function isNumeric(obj) { + return !isArray$1(obj) && obj - _Number$parseFloat(obj) + 1 >= 0; +} /** * 判断是否为整数 * @param {Anything} obj [description] @@ -2242,7 +2185,74 @@ Log.ENABLE_WARN = true; Log.ENABLE_DEBUG = true; Log.ENABLE_VERBOSE = true; -/** +var _createProperty = function(object, index, value){ + if(index in object)_objectDp.f(object, index, _propertyDesc(0, value)); + else object[index] = value; +}; + +_export(_export.S + _export.F * !_iterDetect(function(iter){ Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ + var O = _toObject(arrayLike) + , C = typeof this == 'function' ? this : Array + , aLen = arguments.length + , mapfn = aLen > 1 ? arguments[1] : undefined + , mapping = mapfn !== undefined + , index = 0 + , iterFn = core_getIteratorMethod(O) + , length, result, step, iterator; + if(mapping)mapfn = _ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if(iterFn != undefined && !(C == Array && _isArrayIter(iterFn))){ + for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ + _createProperty(result, index, mapping ? _iterCall(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = _toLength(O.length); + for(result = new C(length); length > index; index++){ + _createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } +}); + +var from$1 = _core.Array.from; + +var from = createCommonjsModule(function (module) { +module.exports = { "default": from$1, __esModule: true }; +}); + +var _Array$from = unwrapExports(from); + +var toConsumableArray = createCommonjsModule(function (module, exports) { +"use strict"; + +exports.__esModule = true; + + + +var _from2 = _interopRequireDefault(from); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } else { + return (0, _from2.default)(arr); + } +}; +}); + +var _toConsumableArray = unwrapExports(toConsumableArray); + +/** * toxic-utils v0.1.5 * (c) 2017 toxic-johann * Released under MIT @@ -2461,68 +2471,6 @@ function runStoppableQueue(queue) { }; return step(0); } -/** - * 函数节流(控制函数执行频率) - * @param {Function} func 要节流控制的函数,必填 - * @return {Number} wait 等待时长 - * @return {Object} options { - * leading<是否首次调用立即执行,否:则按wait设定等待到期后调用才执行>:false, - * trailing<是否在调用并未到期时启用定时器,以保证一定执行>:true - * } - * @return {Object} cxt 上下文对象 - * @return {Function} - */ -function throttle(func, wait, options, cxt) { - /* options的默认值 - * 表示首次调用返回值方法时,会马上调用func;否则仅会记录当前时刻,当第二次调用的时间间隔超过wait时,才调用func。 - * options.leading = true; - * 表示当调用方法时,未到达wait指定的时间间隔,则启动计时器延迟调用func函数,若后续在既未达到wait指定的时间间隔和func函数又未被调用的情况下调用返回值方法,则被调用请求将被丢弃。 - * options.trailing = true; - * 注意:当options.trailing = false时,效果与上面的简单实现效果相同 - */ - var context = void 0, - args = void 0, - result = void 0; - var timeout = null; - var previous = 0; - if (!options) options = {}; - var later = function later() { - previous = options.leading === false ? 0 : new Date() - 0; - timeout = null; - result = func.apply(context, args); - if (!timeout) context = args = null; - }; - wait = wait || 0; - return function () { - var now = new Date(); - if (!previous && options.leading === false) previous = now; - // 计算剩余时间 - var remaining = wait - (now - previous); - if (cxt) { - context = cxt; - } else { - context = this; - } - - args = arguments; - // 当到达wait指定的时间间隔,则调用func函数 - // 精彩之处:按理来说remaining <= 0已经足够证明已经到达wait的时间间隔,但这里还考虑到假如客户端修改了系统时间则马上执行func函数。 - if (remaining <= 0 || remaining > wait) { - // 由于setTimeout存在最小时间精度问题,因此会存在到达wait的时间间隔,但之前设置的setTimeout操作还没被执行,因此为保险起见,这里先清理setTimeout操作 - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - previous = now; - result = func.apply(context, args); - if (!timeout) context = args = null; - } else if (!timeout && options.trailing !== false) { - // options.trailing=true时,延时执行func函数 - timeout = setTimeout(later, remaining); - } - return result; - }; -} // 19.1.2.1 Object.assign(target, source, ...) var $assign = Object.assign; @@ -2812,7 +2760,7 @@ var CustEvent = function () { }(); /** - * chimee-helper-dom v0.1.1 + * chimee-helper-dom v0.1.2 * (c) 2017 huzunjie * Released under MIT */ @@ -3064,7 +3012,7 @@ var CustEvent$1 = function () { }(); /** - * chimee-helper-utils v0.1.1 + * chimee-helper-utils v0.1.3 * (c) 2017 toxic-johann * Released under MIT */ @@ -3245,7 +3193,7 @@ function addDelegate(el, selector, type, handler) { var handlerWrap = function handlerWrap(e) { - var targetEls = findParents(e.srcElement, el, true); + var targetEls = findParents(e.target || e.srcElement, el, true); var targetEl = query(selector, el, true).find(function (seEl) { return targetEls.find(function (tgEl) { return seEl === tgEl; @@ -3733,96 +3681,15 @@ var NodeWrap = function () { }(); /** - * chimee-helper v0.1.12 + * chimee-helper v0.1.15 * (c) 2017 toxic-johann * Released under MIT */ -var bundleFn = arguments[3]; -var sources = arguments[4]; -var cache = arguments[5]; - -var stringify = JSON.stringify; - -var index$2 = function (fn, options) { - var wkey; - var cacheKeys = Object.keys(cache); - - for (var i = 0, l = cacheKeys.length; i < l; i++) { - var key = cacheKeys[i]; - var exp = cache[key].exports; - // Using babel as a transpiler to use esmodule, the export will always - // be an object with the default export as a property of it. To ensure - // the existing api and babel esmodule exports are both supported we - // check for both - if (exp === fn || exp && exp.default === fn) { - wkey = key; - break; - } - } - - if (!wkey) { - wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); - var wcache = {}; - for (var i = 0, l = cacheKeys.length; i < l; i++) { - var key = cacheKeys[i]; - wcache[key] = key; - } - sources[wkey] = [ - Function(['require','module','exports'], '(' + fn + ')(self)'), - wcache - ]; - } - var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); - - var scache = {}; scache[wkey] = wkey; - sources[skey] = [ - Function(['require'], ( - // try to call default if defined to also support babel esmodule - // exports - 'var f = require(' + stringify(wkey) + ');' + - '(f.default ? f.default : f)(self);' - )), - scache - ]; - - var workerSources = {}; - resolveSources(skey); - - function resolveSources(key) { - workerSources[key] = true; - - for (var depPath in sources[key][1]) { - var depKey = sources[key][1][depPath]; - if (!workerSources[depKey]) { - resolveSources(depKey); - } - } - } - - var src = '(' + bundleFn + ')({' - + Object.keys(workerSources).map(function (key) { - return stringify(key) + ':[' - + sources[key][0] - + ',' + stringify(sources[key][1]) + ']' - ; - }).join(',') - + '},{},[' + stringify(skey) + '])'; - - var URL = window.URL || window.webkitURL || window.mozURL || window.msURL; - - var blob = new Blob([src], { type: 'text/javascript' }); - if (options && options.bare) { return blob; } - var workerUrl = URL.createObjectURL(blob); - var worker = new Worker(workerUrl); - worker.objectURL = workerUrl; - return worker; -}; - var defaultConfig = { type: 'vod', autoPlay: false, - box: 'mp4', + box: 'native', lockInternalProperty: false, debug: true }; @@ -3831,33 +3698,32 @@ var defaultConfig = { * mp4解码器 * * @export - * @class Mp4 + * @class Native */ -var Mp4 = function (_CustEvent) { - _inherits(Mp4, _CustEvent); +var Native = function (_CustEvent) { + _inherits(Native, _CustEvent); /** - * Creates an instance of Mp4. + * Creates an instance of Native. * @param {any} videodom video dom对象 * @param {any} config 配置 - * - * @memberof Mp4 + * @memberof Native */ - function Mp4(videodom, config) { - _classCallCheck(this, Mp4); + function Native(videodom, config) { + _classCallCheck(this, Native); - var _this2 = _possibleConstructorReturn(this, (Mp4.__proto__ || _Object$getPrototypeOf(Mp4)).call(this)); + var _this2 = _possibleConstructorReturn(this, (Native.__proto__ || _Object$getPrototypeOf(Native)).call(this)); _this2.video = videodom; - _this2.box = 'mp4'; + _this2.box = 'Native'; _this2.config = defaultConfig; deepAssign(_this2.config, config); _this2.bindEvents(); return _this2; } - _createClass(Mp4, [{ + _createClass(Native, [{ key: 'internalPropertyHandle', value: function internalPropertyHandle() { if (!_Object$getOwnPropertyDescriptor) { @@ -3931,21772 +3797,183 @@ var Mp4 = function (_CustEvent) { } }]); - return Mp4; + return Native; }(CustEvent); -var MSEController = function (_CustEvent) { - _inherits(MSEController, _CustEvent); - - function MSEController(videoElement, config) { - _classCallCheck(this, MSEController); - - var _this = _possibleConstructorReturn(this, (MSEController.__proto__ || _Object$getPrototypeOf(MSEController)).call(this)); - - _this.video = videoElement; - _this.config = config; - _this.tag = 'mse-controller'; - _this.e = { - onSourceOpen: _this.onSourceOpen.bind(_this), - onSourceEnded: _this.onSourceEnded.bind(_this), - onSourceClose: _this.onSourceClose.bind(_this), - onSourceBufferError: _this.onSourceBufferError.bind(_this) - }; - _this.queue = []; - _this.removeRangesList = []; - _this.mimeCodec = 'video/mp4; codecs="avc1.640020,mp4a.40.2"'; - _this.init(); - return _this; - } - - _createClass(MSEController, [{ - key: 'init', - value: function init() { - if (this.mediaSource) { - Log.Error(this.tag, 'MediaSource has been attached to an HTMLMediaElement!'); - throw new Error('MediaSource has been attached to an HTMLMediaElement!'); - } - var ms = this.mediaSource = new window.MediaSource(); - ms.addEventListener('sourceopen', this.e.onSourceOpen); - ms.addEventListener('sourceended', this.e.onSourceEnded); - ms.addEventListener('sourceclose', this.e.onSourceClose); - } - }, { - key: 'onSourceOpen', - value: function onSourceOpen() { - var _this2 = this; - - Log.verbose(this.tag, 'MediaSource onSourceOpen'); - this.mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen); - this.sourceBuffer = this.mediaSource.addSourceBuffer(this.mimeCodec); - this.sourceBuffer.addEventListener('error', this.e.onSourceBufferError); - this.sourceBuffer.addEventListener('abort', function () { - return console.log('sourceBuffer: abort'); - }); - this.sourceBuffer.addEventListener('updateend', function () { - if (_this2.queue.length >= 1) { - if (!_this2.sourceBuffer.updating) { - var data = _this2.queue.shift(); - _this2.appendBuffer(data); - } - } - _this2.emit('updateend'); - }); - this.emit('source_open'); - this.sourceBufferEvent(); - } - }, { - key: 'sourceBufferEvent', - value: function sourceBufferEvent() { - var _this3 = this; - - this.on('mediaSegment', function (handler) { - var data = handler.data; - // if(this.needCleanupSourceBuffer()) { - // this.doCleanupSourceBuffer(); - // } - if (_this3.sourceBuffer.updating || _this3.queue.length > 0) { - // console.log(new Uint8Array(data)); - _this3.queue.push(data); - } else { - _this3.appendBuffer(data); - } - }); - - this.on('mediaSegmentInit', function (handler) { - var data = handler.data; - if (_this3.sourceBuffer.updating || _this3.queue.length > 0) { - _this3.queue.push(data); - } else { - _this3.appendBuffer(data); - } - }); - } - }, { - key: 'needCleanupSourceBuffer', - value: function needCleanupSourceBuffer() { - var currentTime = this.video.currentTime; - - var sb = this.sourceBuffer; - var buffered = sb.buffered; - - if (buffered.length >= 1) { - if (currentTime - buffered.start(0) >= this.config.autoCleanupMaxBackwardDuration) { - return true; - } - } - return false; - } - }, { - key: 'doCleanupSourceBuffer', - value: function doCleanupSourceBuffer() { - Log.verbose('执行了一次垃圾回收'); - var currentTime = this.video.currentTime; - var sb = this.sourceBuffer; - var buffered = sb.buffered; - var doRemove = false; - for (var i = 0; i < buffered.length; i++) { - var start = buffered.start(i); - var end = buffered.end(i); - - if (start <= currentTime && currentTime < end + 3) { - if (currentTime - start >= this.config.autoCleanupMaxBackwardDuration) { - doRemove = true; - var removeEnd = currentTime - this._config.autoCleanupMinBackwardDuration; - this.removeRangesList.push({ start: start, end: removeEnd }); - } - } else if (end < currentTime) { - doRemove = true; - this.removeRangesList.push({ start: start, end: end }); - } - } - if (doRemove && !this.sourceBuffer.updating) { - this.removeRangesList(); - } - } - }, { - key: 'removeRangesList', - value: function removeRangesList() { - for (var i = 0; i < this.removeRangesListi.length; i++) { - if (this.sourceBuffer.updating) { - continue; - } - var sb = this.sourceBuffer; - var ranges = this.removeRangesList[i]; - while (ranges.length && !sb.updating) { - var range = ranges.shift(); - sb.remove(range.start, range.end); - } - } - } - }, { - key: 'appendBuffer', - value: function appendBuffer(data) { - if (this.needCleanupSourceBuffer()) { - this.doCleanupSourceBuffer(); - } - try { - this.sourceBuffer.appendBuffer(data); - } catch (e) { - if (e.code === 22) { - // chrome 大概会有350M - Log.verbose(this.TAG, 'MediaSource bufferFull'); - this.emit('bufferFull'); - } - } - } - }, { - key: 'onSourceEnded', - value: function onSourceEnded() { - Log.verbose(this.TAG, 'MediaSource onSourceEnded'); - } - }, { - key: 'onSourceClose', - value: function onSourceClose() { - Log.verbose(this.TAG, 'MediaSource onSourceClose'); - if (this.mediaSource && this.e !== null) { - this.mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen); - this.mediaSource.removeEventListener('sourceended', this.e.onSourceEnded); - this.mediaSource.removeEventListener('sourceclose', this.e.onSourceClose); - } - } - }, { - key: 'onSourceBufferError', - value: function onSourceBufferError(e) { - Log.Error(this.tag, 'SourceBuffer Error: ' + e); - } - }, { - key: 'seek', - value: function seek(currentTime) {} - }, { - key: 'destroy', - value: function destroy() { - if (this.mediaSource) { - var ms = this.mediaSource; - // pending segments should be discard - this.queue = []; - // remove all sourcebuffers - var sb = this.sourceBuffer; - if (sb) { - if (ms.readyState !== 'closed') { - ms.removeSourceBuffer(sb); - sb.removeEventListener('error', this.e.onSourceBufferError); - sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd); - } - this.sourceBuffer = null; - } - if (ms.readyState === 'open') { - try { - ms.endOfStream(); - } catch (error) { - Log.e(this.TAG, error.message); - } - } - ms.removeEventListener('sourceopen', this.e.onSourceOpen); - ms.removeEventListener('sourceended', this.e.onSourceEnded); - ms.removeEventListener('sourceclose', this.e.onSourceClose); - this.mediaSource = null; - } - - if (this._mediaElement) { - this._mediaElement.src = ''; - this._mediaElement.removeAttribute('src'); - this._mediaElement = null; - } - if (this._mediaSourceObjectURL) { - window.URL.revokeObjectURL(this._mediaSourceObjectURL); - this._mediaSourceObjectURL = null; - } - } - }]); +var Kernel = function (_CustEvent) { + _inherits(Kernel, _CustEvent); - return MSEController; -}(CustEvent); + /** + * 创建核心解码器 + * @param {any} wrap 父层容器 + * @param {any} option 整合参数 + * @class kernel + */ + function Kernel(videoElement, config) { + _classCallCheck(this, Kernel); -/** -* 处理range的静态函数 -* author songguangyu -* emil 522963130@qq.com -*/ -var handleRange = function (range) { - var headers = {}; - var param = void 0; + var _this = _possibleConstructorReturn(this, (Kernel.__proto__ || _Object$getPrototypeOf(Kernel)).call(this)); - if (range.to !== -1) { - param = 'bytes=' + range.from.toString() + '-' + range.to.toString(); - } else { - param = 'bytes=' + range.from.toString() + '-'; - } - headers['Range'] = param; + _this.tag = 'kernel'; + _this.config = config; + _this.video = videoElement; + _this.videokernel = _this.selectKernel(); + _this.bindEvents(_this.videokernel, _this.video); + _this.timer = null; + return _this; + } - return { - headers: headers - }; -}; + /** + * 绑定事件 + * @memberof kernel + */ -/** -* fetch firfox 直播 点播 -* author songguangyu -* emil 522963130@qq.com -*/ -var FetchLoader = function (_CustEvent) { - _inherits(FetchLoader, _CustEvent); - _createClass(FetchLoader, null, [{ - key: 'isSupport', + _createClass(Kernel, [{ + key: 'bindEvents', + value: function bindEvents(videokernel, video) { + var _this2 = this; + if (videokernel) { + videokernel.on('mediaInfo', function (mediaInfo) { + _this2.emit('mediaInfo', mediaInfo); + }); - /** - * broswer is support moz-chunk - */ - value: function isSupport() { - if (window.fetch && window.ReadableStream) { - return true; - } else { - return false; + video.addEventListener('canplay', function () { + clearTimeout(_this2.timer); + _this2.timer = null; + }); } } /** - * @param {string} video url - * @param {object} range.from range.to - */ - - }]); - - function FetchLoader(src, config) { - _classCallCheck(this, FetchLoader); - - var _this = _possibleConstructorReturn(this, (FetchLoader.__proto__ || _Object$getPrototypeOf(FetchLoader)).call(this)); - - _this.fetching = false; - _this.config = config; - _this.range = { - from: 0, - to: 500000 - }; - _this.src = src; - _this.totalRange = null; - _this.block = 500000; - _this.reader = null; - _this.requestAbort = false; - _this.arrivalDataCallback = null; - _this.bytesStart = 0; - return _this; - } - /** - * if don't need range don't set - * @param {object} range.from range.to + * 选择解码器 + * @memberof kernel */ + }, { + key: 'selectKernel', + value: function selectKernel() { + var config = this.config; - _createClass(FetchLoader, [{ - key: 'open', - value: function open(range, keyframePoint) { - var _this2 = this; - - this.requestAbort = false; - var reqHeaders = new Headers(); - var r = range || { from: 0, to: -1 }; + var box = config.box ? config.box : config.src.indexOf('.flv') !== -1 ? 'flv' : config.src.indexOf('.m3u8') !== -1 ? 'hls' : 'native'; - if (this.config.type === 'vod') { - this.range.from = r.from; - this.range.to = r.to; - var headers = handleRange(r).headers; - for (var i in headers) { - reqHeaders.append(i, headers[i]); - } - } - if (keyframePoint) { - this.bytesStart = 0; + if (box === 'native') { + return new Native(this.video, config); + } else if (box === 'flv') { + return new config.preset[box](this.video, config); + } else if (box === 'hls') { + return new config.preset[box](this.video, config); + } else { + Log.error(this.tag, 'not mactch any player, please check your config'); + return null; } - this.req = new Request(this.src, { headers: reqHeaders }); - - fetch(this.req).then(function (res) { - // console.log(response.headers.get("Content-Range")); - if (res.ok) { - var reader = res.body.getReader(); - return _this2.pump(reader, keyframePoint); - } - }); } - - /** - * pause video - */ - }, { - key: 'pause', - value: function pause() { - this.requestAbort = true; + key: 'attachMedia', + value: function attachMedia() { + if (this.videokernel) { + this.videokernel.attachMedia(); + } else { + Log.error(this.tag, 'video player is not already, must init player'); + } } /** - * pump data - */ + * 启动加载 + * @param {string} src 媒体资源地址 + * @memberof kernel + */ }, { - key: 'pump', - value: function pump(reader, keyframePoint) { - var _this3 = this; + key: 'load', + value: function load(src) { + var _this3 = this; - // ReadableStreamReader - return reader.read().then(function (result) { - if (result.done) { - Log.ver; - // trigger complete - } else { - if (_this3.requestAbort === true) { - return reader.cancel(); - } - var chunk = result.value.buffer; - - if (_this3.arrivalDataCallback) { - _this3.arrivalDataCallback(chunk, _this3.bytesStart, keyframePoint); - _this3.bytesStart += chunk.byteLength; - } - return _this3.pump(reader); + this.config.src = src || this.config.src; + if (this.videokernel && this.config.src) { + this.videokernel.load(src); + if (!this.timer) { + this.timer = setTimeout(function () { + _this3.timer = null; + _this3.pause(); + _this3.refresh(); + }, 1000); } - }); - } - }]); - - return FetchLoader; -}(CustEvent); - -/** -* XHR 点播 -* author songguangyu -* emil 522963130@qq.com -*/ -// import Log from 'helper/log'; -var RangeLoader = function (_CustEvent) { - _inherits(RangeLoader, _CustEvent); - - _createClass(RangeLoader, null, [{ - key: 'isSupport', - - - /** - * broswer is support XMLHttpRequest - */ - value: function isSupport() { - try { - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'https://example.com', true); - xhr.responseType = 'arraybuffer'; - return xhr.responseType === 'arraybuffer'; - } catch (e) { - return false; - } - } - - /** - * @param {string} video url - * @param {object} video config - */ - - }]); - - function RangeLoader(src, config) { - _classCallCheck(this, RangeLoader); - - var _this = _possibleConstructorReturn(this, (RangeLoader.__proto__ || _Object$getPrototypeOf(RangeLoader)).call(this)); - - _this.tag = 'RangeLoader'; - _this.xhr = null; - _this.src = src; - _this.totalLength = null; - _this.chunkSizeKB = 393216; - _this.range = {}; - _this.bytesStart = 0; - return _this; - } - /** - * if don't need range don't set - * @param {object} range.from range.to - */ - - - _createClass(RangeLoader, [{ - key: 'open', - value: function open(range) { - var xhr = this.xhr = new XMLHttpRequest(); - xhr.open('GET', this.src, true); - xhr.responseType = 'arraybuffer'; - xhr.onreadystatechange = this.onReadyStateChange.bind(this); - xhr.onprogress = this.onProgress.bind(this); - xhr.onload = this.onLoad.bind(this); - xhr.onerror = this.onXhrError.bind(this); - var r = range || { from: 0, to: -1 }; - this.range.from = r.from; - this.range.to = r.to; - var headers = handleRange(r).headers; - for (var i in headers) { - xhr.setRequestHeader(i, headers[i]); - } - xhr.send(); - } - - /** - * abort request - */ - - }, { - key: 'abort', - value: function abort() { - this.xhr.onreadystatechange = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - this.xhr.onerror = null; - this.xhr.abort(); - this.xhr = null; - } - - /** - * destroy xhr Object clean cache - */ - - }, { - key: 'destroy', - value: function destroy() { - if (this.xhr) { - this.abort(); - this.xhr.onreadystatechange = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - this.xhr.onerror = null; - this.xhr = null; - } - this.totalLength = null; - this.bytesStart = null; - this.range = {}; - } - - /** - * xhr onReadyStateChange - */ - - }, { - key: 'onReadyStateChange', - value: function onReadyStateChange(e) { - var xhr = this.xhr; - if (xhr.readyState === 2) { - if (xhr.status < 200 && xhr.status > 299) { - var info = { - from: this.range.from, - to: this.range.to, - url: this.src, - msg: 'http Error: http code ' + xhr.status - }; - this.emit(this.tag, info); - } - } - } - - /** - * xhr onProgress - */ - - }, { - key: 'onProgress', - value: function onProgress(e) { - if (!this.totalLength) { - this.totalLength = e.total; - this.abort(); - this.open({ from: 0, to: this.chunkSizeKB }); - } - } - - /** - * xhr onLoad - */ - - }, { - key: 'onLoad', - value: function onLoad(e) { - if (!this.totalLength) { - return; - } - if (this.range.to < this.totalLength) { - // this.open({from: this.range.to + 1, to: this.range.to + 1 + this.chunkSizeKB}); - } - - if (this.arrivalDataCallback) { - var chunk = e.target.response; - this.arrivalDataCallback(chunk, this.bytesStart); - this.bytesStart += chunk.byteLength; - } - } - - /** - * xhr onXhrError - */ - - }, { - key: 'onXhrError', - value: function onXhrError(e) { - var info = { - from: this.range.from, - to: this.range.to, - url: this.src, - msg: e.constructor.name + ' ' + e.type - }; - this.emit(this.tag, info); - } - }]); - - return RangeLoader; -}(CustEvent); - -/** -* XHR firfox 直播 点播 -* author songguangyu -* emil 522963130@qq.com -*/ -// import Log from 'helper/log'; -var MozChunkLoader = function (_CustEvent) { - _inherits(MozChunkLoader, _CustEvent); - - _createClass(MozChunkLoader, null, [{ - key: 'isSupport', - - - /** - * broswer is support moz-chunk - */ - value: function isSupport() { - try { - var xhr = new XMLHttpRequest(); - // Firefox 37- requires .open() to be called before setting responseType - xhr.open('GET', 'https://example.com', true); - xhr.responseType = 'moz-chunked-arraybuffer'; - return xhr.responseType === 'moz-chunked-arraybuffer'; - } catch (e) { - return false; - } - } - - /** - * @param {string} video url - * @param {object} range.from range.to - */ - - }]); - - function MozChunkLoader(src, config) { - _classCallCheck(this, MozChunkLoader); - - var _this = _possibleConstructorReturn(this, (MozChunkLoader.__proto__ || _Object$getPrototypeOf(MozChunkLoader)).call(this)); - - _this.tag = 'mozChunkLoader'; - _this.xhr = null; - _this.src = src; - _this.config = config; - _this.totalLength = null; - _this.chunkSizeKB = 393216; - _this.range = {}; - _this.bytesStart = 0; - return _this; - } - /** - * if don't need range don't set - * @param {object} range.from range.to - */ - - - _createClass(MozChunkLoader, [{ - key: 'open', - value: function open(range) { - var xhr = this.xhr = new XMLHttpRequest(); - xhr.open('GET', this.src, true); - xhr.responseType = 'moz-chunked-arraybuffer'; - xhr.onreadystatechange = this.onReadyStateChange.bind(this); - xhr.onprogress = this.onProgress.bind(this); - xhr.onload = this.onLoadEnd.bind(this); - xhr.onerror = this.onXhrError.bind(this); - if (this.config.type === 'vod') { - var r = range || { from: 0, to: -1 }; - this.range.from = r.from; - this.range.to = r.to; - var headers = handleRange(r).headers; - for (var i in headers) { - xhr.setRequestHeader(i, headers[i]); - } - } - xhr.send(); - } - - /** - * abort request - */ - - }, { - key: 'abort', - value: function abort() { - this.xhr.onreadystatechange = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - this.xhr.onerror = null; - this.xhr.abort(); - this.xhr = null; - } - - /** - * destroy xhr Object clean cache - */ - - }, { - key: 'destroy', - value: function destroy() { - if (this.xhr) { - this.abort(); - this.xhr.onreadystatechange = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - this.xhr.onerror = null; - this.xhr = null; - } - this.totalLength = null; - this.bytesStart = null; - this.range = {}; - } - - /** - * xhr onReadyStateChange - */ - - }, { - key: 'onReadyStateChange', - value: function onReadyStateChange(e) { - var xhr = this.xhr; - if (xhr.readyState === 2) { - if (xhr.status < 200 && xhr.status > 299) { - var info = { - from: this.range.from, - to: this.range.to, - url: this.src, - msg: 'http Error: http code ' + xhr.status - }; - this.emit(this.tag, info); - } - } - } - - /** - * xhr onProgress - */ - - }, { - key: 'onProgress', - value: function onProgress(e) { - if (!this.totalLength) { - this.totalLength = e.total; - if (e.total !== null && e.total !== 0) { - this.totalLength = e.total; - } - } - - var chunk = e.target.response; - this.arrivalDataCallback(chunk, this.bytesStart); - this.bytesStart += chunk.byteLength; - } - - /** - * xhr onLoadEnd - */ - - }, { - key: 'onLoadEnd', - value: function onLoadEnd(e) { - this.emit(this.tag, 'video load end'); - } - - /** - * xhr onXhrError - */ - - }, { - key: 'onXhrError', - value: function onXhrError(e) { - var info = { - from: this.range.from, - to: this.range.to, - url: this.src, - msg: e.constructor.name + ' ' + e.type - }; - this.emit(this.tag, info); - } - }]); - - return MozChunkLoader; -}(CustEvent); - -/** -* 处理range的静态函数 -* author songguangyu -* emil 522963130@qq.com -*/ - -var Ioloader = function (_CustEvent) { - _inherits(Ioloader, _CustEvent); - - /** - * 处理io的调用器 缓存多余数据 - * @param {object} video config - */ - function Ioloader(config) { - _classCallCheck(this, Ioloader); - - var _this = _possibleConstructorReturn(this, (Ioloader.__proto__ || _Object$getPrototypeOf(Ioloader)).call(this)); - - _this.loader = null; - _this.config = {}; - _Object$assign(_this.config, config); - _this.selectLoader(); - _this.bufferSize = 1024 * 1024 * 3; // initial size: 3MB - _this.cacheBuffer = new ArrayBuffer(_this.bufferSize); - _this.cacheRemain = 0; - _this.stashByteStart = 0; - _this.enableStash = true; - _this.stashSize = 1024 * 384; - _this.resumeFrom = 0; - _this.currentRange = {}; - _this.totalReceive = 0; - _this.seekPonit = 0; - return _this; - } - - /** - * 自动选择io处理器 - */ - - - _createClass(Ioloader, [{ - key: 'selectLoader', - value: function selectLoader() { - var config = this.config; - var url = this.config.src; - - if (FetchLoader.isSupport()) { - this.loader = new FetchLoader(url, config); - } else if (MozChunkLoader.isSupport()) { - this.loader = new MozChunkLoader(url, config); - } else if (RangeLoader.isSupport()) { - this.loader = new RangeLoader(url, config); + } else { + Log.error(this.tag, 'video player is not already, must init player'); } - this.loader.arrivalDataCallback = this.onLoaderChunkArrival.bind(this); } - /** - * 数据接收器 - * @param {arrayBuffer} chunk data - * @param {number} chunk byte postion - */ + * 销毁kernel + * @memberof kernel + */ }, { - key: 'onLoaderChunkArrival', - value: function onLoaderChunkArrival(chunk, byteStart, keyframePoint) { - if (keyframePoint) { - this.seekPonit = keyframePoint; - } - if (this.arrivalDataCallback) { - this.totalReceive += chunk.byteLength; - - if (this.cacheRemain === 0 && this.stashByteStart === 0) { - // This is the first chunk after seek action - this.stashByteStart = byteStart; - } - if (this.cacheRemain + chunk.byteLength <= this.stashSize) { - // 小于cache大小 则看做数据太小 进行缓存 不进行下发 - var stashArray = new Uint8Array(this.cacheBuffer, 0, this.stashSize); - stashArray.set(new Uint8Array(chunk), this.cacheRemain); - this.cacheRemain += chunk.byteLength; - } else { - // 大于cache大小的 则把数据放入播放器 溢出数据进行缓存 - var _stashArray = new Uint8Array(this.cacheBuffer, 0, this.bufferSize); - if (this.cacheRemain > 0) { - // There're stash datas in buffer - // dispatch the whole stashBuffer, and stash remain data - // then append chunk to stashBuffer (stash) - var buffer = this.cacheBuffer.slice(0, this.cacheRemain); - var consumed = 0; - if (this.seekPonit) { - consumed = this.arrivalDataCallback(buffer, this.stashByteStart, this.seekPonit); - this.seekPonit = 0; - } else { - consumed = this.arrivalDataCallback(buffer, this.stashByteStart); - } - // const consumed = this.arrivalDataCallback(buffer, this.stashByteStart, keyframePoint); - if (consumed < buffer.byteLength) { - if (consumed > 0) { - var remainArray = new Uint8Array(buffer, consumed); - _stashArray.set(remainArray, 0); - this.cacheRemain = remainArray.byteLength; - this.stashByteStart += consumed; - } - } else { - this.cacheRemain = 0; - this.stashByteStart += consumed; - } - if (this.cacheRemain + chunk.byteLength > this.bufferSize) { - this.expandBuffer(this.cacheRemain + chunk.byteLength); - _stashArray = new Uint8Array(this.cacheBuffer, 0, this.bufferSize); - } - _stashArray.set(new Uint8Array(chunk), this.cacheRemain); - this.cacheRemain += chunk.byteLength; - } else { - // stash buffer empty, but chunkSize > stashSize (oh, holy shit) - // dispatch chunk directly and stash remain data - // const consumed = this.arrivalDataCallback(chunk, byteStart, keyframePoint); - var _consumed = 0; - if (this.seekPonit) { - _consumed = this.arrivalDataCallback(chunk, byteStart, this.seekPonit); - this.seekPonit = 0; - } else { - _consumed = this.arrivalDataCallback(chunk, byteStart); - } - if (_consumed < chunk.byteLength) { - var remain = chunk.byteLength - _consumed; - if (remain > this.bufferSize) { - this.expandBuffer(remain); - _stashArray = new Uint8Array(this.cacheBuffer, 0, this.bufferSize); - } - _stashArray.set(new Uint8Array(chunk, _consumed), 0); - this.cacheRemain += remain; - this.stashByteStart = byteStart + _consumed; - } - } - } + key: 'destroy', + value: function destroy() { + if (this.videokernel) { + this.videokernel.destroy(); + } else { + Log.error(this.tag, 'player is not exit'); } } - // if(this.arrivalDataCallback) { - // this.totalReceive += chunk.byteLength; - // if(this.cacheRemain) { - // if(this.cacheRemain + chunk.byteLength > this.bufferSize) { - // this.expandBuffer(); - // } - // console.log(this.cacheRemain); - // const stashArray = new Uint8Array(this.cacheBuffer, 0, this.bufferSize); - // stashArray.set(new Uint8Array(chunk), this.cacheRemain); - // this.cacheRemain = this.arrivalDataCallback(this.cacheBuffer, byteStart, this.seekPonit); - // if(this.cacheRemain && this.cacheRemain < chunk.byteLength) { - // this.initCacheBuffer(); - // const stashArray = new Uint8Array(this.cacheBuffer, 0, this.bufferSize); - // stashArray.set(new Uint8Array(chunk.slice(this.cacheRemain)), 0); - // } - // } else { - // this.cacheRemain = this.arrivalDataCallback(chunk, byteStart, this.seekPonit); - // } - - // } - // } /** - * 清空缓存buffer - */ - - }, { - key: 'initCacheBuffer', - value: function initCacheBuffer() { - this.cacheBuffer = new ArrayBuffer(this.bufferSize); - } - - /** - * 动态扩展buffer存储器大小 - * @param {number} chunk byte size - */ + * to play + * @memberof kernel + */ }, { - key: 'expandBuffer', - value: function expandBuffer(expectedBytes) { - var bufferNewSize = this.bufferSize; - // while (bufferNewSize < expectedBytes) { - // bufferNewSize *= 2; - // } - if (bufferNewSize < expectedBytes) { - bufferNewSize = expectedBytes; + key: 'play', + value: function play() { + if (this.videokernel) { + this.videokernel.play(); + } else { + Log.error(this.tag, 'video player is not already, must init player'); } - this.cacheBuffer = new ArrayBuffer(bufferNewSize); - this.bufferSize = bufferNewSize; } - /** - * 暂停 - */ + * pause + * @memberof kernel + */ }, { key: 'pause', value: function pause() { - // if (this.cacheRemain !== 0) { - // this.resumeFrom = this.stashByteStart; - // this.currentRange.to = this.stashByteStart - 1; - // } else { - // this.resumeFrom = this.currentRange.to + 1; - // } - this.loader.pause(); + if (this.videokernel && this.config.src) { + this.videokernel.pause(); + } else { + Log.error(this.tag, 'video player is not already, must init player'); + } } - /** - * 打开连接 - */ + * get video currentTime + * @memberof kernel + */ }, { - key: 'open', - value: function open(StartBytes) { - if (StartBytes === undefined) { - StartBytes = 0; - } - this.loader.open({ from: StartBytes, to: -1 }); - } + key: 'seek', /** - * 重新播放 - */ - + * seek to a point + * @memberof kernel + */ + value: function seek(seconds) { + if (!isNumber(seconds)) { + Log.error(this.tag, 'seek params must be a number'); + return; + } + return this.videokernel.seek(seconds); + } }, { - key: 'resume', - value: function resume() { - this.paused = false; - var bytes = this.totalReceive; - this.open(bytes); + key: 'refresh', + value: function refresh() { + this.videokernel.refresh(); } - /** - * seek - */ - - }, { - key: 'seek', - value: function seek(bytes, dropCache, keyframePoint) { - this.loader.open({ from: bytes, to: -1 }, keyframePoint); - } - }, { - key: 'destroy', - value: function destroy() { - this.pause(); - this.cacheBuffer = null; - } - }]); - - return Ioloader; -}(CustEvent); - -/* eslint-disable */ -var FlvTag = function () { - function FlvTag() { - _classCallCheck(this, FlvTag); - - this.tagType = -1; - this.dataSize = -1; - this.Timestamp = -1; - this.StreamID = -1; - this.body = -1; - this.time = -1; - this.arr = []; - } - - _createClass(FlvTag, [{ - key: 'getTime', - value: function getTime() { - // this.Timestamp.pop(); - this.arr = []; - for (var i = 0; i < this.Timestamp.length; i++) { - this.arr.push(this.Timestamp[i].toString(16).length == 1 ? '0' + this.Timestamp[i].toString(16) : this.Timestamp[i].toString(16)); - } - this.arr.pop(); - var time = this.arr.join(''); - this.time = parseInt(time, 16); - return parseInt(time, 16); - } - }]); - - return FlvTag; -}(); - -/* eslint-disable */ -function decodeUTF8$1(uint8array) { - var out = []; - var input = uint8array; - var i = 0; - var length = uint8array.length; - - while (i < length) { - if (input[i] < 0x80) { - out.push(String.fromCharCode(input[i])); - ++i; - continue; - } else if (input[i] < 0xC0) { - // fallthrough - } else if (input[i] < 0xE0) { - if (checkContinuation$1(input, i, 1)) { - var ucs4 = (input[i] & 0x1F) << 6 | input[i + 1] & 0x3F; - if (ucs4 >= 0x80) { - out.push(String.fromCharCode(ucs4 & 0xFFFF)); - i += 2; - continue; - } - } - } else if (input[i] < 0xF0) { - if (checkContinuation$1(input, i, 2)) { - var _ucs = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F; - if (_ucs >= 0x800 && (_ucs & 0xF800) !== 0xD800) { - out.push(String.fromCharCode(_ucs & 0xFFFF)); - i += 3; - continue; - } - } - } else if (input[i] < 0xF8) { - if (checkContinuation$1(input, i, 3)) { - var _ucs2 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12 | (input[i + 2] & 0x3F) << 6 | input[i + 3] & 0x3F; - if (_ucs2 > 0x10000 && _ucs2 < 0x110000) { - _ucs2 -= 0x10000; - out.push(String.fromCharCode(_ucs2 >>> 10 | 0xD800)); - out.push(String.fromCharCode(_ucs2 & 0x3FF | 0xDC00)); - i += 4; - continue; - } - } - } - out.push(String.fromCharCode(0xFFFD)); - ++i; - } - - return out.join(''); -} - -function checkContinuation$1(uint8array, start, checkLength) { - var array = uint8array; - if (start + checkLength < array.length) { - while (checkLength--) { - if ((array[++start] & 0xC0) !== 0x80) return false; - } - return true; - } else { - return false; - } -} - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -// Exponential-Golomb buffer decoder -var ExpGolomb = function () { - function ExpGolomb(uint8array) { - _classCallCheck(this, ExpGolomb); - - this.TAG = this.constructor.name; - - this._buffer = uint8array; - this._buffer_index = 0; - this._total_bytes = uint8array.byteLength; - this._total_bits = uint8array.byteLength * 8; - this._current_word = 0; - this._current_word_bits_left = 0; - } - - _createClass(ExpGolomb, [{ - key: 'destroy', - value: function destroy() { - this._buffer = null; - } - }, { - key: '_fillCurrentWord', - value: function _fillCurrentWord() { - var buffer_bytes_left = this._total_bytes - this._buffer_index; - if (buffer_bytes_left <= 0) { - throw new IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available'); - } - - var bytes_read = Math.min(4, buffer_bytes_left); - var word = new Uint8Array(4); - word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read)); - this._current_word = new DataView(word.buffer).getUint32(0, false); - - this._buffer_index += bytes_read; - this._current_word_bits_left = bytes_read * 8; - } - }, { - key: 'readBits', - value: function readBits(bits) { - if (bits > 32) { - throw new InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!'); - } - - if (bits <= this._current_word_bits_left) { - var _result = this._current_word >>> 32 - bits; - this._current_word <<= bits; - this._current_word_bits_left -= bits; - return _result; - } - - var result = this._current_word_bits_left ? this._current_word : 0; - result = result >>> 32 - this._current_word_bits_left; - var bits_need_left = bits - this._current_word_bits_left; - - this._fillCurrentWord(); - var bits_read_next = Math.min(bits_need_left, this._current_word_bits_left); - - var result2 = this._current_word >>> 32 - bits_read_next; - this._current_word <<= bits_read_next; - this._current_word_bits_left -= bits_read_next; - - result = result << bits_read_next | result2; - return result; - } - }, { - key: 'readBool', - value: function readBool() { - return this.readBits(1) === 1; - } - }, { - key: 'readByte', - value: function readByte() { - return this.readBits(8); - } - }, { - key: '_skipLeadingZero', - value: function _skipLeadingZero() { - var zero_count = void 0; - for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) { - if ((this._current_word & 0x80000000 >>> zero_count) !== 0) { - this._current_word <<= zero_count; - this._current_word_bits_left -= zero_count; - return zero_count; - } - } - this._fillCurrentWord(); - return zero_count + this._skipLeadingZero(); - } - }, { - key: 'readUEG', - value: function readUEG() { - // unsigned exponential golomb - var leading_zeros = this._skipLeadingZero(); - return this.readBits(leading_zeros + 1) - 1; - } - }, { - key: 'readSEG', - value: function readSEG() { - // signed exponential golomb - var value = this.readUEG(); - if (value & 0x01) { - return value + 1 >>> 1; - } else { - return -1 * (value >>> 1); - } - } - }]); - - return ExpGolomb; -}(); - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -var SPSParser = function () { - function SPSParser() { - _classCallCheck(this, SPSParser); - } - - _createClass(SPSParser, null, [{ - key: '_ebsp2rbsp', - value: function _ebsp2rbsp(uint8array) { - var src = uint8array; - var src_length = src.byteLength; - var dst = new Uint8Array(src_length); - var dst_idx = 0; - - for (var i = 0; i < src_length; i++) { - if (i >= 2) { - // Unescape: Skip 0x03 after 00 00 - if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) { - continue; - } - } - dst[dst_idx] = src[i]; - dst_idx++; - } - - return new Uint8Array(dst.buffer, 0, dst_idx); - } - }, { - key: 'parseSPS', - value: function parseSPS(uint8array) { - var rbsp = SPSParser._ebsp2rbsp(uint8array); - var gb = new ExpGolomb(rbsp); - - gb.readByte(); - var profile_idc = gb.readByte(); // profile_idc - gb.readByte(); // constraint_set_flags[5] + reserved_zero[3] - var level_idc = gb.readByte(); // level_idc - gb.readUEG(); // seq_parameter_set_id - - var profile_string = SPSParser.getProfileString(profile_idc); - var level_string = SPSParser.getLevelString(level_idc); - var chroma_format_idc = 1; - var chroma_format = 420; - var chroma_format_table = [0, 420, 422, 444]; - var bit_depth = 8; - - if (profile_idc === 100 || profile_idc === 110 || profile_idc === 122 || profile_idc === 244 || profile_idc === 44 || profile_idc === 83 || profile_idc === 86 || profile_idc === 118 || profile_idc === 128 || profile_idc === 138 || profile_idc === 144) { - - chroma_format_idc = gb.readUEG(); - if (chroma_format_idc === 3) { - gb.readBits(1); // separate_colour_plane_flag - } - if (chroma_format_idc <= 3) { - chroma_format = chroma_format_table[chroma_format_idc]; - } - - bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8 - gb.readUEG(); // bit_depth_chroma_minus8 - gb.readBits(1); // qpprime_y_zero_transform_bypass_flag - if (gb.readBool()) { - // seq_scaling_matrix_present_flag - var scaling_list_count = chroma_format_idc !== 3 ? 8 : 12; - for (var i = 0; i < scaling_list_count; i++) { - if (gb.readBool()) { - // seq_scaling_list_present_flag - if (i < 6) { - SPSParser._skipScalingList(gb, 16); - } else { - SPSParser._skipScalingList(gb, 64); - } - } - } - } - } - gb.readUEG(); // log2_max_frame_num_minus4 - var pic_order_cnt_type = gb.readUEG(); - if (pic_order_cnt_type === 0) { - gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4 - } else if (pic_order_cnt_type === 1) { - gb.readBits(1); // delta_pic_order_always_zero_flag - gb.readSEG(); // offset_for_non_ref_pic - gb.readSEG(); // offset_for_top_to_bottom_field - var num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG(); - for (var _i = 0; _i < num_ref_frames_in_pic_order_cnt_cycle; _i++) { - gb.readSEG(); // offset_for_ref_frame - } - } - gb.readUEG(); // max_num_ref_frames - gb.readBits(1); // gaps_in_frame_num_value_allowed_flag - - var pic_width_in_mbs_minus1 = gb.readUEG(); - var pic_height_in_map_units_minus1 = gb.readUEG(); - - var frame_mbs_only_flag = gb.readBits(1); - if (frame_mbs_only_flag === 0) { - gb.readBits(1); // mb_adaptive_frame_field_flag - } - gb.readBits(1); // direct_8x8_inference_flag - - var frame_crop_left_offset = 0; - var frame_crop_right_offset = 0; - var frame_crop_top_offset = 0; - var frame_crop_bottom_offset = 0; - - var frame_cropping_flag = gb.readBool(); - if (frame_cropping_flag) { - frame_crop_left_offset = gb.readUEG(); - frame_crop_right_offset = gb.readUEG(); - frame_crop_top_offset = gb.readUEG(); - frame_crop_bottom_offset = gb.readUEG(); - } - - var sar_width = 1, - sar_height = 1; - var fps = 0, - fps_fixed = true, - fps_num = 0, - fps_den = 0; - - var vui_parameters_present_flag = gb.readBool(); - if (vui_parameters_present_flag) { - if (gb.readBool()) { - // aspect_ratio_info_present_flag - var aspect_ratio_idc = gb.readByte(); - var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2]; - var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1]; - - if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) { - sar_width = sar_w_table[aspect_ratio_idc - 1]; - sar_height = sar_h_table[aspect_ratio_idc - 1]; - } else if (aspect_ratio_idc === 255) { - sar_width = gb.readByte() << 8 | gb.readByte(); - sar_height = gb.readByte() << 8 | gb.readByte(); - } - } - - if (gb.readBool()) { - // overscan_info_present_flag - gb.readBool(); // overscan_appropriate_flag - } - if (gb.readBool()) { - // video_signal_type_present_flag - gb.readBits(4); // video_format & video_full_range_flag - if (gb.readBool()) { - // colour_description_present_flag - gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients - } - } - if (gb.readBool()) { - // chroma_loc_info_present_flag - gb.readUEG(); // chroma_sample_loc_type_top_field - gb.readUEG(); // chroma_sample_loc_type_bottom_field - } - if (gb.readBool()) { - // timing_info_present_flag - var num_units_in_tick = gb.readBits(32); - var time_scale = gb.readBits(32); - fps_fixed = gb.readBool(); // fixed_frame_rate_flag - - fps_num = time_scale; - fps_den = num_units_in_tick * 2; - fps = fps_num / fps_den; - } - } - - var sarScale = 1; - if (sar_width !== 1 || sar_height !== 1) { - sarScale = sar_width / sar_height; - } - - var crop_unit_x = 0, - crop_unit_y = 0; - if (chroma_format_idc === 0) { - crop_unit_x = 1; - crop_unit_y = 2 - frame_mbs_only_flag; - } else { - var sub_wc = chroma_format_idc === 3 ? 1 : 2; - var sub_hc = chroma_format_idc === 1 ? 2 : 1; - crop_unit_x = sub_wc; - crop_unit_y = sub_hc * (2 - frame_mbs_only_flag); - } - - var codec_width = (pic_width_in_mbs_minus1 + 1) * 16; - var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16); - - codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x; - codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y; - - var present_width = Math.ceil(codec_width * sarScale); - - gb.destroy(); - gb = null; - - return { - profile_string: profile_string, // baseline, high, high10, ... - level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ... - bit_depth: bit_depth, // 8bit, 10bit, ... - chroma_format: chroma_format, // 4:2:0, 4:2:2, ... - chroma_format_string: SPSParser.getChromaFormatString(chroma_format), - - frame_rate: { - fixed: fps_fixed, - fps: fps, - fps_den: fps_den, - fps_num: fps_num - }, - - sar_ratio: { - width: sar_width, - height: sar_height - }, - - codec_size: { - width: codec_width, - height: codec_height - }, - - present_size: { - width: present_width, - height: codec_height - } - }; - } - }, { - key: '_skipScalingList', - value: function _skipScalingList(gb, count) { - var last_scale = 8, - next_scale = 8; - var delta_scale = 0; - for (var i = 0; i < count; i++) { - if (next_scale !== 0) { - delta_scale = gb.readSEG(); - next_scale = (last_scale + delta_scale + 256) % 256; - } - last_scale = next_scale === 0 ? last_scale : next_scale; - } - } - }, { - key: 'getProfileString', - value: function getProfileString(profile_idc) { - switch (profile_idc) { - case 66: - return 'Baseline'; - case 77: - return 'Main'; - case 88: - return 'Extended'; - case 100: - return 'High'; - case 110: - return 'High10'; - case 122: - return 'High422'; - case 244: - return 'High444'; - default: - return 'Unknown'; - } - } - }, { - key: 'getLevelString', - value: function getLevelString(level_idc) { - return (level_idc / 10).toFixed(1); - } - }, { - key: 'getChromaFormatString', - value: function getChromaFormatString(chroma) { - switch (chroma) { - case 420: - return '4:2:0'; - case 422: - return '4:2:2'; - case 444: - return '4:4:4'; - default: - return 'Unknown'; - } - } - }]); - - return SPSParser; -}(); - -/* eslint-disable */ -var le = function () { - var buf = new ArrayBuffer(2); - new DataView(buf).setInt16(0, 256, true); // little-endian write - return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE -}(); - -var flvDemux = function () { - function flvDemux() { - _classCallCheck(this, flvDemux); - } - - _createClass(flvDemux, null, [{ - key: 'parseObject', - value: function parseObject(arrayBuffer, dataOffset, dataSize) { - - var name = flvDemux.parseString(arrayBuffer, dataOffset, dataSize); - var value = flvDemux.parseScript(arrayBuffer, dataOffset + name.size); - var isObjectEnd = value.objectEnd; - - return { - data: { - name: name.data, - value: value.data - }, - size: value.size, - objectEnd: isObjectEnd - }; - } - }, { - key: 'parseVariable', - value: function parseVariable(arrayBuffer, dataOffset, dataSize) { - return flvDemux.parseObject(arrayBuffer, dataOffset, dataSize); - } - }, { - key: 'parseLongString', - value: function parseLongString(arrayBuffer, dataOffset, dataSize) { - - var v = new DataView(arrayBuffer, dataOffset); - var length = v.getUint32(0, !le); - - var str = void 0; - if (length > 0) { - str = decodeUTF8$1(new Uint8Array(arrayBuffer, dataOffset + 4, length)); - } else { - str = ''; - } - - return { - data: str, - size: 4 + length - }; - } - }, { - key: 'parseDate', - value: function parseDate(arrayBuffer, dataOffset, dataSize) { - - var v = new DataView(arrayBuffer, dataOffset); - var timestamp = v.getFloat64(0, !le); - var localTimeOffset = v.getInt16(8, !le); - timestamp += localTimeOffset * 60 * 1000; // get UTC time - - return { - data: new Date(timestamp), - size: 8 + 2 - }; - } - }, { - key: 'parseString', - value: function parseString(arrayBuffer, dataOffset, dataSize) { - var v = new DataView(arrayBuffer, dataOffset); - var length = v.getUint16(0, !le); - var str = void 0; - if (length > 0) { - str = decodeUTF8$1(new Uint8Array(arrayBuffer, dataOffset + 2, length)); - } else { - str = ''; - } - return { - data: str, - size: 2 + length - }; - } - - /** - * 解析metadata - */ - - }, { - key: 'parseMetadata', - value: function parseMetadata(arr) { - var name = flvDemux.parseScript(arr, 0); - var value = flvDemux.parseScript(arr, name.size, arr.length - name.size); - // return {} - var data = {}; - data[name.data] = value.data; - return data; - } - }, { - key: 'parseScript', - value: function parseScript(arr, offset, dataSize) { - var dataOffset = offset; - var object = {}; - var uint8 = new Uint8Array(arr); - var buffer = uint8.buffer; - var dv = new DataView(buffer, 0, dataSize); - var value = null; - var objectEnd = false; - var type = dv.getUint8(dataOffset); - dataOffset += 1; - - switch (type) { - case 0: - // Number(Double) type - value = dv.getFloat64(dataOffset, !le); - dataOffset += 8; - break; - case 1: - { - // Boolean type - var b = dv.getUint8(dataOffset); - value = !!b; - dataOffset += 1; - break; - } - case 2: - { - // String type - // dataOffset += 1; - var amfstr = flvDemux.parseString(buffer, dataOffset); - value = amfstr.data; - dataOffset += amfstr.size; - break; - } - case 3: - - { - // Object(s) type - value = {}; - var terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd - if ((dv.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) { - terminal = 3; - } - while (dataOffset < dataSize - 4) { - // 4 === type(UI8) + ScriptDataObjectEnd(UI24) - var amfobj = flvDemux.parseObject(buffer, dataOffset, dataSize - offset - terminal); - - if (amfobj.objectEnd) { - break; - } - value[amfobj.data.name] = amfobj.data.value; - // dataOffset += amfobj.size; - dataOffset = amfobj.size; - } - if (dataOffset <= dataSize - 3) { - var marker = v.getUint32(dataOffset - 1, !le) & 0x00FFFFFF; - if (marker === 9) { - dataOffset += 3; - } - } - break; - } - case 8: - { - // ECMA array type (Mixed array) - value = {}; - // dataOffset += 1; - dataOffset += 4; // ECMAArrayLength(UI32) - var _terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd - if ((dv.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) { - _terminal = 3; - } - while (dataOffset < dataSize - 8) { - // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24) - var amfvar = flvDemux.parseVariable(buffer, dataOffset); - - if (amfvar.objectEnd) { - break; - } - value[amfvar.data.name] = amfvar.data.value; - dataOffset = amfvar.size; - } - if (dataOffset <= dataSize - 3) { - var _marker = dv.getUint32(dataOffset - 1, !le) & 0x00FFFFFF; - if (_marker === 9) { - dataOffset += 3; - } - } - break; - } - case 9: - // ScriptDataObjectEnd - value = undefined; - dataOffset = 1; - objectEnd = true; - break; - case 10: - { - // Strict array type - // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf - value = []; - var strictArrayLength = dv.getUint32(dataOffset, !le); - dataOffset += 4; - for (var i = 0; i < strictArrayLength; i++) { - var val = flvDemux.parseScript(buffer, dataOffset); - value.push(val.data); - dataOffset = val.size; - } - break; - } - case 11: - { - // Date type - var date = flvDemux.parseDate(buffer, dataOffset + 1, dataSize - 1); - value = date.data; - dataOffset += date.size; - break; - } - case 12: - { - // Long string type - var amfLongStr = flvDemux.parseString(buffer, dataOffset + 1, dataSize - 1); - value = amfLongStr.data; - dataOffset += amfLongStr.size; - break; - } - default: - // ignore and skip - dataOffset = dataSize; - console.log('AMF', 'Unsupported AMF value type ' + type); - } - return { - data: value, - size: dataOffset - }; - } - }]); - - return flvDemux; -}(); - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -var MediaInfo = function () { - function MediaInfo() { - _classCallCheck(this, MediaInfo); - - this.mimeType = null; - this.duration = null; - - this.hasAudio = null; - this.hasVideo = null; - this.audioCodec = null; - this.videoCodec = null; - this.audioDataRate = null; - this.videoDataRate = null; - - this.audioSampleRate = null; - this.audioChannelCount = null; - - this.width = null; - this.height = null; - this.fps = null; - this.profile = null; - this.level = null; - this.chromaFormat = null; - this.sarNum = null; - this.sarDen = null; - - this.metadata = null; - this.segments = null; // MediaInfo[] - this.segmentCount = null; - this.hasKeyframesIndex = null; - this.keyframesIndex = null; - } - - _createClass(MediaInfo, [{ - key: "isComplete", - value: function isComplete() { - var audioInfoComplete = this.hasAudio === false || this.hasAudio === true && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null; - - var videoInfoComplete = this.hasVideo === false || this.hasVideo === true && this.videoCodec != null && this.width != null && this.height != null && this.fps != null && this.profile != null && this.level != null && this.chromaFormat != null && this.sarNum != null && this.sarDen != null; - - // keyframesIndex may not be present - return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && audioInfoComplete && videoInfoComplete; - } - }, { - key: "isSeekable", - value: function isSeekable() { - return this.hasKeyframesIndex === true; - } - }]); - - return MediaInfo; -}(); - -var Error$1 = function Error(type) { - _classCallCheck(this, Error); - - this.type = type; -}; - -/* eslint-disable */ -var tagDemux = function () { - function tagDemux() { - _classCallCheck(this, tagDemux); - - this.TAG = this.constructor.name; - - this._config = {}; - - this._onError = null; - this._onMediaInfo = null; - this._onTrackMetadata = null; - this._onDataAvailable = null; - - this._dataOffset = 0; - this._firstParse = true; - this._dispatch = false; - - this._hasAudio = false; - this._hasVideo = false; - - this._audioInitialMetadataDispatched = false; - this._videoInitialMetadataDispatched = false; - - this._mediaInfo = new MediaInfo(); - this._mediaInfo.hasAudio = this._hasAudio; - this._mediaInfo.hasVideo = this._hasVideo; - this._metadata = null; - this._audioMetadata = null; - this._videoMetadata = null; - - this._naluLengthSize = 4; - this._timestampBase = 0; // int32, in milliseconds - this._timescale = 1000; - this._duration = 0; // int32, in milliseconds - this._durationOverrided = false; - this._referenceFrameRate = { - fixed: true, - fps: 23.976, - fps_num: 23976, - fps_den: 1000 - }; - - this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, addcoefficient: 2, samples: [], length: 0 }; - this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 1, addcoefficient: 2, samples: [], length: 0 }; - - this._littleEndian = function () { - var buf = new ArrayBuffer(2); - new DataView(buf).setInt16(0, 256, true); // little-endian write - return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE - }(); - } - - _createClass(tagDemux, [{ - key: 'onMediaInfo', - value: function onMediaInfo(callback) { - this._onMediaInfo = callback; - } - }, { - key: 'parseMetadata', - value: function parseMetadata(arr) { - var data = flvDemux.parseMetadata(arr); - this._parseScriptData(data); - } - }, { - key: '_parseScriptData', - value: function _parseScriptData(obj) { - var scriptData = obj; - - if (scriptData.hasOwnProperty('onMetaData')) { - if (this._metadata) { - console.log(this.TAG, 'Found another onMetaData tag!'); - } - this._metadata = scriptData; - var onMetaData = this._metadata.onMetaData; - - if (typeof onMetaData.hasAudio === 'boolean') { - // hasAudio - this._hasAudio = onMetaData.hasAudio; - this._mediaInfo.hasAudio = this._hasAudio; - } - if (typeof onMetaData.hasVideo === 'boolean') { - // hasVideo - this._hasVideo = onMetaData.hasVideo; - this._mediaInfo.hasVideo = this._hasVideo; - } - if (typeof onMetaData.audiodatarate === 'number') { - // audiodatarate - this._mediaInfo.audioDataRate = onMetaData.audiodatarate; - } - if (typeof onMetaData.videodatarate === 'number') { - // videodatarate - this._mediaInfo.videoDataRate = onMetaData.videodatarate; - } - if (typeof onMetaData.width === 'number') { - // width - this._mediaInfo.width = onMetaData.width; - } - if (typeof onMetaData.height === 'number') { - // height - this._mediaInfo.height = onMetaData.height; - } - if (typeof onMetaData.duration === 'number') { - // duration - if (!this._durationOverrided) { - var duration = Math.floor(onMetaData.duration * this._timescale); - this._duration = duration; - this._mediaInfo.duration = duration; - } - } else { - this._mediaInfo.duration = 0; - } - if (typeof onMetaData.framerate === 'number') { - // framerate - var fps_num = Math.floor(onMetaData.framerate * 1000); - if (fps_num > 0) { - var fps = fps_num / 1000; - this._referenceFrameRate.fixed = true; - this._referenceFrameRate.fps = fps; - this._referenceFrameRate.fps_num = fps_num; - this._referenceFrameRate.fps_den = 1000; - this._mediaInfo.fps = fps; - } - } - if (_typeof(onMetaData.keyframes) === 'object') { - // keyframes - this._mediaInfo.hasKeyframesIndex = true; - var keyframes = onMetaData.keyframes; - keyframes.times = onMetaData.times; - keyframes.filepositions = onMetaData.filepositions; - this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes); - onMetaData.keyframes = null; // keyframes has been extracted, remove it - } else { - this._mediaInfo.hasKeyframesIndex = false; - } - this._dispatch = false; - this._mediaInfo.metadata = onMetaData; - console.log(this.TAG, 'Parsed onMetaData'); - // if (this._mediaInfo.isComplete()) { - // this._onMediaInfo(this._mediaInfo); - // } - return this._mediaInfo; - } - } - }, { - key: '_parseKeyframesIndex', - value: function _parseKeyframesIndex(keyframes) { - var times = []; - var filepositions = []; - - // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord) - for (var i = 1; i < keyframes.times.length; i++) { - var time = this._timestampBase + Math.floor(keyframes.times[i] * 1000); - times.push(time); - filepositions.push(keyframes.filepositions[i]); - } - - return { - times: times, - filepositions: filepositions - }; - } - - /** - * 传入tags输出moof和mdat - * - * @param {any} tags - * - * @memberof tagDemux - */ - - }, { - key: 'moofTag', - value: function moofTag(tags) { - - for (var i = 0; i < tags.length; i++) { - this._dispatch = true; - this.parseChunks(tags[i]); - // console.log("tagTimestamp", tags[i].getTime(), tags[i]); - } - if (this._isInitialMetadataDispatched()) { - if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) { - this._onDataAvailable(this._audioTrack, this._videoTrack); - } - } - } - }, { - key: 'parseChunks', - value: function parseChunks(flvtag) { - - switch (flvtag.tagType) { - case 8: - // Audio - this._parseAudioData(flvtag.body.buffer, 0, flvtag.body.length, flvtag.getTime()); - break; - case 9: - // Video - this._parseVideoData(flvtag.body.buffer, 0, flvtag.body.length, flvtag.getTime(), 0); - break; - case 18: - // ScriptDataObject - this.parseMetadata(flvtag.body); - break; - } - } - }, { - key: '_parseVideoData', - value: function _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) { - if (tagTimestamp == this._timestampBase && this._timestampBase != 0) { - throw new Error$1(tagTimestamp + this._timestampBase + '夭寿啦这个视频不是从0开始'); - // this.timestampBase(0); - } - if (dataSize <= 1) { - console.log(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!'); - return; - } - // 获取 video tag body 第一字节 - var spec = new Uint8Array(arrayBuffer, dataOffset, dataSize)[0]; - // 获取是否是关键帧 - var frameType = (spec & 240) >>> 4; - // 获取编码格式 - var codecId = spec & 15; - - if (codecId !== 7) { - throw new Error$1('Flv: Unsupported codec in video frame: ' + codecId); - // return; - } - - this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType); - } - }, { - key: '_parseAVCVideoPacket', - value: function _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) { - - if (dataSize < 4) { - console.log(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime'); - return; - } - - var le = this._littleEndian; - // 获取 video tag body 第2字节到结尾 - var v = new DataView(arrayBuffer, dataOffset, dataSize); - - // IF CodecID == 7 AVCPacketType - // 0 = AVC sequence header - // 1 = AVC NALU - // 2 = AVC end of sequence (lower level NALU sequence ender is not required or supported) - var packetType = v.getUint8(0); - // 3字节 - // IF AVCPacketType == 1 - // Composition time offset - // ELSE - // 0 - var cts = v.getUint32(0, !le) & 0x00FFFFFF; - - // IF AVCPacketType == 0 AVCDecoderConfigurationRecord(AVC sequence header) - // IF AVCPacketType == 1 One or more NALUs (Full frames are required) - - /** - *AVCDecoderConfigurationRecord.包含着是H.264解码相关比较重要的sps和pps信息, - *再给AVC解码器送数据 流之前一定要把sps和pps信息送出,否则的话解码器不能正常解码。 - *而且在解码器stop之后再次start之前,如seek、快进快退状态切换等, - *都 需要重新送一遍sps和pps的信息.AVCDecoderConfigurationRecord在FLV文件中一般情况也是出现1次, - *也就是第一个 video tag. - */ - if (packetType === 0) { - // AVCDecoderConfigurationRecord - this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4); - } else if (packetType === 1) { - // One or more Nalus - this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts); - } else if (packetType === 2) { - // empty, AVC end of sequence - } else { - throw new Error$1('Flv: Invalid video packet type ' + packetType); - } - } - - /** - * AVC 初始化 - */ - - }, { - key: '_parseAVCDecoderConfigurationRecord', - value: function _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) { - if (dataSize < 7) { - console.log(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!'); - return; - } - - var meta = this._videoMetadata; - var track = this._videoTrack; - var le = this._littleEndian; - var v = new DataView(arrayBuffer, dataOffset, dataSize); - - if (!meta) { - meta = this._videoMetadata = {}; - meta.type = 'video'; - meta.id = track.id; - meta.timescale = this._timescale; - meta.duration = this._duration; - } else { - if (typeof meta.avcc !== 'undefined') { - console.log(this.TAG, 'Found another AVCDecoderConfigurationRecord!'); - } - } - - var version = v.getUint8(0); // configurationVersion - var avcProfile = v.getUint8(1); // avcProfileIndication - var profileCompatibility = v.getUint8(2); // profile_compatibility - var avcLevel = v.getUint8(3); // AVCLevelIndication - - if (version !== 1 || avcProfile === 0) { - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord'); - return; - } - - this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne - if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) { - // holy shit!!! - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Strange NaluLengthSizeMinusOne: ' + (this._naluLengthSize - 1)); - return; - } - - var spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets - if (spsCount === 0 || spsCount > 1) { - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid H264 SPS count: ' + spsCount); - return; - } - - var offset = 6; - - for (var i = 0; i < spsCount; i++) { - var len = v.getUint16(offset, !le); // sequenceParameterSetLength - offset += 2; - - if (len === 0) { - continue; - } - - // Notice: Nalu without startcode header (00 00 00 01) - var sps = new Uint8Array(arrayBuffer, dataOffset + offset, len); - offset += len; - - var config = SPSParser.parseSPS(sps); - meta.codecWidth = config.codec_size.width; - meta.codecHeight = config.codec_size.height; - meta.presentWidth = config.present_size.width; - meta.presentHeight = config.present_size.height; - - meta.profile = config.profile_string; - meta.level = config.level_string; - meta.bitDepth = config.bit_depth; - meta.chromaFormat = config.chroma_format; - meta.sarRatio = config.sar_ratio; - meta.frameRate = config.frame_rate; - - if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) { - meta.frameRate = this._referenceFrameRate; - } - - var fps_den = meta.frameRate.fps_den; - var fps_num = meta.frameRate.fps_num; - meta.refSampleDuration = Math.floor(meta.timescale * (fps_den / fps_num)); - - var codecArray = sps.subarray(1, 4); - var codecString = 'avc1.'; - for (var j = 0; j < 3; j++) { - var h = codecArray[j].toString(16); - if (h.length < 2) { - h = '0' + h; - } - codecString += h; - } - meta.codec = codecString; - - var mi = this._mediaInfo; - mi.width = meta.codecWidth; - mi.height = meta.codecHeight; - mi.fps = meta.frameRate.fps; - mi.profile = meta.profile; - mi.level = meta.level; - mi.chromaFormat = config.chroma_format_string; - mi.sarNum = meta.sarRatio.width; - mi.sarDen = meta.sarRatio.height; - mi.videoCodec = codecString; - - if (mi.hasAudio) { - if (mi.audioCodec != null) { - mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"'; - } - } else { - mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"'; - } - if (mi.isComplete()) { - this._onMediaInfo(mi); - } - } - - var ppsCount = v.getUint8(offset); // numOfPictureParameterSets - if (ppsCount === 0 || ppsCount > 1) { - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid H264 PPS count: ' + ppsCount); - return; - } - - offset++; - - for (var _i = 0; _i < ppsCount; _i++) { - var _len = v.getUint16(offset, !le); // pictureParameterSetLength - offset += 2; - - if (_len === 0) { - continue; - } - - // pps is useless for extracting video information - offset += _len; - } - - meta.avcc = new Uint8Array(dataSize); - meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0); - console.log(this.TAG, 'Parsed AVCDecoderConfigurationRecord'); - - if (this._isInitialMetadataDispatched()) { - // flush parsed frames - if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) { - this._onDataAvailable(this._audioTrack, this._videoTrack); - } - } else { - this._videoInitialMetadataDispatched = true; - } - // notify new metadata - this._dispatch = false; - // if (this._onTrackMetadata) { - // this._onTrackMetadata.call(null, meta); - // } - - this._onTrackMetadata('video', meta); - } - }, { - key: 'timestampBase', - value: function timestampBase(i) { - this._timestampBase = i; - } - - /** - * 普通的AVC 片段 - */ - - }, { - key: '_parseAVCVideoData', - value: function _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) { - - var le = this._littleEndian; - var v = new DataView(arrayBuffer, dataOffset, dataSize); - - var units = [], - length = 0; - - var offset = 0; - var lengthSize = this._naluLengthSize; - var dts = this._timestampBase + tagTimestamp; - var keyframe = frameType === 1; // from FLV Frame Type constants - - while (offset < dataSize) { - if (offset + 4 >= dataSize) { - console.log(this.TAG, 'Malformed Nalu near timestamp ' + dts + ', offset = ' + offset + ', dataSize = ' + dataSize); - break; // data not enough for next Nalu - } - // Nalu with length-header (AVC1) - var naluSize = v.getUint32(offset, !le); // Big-Endian read - if (lengthSize === 3) { - naluSize >>>= 8; - } - if (naluSize > dataSize - lengthSize) { - console.log(this.TAG, 'Malformed Nalus near timestamp ' + dts + ', NaluSize > DataSize!'); - return; - } - - var unitType = v.getUint8(offset + lengthSize) & 0x1F; - - if (unitType === 5) { - // IDR - keyframe = true; - } - - var data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize); - var unit = { type: unitType, data: data }; - units.push(unit); - length += data.byteLength; - - offset += lengthSize + naluSize; - } - - if (units.length) { - var track = this._videoTrack; - var avcSample = { - units: units, - length: length, - isKeyframe: keyframe, - dts: dts, - cts: cts, - pts: dts + cts - }; - if (keyframe) { - avcSample.fileposition = tagPosition; - } - track.samples.push(avcSample); - track.length += length; - } - } - }, { - key: '_parseAudioData', - value: function _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) { - if (tagTimestamp == this._timestampBase && this._timestampBase != 0) { - console.log(tagTimestamp, this._timestampBase, '夭寿啦这个视频不是从0开始'); - // timestampBase(0); - } - - if (dataSize <= 1) { - console.log(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!'); - return; - } - - var meta = this._audioMetadata; - var track = this._audioTrack; - - if (!meta || !meta.codec) { - // initial metadata - meta = this._audioMetadata = {}; - meta.type = 'audio'; - meta.id = track.id; - meta.timescale = this._timescale; - meta.duration = this._duration; - - var le = this._littleEndian; - var v = new DataView(arrayBuffer, dataOffset, dataSize); - - var soundSpec = v.getUint8(0); - - var soundFormat = soundSpec >>> 4; - if (soundFormat !== 10) { - // AAC - // TODO: support MP3 audio codec - this._onError(DemuxErrors.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat); - return; - } - - var soundRate = 0; - var soundRateIndex = (soundSpec & 12) >>> 2; - - var soundRateTable = [5500, 11025, 22050, 44100, 48000]; - - if (soundRateIndex < soundRateTable.length) { - soundRate = soundRateTable[soundRateIndex]; - } else { - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex); - return; - } - - var soundSize = (soundSpec & 2) >>> 1; // unused - var soundType = soundSpec & 1; - - meta.audioSampleRate = soundRate; - meta.channelCount = soundType === 0 ? 1 : 2; - meta.refSampleDuration = Math.floor(1024 / meta.audioSampleRate * meta.timescale); - meta.codec = 'mp4a.40.5'; - } - - var aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1); - if (aacData == undefined) { - return; - } - - if (aacData.packetType === 0) { - // AAC sequence header (AudioSpecificConfig) - if (meta.config) { - console.log(this.TAG, 'Found another AudioSpecificConfig!'); - } - var misc = aacData.data; - meta.audioSampleRate = misc.samplingRate; - meta.channelCount = misc.channelCount; - meta.codec = misc.codec; - meta.config = misc.config; - // The decode result of an aac sample is 1024 PCM samples - meta.refSampleDuration = Math.floor(1024 / meta.audioSampleRate * meta.timescale); - console.log(this.TAG, 'Parsed AudioSpecificConfig'); - - if (this._isInitialMetadataDispatched()) { - // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer - if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) { - this._onDataAvailable(this._audioTrack, this._videoTrack); - } - } else { - this._audioInitialMetadataDispatched = true; - } - // then notify new metadata - this._dispatch = false; - this._onTrackMetadata('audio', meta); - - var mi = this._mediaInfo; - mi.audioCodec = 'mp4a.40.' + misc.originalAudioObjectType; - mi.audioSampleRate = meta.audioSampleRate; - mi.audioChannelCount = meta.channelCount; - if (mi.hasVideo) { - if (mi.videoCodec != null) { - mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"'; - } - } else { - mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"'; - } - if (mi.isComplete()) { - this._onMediaInfo(mi); - } - return; - } else if (aacData.packetType === 1) { - // AAC raw frame data - var dts = this._timestampBase + tagTimestamp; - var aacSample = { unit: aacData.data, dts: dts, pts: dts }; - track.samples.push(aacSample); - track.length += aacData.data.length; - } else { - console.log(this.TAG, 'Flv: Unsupported AAC data type ' + aacData.packetType); - } - } - }, { - key: '_parseAACAudioData', - value: function _parseAACAudioData(arrayBuffer, dataOffset, dataSize) { - if (dataSize <= 1) { - console.log(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!'); - return; - } - - var result = {}; - var array = new Uint8Array(arrayBuffer, dataOffset, dataSize); - - result.packetType = array[0]; - - if (array[0] === 0) { - result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1); - } else { - result.data = array.subarray(1); - } - - return result; - } - }, { - key: '_parseAACAudioSpecificConfig', - value: function _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) { - var array = new Uint8Array(arrayBuffer, dataOffset, dataSize); - var config = null; - - var mpegSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; - - /* Audio Object Type: - 0: Null - 1: AAC Main - 2: AAC LC - 3: AAC SSR (Scalable Sample Rate) - 4: AAC LTP (Long Term Prediction) - 5: HE-AAC / SBR (Spectral Band Replication) - 6: AAC Scalable - */ - - var audioObjectType = 0; - var originalAudioObjectType = 0; - var audioExtensionObjectType = null; - var samplingIndex = 0; - var extensionSamplingIndex = null; - // debugger; - // 5 bits - audioObjectType = originalAudioObjectType = array[0] >>> 3; - // 4 bits - samplingIndex = (array[0] & 0x07) << 1 | array[1] >>> 7; - if (samplingIndex < 0 || samplingIndex >= mpegSamplingRates.length) { - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!'); - return; - } - - var samplingFrequence = mpegSamplingRates[samplingIndex]; - - // 4 bits - var channelConfig = (array[1] & 0x78) >>> 3; - if (channelConfig < 0 || channelConfig >= 8) { - this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid channel configuration'); - return; - } - - if (audioObjectType === 5) { - // HE-AAC? - // 4 bits - extensionSamplingIndex = (array[1] & 0x07) << 1 | array[2] >>> 7; - // 5 bits - audioExtensionObjectType = (array[2] & 0x7C) >>> 2; - } - - // workarounds for various browsers - var userAgent = self.navigator.userAgent.toLowerCase(); - - if (userAgent.indexOf('firefox') !== -1) { - // firefox: use SBR (HE-AAC) if freq less than 24kHz - if (samplingIndex >= 6) { - audioObjectType = 5; - config = new Array(4); - extensionSamplingIndex = samplingIndex - 3; - } else { - // use LC-AAC - audioObjectType = 2; - config = new Array(2); - extensionSamplingIndex = samplingIndex; - } - } else if (userAgent.indexOf('android') !== -1) { - // android: always use LC-AAC - audioObjectType = 2; - config = new Array(2); - extensionSamplingIndex = samplingIndex; - } else { - // for other browsers, e.g. chrome... - // Always use HE-AAC to make it easier to switch aac codec profile - audioObjectType = 5; - extensionSamplingIndex = samplingIndex; - config = new Array(4); - - if (samplingIndex >= 6) { - extensionSamplingIndex = samplingIndex - 3; - } else if (channelConfig === 1) { - // Mono channel - audioObjectType = 2; - config = new Array(2); - extensionSamplingIndex = samplingIndex; - } - } - - config[0] = audioObjectType << 3; - config[0] |= (samplingIndex & 0x0F) >>> 1; - config[1] = (samplingIndex & 0x0F) << 7; - config[1] |= (channelConfig & 0x0F) << 3; - if (audioObjectType === 5) { - config[1] |= (extensionSamplingIndex & 0x0F) >>> 1; - config[2] = (extensionSamplingIndex & 0x01) << 7; - // extended audio object type: force to 2 (LC-AAC) - config[2] |= 2 << 2; - config[3] = 0; - } - - return { - config: config, - samplingRate: samplingFrequence, - channelCount: channelConfig, - codec: 'mp4a.40.' + audioObjectType, - originalAudioObjectType: originalAudioObjectType - }; - } - }, { - key: '_isInitialMetadataDispatched', - value: function _isInitialMetadataDispatched() { - if (this._hasAudio && this._hasVideo) { - // both audio & video - return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched; - } - if (this._hasAudio && !this._hasVideo) { - // audio only - return this._audioInitialMetadataDispatched; - } - if (!this._hasAudio && this._hasVideo) { - // video only - return this._videoInitialMetadataDispatched; - } - } - }]); - - return tagDemux; -}(); - -var tagdemux = new tagDemux(); - -/* eslint-disable */ -var FlvParse = function () { - function FlvParse() { - _classCallCheck(this, FlvParse); - - this.tempUint8 = new Uint8Array(); - this.arrTag = []; - this.index = 0; - this.tempArr = []; - this.stop = false; - this.offset = 0; - this.frist = true; - this._hasAudio = false; - this._hasVideo = false; - } - - /** - * 接受 外部的flv二进制数据 - */ - - - _createClass(FlvParse, [{ - key: 'setFlv', - value: function setFlv(uint8) { - this.stop = false; - this.arrTag = []; - this.index = 0; - this.tempUint8 = uint8; - if (this.tempUint8.length > 13 && this.tempUint8[0] == 70 && this.tempUint8[1] == 76 && this.tempUint8[2] == 86) { - this.probe(this.tempUint8.buffer); - this.read(9); // 略掉9个字节的flv header tag - this.read(4); // 略掉第一个4字节的 tag size - this.parse(); - this.frist = false; - return this.offset; - } else if (!this.frist) { - return this.parse(); - } else { - return this.offset; - } - } - }, { - key: 'probe', - value: function probe(buffer) { - var data = new Uint8Array(buffer); - var mismatch = { match: false }; - - if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) { - return mismatch; - } - - var hasAudio = (data[4] & 4) >>> 2 !== 0; - var hasVideo = (data[4] & 1) !== 0; - - if (!hasAudio && !hasVideo) { - return mismatch; - } - this._hasAudio = tagdemux._hasAudio = hasAudio; - this._hasVideo = tagdemux._hasVideo = hasVideo; - return { - match: true, - hasAudioTrack: hasAudio, - hasVideoTrack: hasVideo - }; - } - - /** - * 开始解析 - */ - - }, { - key: 'parse', - value: function parse() { - - while (this.index < this.tempUint8.length && !this.stop) { - this.offset = this.index; - - var t = new FlvTag(); - if (this.tempUint8.length - this.index >= 11) { - t.tagType = this.read(1)[0]; // 取出tag类型 - t.dataSize = this.read(3); // 取出包体大小 - t.Timestamp = this.read(4); // 取出解码时间 - t.StreamID = this.read(3); // 取出stream id - } else { - this.stop = true; - continue; - } - if (t.tagType == 18 || t.tagType == 8 || t.tagType == 9) {} else { - throw new Error$1('wrong tagType' + t.tagType); - } - if (this.tempUint8.length - this.index >= this.getBodySum(t.dataSize) + 4) { - t.body = this.read(this.getBodySum(t.dataSize)); // 取出body - if (t.tagType == 9 && this._hasVideo) { - this.arrTag.push(t); - } - if (t.tagType == 8 && this._hasAudio) { - this.arrTag.push(t); - } - if (t.tagType == 18) { - this.arrTag.push(t); - } - this.read(4); - } else { - this.stop = true; - continue; - } - this.offset = this.index; - } - - return this.offset; - } - }, { - key: 'read', - value: function read(length) { - // let u8a = new Uint8Array(length); - // u8a.set(this.tempUint8.subarray(this.index, this.index + length), 0); - var u8a = this.tempUint8.slice(this.index, this.index + length); - this.index += length; - return u8a; - } - - /** - * 计算tag包体大小 - */ - - }, { - key: 'getBodySum', - value: function getBodySum(arr) { - var _str = ''; - _str += arr[0].toString(16).length == 1 ? '0' + arr[0].toString(16) : arr[0].toString(16); - _str += arr[1].toString(16).length == 1 ? '0' + arr[1].toString(16) : arr[1].toString(16); - _str += arr[2].toString(16).length == 1 ? '0' + arr[2].toString(16) : arr[2].toString(16); - return parseInt(_str, 16); - } - }]); - - return FlvParse; -}(); - -var flvparse = new FlvParse(); - -/** - * 代码借鉴了flv.js - * 增加了自己的注释和写法 - */ -/* eslint-disable */ -var MP4 = function () { - function MP4() { - _classCallCheck(this, MP4); - } - - _createClass(MP4, null, [{ - key: 'init', - value: function init() { - MP4.types = { - avc1: [], - avcC: [], - btrt: [], - dinf: [], - dref: [], - esds: [], - ftyp: [], - hdlr: [], - mdat: [], - mdhd: [], - mdia: [], - mfhd: [], - minf: [], - moof: [], - moov: [], - mp4a: [], - mvex: [], - mvhd: [], - sdtp: [], - stbl: [], - stco: [], - stsc: [], - stsd: [], - stsz: [], - stts: [], - tfdt: [], - tfhd: [], - traf: [], - trak: [], - trun: [], - trex: [], - tkhd: [], - vmhd: [], - smhd: [] - }; - - for (var name in MP4.types) { - if (MP4.types.hasOwnProperty(name)) { - MP4.types[name] = [name.charCodeAt(0), name.charCodeAt(1), name.charCodeAt(2), name.charCodeAt(3)]; - } - } - - var constants = MP4.constants = {}; - - constants.FTYP = new Uint8Array([0x69, 0x73, 0x6F, 0x6D, // major_brand: isom isom MP4 Base Media v1 [IS0 14496-12:2003] ISO YES video/mp4 - 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01 - 0x69, 0x73, 0x6F, 0x6D, // isom - 0x61, 0x76, 0x63, 0x31 // avc1 - ]); - - constants.STSD_PREFIX = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags version字段后会有一个entry count字段 - 0x00, 0x00, 0x00, 0x01 // entry_count 根据entry的个数,每个entry会有type信息,如“vide”、“sund”等,根据type不同sample description会提供不同的信息,例如对于video track,会有“VisualSampleEntry”类型信息,对于audio track会有“AudioSampleEntry”类型信息。 - ]); - - constants.STTS = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags - 0x00, 0x00, 0x00, 0x00 // entry_count 0个索引 - ]); - - constants.STSC = constants.STCO = constants.STTS; - - constants.STSZ = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags - 0x00, 0x00, 0x00, 0x00, // sample_size - 0x00, 0x00, 0x00, 0x00 // sample_count - ]); - - constants.HDLR_VIDEO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags - 0x00, 0x00, 0x00, 0x00, // pre_defined - 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' 在media box中,该值为4个字符 “vide”— video track - 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 保留位 - 0x56, 0x69, 0x64, 0x65, 0x6F, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: VideoHandler 长度不定 track type name,以‘\0’结尾的字符串 - ]); - - constants.HDLR_AUDIO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags - 0x00, 0x00, 0x00, 0x00, // pre_defined - 0x73, 0x6F, 0x75, 0x6E, // handler_type: 'soun'在media box中,该值为4个字符 “soun”— audio track - 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 保留位 - 0x53, 0x6F, 0x75, 0x6E, 0x64, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: SoundHandler 长度不定 track type name,以‘\0’结尾的字符串 - ]); - - constants.DREF = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags - 0x00, 0x00, 0x00, 0x01, // entry_count 1个url - // url box开始 - 0x00, 0x00, 0x00, 0x0C, // entry_size - 0x75, 0x72, 0x6C, 0x20, // type 'url ' - 0x00, 0x00, 0x00, 0x01 // version(0) + flags 当“url”或“urn”的box flag为1时,字符串均为空。 - ]); - - // Sound media header - constants.SMHD = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags box版本,0或1,一般为0。 - 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2) 立体声平衡,[8.8] 格式值,一般为0,-1.0表示全部左声道,1.0表示全部右声道+2位保留位 - ]); - - // video media header - constants.VMHD = new Uint8Array([0x00, 0x00, 0x00, 0x01, // version(0) + flags - 0x00, 0x00, // graphicsmode: 2 bytes 视频合成模式,为0时拷贝原始图像,否则与opcolor进行合成 //理论上是4位啊 暂时保留 - 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes {red,green,blue} - 0x00, 0x00]); - } - - /** - * 封装box - */ - - }, { - key: 'box', - value: function box(type) { - var size = 8; - var result = null; - var datas = Array.prototype.slice.call(arguments, 1); - var arrayCount = datas.length; - - for (var i = 0; i < arrayCount; i++) { - size += datas[i].byteLength; - } - // box头部大小 - result = new Uint8Array(size); - result[0] = size >>> 24 & 0xFF; // size - result[1] = size >>> 16 & 0xFF; - result[2] = size >>> 8 & 0xFF; - result[3] = size & 0xFF; - // 写入box的type - result.set(type, 4); // type - - var offset = 8; - for (var _i = 0; _i < arrayCount; _i++) { - // data body - result.set(datas[_i], offset); - offset += datas[_i].byteLength; - } - - return result; - } - - // 创建ftyp&moov - - }, { - key: 'generateInitSegment', - value: function generateInitSegment(meta) { - if (meta.constructor != Array) { - meta = [meta]; - } - var ftyp = MP4.box(MP4.types.ftyp, MP4.constants.FTYP); - var moov = MP4.moov(meta); - - var result = new Uint8Array(ftyp.byteLength + moov.byteLength); - result.set(ftyp, 0); - result.set(moov, ftyp.byteLength); - return result; - } - - // Movie metadata box - - }, { - key: 'moov', - value: function moov(meta) { - var mvhd = MP4.mvhd(meta[0].timescale, meta[0].duration); // /moov里面的第一个box - var vtrak = MP4.trak(meta[0]); - var atrak = void 0; - if (meta.length > 1) { - atrak = MP4.trak(meta[1]); - } - - var mvex = MP4.mvex(meta); - if (meta.length > 1) { - return MP4.box(MP4.types.moov, mvhd, vtrak, atrak, mvex); - } else { - return MP4.box(MP4.types.moov, mvhd, vtrak, mvex); - } - } - - // Movie header box - - }, { - key: 'mvhd', - value: function mvhd(timescale, duration) { - return MP4.box(MP4.types.mvhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags 1位的box版本+3位flags box版本,0或1,一般为0。(以下字节数均按version=0) - 0x00, 0x00, 0x00, 0x00, // creation_time 创建时间 (相对于UTC时间1904-01-01零点的秒数) - 0x00, 0x00, 0x00, 0x00, // modification_time 修改时间 - timescale >>> 24 & 0xFF, // timescale: 4 bytes 文件媒体在1秒时间内的刻度值,可以理解为1秒长度 - timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes 该track的时间长度,用duration和time scale值可以计算track时长,比如audio track的time scale = 8000, duration = 560128,时长为70.016,video track的time scale = 600, duration = 42000,时长为70 - duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0 推荐播放速率,高16位和低16位分别为小数点整数部分和小数部分,即[16.16] 格式,该值为1.0(0x00010000)表示正常前向播放 - 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes) 与rate类似,[8.8] 格式,1.0(0x0100)表示最大音量 - 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes 保留位 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix---- - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 视频变换矩阵 线性代数 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // ----end composition matrix---- - 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes---- - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre-defined 保留位 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ----end pre_defined 6 * 4 bytes---- - 0xFF, 0xFF, 0xFF, 0xFF // next_track_ID 下一个track使用的id号 - ])); - } - - // Track box - - }, { - key: 'trak', - value: function trak(meta) { - return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta)); - } - - // Track header box - - }, { - key: 'tkhd', - value: function tkhd(meta) { - var trackId = meta.id, - duration = meta.duration; - var width = meta.presentWidth, - height = meta.presentHeight; - - return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, 0x00, 0x00, 0x07, // version(0) + flags 1位版本 box版本,0或1,一般为0。(以下字节数均按version=0)按位或操作结果值,预定义如下: - // 0x000001 track_enabled,否则该track不被播放; - // 0x000002 track_in_movie,表示该track在播放中被引用; - // 0x000004 track_in_preview,表示该track在预览时被引用。 - // 一般该值为7,1+2+4 如果一个媒体所有track均未设置track_in_movie和track_in_preview,将被理解为所有track均设置了这两项;对于hint track,该值为0 - // hint track  这个特殊的track并不包含媒体数据,而是包含了一些将其他数据track打包成流媒体的指示信息。 - 0x00, 0x00, 0x00, 0x00, // creation_time 创建时间(相对于UTC时间1904-01-01零点的秒数) - 0x00, 0x00, 0x00, 0x00, // modification_time 修改时间 - trackId >>> 24 & 0xFF, // track_ID: 4 bytes id号,不能重复且不能为0 - trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes 保留位 - duration >>> 24 & 0xFF, // duration: 4 bytes track的时间长度 - duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes 保留位 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes) 视频层,默认为0,值小的在上层.track分组信息,默认为0表示该track未与其他track有群组关系 - 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes) [8.8] 格式,如果为音频track,1.0(0x0100)表示最大音量;否则为0 +保留位 - 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix---- - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // 视频变换矩阵 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // ----end composition matrix---- - width >>> 8 & 0xFF, // //宽度 - width & 0xFF, 0x00, 0x00, height >>> 8 & 0xFF, // 高度 - height & 0xFF, 0x00, 0x00])); - } - - /** - * “mdia”也是个container box,其子box的结构和种类还是比较复杂的。先来看一个“mdia”的实例结构树图。 - * 总体来说,“mdia”定义了track媒体类型以及sample数据,描述sample信息。一般“mdia”包含一个“mdhd”, - * 一个“hdlr”和一个“minf”,其中“mdhd”为media header box,“hdlr”为handler reference box, - * “minf”为media information box。 - * - * mdia - * mdhd - * hdlr - * minf - * smhd - * dinf - * dref - * url - * stbl - * stsd - * mp4a - * esds - * stts - * stsc - * stsz - * stco - */ - - }, { - key: 'mdia', - value: function mdia(meta) { - return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta)); - } - - // Media header box - - }, { - key: 'mdhd', - value: function mdhd(meta) { - var timescale = meta.timescale; - var duration = meta.duration; - return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags // version(0) + flags box版本,0或1,一般为0。 - 0x00, 0x00, 0x00, 0x00, // creation_time 创建时间 - 0x00, 0x00, 0x00, 0x00, // modification_time修改时间 - timescale >>> 24 & 0xFF, // timescale: 4 bytes 文件媒体在1秒时间内的刻度值,可以理解为1秒长度 - timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes track的时间长度 - duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x55, 0xC4, // language: und (undetermined) 媒体语言码。最高位为0,后面15位为3个字符(见ISO 639-2/T标准中定义) - 0x00, 0x00 // pre_defined = 0 - ])); - } - - // Media handler reference box - - }, { - key: 'hdlr', - value: function hdlr(meta) { - var data = null; - if (meta.type === 'audio') { - data = MP4.constants.HDLR_AUDIO; - } else { - data = MP4.constants.HDLR_VIDEO; - } - return MP4.box(MP4.types.hdlr, data); - } - - /** - * “minf”存储了解释track媒体数据的handler-specific信息,media handler用这些信息将媒体时间映射到媒体数据并进行处理。“minf”中的信息格式和内容与媒体类型以及解释媒体数据的media handler密切相关,其他media handler不知道如何解释这些信息。“minf”是一个container box,其实际内容由子box说明。 - 一般情况下,“minf”包含一个header box,一个“dinf”和一个“stbl”,其中,header box根据track type(即media handler type)分为“vmhd”、“smhd”、“hmhd”和“nmhd”,“dinf”为data information box,“stbl”为sample table box。下面分别介绍。 - * - */ - // Media infomation box - - }, { - key: 'minf', - value: function minf(meta) { - // header box根据track type(即media handler type)分为“vmhd”、“smhd”、“hmhd”和“nmhd” - var xmhd = null; - if (meta.type === 'audio') { - xmhd = MP4.box(MP4.types.smhd, MP4.constants.SMHD); - } else { - xmhd = MP4.box(MP4.types.vmhd, MP4.constants.VMHD); - } - return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta)); - } - - /** - * Data Information Box - * “dinf”解释如何定位媒体信息,是一个container box。“dinf”一般包含一个“dref”,即data reference box; - * “dref”下会包含若干个“url”或“urn”,这些box组成一个表,用来定位track数据。 - * 简单的说,track可以被分成若干段,每一段都可以根据“url”或“urn”指向的地址来获取数据, - * sample描述中会用这些片段的序号将这些片段组成一个完整的track。 - * 一般情况下,当数据被完全包含在文件中时,“url”或“urn”中的定位字符串是空的。 - */ - - }, { - key: 'dinf', - value: function dinf() { - var result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF)); - return result; - } - - /** - * Sample Table Box(stbl) - * “stbl”几乎是普通的MP4文件中最复杂的一个box了,首先需要回忆一下sample的概念。 - * sample是媒体数据存储的单位,存储在media的chunk中,chunk和sample的长度均可互不相同,如下图所示。 - “stbl”是一个container box,其子box包括:sample description box(stsd)、 - * time to sample box(stts)、sample size box(stsz或stz2)、 - * sample to chunk box(stsc)、chunk offset box(stco或co64)、 - * composition time to sample box(ctts)、sync sample box(stss) - * stsd”必不可少,且至少包含一个条目,该box包含了data reference box进行sample数据检索的信息。 - * 没有“stsd”就无法计算media sample的存储位置。“stsd”包含了编码的信息,其存储的信息随媒体类型不同而不同。 - * stbl - * stsd - * avc1 - * avcC - * stts - * stsc - * stsz - * stco - */ - - }, { - key: 'stbl', - value: function stbl(meta) { - var result = MP4.box(MP4.types.stbl, // type: stbl - MP4.stsd(meta), // Sample Description Table - MP4.box(MP4.types.stts, MP4.constants.STTS), // Time-To-Sample 因为stts的entry count 为0 - // 所以没有关键帧index 的stss - // 也没有CTTS box CTTS是记录偏移量 - MP4.box(MP4.types.stsc, MP4.constants.STSC), // Sample-To-Chunk - MP4.box(MP4.types.stsz, MP4.constants.STSZ), // Sample size - MP4.box(MP4.types.stco, MP4.constants.STCO) // Chunk offset - ); - return result; - } - - /** - * Sample Description Box(stsd) - box header和version字段后会有一个entry count字段, - * 根据entry的个数,每个entry会有type信息,如“vide”、“sund”等, - * 根据type不同sample description会提供不同的信息,例如对于video track, - * 会有“VisualSampleEntry”类型信息,对于audio track会有“AudioSampleEntry”类型信息。 - * * stsd - * mp4a - * esds - * - * - * - * - * 4 bytes - length in total - 4 bytes - 4 char code of sample description table (stsd) - 4 bytes - version & flags - 4 bytes - number of sample entries (num_sample_entries) - [ - 4 bytes - length of sample entry (len_sample_entry) - 4 bytes - 4 char code of sample entry - ('len_sample_entry' - 8) bytes of data - ] (repeated 'num_sample_entries' times) - (4 bytes - optional 0x00000000 as end of box marker ) - */ - - }, { - key: 'stsd', - value: function stsd(meta) { - if (meta.type === 'audio') { - return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(meta)); - } else { - return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(meta)); - } - } - }, { - key: 'mp4a', - value: function mp4a(meta) { - var channelCount = meta.channelCount; - var sampleRate = meta.audioSampleRate; - - var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4) 6个字节,设置为0; - 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2) - 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes 保留位 - 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2) 单声道还是双声道 - 0x00, 0x10, // sampleSize(2) - 0x00, 0x00, 0x00, 0x00, // reserved(4) 4字节保留位 - sampleRate >>> 8 & 0xFF, // Audio sample rate 显然要右移16位才有意义 template unsigned int(32) samplerate = {timescale of media}<<16; - sampleRate & 0xFF, 0x00, 0x00]); - - return MP4.box(MP4.types.mp4a, data, MP4.esds(meta)); - } - }, { - key: 'esds', - value: function esds(meta) { - var config = meta.config; - var configSize = config.length; - var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version 0 + flags - - 0x03, // descriptor_type MP4ESDescrTag - 0x17 + configSize, // length3 - 0x00, 0x01, // es_id - 0x00, // stream_priority - - 0x04, // descriptor_type MP4DecConfigDescrTag - 0x0F + configSize, // length - 0x40, // codec: mpeg4_audio - /** - *当objectTypeIndication为0x40时,为MPEG-4 Audio(MPEG-4 Audio generally is thought of as AAC - * but there is a whole framework of audio codecs that can Go in MPEG-4 Audio including AAC, BSAC, ALS, CELP, - * and something called MP3On4),如果想更细分format为aac还是mp3, - * 可以读取MP4DecSpecificDescr层data[0]的前五位 - */ - 0x15, // stream_type: Audio - 0x00, 0x00, 0x00, // buffer_size - 0x00, 0x00, 0x00, 0x00, // maxBitrate - 0x00, 0x00, 0x00, 0x00, // avgBitrate - - 0x05 // descriptor_type MP4DecSpecificDescrTag - ].concat([configSize]).concat(config).concat([0x06, 0x01, 0x02 // GASpecificConfig - ])); - return MP4.box(MP4.types.esds, data); - } - - /** - * 改版 - *stsd下的avc1视频解析 - */ - - }, { - key: 'avc1', - value: function avc1(meta) { - var avcc = meta.avcc; - var width = meta.codecWidth, - height = meta.codecHeight; - - var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // // reserved(4) 6个 保留位 Reserved:6个字节,设置为0; - 0x00, 0x00, 0x00, 0x01, // reserved(2) + {{{{data_reference_index(2) 数据引用索引}}}} - 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2) - 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes 3*4个字节的保留位 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, width >>> 8 & 0xFF, // width: 2 bytes - width & 0xFF, height >>> 8 & 0xFF, // height: 2 bytes - height & 0xFF, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes 常数 - 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes 常数 - 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes 保留位 - 0x00, 0x01, // frame_count - // frame_count表明多少帧压缩视频存储在每个样本。默认是1,每样一帧;它可能超过1每个样本的多个帧数 - 0x04, // strlen compressorname: 32 bytes String[32] - // 32个8 bit 第一个8bit表示长度,剩下31个8bit表示内容 - 0x67, 0x31, 0x31, 0x31, // compressorname: 32 bytes 翻译过来是g111 - 0x00, 0x00, 0x00, 0x00, // - 0x00, 0x00, 0x00, 0x00, // - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, // depth 颜色深度 - 0xFF, 0xFF // pre_defined = -1 - ]); - return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc)); - } - - // Movie Extends box - - }, { - key: 'mvex', - value: function mvex(meta) { - if (meta.length > 1) { - return MP4.box(MP4.types.mvex, MP4.trex(meta[0]), MP4.trex(meta[1])); - } else { - return MP4.box(MP4.types.mvex, MP4.trex(meta[0])); - } - } - - // Track Extends box - - }, { - key: 'trex', - value: function trex(meta) { - var trackId = meta.id; - var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags - trackId >>> 24 & 0xFF, // track_ID - trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index - 0x00, 0x00, 0x00, 0x00, // default_sample_duration - 0x00, 0x00, 0x00, 0x00, // default_sample_size - 0x00, 0x01, 0x00, 0x01 // default_sample_flags - ]); - // if (meta.type !== 'video') { - // data[data.length - 1] = 0x00; - // } - return MP4.box(MP4.types.trex, data); - } - - // Movie fragment box - - }, { - key: 'moof', - value: function moof(track, baseMediaDecodeTime) { - return MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime)); - } - }, { - key: 'mfhd', - value: function mfhd(sequenceNumber) { - var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, sequenceNumber >>> 24 & 0xFF, // sequence_number: int32 - sequenceNumber >>> 16 & 0xFF, sequenceNumber >>> 8 & 0xFF, sequenceNumber & 0xFF]); - return MP4.box(MP4.types.mfhd, data); - } - - // Track fragment box - - }, { - key: 'traf', - value: function traf(track, baseMediaDecodeTime) { - var trackId = track.id; - - // Track fragment header box - var tfhd = MP4.box(MP4.types.tfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags - trackId >>> 24 & 0xFF, // track_ID - trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF])); - // Track Fragment Decode Time - var tfdt = MP4.box(MP4.types.tfdt, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags - baseMediaDecodeTime >>> 24 & 0xFF, // baseMediaDecodeTime: int32 - baseMediaDecodeTime >>> 16 & 0xFF, baseMediaDecodeTime >>> 8 & 0xFF, baseMediaDecodeTime & 0xFF])); - var sdtp = MP4.sdtp(track); - var trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8); - - return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp); - } - - // Sample Dependency Type box - - }, { - key: 'sdtp', - value: function sdtp(track) { - var samples = track.samples || []; - var sampleCount = samples.length; - var data = new Uint8Array(4 + sampleCount); - // 0~4 bytes: version(0) & flags - for (var i = 0; i < sampleCount; i++) { - var flags = samples[i].flags; - data[i + 4] = flags.isLeading << 6 | // is_leading: 2 (bit) - flags.dependsOn << 4 // sample_depends_on - | flags.isDependedOn << 2 // sample_is_depended_on - | flags.hasRedundancy; // sample_has_redundancy - } - return MP4.box(MP4.types.sdtp, data); - } - - // Track fragment run box - - }, { - key: 'trun', - value: function trun(track, offset) { - var samples = track.samples || []; - var sampleCount = samples.length; - var dataSize = 12 + 16 * sampleCount; - var data = new Uint8Array(dataSize); - offset += 8 + dataSize; - - data.set([0x00, 0x00, 0x0F, 0x01, // version(0) & flags - sampleCount >>> 24 & 0xFF, // sample_count - sampleCount >>> 16 & 0xFF, sampleCount >>> 8 & 0xFF, sampleCount & 0xFF, offset >>> 24 & 0xFF, // data_offset - offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF], 0); - - for (var i = 0; i < sampleCount; i++) { - - var duration = samples[i].duration; - - var size = samples[i].size; - var flags = samples[i].flags; - var cts = samples[i].cts; - data.set([duration >>> 24 & 0xFF, // sample_duration - duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, size >>> 24 & 0xFF, // sample_size - size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, flags.isLeading << 2 | flags.dependsOn, // sample_flags - flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority - cts >>> 24 & 0xFF, // sample_composition_time_offset - cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF], 12 + 16 * i); - } - return MP4.box(MP4.types.trun, data); - } - }, { - key: 'mdat', - value: function mdat(data) { - return MP4.box(MP4.types.mdat, data); - } - }]); - - return MP4; -}(); - -MP4.init(); - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * This file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js) - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -var AAC = function () { - function AAC() { - _classCallCheck(this, AAC); - } - - _createClass(AAC, null, [{ - key: "getSilentFrame", - value: function getSilentFrame(channelCount) { - if (channelCount === 1) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); - } else if (channelCount === 2) { - return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); - } else if (channelCount === 3) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); - } else if (channelCount === 4) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); - } else if (channelCount === 5) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); - } else if (channelCount === 6) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]); - } - return null; - } - }]); - - return AAC; -}(); - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -var Browser = {}; - -function detect() { - // modified from jquery-browser-plugin - - var ua = self.navigator.userAgent.toLowerCase(); - - var match = /(edge)\/([\w.]+)/.exec(ua) || /(opr)[\/]([\w.]+)/.exec(ua) || /(chrome)[ \/]([\w.]+)/.exec(ua) || /(iemobile)[\/]([\w.]+)/.exec(ua) || /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(ua) || ua.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; - - var platform_match = /(ipad)/.exec(ua) || /(ipod)/.exec(ua) || /(windows phone)/.exec(ua) || /(iphone)/.exec(ua) || /(kindle)/.exec(ua) || /(android)/.exec(ua) || /(windows)/.exec(ua) || /(mac)/.exec(ua) || /(linux)/.exec(ua) || /(cros)/.exec(ua) || []; - - var matched = { - browser: match[5] || match[3] || match[1] || '', - version: match[2] || match[4] || '0', - majorVersion: match[4] || match[2] || '0', - platform: platform_match[0] || '' - }; - - var browser = {}; - if (matched.browser) { - browser[matched.browser] = true; - - var versionArray = matched.majorVersion.split('.'); - browser.version = { - major: parseInt(matched.majorVersion, 10), - string: matched.version - }; - if (versionArray.length > 1) { - browser.version.minor = parseInt(versionArray[1], 10); - } - if (versionArray.length > 2) { - browser.version.build = parseInt(versionArray[2], 10); - } - } - - if (matched.platform) { - browser[matched.platform] = true; - } - - if (browser.chrome || browser.opr || browser.safari) { - browser.webkit = true; - } - - // MSIE. IE11 has 'rv' identifer - if (browser.rv || browser.iemobile) { - if (browser.rv) { - delete browser.rv; - } - var msie = 'msie'; - matched.browser = msie; - browser[msie] = true; - } - - // Microsoft Edge - if (browser.edge) { - delete browser.edge; - var msedge = 'msedge'; - matched.browser = msedge; - browser[msedge] = true; - } - - // Opera 15+ - if (browser.opr) { - var opera = 'opera'; - matched.browser = opera; - browser[opera] = true; - } - - // Stock android browsers are marked as Safari - if (browser.safari && browser.android) { - var android = 'android'; - matched.browser = android; - browser[android] = true; - } - - browser.name = matched.browser; - browser.platform = matched.platform; - - for (var key in Browser) { - if (Browser.hasOwnProperty(key)) { - delete Browser[key]; - } - } - _Object$assign(Browser, browser); -} - -detect(); - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -// Represents an media sample (audio / video) -var SampleInfo = function SampleInfo(dts, pts, duration, originalDts, isSync) { - _classCallCheck(this, SampleInfo); - - this.dts = dts; - this.pts = pts; - this.duration = duration; - this.originalDts = originalDts; - this.isSyncPoint = isSync; - this.fileposition = null; -}; - -// Media Segment concept is defined in Media Source Extensions spec. -// Particularly in ISO BMFF format, an Media Segment contains a moof box followed by a mdat box. -var MediaSegmentInfo = function () { - function MediaSegmentInfo() { - _classCallCheck(this, MediaSegmentInfo); - - this.beginDts = 0; - this.endDts = 0; - this.beginPts = 0; - this.endPts = 0; - this.originalBeginDts = 0; - this.originalEndDts = 0; - this.syncPoints = []; // SampleInfo[n], for video IDR frames only - this.firstSample = null; // SampleInfo - this.lastSample = null; // SampleInfo - } - - _createClass(MediaSegmentInfo, [{ - key: "appendSyncPoint", - value: function appendSyncPoint(sampleInfo) { - // also called Random Access Point - sampleInfo.isSyncPoint = true; - this.syncPoints.push(sampleInfo); - } - }]); - - return MediaSegmentInfo; -}(); - -// Ordered list for recording video IDR frames, sorted by originalDts -var IDRSampleList = function () { - function IDRSampleList() { - _classCallCheck(this, IDRSampleList); - - this._list = []; - } - - _createClass(IDRSampleList, [{ - key: "clear", - value: function clear() { - this._list = []; - } - }, { - key: "appendArray", - value: function appendArray(syncPoints) { - var list = this._list; - - if (syncPoints.length === 0) { - return; - } - - if (list.length > 0 && syncPoints[0].originalDts < list[list.length - 1].originalDts) { - this.clear(); - } - - Array.prototype.push.apply(list, syncPoints); - } - }, { - key: "getLastSyncPointBeforeDts", - value: function getLastSyncPointBeforeDts(dts) { - if (this._list.length == 0) { - return null; - } - - var list = this._list; - var idx = 0; - var last = list.length - 1; - var mid = 0; - var lbound = 0; - var ubound = last; - - if (dts < list[0].dts) { - idx = 0; - lbound = ubound + 1; - } - - while (lbound <= ubound) { - mid = lbound + Math.floor((ubound - lbound) / 2); - if (mid === last || dts >= list[mid].dts && dts < list[mid + 1].dts) { - idx = mid; - break; - } else if (list[mid].dts < dts) { - lbound = mid + 1; - } else { - ubound = mid - 1; - } - } - return this._list[idx]; - } - }]); - - return IDRSampleList; -}(); - -// Data structure for recording information of media segments in single track. -var MediaSegmentInfoList = function () { - function MediaSegmentInfoList(type) { - _classCallCheck(this, MediaSegmentInfoList); - - this._type = type; - this._list = []; - this._lastAppendLocation = -1; // cached last insert location - } - - _createClass(MediaSegmentInfoList, [{ - key: "isEmpty", - value: function isEmpty$$1() { - return this._list.length === 0; - } - }, { - key: "clear", - value: function clear() { - this._list = []; - this._lastAppendLocation = -1; - } - }, { - key: "_searchNearestSegmentBefore", - value: function _searchNearestSegmentBefore(originalBeginDts) { - var list = this._list; - if (list.length === 0) { - return -2; - } - var last = list.length - 1; - var mid = 0; - var lbound = 0; - var ubound = last; - - var idx = 0; - - if (originalBeginDts < list[0].originalBeginDts) { - idx = -1; - return idx; - } - - while (lbound <= ubound) { - mid = lbound + Math.floor((ubound - lbound) / 2); - if (mid === last || originalBeginDts > list[mid].lastSample.originalDts && originalBeginDts < list[mid + 1].originalBeginDts) { - idx = mid; - break; - } else if (list[mid].originalBeginDts < originalBeginDts) { - lbound = mid + 1; - } else { - ubound = mid - 1; - } - } - return idx; - } - }, { - key: "_searchNearestSegmentAfter", - value: function _searchNearestSegmentAfter(originalBeginDts) { - return this._searchNearestSegmentBefore(originalBeginDts) + 1; - } - }, { - key: "append", - value: function append(mediaSegmentInfo) { - var list = this._list; - var msi = mediaSegmentInfo; - var lastAppendIdx = this._lastAppendLocation; - var insertIdx = 0; - - if (lastAppendIdx !== -1 && lastAppendIdx < list.length && msi.originalBeginDts >= list[lastAppendIdx].lastSample.originalDts && (lastAppendIdx === list.length - 1 || lastAppendIdx < list.length - 1 && msi.originalBeginDts < list[lastAppendIdx + 1].originalBeginDts)) { - insertIdx = lastAppendIdx + 1; // use cached location idx - } else { - if (list.length > 0) { - insertIdx = this._searchNearestSegmentBefore(msi.originalBeginDts) + 1; - } - } - - this._lastAppendLocation = insertIdx; - this._list.splice(insertIdx, 0, msi); - } - }, { - key: "getLastSegmentBefore", - value: function getLastSegmentBefore(originalBeginDts) { - var idx = this._searchNearestSegmentBefore(originalBeginDts); - if (idx >= 0) { - return this._list[idx]; - } else { - // -1 - return null; - } - } - }, { - key: "getLastSampleBefore", - value: function getLastSampleBefore(originalBeginDts) { - var segment = this.getLastSegmentBefore(originalBeginDts); - if (segment != null) { - return segment.lastSample; - } else { - return null; - } - } - }, { - key: "getLastSyncPointBefore", - value: function getLastSyncPointBefore(originalBeginDts) { - var segmentIdx = this._searchNearestSegmentBefore(originalBeginDts); - var syncPoints = this._list[segmentIdx].syncPoints; - while (syncPoints.length === 0 && segmentIdx > 0) { - segmentIdx--; - syncPoints = this._list[segmentIdx].syncPoints; - } - if (syncPoints.length > 0) { - return syncPoints[syncPoints.length - 1]; - } else { - return null; - } - } - }, { - key: "type", - get: function get() { - return this._type; - } - }, { - key: "length", - get: function get() { - return this._list.length; - } - }]); - - return MediaSegmentInfoList; -}(); - -/* - * Copyright (C) 2016 Bilibili. All Rights Reserved. - * - * @author zheng qian - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable */ -// Fragmented mp4 remuxer - -var MP4Remuxer = function () { - function MP4Remuxer(config) { - _classCallCheck(this, MP4Remuxer); - - this.TAG = this.constructor.name; - - this._config = config; - this._isLive = config.isLive === true; - - this._dtsBase = -1; - this._dtsBaseInited = false; - this._audioDtsBase = Infinity; - this._videoDtsBase = Infinity; - this._audioNextDts = undefined; - this._videoNextDts = undefined; - - this._audioMeta = null; - this._videoMeta = null; - - this._audioSegmentInfoList = new MediaSegmentInfoList('audio'); - this._videoSegmentInfoList = new MediaSegmentInfoList('video'); - - this._onInitSegment = null; - this._onMediaSegment = null; - - // Workaround for chrome < 50: Always force first sample as a Random Access Point in media segment - // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412 - this._forceFirstIDR = !!(Browser.chrome && (Browser.version.major < 50 || Browser.version.major === 50 && Browser.version.build < 2661)); - - // Workaround for IE11/Edge: Fill silent aac frame after keyframe-seeking - // Make audio beginDts equals with video beginDts, in order to fix seek freeze - this._fillSilentAfterSeek = Browser.msedge || Browser.msie; - } - - _createClass(MP4Remuxer, [{ - key: 'destroy', - value: function destroy() { - this._dtsBase = -1; - this._dtsBaseInited = false; - this._audioMeta = null; - this._videoMeta = null; - this._audioSegmentInfoList.clear(); - this._audioSegmentInfoList = null; - this._videoSegmentInfoList.clear(); - this._videoSegmentInfoList = null; - this._onInitSegment = null; - this._onMediaSegment = null; - } - }, { - key: 'bindDataSource', - value: function bindDataSource(producer) { - producer.onDataAvailable = this.remux.bind(this); - producer.onTrackMetadata = this._onTrackMetadataReceived.bind(this); - return this; - } - - /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void - InitSegment: { - type: string, - data: ArrayBuffer, - codec: string, - container: string - } - */ - - }, { - key: 'insertDiscontinuity', - value: function insertDiscontinuity() { - this._audioNextDts = this._videoNextDts = undefined; - } - }, { - key: 'seek', - value: function seek(originalDts) { - this._videoSegmentInfoList.clear(); - this._audioSegmentInfoList.clear(); - } - }, { - key: 'remux', - value: function remux(audioTrack, videoTrack) { - if (!this._onMediaSegment) { - throw new Error$1('MP4Remuxer: onMediaSegment callback must be specificed!'); - } - if (!this._dtsBaseInited) { - this._calculateDtsBase(audioTrack, videoTrack); - } - this._remuxVideo(videoTrack); - this._remuxAudio(audioTrack); - } - }, { - key: '_onTrackMetadataReceived', - value: function _onTrackMetadataReceived(type, metadata) { - var metabox = null; - - if (type === 'audio') { - this._audioMeta = metadata; - metabox = MP4.generateInitSegment(metadata); - console.log('msg+audio', metadata); - } else if (type === 'video') { - this._videoMeta = metadata; - metabox = MP4.generateInitSegment(metadata); - console.log('msg+video', metadata); - } else { - return; - } - - // dispatch metabox (Initialization Segment) - if (!this._onInitSegment) { - throw new Error$1('MP4Remuxer: onInitSegment callback must be specified!'); - } - this._onInitSegment(type, { - type: type, - data: metabox.buffer, - codec: metadata.codec, - container: type + '/mp4' - }); - } - }, { - key: '_calculateDtsBase', - value: function _calculateDtsBase(audioTrack, videoTrack) { - if (this._dtsBaseInited) { - return; - } - - if (audioTrack.samples && audioTrack.samples.length) { - this._audioDtsBase = audioTrack.samples[0].dts; - } - if (videoTrack.samples && videoTrack.samples.length) { - this._videoDtsBase = videoTrack.samples[0].dts; - } - - this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase); - this._dtsBaseInited = true; - } - }, { - key: '_remuxAudio', - value: function _remuxAudio(audioTrack) { - var track = audioTrack; - var samples = track.samples; - var dtsCorrection = void 0; - var firstDts = -1, - lastDts = -1, - lastPts = -1; - - var remuxSilentFrame = false; - var silentFrameDuration = -1; - - if (!samples || samples.length === 0) { - return; - } - - var bytes = 8 + track.length; - var mdatbox = new Uint8Array(bytes); - mdatbox[0] = bytes >>> 24 & 0xFF; - mdatbox[1] = bytes >>> 16 & 0xFF; - mdatbox[2] = bytes >>> 8 & 0xFF; - mdatbox[3] = bytes & 0xFF; - - mdatbox.set(MP4.types.mdat, 4); - - var offset = 8; // size + type - var mp4Samples = []; - - while (samples.length) { - var aacSample = samples.shift(); - var unit = aacSample.unit; - var originalDts = aacSample.dts - this._dtsBase; - - if (dtsCorrection == undefined) { - if (this._audioNextDts == undefined) { - if (this._audioSegmentInfoList.isEmpty()) { - dtsCorrection = 0; - if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) { - remuxSilentFrame = true; - } - } else { - var lastSample = this._audioSegmentInfoList.getLastSampleBefore(originalDts); - if (lastSample != null) { - var distance = originalDts - (lastSample.originalDts + lastSample.duration); - if (distance <= 3) { - distance = 0; - } - var expectedDts = lastSample.dts + lastSample.duration + distance; - dtsCorrection = originalDts - expectedDts; - } else { - // lastSample == null - dtsCorrection = 0; - } - } - } else { - dtsCorrection = originalDts - this._audioNextDts; - } - } - - var dts = originalDts - dtsCorrection; - if (remuxSilentFrame) { - // align audio segment beginDts to match with current video segment's beginDts - var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(originalDts); - if (videoSegment != null && videoSegment.beginDts < dts) { - silentFrameDuration = dts - videoSegment.beginDts; - dts = videoSegment.beginDts; - } else { - remuxSilentFrame = false; - } - } - if (firstDts === -1) { - firstDts = dts; - } - - if (remuxSilentFrame) { - remuxSilentFrame = false; - samples.unshift(aacSample); - - var frame = this._generateSilentAudio(dts, silentFrameDuration); - if (frame == null) { - continue; - } - var _mp4Sample = frame.mp4Sample; - var _unit = frame.unit; - - mp4Samples.push(_mp4Sample); - - // re-allocate mdatbox buffer with new size, to fit with this silent frame - bytes += _unit.byteLength; - mdatbox = new Uint8Array(bytes); - mdatbox[0] = bytes >>> 24 & 0xFF; - mdatbox[1] = bytes >>> 16 & 0xFF; - mdatbox[2] = bytes >>> 8 & 0xFF; - mdatbox[3] = bytes & 0xFF; - mdatbox.set(MP4.types.mdat, 4); - - // fill data now - mdatbox.set(_unit, offset); - offset += _unit.byteLength; - continue; - } - - var sampleDuration = 0; - - if (samples.length >= 1) { - var nextDts = samples[0].dts - this._dtsBase - dtsCorrection; - sampleDuration = nextDts - dts; - } else { - if (mp4Samples.length >= 1) { - // use second last sample duration - sampleDuration = mp4Samples[mp4Samples.length - 1].duration; - } else { - // the only one sample, use reference sample duration - sampleDuration = this._audioMeta.refSampleDuration; - } - } - - var mp4Sample = { - dts: dts, - pts: dts, - cts: 0, - size: unit.byteLength, - duration: sampleDuration, - originalDts: originalDts, - flags: { - isLeading: 0, - dependsOn: 1, - isDependedOn: 0, - hasRedundancy: 0 - } - }; - mp4Samples.push(mp4Sample); - mdatbox.set(unit, offset); - offset += unit.byteLength; - } - var latest = mp4Samples[mp4Samples.length - 1]; - lastDts = latest.dts + latest.duration; - this._audioNextDts = lastDts; - - // fill media segment info & add to info list - var info = new MediaSegmentInfo(); - info.beginDts = firstDts; - info.endDts = lastDts; - info.beginPts = firstDts; - info.endPts = lastDts; - info.originalBeginDts = mp4Samples[0].originalDts; - info.originalEndDts = latest.originalDts + latest.duration; - info.firstSample = new SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, false); - info.lastSample = new SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, false); - if (!this._isLive) { - this._audioSegmentInfoList.append(info); - } - - track.samples = mp4Samples; - track.sequenceNumber += track.addcoefficient; - - var moofbox = MP4.moof(track, firstDts); - track.samples = []; - track.length = 0; - - this._onMediaSegment('audio', { - type: 'audio', - data: this._mergeBoxes(moofbox, mdatbox).buffer, - sampleCount: mp4Samples.length, - info: info - }); - } - }, { - key: '_generateSilentAudio', - value: function _generateSilentAudio(dts, frameDuration) { - console.log(this.TAG, 'GenerateSilentAudio: dts = ' + dts + ', duration = ' + frameDuration); - - var unit = AAC.getSilentFrame(this._audioMeta.channelCount); - if (unit == null) { - console.log(this.TAG, 'Cannot generate silent aac frame for channelCount = ' + this._audioMeta.channelCount); - return null; - } - - var mp4Sample = { - dts: dts, - pts: dts, - cts: 0, - size: unit.byteLength, - duration: frameDuration, - originalDts: dts, - flags: { - isLeading: 0, - dependsOn: 1, - isDependedOn: 0, - hasRedundancy: 0 - } - }; - - return { - unit: unit, - mp4Sample: mp4Sample - }; - } - }, { - key: '_remuxVideo', - value: function _remuxVideo(videoTrack) { - var track = videoTrack; - var samples = track.samples; - var dtsCorrection = void 0; - var firstDts = -1, - lastDts = -1; - var firstPts = -1, - lastPts = -1; - - if (!samples || samples.length === 0) { - return; - } - - var bytes = 8 + videoTrack.length; - var mdatbox = new Uint8Array(bytes); - mdatbox[0] = bytes >>> 24 & 0xFF; - mdatbox[1] = bytes >>> 16 & 0xFF; - mdatbox[2] = bytes >>> 8 & 0xFF; - mdatbox[3] = bytes & 0xFF; - mdatbox.set(MP4.types.mdat, 4); - - var offset = 8; - var mp4Samples = []; - var info = new MediaSegmentInfo(); - - while (samples.length) { - var avcSample = samples.shift(); - var keyframe = avcSample.isKeyframe; - var originalDts = avcSample.dts - this._dtsBase; - - if (dtsCorrection == undefined) { - if (this._videoNextDts == undefined) { - if (this._videoSegmentInfoList.isEmpty()) { - dtsCorrection = 0; - } else { - var lastSample = this._videoSegmentInfoList.getLastSampleBefore(originalDts); - if (lastSample != null) { - var distance = originalDts - (lastSample.originalDts + lastSample.duration); - if (distance <= 3) { - distance = 0; - } - var expectedDts = lastSample.dts + lastSample.duration + distance; - dtsCorrection = originalDts - expectedDts; - } else { - // lastSample == null - dtsCorrection = 0; - } - } - } else { - dtsCorrection = originalDts - this._videoNextDts; - } - } - - var dts = originalDts - dtsCorrection; - var cts = avcSample.cts; - var pts = dts + cts; - - if (firstDts === -1) { - firstDts = dts; - firstPts = pts; - } - - // fill mdat box - var sampleSize = 0; - while (avcSample.units.length) { - var unit = avcSample.units.shift(); - var data = unit.data; - mdatbox.set(data, offset); - offset += data.byteLength; - sampleSize += data.byteLength; - } - - var sampleDuration = 0; - - if (samples.length >= 1) { - var nextDts = samples[0].dts - this._dtsBase - dtsCorrection; - sampleDuration = nextDts - dts; - } else { - if (mp4Samples.length >= 1) { - // lastest sample, use second last duration - sampleDuration = mp4Samples[mp4Samples.length - 1].duration; - } else { - // the only one sample, use reference duration - sampleDuration = this._videoMeta.refSampleDuration; - } - } - - if (keyframe) { - var syncPoint = new SampleInfo(dts, pts, sampleDuration, avcSample.dts, true); - syncPoint.fileposition = avcSample.fileposition; - info.appendSyncPoint(syncPoint); - } - - var mp4Sample = { - dts: dts, - pts: pts, - cts: cts, - size: sampleSize, - isKeyframe: keyframe, - duration: sampleDuration, - originalDts: originalDts, - flags: { - isLeading: 0, - dependsOn: keyframe ? 2 : 1, - isDependedOn: keyframe ? 1 : 0, - hasRedundancy: 0, - isNonSync: keyframe ? 0 : 1 - } - }; - - mp4Samples.push(mp4Sample); - } - var latest = mp4Samples[mp4Samples.length - 1]; - lastDts = latest.dts + latest.duration; - lastPts = latest.pts + latest.duration; - this._videoNextDts = lastDts; - - // fill media segment info & add to info list - info.beginDts = firstDts; - info.endDts = lastDts; - info.beginPts = firstPts; - info.endPts = lastPts; - info.originalBeginDts = mp4Samples[0].originalDts; - info.originalEndDts = latest.originalDts + latest.duration; - info.firstSample = new SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, mp4Samples[0].isKeyframe); - info.lastSample = new SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, latest.isKeyframe); - if (!this._isLive) { - this._videoSegmentInfoList.append(info); - } - - track.samples = mp4Samples; - track.sequenceNumber += track.addcoefficient; - - // workaround for chrome < 50: force first sample as a random access point - // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412 - if (this._forceFirstIDR) { - var flags = mp4Samples[0].flags; - flags.dependsOn = 2; - flags.isNonSync = 0; - } - - var moofbox = MP4.moof(track, firstDts); - track.samples = []; - track.length = 0; - - this._onMediaSegment('video', { - type: 'video', - data: this._mergeBoxes(moofbox, mdatbox).buffer, - sampleCount: mp4Samples.length, - info: info - }); - } - }, { - key: '_mergeBoxes', - value: function _mergeBoxes(moof, mdat) { - var result = new Uint8Array(moof.byteLength + mdat.byteLength); - result.set(moof, 0); - result.set(mdat, moof.byteLength); - return result; - } - }, { - key: 'onInitSegment', - get: function get() { - return this._onInitSegment; - }, - set: function set(callback) { - this._onInitSegment = callback; - } - - /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void - MediaSegment: { - type: string, - data: ArrayBuffer, - sampleCount: int32 - info: MediaSegmentInfo - } - */ - - }, { - key: 'onMediaSegment', - get: function get() { - return this._onMediaSegment; - }, - set: function set(callback) { - this._onMediaSegment = callback; - } - }]); - - return MP4Remuxer; -}(); - -/* eslint-disable */ -var flv2fmp4 = function () { - - /** - * Creates an instance of flv2fmp4. - * config 里面有_isLive属性,是否是直播 - * @param {any} config - * - * @memberof flv2fmp4 - */ - function flv2fmp4(config) { - _classCallCheck(this, flv2fmp4); - - this._config = { _isLive: false }; - this._config = _Object$assign(this._config, config); - - // 外部方法赋值 - this.onInitSegment = null; - this.onMediaSegment = null; - this.onMediaInfo = null; - this.seekCallBack = null; - - // 内部使用 - this.loadmetadata = false; - this.ftyp_moov = null; - this.metaSuccRun = false; - this.metas = []; - this.parseChunk = null; - this.hasVideo = false; - this.hasAudio = false; - this._error = null; - // 临时记录seek时间 - this._pendingResolveSeekPoint = -1; - - // 临时记录flv数据起始时间 - this._tempBaseTime = 0; - - // 处理flv数据入口 - this.setflvBase = this.setflvBasefrist; - - tagdemux._onTrackMetadata = this.Metadata.bind(this); - tagdemux._onMediaInfo = this.metaSucc.bind(this); - tagdemux._onDataAvailable = this.onDataAvailable.bind(this); - tagdemux._onError = this.error.bind(this); - this.m4mof = new MP4Remuxer(this._config); - this.m4mof.onMediaSegment = this.onMdiaSegment.bind(this); - } - - _createClass(flv2fmp4, [{ - key: 'seek', - value: function seek(baseTime) { - this.setflvBase = this.setflvBasefrist; - if (baseTime == undefined || baseTime == 0) { - baseTime = 0; - this._pendingResolveSeekPoint = -1; - } - if (this._tempBaseTime != baseTime) { - this._tempBaseTime = baseTime; - tagdemux._timestampBase = baseTime; - this.m4mof.seek(baseTime); - this.m4mof.insertDiscontinuity(); - this._pendingResolveSeekPoint = baseTime; - } - } - - /** - * 不要主动调用这个接口!!!!!!!!!!!!!!!!!!!!!!!!!!!! - * 第一次接受数据,和seek时候接受数据入口, - * - * @param {any} arraybuff - * @param {any} baseTime - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'setflvBasefrist', - value: function setflvBasefrist(arraybuff, baseTime) { - var offset = 0; - try { - offset = flvparse.setFlv(new Uint8Array(arraybuff)); - } catch (error) { - this.error(error); - } - - if (flvparse.arrTag.length > 0) { - this.hasAudio = flvparse._hasAudio; - this.hasVideo = flvparse._hasVideo; - if (this._tempBaseTime != 0 && this._tempBaseTime == flvparse.arrTag[0].getTime()) { - tagdemux._timestampBase = 0; - } - try { - tagdemux.moofTag(flvparse.arrTag); - } catch (error) { - this.error(error); - } - - this.setflvBase = this.setflvBaseUsually; - } - - return offset; - } - - /** - * 不要主动调用这个接口!!!!!!!!!!!!!!!!!!!!!!!!!!!! - * 后续接受数据接口 - * @param {any} arraybuff - * @param {any} baseTime - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'setflvBaseUsually', - value: function setflvBaseUsually(arraybuff, baseTime) { - var offset = 0; - try { - offset = flvparse.setFlv(new Uint8Array(arraybuff)); - } catch (error) { - this.error(error); - } - if (flvparse.arrTag.length > 0) { - try { - tagdemux.moofTag(flvparse.arrTag); - } catch (error) { - this.error(error); - } - } - - return offset; - } - - /** - * 不要主动调用这个接口!!!!!!!!!!!!!!!!!!!!!!!!!!!! - * moof回调 - * - * @param {any} track - * @param {any} value - * - * @memberof flv2fmp4 - */ - - }, { - key: 'onMdiaSegment', - value: function onMdiaSegment(track, value) { - - if (this.onMediaSegment) { - this.onMediaSegment(new Uint8Array(value.data)); - } - if (this._pendingResolveSeekPoint != -1 && track == 'video') { - var seekpoint = this._pendingResolveSeekPoint; - this._pendingResolveSeekPoint = -1; - if (this.seekCallBack) { - this.seekCallBack(seekpoint); - } - } - } - - /** - * - * 音频和视频的初始化tag - * - * @param {any} type - * @param {any} meta - * - * @memberof flv2fmp4 - */ - - }, { - key: 'Metadata', - value: function Metadata(type, meta) { - switch (type) { - case 'video': - this.metas.push(meta); - this.m4mof._videoMeta = meta; - if (this.hasVideo && !this.hasAudio) { - this.metaSucc(); - return; - } - break; - case 'audio': - this.metas.push(meta); - this.m4mof._audioMeta = meta; - if (!this.hasVideo && this.hasAudio) { - this.metaSucc(); - return; - } - break; - } - if (this.hasVideo && this.hasAudio && this.metaSuccRun && this.metas.length > 1) { - this.metaSucc(); - } - } - - /** - * metadata解读成功后触发及第一个视频tag和第一个音频tag - * - * @param {any} mi - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'metaSucc', - value: function metaSucc(mi) { - if (this.onMediaInfo) { - this.onMediaInfo(mi, { hasAudio: this.hasAudio, hasVideo: this.hasVideo }); - } - // 获取ftyp和moov - if (this.metas.length == 0) { - this.metaSuccRun = true; - return; - } - - this.ftyp_moov = MP4.generateInitSegment(this.metas); - if (this.onInitSegment && this.loadmetadata == false) { - - this.onInitSegment(this.ftyp_moov); - this.loadmetadata = true; - } - } - }, { - key: 'onDataAvailable', - value: function onDataAvailable(audiotrack, videotrack) { - try { - this.m4mof.remux(audiotrack, videotrack); - } catch (e) { - this.error(e); - } - } - - /** - * 传入flv的二进制数据 - * 统一入口 - * @param {any} arraybuff - * @param {any} baseTime flv数据开始时间 - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'setflv', - value: function setflv(arraybuff, baseTime) { - return this.setflvBase(arraybuff, baseTime); - } - - /** - * - * 本地调试代码,不用理会 - * @param {any} arraybuff - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'setflvloc', - value: function setflvloc(arraybuff) { - var offset = flvparse.setFlv(new Uint8Array(arraybuff)); - - if (flvparse.arrTag.length > 0) { - return flvparse.arrTag; - } - } - - /** - * - * 异常抛出处理 - * @param {any} e - * @memberof flv2fmp4 - */ - - }, { - key: 'error', - value: function error(e) { - if (this._error) { - this._error(e); - } - } - }]); - - return flv2fmp4; -}(); - -/** - * 封装的对外类,有些方法不想对外暴露,所以封装这么一个类 - * - * @class foreign - */ - - -var foreign = function (_CustEvent) { - _inherits(foreign, _CustEvent); - - function foreign(config) { - _classCallCheck(this, foreign); - - var _this = _possibleConstructorReturn(this, (foreign.__proto__ || _Object$getPrototypeOf(foreign)).call(this)); - - _this.f2m = new flv2fmp4(config); - _this.f2m._error = _this.error; - // 外部方法赋值 - _this._onInitSegment = null; - _this._onMediaSegment = null; - _this._onMediaInfo = null; - _this._seekCallBack = null; - return _this; - } - - _createClass(foreign, [{ - key: 'error', - value: function error(e) { - this.emit('error', e.type); - } - /** - * - * 跳转 - * @param {any} basetime 跳转时间 - * - * @memberof foreign - */ - - }, { - key: 'seek', - value: function seek(basetime) { - this.f2m.seek(basetime); - } - - /** - * 传入flv的二进制数据 - * 统一入口 - * @param {any} arraybuff - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'setflv', - value: function setflv(arraybuff) { - return this.f2m.setflv(arraybuff, 0); - } - - /** - * - * 本地调试代码,不用理会 - * @param {any} arraybuff - * @returns - * - * @memberof flv2fmp4 - */ - - }, { - key: 'setflvloc', - value: function setflvloc(arraybuff) { - return this.f2m.setflvloc(arraybuff); - } - - /** - * 赋值初始化seg接受方法 - * - * - * @memberof foreign - */ - - }, { - key: 'onInitSegment', - set: function set(fun) { - this._onInitSegment = fun; - this.f2m.onInitSegment = fun; - } - - /** - * 赋值moof接受方法 - * - * - * @memberof foreign - */ - - }, { - key: 'onMediaSegment', - set: function set(fun) { - this._onMediaSegment = fun; - this.f2m.onMediaSegment = fun; - } - - /** - * 赋值metadata接受方法 - * - * - * @memberof foreign - */ - - }, { - key: 'onMediaInfo', - set: function set(fun) { - this._onMediaInfo = fun; - this.f2m.onMediaInfo = fun; - } - - /** - * 赋值是否跳转回调接受方法 - * - * - * @memberof foreign - */ - - }, { - key: 'seekCallBack', - set: function set(fun) { - this._seekCallBack = fun; - this.f2m.seekCallBack = fun; - } - }]); - - return foreign; -}(CustEvent); - -// const F2M = require('chimee-flv2fmp4'); -var Transmuxer = function (_CustEvent) { - _inherits(Transmuxer, _CustEvent); - - function Transmuxer(mediaSource, config) { - _classCallCheck(this, Transmuxer); - - var _this = _possibleConstructorReturn(this, (Transmuxer.__proto__ || _Object$getPrototypeOf(Transmuxer)).call(this)); - - _this.config = {}; - _this.tag = 'transmuxer'; - _this.loader = null; - _this.CPU = null; - _this.keyframePoint = false; - _this.w = null; - _Object$assign(_this.config, config); - if (_this.config.webWorker) { - _this.w = index$2('./transmuxer-worker'); - _this.w.postMessage({ cmd: 'init' }); - _this.w.addEventListener('message', function (e) { - _this.parseCallback(e.data); - }); - } - return _this; - } - /** - * instance ioloader - */ - - - _createClass(Transmuxer, [{ - key: 'loadSource', - value: function loadSource() { - if (this.config.webWorker) { - this.w.postMessage({ cmd: 'loadSource' }); - // this.loader.arrivalDataCallback = this.arrivalDataCallbackWorker.bind(this); - } else { - this.loader = new Ioloader(this.config); - this.loader.arrivalDataCallback = this.arrivalDataCallback.bind(this); - this.loader.open(); - } - } - /** - * data arrive to webworker - */ - // arrivalDataCallbackWorker (data, byteStart, keyframePoint) { - // if(keyframePoint) { - // this.w.postMessage({cmd: 'seek', source: data}); - // } - // this.w.postMessage({cmd: 'pipe', source: data}); - // return; - // } - - }, { - key: 'arrivalDataCallback', - value: function arrivalDataCallback(data, byteStart, keyframePoint) { - var consumed = 0; - if (!this.CPU) { - this.CPU = new foreign(); - this.CPU.onInitSegment = this.onRemuxerInitSegmentArrival.bind(this); - this.CPU.onMediaSegment = this.onRemuxerMediaSegmentArrival.bind(this); - this.CPU.onError = this.onCPUError.bind(this); - this.CPU.onMediaInfo = this.onMediaInfo.bind(this); - this.CPU.seekCallBack = this.seekCallBack.bind(this); - } - if (keyframePoint) { - this.keyframePoint = true; - this.CPU.seek(keyframePoint); - } - consumed = this.CPU.setflv(data); - return consumed; - } - }, { - key: 'parseCallback', - value: function parseCallback(data) { - switch (data.cmd) { - case 'pipeCallback': - data.source; - break; - case 'mediaSegmentInit': - this.emit('mediaSegmentInit', data.source); - break; - case 'mediaSegment': - this.emit('mediaSegment', data.source); - break; - case 'mediainfo': - this.emit('mediainfo', data.source); - break; - } - } - }, { - key: 'onDemuxError', - value: function onDemuxError(type, info) { - Log.error(this.tag, 'DemuxError: type = ' + type + ', info = ' + info); - this.emit('DemuxError', type, info); - } - }, { - key: 'onMediaInfo', - value: function onMediaInfo(mediaInfo, o) { - this.mediaInfo = mediaInfo; - this.emit('mediaInfo', mediaInfo); - } - }, { - key: 'seekCallBack', - value: function seekCallBack(t) {} - }, { - key: 'onRemuxerInitSegmentArrival', - value: function onRemuxerInitSegmentArrival(data) { - this.emit('mediaSegmentInit', data); - } - }, { - key: 'onRemuxerMediaSegmentArrival', - value: function onRemuxerMediaSegmentArrival(data) { - this.emit('mediaSegment', data); - } - }, { - key: 'onCPUError', - value: function onCPUError(handle) { - this.emit('ERROR', handle.data); - } - }, { - key: 'getMediaInfo', - value: function getMediaInfo() { - return this.mediaInfo; - } - }, { - key: 'pause', - value: function pause() { - this.loader.pause(); - } - }, { - key: 'resume', - value: function resume() { - this.loader.resume(); - } - }, { - key: 'isSeekable', - value: function isSeekable() { - return this.mediaInfo.hasKeyframesIndex; - } - }, { - key: 'seek', - value: function seek(keyframe) { - if (!this.isSeekable()) { - this.emit('ERROR', '这个flv视频不支持seek'); - return false; - } - this.loader = new Ioloader(this.config); - this.loader.arrivalDataCallback = this.arrivalDataCallback.bind(this); - this.loader.seek(keyframe.keyframePoint, false, keyframe.keyframetime); - } - }, { - key: 'destroy', - value: function destroy() { - this.loader.destroy(); - this.loader = null; - this.CPU = null; - } - }, { - key: 'getNearlestKeyframe', - value: function getNearlestKeyframe(times) { - if (this.mediaInfo && this.mediaInfo.keyframesIndex) { - var keyframesList = this.mediaInfo.keyframesIndex.times; - var keyframesPositions = this.mediaInfo.keyframesIndex.filepositions; - var binarySearch = function binarySearch(list, val) { - var length = list.length; - var index = Math.floor(length / 2); - if (length === 1) { - var position = keyframesList.indexOf(list[0]); - return { - keyframetime: list[0], - keyframePoint: keyframesPositions[position] - }; - } else if (list[index] > val) { - return binarySearch(list.slice(0, index), val); - } else if (list[index] < val) { - return binarySearch(list.slice(index), val); - } else { - var _position = keyframesList.indexOf(list[0]); - return { - keyframetime: list[0], - keyframePoint: keyframesPositions[_position] - }; - } - }; - return binarySearch(keyframesList, times); - } else { - return 0; - } - } - }]); - - return Transmuxer; -}(CustEvent); - -var defaultConfig$1 = { - type: 'vod', - autoPlay: false, - box: 'flv', - prestrain: 30, - alwaysSeekKeyframe: true, - lazyLoadMaxDuration: 2 * 60, - lazyLoadRecoverDuration: 30, - lockInternalProperty: false, - debug: true, - webWorker: false, - autoCleanupSourceBuffer: true -}; - -/** - * flv 控制层 - * - * @export - * @class mp4 - */ - -var Flv = function (_CustEvent) { - _inherits(Flv, _CustEvent); - - function Flv(videodom, config) { - _classCallCheck(this, Flv); - - var _this2 = _possibleConstructorReturn(this, (Flv.__proto__ || _Object$getPrototypeOf(Flv)).call(this)); - - _this2.tag = 'FLV-player'; - _this2.video = videodom; - _this2.box = 'flv'; - _this2.config = defaultConfig$1; - _this2.timer = null; - deepAssign(_this2.config, config); - _this2.requestSetTime = false; - _this2.bindEvents(); - _this2.attachMedia(); - return _this2; - } - - _createClass(Flv, [{ - key: 'internalPropertyHandle', - value: function internalPropertyHandle() { - if (!_Object$getOwnPropertyDescriptor) { - return; - } - var _this = this; - var time = _Object$getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'currentTime'); - - Object.defineProperty(this.video, 'currentTime', { - get: function get() { - return time.get.call(_this.video); - }, - set: function set(t) { - if (!_this.currentTimeLock) { - throw new Error('can not set currentTime by youself'); - } else { - return time.set.call(_this.video, t); - } - } - }); - } - }, { - key: 'bindEvents', - value: function bindEvents() { - var _this3 = this; - - if (this.video) { - this.video.addEventListener('canplay', function () { - if (_this3.config.type === 'live') { - _this3.video.play(); - } - if (_this3.config.lockInternalProperty) { - _this3.internalPropertyHandle(); - } - }); - } - } - }, { - key: 'attachMedia', - value: function attachMedia() { - var _this4 = this; - - this.mediaSource = new MSEController(this.video, this.config); - this.mediaSource.on('source_open', function () { - _this4.transmuxer.loadSource(); - }); - this.mediaSource.on('bufferFull', function () { - _this4.pauseTransmuxer(); - }); - this.mediaSource.on('mediaInfo', function (mediaInfo) { - _this4.emit('mediaInfo', mediaInfo); - }); - this.mediaSource.on('updateend', this.onmseUpdateEnd.bind(this)); - } - }, { - key: 'load', - value: function load() { - var _this5 = this; - - this.video.src = URL.createObjectURL(this.mediaSource.mediaSource); - this.video.addEventListener('seeking', throttle(this._seek.bind(this), 200, { leading: false })); - this.transmuxer = new Transmuxer(this.mediaSource, this.config); - this.transmuxer.on('mediaSegment', function (handle) { - _this5.mediaSource.emit('mediaSegment', handle.data); - }); - this.transmuxer.on('mediaSegmentInit', function (handle) { - _this5.mediaSource.emit('mediaSegmentInit', handle.data); - }); - this.transmuxer.on('error', function (handle) { - _this5.emit('error', handle.data); - }); - } - }, { - key: 'isTimeinBuffered', - value: function isTimeinBuffered(seconds) { - var buffered = this.video.buffered; - for (var i = 0; i < buffered.length; i++) { - var from = buffered.start(i); - var to = buffered.end(i); - if (seconds >= from && seconds < to) { - return true; - } - } - return false; - } - }, { - key: 'getCurrentBufferEnd', - value: function getCurrentBufferEnd() { - var buffered = this.video.buffered; - var currentTime = this.video.currentTime; - var currentRangeEnd = 0; - - for (var i = 0; i < buffered.length; i++) { - var start = buffered.start(i); - var end = buffered.end(i); - if (start <= currentTime && currentTime < end) { - currentRangeEnd = end; - return currentRangeEnd; - } - } - } - }, { - key: '_seek', - value: function _seek(e, seconds) { - this.currentTimeLock = true; - this.timer = null; - - var currentTime = seconds ? seconds : this.video.currentTime; - if (this.requestSetTime) { - this.requestSetTime = false; - this.currentTimeLock = false; - return; - } - // const buffered = this.video.buffered; - if (this.isTimeinBuffered(currentTime)) { - if (this.config.alwaysSeekKeyframe) { - var nearlestkeyframe = this.transmuxer.getNearlestKeyframe(Math.floor(currentTime * 1000)); - if (nearlestkeyframe) { - this.requestSetTime = true; - this.video.currentTime = nearlestkeyframe.keyframetime / 1000; - } - } - } else { - this.transmuxer.pause(); - var _nearlestkeyframe = this.transmuxer.getNearlestKeyframe(Math.floor(currentTime * 1000)); - currentTime = _nearlestkeyframe.keyframetime / 1000; - this.transmuxer.seek(_nearlestkeyframe); - this.mediaSource.seek(currentTime); - this.requestSetTime = true; - this.video.currentTime = currentTime; - window.clearInterval(this.timer); - this.timer = null; - } - this.currentTimeLock = false; - return currentTime; - } - }, { - key: 'onmseUpdateEnd', - value: function onmseUpdateEnd() { - if (this.config.isLive) { - return; - } - var currentBufferEnd = this.getCurrentBufferEnd(); - var currentTime = this.video.currentTime; - if (currentBufferEnd >= currentTime + this.config.lazyLoadMaxDuration && this.timer === null) { - Log.verbose(this.tag, 'Maximum buffering duration exceeded, suspend transmuxing task'); - this.pauseTransmuxer(); - } - } - }, { - key: 'heartbeat', - value: function heartbeat() { - var currentTime = this.video.currentTime; - var buffered = this.video.buffered; - - var needResume = false; - - for (var i = 0; i < buffered.length; i++) { - var from = buffered.start(i); - var to = buffered.end(i); - if (currentTime >= from && currentTime < to) { - if (currentTime >= to - this.config.lazyLoadRecoverDuration) { - needResume = true; - } - break; - } - } - - if (needResume) { - window.clearInterval(this.timer); - this.timer = null; - Log.verbose(this.TAG, 'Continue loading from paused position'); - this.transmuxer.resume(); - } - } - }, { - key: 'pauseTransmuxer', - value: function pauseTransmuxer() { - this.transmuxer.pause(); - if (!this.timer) { - this.timer = setInterval(this.heartbeat.bind(this), 1000); - } - } - }, { - key: 'resume', - value: function resume() {} - }, { - key: 'destroy', - value: function destroy() { - if (this.video) { - this.video.src = ''; - this.video.removeAttribute('src'); - this.transmuxer.destroy(); - this.transmuxer = null; - this.mediaSource.destroy(); - this.mediaSource = null; - } - } - }, { - key: 'seek', - value: function seek(seconds) { - // throttle(this._seek.bind(this, seconds), 200, {leading: false}); - return this._seek(null, seconds); - } - }, { - key: 'play', - value: function play() { - return this.video.play(); - } - }, { - key: 'pause', - value: function pause() { - return this.video.pause(); - } - }]); - - return Flv; -}(CustEvent); - -function commonjsRequire$1 () { - throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); -} - -function unwrapExports$1 (x) { - return x && x.__esModule ? x['default'] : x; -} - -function createCommonjsModule$1(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -var hls = createCommonjsModule$1(function (module, exports) { -(function(f){{module.exports=f();}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire$1=="function"&&commonjsRequire$1;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire$1=="function"&&commonjsRequire$1;for(var o=0;o 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction$$1(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction$$1(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction$$1(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction$$1(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction$$1(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction$$1(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction$$1(arg) { - return typeof arg === 'function'; -} - -function isNumber$$1(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - -},{}],2:[function(_dereq_,module,exports){ -// see https://tools.ietf.org/html/rfc1808 - -/* jshint ignore:start */ -(function(root) { -/* jshint ignore:end */ - - var URL_REGEX = /^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/; - var FIRST_SEGMENT_REGEX = /^([^\/;?#]*)(.*)$/; - var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g; - var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g; - - var URLToolkit = { // jshint ignore:line - // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or // - // E.g - // With opts.alwaysNormalize = false (default, spec compliant) - // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g - // With opts.alwaysNormalize = true (default, not spec compliant) - // http://a.com/b/cd + /e/f/../g => http://a.com/e/g - buildAbsoluteURL: function(baseURL, relativeURL, opts) { - opts = opts || {}; - // remove any remaining space and CRLF - baseURL = baseURL.trim(); - relativeURL = relativeURL.trim(); - if (!relativeURL) { - // 2a) If the embedded URL is entirely empty, it inherits the - // entire base URL (i.e., is set equal to the base URL) - // and we are done. - if (!opts.alwaysNormalize) { - return baseURL; - } - var basePartsForNormalise = this.parseURL(baseURL); - if (!baseParts) { - throw new Error('Error trying to parse base URL.'); - } - basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path); - return URLToolkit.buildURLFromParts(basePartsForNormalise); - } - var relativeParts = this.parseURL(relativeURL); - if (!relativeParts) { - throw new Error('Error trying to parse relative URL.'); - } - if (relativeParts.scheme) { - // 2b) If the embedded URL starts with a scheme name, it is - // interpreted as an absolute URL and we are done. - if (!opts.alwaysNormalize) { - return relativeURL; - } - relativeParts.path = URLToolkit.normalizePath(relativeParts.path); - return URLToolkit.buildURLFromParts(relativeParts); - } - var baseParts = this.parseURL(baseURL); - if (!baseParts) { - throw new Error('Error trying to parse base URL.'); - } - if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') { - // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc - // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a' - var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path); - baseParts.netLoc = pathParts[1]; - baseParts.path = pathParts[2]; - } - if (baseParts.netLoc && !baseParts.path) { - baseParts.path = '/'; - } - var builtParts = { - // 2c) Otherwise, the embedded URL inherits the scheme of - // the base URL. - scheme: baseParts.scheme, - netLoc: relativeParts.netLoc, - path: null, - params: relativeParts.params, - query: relativeParts.query, - fragment: relativeParts.fragment - }; - if (!relativeParts.netLoc) { - // 3) If the embedded URL's is non-empty, we skip to - // Step 7. Otherwise, the embedded URL inherits the - // (if any) of the base URL. - builtParts.netLoc = baseParts.netLoc; - // 4) If the embedded URL path is preceded by a slash "/", the - // path is not relative and we skip to Step 7. - if (relativeParts.path[0] !== '/') { - if (!relativeParts.path) { - // 5) If the embedded URL path is empty (and not preceded by a - // slash), then the embedded URL inherits the base URL path - builtParts.path = baseParts.path; - // 5a) if the embedded URL's is non-empty, we skip to - // step 7; otherwise, it inherits the of the base - // URL (if any) and - if (!relativeParts.params) { - builtParts.params = baseParts.params; - // 5b) if the embedded URL's is non-empty, we skip to - // step 7; otherwise, it inherits the of the base - // URL (if any) and we skip to step 7. - if (!relativeParts.query) { - builtParts.query = baseParts.query; - } - } - } else { - // 6) The last segment of the base URL's path (anything - // following the rightmost slash "/", or the entire path if no - // slash is present) is removed and the embedded URL's path is - // appended in its place. - var baseURLPath = baseParts.path; - var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path; - builtParts.path = URLToolkit.normalizePath(newPath); - } - } - } - if (builtParts.path === null) { - builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path; - } - return URLToolkit.buildURLFromParts(builtParts); - }, - parseURL: function(url) { - var parts = URL_REGEX.exec(url); - if (!parts) { - return null; - } - return { - scheme: parts[1] || '', - netLoc: parts[2] || '', - path: parts[3] || '', - params: parts[4] || '', - query: parts[5] || '', - fragment: parts[6] || '' - }; - }, - normalizePath: function(path) { - // The following operations are - // then applied, in order, to the new path: - // 6a) All occurrences of "./", where "." is a complete path - // segment, are removed. - // 6b) If the path ends with "." as a complete path segment, - // that "." is removed. - path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); - // 6c) All occurrences of "/../", where is a - // complete path segment not equal to "..", are removed. - // Removal of these path segments is performed iteratively, - // removing the leftmost matching pattern on each iteration, - // until no matching pattern remains. - // 6d) If the path ends with "/..", where is a - // complete path segment not equal to "..", that - // "/.." is removed. - while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line - return path.split('').reverse().join(''); - }, - buildURLFromParts: function(parts) { - return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment; - } - }; - -/* jshint ignore:start */ - if(typeof exports === 'object' && typeof module === 'object') - module.exports = URLToolkit; - else if(typeof define === 'function' && define.amd) - define([], function() { return URLToolkit; }); - else if(typeof exports === 'object') - exports["URLToolkit"] = URLToolkit; - else - root["URLToolkit"] = URLToolkit; -})(this); -/* jshint ignore:end */ - -},{}],3:[function(_dereq_,module,exports){ -var bundleFn = arguments[3]; -var sources = arguments[4]; -var cache = arguments[5]; - -var stringify = JSON.stringify; - -module.exports = function (fn, options) { - var wkey; - var cacheKeys = Object.keys(cache); - - for (var i = 0, l = cacheKeys.length; i < l; i++) { - var key = cacheKeys[i]; - var exp = cache[key].exports; - // Using babel as a transpiler to use esmodule, the export will always - // be an object with the default export as a property of it. To ensure - // the existing api and babel esmodule exports are both supported we - // check for both - if (exp === fn || exp && exp.default === fn) { - wkey = key; - break; - } - } - - if (!wkey) { - wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); - var wcache = {}; - for (var i = 0, l = cacheKeys.length; i < l; i++) { - var key = cacheKeys[i]; - wcache[key] = key; - } - sources[wkey] = [ - Function(['require','module','exports'], '(' + fn + ')(self)'), - wcache - ]; - } - var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); - - var scache = {}; scache[wkey] = wkey; - sources[skey] = [ - Function(['require'], ( - // try to call default if defined to also support babel esmodule - // exports - 'var f = require(' + stringify(wkey) + ');' + - '(f.default ? f.default : f)(self);' - )), - scache - ]; - - var workerSources = {}; - resolveSources(skey); - - function resolveSources(key) { - workerSources[key] = true; - - for (var depPath in sources[key][1]) { - var depKey = sources[key][1][depPath]; - if (!workerSources[depKey]) { - resolveSources(depKey); - } - } - } - - var src = '(' + bundleFn + ')({' - + Object.keys(workerSources).map(function (key) { - return stringify(key) + ':[' - + sources[key][0] - + ',' + stringify(sources[key][1]) + ']' - ; - }).join(',') - + '},{},[' + stringify(skey) + '])'; - - var URL = window.URL || window.webkitURL || window.mozURL || window.msURL; - - var blob = new Blob([src], { type: 'text/javascript' }); - if (options && options.bare) { return blob; } - var workerUrl = URL.createObjectURL(blob); - var worker = new Worker(workerUrl); - worker.objectURL = workerUrl; - return worker; -}; - -},{}],4:[function(_dereq_,module,exports){ -/** - * HLS config - */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hlsDefaultConfig = undefined; - -var _abrController = _dereq_(5); - -var _abrController2 = _interopRequireDefault(_abrController); - -var _bufferController = _dereq_(8); - -var _bufferController2 = _interopRequireDefault(_bufferController); - -var _capLevelController = _dereq_(9); - -var _capLevelController2 = _interopRequireDefault(_capLevelController); - -var _fpsController = _dereq_(10); - -var _fpsController2 = _interopRequireDefault(_fpsController); - -var _xhrLoader = _dereq_(59); - -var _xhrLoader2 = _interopRequireDefault(_xhrLoader); - -var _audioTrackController = _dereq_(7); - -var _audioTrackController2 = _interopRequireDefault(_audioTrackController); - -var _audioStreamController = _dereq_(6); - -var _audioStreamController2 = _interopRequireDefault(_audioStreamController); - -var _cues = _dereq_(50); - -var _cues2 = _interopRequireDefault(_cues); - -var _timelineController = _dereq_(16); - -var _timelineController2 = _interopRequireDefault(_timelineController); - -var _subtitleTrackController = _dereq_(15); - -var _subtitleTrackController2 = _interopRequireDefault(_subtitleTrackController); - -var _subtitleStreamController = _dereq_(14); - -var _subtitleStreamController2 = _interopRequireDefault(_subtitleStreamController); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -//#endif - -//#endif - -//#if subtitle - -//import FetchLoader from './utils/fetch-loader'; -//#if altaudio -var hlsDefaultConfig = exports.hlsDefaultConfig = { - autoStartLoad: true, // used by stream-controller - startPosition: -1, // used by stream-controller - defaultAudioCodec: undefined, // used by stream-controller - debug: false, // used by logger - capLevelOnFPSDrop: false, // used by fps-controller - capLevelToPlayerSize: false, // used by cap-level-controller - initialLiveManifestSize: 1, // used by stream-controller - maxBufferLength: 30, // used by stream-controller - maxBufferSize: 60 * 1000 * 1000, // used by stream-controller - maxBufferHole: 0.5, // used by stream-controller - maxSeekHole: 2, // used by stream-controller - lowBufferWatchdogPeriod: 0.5, // used by stream-controller - highBufferWatchdogPeriod: 3, // used by stream-controller - nudgeOffset: 0.1, // used by stream-controller - nudgeMaxRetry: 3, // used by stream-controller - maxFragLookUpTolerance: 0.25, // used by stream-controller - liveSyncDurationCount: 3, // used by stream-controller - liveMaxLatencyDurationCount: Infinity, // used by stream-controller - liveSyncDuration: undefined, // used by stream-controller - liveMaxLatencyDuration: undefined, // used by stream-controller - maxMaxBufferLength: 600, // used by stream-controller - enableWorker: true, // used by demuxer - enableSoftwareAES: true, // used by decrypter - manifestLoadingTimeOut: 10000, // used by playlist-loader - manifestLoadingMaxRetry: 1, // used by playlist-loader - manifestLoadingRetryDelay: 1000, // used by playlist-loader - manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader - startLevel: undefined, // used by level-controller - levelLoadingTimeOut: 10000, // used by playlist-loader - levelLoadingMaxRetry: 4, // used by playlist-loader - levelLoadingRetryDelay: 1000, // used by playlist-loader - levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader - fragLoadingTimeOut: 20000, // used by fragment-loader - fragLoadingMaxRetry: 6, // used by fragment-loader - fragLoadingRetryDelay: 1000, // used by fragment-loader - fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader - fragLoadingLoopThreshold: 3, // used by stream-controller - startFragPrefetch: false, // used by stream-controller - fpsDroppedMonitoringPeriod: 5000, // used by fps-controller - fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller - appendErrorMaxRetry: 3, // used by buffer-controller - loader: _xhrLoader2.default, - //loader: FetchLoader, - fLoader: undefined, - pLoader: undefined, - xhrSetup: undefined, - fetchSetup: undefined, - abrController: _abrController2.default, - bufferController: _bufferController2.default, - capLevelController: _capLevelController2.default, - fpsController: _fpsController2.default, - //#if altaudio - audioStreamController: _audioStreamController2.default, - audioTrackController: _audioTrackController2.default, - //#endif - //#if subtitle - subtitleStreamController: _subtitleStreamController2.default, - subtitleTrackController: _subtitleTrackController2.default, - timelineController: _timelineController2.default, - cueHandler: _cues2.default, - enableCEA708Captions: true, // used by timeline-controller - enableWebVTT: true, // used by timeline-controller - captionsTextTrack1Label: 'English', // used by timeline-controller - captionsTextTrack1LanguageCode: 'en', // used by timeline-controller - captionsTextTrack2Label: 'Spanish', // used by timeline-controller - captionsTextTrack2LanguageCode: 'es', // used by timeline-controller - //#endif - stretchShortVideoTrack: false, // used by mp4-remuxer - forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer - abrEwmaFastLive: 3, // used by abr-controller - abrEwmaSlowLive: 9, // used by abr-controller - abrEwmaFastVoD: 3, // used by abr-controller - abrEwmaSlowVoD: 9, // used by abr-controller - abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller - abrBandWidthFactor: 0.95, // used by abr-controller - abrBandWidthUpFactor: 0.7, // used by abr-controller - abrMaxWithRealBitrate: false, // used by abr-controller - maxStarvationDelay: 4, // used by abr-controller - maxLoadingDelay: 4, // used by abr-controller - minAutoBitrate: 0 // used by hls -}; - -},{"10":10,"14":14,"15":15,"16":16,"5":5,"50":50,"59":59,"6":6,"7":7,"8":8,"9":9}],5:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _bufferHelper = _dereq_(37); - -var _bufferHelper2 = _interopRequireDefault(_bufferHelper); - -var _errors = _dereq_(33); - -var _logger = _dereq_(54); - -var _ewmaBandwidthEstimator = _dereq_(52); - -var _ewmaBandwidthEstimator2 = _interopRequireDefault(_ewmaBandwidthEstimator); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * simple ABR Controller - * - compute next level based on last fragment bw heuristics - * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling - */ - -var AbrController = function (_EventHandler) { - _inherits$$1(AbrController, _EventHandler); - - function AbrController(hls) { - _classCallCheck$$1(this, AbrController); - - var _this = _possibleConstructorReturn$$1(this, (AbrController.__proto__ || Object.getPrototypeOf(AbrController)).call(this, hls, _events2.default.FRAG_LOADING, _events2.default.FRAG_LOADED, _events2.default.FRAG_BUFFERED, _events2.default.ERROR)); - - _this.lastLoadedFragLevel = 0; - _this._nextAutoLevel = -1; - _this.hls = hls; - _this.timer = null; - _this._bwEstimator = null; - _this.onCheck = _this._abandonRulesCheck.bind(_this); - return _this; - } - - _createClass$$1(AbrController, [{ - key: 'destroy', - value: function destroy() { - this.clearTimer(); - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'onFragLoading', - value: function onFragLoading(data) { - var frag = data.frag; - if (frag.type === 'main') { - if (!this.timer) { - this.timer = setInterval(this.onCheck, 100); - } - // lazy init of bw Estimator, rationale is that we use different params for Live/VoD - // so we need to wait for stream manifest / playlist type to instantiate it. - if (!this._bwEstimator) { - var hls = this.hls, - level = data.frag.level, - isLive = hls.levels[level].details.live, - config = hls.config, - ewmaFast = void 0, - ewmaSlow = void 0; - - if (isLive) { - ewmaFast = config.abrEwmaFastLive; - ewmaSlow = config.abrEwmaSlowLive; - } else { - ewmaFast = config.abrEwmaFastVoD; - ewmaSlow = config.abrEwmaSlowVoD; - } - this._bwEstimator = new _ewmaBandwidthEstimator2.default(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate); - } - this.fragCurrent = frag; - } - } - }, { - key: '_abandonRulesCheck', - value: function _abandonRulesCheck() { - /* - monitor fragment retrieval time... - we compute expected time of arrival of the complete fragment. - we compare it to expected time of buffer starvation - */ - var hls = this.hls, - v = hls.media, - frag = this.fragCurrent, - loader = frag.loader, - minAutoLevel = hls.minAutoLevel; - - // if loader has been destroyed or loading has been aborted, stop timer and return - if (!loader || loader.stats && loader.stats.aborted) { - _logger.logger.warn('frag loader destroy or aborted, disarm abandonRules'); - this.clearTimer(); - return; - } - var stats = loader.stats; - /* only monitor frag retrieval time if - (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */ - if (v && (!v.paused && v.playbackRate !== 0 || !v.readyState) && frag.autoLevel && frag.level) { - var requestDelay = performance.now() - stats.trequest, - playbackRate = Math.abs(v.playbackRate); - // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate - if (requestDelay > 500 * frag.duration / playbackRate) { - var levels = hls.levels, - loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay), - // byte/s; at least 1 byte/s to avoid division by zero - // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size - level = levels[frag.level], - levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate, - expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)), - pos = v.currentTime, - fragLoadedDelay = (expectedLen - stats.loaded) / loadRate, - bufferStarvationDelay = (_bufferHelper2.default.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos) / playbackRate; - // consider emergency switch down only if we have less than 2 frag buffered AND - // time to finish loading current fragment is bigger than buffer starvation delay - // ie if we risk buffer starvation if bw does not increase quickly - if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) { - var fragLevelNextLoadedDelay = void 0, - nextLoadLevel = void 0; - // lets iterate through lower level and try to find the biggest one that could avoid rebuffering - // we start from current level - 1 and we step down , until we find a matching level - for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) { - // compute time to load next fragment at lower level - // 0.8 : consider only 80% of current bw to be conservative - // 8 = bits per byte (bps/Bps) - var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate; - fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate); - if (fragLevelNextLoadedDelay < bufferStarvationDelay) { - // we found a lower level that be rebuffering free with current estimated bw ! - break; - } - } - // only emergency switch down if it takes less time to load new fragment at lowest level instead - // of finishing loading current one ... - if (fragLevelNextLoadedDelay < fragLoadedDelay) { - _logger.logger.warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel + ':fragLoadedDelay[' + nextLoadLevel + ']= minAutoLevel; i--) { - var levelInfo = levels[i], - levelDetails = levelInfo.details, - avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration, - live = levelDetails ? levelDetails.live : false, - adjustedbw = void 0; - // follow algorithm captured from stagefright : - // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp - // Pick the highest bandwidth stream below or equal to estimated bandwidth. - // consider only 80% of the available bandwidth, but if we are switching up, - // be even more conservative (70%) to avoid overestimating and immediately - // switching back. - if (i <= currentLevel) { - adjustedbw = bwFactor * currentBw; - } else { - adjustedbw = bwUpFactor * currentBw; - } - var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate, - fetchDuration = bitrate * avgDuration / adjustedbw; - - _logger.logger.trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration); - // if adjusted bw is greater than level bitrate AND - if (adjustedbw > bitrate && ( - // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches - // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ... - // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1 - !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) { - // as we are looping from highest to lowest, this will return the best achievable quality level - return i; - } - } - // not enough time budget even with quality level 0 ... rebuffering might happen - return -1; - } - }, { - key: 'nextAutoLevel', - get: function get() { - var forcedAutoLevel = this._nextAutoLevel; - var bwEstimator = this._bwEstimator; - // in case next auto level has been forced, and bw not available or not reliable, return forced value - if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) { - return forcedAutoLevel; - } - // compute next level using ABR logic - var nextABRAutoLevel = this._nextABRAutoLevel; - // if forced auto level has been defined, use it to cap ABR computed quality level - if (forcedAutoLevel !== -1) { - nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel); - } - return nextABRAutoLevel; - }, - set: function set(nextLevel) { - this._nextAutoLevel = nextLevel; - } - }, { - key: '_nextABRAutoLevel', - get: function get() { - var hls = this.hls, - maxAutoLevel = hls.maxAutoLevel, - levels = hls.levels, - config = hls.config, - minAutoLevel = hls.minAutoLevel; - var v = hls.media, - currentLevel = this.lastLoadedFragLevel, - currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0, - pos = v ? v.currentTime : 0, - - // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as - // if we're playing back at the normal rate. - playbackRate = v && v.playbackRate !== 0 ? Math.abs(v.playbackRate) : 1.0, - avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate, - - // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted. - bufferStarvationDelay = (_bufferHelper2.default.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate; - - // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all - var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels); - if (bestLevel >= 0) { - return bestLevel; - } else { - _logger.logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering'); - // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering - // if no matching level found, logic will return 0 - var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay, - bwFactor = config.abrBandWidthFactor, - bwUpFactor = config.abrBandWidthUpFactor; - if (bufferStarvationDelay === 0) { - // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test - var bitrateTestDelay = this.bitrateTestDelay; - if (bitrateTestDelay) { - // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value - // max video loading delay used in automatic start level selection : - // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level + - // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` ) - // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration - var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay; - maxStarvationDelay = maxLoadingDelay - bitrateTestDelay; - _logger.logger.trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms'); - // don't use conservative factor on bitrate test - bwFactor = bwUpFactor = 1; - } - } - bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels); - return Math.max(bestLevel, 0); - } - } - }]); - - return AbrController; -}(_eventHandler2.default); - -exports.default = AbrController; - -},{"33":33,"34":34,"35":35,"37":37,"52":52,"54":54}],6:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _binarySearch = _dereq_(48); - -var _binarySearch2 = _interopRequireDefault(_binarySearch); - -var _bufferHelper = _dereq_(37); - -var _bufferHelper2 = _interopRequireDefault(_bufferHelper); - -var _demuxer = _dereq_(25); - -var _demuxer2 = _interopRequireDefault(_demuxer); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _levelHelper = _dereq_(38); - -var _levelHelper2 = _interopRequireDefault(_levelHelper); - -var _timeRanges = _dereq_(55); - -var _timeRanges2 = _interopRequireDefault(_timeRanges); - -var _errors = _dereq_(33); - -var _logger = _dereq_(54); - -var _discontinuities = _dereq_(51); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Audio Stream Controller - */ - -var State = { - STOPPED: 'STOPPED', - STARTING: 'STARTING', - IDLE: 'IDLE', - PAUSED: 'PAUSED', - KEY_LOADING: 'KEY_LOADING', - FRAG_LOADING: 'FRAG_LOADING', - FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', - WAITING_TRACK: 'WAITING_TRACK', - PARSING: 'PARSING', - PARSED: 'PARSED', - BUFFER_FLUSHING: 'BUFFER_FLUSHING', - ENDED: 'ENDED', - ERROR: 'ERROR', - WAITING_INIT_PTS: 'WAITING_INIT_PTS' -}; - -var AudioStreamController = function (_EventHandler) { - _inherits$$1(AudioStreamController, _EventHandler); - - function AudioStreamController(hls) { - _classCallCheck$$1(this, AudioStreamController); - - var _this = _possibleConstructorReturn$$1(this, (AudioStreamController.__proto__ || Object.getPrototypeOf(AudioStreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.AUDIO_TRACKS_UPDATED, _events2.default.AUDIO_TRACK_SWITCHING, _events2.default.AUDIO_TRACK_LOADED, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.ERROR, _events2.default.BUFFER_CREATED, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED, _events2.default.INIT_PTS_FOUND)); - - _this.config = hls.config; - _this.audioCodecSwap = false; - _this.ticks = 0; - _this._state = State.STOPPED; - _this.ontick = _this.tick.bind(_this); - _this.initPTS = []; - _this.waitingFragment = null; - _this.videoTrackCC = null; - return _this; - } - - _createClass$$1(AudioStreamController, [{ - key: 'destroy', - value: function destroy() { - this.stopLoad(); - if (this.timer) { - clearInterval(this.timer); - this.timer = null; - } - _eventHandler2.default.prototype.destroy.call(this); - this.state = State.STOPPED; - } - - //Signal that video PTS was found - - }, { - key: 'onInitPtsFound', - value: function onInitPtsFound(data) { - var demuxerId = data.id, - cc = data.frag.cc, - initPTS = data.initPTS; - if (demuxerId === 'main') { - //Always update the new INIT PTS - //Can change due level switch - this.initPTS[cc] = initPTS; - this.videoTrackCC = cc; - _logger.logger.log('InitPTS for cc:' + cc + ' found from video track:' + initPTS); - - //If we are waiting we need to demux/remux the waiting frag - //With the new initPTS - if (this.state === State.WAITING_INIT_PTS) { - this.tick(); - } - } - } - }, { - key: 'startLoad', - value: function startLoad(startPosition) { - if (this.tracks) { - var lastCurrentTime = this.lastCurrentTime; - this.stopLoad(); - if (!this.timer) { - this.timer = setInterval(this.ontick, 100); - } - this.fragLoadError = 0; - if (lastCurrentTime > 0 && startPosition === -1) { - _logger.logger.log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3)); - this.state = State.IDLE; - } else { - this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition; - this.state = State.STARTING; - } - this.nextLoadPosition = this.startPosition = this.lastCurrentTime; - this.tick(); - } else { - this.startPosition = startPosition; - this.state = State.STOPPED; - } - } - }, { - key: 'stopLoad', - value: function stopLoad() { - var frag = this.fragCurrent; - if (frag) { - if (frag.loader) { - frag.loader.abort(); - } - this.fragCurrent = null; - } - this.fragPrevious = null; - if (this.demuxer) { - this.demuxer.destroy(); - this.demuxer = null; - } - this.state = State.STOPPED; - } - }, { - key: 'tick', - value: function tick() { - this.ticks++; - if (this.ticks === 1) { - this.doTick(); - if (this.ticks > 1) { - setTimeout(this.tick, 1); - } - this.ticks = 0; - } - } - }, { - key: 'doTick', - value: function doTick() { - var pos, - track, - trackDetails, - hls = this.hls, - config = hls.config; - //logger.log('audioStream:' + this.state); - switch (this.state) { - case State.ERROR: - //don't do anything in error state to avoid breaking further ... - case State.PAUSED: - //don't do anything in paused state either ... - case State.BUFFER_FLUSHING: - break; - case State.STARTING: - this.state = State.WAITING_TRACK; - this.loadedmetadata = false; - break; - case State.IDLE: - var tracks = this.tracks; - // audio tracks not received => exit loop - if (!tracks) { - break; - } - // if video not attached AND - // start fragment already requested OR start frag prefetch disable - // exit loop - // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop - if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) { - break; - } - // determine next candidate fragment to be loaded, based on current position and - // end of buffer position - // if we have not yet loaded any fragment, start loading from start position - if (this.loadedmetadata) { - pos = this.media.currentTime; - } else { - pos = this.nextLoadPosition; - if (pos === undefined) { - break; - } - } - var media = this.mediaBuffer ? this.mediaBuffer : this.media, - bufferInfo = _bufferHelper2.default.bufferInfo(media, pos, config.maxBufferHole), - bufferLen = bufferInfo.len, - bufferEnd = bufferInfo.end, - fragPrevious = this.fragPrevious, - maxBufLen = config.maxMaxBufferLength, - audioSwitch = this.audioSwitch, - trackId = this.trackId; - - // if buffer length is less than maxBufLen try to load a new fragment - if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) { - trackDetails = tracks[trackId].details; - // if track info not retrieved yet, switch state and wait for track retrieval - if (typeof trackDetails === 'undefined') { - this.state = State.WAITING_TRACK; - break; - } - - // we just got done loading the final fragment, check if we need to finalize media stream - if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN) { - // if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos - // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching - // between different renditions. using half frag duration should help cope with these cases. - if (!this.media.seeking || this.media.duration - bufferEnd < fragPrevious.duration / 2) { - // Finalize the media stream - this.hls.trigger(_events2.default.BUFFER_EOS, { type: 'audio' }); - this.state = State.ENDED; - break; - } - } - - // find fragment index, contiguous with end of buffer position - var fragments = trackDetails.fragments, - fragLen = fragments.length, - start = fragments[0].start, - end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, - frag = void 0; - - // When switching audio track, reload audio as close as possible to currentTime - if (audioSwitch) { - if (trackDetails.live && !trackDetails.PTSKnown) { - _logger.logger.log('switching audiotrack, live stream, unknown PTS,load first fragment'); - bufferEnd = 0; - } else { - bufferEnd = pos; - // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime - if (trackDetails.PTSKnown && pos < start) { - // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start - if (bufferInfo.end > start || bufferInfo.nextStart) { - _logger.logger.log('alt audio track ahead of main track, seek to start of alt audio track'); - this.media.currentTime = start + 0.05; - } else { - return; - } - } - } - } - if (trackDetails.initSegment && !trackDetails.initSegment.data) { - frag = trackDetails.initSegment; - } - // if bufferEnd before start of playlist, load first fragment - else if (bufferEnd <= start) { - frag = fragments[0]; - if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) { - // Ensure we find a fragment which matches the continuity of the video track - frag = (0, _discontinuities.findFragWithCC)(fragments, this.videoTrackCC); - } - if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) { - // we just loaded this first fragment, and we are still lagging behind the start of the live playlist - // let's force seek to start - var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start; - _logger.logger.log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05)); - this.media.currentTime = nextBuffered + 0.05; - return; - } - } else { - var foundFrag = void 0; - var maxFragLookUpTolerance = config.maxFragLookUpTolerance; - var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined; - var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) { - // offset should be within fragment boundary - config.maxFragLookUpTolerance - // this is to cope with situations like - // bufferEnd = 9.991 - // frag[Ø] : [0,10] - // frag[1] : [10,20] - // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here - // frag start frag start+duration - // |-----------------------------| - // <---> <---> - // ...--------><-----------------------------><---------.... - // previous frag matching fragment next frag - // return -1 return 0 return 1 - //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); - // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments - var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration); - if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { - return 1; - } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element - else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { - return -1; - } - return 0; - }; - - if (bufferEnd < end) { - if (bufferEnd > end - maxFragLookUpTolerance) { - maxFragLookUpTolerance = 0; - } - // Prefer the next fragment if it's within tolerance - if (fragNext && !fragmentWithinToleranceTest(fragNext)) { - foundFrag = fragNext; - } else { - foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest); - } - } else { - // reach end of playlist - foundFrag = fragments[fragLen - 1]; - } - if (foundFrag) { - frag = foundFrag; - start = foundFrag.start; - //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn); - if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) { - if (frag.sn < trackDetails.endSN) { - frag = fragments[frag.sn + 1 - trackDetails.startSN]; - _logger.logger.log('SN just loaded, load next one: ' + frag.sn); - } else { - frag = null; - } - } - } - } - if (frag) { - //logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3)); - if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) { - _logger.logger.log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId); - this.state = State.KEY_LOADING; - hls.trigger(_events2.default.KEY_LOADING, { frag: frag }); - } else { - _logger.logger.log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3)); - // ensure that we are not reloading the same fragments in loop ... - if (this.fragLoadIdx !== undefined) { - this.fragLoadIdx++; - } else { - this.fragLoadIdx = 0; - } - if (frag.loadCounter) { - frag.loadCounter++; - var maxThreshold = config.fragLoadingLoopThreshold; - // if this frag has already been loaded 3 times, and if it has been reloaded recently - if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag }); - return; - } - } else { - frag.loadCounter = 1; - } - frag.loadIdx = this.fragLoadIdx; - this.fragCurrent = frag; - this.startFragRequested = true; - if (!isNaN(frag.sn)) { - this.nextLoadPosition = frag.start + frag.duration; - } - hls.trigger(_events2.default.FRAG_LOADING, { frag: frag }); - this.state = State.FRAG_LOADING; - } - } - } - break; - case State.WAITING_TRACK: - track = this.tracks[this.trackId]; - // check if playlist is already loaded - if (track && track.details) { - this.state = State.IDLE; - } - break; - case State.FRAG_LOADING_WAITING_RETRY: - var now = performance.now(); - var retryDate = this.retryDate; - media = this.media; - var isSeeking = media && media.seeking; - // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading - if (!retryDate || now >= retryDate || isSeeking) { - _logger.logger.log('audioStreamController: retryDate reached, switch back to IDLE state'); - this.state = State.IDLE; - } - break; - case State.WAITING_INIT_PTS: - if (this.initPTS[this.videoTrackCC] === undefined) { - break; - } - - // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS - var waitingFrag = this.waitingFragment; - if (waitingFrag) { - var waitingFragCC = waitingFrag.frag.cc; - if (this.videoTrackCC !== waitingFragCC) { - _logger.logger.warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + this.videoTrackCC + ')'); - this.waitingFragment = null; - this.state = State.IDLE; - } else { - this.state = State.FRAG_LOADING; - this.onFragLoaded(this.waitingFragment); - this.waitingFragment = null; - } - } else { - this.state = State.IDLE; - } - - break; - case State.STOPPED: - case State.FRAG_LOADING: - case State.PARSING: - case State.PARSED: - case State.ENDED: - break; - default: - break; - } - } - }, { - key: 'onMediaAttached', - value: function onMediaAttached(data) { - var media = this.media = this.mediaBuffer = data.media; - this.onvseeking = this.onMediaSeeking.bind(this); - this.onvended = this.onMediaEnded.bind(this); - media.addEventListener('seeking', this.onvseeking); - media.addEventListener('ended', this.onvended); - var config = this.config; - if (this.tracks && config.autoStartLoad) { - this.startLoad(config.startPosition); - } - } - }, { - key: 'onMediaDetaching', - value: function onMediaDetaching() { - var media = this.media; - if (media && media.ended) { - _logger.logger.log('MSE detaching and video ended, reset startPosition'); - this.startPosition = this.lastCurrentTime = 0; - } - - // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery - var tracks = this.tracks; - if (tracks) { - // reset fragment load counter - tracks.forEach(function (track) { - if (track.details) { - track.details.fragments.forEach(function (fragment) { - fragment.loadCounter = undefined; - }); - } - }); - } - // remove video listeners - if (media) { - media.removeEventListener('seeking', this.onvseeking); - media.removeEventListener('ended', this.onvended); - this.onvseeking = this.onvseeked = this.onvended = null; - } - this.media = this.mediaBuffer = null; - this.loadedmetadata = false; - this.stopLoad(); - } - }, { - key: 'onMediaSeeking', - value: function onMediaSeeking() { - if (this.state === State.ENDED) { - // switch to IDLE state to check for potential new fragment - this.state = State.IDLE; - } - if (this.media) { - this.lastCurrentTime = this.media.currentTime; - } - // avoid reporting fragment loop loading error in case user is seeking several times on same position - if (this.fragLoadIdx !== undefined) { - this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; - } - // tick to speed up processing - this.tick(); - } - }, { - key: 'onMediaEnded', - value: function onMediaEnded() { - // reset startPosition and lastCurrentTime to restart playback @ stream beginning - this.startPosition = this.lastCurrentTime = 0; - } - }, { - key: 'onAudioTracksUpdated', - value: function onAudioTracksUpdated(data) { - _logger.logger.log('audio tracks updated'); - this.tracks = data.audioTracks; - } - }, { - key: 'onAudioTrackSwitching', - value: function onAudioTrackSwitching(data) { - // if any URL found on new audio track, it is an alternate audio track - var altAudio = !!data.url; - this.trackId = data.id; - - this.fragCurrent = null; - this.state = State.PAUSED; - this.waitingFragment = null; - // destroy useless demuxer when switching audio to main - if (!altAudio) { - if (this.demuxer) { - this.demuxer.destroy(); - this.demuxer = null; - } - } else { - // switching to audio track, start timer if not already started - if (!this.timer) { - this.timer = setInterval(this.ontick, 100); - } - } - - //should we switch tracks ? - if (altAudio) { - this.audioSwitch = true; - //main audio track are handled by stream-controller, just do something if switching to alt audio track - this.state = State.IDLE; - // increase fragment load Index to avoid frag loop loading error after buffer flush - if (this.fragLoadIdx !== undefined) { - this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; - } - } - this.tick(); - } - }, { - key: 'onAudioTrackLoaded', - value: function onAudioTrackLoaded(data) { - var newDetails = data.details, - trackId = data.id, - track = this.tracks[trackId], - duration = newDetails.totalduration, - sliding = 0; - - _logger.logger.log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration); - - if (newDetails.live) { - var curDetails = track.details; - if (curDetails && newDetails.fragments.length > 0) { - // we already have details for that level, merge them - _levelHelper2.default.mergeDetails(curDetails, newDetails); - sliding = newDetails.fragments[0].start; - // TODO - //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails); - if (newDetails.PTSKnown) { - _logger.logger.log('live audio playlist sliding:' + sliding.toFixed(3)); - } else { - _logger.logger.log('live audio playlist - outdated PTS, unknown sliding'); - } - } else { - newDetails.PTSKnown = false; - _logger.logger.log('live audio playlist - first load, unknown sliding'); - } - } else { - newDetails.PTSKnown = false; - } - track.details = newDetails; - - // compute start position - if (!this.startFragRequested) { - // compute start position if set to -1. use it straight away if value is defined - if (this.startPosition === -1) { - // first, check if start time offset has been set in playlist, if yes, use this value - var startTimeOffset = newDetails.startTimeOffset; - if (!isNaN(startTimeOffset)) { - _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset); - this.startPosition = startTimeOffset; - } else { - this.startPosition = 0; - } - } - this.nextLoadPosition = this.startPosition; - } - // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment - if (this.state === State.WAITING_TRACK) { - this.state = State.IDLE; - } - //trigger handler right now - this.tick(); - } - }, { - key: 'onKeyLoaded', - value: function onKeyLoaded() { - if (this.state === State.KEY_LOADING) { - this.state = State.IDLE; - this.tick(); - } - } - }, { - key: 'onFragLoaded', - value: function onFragLoaded(data) { - var fragCurrent = this.fragCurrent, - fragLoaded = data.frag; - if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) { - var track = this.tracks[this.trackId], - details = track.details, - duration = details.totalduration, - trackId = fragCurrent.level, - sn = fragCurrent.sn, - cc = fragCurrent.cc, - audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2', - stats = this.stats = data.stats; - if (sn === 'initSegment') { - this.state = State.IDLE; - - stats.tparsed = stats.tbuffered = performance.now(); - details.initSegment.data = data.payload; - this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' }); - this.tick(); - } else { - this.state = State.PARSING; - // transmux the MPEG-TS data to ISO-BMFF segments - this.appended = false; - if (!this.demuxer) { - this.demuxer = new _demuxer2.default(this.hls, 'audio'); - } - //Check if we have video initPTS - // If not we need to wait for it - var initPTS = this.initPTS[cc]; - var initSegmentData = details.initSegment ? details.initSegment.data : []; - if (details.initSegment || initPTS !== undefined) { - this.pendingBuffering = true; - _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId); - // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) - var accurateTimeOffset = false; //details.PTSKnown || !details.live; - this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS); - } else { - _logger.logger.log('unknown video PTS for continuity counter ' + cc + ', waiting for video PTS before demuxing audio frag ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId); - this.waitingFragment = data; - this.state = State.WAITING_INIT_PTS; - } - } - } - this.fragLoadError = 0; - } - }, { - key: 'onFragParsingInitSegment', - value: function onFragParsingInitSegment(data) { - var fragCurrent = this.fragCurrent; - var fragNew = data.frag; - if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { - var tracks = data.tracks, - track = void 0; - - // delete any video track found on audio demuxer - if (tracks.video) { - delete tracks.video; - } - - // include levelCodec in audio and video tracks - track = tracks.audio; - if (track) { - track.levelCodec = track.codec; - track.id = data.id; - this.hls.trigger(_events2.default.BUFFER_CODECS, tracks); - _logger.logger.log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']'); - var initSegment = track.initSegment; - if (initSegment) { - var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' }; - if (this.audioSwitch) { - this.pendingData = [appendObj]; - } else { - this.appended = true; - // arm pending Buffering flag before appending a segment - this.pendingBuffering = true; - this.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj); - } - } - //trigger handler right now - this.tick(); - } - } - } - }, { - key: 'onFragParsingData', - value: function onFragParsingData(data) { - var _this2 = this; - - var fragCurrent = this.fragCurrent; - var fragNew = data.frag; - if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { - var trackId = this.trackId, - track = this.tracks[trackId], - hls = this.hls; - - if (isNaN(data.endPTS)) { - data.endPTS = data.startPTS + fragCurrent.duration; - data.endDTS = data.startDTS + fragCurrent.duration; - } - - _logger.logger.log('parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb); - _levelHelper2.default.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS); - - var audioSwitch = this.audioSwitch, - media = this.media, - appendOnBufferFlush = false; - //Only flush audio from old audio tracks when PTS is known on new audio track - if (audioSwitch && media) { - if (media.readyState) { - var currentTime = media.currentTime; - _logger.logger.log('switching audio track : currentTime:' + currentTime); - if (currentTime >= data.startPTS) { - _logger.logger.log('switching audio track : flushing all audio'); - this.state = State.BUFFER_FLUSHING; - hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); - appendOnBufferFlush = true; - //Lets announce that the initial audio track switch flush occur - this.audioSwitch = false; - hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId }); - } - } else { - //Lets announce that the initial audio track switch flush occur - this.audioSwitch = false; - hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId }); - } - } - - var pendingData = this.pendingData; - if (!this.audioSwitch) { - [data.data1, data.data2].forEach(function (buffer) { - if (buffer && buffer.length) { - pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' }); - } - }); - if (!appendOnBufferFlush && pendingData.length) { - pendingData.forEach(function (appendObj) { - // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending) - // in that case it is useless to append following segments - if (_this2.state === State.PARSING) { - // arm pending Buffering flag before appending a segment - _this2.pendingBuffering = true; - _this2.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj); - } - }); - this.pendingData = []; - this.appended = true; - } - } - //trigger handler right now - this.tick(); - } - } - }, { - key: 'onFragParsed', - value: function onFragParsed(data) { - var fragCurrent = this.fragCurrent; - var fragNew = data.frag; - if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { - this.stats.tparsed = performance.now(); - this.state = State.PARSED; - this._checkAppendedParsed(); - } - } - }, { - key: 'onBufferCreated', - value: function onBufferCreated(data) { - var audioTrack = data.tracks.audio; - if (audioTrack) { - this.mediaBuffer = audioTrack.buffer; - this.loadedmetadata = true; - } - } - }, { - key: 'onBufferAppended', - value: function onBufferAppended(data) { - if (data.parent === 'audio') { - var state = this.state; - if (state === State.PARSING || state === State.PARSED) { - // check if all buffers have been appended - this.pendingBuffering = data.pending > 0; - this._checkAppendedParsed(); - } - } - } - }, { - key: '_checkAppendedParsed', - value: function _checkAppendedParsed() { - //trigger handler right now - if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) { - var frag = this.fragCurrent, - stats = this.stats, - hls = this.hls; - if (frag) { - this.fragPrevious = frag; - stats.tbuffered = performance.now(); - hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' }); - var media = this.mediaBuffer ? this.mediaBuffer : this.media; - _logger.logger.log('audio buffered : ' + _timeRanges2.default.toString(media.buffered)); - if (this.audioSwitch && this.appended) { - this.audioSwitch = false; - hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: this.trackId }); - } - this.state = State.IDLE; - } - this.tick(); - } - } - }, { - key: 'onError', - value: function onError(data) { - var frag = data.frag; - // don't handle frag error not related to audio fragment - if (frag && frag.type !== 'audio') { - return; - } - switch (data.details) { - case _errors.ErrorDetails.FRAG_LOAD_ERROR: - case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT: - if (!data.fatal) { - var loadError = this.fragLoadError; - if (loadError) { - loadError++; - } else { - loadError = 1; - } - var config = this.config; - if (loadError <= config.fragLoadingMaxRetry) { - this.fragLoadError = loadError; - // reset load counter to avoid frag loop loading error - frag.loadCounter = 0; - // exponential backoff capped to config.fragLoadingMaxRetryTimeout - var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout); - _logger.logger.warn('audioStreamController: frag loading failed, retry in ' + delay + ' ms'); - this.retryDate = performance.now() + delay; - // retry loading state - this.state = State.FRAG_LOADING_WAITING_RETRY; - } else { - _logger.logger.error('audioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...'); - // switch error to fatal - data.fatal = true; - this.state = State.ERROR; - } - } - break; - case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR: - case _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR: - case _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT: - case _errors.ErrorDetails.KEY_LOAD_ERROR: - case _errors.ErrorDetails.KEY_LOAD_TIMEOUT: - // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received - if (this.state !== State.ERROR) { - // if fatal error, stop processing, otherwise move to IDLE to retry loading - this.state = data.fatal ? State.ERROR : State.IDLE; - _logger.logger.warn('audioStreamController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...'); - } - break; - case _errors.ErrorDetails.BUFFER_FULL_ERROR: - // if in appending state - if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) { - var media = this.mediaBuffer, - currentTime = this.media.currentTime, - mediaBuffered = media && _bufferHelper2.default.isBuffered(media, currentTime) && _bufferHelper2.default.isBuffered(media, currentTime + 0.5); - // reduce max buf len if current position is buffered - if (mediaBuffered) { - var _config = this.config; - if (_config.maxMaxBufferLength >= _config.maxBufferLength) { - // reduce max buffer length as it might be too high. we do this to avoid loop flushing ... - _config.maxMaxBufferLength /= 2; - _logger.logger.warn('audio:reduce max buffer length to ' + _config.maxMaxBufferLength + 's'); - // increase fragment load Index to avoid frag loop loading error after buffer flush - this.fragLoadIdx += 2 * _config.fragLoadingLoopThreshold; - } - this.state = State.IDLE; - } else { - // current position is not buffered, but browser is still complaining about buffer full error - // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 - // in that case flush the whole audio buffer to recover - _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush audio buffer'); - this.fragCurrent = null; - // flush everything - this.state = State.BUFFER_FLUSHING; - this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); - } - } - break; - default: - break; - } - } - }, { - key: 'onBufferFlushed', - value: function onBufferFlushed() { - var _this3 = this; - - var pendingData = this.pendingData; - if (pendingData && pendingData.length) { - _logger.logger.log('appending pending audio data on Buffer Flushed'); - pendingData.forEach(function (appendObj) { - _this3.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj); - }); - this.appended = true; - this.pendingData = []; - this.state = State.PARSED; - } else { - // move to IDLE once flush complete. this should trigger new fragment loading - this.state = State.IDLE; - // reset reference to frag - this.fragPrevious = null; - this.tick(); - } - } - }, { - key: 'state', - set: function set(nextState) { - if (this.state !== nextState) { - var previousState = this.state; - this._state = nextState; - _logger.logger.log('audio stream:' + previousState + '->' + nextState); - } - }, - get: function get() { - return this._state; - } - }]); - - return AudioStreamController; -}(_eventHandler2.default); - -exports.default = AudioStreamController; - -},{"25":25,"33":33,"34":34,"35":35,"37":37,"38":38,"48":48,"51":51,"54":54,"55":55}],7:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * audio track controller - */ - -var AudioTrackController = function (_EventHandler) { - _inherits$$1(AudioTrackController, _EventHandler); - - function AudioTrackController(hls) { - _classCallCheck$$1(this, AudioTrackController); - - var _this = _possibleConstructorReturn$$1(this, (AudioTrackController.__proto__ || Object.getPrototypeOf(AudioTrackController)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.AUDIO_TRACK_LOADED)); - - _this.ticks = 0; - _this.ontick = _this.tick.bind(_this); - return _this; - } - - _createClass$$1(AudioTrackController, [{ - key: 'destroy', - value: function destroy() { - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'tick', - value: function tick() { - this.ticks++; - if (this.ticks === 1) { - this.doTick(); - if (this.ticks > 1) { - setTimeout(this.tick, 1); - } - this.ticks = 0; - } - } - }, { - key: 'doTick', - value: function doTick() { - this.updateTrack(this.trackId); - } - }, { - key: 'onManifestLoading', - value: function onManifestLoading() { - // reset audio tracks on manifest loading - this.tracks = []; - this.trackId = -1; - } - }, { - key: 'onManifestLoaded', - value: function onManifestLoaded(data) { - var _this2 = this; - - var tracks = data.audioTracks || []; - var defaultFound = false; - this.tracks = tracks; - this.hls.trigger(_events2.default.AUDIO_TRACKS_UPDATED, { audioTracks: tracks }); - // loop through available audio tracks and autoselect default if needed - var id = 0; - tracks.forEach(function (track) { - if (track.default) { - _this2.audioTrack = id; - defaultFound = true; - return; - } - id++; - }); - if (defaultFound === false && tracks.length) { - _logger.logger.log('no default audio track defined, use first audio track as default'); - this.audioTrack = 0; - } - } - }, { - key: 'onAudioTrackLoaded', - value: function onAudioTrackLoaded(data) { - if (data.id < this.tracks.length) { - _logger.logger.log('audioTrack ' + data.id + ' loaded'); - this.tracks[data.id].details = data.details; - // check if current playlist is a live playlist - if (data.details.live && !this.timer) { - // if live playlist we will have to reload it periodically - // set reload period to playlist target duration - this.timer = setInterval(this.ontick, 1000 * data.details.targetduration); - } - if (!data.details.live && this.timer) { - // playlist is not live and timer is armed : stopping it - clearInterval(this.timer); - this.timer = null; - } - } - } - - /** get alternate audio tracks list from playlist **/ - - }, { - key: 'setAudioTrackInternal', - value: function setAudioTrackInternal(newId) { - // check if level idx is valid - if (newId >= 0 && newId < this.tracks.length) { - // stopping live reloading timer if any - if (this.timer) { - clearInterval(this.timer); - this.timer = null; - } - this.trackId = newId; - _logger.logger.log('switching to audioTrack ' + newId); - var audioTrack = this.tracks[newId], - hls = this.hls, - type = audioTrack.type, - url = audioTrack.url, - eventObj = { id: newId, type: type, url: url }; - // keep AUDIO_TRACK_SWITCH for legacy reason - hls.trigger(_events2.default.AUDIO_TRACK_SWITCH, eventObj); - hls.trigger(_events2.default.AUDIO_TRACK_SWITCHING, eventObj); - // check if we need to load playlist for this audio Track - var details = audioTrack.details; - if (url && (details === undefined || details.live === true)) { - // track not retrieved yet, or live playlist we need to (re)load it - _logger.logger.log('(re)loading playlist for audioTrack ' + newId); - hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: newId }); - } - } - } - }, { - key: 'updateTrack', - value: function updateTrack(newId) { - // check if level idx is valid - if (newId >= 0 && newId < this.tracks.length) { - // stopping live reloading timer if any - if (this.timer) { - clearInterval(this.timer); - this.timer = null; - } - this.trackId = newId; - _logger.logger.log('updating audioTrack ' + newId); - var audioTrack = this.tracks[newId], - url = audioTrack.url; - // check if we need to load playlist for this audio Track - var details = audioTrack.details; - if (url && (details === undefined || details.live === true)) { - // track not retrieved yet, or live playlist we need to (re)load it - _logger.logger.log('(re)loading playlist for audioTrack ' + newId); - this.hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: newId }); - } - } - } - }, { - key: 'audioTracks', - get: function get() { - return this.tracks; - } - - /** get index of the selected audio track (index in audio track lists) **/ - - }, { - key: 'audioTrack', - get: function get() { - return this.trackId; - } - - /** select an audio track, based on its index in audio track lists**/ - , - set: function set(audioTrackId) { - if (this.trackId !== audioTrackId || this.tracks[audioTrackId].details === undefined) { - this.setAudioTrackInternal(audioTrackId); - } - } - }]); - - return AudioTrackController; -}(_eventHandler2.default); - -exports.default = AudioTrackController; - -},{"34":34,"35":35,"54":54}],8:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _logger = _dereq_(54); - -var _errors = _dereq_(33); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Buffer Controller - */ - -var BufferController = function (_EventHandler) { - _inherits$$1(BufferController, _EventHandler); - - function BufferController(hls) { - _classCallCheck$$1(this, BufferController); - - // the value that we have set mediasource.duration to - // (the actual duration may be tweaked slighly by the browser) - var _this = _possibleConstructorReturn$$1(this, (BufferController.__proto__ || Object.getPrototypeOf(BufferController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_PARSED, _events2.default.BUFFER_RESET, _events2.default.BUFFER_APPENDING, _events2.default.BUFFER_CODECS, _events2.default.BUFFER_EOS, _events2.default.BUFFER_FLUSHING, _events2.default.LEVEL_PTS_UPDATED, _events2.default.LEVEL_UPDATED)); - - _this._msDuration = null; - // the value that we want to set mediaSource.duration to - _this._levelDuration = null; - - // Source Buffer listeners - _this.onsbue = _this.onSBUpdateEnd.bind(_this); - _this.onsbe = _this.onSBUpdateError.bind(_this); - _this.pendingTracks = {}; - _this.tracks = {}; - return _this; - } - - _createClass$$1(BufferController, [{ - key: 'destroy', - value: function destroy() { - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'onLevelPtsUpdated', - value: function onLevelPtsUpdated(data) { - var type = data.type; - var audioTrack = this.tracks.audio; - - // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended) - // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset` - // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue - // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend` - // event if SB is in updating state. - // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486 - - if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { - // Chrome audio mp3 track - var audioBuffer = this.sourceBuffer.audio; - var delta = Math.abs(audioBuffer.timestampOffset - data.start); - - // adjust timestamp offset if time delta is greater than 100ms - if (delta > 0.1) { - var updating = audioBuffer.updating; - - try { - audioBuffer.abort(); - } catch (err) { - updating = true; - _logger.logger.warn('can not abort audio buffer: ' + err); - } - - if (!updating) { - _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start); - audioBuffer.timestampOffset = data.start; - } else { - this.audioTimestampOffset = data.start; - } - } - } - } - }, { - key: 'onManifestParsed', - value: function onManifestParsed(data) { - var audioExpected = data.audio, - videoExpected = data.video, - sourceBufferNb = 0; - // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller - // sourcebuffers will be created all at once when the expected nb of tracks will be reached - // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller - // it will contain the expected nb of source buffers, no need to compute it - if (data.altAudio && (audioExpected || videoExpected)) { - sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0); - _logger.logger.log(sourceBufferNb + ' sourceBuffer(s) expected'); - } - this.sourceBufferNb = sourceBufferNb; - } - }, { - key: 'onMediaAttaching', - value: function onMediaAttaching(data) { - var media = this.media = data.media; - if (media) { - // setup the media source - var ms = this.mediaSource = new MediaSource(); - //Media Source listeners - this.onmso = this.onMediaSourceOpen.bind(this); - this.onmse = this.onMediaSourceEnded.bind(this); - this.onmsc = this.onMediaSourceClose.bind(this); - ms.addEventListener('sourceopen', this.onmso); - ms.addEventListener('sourceended', this.onmse); - ms.addEventListener('sourceclose', this.onmsc); - // link video and media Source - media.src = URL.createObjectURL(ms); - } - } - }, { - key: 'onMediaDetaching', - value: function onMediaDetaching() { - _logger.logger.log('media source detaching'); - var ms = this.mediaSource; - if (ms) { - if (ms.readyState === 'open') { - try { - // endOfStream could trigger exception if any sourcebuffer is in updating state - // we don't really care about checking sourcebuffer state here, - // as we are anyway detaching the MediaSource - // let's just avoid this exception to propagate - ms.endOfStream(); - } catch (err) { - _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream'); - } - } - ms.removeEventListener('sourceopen', this.onmso); - ms.removeEventListener('sourceended', this.onmse); - ms.removeEventListener('sourceclose', this.onmsc); - - // Detach properly the MediaSource from the HTMLMediaElement as - // suggested in https://github.com/w3c/media-source/issues/53. - if (this.media) { - URL.revokeObjectURL(this.media.src); - this.media.removeAttribute('src'); - this.media.load(); - } - - this.mediaSource = null; - this.media = null; - this.pendingTracks = {}; - this.tracks = {}; - this.sourceBuffer = {}; - this.flushRange = []; - this.segments = []; - this.appended = 0; - } - this.onmso = this.onmse = this.onmsc = null; - this.hls.trigger(_events2.default.MEDIA_DETACHED); - } - }, { - key: 'onMediaSourceOpen', - value: function onMediaSourceOpen() { - _logger.logger.log('media source opened'); - this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media }); - var mediaSource = this.mediaSource; - if (mediaSource) { - // once received, don't listen anymore to sourceopen event - mediaSource.removeEventListener('sourceopen', this.onmso); - } - this.checkPendingTracks(); - } - }, { - key: 'checkPendingTracks', - value: function checkPendingTracks() { - // if any buffer codecs pending, check if we have enough to create sourceBuffers - var pendingTracks = this.pendingTracks, - pendingTracksNb = Object.keys(pendingTracks).length; - // if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb) - if (pendingTracksNb && (this.sourceBufferNb <= pendingTracksNb || this.sourceBufferNb === 0)) { - // ok, let's create them now ! - this.createSourceBuffers(pendingTracks); - this.pendingTracks = {}; - // append any pending segments now ! - this.doAppending(); - } - } - }, { - key: 'onMediaSourceClose', - value: function onMediaSourceClose() { - _logger.logger.log('media source closed'); - } - }, { - key: 'onMediaSourceEnded', - value: function onMediaSourceEnded() { - _logger.logger.log('media source ended'); - } - }, { - key: 'onSBUpdateEnd', - value: function onSBUpdateEnd() { - // update timestampOffset - if (this.audioTimestampOffset) { - var audioBuffer = this.sourceBuffer.audio; - _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset); - audioBuffer.timestampOffset = this.audioTimestampOffset; - delete this.audioTimestampOffset; - } - - if (this._needsFlush) { - this.doFlush(); - } - - if (this._needsEos) { - this.checkEos(); - } - this.appending = false; - var parent = this.parent; - // count nb of pending segments waiting for appending on this sourcebuffer - var pending = this.segments.reduce(function (counter, segment) { - return segment.parent === parent ? counter + 1 : counter; - }, 0); - this.hls.trigger(_events2.default.BUFFER_APPENDED, { parent: parent, pending: pending }); - - // don't append in flushing mode - if (!this._needsFlush) { - this.doAppending(); - } - - this.updateMediaElementDuration(); - } - }, { - key: 'onSBUpdateError', - value: function onSBUpdateError(event) { - _logger.logger.error('sourceBuffer error:', event); - // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error - // this error might not always be fatal (it is fatal if decode error is set, in that case - // it will be followed by a mediaElement error ...) - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false }); - // we don't need to do more than that, as accordin to the spec, updateend will be fired just after - } - }, { - key: 'onBufferReset', - value: function onBufferReset() { - var sourceBuffer = this.sourceBuffer; - for (var type in sourceBuffer) { - var sb = sourceBuffer[type]; - try { - this.mediaSource.removeSourceBuffer(sb); - sb.removeEventListener('updateend', this.onsbue); - sb.removeEventListener('error', this.onsbe); - } catch (err) {} - } - this.sourceBuffer = {}; - this.flushRange = []; - this.segments = []; - this.appended = 0; - } - }, { - key: 'onBufferCodecs', - value: function onBufferCodecs(tracks) { - // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks - // if sourcebuffers already created, do nothing ... - if (Object.keys(this.sourceBuffer).length === 0) { - for (var trackName in tracks) { - this.pendingTracks[trackName] = tracks[trackName]; - } - var mediaSource = this.mediaSource; - if (mediaSource && mediaSource.readyState === 'open') { - // try to create sourcebuffers if mediasource opened - this.checkPendingTracks(); - } - } - } - }, { - key: 'createSourceBuffers', - value: function createSourceBuffers(tracks) { - var sourceBuffer = this.sourceBuffer, - mediaSource = this.mediaSource; - - for (var trackName in tracks) { - if (!sourceBuffer[trackName]) { - var track = tracks[trackName]; - // use levelCodec as first priority - var codec = track.levelCodec || track.codec; - var mimeType = track.container + ';codecs=' + codec; - _logger.logger.log('creating sourceBuffer(' + mimeType + ')'); - try { - var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType); - sb.addEventListener('updateend', this.onsbue); - sb.addEventListener('error', this.onsbe); - this.tracks[trackName] = { codec: codec, container: track.container }; - track.buffer = sb; - } catch (err) { - _logger.logger.error('error while trying to add sourceBuffer:' + err.message); - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType }); - } - } - } - this.hls.trigger(_events2.default.BUFFER_CREATED, { tracks: tracks }); - } - }, { - key: 'onBufferAppending', - value: function onBufferAppending(data) { - if (!this._needsFlush) { - if (!this.segments) { - this.segments = [data]; - } else { - this.segments.push(data); - } - this.doAppending(); - } - } - }, { - key: 'onBufferAppendFail', - value: function onBufferAppendFail(data) { - _logger.logger.error('sourceBuffer error:', data.event); - // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error - // this error might not always be fatal (it is fatal if decode error is set, in that case - // it will be followed by a mediaElement error ...) - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false }); - } - - // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos() - - }, { - key: 'onBufferEos', - value: function onBufferEos(data) { - var sb = this.sourceBuffer; - var dataType = data.type; - for (var type in sb) { - if (!dataType || type === dataType) { - if (!sb[type].ended) { - sb[type].ended = true; - _logger.logger.log(type + ' sourceBuffer now EOS'); - } - } - } - this.checkEos(); - } - - // if all source buffers are marked as ended, signal endOfStream() to MediaSource. - - }, { - key: 'checkEos', - value: function checkEos() { - var sb = this.sourceBuffer, - mediaSource = this.mediaSource; - if (!mediaSource || mediaSource.readyState !== 'open') { - this._needsEos = false; - return; - } - for (var type in sb) { - var sbobj = sb[type]; - if (!sbobj.ended) { - return; - } - if (sbobj.updating) { - this._needsEos = true; - return; - } - } - _logger.logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment'); - //Notify the media element that it now has all of the media data - try { - mediaSource.endOfStream(); - } catch (e) { - _logger.logger.warn('exception while calling mediaSource.endOfStream()'); - } - this._needsEos = false; - } - }, { - key: 'onBufferFlushing', - value: function onBufferFlushing(data) { - this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type }); - // attempt flush immediatly - this.flushBufferCounter = 0; - this.doFlush(); - } - }, { - key: 'onLevelUpdated', - value: function onLevelUpdated(event) { - var details = event.details; - if (details.fragments.length === 0) { - return; - } - this._levelDuration = details.totalduration + details.fragments[0].start; - this.updateMediaElementDuration(); - } - - // https://github.com/video-dev/hls.js/issues/355 - - }, { - key: 'updateMediaElementDuration', - value: function updateMediaElementDuration() { - var media = this.media, - mediaSource = this.mediaSource, - sourceBuffer = this.sourceBuffer, - levelDuration = this._levelDuration; - if (levelDuration === null || !media || !mediaSource || !sourceBuffer || media.readyState === 0 || mediaSource.readyState !== 'open') { - return; - } - for (var type in sourceBuffer) { - if (sourceBuffer[type].updating) { - // can't set duration whilst a buffer is updating - return; - } - } - if (this._msDuration === null) { - // initialise to the value that the media source is reporting - this._msDuration = mediaSource.duration; - } - var duration = media.duration; - // levelDuration was the last value we set. - // not using mediaSource.duration as the browser may tweak this value - // only update mediasource duration if its value increase, this is to avoid - // flushing already buffered portion when switching between quality level - if (levelDuration > this._msDuration && levelDuration > duration || duration === Infinity || isNaN(duration)) { - _logger.logger.log('Updating mediasource duration to ' + levelDuration.toFixed(3)); - this._msDuration = mediaSource.duration = levelDuration; - } - } - }, { - key: 'doFlush', - value: function doFlush() { - // loop through all buffer ranges to flush - while (this.flushRange.length) { - var range = this.flushRange[0]; - // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer - if (this.flushBuffer(range.start, range.end, range.type)) { - // range flushed, remove from flush array - this.flushRange.shift(); - this.flushBufferCounter = 0; - } else { - this._needsFlush = true; - // avoid looping, wait for SB update end to retrigger a flush - return; - } - } - if (this.flushRange.length === 0) { - // everything flushed - this._needsFlush = false; - - // let's recompute this.appended, which is used to avoid flush looping - var appended = 0; - var sourceBuffer = this.sourceBuffer; - try { - for (var type in sourceBuffer) { - appended += sourceBuffer[type].buffered.length; - } - } catch (error) { - // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource - // this is harmess at this stage, catch this to avoid reporting an internal exception - _logger.logger.error('error while accessing sourceBuffer.buffered'); - } - this.appended = appended; - this.hls.trigger(_events2.default.BUFFER_FLUSHED); - } - } - }, { - key: 'doAppending', - value: function doAppending() { - var hls = this.hls, - sourceBuffer = this.sourceBuffer, - segments = this.segments; - if (Object.keys(sourceBuffer).length) { - if (this.media.error) { - this.segments = []; - _logger.logger.error('trying to append although a media error occured, flush segment and abort'); - return; - } - if (this.appending) { - //logger.log(`sb appending in progress`); - return; - } - if (segments && segments.length) { - var segment = segments.shift(); - try { - var type = segment.type, - sb = sourceBuffer[type]; - if (sb) { - if (!sb.updating) { - // reset sourceBuffer ended flag before appending segment - sb.ended = false; - //logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`); - this.parent = segment.parent; - sb.appendBuffer(segment.data); - this.appendError = 0; - this.appended++; - this.appending = true; - } else { - segments.unshift(segment); - } - } else { - // in case we don't have any source buffer matching with this segment type, - // it means that Mediasource fails to create sourcebuffer - // discard this segment, and trigger update end - this.onSBUpdateEnd(); - } - } catch (err) { - // in case any error occured while appending, put back segment in segments table - _logger.logger.error('error while trying to append buffer:' + err.message); - segments.unshift(segment); - var event = { type: _errors.ErrorTypes.MEDIA_ERROR, parent: segment.parent }; - if (err.code !== 22) { - if (this.appendError) { - this.appendError++; - } else { - this.appendError = 1; - } - event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR; - /* with UHD content, we could get loop of quota exceeded error until - browser is able to evict some data from sourcebuffer. retrying help recovering this - */ - if (this.appendError > hls.config.appendErrorMaxRetry) { - _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer'); - segments = []; - event.fatal = true; - hls.trigger(_events2.default.ERROR, event); - return; - } else { - event.fatal = false; - hls.trigger(_events2.default.ERROR, event); - } - } else { - // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror - // let's stop appending any segments, and report BUFFER_FULL_ERROR error - this.segments = []; - event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR; - event.fatal = false; - hls.trigger(_events2.default.ERROR, event); - return; - } - } - } - } - } - - /* - flush specified buffered range, - return true once range has been flushed. - as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end - */ - - }, { - key: 'flushBuffer', - value: function flushBuffer(startOffset, endOffset, typeIn) { - var sb, - i, - bufStart, - bufEnd, - flushStart, - flushEnd, - sourceBuffer = this.sourceBuffer; - if (Object.keys(sourceBuffer).length) { - _logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset); - // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments - if (this.flushBufferCounter < this.appended) { - for (var type in sourceBuffer) { - // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one - // if no, let's flush all sourcebuffers - if (typeIn && type !== typeIn) { - continue; - } - sb = sourceBuffer[type]; - // we are going to flush buffer, mark source buffer as 'not ended' - sb.ended = false; - if (!sb.updating) { - try { - for (i = 0; i < sb.buffered.length; i++) { - bufStart = sb.buffered.start(i); - bufEnd = sb.buffered.end(i); - // workaround firefox not able to properly flush multiple buffered range. - if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) { - flushStart = startOffset; - flushEnd = endOffset; - } else { - flushStart = Math.max(bufStart, startOffset); - flushEnd = Math.min(bufEnd, endOffset); - } - /* sometimes sourcebuffer.remove() does not flush - the exact expected time range. - to avoid rounding issues/infinite loop, - only flush buffer range of length greater than 500ms. - */ - if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) { - this.flushBufferCounter++; - _logger.logger.log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime); - sb.remove(flushStart, flushEnd); - return false; - } - } - } catch (e) { - _logger.logger.warn('exception while accessing sourcebuffer, it might have been removed from MediaSource'); - } - } else { - //logger.log('abort ' + type + ' append in progress'); - // this will abort any appending in progress - //sb.abort(); - _logger.logger.warn('cannot flush, sb updating in progress'); - return false; - } - } - } else { - _logger.logger.warn('abort flushing too many retries'); - } - _logger.logger.log('buffer flushed'); - } - // everything flushed ! - return true; - } - }]); - - return BufferController; -}(_eventHandler2.default); - -exports.default = BufferController; - -},{"33":33,"34":34,"35":35,"54":54}],9:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * cap stream level to media size dimension controller - */ - -var CapLevelController = function (_EventHandler) { - _inherits$$1(CapLevelController, _EventHandler); - - function CapLevelController(hls) { - _classCallCheck$$1(this, CapLevelController); - - return _possibleConstructorReturn$$1(this, (CapLevelController.__proto__ || Object.getPrototypeOf(CapLevelController)).call(this, hls, _events2.default.FPS_DROP_LEVEL_CAPPING, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED)); - } - - _createClass$$1(CapLevelController, [{ - key: 'destroy', - value: function destroy() { - if (this.hls.config.capLevelToPlayerSize) { - this.media = this.restrictedLevels = null; - this.autoLevelCapping = Number.POSITIVE_INFINITY; - if (this.timer) { - this.timer = clearInterval(this.timer); - } - } - } - }, { - key: 'onFpsDropLevelCapping', - value: function onFpsDropLevelCapping(data) { - // Don't add a restricted level more than once - if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) { - this.restrictedLevels.push(data.droppedLevel); - } - } - }, { - key: 'onMediaAttaching', - value: function onMediaAttaching(data) { - this.media = data.media instanceof HTMLVideoElement ? data.media : null; - } - }, { - key: 'onManifestParsed', - value: function onManifestParsed(data) { - var hls = this.hls; - this.restrictedLevels = []; - if (hls.config.capLevelToPlayerSize) { - this.autoLevelCapping = Number.POSITIVE_INFINITY; - this.levels = data.levels; - hls.firstLevel = this.getMaxLevel(data.firstLevel); - clearInterval(this.timer); - this.timer = setInterval(this.detectPlayerSize.bind(this), 1000); - this.detectPlayerSize(); - } - } - }, { - key: 'detectPlayerSize', - value: function detectPlayerSize() { - if (this.media) { - var levelsLength = this.levels ? this.levels.length : 0; - if (levelsLength) { - var hls = this.hls; - hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1); - if (hls.autoLevelCapping > this.autoLevelCapping) { - // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch - // usually happen when the user go to the fullscreen mode. - hls.streamController.nextLevelSwitch(); - } - this.autoLevelCapping = hls.autoLevelCapping; - } - } - } - - /* - * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled) - */ - - }, { - key: 'getMaxLevel', - value: function getMaxLevel(capLevelIndex) { - var _this2 = this; - - if (!this.levels) { - return -1; - } - - var validLevels = this.levels.filter(function (level, index) { - return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex; - }); - - return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight); - } - }, { - key: 'mediaWidth', - get: function get() { - var width = void 0; - var media = this.media; - if (media) { - width = media.width || media.clientWidth || media.offsetWidth; - width *= CapLevelController.contentScaleFactor; - } - return width; - } - }, { - key: 'mediaHeight', - get: function get() { - var height = void 0; - var media = this.media; - if (media) { - height = media.height || media.clientHeight || media.offsetHeight; - height *= CapLevelController.contentScaleFactor; - } - return height; - } - }], [{ - key: 'isLevelAllowed', - value: function isLevelAllowed(level) { - var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - - return restrictedLevels.indexOf(level) === -1; - } - }, { - key: 'getMaxLevelByMediaSize', - value: function getMaxLevelByMediaSize(levels, width, height) { - if (!levels || levels && !levels.length) { - return -1; - } - - // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next - // to determine whether we've chosen the greatest bandwidth for the media's dimensions - var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) { - if (!nextLevel) { - return true; - } - return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height; - }; - - // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to - // the max level - var maxLevelIndex = levels.length - 1; - - for (var i = 0; i < levels.length; i += 1) { - var level = levels[i]; - if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) { - maxLevelIndex = i; - break; - } - } - - return maxLevelIndex; - } - }, { - key: 'contentScaleFactor', - get: function get() { - var pixelRatio = 1; - try { - pixelRatio = window.devicePixelRatio; - } catch (e) {} - return pixelRatio; - } - }]); - - return CapLevelController; -}(_eventHandler2.default); - -exports.default = CapLevelController; - -},{"34":34,"35":35}],10:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * FPS Controller - */ - -var FPSController = function (_EventHandler) { - _inherits$$1(FPSController, _EventHandler); - - function FPSController(hls) { - _classCallCheck$$1(this, FPSController); - - return _possibleConstructorReturn$$1(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING)); - } - - _createClass$$1(FPSController, [{ - key: 'destroy', - value: function destroy() { - if (this.timer) { - clearInterval(this.timer); - } - this.isVideoPlaybackQualityAvailable = false; - } - }, { - key: 'onMediaAttaching', - value: function onMediaAttaching(data) { - var config = this.hls.config; - if (config.capLevelOnFPSDrop) { - var video = this.video = data.media instanceof HTMLVideoElement ? data.media : null; - if (typeof video.getVideoPlaybackQuality === 'function') { - this.isVideoPlaybackQualityAvailable = true; - } - clearInterval(this.timer); - this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod); - } - } - }, { - key: 'checkFPS', - value: function checkFPS(video, decodedFrames, droppedFrames) { - var currentTime = performance.now(); - if (decodedFrames) { - if (this.lastTime) { - var currentPeriod = currentTime - this.lastTime, - currentDropped = droppedFrames - this.lastDroppedFrames, - currentDecoded = decodedFrames - this.lastDecodedFrames, - droppedFPS = 1000 * currentDropped / currentPeriod, - hls = this.hls; - hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames }); - if (droppedFPS > 0) { - //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod)); - if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) { - var currentLevel = hls.currentLevel; - _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel); - if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) { - currentLevel = currentLevel - 1; - hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel }); - hls.autoLevelCapping = currentLevel; - hls.streamController.nextLevelSwitch(); - } - } - } - } - this.lastTime = currentTime; - this.lastDroppedFrames = droppedFrames; - this.lastDecodedFrames = decodedFrames; - } - } - }, { - key: 'checkFPSInterval', - value: function checkFPSInterval() { - var video = this.video; - if (video) { - if (this.isVideoPlaybackQualityAvailable) { - var videoPlaybackQuality = video.getVideoPlaybackQuality(); - this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames); - } else { - this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount); - } - } - } - }]); - - return FPSController; -}(_eventHandler2.default); - -exports.default = FPSController; - -},{"34":34,"35":35,"54":54}],11:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _id = _dereq_(27); - -var _id2 = _interopRequireDefault(_id); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * id3 metadata track controller - */ - -var ID3TrackController = function (_EventHandler) { - _inherits$$1(ID3TrackController, _EventHandler); - - function ID3TrackController(hls) { - _classCallCheck$$1(this, ID3TrackController); - - var _this = _possibleConstructorReturn$$1(this, (ID3TrackController.__proto__ || Object.getPrototypeOf(ID3TrackController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_METADATA)); - - _this.id3Track = undefined; - _this.media = undefined; - return _this; - } - - _createClass$$1(ID3TrackController, [{ - key: 'destroy', - value: function destroy() { - _eventHandler2.default.prototype.destroy.call(this); - } - - // Add ID3 metatadata text track. - - }, { - key: 'onMediaAttached', - value: function onMediaAttached(data) { - this.media = data.media; - if (!this.media) { - return; - } - - this.id3Track = this.media.addTextTrack('metadata', 'id3'); - this.id3Track.mode = 'hidden'; - } - }, { - key: 'onMediaDetaching', - value: function onMediaDetaching() { - this.media = undefined; - } - }, { - key: 'onFragParsingMetadata', - value: function onFragParsingMetadata(data) { - var fragment = data.frag; - var samples = data.samples; - - // Attempt to recreate Safari functionality by creating - // WebKitDataCue objects when available and store the decoded - // ID3 data in the value property of the cue - var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue; - - for (var i = 0; i < samples.length; i++) { - var frames = _id2.default.getID3Frames(samples[i].data); - if (frames) { - var startTime = samples[i].pts; - var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS; - - // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE - if (startTime === endTime) { - endTime += 0.0001; - } - - for (var j = 0; j < frames.length; j++) { - var frame = frames[j]; - // Safari doesn't put the timestamp frame in the TextTrack - if (!_id2.default.isTimeStampFrame(frame)) { - var cue = new Cue(startTime, endTime, ''); - cue.value = frame; - this.id3Track.addCue(cue); - } - } - } - } - } - }]); - - return ID3TrackController; -}(_eventHandler2.default); - -exports.default = ID3TrackController; - -},{"27":27,"34":34,"35":35}],12:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _logger = _dereq_(54); - -var _errors = _dereq_(33); - -var _bufferHelper = _dereq_(37); - -var _bufferHelper2 = _interopRequireDefault(_bufferHelper); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Level Controller - */ - -var LevelController = function (_EventHandler) { - _inherits$$1(LevelController, _EventHandler); - - function LevelController(hls) { - _classCallCheck$$1(this, LevelController); - - var _this = _possibleConstructorReturn$$1(this, (LevelController.__proto__ || Object.getPrototypeOf(LevelController)).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.FRAG_LOADED, _events2.default.ERROR)); - - _this.ontick = _this.tick.bind(_this); - _this._manualLevel = -1; - return _this; - } - - _createClass$$1(LevelController, [{ - key: 'destroy', - value: function destroy() { - if (this.timer) { - clearTimeout(this.timer); - this.timer = null; - } - this._manualLevel = -1; - } - }, { - key: 'startLoad', - value: function startLoad() { - this.canload = true; - var levels = this._levels; - // clean up live level details to force reload them, and reset load errors - if (levels) { - levels.forEach(function (level) { - level.loadError = 0; - var levelDetails = level.details; - if (levelDetails && levelDetails.live) { - level.details = undefined; - } - }); - } - // speed up live playlist refresh if timer exists - if (this.timer) { - this.tick(); - } - } - }, { - key: 'stopLoad', - value: function stopLoad() { - this.canload = false; - } - }, { - key: 'onManifestLoaded', - value: function onManifestLoaded(data) { - var levels0 = [], - levels = [], - bitrateStart, - bitrateSet = {}, - videoCodecFound = false, - audioCodecFound = false, - hls = this.hls, - brokenmp4inmp3 = /chrome|firefox/.test(navigator.userAgent.toLowerCase()), - checkSupported = function checkSupported(type, codec) { - return MediaSource.isTypeSupported(type + '/mp4;codecs=' + codec); - }; - - // regroup redundant level together - data.levels.forEach(function (level) { - if (level.videoCodec) { - videoCodecFound = true; - } - // erase audio codec info if browser does not support mp4a.40.34. demuxer will autodetect codec and fallback to mpeg/audio - if (brokenmp4inmp3 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) { - level.audioCodec = undefined; - } - if (level.audioCodec || level.attrs && level.attrs.AUDIO) { - audioCodecFound = true; - } - var redundantLevelId = bitrateSet[level.bitrate]; - if (redundantLevelId === undefined) { - bitrateSet[level.bitrate] = levels0.length; - level.url = [level.url]; - level.urlId = 0; - levels0.push(level); - } else { - levels0[redundantLevelId].url.push(level.url); - } - }); - - // remove audio-only level if we also have levels with audio+video codecs signalled - if (videoCodecFound && audioCodecFound) { - levels0.forEach(function (level) { - if (level.videoCodec) { - levels.push(level); - } - }); - } else { - levels = levels0; - } - // only keep level with supported audio/video codecs - levels = levels.filter(function (level) { - var audioCodec = level.audioCodec, - videoCodec = level.videoCodec; - return (!audioCodec || checkSupported('audio', audioCodec)) && (!videoCodec || checkSupported('video', videoCodec)); - }); - - if (levels.length) { - // start bitrate is the first bitrate of the manifest - bitrateStart = levels[0].bitrate; - // sort level on bitrate - levels.sort(function (a, b) { - return a.bitrate - b.bitrate; - }); - this._levels = levels; - // find index of first level in sorted levels - for (var i = 0; i < levels.length; i++) { - if (levels[i].bitrate === bitrateStart) { - this._firstLevel = i; - _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart); - break; - } - } - hls.trigger(_events2.default.MANIFEST_PARSED, { levels: levels, firstLevel: this._firstLevel, stats: data.stats, audio: audioCodecFound, video: videoCodecFound, altAudio: data.audioTracks.length > 0 }); - } else { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest' }); - } - return; - } - }, { - key: 'setLevelInternal', - value: function setLevelInternal(newLevel) { - var levels = this._levels; - var hls = this.hls; - // check if level idx is valid - if (newLevel >= 0 && newLevel < levels.length) { - // stopping live reloading timer if any - if (this.timer) { - clearTimeout(this.timer); - this.timer = null; - } - if (this._level !== newLevel) { - _logger.logger.log('switching to level ' + newLevel); - this._level = newLevel; - var levelProperties = levels[newLevel]; - levelProperties.level = newLevel; - // LEVEL_SWITCH to be deprecated in next major release - hls.trigger(_events2.default.LEVEL_SWITCH, levelProperties); - hls.trigger(_events2.default.LEVEL_SWITCHING, levelProperties); - } - var level = levels[newLevel], - levelDetails = level.details; - // check if we need to load playlist for this level - if (!levelDetails || levelDetails.live === true) { - // level not retrieved yet, or live playlist we need to (re)load it - var urlId = level.urlId; - hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId }); - } - } else { - // invalid level id given, trigger error - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' }); - } - } - }, { - key: 'onError', - value: function onError(data) { - if (data.fatal) { - return; - } - - var details = data.details, - hls = this.hls, - levelId = void 0, - level = void 0, - levelError = false; - // try to recover not fatal errors - switch (details) { - case _errors.ErrorDetails.FRAG_LOAD_ERROR: - case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT: - case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR: - case _errors.ErrorDetails.KEY_LOAD_ERROR: - case _errors.ErrorDetails.KEY_LOAD_TIMEOUT: - levelId = data.frag.level; - break; - case _errors.ErrorDetails.LEVEL_LOAD_ERROR: - case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT: - levelId = data.context.level; - levelError = true; - break; - case _errors.ErrorDetails.REMUX_ALLOC_ERROR: - levelId = data.level; - break; - default: - break; - } - /* try to switch to a redundant stream if any available. - * if no redundant stream available, emergency switch down (if in auto mode and current level not 0) - * otherwise, we cannot recover this network error ... - */ - if (levelId !== undefined) { - level = this._levels[levelId]; - if (!level.loadError) { - level.loadError = 1; - } else { - level.loadError++; - } - // if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load. - // if level.loadError reaches nbRedundantLevel it means that we tried them all, no hope => let's switch down - var nbRedundantLevel = level.url.length; - if (nbRedundantLevel > 1 && level.loadError < nbRedundantLevel) { - level.urlId = (level.urlId + 1) % nbRedundantLevel; - level.details = undefined; - _logger.logger.warn('level controller,' + details + ' for level ' + levelId + ': switching to redundant stream id ' + level.urlId); - } else { - // we could try to recover if in auto mode and current level not lowest level (0) - var recoverable = this._manualLevel === -1 && levelId; - if (recoverable) { - _logger.logger.warn('level controller,' + details + ': switch-down for next fragment'); - hls.nextAutoLevel = Math.max(0, levelId - 1); - } else if (level && level.details && level.details.live) { - _logger.logger.warn('level controller,' + details + ' on live stream, discard'); - if (levelError) { - // reset this._level so that another call to set level() will retrigger a frag load - this._level = undefined; - } - // other errors are handled by stream controller - } else if (details === _errors.ErrorDetails.LEVEL_LOAD_ERROR || details === _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT) { - var media = hls.media, - - // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end - mediaBuffered = media && _bufferHelper2.default.isBuffered(media, media.currentTime) && _bufferHelper2.default.isBuffered(media, media.currentTime + 0.5); - if (mediaBuffered) { - var retryDelay = hls.config.levelLoadingRetryDelay; - _logger.logger.warn('level controller,' + details + ', but media buffered, retry in ' + retryDelay + 'ms'); - this.timer = setTimeout(this.ontick, retryDelay); - // boolean used to inform stream controller not to switch back to IDLE on non fatal error - data.levelRetry = true; - } else { - _logger.logger.error('cannot recover ' + details + ' error'); - this._level = undefined; - // stopping live reloading timer if any - if (this.timer) { - clearTimeout(this.timer); - this.timer = null; - } - // switch error to fatal - data.fatal = true; - } - } - } - } - } - - // reset level load error counter on successful frag loaded - - }, { - key: 'onFragLoaded', - value: function onFragLoaded(data) { - var fragLoaded = data.frag; - if (fragLoaded && fragLoaded.type === 'main') { - var level = this._levels[fragLoaded.level]; - if (level) { - level.loadError = 0; - } - } - } - }, { - key: 'onLevelLoaded', - value: function onLevelLoaded(data) { - var levelId = data.level; - // only process level loaded events matching with expected level - if (levelId === this._level) { - var curLevel = this._levels[levelId]; - // reset level load error counter on successful level loaded - curLevel.loadError = 0; - var newDetails = data.details; - // if current playlist is a live playlist, arm a timer to reload it - if (newDetails.live) { - var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration), - curDetails = curLevel.details; - if (curDetails && newDetails.endSN === curDetails.endSN) { - // follow HLS Spec, If the client reloads a Playlist file and finds that it has not - // changed then it MUST wait for a period of one-half the target - // duration before retrying. - reloadInterval /= 2; - _logger.logger.log('same live playlist, reload twice faster'); - } - // decrement reloadInterval with level loading delay - reloadInterval -= performance.now() - data.stats.trequest; - // in any case, don't reload more than every second - reloadInterval = Math.max(1000, Math.round(reloadInterval)); - _logger.logger.log('live playlist, reload in ' + reloadInterval + ' ms'); - this.timer = setTimeout(this.ontick, reloadInterval); - } else { - this.timer = null; - } - } - } - }, { - key: 'tick', - value: function tick() { - var levelId = this._level; - if (levelId !== undefined && this.canload) { - var level = this._levels[levelId]; - if (level && level.url) { - var urlId = level.urlId; - this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId }); - } - } - } - }, { - key: 'levels', - get: function get() { - return this._levels; - } - }, { - key: 'level', - get: function get() { - return this._level; - }, - set: function set(newLevel) { - var levels = this._levels; - if (levels && levels.length > newLevel) { - if (this._level !== newLevel || levels[newLevel].details === undefined) { - this.setLevelInternal(newLevel); - } - } - } - }, { - key: 'manualLevel', - get: function get() { - return this._manualLevel; - }, - set: function set(newLevel) { - this._manualLevel = newLevel; - if (this._startLevel === undefined) { - this._startLevel = newLevel; - } - if (newLevel !== -1) { - this.level = newLevel; - } - } - }, { - key: 'firstLevel', - get: function get() { - return this._firstLevel; - }, - set: function set(newLevel) { - this._firstLevel = newLevel; - } - }, { - key: 'startLevel', - get: function get() { - // hls.startLevel takes precedence over config.startLevel - // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest) - if (this._startLevel === undefined) { - var configStartLevel = this.hls.config.startLevel; - if (configStartLevel !== undefined) { - return configStartLevel; - } else { - return this._firstLevel; - } - } else { - return this._startLevel; - } - }, - set: function set(newLevel) { - this._startLevel = newLevel; - } - }, { - key: 'nextLoadLevel', - get: function get() { - if (this._manualLevel !== -1) { - return this._manualLevel; - } else { - return this.hls.nextAutoLevel; - } - }, - set: function set(nextLevel) { - this.level = nextLevel; - if (this._manualLevel === -1) { - this.hls.nextAutoLevel = nextLevel; - } - } - }]); - - return LevelController; -}(_eventHandler2.default); - -exports.default = LevelController; - -},{"33":33,"34":34,"35":35,"37":37,"54":54}],13:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _binarySearch = _dereq_(48); - -var _binarySearch2 = _interopRequireDefault(_binarySearch); - -var _bufferHelper = _dereq_(37); - -var _bufferHelper2 = _interopRequireDefault(_bufferHelper); - -var _demuxer = _dereq_(25); - -var _demuxer2 = _interopRequireDefault(_demuxer); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _levelHelper = _dereq_(38); - -var _levelHelper2 = _interopRequireDefault(_levelHelper); - -var _timeRanges = _dereq_(55); - -var _timeRanges2 = _interopRequireDefault(_timeRanges); - -var _errors = _dereq_(33); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Stream Controller - */ - -var State = { - STOPPED: 'STOPPED', - IDLE: 'IDLE', - KEY_LOADING: 'KEY_LOADING', - FRAG_LOADING: 'FRAG_LOADING', - FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', - WAITING_LEVEL: 'WAITING_LEVEL', - PARSING: 'PARSING', - PARSED: 'PARSED', - BUFFER_FLUSHING: 'BUFFER_FLUSHING', - ENDED: 'ENDED', - ERROR: 'ERROR' -}; - -var StreamController = function (_EventHandler) { - _inherits$$1(StreamController, _EventHandler); - - function StreamController(hls) { - _classCallCheck$$1(this, StreamController); - - var _this = _possibleConstructorReturn$$1(this, (StreamController.__proto__ || Object.getPrototypeOf(StreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.LEVEL_LOADED, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_LOAD_EMERGENCY_ABORTED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.ERROR, _events2.default.AUDIO_TRACK_SWITCHING, _events2.default.AUDIO_TRACK_SWITCHED, _events2.default.BUFFER_CREATED, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED)); - - _this.config = hls.config; - _this.audioCodecSwap = false; - _this.ticks = 0; - _this._state = State.STOPPED; - _this.ontick = _this.tick.bind(_this); - return _this; - } - - _createClass$$1(StreamController, [{ - key: 'destroy', - value: function destroy() { - this.stopLoad(); - if (this.timer) { - clearInterval(this.timer); - this.timer = null; - } - _eventHandler2.default.prototype.destroy.call(this); - this.state = State.STOPPED; - } - }, { - key: 'startLoad', - value: function startLoad(startPosition) { - if (this.levels) { - var lastCurrentTime = this.lastCurrentTime, - hls = this.hls; - this.stopLoad(); - if (!this.timer) { - this.timer = setInterval(this.ontick, 100); - } - this.level = -1; - this.fragLoadError = 0; - if (!this.startFragRequested) { - // determine load level - var startLevel = hls.startLevel; - if (startLevel === -1) { - // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level - startLevel = 0; - this.bitrateTest = true; - } - // set new level to playlist loader : this will trigger start level load - // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded - this.level = hls.nextLoadLevel = startLevel; - this.loadedmetadata = false; - } - // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime - if (lastCurrentTime > 0 && startPosition === -1) { - _logger.logger.log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3)); - startPosition = lastCurrentTime; - } - this.state = State.IDLE; - this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; - this.tick(); - } else { - this.forceStartLoad = true; - this.state = State.STOPPED; - } - } - }, { - key: 'stopLoad', - value: function stopLoad() { - var frag = this.fragCurrent; - if (frag) { - if (frag.loader) { - frag.loader.abort(); - } - this.fragCurrent = null; - } - this.fragPrevious = null; - if (this.demuxer) { - this.demuxer.destroy(); - this.demuxer = null; - } - this.state = State.STOPPED; - this.forceStartLoad = false; - } - }, { - key: 'tick', - value: function tick() { - this.ticks++; - if (this.ticks === 1) { - this.doTick(); - if (this.ticks > 1) { - setTimeout(this.tick, 1); - } - this.ticks = 0; - } - } - }, { - key: 'doTick', - value: function doTick() { - switch (this.state) { - case State.ERROR: - //don't do anything in error state to avoid breaking further ... - break; - case State.BUFFER_FLUSHING: - // in buffer flushing state, reset fragLoadError counter - this.fragLoadError = 0; - break; - case State.IDLE: - this._doTickIdle(); - break; - case State.WAITING_LEVEL: - var level = this.levels[this.level]; - // check if playlist is already loaded - if (level && level.details) { - this.state = State.IDLE; - } - break; - case State.FRAG_LOADING_WAITING_RETRY: - var now = performance.now(); - var retryDate = this.retryDate; - // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading - if (!retryDate || now >= retryDate || this.media && this.media.seeking) { - _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state'); - this.state = State.IDLE; - } - break; - case State.ERROR: - case State.STOPPED: - case State.FRAG_LOADING: - case State.PARSING: - case State.PARSED: - case State.ENDED: - break; - default: - break; - } - // check buffer - this._checkBuffer(); - // check/update current fragment - this._checkFragmentChanged(); - } - - // Ironically the "idle" state is the on we do the most logic in it seems .... - // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently - // played segment, or on pause/play/seek instead of naively checking every 100ms? - - }, { - key: '_doTickIdle', - value: function _doTickIdle() { - var hls = this.hls, - config = hls.config, - media = this.media; - - // if video not attached AND - // start fragment already requested OR start frag prefetch disable - // exit loop - // => if start level loaded and media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop - if (this.levelLastLoaded !== undefined && !media && (this.startFragRequested || !config.startFragPrefetch)) { - return; - } - - // if we have not yet loaded any fragment, start loading from start position - var pos = void 0; - if (this.loadedmetadata) { - pos = media.currentTime; - } else { - pos = this.nextLoadPosition; - } - // determine next load level - var level = hls.nextLoadLevel, - levelInfo = this.levels[level]; - - if (!levelInfo) { - return; - } - - var levelBitrate = levelInfo.bitrate, - maxBufLen = void 0; - - // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s - if (levelBitrate) { - maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength); - } else { - maxBufLen = config.maxBufferLength; - } - maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); - - // determine next candidate fragment to be loaded, based on current position and end of buffer position - // ensure up to `config.maxMaxBufferLength` of buffer upfront - - var bufferInfo = _bufferHelper2.default.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole), - bufferLen = bufferInfo.len; - // Stay idle if we are still with buffer margins - if (bufferLen >= maxBufLen) { - return; - } - - // if buffer length is less than maxBufLen try to load a new fragment ... - _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...'); - - // set next load level : this will trigger a playlist load if needed - this.level = hls.nextLoadLevel = level; - - var levelDetails = levelInfo.details; - // if level info not retrieved yet, switch state and wait for level retrieval - // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load - // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist) - if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) { - this.state = State.WAITING_LEVEL; - return; - } - - // we just got done loading the final fragment, and currentPos is buffered, and there is no other buffered range after ... - // rationale is that in case there are any buffered rangesafter, it means that there are unbuffered portion in between - // so we should not switch to ENDED in that case, to be able to buffer themx - var fragPrevious = this.fragPrevious; - if (!levelDetails.live && fragPrevious && fragPrevious.sn === levelDetails.endSN && bufferLen && !bufferInfo.nextStart) { - // fragPrevious is last fragment. retrieve level duration using last frag start offset + duration - // real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling - var duration = Math.min(media.duration, fragPrevious.start + fragPrevious.duration); - // if everything (almost) til the end is buffered, let's signal eos - // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference (audio/video offsets...) - // tolerate up to one frag duration to cope with these cases. - // also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657 - if (duration - Math.max(bufferInfo.end, fragPrevious.start) <= Math.max(0.2, fragPrevious.duration)) { - // Finalize the media stream - var data = {}; - if (this.altAudio) { - data.type = 'video'; - } - this.hls.trigger(_events2.default.BUFFER_EOS, data); - this.state = State.ENDED; - return; - } - } - - // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..) - this._fetchPayloadOrEos(pos, bufferInfo, levelDetails); - } - }, { - key: '_fetchPayloadOrEos', - value: function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) { - var fragPrevious = this.fragPrevious, - level = this.level, - fragments = levelDetails.fragments, - fragLen = fragments.length; - - // empty playlist - if (fragLen === 0) { - return; - } - - // find fragment index, contiguous with end of buffer position - var start = fragments[0].start, - end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, - bufferEnd = bufferInfo.end, - frag = void 0; - - if (levelDetails.initSegment && !levelDetails.initSegment.data) { - frag = levelDetails.initSegment; - } else { - // in case of live playlist we need to ensure that requested position is not located before playlist start - if (levelDetails.live) { - var initialLiveManifestSize = this.config.initialLiveManifestSize; - if (fragLen < initialLiveManifestSize) { - _logger.logger.warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize); - return; - } - - frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen); - // if it explicitely returns null don't load any fragment and exit function now - if (frag === null) { - return; - } - } else { - // VoD playlist: if bufferEnd before start of playlist, load first fragment - if (bufferEnd < start) { - frag = fragments[0]; - } - } - } - if (!frag) { - frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails); - } - if (frag) { - this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd); - } - return; - } - }, { - key: '_ensureFragmentAtLivePoint', - value: function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) { - var config = this.hls.config, - media = this.media; - - var frag = void 0; - - // check if requested position is within seekable boundaries : - //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`); - var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration; - - if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) { - var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails); - _logger.logger.log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3)); - bufferEnd = liveSyncPosition; - if (media && media.readyState && media.duration > liveSyncPosition) { - media.currentTime = liveSyncPosition; - } - this.nextLoadPosition = liveSyncPosition; - } - - // if end of buffer greater than live edge, don't load any fragment - // this could happen if live playlist intermittently slides in the past. - // level 1 loaded [182580161,182580167] - // level 1 loaded [182580162,182580169] - // Loading 182580168 of [182580162 ,182580169],level 1 .. - // Loading 182580169 of [182580162 ,182580169],level 1 .. - // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168 - // level 1 loaded [182580164,182580171] - // - // don't return null in case media not loaded yet (readystate === 0) - if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) { - return null; - } - - if (this.startFragRequested && !levelDetails.PTSKnown) { - /* we are switching level on live playlist, but we don't have any PTS info for that quality level ... - try to load frag matching with next SN. - even if SN are not synchronized between playlists, loading this frag will help us - compute playlist sliding and find the right one after in case it was not the right consecutive one */ - if (fragPrevious) { - var targetSN = fragPrevious.sn + 1; - if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) { - frag = fragments[targetSN - levelDetails.startSN]; - _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn); - } - } - if (!frag) { - /* we have no idea about which fragment should be loaded. - so let's load mid fragment. it will help computing playlist sliding and find the right one - */ - frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))]; - _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn); - } - } - return frag; - } - }, { - key: '_findFragment', - value: function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) { - var config = this.hls.config; - var frag = void 0; - var foundFrag = void 0; - var maxFragLookUpTolerance = config.maxFragLookUpTolerance; - var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined; - var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) { - // offset should be within fragment boundary - config.maxFragLookUpTolerance - // this is to cope with situations like - // bufferEnd = 9.991 - // frag[Ø] : [0,10] - // frag[1] : [10,20] - // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here - // frag start frag start+duration - // |-----------------------------| - // <---> <---> - // ...--------><-----------------------------><---------.... - // previous frag matching fragment next frag - // return -1 return 0 return 1 - //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); - // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments - var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration); - if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { - return 1; - } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element - else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { - return -1; - } - return 0; - }; - - if (bufferEnd < end) { - if (bufferEnd > end - maxFragLookUpTolerance) { - maxFragLookUpTolerance = 0; - } - // Prefer the next fragment if it's within tolerance - if (fragNext && !fragmentWithinToleranceTest(fragNext)) { - foundFrag = fragNext; - } else { - foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest); - } - } else { - // reach end of playlist - foundFrag = fragments[fragLen - 1]; - } - if (foundFrag) { - frag = foundFrag; - var curSNIdx = frag.sn - levelDetails.startSN; - var sameLevel = fragPrevious && frag.level === fragPrevious.level; - var prevFrag = fragments[curSNIdx - 1]; - var nextFrag = fragments[curSNIdx + 1]; - //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn); - if (fragPrevious && frag.sn === fragPrevious.sn) { - if (sameLevel && !frag.backtracked) { - if (frag.sn < levelDetails.endSN) { - var deltaPTS = fragPrevious.deltaPTS; - // if there is a significant delta between audio and video, larger than max allowed hole, - // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped) - // let's try to load previous fragment again to get last keyframe - // then we will reload again current fragment (that way we should be able to fill the buffer hole ...) - if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) { - frag = prevFrag; - _logger.logger.warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this'); - // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded - fragPrevious.loadCounter--; - } else { - frag = nextFrag; - _logger.logger.log('SN just loaded, load next one: ' + frag.sn); - } - } else { - frag = null; - } - } else if (frag.backtracked) { - // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes - if (nextFrag && nextFrag.backtracked) { - _logger.logger.warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn); - frag = nextFrag; - } else { - // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe - // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment - _logger.logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe'); - frag.dropped = 0; - if (prevFrag) { - if (prevFrag.loadCounter) { - prevFrag.loadCounter--; - } - frag = prevFrag; - frag.backtracked = true; - } else if (curSNIdx) { - // can't backtrack on very first fragment - frag = null; - } - } - } - } - } - return frag; - } - }, { - key: '_loadFragmentOrKey', - value: function _loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd) { - var hls = this.hls, - config = hls.config; - - //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3)); - if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) { - _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level); - this.state = State.KEY_LOADING; - hls.trigger(_events2.default.KEY_LOADING, { frag: frag }); - } else { - _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3)); - // ensure that we are not reloading the same fragments in loop ... - if (this.fragLoadIdx !== undefined) { - this.fragLoadIdx++; - } else { - this.fragLoadIdx = 0; - } - if (frag.loadCounter) { - frag.loadCounter++; - var maxThreshold = config.fragLoadingLoopThreshold; - // if this frag has already been loaded 3 times, and if it has been reloaded recently - if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag }); - return; - } - } else { - frag.loadCounter = 1; - } - frag.loadIdx = this.fragLoadIdx; - this.fragCurrent = frag; - this.startFragRequested = true; - if (!isNaN(frag.sn)) { - this.nextLoadPosition = frag.start + frag.duration; - } - frag.autoLevel = hls.autoLevelEnabled; - frag.bitrateTest = this.bitrateTest; - hls.trigger(_events2.default.FRAG_LOADING, { frag: frag }); - // lazy demuxer init, as this could take some time ... do it during frag loading - if (!this.demuxer) { - this.demuxer = new _demuxer2.default(hls, 'main'); - } - this.state = State.FRAG_LOADING; - return; - } - } - }, { - key: 'getBufferedFrag', - value: function getBufferedFrag(position) { - return _binarySearch2.default.search(this._bufferedFrags, function (frag) { - if (position < frag.startPTS) { - return -1; - } else if (position > frag.endPTS) { - return 1; - } - return 0; - }); - } - }, { - key: 'followingBufferedFrag', - value: function followingBufferedFrag(frag) { - if (frag) { - // try to get range of next fragment (500ms after this range) - return this.getBufferedFrag(frag.endPTS + 0.5); - } - return null; - } - }, { - key: '_checkFragmentChanged', - value: function _checkFragmentChanged() { - var fragPlayingCurrent, - currentTime, - video = this.media; - if (video && video.readyState && video.seeking === false) { - currentTime = video.currentTime; - /* if video element is in seeked state, currentTime can only increase. - (assuming that playback rate is positive ...) - As sometimes currentTime jumps back to zero after a - media decode error, check this, to avoid seeking back to - wrong position after a media decode error - */ - if (currentTime > video.playbackRate * this.lastCurrentTime) { - this.lastCurrentTime = currentTime; - } - if (_bufferHelper2.default.isBuffered(video, currentTime)) { - fragPlayingCurrent = this.getBufferedFrag(currentTime); - } else if (_bufferHelper2.default.isBuffered(video, currentTime + 0.1)) { - /* ensure that FRAG_CHANGED event is triggered at startup, - when first video frame is displayed and playback is paused. - add a tolerance of 100ms, in case current position is not buffered, - check if current pos+100ms is buffered and use that buffer range - for FRAG_CHANGED event reporting */ - fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1); - } - if (fragPlayingCurrent) { - var fragPlaying = fragPlayingCurrent; - if (fragPlaying !== this.fragPlaying) { - this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying }); - var fragPlayingLevel = fragPlaying.level; - if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) { - this.hls.trigger(_events2.default.LEVEL_SWITCHED, { level: fragPlayingLevel }); - } - this.fragPlaying = fragPlaying; - } - } - } - } - - /* - on immediate level switch : - - pause playback if playing - - cancel any pending load request - - and trigger a buffer flush - */ - - }, { - key: 'immediateLevelSwitch', - value: function immediateLevelSwitch() { - _logger.logger.log('immediateLevelSwitch'); - if (!this.immediateSwitch) { - this.immediateSwitch = true; - var media = this.media, - previouslyPaused = void 0; - if (media) { - previouslyPaused = media.paused; - media.pause(); - } else { - // don't restart playback after instant level switch in case media not attached - previouslyPaused = true; - } - this.previouslyPaused = previouslyPaused; - } - var fragCurrent = this.fragCurrent; - if (fragCurrent && fragCurrent.loader) { - fragCurrent.loader.abort(); - } - this.fragCurrent = null; - // increase fragment load Index to avoid frag loop loading error after buffer flush - this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; - // flush everything - this.flushMainBuffer(0, Number.POSITIVE_INFINITY); - } - - /* - on immediate level switch end, after new fragment has been buffered : - - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered) - - resume the playback if needed - */ - - }, { - key: 'immediateLevelSwitchEnd', - value: function immediateLevelSwitchEnd() { - var media = this.media; - if (media && media.buffered.length) { - this.immediateSwitch = false; - if (_bufferHelper2.default.isBuffered(media, media.currentTime)) { - // only nudge if currentTime is buffered - media.currentTime -= 0.0001; - } - if (!this.previouslyPaused) { - media.play(); - } - } - } - }, { - key: 'nextLevelSwitch', - value: function nextLevelSwitch() { - /* try to switch ASAP without breaking video playback : - in order to ensure smooth but quick level switching, - we need to find the next flushable buffer range - we should take into account new segment fetch time - */ - var media = this.media; - // ensure that media is defined and that metadata are available (to retrieve currentTime) - if (media && media.readyState) { - var fetchdelay = void 0, - fragPlayingCurrent = void 0, - nextBufferedFrag = void 0; - // increase fragment load Index to avoid frag loop loading error after buffer flush - this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; - fragPlayingCurrent = this.getBufferedFrag(media.currentTime); - if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) { - // flush buffer preceding current fragment (flush until current fragment start offset) - // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ... - this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1); - } - if (!media.paused) { - // add a safety delay of 1s - var nextLevelId = this.hls.nextLoadLevel, - nextLevel = this.levels[nextLevelId], - fragLastKbps = this.fragLastKbps; - if (fragLastKbps && this.fragCurrent) { - fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1; - } else { - fetchdelay = 0; - } - } else { - fetchdelay = 0; - } - //logger.log('fetchdelay:'+fetchdelay); - // find buffer range that will be reached once new fragment will be fetched - nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay); - if (nextBufferedFrag) { - // we can flush buffer range following this one without stalling playback - nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag); - if (nextBufferedFrag) { - // if we are here, we can also cancel any loading/demuxing in progress, as they are useless - var fragCurrent = this.fragCurrent; - if (fragCurrent && fragCurrent.loader) { - fragCurrent.loader.abort(); - } - this.fragCurrent = null; - // start flush position is the start PTS of next buffered frag. - // we use frag.naxStartPTS which is max(audio startPTS, video startPTS). - // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment - this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY); - } - } - } - } - }, { - key: 'flushMainBuffer', - value: function flushMainBuffer(startOffset, endOffset) { - this.state = State.BUFFER_FLUSHING; - var flushScope = { startOffset: startOffset, endOffset: endOffset }; - // if alternate audio tracks are used, only flush video, otherwise flush everything - if (this.altAudio) { - flushScope.type = 'video'; - } - this.hls.trigger(_events2.default.BUFFER_FLUSHING, flushScope); - } - }, { - key: 'onMediaAttached', - value: function onMediaAttached(data) { - var media = this.media = this.mediaBuffer = data.media; - this.onvseeking = this.onMediaSeeking.bind(this); - this.onvseeked = this.onMediaSeeked.bind(this); - this.onvended = this.onMediaEnded.bind(this); - media.addEventListener('seeking', this.onvseeking); - media.addEventListener('seeked', this.onvseeked); - media.addEventListener('ended', this.onvended); - var config = this.config; - if (this.levels && config.autoStartLoad) { - this.hls.startLoad(config.startPosition); - } - } - }, { - key: 'onMediaDetaching', - value: function onMediaDetaching() { - var media = this.media; - if (media && media.ended) { - _logger.logger.log('MSE detaching and video ended, reset startPosition'); - this.startPosition = this.lastCurrentTime = 0; - } - - // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery - var levels = this.levels; - if (levels) { - // reset fragment load counter - levels.forEach(function (level) { - if (level.details) { - level.details.fragments.forEach(function (fragment) { - fragment.loadCounter = undefined; - fragment.backtracked = undefined; - }); - } - }); - } - // remove video listeners - if (media) { - media.removeEventListener('seeking', this.onvseeking); - media.removeEventListener('seeked', this.onvseeked); - media.removeEventListener('ended', this.onvended); - this.onvseeking = this.onvseeked = this.onvended = null; - } - this.media = this.mediaBuffer = null; - this.loadedmetadata = false; - this.stopLoad(); - } - }, { - key: 'onMediaSeeking', - value: function onMediaSeeking() { - var media = this.media, - currentTime = media ? media.currentTime : undefined, - config = this.config; - if (!isNaN(currentTime)) { - _logger.logger.log('media seeking to ' + currentTime.toFixed(3)); - } - var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media; - var bufferInfo = _bufferHelper2.default.bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole); - if (this.state === State.FRAG_LOADING) { - var fragCurrent = this.fragCurrent; - // check if we are seeking to a unbuffered area AND if frag loading is in progress - if (bufferInfo.len === 0 && fragCurrent) { - var tolerance = config.maxFragLookUpTolerance, - fragStartOffset = fragCurrent.start - tolerance, - fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; - // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything - if (currentTime < fragStartOffset || currentTime > fragEndOffset) { - if (fragCurrent.loader) { - _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load'); - fragCurrent.loader.abort(); - } - this.fragCurrent = null; - this.fragPrevious = null; - // switch to IDLE state to load new fragment - this.state = State.IDLE; - } else { - _logger.logger.log('seeking outside of buffer but within currently loaded fragment range'); - } - } - } else if (this.state === State.ENDED) { - // if seeking to unbuffered area, clean up fragPrevious - if (bufferInfo.len === 0) { - this.fragPrevious = 0; - } - // switch to IDLE state to check for potential new fragment - this.state = State.IDLE; - } - if (media) { - this.lastCurrentTime = currentTime; - } - // avoid reporting fragment loop loading error in case user is seeking several times on same position - if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) { - this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold; - } - // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target - if (!this.loadedmetadata) { - this.nextLoadPosition = this.startPosition = currentTime; - } - // tick to speed up processing - this.tick(); - } - }, { - key: 'onMediaSeeked', - value: function onMediaSeeked() { - var media = this.media, - currentTime = media ? media.currentTime : undefined; - if (!isNaN(currentTime)) { - _logger.logger.log('media seeked to ' + currentTime.toFixed(3)); - } - // tick to speed up FRAGMENT_PLAYING triggering - this.tick(); - } - }, { - key: 'onMediaEnded', - value: function onMediaEnded() { - _logger.logger.log('media ended'); - // reset startPosition and lastCurrentTime to restart playback @ stream beginning - this.startPosition = this.lastCurrentTime = 0; - } - }, { - key: 'onManifestLoading', - value: function onManifestLoading() { - // reset buffer on manifest loading - _logger.logger.log('trigger BUFFER_RESET'); - this.hls.trigger(_events2.default.BUFFER_RESET); - this._bufferedFrags = []; - this.stalled = false; - this.startPosition = this.lastCurrentTime = 0; - } - }, { - key: 'onManifestParsed', - value: function onManifestParsed(data) { - var aac = false, - heaac = false, - codec; - data.levels.forEach(function (level) { - // detect if we have different kind of audio codecs used amongst playlists - codec = level.audioCodec; - if (codec) { - if (codec.indexOf('mp4a.40.2') !== -1) { - aac = true; - } - if (codec.indexOf('mp4a.40.5') !== -1) { - heaac = true; - } - } - }); - this.audioCodecSwitch = aac && heaac; - if (this.audioCodecSwitch) { - _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'); - } - this.levels = data.levels; - this.startLevelLoaded = false; - this.startFragRequested = false; - var config = this.config; - if (config.autoStartLoad || this.forceStartLoad) { - this.hls.startLoad(config.startPosition); - } - } - }, { - key: 'onLevelLoaded', - value: function onLevelLoaded(data) { - var newDetails = data.details, - newLevelId = data.level, - curLevel = this.levels[newLevelId], - duration = newDetails.totalduration, - sliding = 0; - - _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration); - this.levelLastLoaded = newLevelId; - - if (newDetails.live) { - var curDetails = curLevel.details; - if (curDetails && newDetails.fragments.length > 0) { - // we already have details for that level, merge them - _levelHelper2.default.mergeDetails(curDetails, newDetails); - sliding = newDetails.fragments[0].start; - this.liveSyncPosition = this.computeLivePosition(sliding, curDetails); - if (newDetails.PTSKnown) { - _logger.logger.log('live playlist sliding:' + sliding.toFixed(3)); - } else { - _logger.logger.log('live playlist - outdated PTS, unknown sliding'); - } - } else { - newDetails.PTSKnown = false; - _logger.logger.log('live playlist - first load, unknown sliding'); - } - } else { - newDetails.PTSKnown = false; - } - // override level info - curLevel.details = newDetails; - this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId }); - - if (this.startFragRequested === false) { - // compute start position if set to -1. use it straight away if value is defined - if (this.startPosition === -1 || this.lastCurrentTime === -1) { - // first, check if start time offset has been set in playlist, if yes, use this value - var startTimeOffset = newDetails.startTimeOffset; - if (!isNaN(startTimeOffset)) { - if (startTimeOffset < 0) { - _logger.logger.log('negative start time offset ' + startTimeOffset + ', count from end of last fragment'); - startTimeOffset = sliding + duration + startTimeOffset; - } - _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset); - this.startPosition = startTimeOffset; - } else { - // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3) - if (newDetails.live) { - this.startPosition = this.computeLivePosition(sliding, newDetails); - _logger.logger.log('configure startPosition to ' + this.startPosition); - } else { - this.startPosition = 0; - } - } - this.lastCurrentTime = this.startPosition; - } - this.nextLoadPosition = this.startPosition; - } - // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment - if (this.state === State.WAITING_LEVEL) { - this.state = State.IDLE; - } - //trigger handler right now - this.tick(); - } - }, { - key: 'onKeyLoaded', - value: function onKeyLoaded() { - if (this.state === State.KEY_LOADING) { - this.state = State.IDLE; - this.tick(); - } - } - }, { - key: 'onFragLoaded', - value: function onFragLoaded(data) { - var fragCurrent = this.fragCurrent, - fragLoaded = data.frag; - if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) { - var stats = data.stats, - currentLevel = this.levels[fragCurrent.level], - details = currentLevel.details; - _logger.logger.log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level); - // reset frag bitrate test in any case after frag loaded event - this.bitrateTest = false; - this.stats = stats; - // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0 - // then this means that we should be able to load a fragment at a higher quality level - if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) { - // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo - this.state = State.IDLE; - this.startFragRequested = false; - stats.tparsed = stats.tbuffered = performance.now(); - this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' }); - this.tick(); - } else if (fragLoaded.sn === 'initSegment') { - this.state = State.IDLE; - stats.tparsed = stats.tbuffered = performance.now(); - details.initSegment.data = data.payload; - this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' }); - this.tick(); - } else { - this.state = State.PARSING; - // transmux the MPEG-TS data to ISO-BMFF segments - var duration = details.totalduration, - level = fragCurrent.level, - sn = fragCurrent.sn, - audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec; - if (this.audioCodecSwap) { - _logger.logger.log('swapping playlist audio codec'); - if (audioCodec === undefined) { - audioCodec = this.lastAudioCodec; - } - if (audioCodec) { - if (audioCodec.indexOf('mp4a.40.5') !== -1) { - audioCodec = 'mp4a.40.2'; - } else { - audioCodec = 'mp4a.40.5'; - } - } - } - this.pendingBuffering = true; - this.appended = false; - _logger.logger.log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc); - var demuxer = this.demuxer; - if (!demuxer) { - demuxer = this.demuxer = new _demuxer2.default(this.hls, 'main'); - } - // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments) - var media = this.media; - var mediaSeeking = media && media.seeking; - var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live); - var initSegmentData = details.initSegment ? details.initSegment.data : []; - demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset, undefined); - } - } - this.fragLoadError = 0; - } - }, { - key: 'onFragParsingInitSegment', - value: function onFragParsingInitSegment(data) { - var fragCurrent = this.fragCurrent; - var fragNew = data.frag; - if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { - var tracks = data.tracks, - trackName, - track; - - // if audio track is expected to come from audio stream controller, discard any coming from main - if (tracks.audio && this.altAudio) { - delete tracks.audio; - } - // include levelCodec in audio and video tracks - track = tracks.audio; - if (track) { - var audioCodec = this.levels[this.level].audioCodec, - ua = navigator.userAgent.toLowerCase(); - if (audioCodec && this.audioCodecSwap) { - _logger.logger.log('swapping playlist audio codec'); - if (audioCodec.indexOf('mp4a.40.5') !== -1) { - audioCodec = 'mp4a.40.2'; - } else { - audioCodec = 'mp4a.40.5'; - } - } - // in case AAC and HE-AAC audio codecs are signalled in manifest - // force HE-AAC , as it seems that most browsers prefers that way, - // except for mono streams OR on FF - // these conditions might need to be reviewed ... - if (this.audioCodecSwitch) { - // don't force HE-AAC if mono stream - if (track.metadata.channelCount !== 1 && - // don't force HE-AAC if firefox - ua.indexOf('firefox') === -1) { - audioCodec = 'mp4a.40.5'; - } - } - // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise - if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { - // Exclude mpeg audio - audioCodec = 'mp4a.40.2'; - _logger.logger.log('Android: force audio codec to ' + audioCodec); - } - track.levelCodec = audioCodec; - track.id = data.id; - } - track = tracks.video; - if (track) { - track.levelCodec = this.levels[this.level].videoCodec; - track.id = data.id; - } - this.hls.trigger(_events2.default.BUFFER_CODECS, tracks); - // loop through tracks that are going to be provided to bufferController - for (trackName in tracks) { - track = tracks[trackName]; - _logger.logger.log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']'); - var initSegment = track.initSegment; - if (initSegment) { - this.appended = true; - // arm pending Buffering flag before appending a segment - this.pendingBuffering = true; - this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' }); - } - } - //trigger handler right now - this.tick(); - } - } - }, { - key: 'onFragParsingData', - value: function onFragParsingData(data) { - var _this2 = this; - - var fragCurrent = this.fragCurrent; - var fragNew = data.frag; - if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller - this.state === State.PARSING) { - var level = this.levels[this.level], - frag = fragCurrent; - if (isNaN(data.endPTS)) { - data.endPTS = data.startPTS + fragCurrent.duration; - data.endDTS = data.startDTS + fragCurrent.duration; - } - - _logger.logger.log('Parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0)); - - // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments) - if (data.type === 'video') { - frag.dropped = data.dropped; - if (frag.dropped) { - if (!frag.backtracked) { - _logger.logger.warn('missing video frame(s), backtracking fragment'); - // Return back to the IDLE state without appending to buffer - // Causes findFragments to backtrack a segment and find the keyframe - // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment - frag.backtracked = true; - this.nextLoadPosition = data.startPTS; - this.state = State.IDLE; - this.fragPrevious = frag; - this.tick(); - return; - } else { - _logger.logger.warn('Already backtracked on this fragment, appending with the gap'); - } - } else { - // Only reset the backtracked flag if we've loaded the frag without any dropped frames - frag.backtracked = false; - } - } - - var drift = _levelHelper2.default.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS), - hls = this.hls; - hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS }); - - // has remuxer dropped video frames located before first keyframe ? - [data.data1, data.data2].forEach(function (buffer) { - // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending) - // in that case it is useless to append following segments - if (buffer && buffer.length && _this2.state === State.PARSING) { - _this2.appended = true; - // arm pending Buffering flag before appending a segment - _this2.pendingBuffering = true; - hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' }); - } - }); - //trigger handler right now - this.tick(); - } - } - }, { - key: 'onFragParsed', - value: function onFragParsed(data) { - var fragCurrent = this.fragCurrent; - var fragNew = data.frag; - if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { - this.stats.tparsed = performance.now(); - this.state = State.PARSED; - this._checkAppendedParsed(); - } - } - }, { - key: 'onAudioTrackSwitching', - value: function onAudioTrackSwitching(data) { - // if any URL found on new audio track, it is an alternate audio track - var altAudio = !!data.url, - trackId = data.id; - // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered - // don't do anything if we switch to alt audio: audio stream controller is handling it. - // we will just have to change buffer scheduling on audioTrackSwitched - if (!altAudio) { - if (this.mediaBuffer !== this.media) { - _logger.logger.log('switching on main audio, use media.buffered to schedule main fragment loading'); - this.mediaBuffer = this.media; - var fragCurrent = this.fragCurrent; - // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch - if (fragCurrent.loader) { - _logger.logger.log('switching to main audio track, cancel main fragment load'); - fragCurrent.loader.abort(); - } - this.fragCurrent = null; - this.fragPrevious = null; - // destroy demuxer to force init segment generation (following audio switch) - if (this.demuxer) { - this.demuxer.destroy(); - this.demuxer = null; - } - // switch to IDLE state to load new fragment - this.state = State.IDLE; - } - var hls = this.hls; - // switching to main audio, flush all audio and trigger track switched - hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); - hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId }); - this.altAudio = false; - } - } - }, { - key: 'onAudioTrackSwitched', - value: function onAudioTrackSwitched(data) { - var trackId = data.id, - altAudio = !!this.hls.audioTracks[trackId].url; - if (altAudio) { - var videoBuffer = this.videoBuffer; - // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered - if (videoBuffer && this.mediaBuffer !== videoBuffer) { - _logger.logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading'); - this.mediaBuffer = videoBuffer; - } - } - this.altAudio = altAudio; - this.tick(); - } - }, { - key: 'onBufferCreated', - value: function onBufferCreated(data) { - var tracks = data.tracks, - mediaTrack = void 0, - name = void 0, - alternate = false; - for (var type in tracks) { - var track = tracks[type]; - if (track.id === 'main') { - name = type; - mediaTrack = track; - // keep video source buffer reference - if (type === 'video') { - this.videoBuffer = tracks[type].buffer; - } - } else { - alternate = true; - } - } - if (alternate && mediaTrack) { - _logger.logger.log('alternate track found, use ' + name + '.buffered to schedule main fragment loading'); - this.mediaBuffer = mediaTrack.buffer; - } else { - this.mediaBuffer = this.media; - } - } - }, { - key: 'onBufferAppended', - value: function onBufferAppended(data) { - if (data.parent === 'main') { - var state = this.state; - if (state === State.PARSING || state === State.PARSED) { - // check if all buffers have been appended - this.pendingBuffering = data.pending > 0; - this._checkAppendedParsed(); - } - } - } - }, { - key: '_checkAppendedParsed', - value: function _checkAppendedParsed() { - //trigger handler right now - if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) { - var frag = this.fragCurrent; - if (frag) { - var media = this.mediaBuffer ? this.mediaBuffer : this.media; - _logger.logger.log('main buffered : ' + _timeRanges2.default.toString(media.buffered)); - // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams - var bufferedFrags = this._bufferedFrags.filter(function (frag) { - return _bufferHelper2.default.isBuffered(media, (frag.startPTS + frag.endPTS) / 2); - }); - // push new range - bufferedFrags.push(frag); - // sort frags, as we use BinarySearch for lookup in getBufferedFrag ... - this._bufferedFrags = bufferedFrags.sort(function (a, b) { - return a.startPTS - b.startPTS; - }); - this.fragPrevious = frag; - var stats = this.stats; - stats.tbuffered = performance.now(); - // we should get rid of this.fragLastKbps - this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst)); - this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' }); - this.state = State.IDLE; - } - this.tick(); - } - } - }, { - key: 'onError', - value: function onError(data) { - var frag = data.frag || this.fragCurrent; - // don't handle frag error not related to main fragment - if (frag && frag.type !== 'main') { - return; - } - var media = this.media, - - // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end - mediaBuffered = media && _bufferHelper2.default.isBuffered(media, media.currentTime) && _bufferHelper2.default.isBuffered(media, media.currentTime + 0.5); - switch (data.details) { - case _errors.ErrorDetails.FRAG_LOAD_ERROR: - case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT: - case _errors.ErrorDetails.KEY_LOAD_ERROR: - case _errors.ErrorDetails.KEY_LOAD_TIMEOUT: - if (!data.fatal) { - var loadError = this.fragLoadError; - if (loadError) { - loadError++; - } else { - loadError = 1; - } - var config = this.config; - // keep retrying / don't raise fatal network error if current position is buffered or if in automode with current level not 0 - if (loadError <= config.fragLoadingMaxRetry || mediaBuffered || frag.autoLevel && frag.level) { - this.fragLoadError = loadError; - // reset load counter to avoid frag loop loading error - frag.loadCounter = 0; - // exponential backoff capped to config.fragLoadingMaxRetryTimeout - var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout); - _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms'); - this.retryDate = performance.now() + delay; - // retry loading state - // if loadedmetadata is not set, it means that we are emergency switch down on first frag - // in that case, reset startFragRequested flag - if (!this.loadedmetadata) { - this.startFragRequested = false; - this.nextLoadPosition = this.startPosition; - } - this.state = State.FRAG_LOADING_WAITING_RETRY; - } else { - _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...'); - // switch error to fatal - data.fatal = true; - this.state = State.ERROR; - } - } - break; - case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR: - if (!data.fatal) { - // if buffer is not empty - if (mediaBuffered) { - // try to reduce max buffer length : rationale is that we could get - // frag loop loading error because of buffer eviction - this._reduceMaxBufferLength(frag.duration); - this.state = State.IDLE; - } else { - // buffer empty. report as fatal if in manual mode or if lowest level. - // level controller takes care of emergency switch down logic - if (!frag.autoLevel || frag.level === 0) { - // switch error to fatal - data.fatal = true; - this.state = State.ERROR; - } - } - } - break; - case _errors.ErrorDetails.LEVEL_LOAD_ERROR: - case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT: - if (this.state !== State.ERROR) { - if (data.fatal) { - // if fatal error, stop processing - this.state = State.ERROR; - _logger.logger.warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...'); - } else { - // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE - if (!data.levelRetry && this.state === State.WAITING_LEVEL) { - this.state = State.IDLE; - } - } - } - break; - case _errors.ErrorDetails.BUFFER_FULL_ERROR: - // if in appending state - if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) { - // reduce max buf len if current position is buffered - if (mediaBuffered) { - this._reduceMaxBufferLength(this.config.maxBufferLength); - this.state = State.IDLE; - } else { - // current position is not buffered, but browser is still complaining about buffer full error - // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 - // in that case flush the whole buffer to recover - _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush everything'); - this.fragCurrent = null; - // flush everything - this.flushMainBuffer(0, Number.POSITIVE_INFINITY); - } - } - break; - default: - break; - } - } - }, { - key: '_reduceMaxBufferLength', - value: function _reduceMaxBufferLength(minLength) { - var config = this.config; - if (config.maxMaxBufferLength >= minLength) { - // reduce max buffer length as it might be too high. we do this to avoid loop flushing ... - config.maxMaxBufferLength /= 2; - _logger.logger.warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's'); - // increase fragment load Index to avoid frag loop loading error after buffer flush - this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold; - } - } - }, { - key: '_checkBuffer', - value: function _checkBuffer() { - var media = this.media, - config = this.config; - // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek - if (media && media.readyState) { - var currentTime = media.currentTime, - mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media, - buffered = mediaBuffer.buffered; - // adjust currentTime to start position on loaded metadata - if (!this.loadedmetadata && buffered.length) { - this.loadedmetadata = true; - // only adjust currentTime if different from startPosition or if startPosition not buffered - // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered - var startPosition = media.seeking ? currentTime : this.startPosition, - startPositionBuffered = _bufferHelper2.default.isBuffered(mediaBuffer, startPosition), - firstbufferedPosition = buffered.start(0); - // if currentTime not matching with expected startPosition or startPosition not buffered - if (currentTime !== startPosition || !startPositionBuffered && Math.abs(startPosition - firstbufferedPosition) < config.maxSeekHole) { - _logger.logger.log('target start position:' + startPosition); - // if startPosition not buffered, let's seek to buffered.start(0) - if (!startPositionBuffered) { - startPosition = firstbufferedPosition; - _logger.logger.log('target start position not buffered, seek to buffered.start(0) ' + startPosition); - } - _logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + startPosition); - media.currentTime = startPosition; - } - } else if (this.immediateSwitch) { - this.immediateLevelSwitchEnd(); - } else { - var bufferInfo = _bufferHelper2.default.bufferInfo(media, currentTime, 0), - expectedPlaying = !(media.paused || // not playing when media is paused - media.ended || // not playing when media is ended - media.buffered.length === 0), - // not playing if nothing buffered - jumpThreshold = 0.5, - // tolerance needed as some browsers stalls playback before reaching buffered range end - playheadMoving = currentTime !== this.lastCurrentTime; - - if (playheadMoving) { - // played moving, but was previously stalled => now not stuck anymore - if (this.stallReported) { - _logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(performance.now() - this.stalled) + 'ms'); - this.stallReported = false; - } - this.stalled = undefined; - this.nudgeRetry = 0; - } else { - // playhead not moving - if (expectedPlaying) { - // playhead not moving BUT media expected to play - var tnow = performance.now(); - var hls = this.hls; - if (!this.stalled) { - // stall just detected, store current time - this.stalled = tnow; - this.stallReported = false; - } else { - // playback already stalled, check stalling duration - // if stalling for more than a given threshold, let's try to recover - var stalledDuration = tnow - this.stalled; - var bufferLen = bufferInfo.len; - var nudgeRetry = this.nudgeRetry || 0; - // have we reached stall deadline ? - if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) { - // report stalled error once - if (!this.stallReported) { - this.stallReported = true; - _logger.logger.warn('playback stalling in low buffer @' + currentTime); - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); - } - // if buffer len is below threshold, try to jump to start of next buffer range if close - // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range) - var nextBufferStart = bufferInfo.nextStart, - delta = nextBufferStart - currentTime; - if (nextBufferStart && delta < config.maxSeekHole && delta > 0) { - this.nudgeRetry = ++nudgeRetry; - var nudgeOffset = nudgeRetry * config.nudgeOffset; - // next buffer is close ! adjust currentTime to nextBufferStart - // this will ensure effective video decoding - _logger.logger.log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset); - media.currentTime = nextBufferStart + nudgeOffset; - // reset stalled so to rearm watchdog timer - this.stalled = undefined; - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime }); - } - } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) { - // report stalled error once - if (!this.stallReported) { - this.stallReported = true; - _logger.logger.warn('playback stalling in high buffer @' + currentTime); - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); - } - // reset stalled so to rearm watchdog timer - this.stalled = undefined; - this.nudgeRetry = ++nudgeRetry; - if (nudgeRetry < config.nudgeMaxRetry) { - var _currentTime = media.currentTime; - var targetTime = _currentTime + nudgeRetry * config.nudgeOffset; - _logger.logger.log('adjust currentTime from ' + _currentTime + ' to ' + targetTime); - // playback stalled in buffered area ... let's nudge currentTime to try to overcome this - media.currentTime = targetTime; - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false }); - } else { - _logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error'); - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: true }); - } - } - } - } - } - } - } - } - }, { - key: 'onFragLoadEmergencyAborted', - value: function onFragLoadEmergencyAborted() { - this.state = State.IDLE; - // if loadedmetadata is not set, it means that we are emergency switch down on first frag - // in that case, reset startFragRequested flag - if (!this.loadedmetadata) { - this.startFragRequested = false; - this.nextLoadPosition = this.startPosition; - } - this.tick(); - } - }, { - key: 'onBufferFlushed', - value: function onBufferFlushed() { - /* after successful buffer flushing, filter flushed fragments from bufferedFrags - use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track) - */ - var media = this.mediaBuffer ? this.mediaBuffer : this.media; - this._bufferedFrags = this._bufferedFrags.filter(function (frag) { - return _bufferHelper2.default.isBuffered(media, (frag.startPTS + frag.endPTS) / 2); - }); - - // increase fragment load Index to avoid frag loop loading error after buffer flush - this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; - // move to IDLE once flush complete. this should trigger new fragment loading - this.state = State.IDLE; - // reset reference to frag - this.fragPrevious = null; - } - }, { - key: 'swapAudioCodec', - value: function swapAudioCodec() { - this.audioCodecSwap = !this.audioCodecSwap; - } - }, { - key: 'computeLivePosition', - value: function computeLivePosition(sliding, levelDetails) { - var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration; - return sliding + Math.max(0, levelDetails.totalduration - targetLatency); - } - }, { - key: 'state', - set: function set(nextState) { - if (this.state !== nextState) { - var previousState = this.state; - this._state = nextState; - _logger.logger.log('main stream:' + previousState + '->' + nextState); - this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState }); - } - }, - get: function get() { - return this._state; - } - }, { - key: 'currentLevel', - get: function get() { - var media = this.media; - if (media) { - var frag = this.getBufferedFrag(media.currentTime); - if (frag) { - return frag.level; - } - } - return -1; - } - }, { - key: 'nextBufferedFrag', - get: function get() { - var media = this.media; - if (media) { - // first get end range of current fragment - return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime)); - } else { - return null; - } - } - }, { - key: 'nextLevel', - get: function get() { - var frag = this.nextBufferedFrag; - if (frag) { - return frag.level; - } else { - return -1; - } - } - }, { - key: 'liveSyncPosition', - get: function get() { - return this._liveSyncPosition; - }, - set: function set(value) { - this._liveSyncPosition = value; - } - }]); - - return StreamController; -}(_eventHandler2.default); - -exports.default = StreamController; - -},{"25":25,"33":33,"34":34,"35":35,"37":37,"38":38,"48":48,"54":54,"55":55}],14:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Subtitle Stream Controller - */ - -var SubtitleStreamController = function (_EventHandler) { - _inherits$$1(SubtitleStreamController, _EventHandler); - - function SubtitleStreamController(hls) { - _classCallCheck$$1(this, SubtitleStreamController); - - var _this = _possibleConstructorReturn$$1(this, (SubtitleStreamController.__proto__ || Object.getPrototypeOf(SubtitleStreamController)).call(this, hls, _events2.default.ERROR, _events2.default.SUBTITLE_TRACKS_UPDATED, _events2.default.SUBTITLE_TRACK_SWITCH, _events2.default.SUBTITLE_TRACK_LOADED, _events2.default.SUBTITLE_FRAG_PROCESSED)); - - _this.config = hls.config; - _this.vttFragSNsProcessed = {}; - _this.vttFragQueues = undefined; - _this.currentlyProcessing = null; - _this.currentTrackId = -1; - return _this; - } - - _createClass$$1(SubtitleStreamController, [{ - key: 'destroy', - value: function destroy() { - _eventHandler2.default.prototype.destroy.call(this); - } - - // Remove all queued items and create a new, empty queue for each track. - - }, { - key: 'clearVttFragQueues', - value: function clearVttFragQueues() { - var _this2 = this; - - this.vttFragQueues = {}; - this.tracks.forEach(function (track) { - _this2.vttFragQueues[track.id] = []; - }); - } - - // If no frag is being processed and queue isn't empty, initiate processing of next frag in line. - - }, { - key: 'nextFrag', - value: function nextFrag() { - if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) { - var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift(); - this.hls.trigger(_events2.default.FRAG_LOADING, { frag: frag }); - } - } - - // When fragment has finished processing, add sn to list of completed if successful. - - }, { - key: 'onSubtitleFragProcessed', - value: function onSubtitleFragProcessed(data) { - if (data.success) { - this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn); - } - this.currentlyProcessing = null; - this.nextFrag(); - } - - // If something goes wrong, procede to next frag, if we were processing one. - - }, { - key: 'onError', - value: function onError(data) { - var frag = data.frag; - // don't handle frag error not related to subtitle fragment - if (frag && frag.type !== 'subtitle') { - return; - } - if (this.currentlyProcessing) { - this.currentlyProcessing = null; - this.nextFrag(); - } - } - - // Got all new subtitle tracks. - - }, { - key: 'onSubtitleTracksUpdated', - value: function onSubtitleTracksUpdated(data) { - var _this3 = this; - - _logger.logger.log('subtitle tracks updated'); - this.tracks = data.subtitleTracks; - this.clearVttFragQueues(); - this.vttFragSNsProcessed = {}; - this.tracks.forEach(function (track) { - _this3.vttFragSNsProcessed[track.id] = []; - }); - } - }, { - key: 'onSubtitleTrackSwitch', - value: function onSubtitleTrackSwitch(data) { - this.currentTrackId = data.id; - this.clearVttFragQueues(); - } - - // Got a new set of subtitle fragments. - - }, { - key: 'onSubtitleTrackLoaded', - value: function onSubtitleTrackLoaded(data) { - var processedFragSNs = this.vttFragSNsProcessed[data.id], - fragQueue = this.vttFragQueues[data.id], - currentFragSN = !!this.currentlyProcessing ? this.currentlyProcessing.sn : -1; - - var alreadyProcessed = function alreadyProcessed(frag) { - return processedFragSNs.indexOf(frag.sn) > -1; - }; - - var alreadyInQueue = function alreadyInQueue(frag) { - return fragQueue.some(function (fragInQueue) { - return fragInQueue.sn === frag.sn; - }); - }; - - // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue. - data.details.fragments.forEach(function (frag) { - if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) { - // Frags don't know their subtitle track ID, so let's just add that... - frag.trackId = data.id; - fragQueue.push(frag); - } - }); - - this.nextFrag(); - } - }]); - - return SubtitleStreamController; -}(_eventHandler2.default); - -exports.default = SubtitleStreamController; - -},{"34":34,"35":35,"54":54}],15:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * audio track controller - */ - -function filterSubtitleTracks(textTrackList) { - var tracks = []; - for (var i = 0; i < textTrackList.length; i++) { - if (textTrackList[i].kind === 'subtitles') { - tracks.push(textTrackList[i]); - } - } - return tracks; -} - -var SubtitleTrackController = function (_EventHandler) { - _inherits$$1(SubtitleTrackController, _EventHandler); - - function SubtitleTrackController(hls) { - _classCallCheck$$1(this, SubtitleTrackController); - - var _this = _possibleConstructorReturn$$1(this, (SubtitleTrackController.__proto__ || Object.getPrototypeOf(SubtitleTrackController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.SUBTITLE_TRACK_LOADED)); - - _this.tracks = []; - _this.trackId = -1; - _this.media = undefined; - return _this; - } - - _createClass$$1(SubtitleTrackController, [{ - key: '_onTextTracksChanged', - value: function _onTextTracksChanged() { - // Media is undefined when switching streams via loadSource() - if (!this.media) { - return; - } - - var trackId = -1; - var tracks = filterSubtitleTracks(this.media.textTracks); - for (var id = 0; id < tracks.length; id++) { - if (tracks[id].mode === 'showing') { - trackId = id; - } - } - - // Setting current subtitleTrack will invoke code. - this.subtitleTrack = trackId; - } - }, { - key: 'destroy', - value: function destroy() { - _eventHandler2.default.prototype.destroy.call(this); - } - - // Listen for subtitle track change, then extract the current track ID. - - }, { - key: 'onMediaAttached', - value: function onMediaAttached(data) { - this.media = data.media; - if (!this.media) { - return; - } - - this.trackChangeListener = this._onTextTracksChanged.bind(this); - this.media.textTracks.addEventListener('change', this.trackChangeListener); - } - }, { - key: 'onMediaDetaching', - value: function onMediaDetaching() { - if (!this.media) { - return; - } - - this.media.textTracks.removeEventListener('change', this.trackChangeListener); - - this.media = undefined; - } - - // Reset subtitle tracks on manifest loading - - }, { - key: 'onManifestLoading', - value: function onManifestLoading() { - this.tracks = []; - this.trackId = -1; - } - - // Fired whenever a new manifest is loaded. - - }, { - key: 'onManifestLoaded', - value: function onManifestLoaded(data) { - var _this2 = this; - - var tracks = data.subtitles || []; - var defaultFound = false; - this.tracks = tracks; - this.trackId = -1; - this.hls.trigger(_events2.default.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks }); - - // loop through available subtitle tracks and autoselect default if needed - // TODO: improve selection logic to handle forced, etc - tracks.forEach(function (track) { - if (track.default) { - _this2.subtitleTrack = track.id; - defaultFound = true; - } - }); - } - - // Trigger subtitle track playlist reload. - - }, { - key: 'onTick', - value: function onTick() { - var trackId = this.trackId; - var subtitleTrack = this.tracks[trackId]; - if (!subtitleTrack) { - return; - } - - var details = subtitleTrack.details; - // check if we need to load playlist for this subtitle Track - if (details === undefined || details.live === true) { - // track not retrieved yet, or live playlist we need to (re)load it - _logger.logger.log('(re)loading playlist for subtitle track ' + trackId); - this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: trackId }); - } - } - }, { - key: 'onSubtitleTrackLoaded', - value: function onSubtitleTrackLoaded(data) { - var _this3 = this; - - if (data.id < this.tracks.length) { - _logger.logger.log('subtitle track ' + data.id + ' loaded'); - this.tracks[data.id].details = data.details; - // check if current playlist is a live playlist - if (data.details.live && !this.timer) { - // if live playlist we will have to reload it periodically - // set reload period to playlist target duration - this.timer = setInterval(function () { - _this3.onTick(); - }, 1000 * data.details.targetduration, this); - } - if (!data.details.live && this.timer) { - // playlist is not live and timer is armed : stopping it - clearInterval(this.timer); - this.timer = null; - } - } - } - - /** get alternate subtitle tracks list from playlist **/ - - }, { - key: 'setSubtitleTrackInternal', - value: function setSubtitleTrackInternal(newId) { - // check if level idx is valid - if (newId >= 0 && newId < this.tracks.length) { - // stopping live reloading timer if any - if (this.timer) { - clearInterval(this.timer); - this.timer = null; - } - this.trackId = newId; - _logger.logger.log('switching to subtitle track ' + newId); - var subtitleTrack = this.tracks[newId]; - this.hls.trigger(_events2.default.SUBTITLE_TRACK_SWITCH, { id: newId }); - // check if we need to load playlist for this subtitle Track - var details = subtitleTrack.details; - if (details === undefined || details.live === true) { - // track not retrieved yet, or live playlist we need to (re)load it - _logger.logger.log('(re)loading playlist for subtitle track ' + newId); - this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId }); - } - } - } - }, { - key: 'subtitleTracks', - get: function get() { - return this.tracks; - } - - /** get index of the selected subtitle track (index in subtitle track lists) **/ - - }, { - key: 'subtitleTrack', - get: function get() { - return this.trackId; - } - - /** select a subtitle track, based on its index in subtitle track lists**/ - , - set: function set(subtitleTrackId) { - if (this.trackId !== subtitleTrackId) { - // || this.tracks[subtitleTrackId].details === undefined) { - this.setSubtitleTrackInternal(subtitleTrackId); - } - } - }]); - - return SubtitleTrackController; -}(_eventHandler2.default); - -exports.default = SubtitleTrackController; - -},{"34":34,"35":35,"54":54}],16:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _cea608Parser = _dereq_(49); - -var _cea608Parser2 = _interopRequireDefault(_cea608Parser); - -var _webvttParser = _dereq_(58); - -var _webvttParser2 = _interopRequireDefault(_webvttParser); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Timeline Controller - */ - -function clearCurrentCues(track) { - if (track && track.cues) { - while (track.cues.length > 0) { - track.removeCue(track.cues[0]); - } - } -} - -function reuseVttTextTrack(inUseTrack, manifestTrack) { - return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2); -} - -function intersection(x1, x2, y1, y2) { - return Math.min(x2, y2) - Math.max(x1, y1); -} - -var TimelineController = function (_EventHandler) { - _inherits$$1(TimelineController, _EventHandler); - - function TimelineController(hls) { - _classCallCheck$$1(this, TimelineController); - - var _this = _possibleConstructorReturn$$1(this, (TimelineController.__proto__ || Object.getPrototypeOf(TimelineController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_USERDATA, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.FRAG_LOADED, _events2.default.LEVEL_SWITCHING, _events2.default.INIT_PTS_FOUND)); - - _this.hls = hls; - _this.config = hls.config; - _this.enabled = true; - _this.Cues = hls.config.cueHandler; - _this.textTracks = []; - _this.tracks = []; - _this.unparsedVttFrags = []; - _this.initPTS = undefined; - _this.cueRanges = []; - - if (_this.config.enableCEA708Captions) { - var self = _this; - var sendAddTrackEvent = function sendAddTrackEvent(track, media) { - var e = null; - try { - e = new window.Event('addtrack'); - } catch (err) { - //for IE11 - e = document.createEvent('Event'); - e.initEvent('addtrack', false, false); - } - e.track = track; - media.dispatchEvent(e); - }; - - var channel1 = { - 'newCue': function newCue(startTime, endTime, screen) { - if (!self.textTrack1) { - //Enable reuse of existing text track. - var existingTrack1 = self.getExistingTrack('1'); - if (!existingTrack1) { - var textTrack1 = self.createTextTrack('captions', self.config.captionsTextTrack1Label, self.config.captionsTextTrack1LanguageCode); - if (textTrack1) { - textTrack1.textTrack1 = true; - self.textTrack1 = textTrack1; - } - } else { - self.textTrack1 = existingTrack1; - clearCurrentCues(self.textTrack1); - - sendAddTrackEvent(self.textTrack1, self.media); - } - } - self.addCues('textTrack1', startTime, endTime, screen); - } - }; - - var channel2 = { - 'newCue': function newCue(startTime, endTime, screen) { - if (!self.textTrack2) { - //Enable reuse of existing text track. - var existingTrack2 = self.getExistingTrack('2'); - if (!existingTrack2) { - var textTrack2 = self.createTextTrack('captions', self.config.captionsTextTrack2Label, self.config.captionsTextTrack1LanguageCode); - if (textTrack2) { - textTrack2.textTrack2 = true; - self.textTrack2 = textTrack2; - } - } else { - self.textTrack2 = existingTrack2; - clearCurrentCues(self.textTrack2); - - sendAddTrackEvent(self.textTrack2, self.media); - } - } - self.addCues('textTrack2', startTime, endTime, screen); - } - }; - - _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2); - } - return _this; - } - - _createClass$$1(TimelineController, [{ - key: 'addCues', - value: function addCues(channel, startTime, endTime, screen) { - // skip cues which overlap more than 50% with previously parsed time ranges - var ranges = this.cueRanges; - var merged = false; - for (var i = ranges.length; i--;) { - var cueRange = ranges[i]; - var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime); - if (overlap >= 0) { - cueRange[0] = Math.min(cueRange[0], startTime); - cueRange[1] = Math.max(cueRange[1], endTime); - merged = true; - if (overlap / (endTime - startTime) > 0.5) { - return; - } - } - } - if (!merged) { - ranges.push([startTime, endTime]); - } - this.Cues.newCue(this[channel], startTime, endTime, screen); - } - - // Triggered when an initial PTS is found; used for synchronisation of WebVTT. - - }, { - key: 'onInitPtsFound', - value: function onInitPtsFound(data) { - var _this2 = this; - - if (typeof this.initPTS === 'undefined') { - this.initPTS = data.initPTS; - } - - // Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded. - // Parse any unparsed fragments upon receiving the initial PTS. - if (this.unparsedVttFrags.length) { - this.unparsedVttFrags.forEach(function (frag) { - _this2.onFragLoaded(frag); - }); - this.unparsedVttFrags = []; - } - } - }, { - key: 'getExistingTrack', - value: function getExistingTrack(channelNumber) { - var media = this.media; - if (media) { - for (var i = 0; i < media.textTracks.length; i++) { - var textTrack = media.textTracks[i]; - var propName = 'textTrack' + channelNumber; - if (textTrack[propName] === true) { - return textTrack; - } - } - } - return null; - } - }, { - key: 'createTextTrack', - value: function createTextTrack(kind, label, lang) { - var media = this.media; - if (media) { - return media.addTextTrack(kind, label, lang); - } - } - }, { - key: 'destroy', - value: function destroy() { - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'onMediaAttaching', - value: function onMediaAttaching(data) { - this.media = data.media; - } - }, { - key: 'onMediaDetaching', - value: function onMediaDetaching() { - clearCurrentCues(this.textTrack1); - clearCurrentCues(this.textTrack2); - } - }, { - key: 'onManifestLoading', - value: function onManifestLoading() { - this.lastSn = -1; // Detect discontiguity in fragment parsing - this.prevCC = -1; - this.vttCCs = { ccOffset: 0, presentationOffset: 0 }; // Detect discontinuity in subtitle manifests - - // clear outdated subtitles - var media = this.media; - if (media) { - var textTracks = media.textTracks; - if (textTracks) { - for (var i = 0; i < textTracks.length; i++) { - clearCurrentCues(textTracks[i]); - } - } - } - } - }, { - key: 'onManifestLoaded', - value: function onManifestLoaded(data) { - var _this3 = this; - - this.textTracks = []; - this.unparsedVttFrags = this.unparsedVttFrags || []; - this.initPTS = undefined; - this.cueRanges = []; - - if (this.config.enableWebVTT) { - this.tracks = data.subtitles || []; - var inUseTracks = this.media ? this.media.textTracks : []; - - this.tracks.forEach(function (track, index) { - var textTrack = void 0; - if (index < inUseTracks.length) { - var inUseTrack = inUseTracks[index]; - // Reuse tracks with the same label, but do not reuse 608/708 tracks - if (reuseVttTextTrack(inUseTrack, track)) { - textTrack = inUseTrack; - } - } - if (!textTrack) { - textTrack = _this3.createTextTrack('subtitles', track.name, track.lang); - } - textTrack.mode = track.default ? 'showing' : 'hidden'; - _this3.textTracks.push(textTrack); - }); - } - } - }, { - key: 'onLevelSwitching', - value: function onLevelSwitching() { - this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE'; - } - }, { - key: 'onFragLoaded', - value: function onFragLoaded(data) { - var frag = data.frag, - payload = data.payload; - if (frag.type === 'main') { - var sn = frag.sn; - // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack - if (sn !== this.lastSn + 1) { - var cea608Parser = this.cea608Parser; - if (cea608Parser) { - cea608Parser.reset(); - } - } - this.lastSn = sn; - } - // If fragment is subtitle type, parse as WebVTT. - else if (frag.type === 'subtitle') { - if (payload.byteLength) { - // We need an initial synchronisation PTS. Store fragments as long as none has arrived. - if (typeof this.initPTS === 'undefined') { - this.unparsedVttFrags.push(data); - return; - } - var vttCCs = this.vttCCs; - if (!vttCCs[frag.cc]) { - vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true }; - this.prevCC = frag.cc; - } - var textTracks = this.textTracks, - hls = this.hls; - - // Parse the WebVTT file contents. - _webvttParser2.default.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) { - var currentTrack = textTracks[frag.trackId]; - // Add cues and trigger event with success true. - cues.forEach(function (cue) { - // Sometimes there are cue overlaps on segmented vtts so the same - // cue can appear more than once in different vtt files. - // This avoid showing duplicated cues with same timecode and text. - if (!currentTrack.cues.getCueById(cue.id)) { - currentTrack.addCue(cue); - } - }); - hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag }); - }, function (e) { - // Something went wrong while parsing. Trigger event with success false. - _logger.logger.log('Failed to parse VTT cue: ' + e); - hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); - }); - } else { - // In case there is no payload, finish unsuccessfully. - this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); - } - } - } - }, { - key: 'onFragParsingUserdata', - value: function onFragParsingUserdata(data) { - // push all of the CEA-708 messages into the interpreter - // immediately. It will create the proper timestamps based on our PTS value - if (this.enabled && this.config.enableCEA708Captions) { - for (var i = 0; i < data.samples.length; i++) { - var ccdatas = this.extractCea608Data(data.samples[i].bytes); - this.cea608Parser.addData(data.samples[i].pts, ccdatas); - } - } - } - }, { - key: 'extractCea608Data', - value: function extractCea608Data(byteArray) { - var count = byteArray[0] & 31; - var position = 2; - var tmpByte, ccbyte1, ccbyte2, ccValid, ccType; - var actualCCBytes = []; - - for (var j = 0; j < count; j++) { - tmpByte = byteArray[position++]; - ccbyte1 = 0x7F & byteArray[position++]; - ccbyte2 = 0x7F & byteArray[position++]; - ccValid = (4 & tmpByte) !== 0; - ccType = 3 & tmpByte; - - if (ccbyte1 === 0 && ccbyte2 === 0) { - continue; - } - - if (ccValid) { - if (ccType === 0) // || ccType === 1 - { - actualCCBytes.push(ccbyte1); - actualCCBytes.push(ccbyte2); - } - } - } - return actualCCBytes; - } - }]); - - return TimelineController; -}(_eventHandler2.default); - -exports.default = TimelineController; - -},{"34":34,"35":35,"49":49,"54":54,"58":58}],17:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var AESCrypto = function () { - function AESCrypto(subtle, iv) { - _classCallCheck$$1(this, AESCrypto); - - this.subtle = subtle; - this.aesIV = iv; - } - - _createClass$$1(AESCrypto, [{ - key: 'decrypt', - value: function decrypt(data, key) { - return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data); - } - }]); - - return AESCrypto; -}(); - -exports.default = AESCrypto; - -},{}],18:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var AESDecryptor = function () { - function AESDecryptor() { - _classCallCheck$$1(this, AESDecryptor); - - // Static after running initTable - this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; - this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; - this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; - this.sBox = new Uint32Array(256); - this.invSBox = new Uint32Array(256); - - // Changes during runtime - this.key = new Uint32Array(0); - - this.initTable(); - } - - // Using view.getUint32() also swaps the byte order. - - - _createClass$$1(AESDecryptor, [{ - key: 'uint8ArrayToUint32Array_', - value: function uint8ArrayToUint32Array_(arrayBuffer) { - var view = new DataView(arrayBuffer); - var newArray = new Uint32Array(4); - for (var i = 0; i < 4; i++) { - newArray[i] = view.getUint32(i * 4); - } - return newArray; - } - }, { - key: 'initTable', - value: function initTable() { - var sBox = this.sBox; - var invSBox = this.invSBox; - var subMix = this.subMix; - var subMix0 = subMix[0]; - var subMix1 = subMix[1]; - var subMix2 = subMix[2]; - var subMix3 = subMix[3]; - var invSubMix = this.invSubMix; - var invSubMix0 = invSubMix[0]; - var invSubMix1 = invSubMix[1]; - var invSubMix2 = invSubMix[2]; - var invSubMix3 = invSubMix[3]; - - var d = new Uint32Array(256); - var x = 0; - var xi = 0; - var i = 0; - for (i = 0; i < 256; i++) { - if (i < 128) { - d[i] = i << 1; - } else { - d[i] = i << 1 ^ 0x11b; - } - } - - for (i = 0; i < 256; i++) { - var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; - sx = sx >>> 8 ^ sx & 0xff ^ 0x63; - sBox[x] = sx; - invSBox[sx] = x; - - // Compute multiplication - var x2 = d[x]; - var x4 = d[x2]; - var x8 = d[x4]; - - // Compute sub/invSub bytes, mix columns tables - var t = d[sx] * 0x101 ^ sx * 0x1010100; - subMix0[x] = t << 24 | t >>> 8; - subMix1[x] = t << 16 | t >>> 16; - subMix2[x] = t << 8 | t >>> 24; - subMix3[x] = t; - - // Compute inv sub bytes, inv mix columns tables - t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; - invSubMix0[sx] = t << 24 | t >>> 8; - invSubMix1[sx] = t << 16 | t >>> 16; - invSubMix2[sx] = t << 8 | t >>> 24; - invSubMix3[sx] = t; - - // Compute next counter - if (!x) { - x = xi = 1; - } else { - x = x2 ^ d[d[d[x8 ^ x2]]]; - xi ^= d[d[xi]]; - } - } - } - }, { - key: 'expandKey', - value: function expandKey(keyBuffer) { - // convert keyBuffer to Uint32Array - var key = this.uint8ArrayToUint32Array_(keyBuffer); - var sameKey = true; - var offset = 0; - - while (offset < key.length && sameKey) { - sameKey = key[offset] === this.key[offset]; - offset++; - } - - if (sameKey) { - return; - } - - this.key = key; - var keySize = this.keySize = key.length; - - if (keySize !== 4 && keySize !== 6 && keySize !== 8) { - throw new Error('Invalid aes key size=' + keySize); - } - - var ksRows = this.ksRows = (keySize + 6 + 1) * 4; - var ksRow = void 0; - var invKsRow = void 0; - - var keySchedule = this.keySchedule = new Uint32Array(ksRows); - var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows); - var sbox = this.sBox; - var rcon = this.rcon; - - var invSubMix = this.invSubMix; - var invSubMix0 = invSubMix[0]; - var invSubMix1 = invSubMix[1]; - var invSubMix2 = invSubMix[2]; - var invSubMix3 = invSubMix[3]; - - var prev = void 0; - var t = void 0; - - for (ksRow = 0; ksRow < ksRows; ksRow++) { - if (ksRow < keySize) { - prev = keySchedule[ksRow] = key[ksRow]; - continue; - } - t = prev; - - if (ksRow % keySize === 0) { - // Rot word - t = t << 8 | t >>> 24; - - // Sub word - t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; - - // Mix Rcon - t ^= rcon[ksRow / keySize | 0] << 24; - } else if (keySize > 6 && ksRow % keySize === 4) { - // Sub word - t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; - } - - keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0; - } - - for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { - ksRow = ksRows - invKsRow; - if (invKsRow & 3) { - t = keySchedule[ksRow]; - } else { - t = keySchedule[ksRow - 4]; - } - - if (invKsRow < 4 || ksRow <= 4) { - invKeySchedule[invKsRow] = t; - } else { - invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]]; - } - - invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0; - } - } - - // Adding this as a method greatly improves performance. - - }, { - key: 'networkToHostOrderSwap', - value: function networkToHostOrderSwap(word) { - return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24; - } - }, { - key: 'decrypt', - value: function decrypt(inputArrayBuffer, offset, aesIV) { - var nRounds = this.keySize + 6; - var invKeySchedule = this.invKeySchedule; - var invSBOX = this.invSBox; - - var invSubMix = this.invSubMix; - var invSubMix0 = invSubMix[0]; - var invSubMix1 = invSubMix[1]; - var invSubMix2 = invSubMix[2]; - var invSubMix3 = invSubMix[3]; - - var initVector = this.uint8ArrayToUint32Array_(aesIV); - var initVector0 = initVector[0]; - var initVector1 = initVector[1]; - var initVector2 = initVector[2]; - var initVector3 = initVector[3]; - - var inputInt32 = new Int32Array(inputArrayBuffer); - var outputInt32 = new Int32Array(inputInt32.length); - - var t0 = void 0, - t1 = void 0, - t2 = void 0, - t3 = void 0; - var s0 = void 0, - s1 = void 0, - s2 = void 0, - s3 = void 0; - var inputWords0 = void 0, - inputWords1 = void 0, - inputWords2 = void 0, - inputWords3 = void 0; - - var ksRow, i; - var swapWord = this.networkToHostOrderSwap; - - while (offset < inputInt32.length) { - inputWords0 = swapWord(inputInt32[offset]); - inputWords1 = swapWord(inputInt32[offset + 1]); - inputWords2 = swapWord(inputInt32[offset + 2]); - inputWords3 = swapWord(inputInt32[offset + 3]); - - s0 = inputWords0 ^ invKeySchedule[0]; - s1 = inputWords3 ^ invKeySchedule[1]; - s2 = inputWords2 ^ invKeySchedule[2]; - s3 = inputWords1 ^ invKeySchedule[3]; - - ksRow = 4; - - // Iterate through the rounds of decryption - for (i = 1; i < nRounds; i++) { - t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow]; - t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; - t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; - t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; - // Update state - s0 = t0; - s1 = t1; - s2 = t2; - s3 = t3; - - ksRow = ksRow + 4; - } - - // Shift rows, sub bytes, add round key - t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow]; - t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; - t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; - t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; - ksRow = ksRow + 3; - - // Write - outputInt32[offset] = swapWord(t0 ^ initVector0); - outputInt32[offset + 1] = swapWord(t3 ^ initVector1); - outputInt32[offset + 2] = swapWord(t2 ^ initVector2); - outputInt32[offset + 3] = swapWord(t1 ^ initVector3); - - // reset initVector to last 4 unsigned int - initVector0 = inputWords0; - initVector1 = inputWords1; - initVector2 = inputWords2; - initVector3 = inputWords3; - - offset = offset + 4; - } - - return outputInt32.buffer; - } - }, { - key: 'destroy', - value: function destroy() { - this.key = undefined; - this.keySize = undefined; - this.ksRows = undefined; - - this.sBox = undefined; - this.invSBox = undefined; - this.subMix = undefined; - this.invSubMix = undefined; - this.keySchedule = undefined; - this.invKeySchedule = undefined; - - this.rcon = undefined; - } - }]); - - return AESDecryptor; -}(); - -exports.default = AESDecryptor; - -},{}],19:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _aesCrypto = _dereq_(17); - -var _aesCrypto2 = _interopRequireDefault(_aesCrypto); - -var _fastAesKey = _dereq_(20); - -var _fastAesKey2 = _interopRequireDefault(_fastAesKey); - -var _aesDecryptor = _dereq_(18); - -var _aesDecryptor2 = _interopRequireDefault(_aesDecryptor); - -var _errors = _dereq_(33); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/*globals self: false */ - -var Decrypter = function () { - function Decrypter(observer, config) { - _classCallCheck$$1(this, Decrypter); - - this.observer = observer; - this.config = config; - this.logEnabled = true; - try { - var browserCrypto = crypto ? crypto : self.crypto; - this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; - } catch (e) {} - this.disableWebCrypto = !this.subtle; - } - - _createClass$$1(Decrypter, [{ - key: 'isSync', - value: function isSync() { - return this.disableWebCrypto && this.config.enableSoftwareAES; - } - }, { - key: 'decrypt', - value: function decrypt(data, key, iv, callback) { - var _this = this; - - if (this.disableWebCrypto && this.config.enableSoftwareAES) { - if (this.logEnabled) { - _logger.logger.log('JS AES decrypt'); - this.logEnabled = false; - } - var decryptor = this.decryptor; - if (!decryptor) { - this.decryptor = decryptor = new _aesDecryptor2.default(); - } - decryptor.expandKey(key); - callback(decryptor.decrypt(data, 0, iv)); - } else { - if (this.logEnabled) { - _logger.logger.log('WebCrypto AES decrypt'); - this.logEnabled = false; - } - var subtle = this.subtle; - if (this.key !== key) { - this.key = key; - this.fastAesKey = new _fastAesKey2.default(subtle, key); - } - - this.fastAesKey.expandKey().then(function (aesKey) { - // decrypt using web crypto - var crypto = new _aesCrypto2.default(subtle, iv); - crypto.decrypt(data, aesKey).catch(function (err) { - _this.onWebCryptoError(err, data, key, iv, callback); - }).then(function (result) { - callback(result); - }); - }).catch(function (err) { - _this.onWebCryptoError(err, data, key, iv, callback); - }); - } - } - }, { - key: 'onWebCryptoError', - value: function onWebCryptoError(err, data, key, iv, callback) { - if (this.config.enableSoftwareAES) { - _logger.logger.log('WebCrypto Error, disable WebCrypto API'); - this.disableWebCrypto = true; - this.logEnabled = true; - this.decrypt(data, key, iv, callback); - } else { - _logger.logger.error('decrypting error : ' + err.message); - this.observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message }); - } - } - }, { - key: 'destroy', - value: function destroy() { - var decryptor = this.decryptor; - if (decryptor) { - decryptor.destroy(); - this.decryptor = undefined; - } - } - }]); - - return Decrypter; -}(); - -exports.default = Decrypter; - -},{"17":17,"18":18,"20":20,"33":33,"54":54}],20:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var FastAESKey = function () { - function FastAESKey(subtle, key) { - _classCallCheck$$1(this, FastAESKey); - - this.subtle = subtle; - this.key = key; - } - - _createClass$$1(FastAESKey, [{ - key: 'expandKey', - value: function expandKey() { - return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']); - } - }]); - - return FastAESKey; -}(); - -exports.default = FastAESKey; - -},{}],21:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * AAC demuxer - */ - - -var _adts = _dereq_(22); - -var _adts2 = _interopRequireDefault(_adts); - -var _logger = _dereq_(54); - -var _id = _dereq_(27); - -var _id2 = _interopRequireDefault(_id); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var AACDemuxer = function () { - function AACDemuxer(observer, remuxer, config) { - _classCallCheck$$1(this, AACDemuxer); - - this.observer = observer; - this.config = config; - this.remuxer = remuxer; - } - - _createClass$$1(AACDemuxer, [{ - key: 'resetInitSegment', - value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { - this._audioTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 }; - } - }, { - key: 'resetTimeStamp', - value: function resetTimeStamp() {} - }, { - key: 'append', - - - // feed incoming data to the front of the parsing pipeline - value: function append(data, timeOffset, contiguous, accurateTimeOffset) { - var track = this._audioTrack, - id3Data = _id2.default.getID3Data(data, 0), - pts = 90 * _id2.default.getTimeStamp(id3Data), - frameIndex = 0, - stamp = pts, - length = data.length, - offset = id3Data.length; - - var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }]; - - while (offset < length - 1) { - if (_adts2.default.isHeader(data, offset) && offset + 5 < length) { - _adts2.default.initTrackConfig(track, this.observer, data, offset, track.manifestCodec); - var frame = _adts2.default.appendFrame(track, data, offset, pts, frameIndex); - if (frame) { - offset += frame.length; - stamp = frame.sample.pts; - frameIndex++; - } else { - _logger.logger.log('Unable to parse AAC frame'); - break; - } - } else if (_id2.default.isHeader(data, offset)) { - id3Data = _id2.default.getID3Data(data, offset); - id3Samples.push({ pts: stamp, dts: stamp, data: id3Data }); - offset += id3Data.length; - } else { - //nothing found, keep looking - offset++; - } - } - - this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset); - } - }, { - key: 'destroy', - value: function destroy() {} - }], [{ - key: 'probe', - value: function probe(data) { - // check if data contains ID3 timestamp and ADTS sync word - var offset, length; - var id3Data = _id2.default.getID3Data(data, 0); - if (id3Data && _id2.default.getTimeStamp(id3Data) !== undefined) { - // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 - // Layer bits (position 14 and 15) in header should be always 0 for ADTS - // More info https://wiki.multimedia.cx/index.php?title=ADTS - for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) { - if (_adts2.default.probe(data, offset)) { - _logger.logger.log('ADTS sync word found !'); - return true; - } - } - } - return false; - } - }]); - - return AACDemuxer; -}(); - -exports.default = AACDemuxer; - -},{"22":22,"27":27,"54":54}],22:[function(_dereq_,module,exports){ -'use strict'; - -var _logger = _dereq_(54); - -var _errors = _dereq_(33); - -/** - * ADTS parser helper - */ -var ADTS = { - getAudioConfig: function getAudioConfig(observer, data, offset, audioCodec) { - var adtsObjectType, - // :int - adtsSampleingIndex, - // :int - adtsExtensionSampleingIndex, - // :int - adtsChanelConfig, - // :int - config, - userAgent = navigator.userAgent.toLowerCase(), - manifestCodec = audioCodec, - adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; - // byte 2 - adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1; - adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2; - if (adtsSampleingIndex > adtsSampleingRates.length - 1) { - observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex }); - return; - } - adtsChanelConfig = (data[offset + 2] & 0x01) << 2; - // byte 3 - adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6; - _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig); - // firefox: freq less than 24kHz = AAC SBR (HE-AAC) - if (/firefox/i.test(userAgent)) { - if (adtsSampleingIndex >= 6) { - adtsObjectType = 5; - config = new Array(4); - // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies - // there is a factor 2 between frame sample rate and output sample rate - // multiply frequency by 2 (see table below, equivalent to substract 3) - adtsExtensionSampleingIndex = adtsSampleingIndex - 3; - } else { - adtsObjectType = 2; - config = new Array(2); - adtsExtensionSampleingIndex = adtsSampleingIndex; - } - // Android : always use AAC - } else if (userAgent.indexOf('android') !== -1) { - adtsObjectType = 2; - config = new Array(2); - adtsExtensionSampleingIndex = adtsSampleingIndex; - } else { - /* for other browsers (Chrome/Vivaldi/Opera ...) - always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...) - */ - adtsObjectType = 5; - config = new Array(4); - // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz) - if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) { - // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies - // there is a factor 2 between frame sample rate and output sample rate - // multiply frequency by 2 (see table below, equivalent to substract 3) - adtsExtensionSampleingIndex = adtsSampleingIndex - 3; - } else { - // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio) - // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo. - if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || !audioCodec && adtsChanelConfig === 1) { - adtsObjectType = 2; - config = new Array(2); - } - adtsExtensionSampleingIndex = adtsSampleingIndex; - } - } - /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config - ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig() - Audio Profile / Audio Object Type - 0: Null - 1: AAC Main - 2: AAC LC (Low Complexity) - 3: AAC SSR (Scalable Sample Rate) - 4: AAC LTP (Long Term Prediction) - 5: SBR (Spectral Band Replication) - 6: AAC Scalable - sampling freq - 0: 96000 Hz - 1: 88200 Hz - 2: 64000 Hz - 3: 48000 Hz - 4: 44100 Hz - 5: 32000 Hz - 6: 24000 Hz - 7: 22050 Hz - 8: 16000 Hz - 9: 12000 Hz - 10: 11025 Hz - 11: 8000 Hz - 12: 7350 Hz - 13: Reserved - 14: Reserved - 15: frequency is written explictly - Channel Configurations - These are the channel configurations: - 0: Defined in AOT Specifc Config - 1: 1 channel: front-center - 2: 2 channels: front-left, front-right - */ - // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1 - config[0] = adtsObjectType << 3; - // samplingFrequencyIndex - config[0] |= (adtsSampleingIndex & 0x0E) >> 1; - config[1] |= (adtsSampleingIndex & 0x01) << 7; - // channelConfiguration - config[1] |= adtsChanelConfig << 3; - if (adtsObjectType === 5) { - // adtsExtensionSampleingIndex - config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1; - config[2] = (adtsExtensionSampleingIndex & 0x01) << 7; - // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ??? - // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc - config[2] |= 2 << 2; - config[3] = 0; - } - return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec }; - }, - - isHeaderPattern: function isHeaderPattern(data, offset) { - return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0; - }, - - getHeaderLength: function getHeaderLength(data, offset) { - return !!(data[offset + 1] & 0x01) ? 7 : 9; - }, - - getFullFrameLength: function getFullFrameLength(data, offset) { - return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5; - }, - - isHeader: function isHeader(data, offset) { - // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 - // Layer bits (position 14 and 15) in header should be always 0 for ADTS - // More info https://wiki.multimedia.cx/index.php?title=ADTS - if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) { - return true; - } - return false; - }, - - probe: function probe(data, offset) { - // same as isHeader but we also check that ADTS frame follows last ADTS frame - // or end of data is reached - if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) { - // ADTS header Length - var headerLength = this.getHeaderLength(data, offset); - // ADTS frame Length - var frameLength = headerLength; - if (offset + 5 < data.length) { - frameLength = this.getFullFrameLength(data, offset); - } - var newOffset = offset + frameLength; - if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) { - return true; - } - } - return false; - }, - - initTrackConfig: function initTrackConfig(track, observer, data, offset, audioCodec) { - if (!track.samplerate) { - var config = this.getAudioConfig(observer, data, offset, audioCodec); - track.config = config.config; - track.samplerate = config.samplerate; - track.channelCount = config.channelCount; - track.codec = config.codec; - track.manifestCodec = config.manifestCodec; - _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount); - } - }, - - getFrameDuration: function getFrameDuration(samplerate) { - return 1024 * 90000 / samplerate; - }, - - appendFrame: function appendFrame(track, data, offset, pts, frameIndex) { - var frameDuration = this.getFrameDuration(track.samplerate); - var header = this.parseFrameHeader(data, offset, pts, frameIndex, frameDuration); - if (header) { - var stamp = header.stamp; - var headerLength = header.headerLength; - var frameLength = header.frameLength; - - //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); - var aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp }; - - track.samples.push(aacSample); - track.len += frameLength; - - return { sample: aacSample, length: frameLength + headerLength }; - } - - return undefined; - }, - - parseFrameHeader: function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) { - var headerLength, frameLength, stamp; - var length = data.length; - - // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header - headerLength = this.getHeaderLength(data, offset); - // retrieve frame size - frameLength = this.getFullFrameLength(data, offset); - frameLength -= headerLength; - - if (frameLength > 0 && offset + headerLength + frameLength <= length) { - stamp = pts + frameIndex * frameDuration; - //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); - return { headerLength: headerLength, frameLength: frameLength, stamp: stamp }; - } - - return undefined; - } -}; - -module.exports = ADTS; - -},{"33":33,"54":54}],23:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* inline demuxer. - * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...) - */ - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _errors = _dereq_(33); - -var _decrypter = _dereq_(19); - -var _decrypter2 = _interopRequireDefault(_decrypter); - -var _aacdemuxer = _dereq_(21); - -var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer); - -var _mp4demuxer = _dereq_(29); - -var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer); - -var _tsdemuxer = _dereq_(32); - -var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer); - -var _mp3demuxer = _dereq_(28); - -var _mp3demuxer2 = _interopRequireDefault(_mp3demuxer); - -var _mp4Remuxer = _dereq_(45); - -var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer); - -var _passthroughRemuxer = _dereq_(46); - -var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var DemuxerInline = function () { - function DemuxerInline(observer, typeSupported, config, vendor) { - _classCallCheck$$1(this, DemuxerInline); - - this.observer = observer; - this.typeSupported = typeSupported; - this.config = config; - this.vendor = vendor; - } - - _createClass$$1(DemuxerInline, [{ - key: 'destroy', - value: function destroy() { - var demuxer = this.demuxer; - if (demuxer) { - demuxer.destroy(); - } - } - }, { - key: 'push', - value: function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) { - if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') { - var decrypter = this.decrypter; - if (decrypter == null) { - decrypter = this.decrypter = new _decrypter2.default(this.observer, this.config); - } - var localthis = this; - // performance.now() not available on WebWorker, at least on Safari Desktop - var startTime; - try { - startTime = performance.now(); - } catch (error) { - startTime = Date.now(); - } - decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) { - var endTime; - try { - endTime = performance.now(); - } catch (error) { - endTime = Date.now(); - } - localthis.observer.trigger(_events2.default.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } }); - localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); - }); - } else { - this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); - } - } - }, { - key: 'pushDecrypted', - value: function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) { - var demuxer = this.demuxer; - if (!demuxer || - // in case of continuity change, we might switch from content type (AAC container to TS container for example) - // so let's check that current demuxer is still valid - discontinuity && !this.probe(data)) { - var observer = this.observer; - var typeSupported = this.typeSupported; - var config = this.config; - // probing order is AAC/MP3/TS/MP4 - var muxConfig = [{ demux: _aacdemuxer2.default, remux: _mp4Remuxer2.default }, { demux: _mp3demuxer2.default, remux: _mp4Remuxer2.default }, { demux: _tsdemuxer2.default, remux: _mp4Remuxer2.default }, { demux: _mp4demuxer2.default, remux: _passthroughRemuxer2.default }]; - - // probe for content type - for (var i = 0, len = muxConfig.length; i < len; i++) { - var mux = muxConfig[i]; - var probe = mux.demux.probe; - if (probe(data)) { - var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor); - demuxer = new mux.demux(observer, _remuxer, config, typeSupported); - this.probe = probe; - break; - } - } - if (!demuxer) { - observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' }); - return; - } - this.demuxer = demuxer; - } - var remuxer = this.remuxer; - - if (discontinuity || trackSwitch) { - demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration); - remuxer.resetInitSegment(); - } - if (discontinuity) { - demuxer.resetTimeStamp(defaultInitPTS); - remuxer.resetTimeStamp(defaultInitPTS); - } - if (typeof demuxer.setDecryptData === 'function') { - demuxer.setDecryptData(decryptdata); - } - demuxer.append(data, timeOffset, contiguous, accurateTimeOffset); - } - }]); - - return DemuxerInline; -}(); - -exports.default = DemuxerInline; - -},{"19":19,"21":21,"28":28,"29":29,"32":32,"33":33,"35":35,"45":45,"46":46}],24:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _demuxerInline = _dereq_(23); - -var _demuxerInline2 = _interopRequireDefault(_demuxerInline); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _logger = _dereq_(54); - -var _events3 = _dereq_(1); - -var _events4 = _interopRequireDefault(_events3); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* demuxer web worker. - * - listen to worker message, and trigger DemuxerInline upon reception of Fragments. - * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead. - */ - -var DemuxerWorker = function DemuxerWorker(self) { - // observer setup - var observer = new _events4.default(); - observer.trigger = function trigger(event) { - for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - data[_key - 1] = arguments[_key]; - } - - observer.emit.apply(observer, [event, event].concat(data)); - }; - - observer.off = function off(event) { - for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - data[_key2 - 1] = arguments[_key2]; - } - - observer.removeListener.apply(observer, [event].concat(data)); - }; - - var forwardMessage = function forwardMessage(ev, data) { - self.postMessage({ event: ev, data: data }); - }; - - self.addEventListener('message', function (ev) { - var data = ev.data; - //console.log('demuxer cmd:' + data.cmd); - switch (data.cmd) { - case 'init': - var config = JSON.parse(data.config); - self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, config, data.vendor); - try { - (0, _logger.enableLogs)(config.debug === true); - } catch (err) { - console.warn('demuxerWorker: unable to enable logs'); - } - // signal end of worker init - forwardMessage('init', null); - break; - case 'demux': - self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS); - break; - default: - break; - } - }); - - // forward events to main thread - observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage); - observer.on(_events2.default.FRAG_PARSED, forwardMessage); - observer.on(_events2.default.ERROR, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage); - observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage); - - // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy) - observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) { - var transferable = []; - var message = { event: ev, data: data }; - if (data.data1) { - message.data1 = data.data1.buffer; - transferable.push(data.data1.buffer); - delete data.data1; - } - if (data.data2) { - message.data2 = data.data2.buffer; - transferable.push(data.data2.buffer); - delete data.data2; - } - self.postMessage(message, transferable); - }); -}; - -exports.default = DemuxerWorker; - -},{"1":1,"23":23,"35":35,"54":54}],25:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _demuxerInline = _dereq_(23); - -var _demuxerInline2 = _interopRequireDefault(_demuxerInline); - -var _demuxerWorker = _dereq_(24); - -var _demuxerWorker2 = _interopRequireDefault(_demuxerWorker); - -var _logger = _dereq_(54); - -var _errors = _dereq_(33); - -var _events3 = _dereq_(1); - -var _events4 = _interopRequireDefault(_events3); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Demuxer = function () { - function Demuxer(hls, id) { - _classCallCheck$$1(this, Demuxer); - - this.hls = hls; - this.id = id; - // observer setup - var observer = this.observer = new _events4.default(); - var config = hls.config; - observer.trigger = function trigger(event) { - for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - data[_key - 1] = arguments[_key]; - } - - observer.emit.apply(observer, [event, event].concat(data)); - }; - - observer.off = function off(event) { - for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - data[_key2 - 1] = arguments[_key2]; - } - - observer.removeListener.apply(observer, [event].concat(data)); - }; - - var forwardMessage = function (ev, data) { - data = data || {}; - data.frag = this.frag; - data.id = this.id; - hls.trigger(ev, data); - }.bind(this); - - // forward events to main thread - observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_DATA, forwardMessage); - observer.on(_events2.default.FRAG_PARSED, forwardMessage); - observer.on(_events2.default.ERROR, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage); - observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage); - observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage); - - var typeSupported = { - mp4: MediaSource.isTypeSupported('video/mp4'), - mpeg: MediaSource.isTypeSupported('audio/mpeg'), - mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"') - }; - // navigator.vendor is not always available in Web Worker - // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator - var vendor = navigator.vendor; - if (config.enableWorker && typeof Worker !== 'undefined') { - _logger.logger.log('demuxing in webworker'); - var w = void 0; - try { - var work$$1 = _dereq_(3); - w = this.w = work$$1(_demuxerWorker2.default); - this.onwmsg = this.onWorkerMessage.bind(this); - w.addEventListener('message', this.onwmsg); - w.onerror = function (event) { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } }); - }; - w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) }); - } catch (err) { - _logger.logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline'); - if (w) { - // revoke the Object URL that was used to create demuxer worker, so as not to leak it - URL.revokeObjectURL(w.objectURL); - } - this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor); - this.w = undefined; - } - } else { - this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor); - } - } - - _createClass$$1(Demuxer, [{ - key: 'destroy', - value: function destroy() { - var w = this.w; - if (w) { - w.removeEventListener('message', this.onwmsg); - w.terminate(); - this.w = null; - } else { - var demuxer = this.demuxer; - if (demuxer) { - demuxer.destroy(); - this.demuxer = null; - } - } - var observer = this.observer; - if (observer) { - observer.removeAllListeners(); - this.observer = null; - } - } - }, { - key: 'push', - value: function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) { - var w = this.w; - var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start; - var decryptdata = frag.decryptdata; - var lastFrag = this.frag; - var discontinuity = !(lastFrag && frag.cc === lastFrag.cc); - var trackSwitch = !(lastFrag && frag.level === lastFrag.level); - var nextSN = lastFrag && frag.sn === lastFrag.sn + 1; - var contiguous = !trackSwitch && nextSN; - if (discontinuity) { - _logger.logger.log(this.id + ':discontinuity detected'); - } - if (trackSwitch) { - _logger.logger.log(this.id + ':switch detected'); - } - this.frag = frag; - if (w) { - // post fragment payload as transferable objects (no copy) - w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous, duration: duration, accurateTimeOffset: accurateTimeOffset, defaultInitPTS: defaultInitPTS }, [data]); - } else { - var demuxer = this.demuxer; - if (demuxer) { - demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); - } - } - } - }, { - key: 'onWorkerMessage', - value: function onWorkerMessage(ev) { - var data = ev.data, - hls = this.hls; - //console.log('onWorkerMessage:' + data.event); - switch (data.event) { - case 'init': - // revoke the Object URL that was used to create demuxer worker, so as not to leak it - URL.revokeObjectURL(this.w.objectURL); - break; - // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects - case _events2.default.FRAG_PARSING_DATA: - data.data.data1 = new Uint8Array(data.data1); - if (data.data2) { - data.data.data2 = new Uint8Array(data.data2); - } - /* falls through */ - default: - data.data = data.data || {}; - data.data.frag = this.frag; - data.data.id = this.id; - hls.trigger(data.event, data.data); - break; - } - } - }]); - - return Demuxer; -}(); - -exports.default = Demuxer; - -},{"1":1,"23":23,"24":24,"3":3,"33":33,"35":35,"54":54}],26:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264. - */ - -var _logger = _dereq_(54); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var ExpGolomb = function () { - function ExpGolomb(data) { - _classCallCheck$$1(this, ExpGolomb); - - this.data = data; - // the number of bytes left to examine in this.data - this.bytesAvailable = data.byteLength; - // the current word being examined - this.word = 0; // :uint - // the number of bits left to examine in the current word - this.bitsAvailable = 0; // :uint - } - - // ():void - - - _createClass$$1(ExpGolomb, [{ - key: 'loadWord', - value: function loadWord() { - var data = this.data, - bytesAvailable = this.bytesAvailable, - position = data.byteLength - bytesAvailable, - workingBytes = new Uint8Array(4), - availableBytes = Math.min(4, bytesAvailable); - if (availableBytes === 0) { - throw new Error('no bytes available'); - } - workingBytes.set(data.subarray(position, position + availableBytes)); - this.word = new DataView(workingBytes.buffer).getUint32(0); - // track the amount of this.data that has been processed - this.bitsAvailable = availableBytes * 8; - this.bytesAvailable -= availableBytes; - } - - // (count:int):void - - }, { - key: 'skipBits', - value: function skipBits(count) { - var skipBytes; // :int - if (this.bitsAvailable > count) { - this.word <<= count; - this.bitsAvailable -= count; - } else { - count -= this.bitsAvailable; - skipBytes = count >> 3; - count -= skipBytes >> 3; - this.bytesAvailable -= skipBytes; - this.loadWord(); - this.word <<= count; - this.bitsAvailable -= count; - } - } - - // (size:int):uint - - }, { - key: 'readBits', - value: function readBits(size) { - var bits = Math.min(this.bitsAvailable, size), - // :uint - valu = this.word >>> 32 - bits; // :uint - if (size > 32) { - _logger.logger.error('Cannot read more than 32 bits at a time'); - } - this.bitsAvailable -= bits; - if (this.bitsAvailable > 0) { - this.word <<= bits; - } else if (this.bytesAvailable > 0) { - this.loadWord(); - } - bits = size - bits; - if (bits > 0 && this.bitsAvailable) { - return valu << bits | this.readBits(bits); - } else { - return valu; - } - } - - // ():uint - - }, { - key: 'skipLZ', - value: function skipLZ() { - var leadingZeroCount; // :uint - for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { - if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) { - // the first bit of working word is 1 - this.word <<= leadingZeroCount; - this.bitsAvailable -= leadingZeroCount; - return leadingZeroCount; - } - } - // we exhausted word and still have not found a 1 - this.loadWord(); - return leadingZeroCount + this.skipLZ(); - } - - // ():void - - }, { - key: 'skipUEG', - value: function skipUEG() { - this.skipBits(1 + this.skipLZ()); - } - - // ():void - - }, { - key: 'skipEG', - value: function skipEG() { - this.skipBits(1 + this.skipLZ()); - } - - // ():uint - - }, { - key: 'readUEG', - value: function readUEG() { - var clz = this.skipLZ(); // :uint - return this.readBits(clz + 1) - 1; - } - - // ():int - - }, { - key: 'readEG', - value: function readEG() { - var valu = this.readUEG(); // :int - if (0x01 & valu) { - // the number is odd if the low order bit is set - return 1 + valu >>> 1; // add 1 to make it even, and divide by 2 - } else { - return -1 * (valu >>> 1); // divide by two then make it negative - } - } - - // Some convenience functions - // :Boolean - - }, { - key: 'readBoolean', - value: function readBoolean() { - return 1 === this.readBits(1); - } - - // ():int - - }, { - key: 'readUByte', - value: function readUByte() { - return this.readBits(8); - } - - // ():int - - }, { - key: 'readUShort', - value: function readUShort() { - return this.readBits(16); - } - // ():int - - }, { - key: 'readUInt', - value: function readUInt() { - return this.readBits(32); - } - - /** - * Advance the ExpGolomb decoder past a scaling list. The scaling - * list is optionally transmitted as part of a sequence parameter - * set and is not relevant to transmuxing. - * @param count {number} the number of entries in this scaling list - * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 - */ - - }, { - key: 'skipScalingList', - value: function skipScalingList(count) { - var lastScale = 8, - nextScale = 8, - j, - deltaScale; - for (j = 0; j < count; j++) { - if (nextScale !== 0) { - deltaScale = this.readEG(); - nextScale = (lastScale + deltaScale + 256) % 256; - } - lastScale = nextScale === 0 ? lastScale : nextScale; - } - } - - /** - * Read a sequence parameter set and return some interesting video - * properties. A sequence parameter set is the H264 metadata that - * describes the properties of upcoming video frames. - * @param data {Uint8Array} the bytes of a sequence parameter set - * @return {object} an object with configuration parsed from the - * sequence parameter set, including the dimensions of the - * associated video frames. - */ - - }, { - key: 'readSPS', - value: function readSPS() { - var frameCropLeftOffset = 0, - frameCropRightOffset = 0, - frameCropTopOffset = 0, - frameCropBottomOffset = 0, - profileIdc, - profileCompat, - levelIdc, - numRefFramesInPicOrderCntCycle, - picWidthInMbsMinus1, - picHeightInMapUnitsMinus1, - frameMbsOnlyFlag, - scalingListCount, - i, - readUByte = this.readUByte.bind(this), - readBits = this.readBits.bind(this), - readUEG = this.readUEG.bind(this), - readBoolean = this.readBoolean.bind(this), - skipBits = this.skipBits.bind(this), - skipEG = this.skipEG.bind(this), - skipUEG = this.skipUEG.bind(this), - skipScalingList = this.skipScalingList.bind(this); - - readUByte(); - profileIdc = readUByte(); // profile_idc - profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5) - skipBits(3); // reserved_zero_3bits u(3), - levelIdc = readUByte(); //level_idc u(8) - skipUEG(); // seq_parameter_set_id - // some profiles have more optional data we don't need - if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) { - var chromaFormatIdc = readUEG(); - if (chromaFormatIdc === 3) { - skipBits(1); // separate_colour_plane_flag - } - skipUEG(); // bit_depth_luma_minus8 - skipUEG(); // bit_depth_chroma_minus8 - skipBits(1); // qpprime_y_zero_transform_bypass_flag - if (readBoolean()) { - // seq_scaling_matrix_present_flag - scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; - for (i = 0; i < scalingListCount; i++) { - if (readBoolean()) { - // seq_scaling_list_present_flag[ i ] - if (i < 6) { - skipScalingList(16); - } else { - skipScalingList(64); - } - } - } - } - } - skipUEG(); // log2_max_frame_num_minus4 - var picOrderCntType = readUEG(); - if (picOrderCntType === 0) { - readUEG(); //log2_max_pic_order_cnt_lsb_minus4 - } else if (picOrderCntType === 1) { - skipBits(1); // delta_pic_order_always_zero_flag - skipEG(); // offset_for_non_ref_pic - skipEG(); // offset_for_top_to_bottom_field - numRefFramesInPicOrderCntCycle = readUEG(); - for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) { - skipEG(); // offset_for_ref_frame[ i ] - } - } - skipUEG(); // max_num_ref_frames - skipBits(1); // gaps_in_frame_num_value_allowed_flag - picWidthInMbsMinus1 = readUEG(); - picHeightInMapUnitsMinus1 = readUEG(); - frameMbsOnlyFlag = readBits(1); - if (frameMbsOnlyFlag === 0) { - skipBits(1); // mb_adaptive_frame_field_flag - } - skipBits(1); // direct_8x8_inference_flag - if (readBoolean()) { - // frame_cropping_flag - frameCropLeftOffset = readUEG(); - frameCropRightOffset = readUEG(); - frameCropTopOffset = readUEG(); - frameCropBottomOffset = readUEG(); - } - var pixelRatio = [1, 1]; - if (readBoolean()) { - // vui_parameters_present_flag - if (readBoolean()) { - // aspect_ratio_info_present_flag - var aspectRatioIdc = readUByte(); - switch (aspectRatioIdc) { - case 1: - pixelRatio = [1, 1];break; - case 2: - pixelRatio = [12, 11];break; - case 3: - pixelRatio = [10, 11];break; - case 4: - pixelRatio = [16, 11];break; - case 5: - pixelRatio = [40, 33];break; - case 6: - pixelRatio = [24, 11];break; - case 7: - pixelRatio = [20, 11];break; - case 8: - pixelRatio = [32, 11];break; - case 9: - pixelRatio = [80, 33];break; - case 10: - pixelRatio = [18, 11];break; - case 11: - pixelRatio = [15, 11];break; - case 12: - pixelRatio = [64, 33];break; - case 13: - pixelRatio = [160, 99];break; - case 14: - pixelRatio = [4, 3];break; - case 15: - pixelRatio = [3, 2];break; - case 16: - pixelRatio = [2, 1];break; - case 255: - { - pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()]; - break; - } - } - } - } - return { - width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2), - height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset), - pixelRatio: pixelRatio - }; - } - }, { - key: 'readSliceType', - value: function readSliceType() { - // skip NALu type - this.readUByte(); - // discard first_mb_in_slice - this.readUEG(); - // return slice_type - return this.readUEG(); - } - }]); - - return ExpGolomb; -}(); - -exports.default = ExpGolomb; - -},{"54":54}],27:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * ID3 parser - */ -var ID3 = function () { - function ID3() { - _classCallCheck$$1(this, ID3); - } - - _createClass$$1(ID3, null, [{ - key: 'isHeader', - - /** - * Returns true if an ID3 header can be found at offset in data - * @param {Uint8Array} data - The data to search in - * @param {number} offset - The offset at which to start searching - * @return {boolean} - True if an ID3 header is found - */ - value: function isHeader(data, offset) { - /* - * http://id3.org/id3v2.3.0 - * [0] = 'I' - * [1] = 'D' - * [2] = '3' - * [3,4] = {Version} - * [5] = {Flags} - * [6-9] = {ID3 Size} - * - * An ID3v2 tag can be detected with the following pattern: - * $49 44 33 yy yy xx zz zz zz zz - * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80 - */ - if (offset + 10 <= data.length) { - //look for 'ID3' identifier - if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) { - //check version is within range - if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) { - //check size is within range - if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { - return true; - } - } - } - } - - return false; - } - - /** - * Returns true if an ID3 footer can be found at offset in data - * @param {Uint8Array} data - The data to search in - * @param {number} offset - The offset at which to start searching - * @return {boolean} - True if an ID3 footer is found - */ - - }, { - key: 'isFooter', - value: function isFooter(data, offset) { - /* - * The footer is a copy of the header, but with a different identifier - */ - if (offset + 10 <= data.length) { - //look for '3DI' identifier - if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) { - //check version is within range - if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) { - //check size is within range - if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { - return true; - } - } - } - } - - return false; - } - - /** - * Returns any adjacent ID3 tags found in data starting at offset, as one block of data - * @param {Uint8Array} data - The data to search in - * @param {number} offset - The offset at which to start searching - * @return {Uint8Array} - The block of data containing any ID3 tags found - */ - - }, { - key: 'getID3Data', - value: function getID3Data(data, offset) { - var front = offset; - var length = 0; - - while (ID3.isHeader(data, offset)) { - //ID3 header is 10 bytes - length += 10; - - var size = ID3._readSize(data, offset + 6); - length += size; - - if (ID3.isFooter(data, offset + 10)) { - //ID3 footer is 10 bytes - length += 10; - } - - offset += length; - } - - if (length > 0) { - return data.subarray(front, front + length); - } - - return undefined; - } - }, { - key: '_readSize', - value: function _readSize(data, offset) { - var size = 0; - size = (data[offset] & 0x7f) << 21; - size |= (data[offset + 1] & 0x7f) << 14; - size |= (data[offset + 2] & 0x7f) << 7; - size |= data[offset + 3] & 0x7f; - return size; - } - - /** - * Searches for the Elementary Stream timestamp found in the ID3 data chunk - * @param {Uint8Array} data - Block of data containing one or more ID3 tags - * @return {number} - The timestamp - */ - - }, { - key: 'getTimeStamp', - value: function getTimeStamp(data) { - var frames = ID3.getID3Frames(data); - for (var i = 0; i < frames.length; i++) { - var frame = frames[i]; - if (ID3.isTimeStampFrame(frame)) { - return ID3._readTimeStamp(frame); - } - } - - return undefined; - } - - /** - * Returns true if the ID3 frame is an Elementary Stream timestamp frame - * @param {ID3 frame} frame - */ - - }, { - key: 'isTimeStampFrame', - value: function isTimeStampFrame(frame) { - return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp'; - } - }, { - key: '_getFrameData', - value: function _getFrameData(data) { - /* - Frame ID $xx xx xx xx (four characters) - Size $xx xx xx xx - Flags $xx xx - */ - var type = String.fromCharCode(data[0], data[1], data[2], data[3]); - var size = ID3._readSize(data, 4); - - //skip frame id, size, and flags - var offset = 10; - - return { type: type, size: size, data: data.subarray(offset, offset + size) }; - } - - /** - * Returns an array of ID3 frames found in all the ID3 tags in the id3Data - * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags - * @return {ID3 frame[]} - Array of ID3 frame objects - */ - - }, { - key: 'getID3Frames', - value: function getID3Frames(id3Data) { - var offset = 0; - var frames = []; - - while (ID3.isHeader(id3Data, offset)) { - var size = ID3._readSize(id3Data, offset + 6); - //skip past ID3 header - offset += 10; - var end = offset + size; - //loop through frames in the ID3 tag - while (offset + 8 < end) { - var frameData = ID3._getFrameData(id3Data.subarray(offset)); - var frame = ID3._decodeFrame(frameData); - if (frame) { - frames.push(frame); - } - //skip frame header and frame data - offset += frameData.size + 10; - } - - if (ID3.isFooter(id3Data, offset)) { - offset += 10; - } - } - - return frames; - } - }, { - key: '_decodeFrame', - value: function _decodeFrame(frame) { - if (frame.type === 'PRIV') { - return ID3._decodePrivFrame(frame); - } else if (frame.type[0] === 'T') { - return ID3._decodeTextFrame(frame); - } else if (frame.type[0] === 'W') { - return ID3._decodeURLFrame(frame); - } - - return undefined; - } - }, { - key: '_readTimeStamp', - value: function _readTimeStamp(timeStampFrame) { - if (timeStampFrame.data.byteLength === 8) { - var data = new Uint8Array(timeStampFrame.data); - // timestamp is 33 bit expressed as a big-endian eight-octet number, - // with the upper 31 bits set to zero. - var pts33Bit = data[3] & 0x1; - var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7]; - timestamp /= 45; - - if (pts33Bit) { - timestamp += 47721858.84; // 2^32 / 90 - } - - return Math.round(timestamp); - } - - return undefined; - } - }, { - key: '_decodePrivFrame', - value: function _decodePrivFrame(frame) { - /* - Format: \0 - */ - if (frame.size < 2) { - return undefined; - } - - var owner = ID3._utf8ArrayToStr(frame.data); - var privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); - - return { key: frame.type, info: owner, data: privateData.buffer }; - } - }, { - key: '_decodeTextFrame', - value: function _decodeTextFrame(frame) { - if (frame.size < 2) { - return undefined; - } - - if (frame.type === 'TXXX') { - /* - Format: - [0] = {Text Encoding} - [1-?] = {Description}\0{Value} - */ - var index = 1; - var description = ID3._utf8ArrayToStr(frame.data.subarray(index)); - - index += description.length + 1; - var value = ID3._utf8ArrayToStr(frame.data.subarray(index)); - - return { key: frame.type, info: description, data: value }; - } else { - /* - Format: - [0] = {Text Encoding} - [1-?] = {Value} - */ - var text = ID3._utf8ArrayToStr(frame.data.subarray(1)); - return { key: frame.type, data: text }; - } - } - }, { - key: '_decodeURLFrame', - value: function _decodeURLFrame(frame) { - if (frame.type === 'WXXX') { - /* - Format: - [0] = {Text Encoding} - [1-?] = {Description}\0{URL} - */ - if (frame.size < 2) { - return undefined; - } - - var index = 1; - var description = ID3._utf8ArrayToStr(frame.data.subarray(index)); - - index += description.length + 1; - var value = ID3._utf8ArrayToStr(frame.data.subarray(index)); - - return { key: frame.type, info: description, data: value }; - } else { - /* - Format: - [0-?] = {URL} - */ - var url = ID3._utf8ArrayToStr(frame.data); - return { key: frame.type, data: url }; - } - } - - // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197 - // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt - /* utf.js - UTF-8 <=> UTF-16 convertion - * - * Copyright (C) 1999 Masanao Izumo - * Version: 1.0 - * LastModified: Dec 25 1999 - * This library is free. You can redistribute it and/or modify it. - */ - - }, { - key: '_utf8ArrayToStr', - value: function _utf8ArrayToStr(array) { - - var char2 = void 0; - var char3 = void 0; - var out = ''; - var i = 0; - var length = array.length; - - while (i < length) { - var c = array[i++]; - switch (c >> 4) { - case 0: - return out; - case 1:case 2:case 3:case 4:case 5:case 6:case 7: - // 0xxxxxxx - out += String.fromCharCode(c); - break; - case 12:case 13: - // 110x xxxx 10xx xxxx - char2 = array[i++]; - out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F); - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = array[i++]; - char3 = array[i++]; - out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0); - break; - } - } - - return out; - } - }]); - - return ID3; -}(); - -exports.default = ID3; - -},{}],28:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * MP3 demuxer - */ - - -var _id = _dereq_(27); - -var _id2 = _interopRequireDefault(_id); - -var _logger = _dereq_(54); - -var _mpegaudio = _dereq_(30); - -var _mpegaudio2 = _interopRequireDefault(_mpegaudio); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var MP3Demuxer = function () { - function MP3Demuxer(observer, remuxer, config) { - _classCallCheck$$1(this, MP3Demuxer); - - this.observer = observer; - this.config = config; - this.remuxer = remuxer; - } - - _createClass$$1(MP3Demuxer, [{ - key: 'resetInitSegment', - value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { - this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 }; - } - }, { - key: 'resetTimeStamp', - value: function resetTimeStamp() {} - }, { - key: 'append', - - - // feed incoming data to the front of the parsing pipeline - value: function append(data, timeOffset, contiguous, accurateTimeOffset) { - var id3Data = _id2.default.getID3Data(data, 0); - var pts = 90 * _id2.default.getTimeStamp(id3Data); - var offset = id3Data.length; - var length = data.length; - var frameIndex = 0, - stamp = 0; - var track = this._audioTrack; - - var id3Samples = [{ pts: pts, dts: pts, data: id3Data }]; - - while (offset < length) { - if (_mpegaudio2.default.isHeader(data, offset)) { - var frame = _mpegaudio2.default.appendFrame(track, data, offset, pts, frameIndex); - if (frame) { - offset += frame.length; - stamp = frame.sample.pts; - frameIndex++; - } else { - //logger.log('Unable to parse Mpeg audio frame'); - break; - } - } else if (_id2.default.isHeader(data, offset)) { - id3Data = _id2.default.getID3Data(data, offset); - id3Samples.push({ pts: stamp, dts: stamp, data: id3Data }); - offset += id3Data.length; - } else { - //nothing found, keep looking - offset++; - } - } - - this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset); - } - }, { - key: 'destroy', - value: function destroy() {} - }], [{ - key: 'probe', - value: function probe(data) { - // check if data contains ID3 timestamp and MPEG sync word - var offset, length; - var id3Data = _id2.default.getID3Data(data, 0); - if (id3Data && _id2.default.getTimeStamp(id3Data) !== undefined) { - // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 - // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) - // More info http://www.mp3-tech.org/programmer/frame_header.html - for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) { - if (_mpegaudio2.default.probe(data, offset)) { - _logger.logger.log('MPEG Audio sync word found !'); - return true; - } - } - } - return false; - } - }]); - - return MP3Demuxer; -}(); - -exports.default = MP3Demuxer; - -},{"27":27,"30":30,"54":54}],29:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * MP4 demuxer - */ -//import {logger} from '../utils/logger'; - - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var UINT32_MAX = Math.pow(2, 32) - 1; - -var MP4Demuxer = function () { - function MP4Demuxer(observer, remuxer) { - _classCallCheck$$1(this, MP4Demuxer); - - this.observer = observer; - this.remuxer = remuxer; - } - - _createClass$$1(MP4Demuxer, [{ - key: 'resetTimeStamp', - value: function resetTimeStamp(initPTS) { - this.initPTS = initPTS; - } - }, { - key: 'resetInitSegment', - value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { - //jshint unused:false - if (initSegment && initSegment.byteLength) { - var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment); - var tracks = {}; - if (initData.audio) { - tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null }; - } - if (initData.video) { - tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null }; - } - this.observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, { tracks: tracks }); - } else { - if (audioCodec) { - this.audioCodec = audioCodec; - } - if (videoCodec) { - this.videoCodec = videoCodec; - } - } - } - }, { - key: 'append', - - - // feed incoming data to the front of the parsing pipeline - value: function append(data, timeOffset, contiguous, accurateTimeOffset) { - var initData = this.initData; - if (!initData) { - this.resetInitSegment(data, this.audioCodec, this.videoCodec); - initData = this.initData; - } - var startDTS = void 0, - initPTS = this.initPTS; - if (initPTS === undefined) { - var _startDTS = MP4Demuxer.getStartDTS(initData, data); - this.initPTS = initPTS = _startDTS - timeOffset; - this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS }); - } - MP4Demuxer.offsetStartDTS(initData, data, initPTS); - startDTS = MP4Demuxer.getStartDTS(initData, data); - this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data); - } - }, { - key: 'destroy', - value: function destroy() {} - }], [{ - key: 'probe', - value: function probe(data) { - if (data.length >= 8) { - var dataType = MP4Demuxer.bin2str(data.subarray(4, 8)); - return ['moof', 'ftyp', 'styp'].indexOf(dataType) >= 0; - } - return false; - } - }, { - key: 'bin2str', - value: function bin2str(buffer) { - return String.fromCharCode.apply(null, buffer); - } - }, { - key: 'readUint32', - value: function readUint32(buffer, offset) { - if (buffer.data) { - offset += buffer.start; - buffer = buffer.data; - } - - var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3]; - return val < 0 ? 4294967296 + val : val; - } - }, { - key: 'writeUint32', - value: function writeUint32(buffer, offset, value) { - if (buffer.data) { - offset += buffer.start; - buffer = buffer.data; - } - buffer[offset] = value >> 24; - buffer[offset + 1] = value >> 16 & 0xff; - buffer[offset + 2] = value >> 8 & 0xff; - buffer[offset + 3] = value & 0xff; - } - - // Find the data for a box specified by its path - - }, { - key: 'findBox', - value: function findBox(data, path) { - var results = [], - i, - size, - type, - end, - subresults, - start, - endbox; - - if (data.data) { - start = data.start; - end = data.end; - data = data.data; - } else { - start = 0; - end = data.byteLength; - } - - if (!path.length) { - // short-circuit the search for empty paths - return null; - } - - for (i = start; i < end;) { - size = MP4Demuxer.readUint32(data, i); - type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8)); - endbox = size > 1 ? i + size : end; - - if (type === path[0]) { - - if (path.length === 1) { - // this is the end of the path and we've found the box we were - // looking for - results.push({ data: data, start: i + 8, end: endbox }); - } else { - // recursively search for the next box along the path - subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1)); - if (subresults.length) { - results = results.concat(subresults); - } - } - } - i = endbox; - } - - // we've finished searching all of data - return results; - } - - /** - * Parses an MP4 initialization segment and extracts stream type and - * timescale values for any declared tracks. Timescale values indicate the - * number of clock ticks per second to assume for time-based values - * elsewhere in the MP4. - * - * To determine the start time of an MP4, you need two pieces of - * information: the timescale unit and the earliest base media decode - * time. Multiple timescales can be specified within an MP4 but the - * base media decode time is always expressed in the timescale from - * the media header box for the track: - * ``` - * moov > trak > mdia > mdhd.timescale - * moov > trak > mdia > hdlr - * ``` - * @param init {Uint8Array} the bytes of the init segment - * @return {object} a hash of track type to timescale values or null if - * the init segment is malformed. - */ - - }, { - key: 'parseInitSegment', - value: function parseInitSegment(initSegment) { - var result = []; - var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']); - - traks.forEach(function (trak) { - var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0]; - if (tkhd) { - var version = tkhd.data[tkhd.start]; - var index = version === 0 ? 12 : 20; - var trackId = MP4Demuxer.readUint32(tkhd, index); - - var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0]; - if (mdhd) { - version = mdhd.data[mdhd.start]; - index = version === 0 ? 12 : 20; - var timescale = MP4Demuxer.readUint32(mdhd, index); - - var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0]; - if (hdlr) { - var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12)); - var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType]; - if (type) { - result[trackId] = { timescale: timescale, type: type }; - result[type] = { timescale: timescale, id: trackId }; - } - } - } - } - }); - return result; - } - - /** - * Determine the base media decode start time, in seconds, for an MP4 - * fragment. If multiple fragments are specified, the earliest time is - * returned. - * - * The base media decode time can be parsed from track fragment - * metadata: - * ``` - * moof > traf > tfdt.baseMediaDecodeTime - * ``` - * It requires the timescale value from the mdhd to interpret. - * - * @param timescale {object} a hash of track ids to timescale values. - * @return {number} the earliest base media decode start time for the - * fragment, in seconds - */ - - }, { - key: 'getStartDTS', - value: function getStartDTS(initData, fragment) { - var trafs, baseTimes, result; - - // we need info from two childrend of each track fragment box - trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']); - - // determine the start times for each track - baseTimes = [].concat.apply([], trafs.map(function (traf) { - return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) { - var id, scale, baseTime; - - // get the track id from the tfhd - id = MP4Demuxer.readUint32(tfhd, 4); - // assume a 90kHz clock if no timescale was specified - scale = initData[id].timescale || 90e3; - - // get the base media decode time from the tfdt - baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) { - var version, result; - - version = tfdt.data[tfdt.start]; - result = MP4Demuxer.readUint32(tfdt, 4); - if (version === 1) { - result *= Math.pow(2, 32); - - result += MP4Demuxer.readUint32(tfdt, 8); - } - return result; - })[0]; - baseTime = baseTime || Infinity; - - // convert base time to seconds - return baseTime / scale; - }); - })); - - // return the minimum - result = Math.min.apply(null, baseTimes); - return isFinite(result) ? result : 0; - } - }, { - key: 'offsetStartDTS', - value: function offsetStartDTS(initData, fragment, timeOffset) { - MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) { - return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) { - // get the track id from the tfhd - var id = MP4Demuxer.readUint32(tfhd, 4); - // assume a 90kHz clock if no timescale was specified - var timescale = initData[id].timescale || 90e3; - - // get the base media decode time from the tfdt - MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) { - var version = tfdt.data[tfdt.start]; - var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4); - if (version === 0) { - MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale); - } else { - baseMediaDecodeTime *= Math.pow(2, 32); - baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8); - baseMediaDecodeTime -= timeOffset * timescale; - var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); - var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); - MP4Demuxer.writeUint32(tfdt, 4, upper); - MP4Demuxer.writeUint32(tfdt, 8, lower); - } - }); - }); - }); - } - }]); - - return MP4Demuxer; -}(); - -exports.default = MP4Demuxer; - -},{"35":35}],30:[function(_dereq_,module,exports){ -"use strict"; - -/** - * MPEG parser helper - */ - -var MpegAudio = { - - BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], - - SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000], - - appendFrame: function appendFrame(track, data, offset, pts, frameIndex) { - // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference - if (offset + 24 > data.length) { - return undefined; - } - - var header = this.parseHeader(data, offset); - if (header && offset + header.frameLength <= data.length) { - var frameDuration = 1152 * 90000 / header.sampleRate; - var stamp = pts + frameIndex * frameDuration; - var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp }; - - track.config = []; - track.channelCount = header.channelCount; - track.samplerate = header.sampleRate; - track.samples.push(sample); - track.len += header.frameLength; - - return { sample: sample, length: header.frameLength }; - } - - return undefined; - }, - - parseHeader: function parseHeader(data, offset) { - var headerB = data[offset + 1] >> 3 & 3; - var headerC = data[offset + 1] >> 1 & 3; - var headerE = data[offset + 2] >> 4 & 15; - var headerF = data[offset + 2] >> 2 & 3; - var headerG = !!(data[offset + 2] & 2); - if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) { - var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4; - var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000; - var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2; - var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF]; - var padding = headerG ? 1 : 0; - var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) - var frameLength = headerC === 3 ? (headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding << 2 : (headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding | 0; - - return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength }; - } - - return undefined; - }, - - isHeaderPattern: function isHeaderPattern(data, offset) { - return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00; - }, - - isHeader: function isHeader(data, offset) { - // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 - // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) - // More info http://www.mp3-tech.org/programmer/frame_header.html - if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) { - return true; - } - return false; - }, - - probe: function probe(data, offset) { - // same as isHeader but we also check that MPEG frame follows last MPEG frame - // or end of data is reached - if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) { - // MPEG header Length - var headerLength = 4; - // MPEG frame Length - var header = this.parseHeader(data, offset); - var frameLength = headerLength; - if (header && header.frameLength) { - frameLength = header.frameLength; - } - var newOffset = offset + frameLength; - if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) { - return true; - } - } - return false; - } -}; - -module.exports = MpegAudio; - -},{}],31:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * SAMPLE-AES decrypter - */ - -var _decrypter = _dereq_(19); - -var _decrypter2 = _interopRequireDefault(_decrypter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var SampleAesDecrypter = function () { - function SampleAesDecrypter(observer, config, decryptdata, discardEPB) { - _classCallCheck$$1(this, SampleAesDecrypter); - - this.decryptdata = decryptdata; - this.discardEPB = discardEPB; - this.decrypter = new _decrypter2.default(observer, config); - } - - _createClass$$1(SampleAesDecrypter, [{ - key: 'decryptBuffer', - value: function decryptBuffer(encryptedData, callback) { - this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback); - } - - // AAC - encrypt all full 16 bytes blocks starting from offset 16 - - }, { - key: 'decryptAacSample', - value: function decryptAacSample(samples, sampleIndex, callback, sync) { - var curUnit = samples[sampleIndex].unit; - var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16); - var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length); - - var localthis = this; - this.decryptBuffer(encryptedBuffer, function (decryptedData) { - decryptedData = new Uint8Array(decryptedData); - curUnit.set(decryptedData, 16); - - if (!sync) { - localthis.decryptAacSamples(samples, sampleIndex + 1, callback); - } - }); - } - }, { - key: 'decryptAacSamples', - value: function decryptAacSamples(samples, sampleIndex, callback) { - for (;; sampleIndex++) { - if (sampleIndex >= samples.length) { - callback(); - return; - } - - if (samples[sampleIndex].unit.length < 32) { - continue; - } - - var sync = this.decrypter.isSync(); - - this.decryptAacSample(samples, sampleIndex, callback, sync); - - if (!sync) { - return; - } - } - } - - // AVC - encrypt one 16 bytes block out of ten, starting from offset 32 - - }, { - key: 'getAvcEncryptedData', - value: function getAvcEncryptedData(decodedData) { - var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16; - var encryptedData = new Int8Array(encryptedDataLen); - var outputPos = 0; - for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) { - encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos); - } - return encryptedData; - } - }, { - key: 'getAvcDecryptedUnit', - value: function getAvcDecryptedUnit(decodedData, decryptedData) { - decryptedData = new Uint8Array(decryptedData); - var inputPos = 0; - for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) { - decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos); - } - return decodedData; - } - }, { - key: 'decryptAvcSample', - value: function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) { - var decodedData = this.discardEPB(curUnit.data); - var encryptedData = this.getAvcEncryptedData(decodedData); - var localthis = this; - - this.decryptBuffer(encryptedData.buffer, function (decryptedData) { - curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData); - - if (!sync) { - localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback); - } - }); - } - }, { - key: 'decryptAvcSamples', - value: function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) { - for (;; sampleIndex++, unitIndex = 0) { - if (sampleIndex >= samples.length) { - callback(); - return; - } - - var curUnits = samples[sampleIndex].units; - for (;; unitIndex++) { - if (unitIndex >= curUnits.length) { - break; - } - - var curUnit = curUnits[unitIndex]; - if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) { - continue; - } - - var sync = this.decrypter.isSync(); - - this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync); - - if (!sync) { - return; - } - } - } - } - }]); - - return SampleAesDecrypter; -}(); - -exports.default = SampleAesDecrypter; - -},{"19":19}],32:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * highly optimized TS demuxer: - * parse PAT, PMT - * extract PES packet from audio and video PIDs - * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet - * trigger the remuxer upon parsing completion - * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource. - * it also controls the remuxing process : - * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state. - */ - -// import Hex from '../utils/hex'; - - -var _adts = _dereq_(22); - -var _adts2 = _interopRequireDefault(_adts); - -var _mpegaudio = _dereq_(30); - -var _mpegaudio2 = _interopRequireDefault(_mpegaudio); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _expGolomb = _dereq_(26); - -var _expGolomb2 = _interopRequireDefault(_expGolomb); - -var _sampleAes = _dereq_(31); - -var _sampleAes2 = _interopRequireDefault(_sampleAes); - -var _logger = _dereq_(54); - -var _errors = _dereq_(33); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var TSDemuxer = function () { - function TSDemuxer(observer, remuxer, config, typeSupported) { - _classCallCheck$$1(this, TSDemuxer); - - this.observer = observer; - this.config = config; - this.typeSupported = typeSupported; - this.remuxer = remuxer; - this.sampleAes = null; - } - - _createClass$$1(TSDemuxer, [{ - key: 'setDecryptData', - value: function setDecryptData(decryptdata) { - if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') { - this.sampleAes = new _sampleAes2.default(this.observer, this.config, decryptdata, this.discardEPB); - } else { - this.sampleAes = null; - } - } - }, { - key: 'resetInitSegment', - value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { - this.pmtParsed = false; - this._pmtId = -1; - this._avcTrack = { container: 'video/mp2t', type: 'video', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0, dropped: 0 }; - this._audioTrack = { container: 'video/mp2t', type: 'audio', id: -1, inputTimeScale: 90000, duration: duration, sequenceNumber: 0, samples: [], len: 0, isAAC: true }; - this._id3Track = { type: 'id3', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0 }; - this._txtTrack = { type: 'text', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0 }; - // flush any partial content - this.aacOverFlow = null; - this.aacLastPTS = null; - this.avcSample = null; - this.audioCodec = audioCodec; - this.videoCodec = videoCodec; - this._duration = duration; - } - }, { - key: 'resetTimeStamp', - value: function resetTimeStamp() {} - - // feed incoming data to the front of the parsing pipeline - - }, { - key: 'append', - value: function append(data, timeOffset, contiguous, accurateTimeOffset) { - var start, - len = data.length, - stt, - pid, - atf, - offset, - pes, - unknownPIDs = false; - this.contiguous = contiguous; - var pmtParsed = this.pmtParsed, - avcTrack = this._avcTrack, - audioTrack = this._audioTrack, - id3Track = this._id3Track, - avcId = avcTrack.id, - audioId = audioTrack.id, - id3Id = id3Track.id, - pmtId = this._pmtId, - avcData = avcTrack.pesData, - audioData = audioTrack.pesData, - id3Data = id3Track.pesData, - parsePAT = this._parsePAT, - parsePMT = this._parsePMT, - parsePES = this._parsePES, - parseAVCPES = this._parseAVCPES.bind(this), - parseAACPES = this._parseAACPES.bind(this), - parseMPEGPES = this._parseMPEGPES.bind(this), - parseID3PES = this._parseID3PES.bind(this); - - // don't parse last TS packet if incomplete - len -= len % 188; - // loop through TS packets - for (start = 0; start < len; start += 188) { - if (data[start] === 0x47) { - stt = !!(data[start + 1] & 0x40); - // pid is a 13-bit field starting at the last bit of TS[1] - pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2]; - atf = (data[start + 3] & 0x30) >> 4; - // if an adaption field is present, its length is specified by the fifth byte of the TS packet header. - if (atf > 1) { - offset = start + 5 + data[start + 4]; - // continue if there is only adaptation field - if (offset === start + 188) { - continue; - } - } else { - offset = start + 4; - } - switch (pid) { - case avcId: - if (stt) { - if (avcData && (pes = parsePES(avcData))) { - parseAVCPES(pes, false); - } - avcData = { data: [], size: 0 }; - } - if (avcData) { - avcData.data.push(data.subarray(offset, start + 188)); - avcData.size += start + 188 - offset; - } - break; - case audioId: - if (stt) { - if (audioData && (pes = parsePES(audioData))) { - if (audioTrack.isAAC) { - parseAACPES(pes); - } else { - parseMPEGPES(pes); - } - } - audioData = { data: [], size: 0 }; - } - if (audioData) { - audioData.data.push(data.subarray(offset, start + 188)); - audioData.size += start + 188 - offset; - } - break; - case id3Id: - if (stt) { - if (id3Data && (pes = parsePES(id3Data))) { - parseID3PES(pes); - } - id3Data = { data: [], size: 0 }; - } - if (id3Data) { - id3Data.data.push(data.subarray(offset, start + 188)); - id3Data.size += start + 188 - offset; - } - break; - case 0: - if (stt) { - offset += data[offset] + 1; - } - pmtId = this._pmtId = parsePAT(data, offset); - break; - case pmtId: - if (stt) { - offset += data[offset] + 1; - } - var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null); - - // only update track id if track PID found while parsing PMT - // this is to avoid resetting the PID to -1 in case - // track PID transiently disappears from the stream - // this could happen in case of transient missing audio samples for example - avcId = parsedPIDs.avc; - if (avcId > 0) { - avcTrack.id = avcId; - } - audioId = parsedPIDs.audio; - if (audioId > 0) { - audioTrack.id = audioId; - audioTrack.isAAC = parsedPIDs.isAAC; - } - id3Id = parsedPIDs.id3; - if (id3Id > 0) { - id3Track.id = id3Id; - } - if (unknownPIDs && !pmtParsed) { - _logger.logger.log('reparse from beginning'); - unknownPIDs = false; - // we set it to -188, the += 188 in the for loop will reset start to 0 - start = -188; - } - pmtParsed = this.pmtParsed = true; - break; - case 17: - case 0x1fff: - break; - default: - unknownPIDs = true; - break; - } - } else { - this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' }); - } - } - // try to parse last PES packets - if (avcData && (pes = parsePES(avcData))) { - parseAVCPES(pes, true); - avcTrack.pesData = null; - } else { - // either avcData null or PES truncated, keep it for next frag parsing - avcTrack.pesData = avcData; - } - - if (audioData && (pes = parsePES(audioData))) { - if (audioTrack.isAAC) { - parseAACPES(pes); - } else { - parseMPEGPES(pes); - } - audioTrack.pesData = null; - } else { - if (audioData && audioData.size) { - _logger.logger.log('last AAC PES packet truncated,might overlap between fragments'); - } - // either audioData null or PES truncated, keep it for next frag parsing - audioTrack.pesData = audioData; - } - - if (id3Data && (pes = parsePES(id3Data))) { - parseID3PES(pes); - id3Track.pesData = null; - } else { - // either id3Data null or PES truncated, keep it for next frag parsing - id3Track.pesData = id3Data; - } - - if (this.sampleAes == null) { - this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset); - } else { - this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset); - } - } - }, { - key: 'decryptAndRemux', - value: function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { - if (audioTrack.samples && audioTrack.isAAC) { - var localthis = this; - this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () { - localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); - }); - } else { - this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); - } - } - }, { - key: 'decryptAndRemuxAvc', - value: function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { - if (videoTrack.samples) { - var localthis = this; - this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () { - localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); - }); - } else { - this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); - } - } - }, { - key: 'destroy', - value: function destroy() { - this._initPTS = this._initDTS = undefined; - this._duration = 0; - } - }, { - key: '_parsePAT', - value: function _parsePAT(data, offset) { - // skip the PSI header and parse the first PMT entry - return (data[offset + 10] & 0x1F) << 8 | data[offset + 11]; - //logger.log('PMT PID:' + this._pmtId); - } - }, { - key: '_parsePMT', - value: function _parsePMT(data, offset, mpegSupported, isSampleAes) { - var sectionLength, - tableEnd, - programInfoLength, - pid, - result = { audio: -1, avc: -1, id3: -1, isAAC: true }; - sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2]; - tableEnd = offset + 3 + sectionLength - 4; - // to determine where the table is, we have to figure out how - // long the program info descriptors are - programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; - // advance the offset to the first entry in the mapping table - offset += 12 + programInfoLength; - while (offset < tableEnd) { - pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2]; - switch (data[offset]) { - case 0xcf: - // SAMPLE-AES AAC - if (!isSampleAes) { - _logger.logger.log('unkown stream type:' + data[offset]); - break; - } - /* falls through */ - - // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio) - case 0x0f: - //logger.log('AAC PID:' + pid); - if (result.audio === -1) { - result.audio = pid; - } - break; - - // Packetized metadata (ID3) - case 0x15: - //logger.log('ID3 PID:' + pid); - if (result.id3 === -1) { - result.id3 = pid; - } - break; - - case 0xdb: - // SAMPLE-AES AVC - if (!isSampleAes) { - _logger.logger.log('unkown stream type:' + data[offset]); - break; - } - /* falls through */ - - // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video) - case 0x1b: - //logger.log('AVC PID:' + pid); - if (result.avc === -1) { - result.avc = pid; - } - break; - - // ISO/IEC 11172-3 (MPEG-1 audio) - // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio) - case 0x03: - case 0x04: - //logger.log('MPEG PID:' + pid); - if (!mpegSupported) { - _logger.logger.log('MPEG audio found, not supported in this browser for now'); - } else if (result.audio === -1) { - result.audio = pid; - result.isAAC = false; - } - break; - - case 0x24: - _logger.logger.warn('HEVC stream type found, not supported for now'); - break; - - default: - _logger.logger.log('unkown stream type:' + data[offset]); - break; - } - // move to the next table entry - // skip past the elementary stream descriptors, if present - offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5; - } - return result; - } - }, { - key: '_parsePES', - value: function _parsePES(stream) { - var i = 0, - frag, - pesFlags, - pesPrefix, - pesLen, - pesHdrLen, - pesData, - pesPts, - pesDts, - payloadStartOffset, - data = stream.data; - // safety check - if (!stream || stream.size === 0) { - return null; - } - - // we might need up to 19 bytes to read PES header - // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes - // usually only one merge is needed (and this is rare ...) - while (data[0].length < 19 && data.length > 1) { - var newData = new Uint8Array(data[0].length + data[1].length); - newData.set(data[0]); - newData.set(data[1], data[0].length); - data[0] = newData; - data.splice(1, 1); - } - //retrieve PTS/DTS from first fragment - frag = data[0]; - pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2]; - if (pesPrefix === 1) { - pesLen = (frag[4] << 8) + frag[5]; - // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated - // minus 6 : PES header size - if (pesLen && pesLen > stream.size - 6) { - return null; - } - pesFlags = frag[7]; - if (pesFlags & 0xC0) { - /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html - as PTS / DTS is 33 bit we cannot use bitwise operator in JS, - as Bitwise operators treat their operands as a sequence of 32 bits */ - pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29 - (frag[10] & 0xFF) * 4194304 + // 1 << 22 - (frag[11] & 0xFE) * 16384 + // 1 << 14 - (frag[12] & 0xFF) * 128 + // 1 << 7 - (frag[13] & 0xFE) / 2; - // check if greater than 2^32 -1 - if (pesPts > 4294967295) { - // decrement 2^33 - pesPts -= 8589934592; - } - if (pesFlags & 0x40) { - pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29 - (frag[15] & 0xFF) * 4194304 + // 1 << 22 - (frag[16] & 0xFE) * 16384 + // 1 << 14 - (frag[17] & 0xFF) * 128 + // 1 << 7 - (frag[18] & 0xFE) / 2; - // check if greater than 2^32 -1 - if (pesDts > 4294967295) { - // decrement 2^33 - pesDts -= 8589934592; - } - if (pesPts - pesDts > 60 * 90000) { - _logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them'); - pesPts = pesDts; - } - } else { - pesDts = pesPts; - } - } - pesHdrLen = frag[8]; - // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension - payloadStartOffset = pesHdrLen + 9; - - stream.size -= payloadStartOffset; - //reassemble PES packet - pesData = new Uint8Array(stream.size); - for (var j = 0, dataLen = data.length; j < dataLen; j++) { - frag = data[j]; - var len = frag.byteLength; - if (payloadStartOffset) { - if (payloadStartOffset > len) { - // trim full frag if PES header bigger than frag - payloadStartOffset -= len; - continue; - } else { - // trim partial frag if PES header smaller than frag - frag = frag.subarray(payloadStartOffset); - len -= payloadStartOffset; - payloadStartOffset = 0; - } - } - pesData.set(frag, i); - i += len; - } - if (pesLen) { - // payload size : remove PES header + PES extension - pesLen -= pesHdrLen + 3; - } - return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen }; - } else { - return null; - } - } - }, { - key: 'pushAccesUnit', - value: function pushAccesUnit(avcSample, avcTrack) { - if (avcSample.units.length && avcSample.frame) { - var samples = avcTrack.samples; - var nbSamples = samples.length; - // only push AVC sample if starting with a keyframe is not mandatory OR - // if keyframe already found in this fragment OR - // keyframe found in last fragment (track.sps) AND - // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous - if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) { - avcSample.id = nbSamples; - samples.push(avcSample); - } else { - // dropped samples, track it - avcTrack.dropped++; - } - } - if (avcSample.debug.length) { - _logger.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug); - } - } - }, { - key: '_parseAVCPES', - value: function _parseAVCPES(pes, last) { - var _this = this; - - //logger.log('parse new PES'); - var track = this._avcTrack, - units = this._parseAVCNALu(pes.data), - debug = false, - expGolombDecoder, - avcSample = this.avcSample, - push, - spsfound = false, - i; - //free pes.data to save up some memory - pes.data = null; - - units.forEach(function (unit) { - switch (unit.type) { - //NDR - case 1: - push = true; - if (debug && avcSample) { - avcSample.debug += 'NDR '; - } - avcSample.frame = true; - var data = unit.data; - // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...) - if (spsfound && data.length > 4) { - // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR - var sliceType = new _expGolomb2.default(data).readSliceType(); - // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice - // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples. - // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice. - // I slice: A slice that is not an SI slice that is decoded using intra prediction only. - //if (sliceType === 2 || sliceType === 7) { - if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) { - avcSample.key = true; - } - } - break; - //IDR - case 5: - push = true; - // handle PES not starting with AUD - if (!avcSample) { - avcSample = _this.avcSample = _this._createAVCSample(true, pes.pts, pes.dts, ''); - } - if (debug) { - avcSample.debug += 'IDR '; - } - avcSample.key = true; - avcSample.frame = true; - break; - //SEI - case 6: - push = true; - if (debug && avcSample) { - avcSample.debug += 'SEI '; - } - expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data)); - - // skip frameType - expGolombDecoder.readUByte(); - - var payloadType = 0; - var payloadSize = 0; - var endOfCaptions = false; - var b = 0; - - while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) { - payloadType = 0; - do { - b = expGolombDecoder.readUByte(); - payloadType += b; - } while (b === 0xFF); - - // Parse payload size. - payloadSize = 0; - do { - b = expGolombDecoder.readUByte(); - payloadSize += b; - } while (b === 0xFF); - - // TODO: there can be more than one payload in an SEI packet... - // TODO: need to read type and size in a while loop to get them all - if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) { - - endOfCaptions = true; - - var countryCode = expGolombDecoder.readUByte(); - - if (countryCode === 181) { - var providerCode = expGolombDecoder.readUShort(); - - if (providerCode === 49) { - var userStructure = expGolombDecoder.readUInt(); - - if (userStructure === 0x47413934) { - var userDataType = expGolombDecoder.readUByte(); - - // Raw CEA-608 bytes wrapped in CEA-708 packet - if (userDataType === 3) { - var firstByte = expGolombDecoder.readUByte(); - var secondByte = expGolombDecoder.readUByte(); - - var totalCCs = 31 & firstByte; - var byteArray = [firstByte, secondByte]; - - for (i = 0; i < totalCCs; i++) { - // 3 bytes per CC - byteArray.push(expGolombDecoder.readUByte()); - byteArray.push(expGolombDecoder.readUByte()); - byteArray.push(expGolombDecoder.readUByte()); - } - - _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray }); - } - } - } - } - } else if (payloadSize < expGolombDecoder.bytesAvailable) { - for (i = 0; i < payloadSize; i++) { - expGolombDecoder.readUByte(); - } - } - } - break; - //SPS - case 7: - push = true; - spsfound = true; - if (debug && avcSample) { - avcSample.debug += 'SPS '; - } - if (!track.sps) { - expGolombDecoder = new _expGolomb2.default(unit.data); - var config = expGolombDecoder.readSPS(); - track.width = config.width; - track.height = config.height; - track.pixelRatio = config.pixelRatio; - track.sps = [unit.data]; - track.duration = _this._duration; - var codecarray = unit.data.subarray(1, 4); - var codecstring = 'avc1.'; - for (i = 0; i < 3; i++) { - var h = codecarray[i].toString(16); - if (h.length < 2) { - h = '0' + h; - } - codecstring += h; - } - track.codec = codecstring; - } - break; - //PPS - case 8: - push = true; - if (debug && avcSample) { - avcSample.debug += 'PPS '; - } - if (!track.pps) { - track.pps = [unit.data]; - } - break; - // AUD - case 9: - push = false; - if (avcSample) { - _this.pushAccesUnit(avcSample, track); - } - avcSample = _this.avcSample = _this._createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : ''); - break; - // Filler Data - case 12: - push = false; - break; - default: - push = false; - if (avcSample) { - avcSample.debug += 'unknown NAL ' + unit.type + ' '; - } - break; - } - if (avcSample && push) { - var _units = avcSample.units; - _units.push(unit); - } - }); - // if last PES packet, push samples - if (last && avcSample) { - this.pushAccesUnit(avcSample, track); - this.avcSample = null; - } - } - }, { - key: '_createAVCSample', - value: function _createAVCSample(key, pts, dts, debug) { - return { key: key, pts: pts, dts: dts, units: [], debug: debug }; - } - }, { - key: '_insertSampleInOrder', - value: function _insertSampleInOrder(arr, data) { - var len = arr.length; - if (len > 0) { - if (data.pts >= arr[len - 1].pts) { - arr.push(data); - } else { - for (var pos = len - 1; pos >= 0; pos--) { - if (data.pts < arr[pos].pts) { - arr.splice(pos, 0, data); - break; - } - } - } - } else { - arr.push(data); - } - } - }, { - key: '_getLastNalUnit', - value: function _getLastNalUnit() { - var avcSample = this.avcSample, - lastUnit = void 0; - // try to fallback to previous sample if current one is empty - if (!avcSample || avcSample.units.length === 0) { - var track = this._avcTrack, - samples = track.samples; - avcSample = samples[samples.length - 1]; - } - if (avcSample) { - var units = avcSample.units; - lastUnit = units[units.length - 1]; - } - return lastUnit; - } - }, { - key: '_parseAVCNALu', - value: function _parseAVCNALu(array) { - var i = 0, - len = array.byteLength, - value, - overflow, - track = this._avcTrack, - state = track.naluState || 0, - lastState = state; - var units = [], - unit, - unitType, - lastUnitStart = -1, - lastUnitType; - //logger.log('PES:' + Hex.hexDump(array)); - - if (state === -1) { - // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet - lastUnitStart = 0; - // NALu type is value read from offset 0 - lastUnitType = array[0] & 0x1f; - state = 0; - i = 1; - } - - while (i < len) { - value = array[i++]; - // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case - if (!state) { - state = value ? 0 : 1; - continue; - } - if (state === 1) { - state = value ? 0 : 2; - continue; - } - // here we have state either equal to 2 or 3 - if (!value) { - state = 3; - } else if (value === 1) { - if (lastUnitStart >= 0) { - unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType }; - //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength); - units.push(unit); - } else { - // lastUnitStart is undefined => this is the first start code found in this PES packet - // first check if start code delimiter is overlapping between 2 PES packets, - // ie it started in last packet (lastState not zero) - // and ended at the beginning of this PES packet (i <= 4 - lastState) - var lastUnit = this._getLastNalUnit(); - if (lastUnit) { - if (lastState && i <= 4 - lastState) { - // start delimiter overlapping between PES packets - // strip start delimiter bytes from the end of last NAL unit - // check if lastUnit had a state different from zero - if (lastUnit.state) { - // strip last bytes - lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState); - } - } - // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit. - overflow = i - state - 1; - if (overflow > 0) { - //logger.log('first NALU found with overflow:' + overflow); - var tmp = new Uint8Array(lastUnit.data.byteLength + overflow); - tmp.set(lastUnit.data, 0); - tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength); - lastUnit.data = tmp; - } - } - } - // check if we can read unit type - if (i < len) { - unitType = array[i] & 0x1f; - //logger.log('find NALU @ offset:' + i + ',type:' + unitType); - lastUnitStart = i; - lastUnitType = unitType; - state = 0; - } else { - // not enough byte to read unit type. let's read it on next PES parsing - state = -1; - } - } else { - state = 0; - } - } - if (lastUnitStart >= 0 && state >= 0) { - unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state }; - units.push(unit); - //logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state); - } - // no NALu found - if (units.length === 0) { - // append pes.data to previous NAL unit - var _lastUnit = this._getLastNalUnit(); - if (_lastUnit) { - var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength); - _tmp.set(_lastUnit.data, 0); - _tmp.set(array, _lastUnit.data.byteLength); - _lastUnit.data = _tmp; - } - } - track.naluState = state; - return units; - } - - /** - * remove Emulation Prevention bytes from a RBSP - */ - - }, { - key: 'discardEPB', - value: function discardEPB(data) { - var length = data.byteLength, - EPBPositions = [], - i = 1, - newLength, - newData; - - // Find all `Emulation Prevention Bytes` - while (i < length - 2) { - if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) { - EPBPositions.push(i + 2); - i += 2; - } else { - i++; - } - } - - // If no Emulation Prevention Bytes were found just return the original - // array - if (EPBPositions.length === 0) { - return data; - } - - // Create a new array to hold the NAL unit data - newLength = length - EPBPositions.length; - newData = new Uint8Array(newLength); - var sourceIndex = 0; - - for (i = 0; i < newLength; sourceIndex++, i++) { - if (sourceIndex === EPBPositions[0]) { - // Skip this byte - sourceIndex++; - // Remove this position index - EPBPositions.shift(); - } - newData[i] = data[sourceIndex]; - } - return newData; - } - }, { - key: '_parseAACPES', - value: function _parseAACPES(pes) { - var track = this._audioTrack, - data = pes.data, - pts = pes.pts, - startOffset = 0, - aacOverFlow = this.aacOverFlow, - aacLastPTS = this.aacLastPTS, - frameDuration, - frameIndex, - offset, - stamp, - len; - if (aacOverFlow) { - var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength); - tmp.set(aacOverFlow, 0); - tmp.set(data, aacOverFlow.byteLength); - //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`); - data = tmp; - } - // look for ADTS header (0xFFFx) - for (offset = startOffset, len = data.length; offset < len - 1; offset++) { - if (_adts2.default.isHeader(data, offset)) { - break; - } - } - // if ADTS header does not start straight from the beginning of the PES payload, raise an error - if (offset) { - var reason, fatal; - if (offset < len - 1) { - reason = 'AAC PES did not start with ADTS header,offset:' + offset; - fatal = false; - } else { - reason = 'no ADTS header found in AAC PES'; - fatal = true; - } - _logger.logger.warn('parsing error:' + reason); - this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason }); - if (fatal) { - return; - } - } - - _adts2.default.initTrackConfig(track, this.observer, data, offset, this.audioCodec); - frameIndex = 0; - frameDuration = _adts2.default.getFrameDuration(track.samplerate); - - // if last AAC frame is overflowing, we should ensure timestamps are contiguous: - // first sample PTS should be equal to last sample PTS + frameDuration - if (aacOverFlow && aacLastPTS) { - var newPTS = aacLastPTS + frameDuration; - if (Math.abs(newPTS - pts) > 1) { - _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90)); - pts = newPTS; - } - } - - //scan for aac samples - while (offset < len) { - if (_adts2.default.isHeader(data, offset) && offset + 5 < len) { - var frame = _adts2.default.appendFrame(track, data, offset, pts, frameIndex); - if (frame) { - //logger.log(`${Math.round(frame.sample.pts)} : AAC`); - offset += frame.length; - stamp = frame.sample.pts; - frameIndex++; - } else { - //logger.log('Unable to parse AAC frame'); - break; - } - } else { - //nothing found, keep looking - offset++; - } - } - - if (offset < len) { - aacOverFlow = data.subarray(offset, len); - //logger.log(`AAC: overflow detected:${len-offset}`); - } else { - aacOverFlow = null; - } - this.aacOverFlow = aacOverFlow; - this.aacLastPTS = stamp; - } - }, { - key: '_parseMPEGPES', - value: function _parseMPEGPES(pes) { - var data = pes.data; - var length = data.length; - var frameIndex = 0; - var offset = 0; - var pts = pes.pts; - - while (offset < length) { - if (_mpegaudio2.default.isHeader(data, offset)) { - var frame = _mpegaudio2.default.appendFrame(this._audioTrack, data, offset, pts, frameIndex); - if (frame) { - offset += frame.length; - frameIndex++; - } else { - //logger.log('Unable to parse Mpeg audio frame'); - break; - } - } else { - //nothing found, keep looking - offset++; - } - } - } - }, { - key: '_parseID3PES', - value: function _parseID3PES(pes) { - this._id3Track.samples.push(pes); - } - }], [{ - key: 'probe', - value: function probe(data) { - // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47 - if (data.length >= 3 * 188 && data[0] === 0x47 && data[188] === 0x47 && data[2 * 188] === 0x47) { - return true; - } else { - return false; - } - } - }]); - - return TSDemuxer; -}(); - -exports.default = TSDemuxer; - -},{"22":22,"26":26,"30":30,"31":31,"33":33,"35":35,"54":54}],33:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var ErrorTypes = exports.ErrorTypes = { - // Identifier for a network error (loading error / timeout ...) - NETWORK_ERROR: 'networkError', - // Identifier for a media Error (video/parsing/mediasource error) - MEDIA_ERROR: 'mediaError', - // Identifier for a mux Error (demuxing/remuxing) - MUX_ERROR: 'muxError', - // Identifier for all other errors - OTHER_ERROR: 'otherError' -}; - -var ErrorDetails = exports.ErrorDetails = { - // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }} - MANIFEST_LOAD_ERROR: 'manifestLoadError', - // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }} - MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut', - // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason} - MANIFEST_PARSING_ERROR: 'manifestParsingError', - // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason} - MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError', - // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }} - LEVEL_LOAD_ERROR: 'levelLoadError', - // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }} - LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut', - // Identifier for a level switch error - data: { level : faulty level Id, event : error description} - LEVEL_SWITCH_ERROR: 'levelSwitchError', - // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }} - AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError', - // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }} - AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut', - // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }} - FRAG_LOAD_ERROR: 'fragLoadError', - // Identifier for fragment loop loading error - data: { frag : fragment object} - FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError', - // Identifier for fragment load timeout error - data: { frag : fragment object} - FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut', - // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description } - FRAG_DECRYPT_ERROR: 'fragDecryptError', - // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description } - // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release - FRAG_PARSING_ERROR: 'fragParsingError', - // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text } - REMUX_ALLOC_ERROR: 'remuxAllocError', - // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }} - KEY_LOAD_ERROR: 'keyLoadError', - // Identifier for decrypt key load timeout error - data: { frag : fragment object} - KEY_LOAD_TIMEOUT: 'keyLoadTimeOut', - // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType } - BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError', - // Identifier for a buffer append error - data: append error description - BUFFER_APPEND_ERROR: 'bufferAppendError', - // Identifier for a buffer appending error event - data: appending error description - BUFFER_APPENDING_ERROR: 'bufferAppendingError', - // Identifier for a buffer stalled error event - BUFFER_STALLED_ERROR: 'bufferStalledError', - // Identifier for a buffer full event - BUFFER_FULL_ERROR: 'bufferFullError', - // Identifier for a buffer seek over hole event - BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole', - // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area) - BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall', - // Identifier for an internal exception happening inside hls.js while handling an event - INTERNAL_EXCEPTION: 'internalException', - // Malformed WebVTT contents - WEBVTT_EXCEPTION: 'webVTTException' -}; - -},{}],34:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof$$1 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* - * - * All objects in the event handling chain should inherit from this class - * - */ - -var _logger = _dereq_(54); - -var _errors = _dereq_(33); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var EventHandler = function () { - function EventHandler(hls) { - _classCallCheck$$1(this, EventHandler); - - this.hls = hls; - this.onEvent = this.onEvent.bind(this); - - for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - events[_key - 1] = arguments[_key]; - } - - this.handledEvents = events; - this.useGenericHandler = true; - - this.registerListeners(); - } - - _createClass$$1(EventHandler, [{ - key: 'destroy', - value: function destroy() { - this.unregisterListeners(); - } - }, { - key: 'isEventHandler', - value: function isEventHandler() { - return _typeof$$1(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function'; - } - }, { - key: 'registerListeners', - value: function registerListeners() { - if (this.isEventHandler()) { - this.handledEvents.forEach(function (event) { - if (event === 'hlsEventGeneric') { - throw new Error('Forbidden event name: ' + event); - } - this.hls.on(event, this.onEvent); - }, this); - } - } - }, { - key: 'unregisterListeners', - value: function unregisterListeners() { - if (this.isEventHandler()) { - this.handledEvents.forEach(function (event) { - this.hls.off(event, this.onEvent); - }, this); - } - } - - /** - * arguments: event (string), data (any) - */ - - }, { - key: 'onEvent', - value: function onEvent(event, data) { - this.onEventGeneric(event, data); - } - }, { - key: 'onEventGeneric', - value: function onEventGeneric(event, data) { - var eventToFunction = function eventToFunction(event, data) { - var funcName = 'on' + event.replace('hls', ''); - if (typeof this[funcName] !== 'function') { - throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')'); - } - return this[funcName].bind(this, data); - }; - try { - eventToFunction.call(this, event, data).call(); - } catch (err) { - _logger.logger.error('internal error happened while processing ' + event + ':' + err.message); - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err }); - } - } - }]); - - return EventHandler; -}(); - -exports.default = EventHandler; - -},{"33":33,"35":35,"54":54}],35:[function(_dereq_,module,exports){ -'use strict'; - -module.exports = { - // fired before MediaSource is attaching to media element - data: { media } - MEDIA_ATTACHING: 'hlsMediaAttaching', - // fired when MediaSource has been succesfully attached to media element - data: { } - MEDIA_ATTACHED: 'hlsMediaAttached', - // fired before detaching MediaSource from media element - data: { } - MEDIA_DETACHING: 'hlsMediaDetaching', - // fired when MediaSource has been detached from media element - data: { } - MEDIA_DETACHED: 'hlsMediaDetached', - // fired when we buffer is going to be reset - data: { } - BUFFER_RESET: 'hlsBufferReset', - // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }} - BUFFER_CODECS: 'hlsBufferCodecs', - // fired when sourcebuffers have been created - data: { tracks : tracks } - BUFFER_CREATED: 'hlsBufferCreated', - // fired when we append a segment to the buffer - data: { segment: segment object } - BUFFER_APPENDING: 'hlsBufferAppending', - // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent} - BUFFER_APPENDED: 'hlsBufferAppended', - // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { } - BUFFER_EOS: 'hlsBufferEos', - // fired when the media buffer should be flushed - data { startOffset, endOffset } - BUFFER_FLUSHING: 'hlsBufferFlushing', - // fired when the media buffer has been flushed - data: { } - BUFFER_FLUSHED: 'hlsBufferFlushed', - // fired to signal that a manifest loading starts - data: { url : manifestURL} - MANIFEST_LOADING: 'hlsManifestLoading', - // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}} - MANIFEST_LOADED: 'hlsManifestLoaded', - // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest} - MANIFEST_PARSED: 'hlsManifestParsed', - // fired when a level switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING - LEVEL_SWITCH: 'hlsLevelSwitch', - // fired when a level switch is requested - data: { level : id of new level } - LEVEL_SWITCHING: 'hlsLevelSwitching', - // fired when a level switch is effective - data: { level : id of new level } - LEVEL_SWITCHED: 'hlsLevelSwitched', - // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded} - LEVEL_LOADING: 'hlsLevelLoading', - // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} } - LEVEL_LOADED: 'hlsLevelLoaded', - // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level } - LEVEL_UPDATED: 'hlsLevelUpdated', - // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment } - LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated', - // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks } - AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated', - // fired when an audio track switch occurs - data: { id : audio track id } // deprecated in favor AUDIO_TRACK_SWITCHING - AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch', - // fired when an audio track switching is requested - data: { id : audio track id } - AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching', - // fired when an audio track switch actually occurs - data: { id : audio track id } - AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched', - // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id } - AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading', - // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } } - AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded', - // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks } - SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated', - // fired when an subtitle track switch occurs - data: { id : subtitle track id } - SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch', - // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id } - SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading', - // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } } - SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded', - // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag } - SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed', - // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object } - INIT_PTS_FOUND: 'hlsInitPtsFound', - // fired when a fragment loading starts - data: { frag : fragment object } - FRAG_LOADING: 'hlsFragLoading', - // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } } - FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress', - // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object } - FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted', - // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } } - FRAG_LOADED: 'hlsFragLoaded', - // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, stats : { tstart, tdecrypt } } - FRAG_DECRYPTED: 'hlsFragDecrypted', - // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment } - FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment', - // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] } - FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata', - // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] } - FRAG_PARSING_METADATA: 'hlsFragParsingMetadata', - // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null} - FRAG_PARSING_DATA: 'hlsFragParsingData', - // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object } - FRAG_PARSED: 'hlsFragParsed', - // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } } - FRAG_BUFFERED: 'hlsFragBuffered', - // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object } - FRAG_CHANGED: 'hlsFragChanged', - // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames } - FPS_DROP: 'hlsFpsDrop', - //triggered when FPS drop triggers auto level capping - data: { level, droppedlevel } - FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping', - // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data } - ERROR: 'hlsError', - // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { } - DESTROYING: 'hlsDestroying', - // fired when a decrypt key loading starts - data: { frag : fragment object } - KEY_LOADING: 'hlsKeyLoading', - // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } } - KEY_LOADED: 'hlsKeyLoaded', - // fired upon stream controller state transitions - data: { previousState, nextState } - STREAM_STATE_TRANSITION: 'hlsStreamStateTransition' -}; - -},{}],36:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * AAC helper - */ - -var AAC = function () { - function AAC() { - _classCallCheck$$1(this, AAC); - } - - _createClass$$1(AAC, null, [{ - key: 'getSilentFrame', - value: function getSilentFrame(codec, channelCount) { - switch (codec) { - case 'mp4a.40.2': - if (channelCount === 1) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); - } else if (channelCount === 2) { - return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); - } else if (channelCount === 3) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); - } else if (channelCount === 4) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); - } else if (channelCount === 5) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); - } else if (channelCount === 6) { - return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]); - } - break; - // handle HE-AAC below (mp4a.40.5 / mp4a.40.29) - default: - if (channelCount === 1) { - // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac - return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); - } else if (channelCount === 2) { - // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac - return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); - } else if (channelCount === 3) { - // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac - return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); - } - break; - } - return null; - } - }]); - - return AAC; -}(); - -exports.default = AAC; - -},{}],37:[function(_dereq_,module,exports){ -"use strict"; - -/** - * Buffer Helper utils, providing methods dealing buffer length retrieval -*/ - -var BufferHelper = { - isBuffered: function isBuffered(media, position) { - if (media) { - var buffered = media.buffered; - for (var i = 0; i < buffered.length; i++) { - if (position >= buffered.start(i) && position <= buffered.end(i)) { - return true; - } - } - } - return false; - }, - - bufferInfo: function bufferInfo(media, pos, maxHoleDuration) { - if (media) { - var vbuffered = media.buffered, - buffered = [], - i; - for (i = 0; i < vbuffered.length; i++) { - buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); - } - return this.bufferedInfo(buffered, pos, maxHoleDuration); - } else { - return { len: 0, start: pos, end: pos, nextStart: undefined }; - } - }, - - bufferedInfo: function bufferedInfo(buffered, pos, maxHoleDuration) { - var buffered2 = [], - - // bufferStart and bufferEnd are buffer boundaries around current video position - bufferLen, - bufferStart, - bufferEnd, - bufferStartNext, - i; - // sort on buffer.start/smaller end (IE does not always return sorted buffered range) - buffered.sort(function (a, b) { - var diff = a.start - b.start; - if (diff) { - return diff; - } else { - return b.end - a.end; - } - }); - // there might be some small holes between buffer time range - // consider that holes smaller than maxHoleDuration are irrelevant and build another - // buffer time range representations that discards those holes - for (i = 0; i < buffered.length; i++) { - var buf2len = buffered2.length; - if (buf2len) { - var buf2end = buffered2[buf2len - 1].end; - // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative) - if (buffered[i].start - buf2end < maxHoleDuration) { - // merge overlapping time ranges - // update lastRange.end only if smaller than item.end - // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end) - // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15]) - if (buffered[i].end > buf2end) { - buffered2[buf2len - 1].end = buffered[i].end; - } - } else { - // big hole - buffered2.push(buffered[i]); - } - } else { - // first value - buffered2.push(buffered[i]); - } - } - for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) { - var start = buffered2[i].start, - end = buffered2[i].end; - //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i)); - if (pos + maxHoleDuration >= start && pos < end) { - // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length - bufferStart = start; - bufferEnd = end; - bufferLen = bufferEnd - pos; - } else if (pos + maxHoleDuration < start) { - bufferStartNext = start; - break; - } - } - return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext }; - } -}; - -module.exports = BufferHelper; - -},{}],38:[function(_dereq_,module,exports){ -'use strict'; - -var _logger = _dereq_(54); - -var LevelHelper = { - - mergeDetails: function mergeDetails(oldDetails, newDetails) { - var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN, - end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN, - delta = newDetails.startSN - oldDetails.startSN, - oldfragments = oldDetails.fragments, - newfragments = newDetails.fragments, - ccOffset = 0, - PTSFrag; - - // check if old/new playlists have fragments in common - if (end < start) { - newDetails.PTSKnown = false; - return; - } - // loop through overlapping SN and update startPTS , cc, and duration if any found - for (var i = start; i <= end; i++) { - var oldFrag = oldfragments[delta + i], - newFrag = newfragments[i]; - if (newFrag && oldFrag) { - ccOffset = oldFrag.cc - newFrag.cc; - if (!isNaN(oldFrag.startPTS)) { - newFrag.start = newFrag.startPTS = oldFrag.startPTS; - newFrag.endPTS = oldFrag.endPTS; - newFrag.duration = oldFrag.duration; - newFrag.backtracked = oldFrag.backtracked; - newFrag.dropped = oldFrag.dropped; - PTSFrag = newFrag; - } - } - } - - if (ccOffset) { - _logger.logger.log('discontinuity sliding from playlist, take drift into account'); - for (i = 0; i < newfragments.length; i++) { - newfragments[i].cc += ccOffset; - } - } - - // if at least one fragment contains PTS info, recompute PTS information for all fragments - if (PTSFrag) { - LevelHelper.updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS); - } else { - // ensure that delta is within oldfragments range - // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61]) - // in that case we also need to adjust start offset of all fragments - if (delta >= 0 && delta < oldfragments.length) { - // adjust start by sliding offset - var sliding = oldfragments[delta].start; - for (i = 0; i < newfragments.length; i++) { - newfragments[i].start += sliding; - } - } - } - // if we are here, it means we have fragments overlapping between - // old and new level. reliable PTS info is thus relying on old level - newDetails.PTSKnown = oldDetails.PTSKnown; - return; - }, - - updateFragPTSDTS: function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) { - // update frag PTS/DTS - var maxStartPTS = startPTS; - if (!isNaN(frag.startPTS)) { - // delta PTS between audio and video - var deltaPTS = Math.abs(frag.startPTS - startPTS); - if (isNaN(frag.deltaPTS)) { - frag.deltaPTS = deltaPTS; - } else { - frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS); - } - maxStartPTS = Math.max(startPTS, frag.startPTS); - startPTS = Math.min(startPTS, frag.startPTS); - endPTS = Math.max(endPTS, frag.endPTS); - startDTS = Math.min(startDTS, frag.startDTS); - endDTS = Math.max(endDTS, frag.endDTS); - } - - var drift = startPTS - frag.start; - frag.start = frag.startPTS = startPTS; - frag.maxStartPTS = maxStartPTS; - frag.endPTS = endPTS; - frag.startDTS = startDTS; - frag.endDTS = endDTS; - frag.duration = endPTS - startPTS; - - var sn = frag.sn; - // exit if sn out of range - if (!details || sn < details.startSN || sn > details.endSN) { - return 0; - } - var fragIdx, fragments, i; - fragIdx = sn - details.startSN; - fragments = details.fragments; - frag = fragments[fragIdx]; - // adjust fragment PTS/duration from seqnum-1 to frag 0 - for (i = fragIdx; i > 0; i--) { - LevelHelper.updatePTS(fragments, i, i - 1); - } - - // adjust fragment PTS/duration from seqnum to last frag - for (i = fragIdx; i < fragments.length - 1; i++) { - LevelHelper.updatePTS(fragments, i, i + 1); - } - details.PTSKnown = true; - //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`); - - return drift; - }, - - updatePTS: function updatePTS(fragments, fromIdx, toIdx) { - var fragFrom = fragments[fromIdx], - fragTo = fragments[toIdx], - fragToPTS = fragTo.startPTS; - // if we know startPTS[toIdx] - if (!isNaN(fragToPTS)) { - // update fragment duration. - // it helps to fix drifts between playlist reported duration and fragment real duration - if (toIdx > fromIdx) { - fragFrom.duration = fragToPTS - fragFrom.start; - if (fragFrom.duration < 0) { - _logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!'); - } - } else { - fragTo.duration = fragFrom.start - fragToPTS; - if (fragTo.duration < 0) { - _logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!'); - } - } - } else { - // we dont know startPTS[toIdx] - if (toIdx > fromIdx) { - fragTo.start = fragFrom.start + fragFrom.duration; - } else { - fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0); - } - } - } -}; /** - * Level Helper class, providing methods dealing with playlist sliding and drift - */ - -module.exports = LevelHelper; - -},{"54":54}],39:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * HLS interface - */ - - -var _urlToolkit = _dereq_(2); - -var _urlToolkit2 = _interopRequireDefault(_urlToolkit); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _errors = _dereq_(33); - -var _playlistLoader = _dereq_(43); - -var _playlistLoader2 = _interopRequireDefault(_playlistLoader); - -var _fragmentLoader = _dereq_(41); - -var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader); - -var _keyLoader = _dereq_(42); - -var _keyLoader2 = _interopRequireDefault(_keyLoader); - -var _streamController = _dereq_(13); - -var _streamController2 = _interopRequireDefault(_streamController); - -var _levelController = _dereq_(12); - -var _levelController2 = _interopRequireDefault(_levelController); - -var _id3TrackController = _dereq_(11); - -var _id3TrackController2 = _interopRequireDefault(_id3TrackController); - -var _logger = _dereq_(54); - -var _events3 = _dereq_(1); - -var _events4 = _interopRequireDefault(_events3); - -var _config = _dereq_(4); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Hls = function () { - _createClass$$1(Hls, null, [{ - key: 'isSupported', - value: function isSupported() { - var mediaSource = window.MediaSource = window.MediaSource || window.WebKitMediaSource; - var sourceBuffer = window.SourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer; - var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); - - // if SourceBuffer is exposed ensure its API is valid - // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible - var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function'; - return isTypeSupported && sourceBufferValidAPI; - } - }, { - key: 'version', - get: function get() { - // replaced with browserify-versionify transform - return '0.7.10'; - } - }, { - key: 'Events', - get: function get() { - return _events2.default; - } - }, { - key: 'ErrorTypes', - get: function get() { - return _errors.ErrorTypes; - } - }, { - key: 'ErrorDetails', - get: function get() { - return _errors.ErrorDetails; - } - }, { - key: 'DefaultConfig', - get: function get() { - if (!Hls.defaultConfig) { - return _config.hlsDefaultConfig; - } - return Hls.defaultConfig; - }, - set: function set(defaultConfig) { - Hls.defaultConfig = defaultConfig; - } - }]); - - function Hls() { - var _this = this; - - var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck$$1(this, Hls); - - var defaultConfig = Hls.DefaultConfig; - - if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) { - throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration'); - } - - for (var prop in defaultConfig) { - if (prop in config) { - continue; - } - config[prop] = defaultConfig[prop]; - } - - if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) { - throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"'); - } - - if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) { - throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"'); - } - - (0, _logger.enableLogs)(config.debug); - this.config = config; - this._autoLevelCapping = -1; - // observer setup - var observer = this.observer = new _events4.default(); - observer.trigger = function trigger(event) { - for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - data[_key - 1] = arguments[_key]; - } - - observer.emit.apply(observer, [event, event].concat(data)); - }; - - observer.off = function off(event) { - for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - data[_key2 - 1] = arguments[_key2]; - } - - observer.removeListener.apply(observer, [event].concat(data)); - }; - this.on = observer.on.bind(observer); - this.off = observer.off.bind(observer); - this.trigger = observer.trigger.bind(observer); - - // core controllers and network loaders - var abrController = this.abrController = new config.abrController(this); - var bufferController = new config.bufferController(this); - var capLevelController = new config.capLevelController(this); - var fpsController = new config.fpsController(this); - var playListLoader = new _playlistLoader2.default(this); - var fragmentLoader = new _fragmentLoader2.default(this); - var keyLoader = new _keyLoader2.default(this); - var id3TrackController = new _id3TrackController2.default(this); - - // network controllers - var levelController = this.levelController = new _levelController2.default(this); - var streamController = this.streamController = new _streamController2.default(this); - var networkControllers = [levelController, streamController]; - - // optional audio stream controller - var Controller = config.audioStreamController; - if (Controller) { - networkControllers.push(new Controller(this)); - } - this.networkControllers = networkControllers; - - var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController]; - - // optional audio track and subtitle controller - Controller = config.audioTrackController; - if (Controller) { - var audioTrackController = new Controller(this); - this.audioTrackController = audioTrackController; - coreComponents.push(audioTrackController); - } - - Controller = config.subtitleTrackController; - if (Controller) { - var subtitleTrackController = new Controller(this); - this.subtitleTrackController = subtitleTrackController; - coreComponents.push(subtitleTrackController); - } - - // optional subtitle controller - [config.subtitleStreamController, config.timelineController].forEach(function (Controller) { - if (Controller) { - coreComponents.push(new Controller(_this)); - } - }); - this.coreComponents = coreComponents; - } - - _createClass$$1(Hls, [{ - key: 'destroy', - value: function destroy() { - _logger.logger.log('destroy'); - this.trigger(_events2.default.DESTROYING); - this.detachMedia(); - this.coreComponents.concat(this.networkControllers).forEach(function (component) { - component.destroy(); - }); - this.url = null; - this.observer.removeAllListeners(); - this._autoLevelCapping = -1; - } - }, { - key: 'attachMedia', - value: function attachMedia(media) { - _logger.logger.log('attachMedia'); - this.media = media; - this.trigger(_events2.default.MEDIA_ATTACHING, { media: media }); - } - }, { - key: 'detachMedia', - value: function detachMedia() { - _logger.logger.log('detachMedia'); - this.trigger(_events2.default.MEDIA_DETACHING); - this.media = null; - } - }, { - key: 'loadSource', - value: function loadSource(url) { - url = _urlToolkit2.default.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true }); - _logger.logger.log('loadSource:' + url); - this.url = url; - // when attaching to a source URL, trigger a playlist load - this.trigger(_events2.default.MANIFEST_LOADING, { url: url }); - } - }, { - key: 'startLoad', - value: function startLoad() { - var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1; - - _logger.logger.log('startLoad(' + startPosition + ')'); - this.networkControllers.forEach(function (controller) { - controller.startLoad(startPosition); - }); - } - }, { - key: 'stopLoad', - value: function stopLoad() { - _logger.logger.log('stopLoad'); - this.networkControllers.forEach(function (controller) { - controller.stopLoad(); - }); - } - }, { - key: 'swapAudioCodec', - value: function swapAudioCodec() { - _logger.logger.log('swapAudioCodec'); - this.streamController.swapAudioCodec(); - } - }, { - key: 'recoverMediaError', - value: function recoverMediaError() { - _logger.logger.log('recoverMediaError'); - var media = this.media; - this.detachMedia(); - this.attachMedia(media); - } - - /** Return all quality levels **/ - - }, { - key: 'levels', - get: function get() { - return this.levelController.levels; - } - - /** Return current playback quality level **/ - - }, { - key: 'currentLevel', - get: function get() { - return this.streamController.currentLevel; - } - - /* set quality level immediately (-1 for automatic level selection) */ - , - set: function set(newLevel) { - _logger.logger.log('set currentLevel:' + newLevel); - this.loadLevel = newLevel; - this.streamController.immediateLevelSwitch(); - } - - /** Return next playback quality level (quality level of next fragment) **/ - - }, { - key: 'nextLevel', - get: function get() { - return this.streamController.nextLevel; - } - - /* set quality level for next fragment (-1 for automatic level selection) */ - , - set: function set(newLevel) { - _logger.logger.log('set nextLevel:' + newLevel); - this.levelController.manualLevel = newLevel; - this.streamController.nextLevelSwitch(); - } - - /** Return the quality level of current/last loaded fragment **/ - - }, { - key: 'loadLevel', - get: function get() { - return this.levelController.level; - } - - /* set quality level for current/next loaded fragment (-1 for automatic level selection) */ - , - set: function set(newLevel) { - _logger.logger.log('set loadLevel:' + newLevel); - this.levelController.manualLevel = newLevel; - } - - /** Return the quality level of next loaded fragment **/ - - }, { - key: 'nextLoadLevel', - get: function get() { - return this.levelController.nextLoadLevel; - } - - /** set quality level of next loaded fragment **/ - , - set: function set(level) { - this.levelController.nextLoadLevel = level; - } - - /** Return first level (index of first level referenced in manifest) - **/ - - }, { - key: 'firstLevel', - get: function get() { - return Math.max(this.levelController.firstLevel, this.minAutoLevel); - } - - /** set first level (index of first level referenced in manifest) - **/ - , - set: function set(newLevel) { - _logger.logger.log('set firstLevel:' + newLevel); - this.levelController.firstLevel = newLevel; - } - - /** Return start level (level of first fragment that will be played back) - if not overrided by user, first level appearing in manifest will be used as start level - if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) - **/ - - }, { - key: 'startLevel', - get: function get() { - return this.levelController.startLevel; - } - - /** set start level (level of first fragment that will be played back) - if not overrided by user, first level appearing in manifest will be used as start level - if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) - **/ - , - set: function set(newLevel) { - _logger.logger.log('set startLevel:' + newLevel); - var hls = this; - // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel - if (newLevel !== -1) { - newLevel = Math.max(newLevel, hls.minAutoLevel); - } - hls.levelController.startLevel = newLevel; - } - - /** Return the capping/max level value that could be used by automatic level selection algorithm **/ - - }, { - key: 'autoLevelCapping', - get: function get() { - return this._autoLevelCapping; - } - - /** set the capping/max level value that could be used by automatic level selection algorithm **/ - , - set: function set(newLevel) { - _logger.logger.log('set autoLevelCapping:' + newLevel); - this._autoLevelCapping = newLevel; - } - - /* check if we are in automatic level selection mode */ - - }, { - key: 'autoLevelEnabled', - get: function get() { - return this.levelController.manualLevel === -1; - } - - /* return manual level */ - - }, { - key: 'manualLevel', - get: function get() { - return this.levelController.manualLevel; - } - - /* return min level selectable in auto mode according to config.minAutoBitrate */ - - }, { - key: 'minAutoLevel', - get: function get() { - var hls = this, - levels = hls.levels, - minAutoBitrate = hls.config.minAutoBitrate, - len = levels ? levels.length : 0; - for (var i = 0; i < len; i++) { - var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate; - if (levelNextBitrate > minAutoBitrate) { - return i; - } - } - return 0; - } - - /* return max level selectable in auto mode according to autoLevelCapping */ - - }, { - key: 'maxAutoLevel', - get: function get() { - var hls = this; - var levels = hls.levels; - var autoLevelCapping = hls.autoLevelCapping; - var maxAutoLevel = void 0; - if (autoLevelCapping === -1 && levels && levels.length) { - maxAutoLevel = levels.length - 1; - } else { - maxAutoLevel = autoLevelCapping; - } - return maxAutoLevel; - } - - // return next auto level - - }, { - key: 'nextAutoLevel', - get: function get() { - var hls = this; - // ensure next auto level is between min and max auto level - return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel); - } - - // this setter is used to force next auto level - // this is useful to force a switch down in auto mode : in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example) - // forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller - , - set: function set(nextLevel) { - var hls = this; - hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel); - } - - /** get alternate audio tracks list from playlist **/ - - }, { - key: 'audioTracks', - get: function get() { - var audioTrackController = this.audioTrackController; - return audioTrackController ? audioTrackController.audioTracks : []; - } - - /** get index of the selected audio track (index in audio track lists) **/ - - }, { - key: 'audioTrack', - get: function get() { - var audioTrackController = this.audioTrackController; - return audioTrackController ? audioTrackController.audioTrack : -1; - } - - /** select an audio track, based on its index in audio track lists**/ - , - set: function set(audioTrackId) { - var audioTrackController = this.audioTrackController; - if (audioTrackController) { - audioTrackController.audioTrack = audioTrackId; - } - } - }, { - key: 'liveSyncPosition', - get: function get() { - return this.streamController.liveSyncPosition; - } - - /** get alternate subtitle tracks list from playlist **/ - - }, { - key: 'subtitleTracks', - get: function get() { - var subtitleTrackController = this.subtitleTrackController; - return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; - } - - /** get index of the selected subtitle track (index in subtitle track lists) **/ - - }, { - key: 'subtitleTrack', - get: function get() { - var subtitleTrackController = this.subtitleTrackController; - return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1; - } - - /** select an subtitle track, based on its index in subtitle track lists**/ - , - set: function set(subtitleTrackId) { - var subtitleTrackController = this.subtitleTrackController; - if (subtitleTrackController) { - subtitleTrackController.subtitleTrack = subtitleTrackId; - } - } - }]); - - return Hls; -}(); - -exports.default = Hls; - -},{"1":1,"11":11,"12":12,"13":13,"2":2,"33":33,"35":35,"4":4,"41":41,"42":42,"43":43,"54":54}],40:[function(_dereq_,module,exports){ -'use strict'; - -// This is mostly for support of the es6 module export -// syntax with the babel compiler, it looks like it doesnt support -// function exports like we are used to in node/commonjs -module.exports = _dereq_(39).default; - -},{"39":39}],41:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _errors = _dereq_(33); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Fragment Loader - */ - -var FragmentLoader = function (_EventHandler) { - _inherits$$1(FragmentLoader, _EventHandler); - - function FragmentLoader(hls) { - _classCallCheck$$1(this, FragmentLoader); - - var _this = _possibleConstructorReturn$$1(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING)); - - _this.loaders = {}; - return _this; - } - - _createClass$$1(FragmentLoader, [{ - key: 'destroy', - value: function destroy() { - var loaders = this.loaders; - for (var loaderName in loaders) { - var loader = loaders[loaderName]; - if (loader) { - loader.destroy(); - } - } - this.loaders = {}; - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'onFragLoading', - value: function onFragLoading(data) { - var frag = data.frag, - type = frag.type, - loader = this.loaders[type], - config = this.hls.config; - - frag.loaded = 0; - if (loader) { - _logger.logger.warn('abort previous fragment loader for type:' + type); - loader.abort(); - } - loader = this.loaders[type] = frag.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config); - - var loaderContext = void 0, - loaderConfig = void 0, - loaderCallbacks = void 0; - loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false }; - var start = frag.byteRangeStartOffset, - end = frag.byteRangeEndOffset; - if (!isNaN(start) && !isNaN(end)) { - loaderContext.rangeStart = start; - loaderContext.rangeEnd = end; - } - loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout }; - loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this), onProgress: this.loadprogress.bind(this) }; - loader.load(loaderContext, loaderConfig, loaderCallbacks); - } - }, { - key: 'loadsuccess', - value: function loadsuccess(response, stats, context) { - var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - var payload = response.data, - frag = context.frag; - // detach fragment loader on load success - frag.loader = undefined; - this.loaders[frag.type] = undefined; - this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails }); - } - }, { - key: 'loaderror', - value: function loaderror(response, context) { - var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - var loader = context.loader; - if (loader) { - loader.abort(); - } - this.loaders[context.type] = undefined; - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails }); - } - }, { - key: 'loadtimeout', - value: function loadtimeout(stats, context) { - var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - var loader = context.loader; - if (loader) { - loader.abort(); - } - this.loaders[context.type] = undefined; - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails }); - } - - // data will be used for progressive parsing - - }, { - key: 'loadprogress', - value: function loadprogress(stats, context, data) { - var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - // jshint ignore:line - var frag = context.frag; - frag.loaded = stats.loaded; - this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails }); - } - }]); - - return FragmentLoader; -}(_eventHandler2.default); - -exports.default = FragmentLoader; - -},{"33":33,"34":34,"35":35,"54":54}],42:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _errors = _dereq_(33); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - * Decrypt key Loader - */ - -var KeyLoader = function (_EventHandler) { - _inherits$$1(KeyLoader, _EventHandler); - - function KeyLoader(hls) { - _classCallCheck$$1(this, KeyLoader); - - var _this = _possibleConstructorReturn$$1(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING)); - - _this.loaders = {}; - _this.decryptkey = null; - _this.decrypturl = null; - return _this; - } - - _createClass$$1(KeyLoader, [{ - key: 'destroy', - value: function destroy() { - for (var loaderName in this.loaders) { - var loader = this.loaders[loaderName]; - if (loader) { - loader.destroy(); - } - } - this.loaders = {}; - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'onKeyLoading', - value: function onKeyLoading(data) { - var frag = data.frag, - type = frag.type, - loader = this.loaders[type], - decryptdata = frag.decryptdata, - uri = decryptdata.uri; - // if uri is different from previous one or if decrypt key not retrieved yet - if (uri !== this.decrypturl || this.decryptkey === null) { - var config = this.hls.config; - - if (loader) { - _logger.logger.warn('abort previous key loader for type:' + type); - loader.abort(); - } - frag.loader = this.loaders[type] = new config.loader(config); - this.decrypturl = uri; - this.decryptkey = null; - - var loaderContext = void 0, - loaderConfig = void 0, - loaderCallbacks = void 0; - loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' }; - loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: config.fragLoadingMaxRetry, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout }; - loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; - frag.loader.load(loaderContext, loaderConfig, loaderCallbacks); - } else if (this.decryptkey) { - // we already loaded this key, return it - decryptdata.key = this.decryptkey; - this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag }); - } - } - }, { - key: 'loadsuccess', - value: function loadsuccess(response, stats, context) { - var frag = context.frag; - this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); - // detach fragment loader on load success - frag.loader = undefined; - this.loaders[frag.type] = undefined; - this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag }); - } - }, { - key: 'loaderror', - value: function loaderror(response, context) { - var frag = context.frag, - loader = frag.loader; - if (loader) { - loader.abort(); - } - this.loaders[context.type] = undefined; - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response }); - } - }, { - key: 'loadtimeout', - value: function loadtimeout(stats, context) { - var frag = context.frag, - loader = frag.loader; - if (loader) { - loader.abort(); - } - this.loaders[context.type] = undefined; - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag }); - } - }]); - - return KeyLoader; -}(_eventHandler2.default); - -exports.default = KeyLoader; - -},{"33":33,"34":34,"35":35,"54":54}],43:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * Playlist Loader - */ - -var _urlToolkit = _dereq_(2); - -var _urlToolkit2 = _interopRequireDefault(_urlToolkit); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _eventHandler = _dereq_(34); - -var _eventHandler2 = _interopRequireDefault(_eventHandler); - -var _errors = _dereq_(33); - -var _attrList = _dereq_(47); - -var _attrList2 = _interopRequireDefault(_attrList); - -var _logger = _dereq_(54); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _possibleConstructorReturn$$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits$$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -// https://regex101.com is your friend -var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g; -var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g; - -var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:,), group 1 => duration, group 2 => title -/|(?!#)(\S+)/.source, // segment URI, group 3 => the URI (note newline is not eaten) -/|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y) -/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec -/|#.*/.source // All other non-segment oriented tags will match with all groups empty -].join(''), 'g'); - -var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/; - -var LevelKey = function () { - function LevelKey() { - _classCallCheck$$1(this, LevelKey); - - this.method = null; - this.key = null; - this.iv = null; - this._uri = null; - } - - _createClass$$1(LevelKey, [{ - key: 'uri', - get: function get() { - if (!this._uri && this.reluri) { - this._uri = _urlToolkit2.default.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true }); - } - return this._uri; - } - }]); - - return LevelKey; -}(); - -var Fragment = function () { - function Fragment() { - _classCallCheck$$1(this, Fragment); - - this._url = null; - this._byteRange = null; - this._decryptdata = null; - this.tagList = []; - } - - _createClass$$1(Fragment, [{ - key: 'createInitializationVector', - - - /** - * Utility method for parseLevelPlaylist to create an initialization vector for a given segment - * @returns {Uint8Array} - */ - value: function createInitializationVector(segmentNumber) { - var uint8View = new Uint8Array(16); - - for (var i = 12; i < 16; i++) { - uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff; - } - - return uint8View; - } - - /** - * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data - * @param levelkey - a playlist's encryption info - * @param segmentNumber - the fragment's segment number - * @returns {*} - an object to be applied as a fragment's decryptdata - */ - - }, { - key: 'fragmentDecryptdataFromLevelkey', - value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) { - var decryptdata = levelkey; - - if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) { - decryptdata = new LevelKey(); - decryptdata.method = levelkey.method; - decryptdata.baseuri = levelkey.baseuri; - decryptdata.reluri = levelkey.reluri; - decryptdata.iv = this.createInitializationVector(segmentNumber); - } - - return decryptdata; - } - }, { - key: 'cloneObj', - value: function cloneObj(obj) { - return JSON.parse(JSON.stringify(obj)); - } - }, { - key: 'url', - get: function get() { - if (!this._url && this.relurl) { - this._url = _urlToolkit2.default.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true }); - } - return this._url; - }, - set: function set(value) { - this._url = value; - } - }, { - key: 'programDateTime', - get: function get() { - if (!this._programDateTime && this.rawProgramDateTime) { - this._programDateTime = new Date(Date.parse(this.rawProgramDateTime)); - } - return this._programDateTime; - } - }, { - key: 'byteRange', - get: function get() { - if (!this._byteRange) { - var byteRange = this._byteRange = []; - if (this.rawByteRange) { - var params = this.rawByteRange.split('@', 2); - if (params.length === 1) { - var lastByteRangeEndOffset = this.lastByteRangeEndOffset; - byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0; - } else { - byteRange[0] = parseInt(params[1]); - } - byteRange[1] = parseInt(params[0]) + byteRange[0]; - } - } - return this._byteRange; - } - }, { - key: 'byteRangeStartOffset', - get: function get() { - return this.byteRange[0]; - } - }, { - key: 'byteRangeEndOffset', - get: function get() { - return this.byteRange[1]; - } - }, { - key: 'decryptdata', - get: function get() { - if (!this._decryptdata) { - this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn); - } - return this._decryptdata; - } - }]); - - return Fragment; -}(); - -var PlaylistLoader = function (_EventHandler) { - _inherits$$1(PlaylistLoader, _EventHandler); - - function PlaylistLoader(hls) { - _classCallCheck$$1(this, PlaylistLoader); - - var _this = _possibleConstructorReturn$$1(this, (PlaylistLoader.__proto__ || Object.getPrototypeOf(PlaylistLoader)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.LEVEL_LOADING, _events2.default.AUDIO_TRACK_LOADING, _events2.default.SUBTITLE_TRACK_LOADING)); - - _this.loaders = {}; - return _this; - } - - _createClass$$1(PlaylistLoader, [{ - key: 'destroy', - value: function destroy() { - for (var loaderName in this.loaders) { - var loader = this.loaders[loaderName]; - if (loader) { - loader.destroy(); - } - } - this.loaders = {}; - _eventHandler2.default.prototype.destroy.call(this); - } - }, { - key: 'onManifestLoading', - value: function onManifestLoading(data) { - this.load(data.url, { type: 'manifest' }); - } - }, { - key: 'onLevelLoading', - value: function onLevelLoading(data) { - this.load(data.url, { type: 'level', level: data.level, id: data.id }); - } - }, { - key: 'onAudioTrackLoading', - value: function onAudioTrackLoading(data) { - this.load(data.url, { type: 'audioTrack', id: data.id }); - } - }, { - key: 'onSubtitleTrackLoading', - value: function onSubtitleTrackLoading(data) { - this.load(data.url, { type: 'subtitleTrack', id: data.id }); - } - }, { - key: 'load', - value: function load(url, context) { - var loader = this.loaders[context.type]; - if (loader) { - var loaderContext = loader.context; - if (loaderContext && loaderContext.url === url) { - _logger.logger.trace('playlist request ongoing'); - return; - } else { - _logger.logger.warn('abort previous loader for type:' + context.type); - loader.abort(); - } - } - var config = this.hls.config, - retry = void 0, - timeout = void 0, - retryDelay = void 0, - maxRetryDelay = void 0; - if (context.type === 'manifest') { - retry = config.manifestLoadingMaxRetry; - timeout = config.manifestLoadingTimeOut; - retryDelay = config.manifestLoadingRetryDelay; - maxRetryDelay = config.manifestLoadingMaxRetryTimeout; - } else { - retry = config.levelLoadingMaxRetry; - timeout = config.levelLoadingTimeOut; - retryDelay = config.levelLoadingRetryDelay; - maxRetryDelay = config.levelLoadingMaxRetryTimeout; - _logger.logger.log('loading playlist for ' + context.type + ' ' + (context.level || context.id)); - } - loader = this.loaders[context.type] = context.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config); - context.url = url; - context.responseType = ''; - - var loaderConfig = void 0, - loaderCallbacks = void 0; - loaderConfig = { timeout: timeout, maxRetry: retry, retryDelay: retryDelay, maxRetryDelay: maxRetryDelay }; - loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; - loader.load(context, loaderConfig, loaderCallbacks); - } - }, { - key: 'resolve', - value: function resolve(url, baseUrl) { - return _urlToolkit2.default.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true }); - } - }, { - key: 'parseMasterPlaylist', - value: function parseMasterPlaylist(string, baseurl) { - var levels = [], - result = void 0; - MASTER_PLAYLIST_REGEX.lastIndex = 0; - while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) { - var level = {}; - - var attrs = level.attrs = new _attrList2.default(result[1]); - level.url = this.resolve(result[2], baseurl); - - var resolution = attrs.decimalResolution('RESOLUTION'); - if (resolution) { - level.width = resolution.width; - level.height = resolution.height; - } - level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'); - level.name = attrs.NAME; - - var codecs = attrs.CODECS; - if (codecs) { - codecs = codecs.split(/[ ,]+/); - for (var i = 0; i < codecs.length; i++) { - var codec = codecs[i]; - if (codec.indexOf('avc1') !== -1) { - level.videoCodec = this.avc1toavcoti(codec); - } else if (codec.indexOf('hvc1') !== -1) { - level.videoCodec = codec; - } else { - level.audioCodec = codec; - } - } - } - - levels.push(level); - } - return levels; - } - }, { - key: 'parseMasterPlaylistMedia', - value: function parseMasterPlaylistMedia(string, baseurl, type) { - var audioCodec = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - var result = void 0, - medias = [], - id = 0; - MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0; - while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) != null) { - var media = {}; - var attrs = new _attrList2.default(result[1]); - if (attrs.TYPE === type) { - media.groupId = attrs['GROUP-ID']; - media.name = attrs.NAME; - media.type = type; - media.default = attrs.DEFAULT === 'YES'; - media.autoselect = attrs.AUTOSELECT === 'YES'; - media.forced = attrs.FORCED === 'YES'; - if (attrs.URI) { - media.url = this.resolve(attrs.URI, baseurl); - } - media.lang = attrs.LANGUAGE; - if (!media.name) { - media.name = media.lang; - } - if (audioCodec) { - media.audioCodec = audioCodec; - } - media.id = id++; - medias.push(media); - } - } - return medias; - } - }, { - key: 'avc1toavcoti', - value: function avc1toavcoti(codec) { - var result, - avcdata = codec.split('.'); - if (avcdata.length > 2) { - result = avcdata.shift() + '.'; - result += parseInt(avcdata.shift()).toString(16); - result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4); - } else { - result = codec; - } - return result; - } - }, { - key: 'parseLevelPlaylist', - value: function parseLevelPlaylist(string, baseurl, id, type) { - var currentSN = 0, - totalduration = 0, - level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 }, - levelkey = new LevelKey(), - cc = 0, - prevFrag = null, - frag = new Fragment(), - result, - i; - - LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0; - - while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) { - var duration = result[1]; - if (duration) { - // INF - frag.duration = parseFloat(duration); - // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 - var title = (' ' + result[2]).slice(1); - frag.title = title ? title : null; - frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]); - } else if (result[3]) { - // url - if (!isNaN(frag.duration)) { - var sn = currentSN++; - frag.type = type; - frag.start = totalduration; - frag.levelkey = levelkey; - frag.sn = sn; - frag.level = id; - frag.cc = cc; - frag.baseurl = baseurl; - // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 - frag.relurl = (' ' + result[3]).slice(1); - - level.fragments.push(frag); - prevFrag = frag; - totalduration += frag.duration; - - frag = new Fragment(); - } - } else if (result[4]) { - // X-BYTERANGE - frag.rawByteRange = (' ' + result[4]).slice(1); - if (prevFrag) { - var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset; - if (lastByteRangeEndOffset) { - frag.lastByteRangeEndOffset = lastByteRangeEndOffset; - } - } - } else if (result[5]) { - // PROGRAM-DATE-TIME - // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 - frag.rawProgramDateTime = (' ' + result[5]).slice(1); - frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]); - } else { - result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW); - for (i = 1; i < result.length; i++) { - if (result[i] !== undefined) { - break; - } - } - - // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 - var value1 = (' ' + result[i + 1]).slice(1); - var value2 = (' ' + result[i + 2]).slice(1); - - switch (result[i]) { - case '#': - frag.tagList.push(value2 ? [value1, value2] : [value1]); - break; - case 'PLAYLIST-TYPE': - level.type = value1.toUpperCase(); - break; - case 'MEDIA-SEQUENCE': - currentSN = level.startSN = parseInt(value1); - break; - case 'TARGETDURATION': - level.targetduration = parseFloat(value1); - break; - case 'VERSION': - level.version = parseInt(value1); - break; - case 'EXTM3U': - break; - case 'ENDLIST': - level.live = false; - break; - case 'DIS': - cc++; - frag.tagList.push(['DIS']); - break; - case 'DISCONTINUITY-SEQ': - cc = parseInt(value1); - break; - case 'KEY': - // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4 - var decryptparams = value1; - var keyAttrs = new _attrList2.default(decryptparams); - var decryptmethod = keyAttrs.enumeratedString('METHOD'), - decrypturi = keyAttrs.URI, - decryptiv = keyAttrs.hexadecimalInteger('IV'); - if (decryptmethod) { - levelkey = new LevelKey(); - if (decrypturi && ['AES-128', 'SAMPLE-AES'].indexOf(decryptmethod) >= 0) { - levelkey.method = decryptmethod; - // URI to get the key - levelkey.baseuri = baseurl; - levelkey.reluri = decrypturi; - levelkey.key = null; - // Initialization Vector (IV) - levelkey.iv = decryptiv; - } - } - break; - case 'START': - var startParams = value1; - var startAttrs = new _attrList2.default(startParams); - var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); - //TIME-OFFSET can be 0 - if (!isNaN(startTimeOffset)) { - level.startTimeOffset = startTimeOffset; - } - break; - case 'MAP': - var mapAttrs = new _attrList2.default(value1); - frag.relurl = mapAttrs.URI; - frag.rawByteRange = mapAttrs.BYTERANGE; - frag.baseurl = baseurl; - frag.level = id; - frag.type = type; - frag.sn = 'initSegment'; - level.initSegment = frag; - frag = new Fragment(); - break; - default: - _logger.logger.warn('line parsed but not handled: ' + result); - break; - } - } - } - frag = prevFrag; - //logger.log('found ' + level.fragments.length + ' fragments'); - if (frag && !frag.relurl) { - level.fragments.pop(); - totalduration -= frag.duration; - } - level.totalduration = totalduration; - level.averagetargetduration = totalduration / level.fragments.length; - level.endSN = currentSN - 1; - return level; - } - }, { - key: 'loadsuccess', - value: function loadsuccess(response, stats, context) { - var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - var string = response.data, - url = response.url, - type = context.type, - id = context.id, - level = context.level, - hls = this.hls; - - this.loaders[type] = undefined; - // responseURL not supported on some browsers (it is used to detect URL redirection) - // data-uri mode also not supported (but no need to detect redirection) - if (url === undefined || url.indexOf('data:') === 0) { - // fallback to initial URL - url = context.url; - } - stats.tload = performance.now(); - //stats.mtime = new Date(target.getResponseHeader('Last-Modified')); - if (string.indexOf('#EXTM3U') === 0) { - if (string.indexOf('#EXTINF:') > 0) { - var isLevel = type !== 'audioTrack' && type !== 'subtitleTrack', - levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0, - levelDetails = this.parseLevelPlaylist(string, url, levelId, type === 'audioTrack' ? 'audio' : type === 'subtitleTrack' ? 'subtitle' : 'main'); - levelDetails.tload = stats.tload; - if (type === 'manifest') { - // first request, stream manifest (no master playlist), fire manifest loaded event with level details - hls.trigger(_events2.default.MANIFEST_LOADED, { levels: [{ url: url, details: levelDetails }], audioTracks: [], url: url, stats: stats, networkDetails: networkDetails }); - } - stats.tparsed = performance.now(); - if (levelDetails.targetduration) { - if (isLevel) { - hls.trigger(_events2.default.LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails }); - } else { - if (type === 'audioTrack') { - hls.trigger(_events2.default.AUDIO_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails }); - } else if (type === 'subtitleTrack') { - hls.trigger(_events2.default.SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails }); - } - } - } else { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration', networkDetails: networkDetails }); - } - } else { - var levels = this.parseMasterPlaylist(string, url); - // multi level playlist, parse level info - if (levels.length) { - var audioTracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO', levels[0].audioCodec); - var subtitles = this.parseMasterPlaylistMedia(string, url, 'SUBTITLES'); - if (audioTracks.length) { - // check if we have found an audio track embedded in main playlist (audio track without URI attribute) - var embeddedAudioFound = false; - audioTracks.forEach(function (audioTrack) { - if (!audioTrack.url) { - embeddedAudioFound = true; - } - }); - // if no embedded audio track defined, but audio codec signaled in quality level, we need to signal this main audio track - // this could happen with playlists with alt audio rendition in which quality levels (main) contains both audio+video. but with mixed audio track not signaled - if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) { - _logger.logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one'); - audioTracks.unshift({ type: 'main', name: 'main' }); - } - } - hls.trigger(_events2.default.MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, url: url, stats: stats, networkDetails: networkDetails }); - } else { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest', networkDetails: networkDetails }); - } - } - } else { - hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter', networkDetails: networkDetails }); - } - } - }, { - key: 'loaderror', - value: function loaderror(response, context) { - var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - var details, - fatal, - loader = context.loader; - switch (context.type) { - case 'manifest': - details = _errors.ErrorDetails.MANIFEST_LOAD_ERROR; - fatal = true; - break; - case 'level': - details = _errors.ErrorDetails.LEVEL_LOAD_ERROR; - fatal = false; - break; - case 'audioTrack': - details = _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR; - fatal = false; - break; - } - if (loader) { - loader.abort(); - this.loaders[context.type] = undefined; - } - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context: context, networkDetails: networkDetails }); - } - }, { - key: 'loadtimeout', - value: function loadtimeout(stats, context) { - var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - var details, - fatal, - loader = context.loader; - switch (context.type) { - case 'manifest': - details = _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT; - fatal = true; - break; - case 'level': - details = _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT; - fatal = false; - break; - case 'audioTrack': - details = _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT; - fatal = false; - break; - } - if (loader) { - loader.abort(); - this.loaders[context.type] = undefined; - } - this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context: context, networkDetails: networkDetails }); - } - }]); - - return PlaylistLoader; -}(_eventHandler2.default); - -exports.default = PlaylistLoader; - -},{"2":2,"33":33,"34":34,"35":35,"47":47,"54":54}],44:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * Generate MP4 Box -*/ - -//import Hex from '../utils/hex'; - -var UINT32_MAX = Math.pow(2, 32) - 1; - -var MP4 = function () { - function MP4() { - _classCallCheck$$1(this, MP4); - } - - _createClass$$1(MP4, null, [{ - key: 'init', - value: function init() { - MP4.types = { - avc1: [], // codingname - avcC: [], - btrt: [], - dinf: [], - dref: [], - esds: [], - ftyp: [], - hdlr: [], - mdat: [], - mdhd: [], - mdia: [], - mfhd: [], - minf: [], - moof: [], - moov: [], - mp4a: [], - '.mp3': [], - mvex: [], - mvhd: [], - pasp: [], - sdtp: [], - stbl: [], - stco: [], - stsc: [], - stsd: [], - stsz: [], - stts: [], - tfdt: [], - tfhd: [], - traf: [], - trak: [], - trun: [], - trex: [], - tkhd: [], - vmhd: [], - smhd: [] - }; - - var i; - for (i in MP4.types) { - if (MP4.types.hasOwnProperty(i)) { - MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)]; - } - } - - var videoHdlr = new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x00, // pre_defined - 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, // reserved - 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler' - ]); - - var audioHdlr = new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x00, // pre_defined - 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, // reserved - 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler' - ]); - - MP4.HDLR_TYPES = { - 'video': videoHdlr, - 'audio': audioHdlr - }; - - var dref = new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x01, // entry_count - 0x00, 0x00, 0x00, 0x0c, // entry_size - 0x75, 0x72, 0x6c, 0x20, // 'url' type - 0x00, // version 0 - 0x00, 0x00, 0x01 // entry_flags - ]); - - var stco = new Uint8Array([0x00, // version - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x00 // entry_count - ]); - - MP4.STTS = MP4.STSC = MP4.STCO = stco; - - MP4.STSZ = new Uint8Array([0x00, // version - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x00, // sample_size - 0x00, 0x00, 0x00, 0x00]); - MP4.VMHD = new Uint8Array([0x00, // version - 0x00, 0x00, 0x01, // flags - 0x00, 0x00, // graphicsmode - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor - ]); - MP4.SMHD = new Uint8Array([0x00, // version - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, // balance - 0x00, 0x00 // reserved - ]); - - MP4.STSD = new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x01]); // entry_count - - var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom - var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1 - var minorVersion = new Uint8Array([0, 0, 0, 1]); - - MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand); - MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref)); - } - }, { - key: 'box', - value: function box(type) { - var payload = Array.prototype.slice.call(arguments, 1), - size = 8, - i = payload.length, - len = i, - result; - // calculate the total size we need to allocate - while (i--) { - size += payload[i].byteLength; - } - result = new Uint8Array(size); - result[0] = size >> 24 & 0xff; - result[1] = size >> 16 & 0xff; - result[2] = size >> 8 & 0xff; - result[3] = size & 0xff; - result.set(type, 4); - // copy the payload into the result - for (i = 0, size = 8; i < len; i++) { - // copy payload[i] array @ offset size - result.set(payload[i], size); - size += payload[i].byteLength; - } - return result; - } - }, { - key: 'hdlr', - value: function hdlr(type) { - return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]); - } - }, { - key: 'mdat', - value: function mdat(data) { - return MP4.box(MP4.types.mdat, data); - } - }, { - key: 'mdhd', - value: function mdhd(timescale, duration) { - duration *= timescale; - var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); - var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); - return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1 - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time - timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale - upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x55, 0xc4, // 'und' language (undetermined) - 0x00, 0x00])); - } - }, { - key: 'mdia', - value: function mdia(track) { - return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track)); - } - }, { - key: 'mfhd', - value: function mfhd(sequenceNumber) { - return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags - sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF])); - } - }, { - key: 'minf', - value: function minf(track) { - if (track.type === 'audio') { - return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track)); - } else { - return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track)); - } - } - }, { - key: 'moof', - value: function moof(sn, baseMediaDecodeTime, track) { - return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime)); - } - /** - * @param tracks... (optional) {array} the tracks associated with this movie - */ - - }, { - key: 'moov', - value: function moov(tracks) { - var i = tracks.length, - boxes = []; - - while (i--) { - boxes[i] = MP4.trak(tracks[i]); - } - - return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks))); - } - }, { - key: 'mvex', - value: function mvex(tracks) { - var i = tracks.length, - boxes = []; - - while (i--) { - boxes[i] = MP4.trex(tracks[i]); - } - return MP4.box.apply(null, [MP4.types.mvex].concat(boxes)); - } - }, { - key: 'mvhd', - value: function mvhd(timescale, duration) { - duration *= timescale; - var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); - var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); - var bytes = new Uint8Array([0x01, // version 1 - 0x00, 0x00, 0x00, // flags - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time - timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale - upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x01, 0x00, 0x00, // 1.0 rate - 0x01, 0x00, // 1.0 volume - 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined - 0xff, 0xff, 0xff, 0xff // next_track_ID - ]); - return MP4.box(MP4.types.mvhd, bytes); - } - }, { - key: 'sdtp', - value: function sdtp(track) { - var samples = track.samples || [], - bytes = new Uint8Array(4 + samples.length), - flags, - i; - // leave the full box header (4 bytes) all zero - // write the sample table - for (i = 0; i < samples.length; i++) { - flags = samples[i].flags; - bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy; - } - - return MP4.box(MP4.types.sdtp, bytes); - } - }, { - key: 'stbl', - value: function stbl(track) { - return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO)); - } - }, { - key: 'avc1', - value: function avc1(track) { - var sps = [], - pps = [], - i, - data, - len; - // assemble the SPSs - - for (i = 0; i < track.sps.length; i++) { - data = track.sps[i]; - len = data.byteLength; - sps.push(len >>> 8 & 0xFF); - sps.push(len & 0xFF); - sps = sps.concat(Array.prototype.slice.call(data)); // SPS - } - - // assemble the PPSs - for (i = 0; i < track.pps.length; i++) { - data = track.pps[i]; - len = data.byteLength; - pps.push(len >>> 8 & 0xFF); - pps.push(len & 0xFF); - pps = pps.concat(Array.prototype.slice.call(data)); - } - - var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version - sps[3], // profile - sps[4], // profile compat - sps[5], // level - 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes - 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets - ].concat(sps).concat([track.pps.length // numOfPictureParameterSets - ]).concat(pps))), - // "PPS" - width = track.width, - height = track.height, - hSpacing = track.pixelRatio[0], - vSpacing = track.pixelRatio[1]; - //console.log('avcc:' + Hex.hexDump(avcc)); - return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, // reserved - 0x00, 0x01, // data_reference_index - 0x00, 0x00, // pre_defined - 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined - width >> 8 & 0xFF, width & 0xff, // width - height >> 8 & 0xFF, height & 0xff, // height - 0x00, 0x48, 0x00, 0x00, // horizresolution - 0x00, 0x48, 0x00, 0x00, // vertresolution - 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x01, // frame_count - 0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js - 0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname - 0x00, 0x18, // depth = 24 - 0x11, 0x11]), // pre_defined = -1 - avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB - 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate - 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate - MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing - hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing - vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF]))); - } - }, { - key: 'esds', - value: function esds(track) { - var configlen = track.config.length; - return new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - - 0x03, // descriptor_type - 0x17 + configlen, // length - 0x00, 0x01, //es_id - 0x00, // stream_priority - - 0x04, // descriptor_type - 0x0f + configlen, // length - 0x40, //codec : mpeg4_audio - 0x15, // stream_type - 0x00, 0x00, 0x00, // buffer_size - 0x00, 0x00, 0x00, 0x00, // maxBitrate - 0x00, 0x00, 0x00, 0x00, // avgBitrate - - 0x05 // descriptor_type - ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor - } - }, { - key: 'mp4a', - value: function mp4a(track) { - var samplerate = track.samplerate; - return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, // reserved - 0x00, 0x01, // data_reference_index - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, track.channelCount, // channelcount - 0x00, 0x10, // sampleSize:16bits - 0x00, 0x00, 0x00, 0x00, // reserved2 - samplerate >> 8 & 0xFF, samplerate & 0xff, // - 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track))); - } - }, { - key: 'mp3', - value: function mp3(track) { - var samplerate = track.samplerate; - return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved - 0x00, 0x00, 0x00, // reserved - 0x00, 0x01, // data_reference_index - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, track.channelCount, // channelcount - 0x00, 0x10, // sampleSize:16bits - 0x00, 0x00, 0x00, 0x00, // reserved2 - samplerate >> 8 & 0xFF, samplerate & 0xff, // - 0x00, 0x00])); - } - }, { - key: 'stsd', - value: function stsd(track) { - if (track.type === 'audio') { - if (!track.isAAC && track.codec === 'mp3') { - return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track)); - } - return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track)); - } else { - return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track)); - } - } - }, { - key: 'tkhd', - value: function tkhd(track) { - var id = track.id, - duration = track.duration * track.timescale, - width = track.width, - height = track.height, - upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)), - lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); - return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1 - 0x00, 0x00, 0x07, // flags - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time - id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID - 0x00, 0x00, 0x00, 0x00, // reserved - upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved - 0x00, 0x00, // layer - 0x00, 0x00, // alternate_group - 0x00, 0x00, // non-audio track volume - 0x00, 0x00, // reserved - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix - width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width - height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height - ])); - } - }, { - key: 'traf', - value: function traf(track, baseMediaDecodeTime) { - var sampleDependencyTable = MP4.sdtp(track), - id = track.id, - upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)), - lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); - return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1 - 0x00, 0x00, 0x00, // flags - upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0XFF, upperWordBaseMediaDecodeTime >> 8 & 0XFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0XFF, lowerWordBaseMediaDecodeTime >> 8 & 0XFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd - 20 + // tfdt - 8 + // traf header - 16 + // mfhd - 8 + // moof header - 8), // mdat header - sampleDependencyTable); - } - - /** - * Generate a track box. - * @param track {object} a track definition - * @return {Uint8Array} the track box - */ - - }, { - key: 'trak', - value: function trak(track) { - track.duration = track.duration || 0xffffffff; - return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track)); - } - }, { - key: 'trex', - value: function trex(track) { - var id = track.id; - return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0 - 0x00, 0x00, 0x00, // flags - id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID - 0x00, 0x00, 0x00, 0x01, // default_sample_description_index - 0x00, 0x00, 0x00, 0x00, // default_sample_duration - 0x00, 0x00, 0x00, 0x00, // default_sample_size - 0x00, 0x01, 0x00, 0x01 // default_sample_flags - ])); - } - }, { - key: 'trun', - value: function trun(track, offset) { - var samples = track.samples || [], - len = samples.length, - arraylen = 12 + 16 * len, - array = new Uint8Array(arraylen), - i, - sample, - duration, - size, - flags, - cts; - offset += 8 + arraylen; - array.set([0x00, // version 0 - 0x00, 0x0f, 0x01, // flags - len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count - offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset - ], 0); - for (i = 0; i < len; i++) { - sample = samples[i]; - duration = sample.duration; - size = sample.size; - flags = sample.flags; - cts = sample.cts; - array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration - size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size - flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags - cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset - ], 12 + 16 * i); - } - return MP4.box(MP4.types.trun, array); - } - }, { - key: 'initSegment', - value: function initSegment(tracks) { - if (!MP4.types) { - MP4.init(); - } - var movie = MP4.moov(tracks), - result; - result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength); - result.set(MP4.FTYP); - result.set(movie, MP4.FTYP.byteLength); - return result; - } - }]); - - return MP4; -}(); - -exports.default = MP4; - -},{}],45:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * fMP4 remuxer - */ - -var _aac = _dereq_(36); - -var _aac2 = _interopRequireDefault(_aac); - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -var _logger = _dereq_(54); - -var _mp4Generator = _dereq_(44); - -var _mp4Generator2 = _interopRequireDefault(_mp4Generator); - -var _errors = _dereq_(33); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -// 10 seconds -var MAX_SILENT_FRAME_DURATION = 10 * 1000; - -var MP4Remuxer = function () { - function MP4Remuxer(observer, config, typeSupported, vendor) { - _classCallCheck$$1(this, MP4Remuxer); - - this.observer = observer; - this.config = config; - this.typeSupported = typeSupported; - var userAgent = navigator.userAgent; - this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS'); - this.ISGenerated = false; - } - - _createClass$$1(MP4Remuxer, [{ - key: 'destroy', - value: function destroy() {} - }, { - key: 'resetTimeStamp', - value: function resetTimeStamp(defaultTimeStamp) { - this._initPTS = this._initDTS = defaultTimeStamp; - } - }, { - key: 'resetInitSegment', - value: function resetInitSegment() { - this.ISGenerated = false; - } - }, { - key: 'remux', - value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { - // generate Init Segment if needed - if (!this.ISGenerated) { - this.generateIS(audioTrack, videoTrack, timeOffset); - } else { - if (accurateTimeOffset) { - // check timestamp consistency. it there is more than 10s gap between expected PTS/DTS, recompute initPTS/DTS - var refPTS = this._initPTS; - var ptsNormalize = this._PTSNormalize; - var timeScale = audioTrack.inputTimeScale || videoTrack.inputTimeScale; - var initPTS = Infinity, - initDTS = Infinity; - var samples = audioTrack.samples; - if (samples.length) { - initPTS = initDTS = ptsNormalize(samples[0].pts - timeScale * timeOffset, refPTS); - } - samples = videoTrack.samples; - if (samples.length) { - var sample = samples[0]; - initPTS = Math.min(initPTS, ptsNormalize(sample.pts - timeScale * timeOffset, refPTS)); - initDTS = Math.min(initDTS, ptsNormalize(sample.dts - timeScale * timeOffset, refPTS)); - } - if (initPTS !== Infinity) { - var initPTSDelta = refPTS - initPTS; - if (Math.abs(initPTSDelta) > 10 * timeScale) { - _logger.logger.warn('timestamp inconsistency, ' + (initPTSDelta / timeScale).toFixed(3) + 's delta against expected value: missing discontinuity ? reset initPTS/initDTS'); - this._initPTS = initPTS; - this._initDTS = initDTS; - this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS }); - } - } - } - } - - if (this.ISGenerated) { - // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is - // calculated in remuxAudio. - //logger.log('nb AAC samples:' + audioTrack.samples.length); - if (audioTrack.samples.length) { - // if initSegment was generated without video samples, regenerate it again - if (!audioTrack.timescale) { - _logger.logger.warn('regenerate InitSegment as audio detected'); - this.generateIS(audioTrack, videoTrack, timeOffset); - } - var audioData = this.remuxAudio(audioTrack, timeOffset, contiguous, accurateTimeOffset); - //logger.log('nb AVC samples:' + videoTrack.samples.length); - if (videoTrack.samples.length) { - var audioTrackLength = void 0; - if (audioData) { - audioTrackLength = audioData.endPTS - audioData.startPTS; - } - // if initSegment was generated without video samples, regenerate it again - if (!videoTrack.timescale) { - _logger.logger.warn('regenerate InitSegment as video detected'); - this.generateIS(audioTrack, videoTrack, timeOffset); - } - this.remuxVideo(videoTrack, timeOffset, contiguous, audioTrackLength, accurateTimeOffset); - } - } else { - var videoData = void 0; - //logger.log('nb AVC samples:' + videoTrack.samples.length); - if (videoTrack.samples.length) { - videoData = this.remuxVideo(videoTrack, timeOffset, contiguous, accurateTimeOffset); - } - if (videoData && audioTrack.codec) { - this.remuxEmptyAudio(audioTrack, timeOffset, contiguous, videoData); - } - } - } - //logger.log('nb ID3 samples:' + audioTrack.samples.length); - if (id3Track.samples.length) { - this.remuxID3(id3Track, timeOffset); - } - //logger.log('nb ID3 samples:' + audioTrack.samples.length); - if (textTrack.samples.length) { - this.remuxText(textTrack, timeOffset); - } - //notify end of parsing - this.observer.trigger(_events2.default.FRAG_PARSED); - } - }, { - key: 'generateIS', - value: function generateIS(audioTrack, videoTrack, timeOffset) { - var observer = this.observer, - audioSamples = audioTrack.samples, - videoSamples = videoTrack.samples, - typeSupported = this.typeSupported, - container = 'audio/mp4', - tracks = {}, - data = { tracks: tracks }, - computePTSDTS = this._initPTS === undefined, - initPTS, - initDTS; - - if (computePTSDTS) { - initPTS = initDTS = Infinity; - } - if (audioTrack.config && audioSamples.length) { - // let's use audio sampling rate as MP4 time scale. - // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC) - // using audio sampling rate here helps having an integer MP4 frame duration - // this avoids potential rounding issue and AV sync issue - audioTrack.timescale = audioTrack.samplerate; - _logger.logger.log('audio sampling rate : ' + audioTrack.samplerate); - if (!audioTrack.isAAC) { - if (typeSupported.mpeg) { - // Chrome and Safari - container = 'audio/mpeg'; - audioTrack.codec = ''; - } else if (typeSupported.mp3) { - // Firefox - audioTrack.codec = 'mp3'; - } - } - tracks.audio = { - container: container, - codec: audioTrack.codec, - initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]), - metadata: { - channelCount: audioTrack.channelCount - } - }; - if (computePTSDTS) { - // remember first PTS of this demuxing context. for audio, PTS = DTS - initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset; - } - } - - if (videoTrack.sps && videoTrack.pps && videoSamples.length) { - // let's use input time scale as MP4 video timescale - // we use input time scale straight away to avoid rounding issues on frame duration / cts computation - var inputTimeScale = videoTrack.inputTimeScale; - videoTrack.timescale = inputTimeScale; - tracks.video = { - container: 'video/mp4', - codec: videoTrack.codec, - initSegment: _mp4Generator2.default.initSegment([videoTrack]), - metadata: { - width: videoTrack.width, - height: videoTrack.height - } - }; - if (computePTSDTS) { - initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset); - initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset); - this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS }); - } - } - - if (Object.keys(tracks).length) { - observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data); - this.ISGenerated = true; - if (computePTSDTS) { - this._initPTS = initPTS; - this._initDTS = initDTS; - } - } else { - observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' }); - } - } - }, { - key: 'remuxVideo', - value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) { - var offset = 8, - timeScale = track.timescale, - mp4SampleDuration, - mdat, - moof, - firstPTS, - firstDTS, - nextDTS, - lastPTS, - lastDTS, - inputSamples = track.samples, - outputSamples = [], - nbSamples = inputSamples.length, - ptsNormalize = this._PTSNormalize, - initDTS = this._initDTS; - - // for (let i = 0; i < track.samples.length; i++) { - // let avcSample = track.samples[i]; - // let units = avcSample.units; - // let unitsString = ''; - // for (let j = 0; j < units.length ; j++) { - // unitsString += units[j].type + ','; - // if (units[j].data.length < 500) { - // unitsString += Hex.hexDump(units[j].data); - // } - // } - // logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length); - // } - - // if parsed fragment is contiguous with last one, let's use last DTS value as reference - var nextAvcDts = this.nextAvcDts; - - var isSafari = this.isSafari; - - // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive - if (isSafari) { - // also consider consecutive fragments as being contiguous (even if a level switch occurs), - // for sake of clarity: - // consecutive fragments are frags with - // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR - // - less than 200 ms PTS gaps (timeScale/5) - contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5); - } - - if (!contiguous) { - // if not contiguous, let's use target timeOffset - nextAvcDts = timeOffset * timeScale; - } - - // PTS is coded on 33bits, and can loop from -2^32 to 2^32 - // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value - inputSamples.forEach(function (sample) { - sample.pts = ptsNormalize(sample.pts - initDTS, nextAvcDts); - sample.dts = ptsNormalize(sample.dts - initDTS, nextAvcDts); - }); - - // sort video samples by DTS then PTS then demux id order - inputSamples.sort(function (a, b) { - var deltadts = a.dts - b.dts; - var deltapts = a.pts - b.pts; - return deltadts ? deltadts : deltapts ? deltapts : a.id - b.id; - }); - - // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale) - var PTSDTSshift = inputSamples.reduce(function (prev, curr) { - return Math.max(Math.min(prev, curr.pts - curr.dts), -18000); - }, 0); - if (PTSDTSshift < 0) { - _logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue'); - for (var i = 0; i < inputSamples.length; i++) { - inputSamples[i].dts += PTSDTSshift; - } - } - - // compute first DTS and last DTS, normalize them against reference value - var sample = inputSamples[0]; - firstDTS = Math.max(sample.dts, 0); - firstPTS = Math.max(sample.pts, 0); - - // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole) - var delta = Math.round((firstDTS - nextAvcDts) / 90); - // if fragment are contiguous, detect hole/overlapping between fragments - if (contiguous) { - if (delta) { - if (delta > 1) { - _logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it'); - } else if (delta < -1) { - _logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected'); - } - // remove hole/gap : set DTS to next expected DTS - firstDTS = nextAvcDts; - inputSamples[0].dts = firstDTS; - // offset PTS as well, ensure that PTS is smaller or equal than new DTS - firstPTS = Math.max(firstPTS - delta, nextAvcDts); - inputSamples[0].pts = firstPTS; - _logger.logger.log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms'); - } - } - nextDTS = firstDTS; - - // compute lastPTS/lastDTS - sample = inputSamples[inputSamples.length - 1]; - lastDTS = Math.max(sample.dts, 0); - lastPTS = Math.max(sample.pts, 0, lastDTS); - - // on Safari let's signal the same sample duration for all samples - // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS - // set this constant duration as being the avg delta between consecutive DTS. - if (isSafari) { - mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1)); - } - - var nbNalu = 0, - naluLen = 0; - for (var _i = 0; _i < nbSamples; _i++) { - // compute total/avc sample length and nb of NAL units - var _sample = inputSamples[_i], - units = _sample.units, - nbUnits = units.length, - sampleLen = 0; - for (var j = 0; j < nbUnits; j++) { - sampleLen += units[j].data.length; - } - naluLen += sampleLen; - nbNalu += nbUnits; - _sample.length = sampleLen; - - // normalize PTS/DTS - if (isSafari) { - // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples - _sample.dts = firstDTS + _i * mp4SampleDuration; - } else { - // ensure sample monotonic DTS - _sample.dts = Math.max(_sample.dts, firstDTS); - } - // ensure that computed value is greater or equal than sample DTS - _sample.pts = Math.max(_sample.pts, _sample.dts); - } - - /* concatenate the video data and construct the mdat in place - (need 8 more bytes to fill length and mpdat type) */ - var mdatSize = naluLen + 4 * nbNalu + 8; - try { - mdat = new Uint8Array(mdatSize); - } catch (err) { - this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MUX_ERROR, details: _errors.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize }); - return; - } - var view = new DataView(mdat.buffer); - view.setUint32(0, mdatSize); - mdat.set(_mp4Generator2.default.types.mdat, 4); - - for (var _i2 = 0; _i2 < nbSamples; _i2++) { - var avcSample = inputSamples[_i2], - avcSampleUnits = avcSample.units, - mp4SampleLength = 0, - compositionTimeOffset = void 0; - // convert NALU bitstream to MP4 format (prepend NALU with size field) - for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) { - var unit = avcSampleUnits[_j], - unitData = unit.data, - unitDataLen = unit.data.byteLength; - view.setUint32(offset, unitDataLen); - offset += 4; - mdat.set(unitData, offset); - offset += unitDataLen; - mp4SampleLength += 4 + unitDataLen; - } - - if (!isSafari) { - // expected sample duration is the Decoding Timestamp diff of consecutive samples - if (_i2 < nbSamples - 1) { - mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts; - } else { - var config = this.config, - lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts; - if (config.stretchShortVideoTrack) { - // In some cases, a segment's audio track duration may exceed the video track duration. - // Since we've already remuxed audio, and we know how long the audio track is, we look to - // see if the delta to the next segment is longer than the minimum of maxBufferHole and - // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate - // the duration of the last frame to minimize any potential gap between segments. - var maxBufferHole = config.maxBufferHole, - maxSeekHole = config.maxSeekHole, - gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale), - deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts; - if (deltaToFrameEnd > gapTolerance) { - // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video - // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway. - mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; - if (mp4SampleDuration < 0) { - mp4SampleDuration = lastFrameDuration; - } - _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.'); - } else { - mp4SampleDuration = lastFrameDuration; - } - } else { - mp4SampleDuration = lastFrameDuration; - } - } - compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); - } else { - compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration)); - } - - //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}'); - outputSamples.push({ - size: mp4SampleLength, - // constant duration - duration: mp4SampleDuration, - cts: compositionTimeOffset, - flags: { - isLeading: 0, - isDependedOn: 0, - hasRedundancy: 0, - degradPrio: 0, - dependsOn: avcSample.key ? 2 : 1, - isNonSync: avcSample.key ? 0 : 1 - } - }); - } - // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale) - this.nextAvcDts = lastDTS + mp4SampleDuration; - var dropped = track.dropped; - track.len = 0; - track.nbNalu = 0; - track.dropped = 0; - if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { - var flags = outputSamples[0].flags; - // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue - // https://code.google.com/p/chromium/issues/detail?id=229412 - flags.dependsOn = 2; - flags.isNonSync = 0; - } - track.samples = outputSamples; - moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS, track); - track.samples = []; - - var data = { - data1: moof, - data2: mdat, - startPTS: firstPTS / timeScale, - endPTS: (lastPTS + mp4SampleDuration) / timeScale, - startDTS: firstDTS / timeScale, - endDTS: this.nextAvcDts / timeScale, - type: 'video', - nb: outputSamples.length, - dropped: dropped - }; - this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data); - return data; - } - }, { - key: 'remuxAudio', - value: function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) { - var inputTimeScale = track.inputTimeScale, - mp4timeScale = track.timescale, - scaleFactor = inputTimeScale / mp4timeScale, - mp4SampleDuration = track.isAAC ? 1024 : 1152, - inputSampleDuration = mp4SampleDuration * scaleFactor, - ptsNormalize = this._PTSNormalize, - initDTS = this._initDTS, - rawMPEG = !track.isAAC && this.typeSupported.mpeg; - - var offset, - mp4Sample, - fillFrame, - mdat, - moof, - firstPTS, - lastPTS, - inputSamples = track.samples, - outputSamples = [], - nextAudioPts = this.nextAudioPts; - - // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs), - // for sake of clarity: - // consecutive fragments are frags with - // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR - // - less than 20 audio frames distance - // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) - // this helps ensuring audio continuity - // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame - contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration); - - if (!contiguous) { - // if fragments are not contiguous, let's use timeOffset to compute next Audio PTS - nextAudioPts = timeOffset * inputTimeScale; - } - - // compute normalized PTS - inputSamples.forEach(function (sample) { - sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, nextAudioPts); - }); - - // sort based on normalized PTS (this is to avoid sorting issues in case timestamp - // reloop in the middle of our samples array) - inputSamples.sort(function (a, b) { - return a.pts - b.pts; - }); - - // If the audio track is missing samples, the frames seem to get "left-shifted" within the - // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment. - // In an effort to prevent this from happening, we inject frames here where there are gaps. - // When possible, we inject a silent frame; when that's not possible, we duplicate the last - // frame. - - // only inject/drop audio frames in case time offset is accurate - if (accurateTimeOffset && track.isAAC) { - for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) { - // First, let's see how far off this frame is from where we expect it to be - var sample = inputSamples[i], - delta; - var pts = sample.pts; - delta = pts - nextPts; - - var duration = Math.abs(1000 * delta / inputTimeScale); - - // If we're overlapping by more than a duration, drop this sample - if (delta <= -inputSampleDuration) { - _logger.logger.warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + duration + ' ms overlap.'); - inputSamples.splice(i, 1); - track.len -= sample.unit.length; - // Don't touch nextPtsNorm or i - } - - // Insert missing frames if: - // 1: We're more than one frame away - // 2: Not more than MAX_SILENT_FRAME_DURATION away - // 3: currentTime (aka nextPtsNorm) is not 0 - else if (delta >= inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) { - var missing = Math.round(delta / inputSampleDuration); - _logger.logger.warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.'); - for (var j = 0; j < missing; j++) { - var newStamp = Math.max(nextPts, 0); - fillFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); - if (!fillFrame) { - _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.'); - fillFrame = sample.unit.subarray(); - } - inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp }); - track.len += fillFrame.length; - nextPts += inputSampleDuration; - i++; - } - - // Adjust sample to next expected pts - sample.pts = sample.dts = nextPts; - nextPts += inputSampleDuration; - i++; - } else { - // Otherwise, just adjust pts - if (Math.abs(delta) > 0.1 * inputSampleDuration) { - //logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`); - } - sample.pts = sample.dts = nextPts; - nextPts += inputSampleDuration; - i++; - } - } - } - - for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) { - var audioSample = inputSamples[_j2]; - var unit = audioSample.unit; - var _pts = audioSample.pts; - //logger.log(`Audio/PTS:${Math.round(pts/90)}`); - // if not first sample - if (lastPTS !== undefined) { - mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor); - } else { - var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale), - numMissingFrames = 0; - // if fragment are contiguous, detect hole/overlapping between fragments - // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) - if (contiguous && track.isAAC) { - // log delta - if (_delta) { - if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) { - numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration); - _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it'); - if (numMissingFrames > 0) { - fillFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); - if (!fillFrame) { - fillFrame = unit.subarray(); - } - track.len += numMissingFrames * fillFrame.length; - } - // if we have frame overlap, overlapping for more than half a frame duraion - } else if (_delta < -12) { - // drop overlapping audio frames... browser will deal with it - _logger.logger.log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms'); - track.len -= unit.byteLength; - continue; - } - // set PTS/DTS to expected PTS/DTS - _pts = nextAudioPts; - } - } - // remember first PTS of our audioSamples, ensure value is positive - firstPTS = Math.max(0, _pts); - if (track.len > 0) { - /* concatenate the audio data and construct the mdat in place - (need 8 more bytes to fill length and mdat type) */ - var mdatSize = rawMPEG ? track.len : track.len + 8; - offset = rawMPEG ? 0 : 8; - try { - mdat = new Uint8Array(mdatSize); - } catch (err) { - this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MUX_ERROR, details: _errors.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize }); - return; - } - if (!rawMPEG) { - var view = new DataView(mdat.buffer); - view.setUint32(0, mdatSize); - mdat.set(_mp4Generator2.default.types.mdat, 4); - } - } else { - // no audio samples - return; - } - for (var _i3 = 0; _i3 < numMissingFrames; _i3++) { - fillFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); - if (!fillFrame) { - _logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.'); - fillFrame = unit.subarray(); - } - mdat.set(fillFrame, offset); - offset += fillFrame.byteLength; - mp4Sample = { - size: fillFrame.byteLength, - cts: 0, - duration: 1024, - flags: { - isLeading: 0, - isDependedOn: 0, - hasRedundancy: 0, - degradPrio: 0, - dependsOn: 1 - } - }; - outputSamples.push(mp4Sample); - } - } - mdat.set(unit, offset); - var unitLen = unit.byteLength; - offset += unitLen; - //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}'); - mp4Sample = { - size: unitLen, - cts: 0, - duration: 0, - flags: { - isLeading: 0, - isDependedOn: 0, - hasRedundancy: 0, - degradPrio: 0, - dependsOn: 1 - } - }; - outputSamples.push(mp4Sample); - lastPTS = _pts; - } - var lastSampleDuration = 0; - var nbSamples = outputSamples.length; - //set last sample duration as being identical to previous sample - if (nbSamples >= 2) { - lastSampleDuration = outputSamples[nbSamples - 2].duration; - mp4Sample.duration = lastSampleDuration; - } - if (nbSamples) { - // next audio sample PTS should be equal to last sample PTS + duration - this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration; - //logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0)); - track.len = 0; - track.samples = outputSamples; - if (rawMPEG) { - moof = new Uint8Array(); - } else { - moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstPTS / scaleFactor, track); - } - track.samples = []; - var start = firstPTS / inputTimeScale; - var end = nextAudioPts / inputTimeScale; - var audioData = { - data1: moof, - data2: mdat, - startPTS: start, - endPTS: end, - startDTS: start, - endDTS: end, - type: 'audio', - nb: nbSamples - }; - this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData); - return audioData; - } - return null; - } - }, { - key: 'remuxEmptyAudio', - value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData) { - var inputTimeScale = track.inputTimeScale, - mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale, - scaleFactor = inputTimeScale / mp4timeScale, - nextAudioPts = this.nextAudioPts, - - - // sync with video's timestamp - startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS, - endDTS = videoData.endDTS * inputTimeScale + this._initDTS, - - // one sample's duration value - sampleDuration = 1024, - frameDuration = scaleFactor * sampleDuration, - - - // samples count of this segment's duration - nbSamples = Math.ceil((endDTS - startDTS) / frameDuration), - - - // silent frame - silentFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); - - _logger.logger.warn('remux empty Audio'); - // Can't remux if we can't generate a silent frame... - if (!silentFrame) { - _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!'); - return; - } - - var samples = []; - for (var i = 0; i < nbSamples; i++) { - var stamp = startDTS + i * frameDuration; - samples.push({ unit: silentFrame, pts: stamp, dts: stamp }); - track.len += silentFrame.length; - } - track.samples = samples; - - this.remuxAudio(track, timeOffset, contiguous); - } - }, { - key: 'remuxID3', - value: function remuxID3(track, timeOffset) { - var length = track.samples.length, - sample; - var inputTimeScale = track.inputTimeScale; - var initPTS = this._initPTS; - var initDTS = this._initDTS; - // consume samples - if (length) { - for (var index = 0; index < length; index++) { - sample = track.samples[index]; - // setting id3 pts, dts to relative time - // using this._initPTS and this._initDTS to calculate relative time - sample.pts = (sample.pts - initPTS) / inputTimeScale; - sample.dts = (sample.dts - initDTS) / inputTimeScale; - } - this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, { - samples: track.samples - }); - } - - track.samples = []; - timeOffset = timeOffset; - } - }, { - key: 'remuxText', - value: function remuxText(track, timeOffset) { - track.samples.sort(function (a, b) { - return a.pts - b.pts; - }); - - var length = track.samples.length, - sample; - var inputTimeScale = track.inputTimeScale; - var initPTS = this._initPTS; - // consume samples - if (length) { - for (var index = 0; index < length; index++) { - sample = track.samples[index]; - // setting text pts, dts to relative time - // using this._initPTS and this._initDTS to calculate relative time - sample.pts = (sample.pts - initPTS) / inputTimeScale; - } - this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, { - samples: track.samples - }); - } - - track.samples = []; - timeOffset = timeOffset; - } - }, { - key: '_PTSNormalize', - value: function _PTSNormalize(value, reference) { - var offset; - if (reference === undefined) { - return value; - } - if (reference < value) { - // - 2^33 - offset = -8589934592; - } else { - // + 2^33 - offset = 8589934592; - } - /* PTS is 33bit (from 0 to 2^33 -1) - if diff between value and reference is bigger than half of the amplitude (2^32) then it means that - PTS looping occured. fill the gap */ - while (Math.abs(value - reference) > 4294967296) { - value += offset; - } - return value; - } - }]); - - return MP4Remuxer; -}(); - -exports.default = MP4Remuxer; - -},{"33":33,"35":35,"36":36,"44":44,"54":54}],46:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * passthrough remuxer - */ - - -var _events = _dereq_(35); - -var _events2 = _interopRequireDefault(_events); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var PassThroughRemuxer = function () { - function PassThroughRemuxer(observer) { - _classCallCheck$$1(this, PassThroughRemuxer); - - this.observer = observer; - } - - _createClass$$1(PassThroughRemuxer, [{ - key: 'destroy', - value: function destroy() {} - }, { - key: 'resetTimeStamp', - value: function resetTimeStamp() {} - }, { - key: 'resetInitSegment', - value: function resetInitSegment() {} - }, { - key: 'remux', - value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) { - var observer = this.observer; - var streamType = ''; - if (audioTrack) { - streamType += 'audio'; - } - if (videoTrack) { - streamType += 'video'; - } - observer.trigger(_events2.default.FRAG_PARSING_DATA, { - data1: rawData, - startPTS: timeOffset, - startDTS: timeOffset, - type: streamType, - nb: 1, - dropped: 0 - }); - //notify end of parsing - observer.trigger(_events2.default.FRAG_PARSED); - } - }]); - - return PassThroughRemuxer; -}(); - -exports.default = PassThroughRemuxer; - -},{"35":35}],47:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; -var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; - -// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js - -var AttrList = function () { - function AttrList(attrs) { - _classCallCheck$$1(this, AttrList); - - if (typeof attrs === 'string') { - attrs = AttrList.parseAttrList(attrs); - } - for (var attr in attrs) { - if (attrs.hasOwnProperty(attr)) { - this[attr] = attrs[attr]; - } - } - } - - _createClass$$1(AttrList, [{ - key: 'decimalInteger', - value: function decimalInteger(attrName) { - var intValue = parseInt(this[attrName], 10); - if (intValue > Number.MAX_SAFE_INTEGER) { - return Infinity; - } - return intValue; - } - }, { - key: 'hexadecimalInteger', - value: function hexadecimalInteger(attrName) { - if (this[attrName]) { - var stringValue = (this[attrName] || '0x').slice(2); - stringValue = (stringValue.length & 1 ? '0' : '') + stringValue; - - var value = new Uint8Array(stringValue.length / 2); - for (var i = 0; i < stringValue.length / 2; i++) { - value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16); - } - return value; - } else { - return null; - } - } - }, { - key: 'hexadecimalIntegerAsNumber', - value: function hexadecimalIntegerAsNumber(attrName) { - var intValue = parseInt(this[attrName], 16); - if (intValue > Number.MAX_SAFE_INTEGER) { - return Infinity; - } - return intValue; - } - }, { - key: 'decimalFloatingPoint', - value: function decimalFloatingPoint(attrName) { - return parseFloat(this[attrName]); - } - }, { - key: 'enumeratedString', - value: function enumeratedString(attrName) { - return this[attrName]; - } - }, { - key: 'decimalResolution', - value: function decimalResolution(attrName) { - var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]); - if (res === null) { - return undefined; - } - return { - width: parseInt(res[1], 10), - height: parseInt(res[2], 10) - }; - } - }], [{ - key: 'parseAttrList', - value: function parseAttrList(input) { - var match, - attrs = {}; - ATTR_LIST_REGEX.lastIndex = 0; - while ((match = ATTR_LIST_REGEX.exec(input)) !== null) { - var value = match[2], - quote = '"'; - - if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) { - value = value.slice(1, -1); - } - attrs[match[1]] = value; - } - return attrs; - } - }]); - - return AttrList; -}(); - -exports.default = AttrList; - -},{}],48:[function(_dereq_,module,exports){ -"use strict"; - -var BinarySearch = { - /** - * Searches for an item in an array which matches a certain condition. - * This requires the condition to only match one item in the array, - * and for the array to be ordered. - * - * @param {Array} list The array to search. - * @param {Function} comparisonFunction - * Called and provided a candidate item as the first argument. - * Should return: - * > -1 if the item should be located at a lower index than the provided item. - * > 1 if the item should be located at a higher index than the provided item. - * > 0 if the item is the item you're looking for. - * - * @return {*} The object if it is found or null otherwise. - */ - search: function search(list, comparisonFunction) { - var minIndex = 0; - var maxIndex = list.length - 1; - var currentIndex = null; - var currentElement = null; - - while (minIndex <= maxIndex) { - currentIndex = (minIndex + maxIndex) / 2 | 0; - currentElement = list[currentIndex]; - - var comparisonResult = comparisonFunction(currentElement); - if (comparisonResult > 0) { - minIndex = currentIndex + 1; - } else if (comparisonResult < 0) { - maxIndex = currentIndex - 1; - } else { - return currentElement; - } - } - - return null; - } -}; - -module.exports = BinarySearch; - -},{}],49:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/** - * - * This code was ported from the dash.js project at: - * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js - * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2 - * - * The original copyright appears below: - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2015-2016, DASH Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * 2. Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/** - * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes - */ - -var specialCea608CharsCodes = { - 0x2a: 0xe1, // lowercase a, acute accent - 0x5c: 0xe9, // lowercase e, acute accent - 0x5e: 0xed, // lowercase i, acute accent - 0x5f: 0xf3, // lowercase o, acute accent - 0x60: 0xfa, // lowercase u, acute accent - 0x7b: 0xe7, // lowercase c with cedilla - 0x7c: 0xf7, // division symbol - 0x7d: 0xd1, // uppercase N tilde - 0x7e: 0xf1, // lowercase n tilde - 0x7f: 0x2588, // Full block - // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS - // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F - // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES - 0x80: 0xae, // Registered symbol (R) - 0x81: 0xb0, // degree sign - 0x82: 0xbd, // 1/2 symbol - 0x83: 0xbf, // Inverted (open) question mark - 0x84: 0x2122, // Trademark symbol (TM) - 0x85: 0xa2, // Cents symbol - 0x86: 0xa3, // Pounds sterling - 0x87: 0x266a, // Music 8'th note - 0x88: 0xe0, // lowercase a, grave accent - 0x89: 0x20, // transparent space (regular) - 0x8a: 0xe8, // lowercase e, grave accent - 0x8b: 0xe2, // lowercase a, circumflex accent - 0x8c: 0xea, // lowercase e, circumflex accent - 0x8d: 0xee, // lowercase i, circumflex accent - 0x8e: 0xf4, // lowercase o, circumflex accent - 0x8f: 0xfb, // lowercase u, circumflex accent - // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS - // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F - 0x90: 0xc1, // capital letter A with acute - 0x91: 0xc9, // capital letter E with acute - 0x92: 0xd3, // capital letter O with acute - 0x93: 0xda, // capital letter U with acute - 0x94: 0xdc, // capital letter U with diaresis - 0x95: 0xfc, // lowercase letter U with diaeresis - 0x96: 0x2018, // opening single quote - 0x97: 0xa1, // inverted exclamation mark - 0x98: 0x2a, // asterisk - 0x99: 0x2019, // closing single quote - 0x9a: 0x2501, // box drawings heavy horizontal - 0x9b: 0xa9, // copyright sign - 0x9c: 0x2120, // Service mark - 0x9d: 0x2022, // (round) bullet - 0x9e: 0x201c, // Left double quotation mark - 0x9f: 0x201d, // Right double quotation mark - 0xa0: 0xc0, // uppercase A, grave accent - 0xa1: 0xc2, // uppercase A, circumflex - 0xa2: 0xc7, // uppercase C with cedilla - 0xa3: 0xc8, // uppercase E, grave accent - 0xa4: 0xca, // uppercase E, circumflex - 0xa5: 0xcb, // capital letter E with diaresis - 0xa6: 0xeb, // lowercase letter e with diaresis - 0xa7: 0xce, // uppercase I, circumflex - 0xa8: 0xcf, // uppercase I, with diaresis - 0xa9: 0xef, // lowercase i, with diaresis - 0xaa: 0xd4, // uppercase O, circumflex - 0xab: 0xd9, // uppercase U, grave accent - 0xac: 0xf9, // lowercase u, grave accent - 0xad: 0xdb, // uppercase U, circumflex - 0xae: 0xab, // left-pointing double angle quotation mark - 0xaf: 0xbb, // right-pointing double angle quotation mark - // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS - // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F - 0xb0: 0xc3, // Uppercase A, tilde - 0xb1: 0xe3, // Lowercase a, tilde - 0xb2: 0xcd, // Uppercase I, acute accent - 0xb3: 0xcc, // Uppercase I, grave accent - 0xb4: 0xec, // Lowercase i, grave accent - 0xb5: 0xd2, // Uppercase O, grave accent - 0xb6: 0xf2, // Lowercase o, grave accent - 0xb7: 0xd5, // Uppercase O, tilde - 0xb8: 0xf5, // Lowercase o, tilde - 0xb9: 0x7b, // Open curly brace - 0xba: 0x7d, // Closing curly brace - 0xbb: 0x5c, // Backslash - 0xbc: 0x5e, // Caret - 0xbd: 0x5f, // Underscore - 0xbe: 0x7c, // Pipe (vertical line) - 0xbf: 0x223c, // Tilde operator - 0xc0: 0xc4, // Uppercase A, umlaut - 0xc1: 0xe4, // Lowercase A, umlaut - 0xc2: 0xd6, // Uppercase O, umlaut - 0xc3: 0xf6, // Lowercase o, umlaut - 0xc4: 0xdf, // Esszett (sharp S) - 0xc5: 0xa5, // Yen symbol - 0xc6: 0xa4, // Generic currency sign - 0xc7: 0x2503, // Box drawings heavy vertical - 0xc8: 0xc5, // Uppercase A, ring - 0xc9: 0xe5, // Lowercase A, ring - 0xca: 0xd8, // Uppercase O, stroke - 0xcb: 0xf8, // Lowercase o, strok - 0xcc: 0x250f, // Box drawings heavy down and right - 0xcd: 0x2513, // Box drawings heavy down and left - 0xce: 0x2517, // Box drawings heavy up and right - 0xcf: 0x251b // Box drawings heavy up and left -}; - -/** - * Utils - */ -var getCharForByte = function getCharForByte(byte) { - var charCode = byte; - if (specialCea608CharsCodes.hasOwnProperty(byte)) { - charCode = specialCea608CharsCodes[byte]; - } - return String.fromCharCode(charCode); -}; - -var NR_ROWS = 15, - NR_COLS = 100; -// Tables to look up row from PAC data -var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 }; -var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 }; -var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 }; -var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 }; - -var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent']; - -/** - * Simple logger class to be able to write with time-stamps and filter on level. - */ -var logger = { - verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 }, - time: null, - verboseLevel: 0, // Only write errors - setTime: function setTime(newTime) { - this.time = newTime; - }, - log: function log(severity, msg) { - var minLevel = this.verboseFilter[severity]; - if (this.verboseLevel >= minLevel) { - console.log(this.time + ' [' + severity + '] ' + msg); - } - } -}; - -var numArrayToHexArray = function numArrayToHexArray(numArray) { - var hexArray = []; - for (var j = 0; j < numArray.length; j++) { - hexArray.push(numArray[j].toString(16)); - } - return hexArray; -}; - -var PenState = function () { - function PenState(foreground, underline, italics, background, flash) { - _classCallCheck$$1(this, PenState); - - this.foreground = foreground || 'white'; - this.underline = underline || false; - this.italics = italics || false; - this.background = background || 'black'; - this.flash = flash || false; - } - - _createClass$$1(PenState, [{ - key: 'reset', - value: function reset() { - this.foreground = 'white'; - this.underline = false; - this.italics = false; - this.background = 'black'; - this.flash = false; - } - }, { - key: 'setStyles', - value: function setStyles(styles) { - var attribs = ['foreground', 'underline', 'italics', 'background', 'flash']; - for (var i = 0; i < attribs.length; i++) { - var style = attribs[i]; - if (styles.hasOwnProperty(style)) { - this[style] = styles[style]; - } - } - } - }, { - key: 'isDefault', - value: function isDefault() { - return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash; - } - }, { - key: 'equals', - value: function equals(other) { - return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash; - } - }, { - key: 'copy', - value: function copy(newPenState) { - this.foreground = newPenState.foreground; - this.underline = newPenState.underline; - this.italics = newPenState.italics; - this.background = newPenState.background; - this.flash = newPenState.flash; - } - }, { - key: 'toString', - value: function toString() { - return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash; - } - }]); - - return PenState; -}(); - -/** - * Unicode character with styling and background. - * @constructor - */ - - -var StyledUnicodeChar = function () { - function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) { - _classCallCheck$$1(this, StyledUnicodeChar); - - this.uchar = uchar || ' '; // unicode character - this.penState = new PenState(foreground, underline, italics, background, flash); - } - - _createClass$$1(StyledUnicodeChar, [{ - key: 'reset', - value: function reset() { - this.uchar = ' '; - this.penState.reset(); - } - }, { - key: 'setChar', - value: function setChar(uchar, newPenState) { - this.uchar = uchar; - this.penState.copy(newPenState); - } - }, { - key: 'setPenState', - value: function setPenState(newPenState) { - this.penState.copy(newPenState); - } - }, { - key: 'equals', - value: function equals(other) { - return this.uchar === other.uchar && this.penState.equals(other.penState); - } - }, { - key: 'copy', - value: function copy(newChar) { - this.uchar = newChar.uchar; - this.penState.copy(newChar.penState); - } - }, { - key: 'isEmpty', - value: function isEmpty$$1() { - return this.uchar === ' ' && this.penState.isDefault(); - } - }]); - - return StyledUnicodeChar; -}(); - -/** - * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar. - * @constructor - */ - - -var Row = function () { - function Row() { - _classCallCheck$$1(this, Row); - - this.chars = []; - for (var i = 0; i < NR_COLS; i++) { - this.chars.push(new StyledUnicodeChar()); - } - this.pos = 0; - this.currPenState = new PenState(); - } - - _createClass$$1(Row, [{ - key: 'equals', - value: function equals(other) { - var equal = true; - for (var i = 0; i < NR_COLS; i++) { - if (!this.chars[i].equals(other.chars[i])) { - equal = false; - break; - } - } - return equal; - } - }, { - key: 'copy', - value: function copy(other) { - for (var i = 0; i < NR_COLS; i++) { - this.chars[i].copy(other.chars[i]); - } - } - }, { - key: 'isEmpty', - value: function isEmpty$$1() { - var empty = true; - for (var i = 0; i < NR_COLS; i++) { - if (!this.chars[i].isEmpty()) { - empty = false; - break; - } - } - return empty; - } - - /** - * Set the cursor to a valid column. - */ - - }, { - key: 'setCursor', - value: function setCursor(absPos) { - if (this.pos !== absPos) { - this.pos = absPos; - } - if (this.pos < 0) { - logger.log('ERROR', 'Negative cursor position ' + this.pos); - this.pos = 0; - } else if (this.pos > NR_COLS) { - logger.log('ERROR', 'Too large cursor position ' + this.pos); - this.pos = NR_COLS; - } - } - - /** - * Move the cursor relative to current position. - */ - - }, { - key: 'moveCursor', - value: function moveCursor(relPos) { - var newPos = this.pos + relPos; - if (relPos > 1) { - for (var i = this.pos + 1; i < newPos + 1; i++) { - this.chars[i].setPenState(this.currPenState); - } - } - this.setCursor(newPos); - } - - /** - * Backspace, move one step back and clear character. - */ - - }, { - key: 'backSpace', - value: function backSpace() { - this.moveCursor(-1); - this.chars[this.pos].setChar(' ', this.currPenState); - } - }, { - key: 'insertChar', - value: function insertChar(byte) { - if (byte >= 0x90) { - //Extended char - this.backSpace(); - } - var char = getCharForByte(byte); - if (this.pos >= NR_COLS) { - logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!'); - return; - } - this.chars[this.pos].setChar(char, this.currPenState); - this.moveCursor(1); - } - }, { - key: 'clearFromPos', - value: function clearFromPos(startPos) { - var i; - for (i = startPos; i < NR_COLS; i++) { - this.chars[i].reset(); - } - } - }, { - key: 'clear', - value: function clear() { - this.clearFromPos(0); - this.pos = 0; - this.currPenState.reset(); - } - }, { - key: 'clearToEndOfRow', - value: function clearToEndOfRow() { - this.clearFromPos(this.pos); - } - }, { - key: 'getTextString', - value: function getTextString() { - var chars = []; - var empty = true; - for (var i = 0; i < NR_COLS; i++) { - var char = this.chars[i].uchar; - if (char !== ' ') { - empty = false; - } - chars.push(char); - } - if (empty) { - return ''; - } else { - return chars.join(''); - } - } - }, { - key: 'setPenStyles', - value: function setPenStyles(styles) { - this.currPenState.setStyles(styles); - var currChar = this.chars[this.pos]; - currChar.setPenState(this.currPenState); - } - }]); - - return Row; -}(); - -/** - * Keep a CEA-608 screen of 32x15 styled characters - * @constructor -*/ - - -var CaptionScreen = function () { - function CaptionScreen() { - _classCallCheck$$1(this, CaptionScreen); - - this.rows = []; - for (var i = 0; i < NR_ROWS; i++) { - this.rows.push(new Row()); // Note that we use zero-based numbering (0-14) - } - this.currRow = NR_ROWS - 1; - this.nrRollUpRows = null; - this.reset(); - } - - _createClass$$1(CaptionScreen, [{ - key: 'reset', - value: function reset() { - for (var i = 0; i < NR_ROWS; i++) { - this.rows[i].clear(); - } - this.currRow = NR_ROWS - 1; - } - }, { - key: 'equals', - value: function equals(other) { - var equal = true; - for (var i = 0; i < NR_ROWS; i++) { - if (!this.rows[i].equals(other.rows[i])) { - equal = false; - break; - } - } - return equal; - } - }, { - key: 'copy', - value: function copy(other) { - for (var i = 0; i < NR_ROWS; i++) { - this.rows[i].copy(other.rows[i]); - } - } - }, { - key: 'isEmpty', - value: function isEmpty$$1() { - var empty = true; - for (var i = 0; i < NR_ROWS; i++) { - if (!this.rows[i].isEmpty()) { - empty = false; - break; - } - } - return empty; - } - }, { - key: 'backSpace', - value: function backSpace() { - var row = this.rows[this.currRow]; - row.backSpace(); - } - }, { - key: 'clearToEndOfRow', - value: function clearToEndOfRow() { - var row = this.rows[this.currRow]; - row.clearToEndOfRow(); - } - - /** - * Insert a character (without styling) in the current row. - */ - - }, { - key: 'insertChar', - value: function insertChar(char) { - var row = this.rows[this.currRow]; - row.insertChar(char); - } - }, { - key: 'setPen', - value: function setPen(styles) { - var row = this.rows[this.currRow]; - row.setPenStyles(styles); - } - }, { - key: 'moveCursor', - value: function moveCursor(relPos) { - var row = this.rows[this.currRow]; - row.moveCursor(relPos); - } - }, { - key: 'setCursor', - value: function setCursor(absPos) { - logger.log('INFO', 'setCursor: ' + absPos); - var row = this.rows[this.currRow]; - row.setCursor(absPos); - } - }, { - key: 'setPAC', - value: function setPAC(pacData) { - logger.log('INFO', 'pacData = ' + JSON.stringify(pacData)); - var newRow = pacData.row - 1; - if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) { - newRow = this.nrRollUpRows - 1; - } - - //Make sure this only affects Roll-up Captions by checking this.nrRollUpRows - if (this.nrRollUpRows && this.currRow !== newRow) { - //clear all rows first - for (var i = 0; i < NR_ROWS; i++) { - this.rows[i].clear(); - } - - //Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location - //topRowIndex - the start of rows to copy (inclusive index) - var topRowIndex = this.currRow + 1 - this.nrRollUpRows; - //We only copy if the last position was already shown. - //We use the cueStartTime value to check this. - var lastOutputScreen = this.lastOutputScreen; - if (lastOutputScreen) { - var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime; - if (prevLineTime && prevLineTime < logger.time) { - for (var _i = 0; _i < this.nrRollUpRows; _i++) { - this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]); - } - } - } - } - - this.currRow = newRow; - var row = this.rows[this.currRow]; - if (pacData.indent !== null) { - var indent = pacData.indent; - var prevPos = Math.max(indent - 1, 0); - row.setCursor(pacData.indent); - pacData.color = row.chars[prevPos].penState.foreground; - } - var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false }; - this.setPen(styles); - } - - /** - * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility). - */ - - }, { - key: 'setBkgData', - value: function setBkgData(bkgData) { - - logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData)); - this.backSpace(); - this.setPen(bkgData); - this.insertChar(0x20); //Space - } - }, { - key: 'setRollUpRows', - value: function setRollUpRows(nrRows) { - this.nrRollUpRows = nrRows; - } - }, { - key: 'rollUp', - value: function rollUp() { - if (this.nrRollUpRows === null) { - logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet'); - return; //Not properly setup - } - logger.log('TEXT', this.getDisplayText()); - var topRowIndex = this.currRow + 1 - this.nrRollUpRows; - var topRow = this.rows.splice(topRowIndex, 1)[0]; - topRow.clear(); - this.rows.splice(this.currRow, 0, topRow); - logger.log('INFO', 'Rolling up'); - //logger.log('TEXT', this.get_display_text()) - } - - /** - * Get all non-empty rows with as unicode text. - */ - - }, { - key: 'getDisplayText', - value: function getDisplayText(asOneRow) { - asOneRow = asOneRow || false; - var displayText = []; - var text = ''; - var rowNr = -1; - for (var i = 0; i < NR_ROWS; i++) { - var rowText = this.rows[i].getTextString(); - if (rowText) { - rowNr = i + 1; - if (asOneRow) { - displayText.push('Row ' + rowNr + ': \'' + rowText + '\''); - } else { - displayText.push(rowText.trim()); - } - } - } - if (displayText.length > 0) { - if (asOneRow) { - text = '[' + displayText.join(' | ') + ']'; - } else { - text = displayText.join('\n'); - } - } - return text; - } - }, { - key: 'getTextAndFormat', - value: function getTextAndFormat() { - return this.rows; - } - }]); - - return CaptionScreen; -}(); - -//var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT']; - -var Cea608Channel = function () { - function Cea608Channel(channelNumber, outputFilter) { - _classCallCheck$$1(this, Cea608Channel); - - this.chNr = channelNumber; - this.outputFilter = outputFilter; - this.mode = null; - this.verbose = 0; - this.displayedMemory = new CaptionScreen(); - this.nonDisplayedMemory = new CaptionScreen(); - this.lastOutputScreen = new CaptionScreen(); - this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; - this.writeScreen = this.displayedMemory; - this.mode = null; - this.cueStartTime = null; // Keeps track of where a cue started. - } - - _createClass$$1(Cea608Channel, [{ - key: 'reset', - value: function reset() { - this.mode = null; - this.displayedMemory.reset(); - this.nonDisplayedMemory.reset(); - this.lastOutputScreen.reset(); - this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; - this.writeScreen = this.displayedMemory; - this.mode = null; - this.cueStartTime = null; - this.lastCueEndTime = null; - } - }, { - key: 'getHandler', - value: function getHandler() { - return this.outputFilter; - } - }, { - key: 'setHandler', - value: function setHandler(newHandler) { - this.outputFilter = newHandler; - } - }, { - key: 'setPAC', - value: function setPAC(pacData) { - this.writeScreen.setPAC(pacData); - } - }, { - key: 'setBkgData', - value: function setBkgData(bkgData) { - this.writeScreen.setBkgData(bkgData); - } - }, { - key: 'setMode', - value: function setMode(newMode) { - if (newMode === this.mode) { - return; - } - this.mode = newMode; - logger.log('INFO', 'MODE=' + newMode); - if (this.mode === 'MODE_POP-ON') { - this.writeScreen = this.nonDisplayedMemory; - } else { - this.writeScreen = this.displayedMemory; - this.writeScreen.reset(); - } - if (this.mode !== 'MODE_ROLL-UP') { - this.displayedMemory.nrRollUpRows = null; - this.nonDisplayedMemory.nrRollUpRows = null; - } - this.mode = newMode; - } - }, { - key: 'insertChars', - value: function insertChars(chars) { - for (var i = 0; i < chars.length; i++) { - this.writeScreen.insertChar(chars[i]); - } - var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP'; - logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true)); - if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') { - logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)); - this.outputDataUpdate(); - } - } - }, { - key: 'ccRCL', - value: function ccRCL() { - // Resume Caption Loading (switch mode to Pop On) - logger.log('INFO', 'RCL - Resume Caption Loading'); - this.setMode('MODE_POP-ON'); - } - }, { - key: 'ccBS', - value: function ccBS() { - // BackSpace - logger.log('INFO', 'BS - BackSpace'); - if (this.mode === 'MODE_TEXT') { - return; - } - this.writeScreen.backSpace(); - if (this.writeScreen === this.displayedMemory) { - this.outputDataUpdate(); - } - } - }, { - key: 'ccAOF', - value: function ccAOF() { - // Reserved (formerly Alarm Off) - return; - } - }, { - key: 'ccAON', - value: function ccAON() { - // Reserved (formerly Alarm On) - return; - } - }, { - key: 'ccDER', - value: function ccDER() { - // Delete to End of Row - logger.log('INFO', 'DER- Delete to End of Row'); - this.writeScreen.clearToEndOfRow(); - this.outputDataUpdate(); - } - }, { - key: 'ccRU', - value: function ccRU(nrRows) { - //Roll-Up Captions-2,3,or 4 Rows - logger.log('INFO', 'RU(' + nrRows + ') - Roll Up'); - this.writeScreen = this.displayedMemory; - this.setMode('MODE_ROLL-UP'); - this.writeScreen.setRollUpRows(nrRows); - } - }, { - key: 'ccFON', - value: function ccFON() { - //Flash On - logger.log('INFO', 'FON - Flash On'); - this.writeScreen.setPen({ flash: true }); - } - }, { - key: 'ccRDC', - value: function ccRDC() { - // Resume Direct Captioning (switch mode to PaintOn) - logger.log('INFO', 'RDC - Resume Direct Captioning'); - this.setMode('MODE_PAINT-ON'); - } - }, { - key: 'ccTR', - value: function ccTR() { - // Text Restart in text mode (not supported, however) - logger.log('INFO', 'TR'); - this.setMode('MODE_TEXT'); - } - }, { - key: 'ccRTD', - value: function ccRTD() { - // Resume Text Display in Text mode (not supported, however) - logger.log('INFO', 'RTD'); - this.setMode('MODE_TEXT'); - } - }, { - key: 'ccEDM', - value: function ccEDM() { - // Erase Displayed Memory - logger.log('INFO', 'EDM - Erase Displayed Memory'); - this.displayedMemory.reset(); - this.outputDataUpdate(); - } - }, { - key: 'ccCR', - value: function ccCR() { - // Carriage Return - logger.log('CR - Carriage Return'); - this.writeScreen.rollUp(); - this.outputDataUpdate(); - } - }, { - key: 'ccENM', - value: function ccENM() { - //Erase Non-Displayed Memory - logger.log('INFO', 'ENM - Erase Non-displayed Memory'); - this.nonDisplayedMemory.reset(); - } - }, { - key: 'ccEOC', - value: function ccEOC() { - //End of Caption (Flip Memories) - logger.log('INFO', 'EOC - End Of Caption'); - if (this.mode === 'MODE_POP-ON') { - var tmp = this.displayedMemory; - this.displayedMemory = this.nonDisplayedMemory; - this.nonDisplayedMemory = tmp; - this.writeScreen = this.nonDisplayedMemory; - logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText()); - } - this.outputDataUpdate(); - } - }, { - key: 'ccTO', - value: function ccTO(nrCols) { - // Tab Offset 1,2, or 3 columns - logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset'); - this.writeScreen.moveCursor(nrCols); - } - }, { - key: 'ccMIDROW', - value: function ccMIDROW(secondByte) { - // Parse MIDROW command - var styles = { flash: false }; - styles.underline = secondByte % 2 === 1; - styles.italics = secondByte >= 0x2e; - if (!styles.italics) { - var colorIndex = Math.floor(secondByte / 2) - 0x10; - var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta']; - styles.foreground = colors[colorIndex]; - } else { - styles.foreground = 'white'; - } - logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles)); - this.writeScreen.setPen(styles); - } - }, { - key: 'outputDataUpdate', - value: function outputDataUpdate() { - var t = logger.time; - if (t === null) { - return; - } - if (this.outputFilter) { - if (this.outputFilter.updateData) { - this.outputFilter.updateData(t, this.displayedMemory); - } - if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { - // Start of a new cue - this.cueStartTime = t; - } else { - if (!this.displayedMemory.equals(this.lastOutputScreen)) { - if (this.outputFilter.newCue) { - this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen); - } - this.cueStartTime = this.displayedMemory.isEmpty() ? null : t; - } - } - this.lastOutputScreen.copy(this.displayedMemory); - } - } - }, { - key: 'cueSplitAtTime', - value: function cueSplitAtTime(t) { - if (this.outputFilter) { - if (!this.displayedMemory.isEmpty()) { - if (this.outputFilter.newCue) { - this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory); - } - this.cueStartTime = t; - } - } - } - }]); - - return Cea608Channel; -}(); - -var Cea608Parser = function () { - function Cea608Parser(field, out1, out2) { - _classCallCheck$$1(this, Cea608Parser); - - this.field = field || 1; - this.outputs = [out1, out2]; - this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)]; - this.currChNr = -1; // Will be 1 or 2 - this.lastCmdA = null; // First byte of last command - this.lastCmdB = null; // Second byte of last command - this.bufferedData = []; - this.startTime = null; - this.lastTime = null; - this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 }; - } - - _createClass$$1(Cea608Parser, [{ - key: 'getHandler', - value: function getHandler(index) { - return this.channels[index].getHandler(); - } - }, { - key: 'setHandler', - value: function setHandler(index, newHandler) { - this.channels[index].setHandler(newHandler); - } - - /** - * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs. - */ - - }, { - key: 'addData', - value: function addData(t, byteList) { - var cmdFound, - a, - b, - charsFound = false; - - this.lastTime = t; - logger.setTime(t); - - for (var i = 0; i < byteList.length; i += 2) { - a = byteList[i] & 0x7f; - b = byteList[i + 1] & 0x7f; - if (a === 0 && b === 0) { - this.dataCounters.padding += 2; - continue; - } else { - logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')'); - } - cmdFound = this.parseCmd(a, b); - if (!cmdFound) { - cmdFound = this.parseMidrow(a, b); - } - if (!cmdFound) { - cmdFound = this.parsePAC(a, b); - } - if (!cmdFound) { - cmdFound = this.parseBackgroundAttributes(a, b); - } - if (!cmdFound) { - charsFound = this.parseChars(a, b); - if (charsFound) { - if (this.currChNr && this.currChNr >= 0) { - var channel = this.channels[this.currChNr - 1]; - channel.insertChars(charsFound); - } else { - logger.log('WARNING', 'No channel found yet. TEXT-MODE?'); - } - } - } - if (cmdFound) { - this.dataCounters.cmd += 2; - } else if (charsFound) { - this.dataCounters.char += 2; - } else { - this.dataCounters.other += 2; - logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]])); - } - } - } - - /** - * Parse Command. - * @returns {Boolean} Tells if a command was found - */ - - }, { - key: 'parseCmd', - value: function parseCmd(a, b) { - var chNr = null; - - var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F; - var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23; - if (!(cond1 || cond2)) { - return false; - } - - if (a === this.lastCmdA && b === this.lastCmdB) { - this.lastCmdA = null; - this.lastCmdB = null; // Repeated commands are dropped (once) - logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'); - return true; - } - - if (a === 0x14 || a === 0x17) { - chNr = 1; - } else { - chNr = 2; // (a === 0x1C || a=== 0x1f) - } - - var channel = this.channels[chNr - 1]; - - if (a === 0x14 || a === 0x1C) { - if (b === 0x20) { - channel.ccRCL(); - } else if (b === 0x21) { - channel.ccBS(); - } else if (b === 0x22) { - channel.ccAOF(); - } else if (b === 0x23) { - channel.ccAON(); - } else if (b === 0x24) { - channel.ccDER(); - } else if (b === 0x25) { - channel.ccRU(2); - } else if (b === 0x26) { - channel.ccRU(3); - } else if (b === 0x27) { - channel.ccRU(4); - } else if (b === 0x28) { - channel.ccFON(); - } else if (b === 0x29) { - channel.ccRDC(); - } else if (b === 0x2A) { - channel.ccTR(); - } else if (b === 0x2B) { - channel.ccRTD(); - } else if (b === 0x2C) { - channel.ccEDM(); - } else if (b === 0x2D) { - channel.ccCR(); - } else if (b === 0x2E) { - channel.ccENM(); - } else if (b === 0x2F) { - channel.ccEOC(); - } - } else { - //a == 0x17 || a == 0x1F - channel.ccTO(b - 0x20); - } - this.lastCmdA = a; - this.lastCmdB = b; - this.currChNr = chNr; - return true; - } - - /** - * Parse midrow styling command - * @returns {Boolean} - */ - - }, { - key: 'parseMidrow', - value: function parseMidrow(a, b) { - var chNr = null; - - if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) { - if (a === 0x11) { - chNr = 1; - } else { - chNr = 2; - } - if (chNr !== this.currChNr) { - logger.log('ERROR', 'Mismatch channel in midrow parsing'); - return false; - } - var channel = this.channels[chNr - 1]; - channel.ccMIDROW(b); - logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')'); - return true; - } - return false; - } - /** - * Parse Preable Access Codes (Table 53). - * @returns {Boolean} Tells if PAC found - */ - - }, { - key: 'parsePAC', - value: function parsePAC(a, b) { - - var chNr = null; - var row = null; - - var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F; - var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F; - if (!(case1 || case2)) { - return false; - } - - if (a === this.lastCmdA && b === this.lastCmdB) { - this.lastCmdA = null; - this.lastCmdB = null; - return true; // Repeated commands are dropped (once) - } - - chNr = a <= 0x17 ? 1 : 2; - - if (0x40 <= b && b <= 0x5F) { - row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a]; - } else { - // 0x60 <= b <= 0x7F - row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a]; - } - var pacData = this.interpretPAC(row, b); - var channel = this.channels[chNr - 1]; - channel.setPAC(pacData); - this.lastCmdA = a; - this.lastCmdB = b; - this.currChNr = chNr; - return true; - } - - /** - * Interpret the second byte of the pac, and return the information. - * @returns {Object} pacData with style parameters. - */ - - }, { - key: 'interpretPAC', - value: function interpretPAC(row, byte) { - var pacIndex = byte; - var pacData = { color: null, italics: false, indent: null, underline: false, row: row }; - - if (byte > 0x5F) { - pacIndex = byte - 0x60; - } else { - pacIndex = byte - 0x40; - } - pacData.underline = (pacIndex & 1) === 1; - if (pacIndex <= 0xd) { - pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)]; - } else if (pacIndex <= 0xf) { - pacData.italics = true; - pacData.color = 'white'; - } else { - pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4; - } - return pacData; // Note that row has zero offset. The spec uses 1. - } - - /** - * Parse characters. - * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise. - */ - - }, { - key: 'parseChars', - value: function parseChars(a, b) { - - var channelNr = null, - charCodes = null, - charCode1 = null; - - if (a >= 0x19) { - channelNr = 2; - charCode1 = a - 8; - } else { - channelNr = 1; - charCode1 = a; - } - if (0x11 <= charCode1 && charCode1 <= 0x13) { - // Special character - var oneCode = b; - if (charCode1 === 0x11) { - oneCode = b + 0x50; - } else if (charCode1 === 0x12) { - oneCode = b + 0x70; - } else { - oneCode = b + 0x90; - } - logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr); - charCodes = [oneCode]; - } else if (0x20 <= a && a <= 0x7f) { - charCodes = b === 0 ? [a] : [a, b]; - } - if (charCodes) { - var hexCodes = numArrayToHexArray(charCodes); - logger.log('DEBUG', 'Char codes = ' + hexCodes.join(',')); - this.lastCmdA = null; - this.lastCmdB = null; - } - return charCodes; - } - - /** - * Parse extended background attributes as well as new foreground color black. - * @returns{Boolean} Tells if background attributes are found - */ - - }, { - key: 'parseBackgroundAttributes', - value: function parseBackgroundAttributes(a, b) { - var bkgData, index, chNr, channel; - - var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f; - var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f; - if (!(case1 || case2)) { - return false; - } - bkgData = {}; - if (a === 0x10 || a === 0x18) { - index = Math.floor((b - 0x20) / 2); - bkgData.background = backgroundColors[index]; - if (b % 2 === 1) { - bkgData.background = bkgData.background + '_semi'; - } - } else if (b === 0x2d) { - bkgData.background = 'transparent'; - } else { - bkgData.foreground = 'black'; - if (b === 0x2f) { - bkgData.underline = true; - } - } - chNr = a < 0x18 ? 1 : 2; - channel = this.channels[chNr - 1]; - channel.setBkgData(bkgData); - this.lastCmdA = null; - this.lastCmdB = null; - return true; - } - - /** - * Reset state of parser and its channels. - */ - - }, { - key: 'reset', - value: function reset() { - for (var i = 0; i < this.channels.length; i++) { - if (this.channels[i]) { - this.channels[i].reset(); - } - } - this.lastCmdA = null; - this.lastCmdB = null; - } - - /** - * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty. - */ - - }, { - key: 'cueSplitAtTime', - value: function cueSplitAtTime(t) { - for (var i = 0; i < this.channels.length; i++) { - if (this.channels[i]) { - this.channels[i].cueSplitAtTime(t); - } - } - } - }]); - - return Cea608Parser; -}(); - -exports.default = Cea608Parser; - -},{}],50:[function(_dereq_,module,exports){ -'use strict'; - -var _vttparser = _dereq_(57); - -var Cues = { - - newCue: function newCue(track, startTime, endTime, captionScreen) { - var row; - var cue; - var indenting; - var indent; - var text; - var VTTCue = window.VTTCue || window.TextTrackCue; - - for (var r = 0; r < captionScreen.rows.length; r++) { - row = captionScreen.rows[r]; - indenting = true; - indent = 0; - text = ''; - - if (!row.isEmpty()) { - for (var c = 0; c < row.chars.length; c++) { - if (row.chars[c].uchar.match(/\s/) && indenting) { - indent++; - } else { - text += row.chars[c].uchar; - indenting = false; - } - } - //To be used for cleaning-up orphaned roll-up captions - row.cueStartTime = startTime; - - // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE - if (startTime === endTime) { - endTime += 0.0001; - } - - cue = new VTTCue(startTime, endTime, (0, _vttparser.fixLineBreaks)(text.trim())); - - if (indent >= 16) { - indent--; - } else { - indent++; - } - - // VTTCue.line get's flakey when using controls, so let's now include line 13&14 - // also, drop line 1 since it's to close to the top - if (navigator.userAgent.match(/Firefox\//)) { - cue.line = r + 1; - } else { - cue.line = r > 7 ? r - 2 : r + 1; - } - cue.align = 'left'; - // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break - cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0))); - track.addCue(cue); - } - } - } - -}; - -module.exports = Cues; - -},{"57":57}],51:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.findFragWithCC = findFragWithCC; - -var _binarySearch = _dereq_(48); - -var _binarySearch2 = _interopRequireDefault(_binarySearch); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function findFragWithCC(fragments, CC) { - return _binarySearch2.default.search(fragments, function (candidate) { - if (candidate.cc < CC) { - return 1; - } else if (candidate.cc > CC) { - return -1; - } else { - return 0; - } - }); -} - -},{"48":48}],52:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* - * EWMA Bandwidth Estimator - * - heavily inspired from shaka-player - * Tracks bandwidth samples and estimates available bandwidth. - * Based on the minimum of two exponentially-weighted moving averages with - * different half-lives. - */ - -var _ewma = _dereq_(53); - -var _ewma2 = _interopRequireDefault(_ewma); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var EwmaBandWidthEstimator = function () { - function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) { - _classCallCheck$$1(this, EwmaBandWidthEstimator); - - this.hls = hls; - this.defaultEstimate_ = defaultEstimate; - this.minWeight_ = 0.001; - this.minDelayMs_ = 50; - this.slow_ = new _ewma2.default(slow); - this.fast_ = new _ewma2.default(fast); - } - - _createClass$$1(EwmaBandWidthEstimator, [{ - key: 'sample', - value: function sample(durationMs, numBytes) { - durationMs = Math.max(durationMs, this.minDelayMs_); - var bandwidth = 8000 * numBytes / durationMs, - - //console.log('instant bw:'+ Math.round(bandwidth)); - // we weight sample using loading duration.... - weight = durationMs / 1000; - this.fast_.sample(weight, bandwidth); - this.slow_.sample(weight, bandwidth); - } - }, { - key: 'canEstimate', - value: function canEstimate() { - var fast = this.fast_; - return fast && fast.getTotalWeight() >= this.minWeight_; - } - }, { - key: 'getEstimate', - value: function getEstimate() { - if (this.canEstimate()) { - //console.log('slow estimate:'+ Math.round(this.slow_.getEstimate())); - //console.log('fast estimate:'+ Math.round(this.fast_.getEstimate())); - // Take the minimum of these two estimates. This should have the effect of - // adapting down quickly, but up more slowly. - return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate()); - } else { - return this.defaultEstimate_; - } - } - }, { - key: 'destroy', - value: function destroy() {} - }]); - - return EwmaBandWidthEstimator; -}(); - -exports.default = EwmaBandWidthEstimator; - -},{"53":53}],53:[function(_dereq_,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -/* - * compute an Exponential Weighted moving average - * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average - * - heavily inspired from shaka-player - */ - -var EWMA = function () { - - // About half of the estimated value will be from the last |halfLife| samples by weight. - function EWMA(halfLife) { - _classCallCheck$$1(this, EWMA); - - // Larger values of alpha expire historical data more slowly. - this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0; - this.estimate_ = 0; - this.totalWeight_ = 0; - } - - _createClass$$1(EWMA, [{ - key: "sample", - value: function sample(weight, value) { - var adjAlpha = Math.pow(this.alpha_, weight); - this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_; - this.totalWeight_ += weight; - } - }, { - key: "getTotalWeight", - value: function getTotalWeight() { - return this.totalWeight_; - } - }, { - key: "getEstimate", - value: function getEstimate() { - if (this.alpha_) { - var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); - return this.estimate_ / zeroFactor; - } else { - return this.estimate_; - } - } - }]); - - return EWMA; -}(); - -exports.default = EWMA; - -},{}],54:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof$$1 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -function noop() {} - -var fakeLogger = { - trace: noop, - debug: noop, - log: noop, - warn: noop, - info: noop, - error: noop -}; - -var exportedLogger = fakeLogger; - -/*globals self: false */ - -//let lastCallTime; -// function formatMsgWithTimeInfo(type, msg) { -// const now = Date.now(); -// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0'; -// lastCallTime = now; -// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )'; -// return msg; -// } - -function formatMsg(type, msg) { - msg = '[' + type + '] > ' + msg; - return msg; -} - -function consolePrintFn(type) { - var func = self.console[type]; - if (func) { - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - if (args[0]) { - args[0] = formatMsg(type, args[0]); - } - func.apply(self.console, args); - }; - } - return noop; -} - -function exportLoggerFunctions(debugConfig) { - for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - functions[_key2 - 1] = arguments[_key2]; - } - - functions.forEach(function (type) { - exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type); - }); -} - -var enableLogs = exports.enableLogs = function enableLogs(debugConfig) { - if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof$$1(debugConfig)) === 'object') { - exportLoggerFunctions(debugConfig, - // Remove out from list here to hard-disable a log-level - //'trace', - 'debug', 'log', 'info', 'warn', 'error'); - // Some browsers don't allow to use bind on console object anyway - // fallback to default if needed - try { - exportedLogger.log(); - } catch (e) { - exportedLogger = fakeLogger; - } - } else { - exportedLogger = fakeLogger; - } -}; - -var logger = exports.logger = exportedLogger; - -},{}],55:[function(_dereq_,module,exports){ -'use strict'; - -/** - * TimeRanges to string helper - */ - -var TimeRanges = { - toString: function toString(r) { - var log = '', - len = r.length; - for (var i = 0; i < len; i++) { - log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']'; - } - return log; - } -}; - -module.exports = TimeRanges; - -},{}],56:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -/** - * Copyright 2013 vtt.js Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -exports.default = function () { - if (typeof window !== 'undefined' && window.VTTCue) { - return window.VTTCue; - } - - var autoKeyword = 'auto'; - var directionSetting = { - '': true, - lr: true, - rl: true - }; - var alignSetting = { - start: true, - middle: true, - end: true, - left: true, - right: true - }; - - function findDirectionSetting(value) { - if (typeof value !== 'string') { - return false; - } - var dir = directionSetting[value.toLowerCase()]; - return dir ? value.toLowerCase() : false; - } - - function findAlignSetting(value) { - if (typeof value !== 'string') { - return false; - } - var align = alignSetting[value.toLowerCase()]; - return align ? value.toLowerCase() : false; - } - - function extend(obj) { - var i = 1; - for (; i < arguments.length; i++) { - var cobj = arguments[i]; - for (var p in cobj) { - obj[p] = cobj[p]; - } - } - - return obj; - } - - function VTTCue(startTime, endTime, text) { - var cue = this; - var isIE8 = function () { - if (typeof navigator === 'undefined') { - return; - } - return (/MSIE\s8\.0/.test(navigator.userAgent) - ); - }(); - var baseObj = {}; - - if (isIE8) { - cue = document.createElement('custom'); - } else { - baseObj.enumerable = true; - } - - /** - * Shim implementation specific properties. These properties are not in - * the spec. - */ - - // Lets us know when the VTTCue's data has changed in such a way that we need - // to recompute its display state. This lets us compute its display state - // lazily. - cue.hasBeenReset = false; - - /** - * VTTCue and TextTrackCue properties - * http://dev.w3.org/html5/webvtt/#vttcue-interface - */ - - var _id = ''; - var _pauseOnExit = false; - var _startTime = startTime; - var _endTime = endTime; - var _text = text; - var _region = null; - var _vertical = ''; - var _snapToLines = true; - var _line = 'auto'; - var _lineAlign = 'start'; - var _position = 50; - var _positionAlign = 'middle'; - var _size = 50; - var _align = 'middle'; - - Object.defineProperty(cue, 'id', extend({}, baseObj, { - get: function get() { - return _id; - }, - set: function set(value) { - _id = '' + value; - } - })); - - Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, { - get: function get() { - return _pauseOnExit; - }, - set: function set(value) { - _pauseOnExit = !!value; - } - })); - - Object.defineProperty(cue, 'startTime', extend({}, baseObj, { - get: function get() { - return _startTime; - }, - set: function set(value) { - if (typeof value !== 'number') { - throw new TypeError('Start time must be set to a number.'); - } - _startTime = value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'endTime', extend({}, baseObj, { - get: function get() { - return _endTime; - }, - set: function set(value) { - if (typeof value !== 'number') { - throw new TypeError('End time must be set to a number.'); - } - _endTime = value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'text', extend({}, baseObj, { - get: function get() { - return _text; - }, - set: function set(value) { - _text = '' + value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'region', extend({}, baseObj, { - get: function get() { - return _region; - }, - set: function set(value) { - _region = value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'vertical', extend({}, baseObj, { - get: function get() { - return _vertical; - }, - set: function set(value) { - var setting = findDirectionSetting(value); - // Have to check for false because the setting an be an empty string. - if (setting === false) { - throw new SyntaxError('An invalid or illegal string was specified.'); - } - _vertical = setting; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, { - get: function get() { - return _snapToLines; - }, - set: function set(value) { - _snapToLines = !!value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'line', extend({}, baseObj, { - get: function get() { - return _line; - }, - set: function set(value) { - if (typeof value !== 'number' && value !== autoKeyword) { - throw new SyntaxError('An invalid number or illegal string was specified.'); - } - _line = value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, { - get: function get() { - return _lineAlign; - }, - set: function set(value) { - var setting = findAlignSetting(value); - if (!setting) { - throw new SyntaxError('An invalid or illegal string was specified.'); - } - _lineAlign = setting; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'position', extend({}, baseObj, { - get: function get() { - return _position; - }, - set: function set(value) { - if (value < 0 || value > 100) { - throw new Error('Position must be between 0 and 100.'); - } - _position = value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, { - get: function get() { - return _positionAlign; - }, - set: function set(value) { - var setting = findAlignSetting(value); - if (!setting) { - throw new SyntaxError('An invalid or illegal string was specified.'); - } - _positionAlign = setting; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'size', extend({}, baseObj, { - get: function get() { - return _size; - }, - set: function set(value) { - if (value < 0 || value > 100) { - throw new Error('Size must be between 0 and 100.'); - } - _size = value; - this.hasBeenReset = true; - } - })); - - Object.defineProperty(cue, 'align', extend({}, baseObj, { - get: function get() { - return _align; - }, - set: function set(value) { - var setting = findAlignSetting(value); - if (!setting) { - throw new SyntaxError('An invalid or illegal string was specified.'); - } - _align = setting; - this.hasBeenReset = true; - } - })); - - /** - * Other <track> spec defined properties - */ - - // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state - cue.displayState = undefined; - - if (isIE8) { - return cue; - } - } - - /** - * VTTCue methods - */ - - VTTCue.prototype.getCueAsHTML = function () { - // Assume WebVTT.convertCueToDOMTree is on the global. - var WebVTT = window.WebVTT; - return WebVTT.convertCueToDOMTree(window, this.text); - }; - - return VTTCue; -}(); - -},{}],57:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.fixLineBreaks = undefined; - -var _vttcue = _dereq_(56); - -var _vttcue2 = _interopRequireDefault(_vttcue); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var StringDecoder = function StringDecoder() { - return { - decode: function decode(data) { - if (!data) { - return ''; - } - if (typeof data !== 'string') { - throw new Error('Error - expected string data.'); - } - return decodeURIComponent(encodeURIComponent(data)); - } - }; -}; /* - * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716 - */ - -function VTTParser() { - this.window = window; - this.state = 'INITIAL'; - this.buffer = ''; - this.decoder = new StringDecoder(); - this.regionList = []; -} - -// Try to parse input as a time stamp. -function parseTimeStamp(input) { - - function computeSeconds(h, m, s, f) { - return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; - } - - var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); - if (!m) { - return null; - } - - if (m[3]) { - // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] - return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]); - } else if (m[1] > 59) { - // Timestamp takes the form of [hours]:[minutes].[milliseconds] - // First position is hours as it's over 59. - return computeSeconds(m[1], m[2], 0, m[4]); - } else { - // Timestamp takes the form of [minutes]:[seconds].[milliseconds] - return computeSeconds(0, m[1], m[2], m[4]); - } -} - -// A settings object holds key/value pairs and will ignore anything but the first -// assignment to a specific key. -function Settings() { - this.values = Object.create(null); -} - -Settings.prototype = { - // Only accept the first assignment to any key. - set: function set(k, v) { - if (!this.get(k) && v !== '') { - this.values[k] = v; - } - }, - // Return the value for a key, or a default value. - // If 'defaultKey' is passed then 'dflt' is assumed to be an object with - // a number of possible default values as properties where 'defaultKey' is - // the key of the property that will be chosen; otherwise it's assumed to be - // a single value. - get: function get(k, dflt, defaultKey) { - if (defaultKey) { - return this.has(k) ? this.values[k] : dflt[defaultKey]; - } - return this.has(k) ? this.values[k] : dflt; - }, - // Check whether we have a value for a key. - has: function has(k) { - return k in this.values; - }, - // Accept a setting if its one of the given alternatives. - alt: function alt(k, v, a) { - for (var n = 0; n < a.length; ++n) { - if (v === a[n]) { - this.set(k, v); - break; - } - } - }, - // Accept a setting if its a valid (signed) integer. - integer: function integer(k, v) { - if (/^-?\d+$/.test(v)) { - // integer - this.set(k, parseInt(v, 10)); - } - }, - // Accept a setting if its a valid percentage. - percent: function percent(k, v) { - var m; - if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) { - v = parseFloat(v); - if (v >= 0 && v <= 100) { - this.set(k, v); - return true; - } - } - return false; - } -}; - -// Helper function to parse input into groups separated by 'groupDelim', and -// interprete each group as a key/value pair separated by 'keyValueDelim'. -function parseOptions(input, callback, keyValueDelim, groupDelim) { - var groups = groupDelim ? input.split(groupDelim) : [input]; - for (var i in groups) { - if (typeof groups[i] !== 'string') { - continue; - } - var kv = groups[i].split(keyValueDelim); - if (kv.length !== 2) { - continue; - } - var k = kv[0]; - var v = kv[1]; - callback(k, v); - } -} - -var defaults = new _vttcue2.default(0, 0, 0); -// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244 -// Chrome and Safari don't yet support this change, but FF does -var center = defaults.align === 'middle' ? 'middle' : 'center'; - -function parseCue(input, cue, regionList) { - // Remember the original input if we need to throw an error. - var oInput = input; - // 4.1 WebVTT timestamp - function consumeTimeStamp() { - var ts = parseTimeStamp(input); - if (ts === null) { - throw new Error('Malformed timestamp: ' + oInput); - } - // Remove time stamp from input. - input = input.replace(/^[^\sa-zA-Z-]+/, ''); - return ts; - } - - // 4.4.2 WebVTT cue settings - function consumeCueSettings(input, cue) { - var settings = new Settings(); - - parseOptions(input, function (k, v) { - switch (k) { - case 'region': - // Find the last region we parsed with the same region id. - for (var i = regionList.length - 1; i >= 0; i--) { - if (regionList[i].id === v) { - settings.set(k, regionList[i].region); - break; - } - } - break; - case 'vertical': - settings.alt(k, v, ['rl', 'lr']); - break; - case 'line': - var vals = v.split(','), - vals0 = vals[0]; - settings.integer(k, vals0); - if (settings.percent(k, vals0)) { - settings.set('snapToLines', false); - } - settings.alt(k, vals0, ['auto']); - if (vals.length === 2) { - settings.alt('lineAlign', vals[1], ['start', center, 'end']); - } - break; - case 'position': - vals = v.split(','); - settings.percent(k, vals[0]); - if (vals.length === 2) { - settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']); - } - break; - case 'size': - settings.percent(k, v); - break; - case 'align': - settings.alt(k, v, ['start', center, 'end', 'left', 'right']); - break; - } - }, /:/, /\s/); - - // Apply default values for any missing fields. - cue.region = settings.get('region', null); - cue.vertical = settings.get('vertical', ''); - var line = settings.get('line', 'auto'); - if (line === 'auto' && defaults.line === -1) { - // set numeric line number for Safari - line = -1; - } - cue.line = line; - cue.lineAlign = settings.get('lineAlign', 'start'); - cue.snapToLines = settings.get('snapToLines', true); - cue.size = settings.get('size', 100); - cue.align = settings.get('align', center); - var position = settings.get('position', 'auto'); - if (position === 'auto' && defaults.position === 50) { - // set numeric position for Safari - position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50; - } - cue.position = position; - } - - function skipWhitespace() { - input = input.replace(/^\s+/, ''); - } - - // 4.1 WebVTT cue timings. - skipWhitespace(); - cue.startTime = consumeTimeStamp(); // (1) collect cue start time - skipWhitespace(); - if (input.substr(0, 3) !== '-->') { - // (3) next characters must match '-->' - throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput); - } - input = input.substr(3); - skipWhitespace(); - cue.endTime = consumeTimeStamp(); // (5) collect cue end time - - // 4.1 WebVTT cue settings list. - skipWhitespace(); - consumeCueSettings(input, cue); -} - -function fixLineBreaks(input) { - return input.replace(/<br(?: \/)?>/gi, '\n'); -} - -VTTParser.prototype = { - parse: function parse(data) { - var self = this; - - // If there is no data then we won't decode it, but will just try to parse - // whatever is in buffer already. This may occur in circumstances, for - // example when flush() is called. - if (data) { - // Try to decode the data that we received. - self.buffer += self.decoder.decode(data, { stream: true }); - } - - function collectNextLine() { - var buffer = self.buffer; - var pos = 0; - - buffer = fixLineBreaks(buffer); - - while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { - ++pos; - } - var line = buffer.substr(0, pos); - // Advance the buffer early in case we fail below. - if (buffer[pos] === '\r') { - ++pos; - } - if (buffer[pos] === '\n') { - ++pos; - } - self.buffer = buffer.substr(pos); - return line; - } - - // 3.2 WebVTT metadata header syntax - function parseHeader(input) { - parseOptions(input, function (k, v) { - switch (k) { - case 'Region': - // 3.3 WebVTT region metadata header syntax - console.log('parse region', v); - //parseRegion(v); - break; - } - }, /:/); - } - - // 5.1 WebVTT file parsing. - try { - var line; - if (self.state === 'INITIAL') { - // We can't start parsing until we have the first line. - if (!/\r\n|\n/.test(self.buffer)) { - return this; - } - - line = collectNextLine(); - - var m = line.match(/^WEBVTT([ \t].*)?$/); - if (!m || !m[0]) { - throw new Error('Malformed WebVTT signature.'); - } - - self.state = 'HEADER'; - } - - var alreadyCollectedLine = false; - while (self.buffer) { - // We can't parse a line until we have the full line. - if (!/\r\n|\n/.test(self.buffer)) { - return this; - } - - if (!alreadyCollectedLine) { - line = collectNextLine(); - } else { - alreadyCollectedLine = false; - } - - switch (self.state) { - case 'HEADER': - // 13-18 - Allow a header (metadata) under the WEBVTT line. - if (/:/.test(line)) { - parseHeader(line); - } else if (!line) { - // An empty line terminates the header and starts the body (cues). - self.state = 'ID'; - } - continue; - case 'NOTE': - // Ignore NOTE blocks. - if (!line) { - self.state = 'ID'; - } - continue; - case 'ID': - // Check for the start of NOTE blocks. - if (/^NOTE($|[ \t])/.test(line)) { - self.state = 'NOTE'; - break; - } - // 19-29 - Allow any number of line terminators, then initialize new cue values. - if (!line) { - continue; - } - self.cue = new _vttcue2.default(0, 0, ''); - self.state = 'CUE'; - // 30-39 - Check if self line contains an optional identifier or timing data. - if (line.indexOf('-->') === -1) { - self.cue.id = line; - continue; - } - // Process line as start of a cue. - /*falls through*/ - case 'CUE': - // 40 - Collect cue timings and settings. - try { - parseCue(line, self.cue, self.regionList); - } catch (e) { - // In case of an error ignore rest of the cue. - self.cue = null; - self.state = 'BADCUE'; - continue; - } - self.state = 'CUETEXT'; - continue; - case 'CUETEXT': - var hasSubstring = line.indexOf('-->') !== -1; - // 34 - If we have an empty line then report the cue. - // 35 - If we have the special substring '-->' then report the cue, - // but do not collect the line as we need to process the current - // one as a new cue. - if (!line || hasSubstring && (alreadyCollectedLine = true)) { - // We are done parsing self cue. - if (self.oncue) { - self.oncue(self.cue); - } - self.cue = null; - self.state = 'ID'; - continue; - } - if (self.cue.text) { - self.cue.text += '\n'; - } - self.cue.text += line; - continue; - case 'BADCUE': - // BADCUE - // 54-62 - Collect and discard the remaining cue. - if (!line) { - self.state = 'ID'; - } - continue; - } - } - } catch (e) { - - // If we are currently parsing a cue, report what we have. - if (self.state === 'CUETEXT' && self.cue && self.oncue) { - self.oncue(self.cue); - } - self.cue = null; - // Enter BADWEBVTT state if header was not parsed correctly otherwise - // another exception occurred so enter BADCUE state. - self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE'; - } - return this; - }, - flush: function flush() { - var self = this; - try { - // Finish decoding the stream. - self.buffer += self.decoder.decode(); - // Synthesize the end of the current cue or region. - if (self.cue || self.state === 'HEADER') { - self.buffer += '\n\n'; - self.parse(); - } - // If we've flushed, parsed, and we're still on the INITIAL state then - // that means we don't have enough of the stream to parse the first - // line. - if (self.state === 'INITIAL') { - throw new Error('Malformed WebVTT signature.'); - } - } catch (e) { - throw e; - } - if (self.onflush) { - self.onflush(); - } - return this; - } -}; - -exports.fixLineBreaks = fixLineBreaks; -exports.default = VTTParser; - -},{"56":56}],58:[function(_dereq_,module,exports){ -'use strict'; - -var _vttparser = _dereq_(57); - -var _vttparser2 = _interopRequireDefault(_vttparser); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// String.prototype.startsWith is not supported in IE11 -var startsWith = function startsWith(inputString, searchString, position) { - return inputString.substr(position || 0, searchString.length) === searchString; -}; - -var cueString2millis = function cueString2millis(timeString) { - var ts = parseInt(timeString.substr(-3)); - var secs = parseInt(timeString.substr(-6, 2)); - var mins = parseInt(timeString.substr(-9, 2)); - var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0; - - if (isNaN(ts) || isNaN(secs) || isNaN(mins) || isNaN(hours)) { - return -1; - } - - ts += 1000 * secs; - ts += 60 * 1000 * mins; - ts += 60 * 60 * 1000 * hours; - - return ts; -}; - -// From https://github.com/darkskyapp/string-hash -var hash = function hash(text) { - var hash = 5381; - var i = text.length; - while (i) { - hash = hash * 33 ^ text.charCodeAt(--i); - } - return (hash >>> 0).toString(); -}; - -var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) { - var currCC = vttCCs[cc]; - var prevCC = vttCCs[currCC.prevCC]; - - // This is the first discontinuity or cues have been processed since the last discontinuity - // Offset = current discontinuity time - if (!prevCC || !prevCC.new && currCC.new) { - vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start; - currCC.new = false; - return; - } - - // There have been discontinuities since cues were last parsed. - // Offset = time elapsed - while (prevCC && prevCC.new) { - vttCCs.ccOffset += currCC.start - prevCC.start; - currCC.new = false; - currCC = prevCC; - prevCC = vttCCs[currCC.prevCC]; - } - - vttCCs.presentationOffset = presentationTime; -}; - -var WebVTTParser = { - parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) { - // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character. - var re = /\r\n|\n\r|\n|\r/g; - var vttLines = String.fromCharCode.apply(null, new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n'); - var cueTime = '00:00.000'; - var mpegTs = 0; - var localTime = 0; - var presentationTime = 0; - var cues = []; - var parsingError = void 0; - var inHeader = true; - // let VTTCue = VTTCue || window.TextTrackCue; - - // Create parser object using VTTCue with TextTrackCue fallback on certain browsers. - var parser = new _vttparser2.default(); - - parser.oncue = function (cue) { - // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline. - var currCC = vttCCs[cc]; - var cueOffset = vttCCs.ccOffset; - - // Update offsets for new discontinuities - if (currCC && currCC.new) { - if (localTime !== undefined) { - // When local time is provided, offset = discontinuity start time - local time - cueOffset = vttCCs.ccOffset = currCC.start; - } else { - calculateOffset(vttCCs, cc, presentationTime); - } - } - - if (presentationTime) { - // If we have MPEGTS, offset = presentation time + discontinuity offset - cueOffset = presentationTime + vttCCs.ccOffset - vttCCs.presentationOffset; - } - - cue.startTime += cueOffset - localTime; - cue.endTime += cueOffset - localTime; - - // Create a unique hash id for a cue based on start/end times and text. - // This helps timeline-controller to avoid showing repeated captions. - cue.id = hash(cue.startTime) + hash(cue.endTime) + hash(cue.text); - - // Fix encoding of special characters. TODO: Test with all sorts of weird characters. - cue.text = decodeURIComponent(escape(cue.text)); - if (cue.endTime > 0) { - cues.push(cue); - } - }; - - parser.onparsingerror = function (e) { - parsingError = e; - }; - - parser.onflush = function () { - if (parsingError && errorCallBack) { - errorCallBack(parsingError); - return; - } - callBack(cues); - }; - - // Go through contents line by line. - vttLines.forEach(function (line) { - if (inHeader) { - // Look for X-TIMESTAMP-MAP in header. - if (startsWith(line, 'X-TIMESTAMP-MAP=')) { - // Once found, no more are allowed anyway, so stop searching. - inHeader = false; - // Extract LOCAL and MPEGTS. - line.substr(16).split(',').forEach(function (timestamp) { - if (startsWith(timestamp, 'LOCAL:')) { - cueTime = timestamp.substr(6); - } else if (startsWith(timestamp, 'MPEGTS:')) { - mpegTs = parseInt(timestamp.substr(7)); - } - }); - try { - // Calculate subtitle offset in milliseconds. - // If sync PTS is less than zero, we have a 33-bit wraparound, which is fixed by adding 2^33 = 8589934592. - syncPTS = syncPTS < 0 ? syncPTS + 8589934592 : syncPTS; - // Adjust MPEGTS by sync PTS. - mpegTs -= syncPTS; - // Convert cue time to seconds - localTime = cueString2millis(cueTime) / 1000; - // Convert MPEGTS to seconds from 90kHz. - presentationTime = mpegTs / 90000; - - if (localTime === -1) { - parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line); - } - } catch (e) { - parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line); - } - // Return without parsing X-TIMESTAMP-MAP line. - return; - } else if (line === '') { - inHeader = false; - } - } - // Parse line by default. - parser.parse(line + '\n'); - }); - - parser.flush(); - } -}; - -module.exports = WebVTTParser; - -},{"57":57}],59:[function(_dereq_,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createClass$$1 = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** - * XHR based logger - */ - -var _logger = _dereq_(54); - -function _classCallCheck$$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var XhrLoader = function () { - function XhrLoader(config) { - _classCallCheck$$1(this, XhrLoader); - - if (config && config.xhrSetup) { - this.xhrSetup = config.xhrSetup; - } - } - - _createClass$$1(XhrLoader, [{ - key: 'destroy', - value: function destroy() { - this.abort(); - this.loader = null; - } - }, { - key: 'abort', - value: function abort() { - var loader = this.loader; - if (loader && loader.readyState !== 4) { - this.stats.aborted = true; - loader.abort(); - } - - window.clearTimeout(this.requestTimeout); - this.requestTimeout = null; - window.clearTimeout(this.retryTimeout); - this.retryTimeout = null; - } - }, { - key: 'load', - value: function load(context, config, callbacks) { - this.context = context; - this.config = config; - this.callbacks = callbacks; - this.stats = { trequest: performance.now(), retry: 0 }; - this.retryDelay = config.retryDelay; - this.loadInternal(); - } - }, { - key: 'loadInternal', - value: function loadInternal() { - var xhr, - context = this.context; - - if (typeof XDomainRequest !== 'undefined') { - xhr = this.loader = new XDomainRequest(); - } else { - xhr = this.loader = new XMLHttpRequest(); - } - var stats = this.stats; - stats.tfirst = 0; - stats.loaded = 0; - var xhrSetup = this.xhrSetup; - - try { - if (xhrSetup) { - try { - xhrSetup(xhr, context.url); - } catch (e) { - // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");} - // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN - xhr.open('GET', context.url, true); - xhrSetup(xhr, context.url); - } - } - if (!xhr.readyState) { - xhr.open('GET', context.url, true); - } - } catch (e) { - // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS - this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr); - return; - } - - if (context.rangeEnd) { - xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1)); - } - xhr.onreadystatechange = this.readystatechange.bind(this); - xhr.onprogress = this.loadprogress.bind(this); - xhr.responseType = context.responseType; - - // setup timeout before we perform request - this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout); - xhr.send(); - } - }, { - key: 'readystatechange', - value: function readystatechange(event) { - var xhr = event.currentTarget, - readyState = xhr.readyState, - stats = this.stats, - context = this.context, - config = this.config; - - // don't proceed if xhr has been aborted - if (stats.aborted) { - return; - } - - // >= HEADERS_RECEIVED - if (readyState >= 2) { - // clear xhr timeout and rearm it if readyState less than 4 - window.clearTimeout(this.requestTimeout); - if (stats.tfirst === 0) { - stats.tfirst = Math.max(performance.now(), stats.trequest); - } - if (readyState === 4) { - var status = xhr.status; - // http status between 200 to 299 are all successful - if (status >= 200 && status < 300) { - stats.tload = Math.max(stats.tfirst, performance.now()); - var data = void 0, - len = void 0; - if (context.responseType === 'arraybuffer') { - data = xhr.response; - len = data.byteLength; - } else { - data = xhr.responseText; - len = data.length; - } - stats.loaded = stats.total = len; - var response = { url: xhr.responseURL, data: data }; - this.callbacks.onSuccess(response, stats, context, xhr); - } else { - // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error - if (stats.retry >= config.maxRetry || status >= 400 && status < 499) { - _logger.logger.error(status + ' while loading ' + context.url); - this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr); - } else { - // retry - _logger.logger.warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...'); - // aborts and resets internal state - this.destroy(); - // schedule retry - this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay); - // set exponential backoff - this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay); - stats.retry++; - } - } - } else { - // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet - this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout); - } - } - } - }, { - key: 'loadtimeout', - value: function loadtimeout() { - _logger.logger.warn('timeout while loading ' + this.context.url); - this.callbacks.onTimeout(this.stats, this.context, null); - } - }, { - key: 'loadprogress', - value: function loadprogress(event) { - var xhr = event.currentTarget, - stats = this.stats; - - stats.loaded = event.loaded; - if (event.lengthComputable) { - stats.total = event.total; - } - var onProgress = this.callbacks.onProgress; - if (onProgress) { - // third arg is to provide on progress data - onProgress(stats, this.context, null, xhr); - } - } - }]); - - return XhrLoader; -}(); - -exports.default = XhrLoader; - -},{"54":54}]},{},[40])(40) -}); - -}); - -var HlsCore = unwrapExports$1(hls); - -var defaultConfig$2 = { - type: 'vod', - autoPlay: false, - box: 'hls', - lockInternalProperty: false, - debug: true, - enableWorker: true -}; - -var Hls = function (_CustEvent) { - _inherits(Hls, _CustEvent); - - function Hls(videodom, config) { - _classCallCheck(this, Hls); - - var _this2 = _possibleConstructorReturn(this, (Hls.__proto__ || _Object$getPrototypeOf(Hls)).call(this)); - - _this2.tag = 'HLS-player'; - _this2.video = videodom; - _this2.box = 'hls'; - _this2.config = defaultConfig$2; - deepAssign(_this2.config, config); - _this2.hls = new HlsCore(); - _this2.bindEvents(_this2.hls); - _this2.attachMedia(); - return _this2; - } - - _createClass(Hls, [{ - key: 'internalPropertyHandle', - value: function internalPropertyHandle() { - if (!_Object$getOwnPropertyDescriptor) { - return; - } - var _this = this; - var time = _Object$getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'currentTime'); - - Object.defineProperty(this.video, 'currentTime', { - get: function get() { - return time.get.call(_this.video); - }, - set: function set(t) { - if (!_this.currentTimeLock) { - throw new Error('can not set currentTime by youself'); - } else { - return time.set.call(_this.video, t); - } - } - }); - } - }, { - key: 'bindEvents', - value: function bindEvents(hlsKernel) { - var _this3 = this; - - if (hlsKernel) { - hlsKernel.on(HlsCore.Events.ERROR, function (event, data) { - // this.emit(this.tag, data); - }); - - hlsKernel.on(HlsCore.Events.LEVEL, function (event, data) {}); - } - if (this.video && this.config.lockInternalProperty) { - this.video.addEventListener('canplay', function () { - _this3.internalPropertyHandle(); - }); - } - } - }, { - key: 'load', - value: function load() { - this.hls.loadSource(this.config.src); - } - }, { - key: 'attachMedia', - value: function attachMedia() { - this.hls.attachMedia(this.video); - } - }, { - key: 'play', - value: function play() { - return this.video.play(); - } - }, { - key: 'destroy', - value: function destroy() { - return this.hls.destroy(); - } - }, { - key: 'seek', - value: function seek(seconds) { - this.currentTimeLock = true; - // throttle(this._seek.bind(this, seconds), 200, {leading: false}); - this._seek(seconds); - this.currentTimeLock = false; - } - }, { - key: '_seek', - value: function _seek(seconds) { - this.video.currentTime = seconds; - } - }, { - key: 'pause', - value: function pause() { - return this.video.pause(); - } - }]); - - return Hls; -}(CustEvent); - -var Kernel = function (_CustEvent) { - _inherits(Kernel, _CustEvent); - - /** - * 创建核心解码器 - * @param {any} wrap 父层容器 - * @param {any} option 整合参数 - * @\ kernel - */ - function Kernel(videoElement, config) { - _classCallCheck(this, Kernel); - - var _this = _possibleConstructorReturn(this, (Kernel.__proto__ || _Object$getPrototypeOf(Kernel)).call(this)); - - _this.tag = 'kernel'; - _this.config = config; - _this.video = videoElement; - _this.videokernel = _this.selectKernel(); - _this.bindEvents(_this.videokernel); - return _this; - } - - /** - * 绑定事件 - * @memberof kernel - */ - - - _createClass(Kernel, [{ - key: 'bindEvents', - value: function bindEvents(videokernel) { - var _this2 = this; - - if (videokernel) { - videokernel.on('mediaInfo', function (mediaInfo) { - _this2.emit('mediaInfo', mediaInfo); - }); - } - } - - /** - * 选择解码器 - * @memberof kernel - */ - - }, { - key: 'selectKernel', - value: function selectKernel() { - var config = this.config; - - var box = config.box ? config.box : config.src.indexOf('.flv') !== -1 ? 'flv' : config.src.indexOf('.m3u8') !== -1 ? 'hls' : 'mp4'; - - if (box === 'mp4') { - return new Mp4(this.video, config); - } else if (box === 'flv') { - return new Flv(this.video, config); - } else if (box === 'hls') { - console.log(config); - return new Hls(this.video, config); - } else { - Log.error(this.tag, 'not mactch any player, please check your config'); - return null; - } - } - }, { - key: 'attachMedia', - value: function attachMedia() { - if (this.videokernel) { - this.videokernel.attachMedia(); - } else { - Log.error(this.tag, 'video player is not already, must init player'); - } - } - - /** - * 启动加载 - * @param {string} src 媒体资源地址 - * @memberof kernel - */ - - }, { - key: 'load', - value: function load(src) { - this.config.src = src || this.config.src; - if (this.videokernel && this.config.src) { - this.videokernel.load(src); - } else { - Log.error(this.tag, 'video player is not already, must init player'); - } - } - /** - * 销毁kernel - * @memberof kernel - */ - - }, { - key: 'destroy', - value: function destroy() { - if (this.videokernel) { - this.videokernel.destroy(); - } else { - Log.error(this.tag, 'player is not exit'); - } - } - /** - * to play - * @memberof kernel - */ - - }, { - key: 'play', - value: function play() { - if (this.videokernel) { - this.videokernel.play(); - } else { - Log.error(this.tag, 'video player is not already, must init player'); - } - } - /** - * pause - * @memberof kernel - */ - - }, { - key: 'pause', - value: function pause() { - if (this.videokernel && this.config.src) { - this.videokernel.pause(); - } else { - Log.error(this.tag, 'video player is not already, must init player'); - } - } - /** - * get video currentTime - * @memberof kernel - */ - - }, { - key: 'seek', - - /** - * seek to a point - * @memberof kernel - */ - value: function seek(seconds) { - if (!isNumber(seconds)) { - Log.error(this.tag, 'seek params must be a number'); - return; - } - return this.videokernel.seek(seconds); - } - /** - * get video duration - * @memberof kernel - */ + * get video duration + * @memberof kernel + */ }, { key: 'currentTime', @@ -26049,9 +4326,11 @@ module.exports = { "default": map$1, __esModule: true }; var _Map = unwrapExports(map); var videoEvents = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'interruptbegin', 'interruptend', 'loadeddata', 'loadedmetadata', 'loadstart', 'mozaudioavailable', 'pause', 'play', 'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; -var videoReadOnlyProperties = ['buffered', 'currentSrc', 'duration', 'ended', 'networkState', 'paused', 'readyState', 'seekable', 'sinkId', 'controlsList']; +var videoReadOnlyProperties = ['buffered', 'currentSrc', 'duration', 'error', 'ended', 'networkState', 'paused', 'readyState', 'seekable', 'sinkId', 'controlsList', 'tabIndex', 'dataset', 'offsetHeight', 'offsetLeft', 'offsetParent', 'offsetTop', 'offsetWidth']; var domEvents = ['beforeinput', 'blur', 'click', 'compositionend', 'compositionstart', 'compositionupdate', 'dblclick', 'focus', 'focusin', 'focusout', 'input', 'keydown', 'keypress', 'keyup', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll', 'select', 'wheel', 'fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange', 'contextmenu']; -var kernelMethods = ['play', 'pause', 'load', 'seek']; +var selfProcessorEvents = ['silentLoad', 'fullScreen']; +var kernelMethods = ['play', 'pause', 'seek']; +var dispatcherMethods = ['load']; var domMethods = ['focus', 'fullScreen', 'requestFullScreen', 'exitFullScreen']; var videoMethods = ['canPlayType', 'captureStream', 'setSinkId']; @@ -26183,10 +4462,12 @@ var Bus = function () { } var event = this.events[key]; if (isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return _Promise.resolve(); return this._eventProcessor.apply(this, [key, { sync: false }].concat(_toConsumableArray(args))); } var beforeQueue = this._getEventQueue(event.before, this.__dispatcher.order); return runRejectableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))).then(function () { + if (selfProcessorEvents.indexOf(key) > -1) return; return _this._eventProcessor.apply(_this, [key, { sync: false }].concat(_toConsumableArray(args))); }).catch(function (error) { if (isError(error)) _this.__dispatcher.throwError(error); @@ -26215,10 +4496,11 @@ var Bus = function () { } if (isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return true; return this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args))); } var beforeQueue = this._getEventQueue(event.before, this.__dispatcher.order); - return runStoppableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))) && this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args))); + return runStoppableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))) && (selfProcessorEvents.indexOf(key) > -1 || this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args)))); } /** * [Can only be called in dispatcher]trigger an event, which will run main -> after -> side effect period @@ -26439,15 +4721,22 @@ var Bus = function () { var isKernelMethod = kernelMethods.indexOf(key) > -1; var isDomMethod = domMethods.indexOf(key) > -1; + var isDispatcherMethod = dispatcherMethods.indexOf(key) > -1; for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { args[_key5 - 2] = arguments[_key5]; } - if (isKernelMethod || isDomMethod) { - var _dispatcher; + if (isKernelMethod || isDomMethod || isDispatcherMethod) { + if (isDispatcherMethod) { + var _dispatcher; + + (_dispatcher = this.__dispatcher)[key].apply(_dispatcher, _toConsumableArray(args)); + } else { + var _dispatcher2; - (_dispatcher = this.__dispatcher[isKernelMethod ? 'kernel' : 'dom'])[key].apply(_dispatcher, _toConsumableArray(args)); + (_dispatcher2 = this.__dispatcher[isKernelMethod ? 'kernel' : 'dom'])[key].apply(_dispatcher2, _toConsumableArray(args)); + } if (videoEvents.indexOf(key) > -1 || domEvents.indexOf(key) > -1) return true; } // $FlowFixMe: flow do not support computed sytax on classs, but it's ok here @@ -27964,137 +6253,525 @@ function watch() { oldVal = value; return value; } - }, { preSet: false }))(obj, prop, descriptor); - }; + }, { preSet: false }))(obj, prop, descriptor); + }; +} + +var preventExtensions = _Object$preventExtensions; + +function nonextendable(obj, prop, descriptor) { + if (descriptor === undefined) throw new Error('@nonextendable could not handle undefined'); + return initialize(function (value) { + preventExtensions(value); + return value; + })(obj, prop, descriptor); +} + +function nonconfigurable(obj, prop, descriptor) { + if (descriptor === undefined) { + return { + value: undefined, + enumerable: true, + configurable: true, + writable: true + }; + } + descriptor.configurable = true; + return descriptor; +} + +function string() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var defaultValue = isString(args[0]) ? args.shift() : ''; + args.unshift(function (value) { + return isString(value) ? value : defaultValue; + }); + return initialize.apply(undefined, args); +} + +function boolean() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var defaultValue = isBoolean(args[0]) ? args.shift() : false; + args.unshift(function (value) { + return isBoolean(value) ? value : defaultValue; + }); + return initialize.apply(undefined, args); +} + +function string$1() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var defaultValue = isString(args[0]) ? args.shift() : ''; + args.unshift(function (value) { + return isString(value) ? value : defaultValue; + }); + return accessor({ set: args, get: args }); +} + +function boolean$1() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var defaultValue = isBoolean(args[0]) ? args.shift() : false; + args.unshift(function (value) { + return isBoolean(value) ? value : defaultValue; + }); + return accessor({ set: args, get: args }); +} + +function number$1() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var defaultValue = isNumber(args[0]) ? args.shift() : 0; + args.unshift(function (value) { + return isNumber(value) ? value : defaultValue; + }); + return accessor({ set: args, get: args }); +} + +var $JSON$1 = _core.JSON || (_core.JSON = {stringify: JSON.stringify}); +var stringify$1 = function stringify(it){ // eslint-disable-line no-unused-vars + return $JSON$1.stringify.apply($JSON$1, arguments); +}; + +var stringify = createCommonjsModule(function (module) { +module.exports = { "default": stringify$1, __esModule: true }; +}); + +var _JSON$stringify = unwrapExports(stringify); + +/** + * checker for on, off, once function + * @param {string} key + * @param {Function} fn + */ +function eventBinderCheck(key, fn) { + if (!isString(key)) throw new TypeError('key parameter must be String'); + if (!isFunction(fn)) throw new TypeError('fn parameter must be Function'); +} +/** + * checker for attr or css function + */ +function attrAndStyleCheck() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (args.length > 2) { + return ['set'].concat(args); + } + if (args.length === 2) { + if (['video', 'container', 'wrapper', 'videoElement'].indexOf(args[0]) > -1) { + return ['get'].concat(args); + } + return ['set', 'container'].concat(args); + } + return ['get', 'container'].concat(args); +} + +// 20.1.2.4 Number.isNaN(number) + + +_export(_export.S, 'Number', { + isNaN: function isNaN(number){ + return number != number; + } +}); + +var isNan$1 = _core.Number.isNaN; + +var isNan = createCommonjsModule(function (module) { +module.exports = { "default": isNan$1, __esModule: true }; +}); + +var _Number$isNaN = unwrapExports(isNan); + +var _dec$4; +var _dec2$2; +var _class$4; +var _descriptor$1; +var _descriptor2$1; +var _descriptor3$1; +var _descriptor4; +var _descriptor5; +var _descriptor6; +var _descriptor7; + +function _initDefineProp$1(target, property, descriptor, context) { + if (!descriptor) return; + + _Object$defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} + +function _applyDecoratedDescriptor$3(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; +} + +function stringOrVoid(value) { + return isString(value) ? value : undefined; +} + +function accessorVideoProperty(property) { + return accessor({ + get: function get(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement[property] : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + this.dom.videoElement[property] = value; + return value; + } + }); +} + +function accessorVideoAttribute(attribute) { + var _ref = isObject$1(attribute) ? attribute : { + set: attribute, + get: attribute, + isBoolean: false + }, + _set = _ref.set, + _get = _ref.get, + isBoolean$$1 = _ref.isBoolean; + + return accessor({ + get: function get(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement[_get] : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = isBoolean$$1 ? value ? '' : undefined : value; + this.dom.setAttr('video', _set, val); + return value; + } + }); +} + +function accessorCustomAttribute(attribute, isBoolean$$1) { + return accessor({ + get: function get(value) { + var attrValue = this.dom.getAttr('video', attribute); + return this.dispatcher.videoConfigReady && this.inited ? isBoolean$$1 ? !!attrValue : attrValue : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = isBoolean$$1 ? value || undefined : value; + this.dom.setAttr('video', attribute, val); + return value; + } + }); +} + +function accessorWidthAndHeight(property) { + return accessor({ + get: function get(value) { + if (!this.dispatcher.videoConfigReady) return value; + var attr = this.dom.getAttr('video', property); + var prop = this.dom.videoElement[property]; + if (isNumeric(attr) && isNumber(prop)) return prop; + return attr || undefined; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = void 0; + if (value === undefined || isNumber(value)) { + val = value; + } else if (isString(value) && !_Number$isNaN(parseFloat(value))) { + val = value; + } + this.dom.setAttr('video', property, val); + return val; + } + }); } -var preventExtensions = _Object$preventExtensions; +var accessorMap = { + src: [string$1(), accessor({ + set: function set(val) { + // must check val !== this.src here + // as we will set config.src in the video + // the may cause dead lock + if (this.dispatcher.readySync && this.autoload && val !== this.src) this.needToLoadSrc = true; + return val; + } + }), accessor({ + set: function set(val) { + if (this.needToLoadSrc) { + // unlock it at first, to avoid deadlock + this.needToLoadSrc = false; + this.dispatcher.bus.emit('load', val); + } + return val; + } + }, { preSet: false })], + autoload: boolean$1(), + autoplay: [boolean$1(), accessorVideoProperty('autoplay')], + controls: [boolean$1(), accessorVideoProperty('controls')], + width: [accessorWidthAndHeight('width')], + height: [accessorWidthAndHeight('height')], + crossOrigin: [accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' })], + loop: [boolean$1(), accessorVideoProperty('loop')], + defaultMuted: [boolean$1(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true })], + muted: [boolean$1(), accessorVideoProperty('muted')], + preload: [accessor({ set: stringOrVoid }), accessorVideoAttribute('preload')], + poster: [accessor({ set: stringOrVoid }), accessorVideoAttribute('poster')], + playsInline: [accessor({ + get: function get(value) { + var playsInline = this.dom.videoElement.playsInline; + return this.dispatcher.videoConfigReady && this.inited ? playsInline === undefined ? value : playsInline : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + this.dom.videoElement.playsInline = value; + var val = value ? '' : undefined; + this.dom.setAttr('video', 'playsinline', val); + this.dom.setAttr('video', 'webkit-playsinline', val); + this.dom.setAttr('video', 'x5-video-player-type', value ? 'h5' : undefined); + return value; + } + }), boolean$1()], + x5VideoPlayerFullScreen: [accessor({ + set: function set(value) { + return !!value; + }, + get: function get(value) { + return !!value; + } + }), accessorCustomAttribute('x5-video-player-fullscreen', true)], + x5VideoOrientation: [accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], + xWebkitAirplay: [accessor({ + set: function set(value) { + return !!value; + }, + get: function get(value) { + return !!value; + } + }), accessorCustomAttribute('x-webkit-airplay', true)], + playbackRate: [number$1(1), accessorVideoProperty('playbackRate')], + defaultPlaybackRate: [accessorVideoProperty('defaultPlaybackRate'), number$1(1)], + disableRemotePlayback: [boolean$1(), accessorVideoProperty('disableRemotePlayback')], + volume: [number$1(1), accessorVideoProperty('volume')] +}; -function nonextendable(obj, prop, descriptor) { - if (descriptor === undefined) throw new Error('@nonextendable could not handle undefined'); - return initialize(function (value) { - preventExtensions(value); - return value; - })(obj, prop, descriptor); -} +var VideoConfig = (_dec$4 = boolean(), _dec2$2 = string(function (str) { + return str.toLocaleLowerCase(); +}), (_class$4 = function () { + _createClass(VideoConfig, [{ + key: 'lockKernelProperty', + value: function lockKernelProperty() { + applyDecorators(this, { + isLive: lock, + box: lock, + preset: lock + }, { self: true }); + } + }]); -function nonconfigurable(obj, prop, descriptor) { - if (descriptor === undefined) { - return { - value: undefined, - enumerable: true, - configurable: true, - writable: true - }; - } - descriptor.configurable = true; - return descriptor; -} + function VideoConfig(dispatcher, config) { + _classCallCheck(this, VideoConfig); -function string() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + _initDefineProp$1(this, 'needToLoadSrc', _descriptor$1, this); - var defaultValue = isString(args[0]) ? args.shift() : ''; - args.unshift(function (value) { - return isString(value) ? value : defaultValue; - }); - return initialize.apply(undefined, args); -} + _initDefineProp$1(this, 'changeWatchable', _descriptor2$1, this); -function array() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + _initDefineProp$1(this, 'inited', _descriptor3$1, this); - var defaultValue = isArray$1(args[0]) ? args.shift() : []; - args.unshift(function (value) { - return isArray$1(value) ? value : defaultValue; - }); - return initialize.apply(undefined, args); -} + this.src = ''; -function string$1() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + _initDefineProp$1(this, 'isLive', _descriptor4, this); - var defaultValue = isString(args[0]) ? args.shift() : ''; - args.unshift(function (value) { - return isString(value) ? value : defaultValue; - }); - return accessor({ set: args, get: args }); -} + _initDefineProp$1(this, 'box', _descriptor5, this); -function boolean$1() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + this.preset = {}; + this.autoload = true; + this.autoplay = false; + this.controls = false; + this.width = undefined; + this.height = undefined; + this.crossOrigin = undefined; + this.loop = false; + this.defaultMuted = false; + this.muted = false; + this.preload = 'auto'; + this.poster = undefined; + this.playsInline = false; + this.x5VideoPlayerFullScreen = false; + this.x5VideoOrientation = undefined; + this.xWebkitAirplay = false; + this.playbackRate = 1; + this.defaultPlaybackRate = 1; + this.disableRemotePlayback = false; + this.volume = 1; - var defaultValue = isBoolean(args[0]) ? args.shift() : false; - args.unshift(function (value) { - return isBoolean(value) ? value : defaultValue; - }); - return accessor({ set: args, get: args }); -} + _initDefineProp$1(this, '_kernelProperty', _descriptor6, this); -function number$1() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + _initDefineProp$1(this, '_realDomAttr', _descriptor7, this); + + applyDecorators(this, accessorMap, { self: true }); + Object.defineProperty(this, 'dispatcher', { + value: dispatcher, + enumerable: false, + writable: false, + configurable: false + }); + Object.defineProperty(this, 'dom', { + value: dispatcher.dom, + enumerable: false, + writable: false, + configurable: false + }); + deepAssign(this, config); } - var defaultValue = isNumber(args[0]) ? args.shift() : 0; - args.unshift(function (value) { - return isNumber(value) ? value : defaultValue; - }); - return accessor({ set: args, get: args }); -} + _createClass(VideoConfig, [{ + key: 'init', + value: function init() { + var _this = this; -/** - * checker for on, off, once function - * @param {string} key - * @param {Function} fn - */ -function eventBinderCheck(key, fn) { - if (!isString(key)) throw new TypeError('key parameter must be String'); - if (!isFunction(fn)) throw new TypeError('fn parameter must be Function'); -} -/** - * checker for attr or css function - */ -function attrAndStyleCheck() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + this._realDomAttr.forEach(function (key) { + // $FlowFixMe: we have check the computed here + _this[key] = _this[key]; + }); + this.inited = true; + } + }]); + + return VideoConfig; +}(), (_descriptor$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'needToLoadSrc', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor2$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'changeWatchable', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return true; + } +}), _descriptor3$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'inited', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor4 = _applyDecoratedDescriptor$3(_class$4.prototype, 'isLive', [_dec$4, nonconfigurable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor5 = _applyDecoratedDescriptor$3(_class$4.prototype, 'box', [_dec2$2, nonconfigurable], { + enumerable: true, + initializer: function initializer() { + return ''; + } +}), _descriptor6 = _applyDecoratedDescriptor$3(_class$4.prototype, '_kernelProperty', [frozen], { + enumerable: true, + initializer: function initializer() { + return ['isLive', 'box', 'preset']; + } +}), _descriptor7 = _applyDecoratedDescriptor$3(_class$4.prototype, '_realDomAttr', [frozen], { + enumerable: true, + initializer: function initializer() { + return ['src', 'controls', 'width', 'height', 'crossOrigin', 'loop', 'muted', 'preload', 'poster', 'autoplay', 'playsInline', 'x5VideoPlayerFullScreen', 'x5VideoOrientation', 'xWebkitAirplay', 'playbackRate', 'defaultPlaybackRate', 'autoload', 'disableRemotePlayback', 'defaultMuted', 'volume']; } +})), _class$4)); + +var _dec$3; +var _dec2$1; +var _dec3$1; +var _dec4$1; +var _dec5$1; +var _dec6; +var _dec7; +var _dec8; +var _dec9; +var _dec10; +var _dec11; +var _dec12; +var _dec13; +var _dec14; +var _dec15; +var _dec16; +var _dec17; +var _class$3; +var _class2$1; - if (args.length > 2) { - return ['set'].concat(args); - } - if (args.length === 2) { - if (['video', 'container', 'wrapper', 'videoElement'].indexOf(args[0]) > -1) { - return ['get'].concat(args); - } - return ['set', 'container'].concat(args); +function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; } - return ['get', 'container'].concat(args); -} -var $JSON$1 = _core.JSON || (_core.JSON = {stringify: JSON.stringify}); -var stringify$2 = function stringify(it){ // eslint-disable-line no-unused-vars - return $JSON$1.stringify.apply($JSON$1, arguments); -}; + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); -var stringify$1 = createCommonjsModule(function (module) { -module.exports = { "default": stringify$2, __esModule: true }; -}); + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } -var _JSON$stringify = unwrapExports(stringify$1); + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } -var VideoWrapper = function () { + return desc; +} + +function propertyAccessibilityWarn(property) { + Log.warn('chimee', 'You are trying to obtain ' + property + ', we will return you the DOM node. It\'s not a good idea to handle this by yourself. If you have some requirement, you can tell use by https://github.com/Chimeejs/chimee/issues'); +} +var VideoWrapper = (_dec$3 = autobindClass(), _dec2$1 = alias('silentLoad'), _dec3$1 = alias('fullScreen'), _dec4$1 = alias('emit'), _dec5$1 = alias('emitSync'), _dec6 = alias('on'), _dec7 = alias('addEventListener'), _dec8 = before(eventBinderCheck), _dec9 = alias('off'), _dec10 = alias('removeEventListener'), _dec11 = before(eventBinderCheck), _dec12 = alias('once'), _dec13 = before(eventBinderCheck), _dec14 = alias('css'), _dec15 = before(attrAndStyleCheck), _dec16 = alias('attr'), _dec17 = before(attrAndStyleCheck), _dec$3(_class$3 = (_class2$1 = function () { function VideoWrapper() { _classCallCheck(this, VideoWrapper); + this.__events = {}; this.__unwatchHandlers = []; } @@ -28132,9 +6809,11 @@ var VideoWrapper = function () { var props = videoConfig._realDomAttr.concat(videoConfig._kernelProperty).reduce(function (props, key) { props[key] = [accessor({ get: function get() { + // $FlowFixMe: support computed key here return videoConfig[key]; }, set: function set(value) { + // $FlowFixMe: support computed key here videoConfig[key] = value; return value; } @@ -28165,6 +6844,7 @@ var VideoWrapper = function () { }); }); domMethods.forEach(function (key) { + if (key === 'fullScreen') return; _Object$defineProperty(_this, key, { value: function value() { var _dispatcher$dom; @@ -28194,17 +6874,17 @@ var VideoWrapper = function () { if (!isString(key) && !isArray$1(key)) throw new TypeError('$watch only accept string and Array<string> as key to find the target to spy on, but not ' + key + ', whose type is ' + (typeof key === 'undefined' ? 'undefined' : _typeof(key))); var watching = true; var watcher = function watcher() { - if (watching) bind(handler, this).apply(undefined, arguments); + if (watching && (!(this instanceof VideoConfig) || this.dispatcher.changeWatchable)) bind(handler, this).apply(undefined, arguments); }; var unwatcher = function unwatcher() { watching = false; var index = _this3.__unwatchHandlers.indexOf(unwatcher); if (index > -1) _this3.__unwatchHandlers.splice(index, 1); }; - var keys = isString(key) ? key.split('.') : key; - var property = keys.pop(); + var keys$$1 = isString(key) ? key.split('.') : key; + var property = keys$$1.pop(); var videoConfig = this.__dispatcher.videoConfig; - var target = keys.length === 0 && !other && videoConfig._realDomAttr.indexOf(property) > -1 ? videoConfig : getDeepProperty(other || this, keys, { throwError: true }); + var target = keys$$1.length === 0 && !other && videoConfig._realDomAttr.indexOf(property) > -1 ? videoConfig : ['isFullScreen', 'fullScreenElement'].indexOf(property) > -1 ? this.__dispatcher.dom : getDeepProperty(other || this, keys$$1, { throwError: true }); applyDecorators(target, _defineProperty$1({}, property, watch(watcher, { deep: deep, diff: diff, proxy: proxy })), { self: true }); this.__unwatchHandlers.push(unwatcher); return unwatcher; @@ -28235,12 +6915,224 @@ var VideoWrapper = function () { } obj.__del(property); } + }, { + key: 'load', + value: function load() { + var _this4 = this; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return new _Promise(function (resolve, reject) { + var _dispatcher$bus2; + + _this4.__dispatcher.bus.once(_this4.__id, '_load', resolve); + (_dispatcher$bus2 = _this4.__dispatcher.bus).emit.apply(_dispatcher$bus2, ['load'].concat(args)); + }); + } + }, { + key: '$silentLoad', + value: function $silentLoad() { + var _this5 = this; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + return this.__dispatcher.bus.emit('silentLoad').then(function () { + var _dispatcher; + + return (_dispatcher = _this5.__dispatcher).silentLoad.apply(_dispatcher, args); + }).then(function (result) { + _this5.__dispatcher.bus.trigger('silentLoad', result); + }); + } + + /** + * call fullscreen api on some specific element + * @param {boolean} flag true means fullscreen and means exit fullscreen + * @param {string} element the element you want to fullscreen, default it's container, you can choose from video | container | wrapper + */ + + }, { + key: '$fullScreen', + value: function $fullScreen() { + var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; + + if (!this.__dispatcher.bus.emitSync('fullScreen', flag, element)) return false; + var result = this.__dispatcher.dom.fullScreen(flag, element); + this.__dispatcher.bus.triggerSync('fullScreen', flag, element); + return result; + } + + /** + * emit an event + * @param {string} key event's name + * @param {...args} args + */ + + }, { + key: '$emit', + value: function $emit(key) { + var _dispatcher$bus3; + + if (!isString(key)) throw new TypeError('emit key parameter must be String'); + if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { + Log.warn('plugin', 'You are try to emit ' + key + ' event. As emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use emitSync'); + } + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + (_dispatcher$bus3 = this.__dispatcher.bus).emit.apply(_dispatcher$bus3, [key].concat(_toConsumableArray(args))); + } + + /** + * emit a sync event + * @param {string} key event's name + * @param {...args} args + */ + + }, { + key: '$emitSync', + value: function $emitSync(key) { + var _dispatcher$bus4; + + if (!isString(key)) throw new TypeError('emitSync key parameter must be String'); + + for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + + return (_dispatcher$bus4 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus4, [key].concat(_toConsumableArray(args))); + } + + /** + * bind event handler through this function + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$on', + value: function $on(key, fn) { + this.__dispatcher.bus.on(this.__id, key, fn); + // set on __events as mark so that i can destroy it when i destroy + this.__addEvents(key, fn); + } + /** + * remove event handler through this function + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$off', + value: function $off(key, fn) { + this.__dispatcher.bus.off(this.__id, key, fn); + this.__removeEvents(key, fn); + } + /** + * bind one time event handler + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$once', + value: function $once(key, fn) { + var self = this; + var boundFn = function boundFn() { + bind(fn, this).apply(undefined, arguments); + self.__removeEvents(key, boundFn); + }; + self.__addEvents(key, boundFn); + this.__dispatcher.bus.once(this.__id, key, boundFn); + } + + /** + * set style + * @param {string} element optional, default to be video, you can choose from video | container | wrapper + * @param {string} attribute the atrribue name + * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; + */ + + }, { + key: '$css', + value: function $css(method) { + var _dispatcher$dom2; + + for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + args[_key6 - 1] = arguments[_key6]; + } + + return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom2, args); + } + + /** + * set attr + * @param {string} element optional, default to be video, you can choose from video | container | wrapper + * @param {string} attribute the atrribue nameß + * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; + */ + + }, { + key: '$attr', + value: function $attr(method) { + var _dispatcher$dom3; + + for (var _len7 = arguments.length, args = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + args[_key7 - 1] = arguments[_key7]; + } + + if (method === 'set' && /video/.test(args[0])) { + if (!this.__dispatcher.videoConfigReady) { + Log.warn('chimee', this.__id + ' is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); + return args[2]; + } + if (this.__dispatcher.videoConfig._realDomAttr.indexOf(args[1]) > -1) { + var key = args[1], + val = args[2]; + + this.__dispatcher.videoConfig[key] = val; + return val; + } + } + return (_dispatcher$dom3 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom3, args); + } + }, { + key: '__addEvents', + value: function __addEvents(key, fn) { + this.__events[key] = this.__events[key] || []; + this.__events[key].push(fn); + } + }, { + key: '__removeEvents', + value: function __removeEvents(key, fn) { + if (isEmpty(this.__events[key])) return; + var index = this.__events[key].indexOf(fn); + if (index < 0) return; + this.__events[key].splice(index, 1); + if (isEmpty(this.__events[key])) delete this.__events[key]; + } }, { key: '__destroy', value: function __destroy() { + var _this6 = this; + this.__unwatchHandlers.forEach(function (unwatcher) { return unwatcher(); }); + _Object$keys(this.__events).forEach(function (key) { + if (!isArray$1(_this6.__events[key])) return; + _this6.__events[key].forEach(function (fn) { + return _this6.$off(key, fn); + }); + }); + delete this.__events; } }, { key: 'currentTime', @@ -28250,48 +7142,51 @@ var VideoWrapper = function () { set: function set(second) { this.__dispatcher.bus.emitSync('seek', second); } - }]); - - return VideoWrapper; -}(); - -var _dec$2; -var _dec2$2; -var _dec3$2; -var _dec4$2; -var _dec5$2; -var _dec6$1; -var _class$2; -var _class2$1; - -function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { - var desc = {}; - Object['ke' + 'ys'](descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } + }, { + key: '$plugins', + get: function get() { + return this.__dispatcher.plugins; + } + }, { + key: '$pluginOrder', + get: function get() { + return this.__dispatcher.order; + } + }, { + key: '$wrapper', + get: function get() { + propertyAccessibilityWarn('wrapper'); + return this.__dispatcher.dom.wrapper; + } + }, { + key: '$container', + get: function get() { + propertyAccessibilityWarn('container'); + return this.__dispatcher.dom.container; + } + }, { + key: '$video', + get: function get() { + propertyAccessibilityWarn('video'); + return this.__dispatcher.dom.videoElement; + } + }, { + key: 'isFullScreen', + get: function get() { + return this.__dispatcher.dom.isFullScreen; + } + }, { + key: 'fullScreenElement', + get: function get() { + return this.__dispatcher.dom.fullScreenElement; + } + }]); - if (desc.initializer === void 0) { - Object['define' + 'Property'](target, property, desc); - desc = null; - } + return VideoWrapper; +}(), (_applyDecoratedDescriptor$2(_class2$1.prototype, '$silentLoad', [_dec2$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$silentLoad'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$fullScreen', [_dec3$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$fullScreen'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emit', [_dec4$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emit'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emitSync', [_dec5$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emitSync'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec6, _dec7, _dec8], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec9, _dec10, _dec11], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec12, _dec13], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec14, _dec15], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec16, _dec17], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$pluginOrder'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$wrapper', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$wrapper'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$container', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$container'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$video', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$video'), _class2$1.prototype)), _class2$1)) || _class$3); - return desc; -} +var _dec$2; +var _class$2; /** * <pre> @@ -28300,7 +7195,7 @@ function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, c * Developer can do most of things base on this plugin * </pre> */ -var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _dec3$2 = before(attrAndStyleCheck), _dec4$2 = before(eventBinderCheck), _dec5$2 = before(eventBinderCheck), _dec6$1 = before(eventBinderCheck), _dec$2(_class$2 = (_class2$1 = function (_VideoWrapper) { +var Plugin = (_dec$2 = autobindClass(), _dec$2(_class$2 = function (_VideoWrapper) { _inherits(Plugin, _VideoWrapper); /** @@ -28366,9 +7261,8 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de var _this = _possibleConstructorReturn(this, (Plugin.__proto__ || _Object$getPrototypeOf(Plugin)).call(this)); _this.destroyed = false; - _this.VERSION = '0.1.3'; + _this.VERSION = '0.2.0'; _this.__operable = true; - _this.__events = {}; _this.__level = 0; if (isEmpty(dispatcher)) { @@ -28531,69 +7425,7 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de }); return this.readySync || this.ready; } - /** - * set style - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: '$css', - value: function $css(method) { - var _dispatcher$dom; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return (_dispatcher$dom = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom, args); - } - /** - * set attr - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: '$attr', - value: function $attr(method) { - var _dispatcher$dom2; - - for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - if (method === 'set' && /video/.test(args[0])) { - if (!this.__dispatcher.videoConfigReady) { - Log.warn('plugin', 'Plugin ' + this.__id + ' is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); - return args[2]; - } - if (this.$videoConfig._realDomAttr.indexOf(args[1]) > -1) { - var key = args[1], - val = args[2]; - - this.$videoConfig[key] = val; - return val; - } - } - return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom2, args); - } - /** - * call fullscreen api on some specific element - * @param {boolean} flag true means fullscreen and means exit fullscreen - * @param {string} element the element you want to fullscreen, default it's container, you can choose from video | container | wrapper - */ - - }, { - key: '$fullScreen', - value: function $fullScreen() { - var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; - return this.__dispatcher.dom.fullScreen(flag, element); - } /** * set the plugin to be the top of all plugins */ @@ -28604,89 +7436,6 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de var topLevel = this.__dispatcher._getTopLevel(this.$inner); this.$level = topLevel + 1; } - /** - * bind event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$on', - value: function $on(key, fn) { - this.__dispatcher.bus.on(this.__id, key, fn); - // set on __events as mark so that i can destroy it when i destroy - this.__addEvents(key, fn); - } - /** - * remove event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$off', - value: function $off(key, fn) { - this.__dispatcher.bus.off(this.__id, key, fn); - this.__removeEvents(key, fn); - } - /** - * bind one time event handler - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$once', - value: function $once(key, fn) { - var self = this; - var boundFn = function boundFn() { - bind(fn, this).apply(undefined, arguments); - self.__removeEvents(key, boundFn); - }; - self.__addEvents(key, boundFn); - this.__dispatcher.bus.once(this.__id, key, boundFn); - } - /** - * emit an event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: '$emit', - value: function $emit(key) { - var _dispatcher$bus; - - if (!isString(key)) throw new TypeError('$emit key parameter must be String'); - if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { - Log.warn('plugin', 'You are using $emit to emit ' + key + ' event. As $emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use $emitSync'); - } - - for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - (_dispatcher$bus = this.__dispatcher.bus).emit.apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - } - /** - * emit a sync event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: '$emitSync', - value: function $emitSync(key) { - var _dispatcher$bus2; - - if (!isString(key)) throw new TypeError('$emitSync key parameter must be String'); - - for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - return (_dispatcher$bus2 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus2, [key].concat(_toConsumableArray(args))); - } }, { key: '$throwError', value: function $throwError(error) { @@ -28700,47 +7449,13 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de }, { key: '$destroy', value: function $destroy() { - var _this3 = this; - isFunction(this.destroy) && this.destroy(); _get(Plugin.prototype.__proto__ || _Object$getPrototypeOf(Plugin.prototype), '__destroy', this).call(this); - _Object$keys(this.__events).forEach(function (key) { - if (!isArray$1(_this3.__events[key])) return; - _this3.__events[key].forEach(function (fn) { - return _this3.$off(key, fn); - }); - }); - delete this.__events; this.__dispatcher.dom.removePlugin(this.__id); delete this.__dispatcher; delete this.$dom; this.destroyed = true; } - }, { - key: '__addEvents', - value: function __addEvents(key, fn) { - this.__events[key] = this.__events[key] || []; - this.__events[key].push(fn); - } - }, { - key: '__removeEvents', - value: function __removeEvents(key, fn) { - if (isEmpty(this.__events[key])) return; - var index = this.__events[key].indexOf(fn); - if (index < 0) return; - this.__events[key].splice(index, 1); - if (isEmpty(this.__events[key])) delete this.__events[key]; - } - }, { - key: '$plugins', - get: function get() { - return this.__dispatcher.plugins; - } - }, { - key: '$pluginOrder', - get: function get() { - return this.__dispatcher.order; - } /** * to tell us if the plugin can be operable, can be dynamic change * @type {boolean} @@ -28753,7 +7468,7 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de this.$dom.style.pointerEvents = val ? 'auto' : 'none'; this.__operable = val; }, - get: function get() { + get: function get$$1() { return this.__operable; } /** @@ -28768,23 +7483,23 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de this.__level = val; this.__dispatcher._sortZIndex(); }, - get: function get() { + get: function get$$1() { return this.__level; } }]); return Plugin; -}(VideoWrapper), (_applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec2$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec4$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec5$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec6$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$pluginOrder'), _class2$1.prototype)), _class2$1)) || _class$2); +}(VideoWrapper)) || _class$2); -var _dec$3; +var _dec$5; var _dec2$3; -var _dec3$3; -var _dec4$3; -var _dec5$3; -var _dec6$2; -var _class$3; +var _dec3$2; +var _dec4$2; +var _dec5$2; +var _dec6$1; +var _class$5; -function _applyDecoratedDescriptor$3(target, property, decorators, descriptor, context) { +function _applyDecoratedDescriptor$4(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; @@ -28834,7 +7549,7 @@ function attrOperationCheck(target, attr, val) { * It take charge of dom management of Dispatcher. * </pre> */ -var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before(attrOperationCheck, targetCheck), _dec3$3 = before(attrOperationCheck, targetCheck), _dec4$3 = before(attrOperationCheck, targetCheck), _dec5$3 = before(attrOperationCheck, targetCheck), _dec6$2 = before(targetCheck), (_class$3 = function () { +var Dom = (_dec$5 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before(attrOperationCheck, targetCheck), _dec3$2 = before(attrOperationCheck, targetCheck), _dec4$2 = before(attrOperationCheck, targetCheck), _dec5$2 = before(attrOperationCheck, targetCheck), _dec6$1 = before(targetCheck), (_class$5 = function () { /** * to mark is the mouse in the video area * @type {boolean} @@ -28871,6 +7586,8 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before this.__domEventHandlerList = {}; this.__mouseInVideo = false; this.__videoExtendedNodes = []; + this.isFullScreen = false; + this.fullScreenElement = undefined; this.__dispatcher = dispatcher; if (!isElement(wrapper) && !isString(wrapper)) throw new TypeError('Illegal wrapper'); @@ -28895,77 +7612,14 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before * referrence of video's dom element * @type {Element} */ - this.videoElement = videoElement; - this.__videoExtendedNodes.push(videoElement); - this.setAttr('videoElement', 'tabindex', -1); - this._autoFocusToVideo(this.videoElement); - // create container - if (this.videoElement.parentElement && isElement(this.videoElement.parentElement) && this.videoElement.parentElement !== this.wrapper) { - this.container = this.videoElement.parentElement; - } else { - this.container = document.createElement('container'); - $(this.container).append(this.videoElement); - } - // check container.position - if (this.container.parentElement !== this.wrapper) { - $wrapper.append(this.container); - } - videoEvents.forEach(function (key) { - var fn = function fn() { - var _dispatcher$bus; - - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - return (_dispatcher$bus = _this.__dispatcher.bus).trigger.apply(_dispatcher$bus, [key].concat(args)); - }; - _this.videoEventHandlerList.push(fn); - addEvent(_this.videoElement, key, fn); - }); + this.installVideo(videoElement); domEvents.forEach(function (key) { var fn = _this._getEventHandler(key, { penetrate: true }); _this.videoDomEventHandlerList.push(fn); addEvent(_this.videoElement, key, fn); - var cfn = function cfn() { - var _dispatcher$bus2; - - for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - - return (_dispatcher$bus2 = _this.__dispatcher.bus).triggerSync.apply(_dispatcher$bus2, ['c_' + key].concat(args)); - }; - _this.containerDomEventHandlerList.push(cfn); - addEvent(_this.container, key, cfn); - var wfn = function wfn() { - var _dispatcher$bus3; - - for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - - return (_dispatcher$bus3 = _this.__dispatcher.bus).triggerSync.apply(_dispatcher$bus3, ['w_' + key].concat(args)); - }; - _this.wrapperDomEventHandlerList.push(wfn); - addEvent(_this.wrapper, key, wfn); }); + this._bindFullScreen(); } - /** - * <pre> - * each plugin has its own dom node, this function will create one or them. - * we support multiple kind of el - * 1. Element, we will append this dom node on wrapper straight - * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper - * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper - * 4. nothing, we will create a div and bind it on the wrapper - * </pre> - * @param {string} id plugin's id - * @param {string|Element} el(optional) the el can be custom dom element or html string to insert - * @param {boolean} inner if it's true, we will put it into conatiner, else we would put it into outer - * @return {Node} - */ - /** * Object to store different plugin's dom event handlers * @type {Object} @@ -28995,10 +7649,91 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before */ - _createClass(Dom, [{ + _createClass(Dom, [{ + key: 'installVideo', + value: function installVideo(videoElement) { + var _this2 = this; + + this.__videoExtendedNodes.push(videoElement); + setAttr(videoElement, 'tabindex', -1); + this._autoFocusToVideo(videoElement); + if (!isElement(this.container)) { + // create container + if (videoElement.parentElement && isElement(videoElement.parentElement) && videoElement.parentElement !== this.wrapper) { + this.container = videoElement.parentElement; + } else { + this.container = document.createElement('container'); + $(this.container).append(videoElement); + } + } else { + var container = this.container; + if (container.childNodes.length === 0) { + container.appendChild(videoElement); + } else { + container.insertBefore(videoElement, container.childNodes[0]); + } + } + // check container.position + if (this.container.parentElement !== this.wrapper) { + $(this.wrapper).append(this.container); + } + videoEvents.forEach(function (key) { + var fn = function fn() { + var _dispatcher$bus; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return (_dispatcher$bus = _this2.__dispatcher.bus).trigger.apply(_dispatcher$bus, [key].concat(args)); + }; + _this2.videoEventHandlerList.push(fn); + addEvent(videoElement, key, fn); + }); + domEvents.forEach(function (key) { + var fn = _this2._getEventHandler(key, { penetrate: true }); + _this2.videoDomEventHandlerList.push(fn); + addEvent(videoElement, key, fn); + }); + this.videoElement = videoElement; + return videoElement; + } + }, { + key: 'removeVideo', + value: function removeVideo() { + var _this3 = this; + + var videoElement = this.videoElement; + this._autoFocusToVideo(this.videoElement, false); + videoEvents.forEach(function (key, index) { + removeEvent(_this3.videoElement, key, _this3.videoEventHandlerList[index]); + }); + domEvents.forEach(function (key, index) { + removeEvent(_this3.videoElement, key, _this3.videoDomEventHandlerList[index]); + }); + $(videoElement).remove(); + delete this.videoElement; + return videoElement; + } + /** + * <pre> + * each plugin has its own dom node, this function will create one or them. + * we support multiple kind of el + * 1. Element, we will append this dom node on wrapper straight + * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper + * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper + * 4. nothing, we will create a div and bind it on the wrapper + * </pre> + * @param {string} id plugin's id + * @param {string|Element} el(optional) the el can be custom dom element or html string to insert + * @param {boolean} inner if it's true, we will put it into conatiner, else we would put it into outer + * @return {Node} + */ + + }, { key: 'insertPlugin', value: function insertPlugin(id, el) { - var _this2 = this; + var _this4 = this; var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -29040,9 +7775,9 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before if (penetrate) { this.__domEventHandlerList[id] = this.__domEventHandlerList[id] || []; domEvents.forEach(function (key) { - var fn = _this2._getEventHandler(key, { penetrate: penetrate }); + var fn = _this4._getEventHandler(key, { penetrate: penetrate }); addEvent(node, key, fn); - _this2.__domEventHandlerList[id].push(fn); + _this4.__domEventHandlerList[id].push(fn); }); this.__videoExtendedNodes.push(node); } @@ -29061,7 +7796,7 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: 'removePlugin', value: function removePlugin(id) { - var _this3 = this; + var _this5 = this; if (!isString(id)) return; var dom = this.plugins[id]; @@ -29071,7 +7806,7 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before } if (!isEmpty(this.__domEventHandlerList[id])) { domEvents.forEach(function (key, index) { - removeEvent(_this3.plugins[id], key, _this3.__domEventHandlerList[id][index]); + removeEvent(_this5.plugins[id], key, _this5.__domEventHandlerList[id][index]); }); delete this.__domEventHandlerList[id]; } @@ -29085,11 +7820,11 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: 'setPluginsZIndex', value: function setPluginsZIndex(plugins) { - var _this4 = this; + var _this6 = this; // $FlowFixMe: there are videoElment and container here plugins.forEach(function (key, index) { - return setStyle(key.match(/^(videoElement|container)$/) ? _this4[key] : _this4.plugins[key], 'z-index', ++index); + return setStyle(key.match(/^(videoElement|container)$/) ? _this6[key] : _this6.plugins[key], 'z-index', ++index); }); } /** @@ -29157,8 +7892,8 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before var request = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; - for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { - args[_key5 - 2] = arguments[_key5]; + for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { + args[_key3 - 2] = arguments[_key3]; } return request ? this.requestFullScreen.apply(this, [target].concat(_toConsumableArray(args))) : this.exitFullScreen.apply(this, _toConsumableArray(args)); @@ -29175,20 +7910,16 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: 'destroy', value: function destroy() { - var _this5 = this; + var _this7 = this; - this._autoFocusToVideo(this.videoElement, false); - videoEvents.forEach(function (key, index) { - removeEvent(_this5.videoElement, key, _this5.videoEventHandlerList[index]); - }); + this.removeVideo(); domEvents.forEach(function (key, index) { - removeEvent(_this5.videoElement, key, _this5.videoDomEventHandlerList[index]); - removeEvent(_this5.container, key, _this5.containerDomEventHandlerList[index]); - removeEvent(_this5.wrapper, key, _this5.wrapperDomEventHandlerList[index]); + removeEvent(_this7.container, key, _this7.containerDomEventHandlerList[index]); + removeEvent(_this7.wrapper, key, _this7.wrapperDomEventHandlerList[index]); }); + this._bindFullScreen(true); this.wrapper.innerHTML = this.originHTML; delete this.wrapper; - delete this.videoElement; delete this.plugins; } }, { @@ -29207,6 +7938,32 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before isFunction(this.videoElement.focus) && this.videoElement.focus(); window.scrollTo(x, y); } + }, { + key: '_fullScreenMonitor', + value: function _fullScreenMonitor() { + var element = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullScreenElement', 'msFullscreenElement'].reduce(function (element, key) { + // $FlowFixMe: support computed element on document + return element || document[key]; + }, null); + if (!element || !isPosterityNode(this.wrapper, element) && element !== this.wrapper) { + this.isFullScreen = false; + this.fullScreenElement = undefined; + return; + } + this.isFullScreen = true; + this.fullScreenElement = this.wrapper === element ? 'wrapper' : this.container === element ? 'container' : this.videoElement === element ? 'video' : element; + } + }, { + key: '_bindFullScreen', + value: function _bindFullScreen(remove) { + var _this8 = this; + + if (!remove) this._fullScreenMonitor(); + ['webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange', 'fullscreenchange'].forEach(function (key) { + // $FlowFixMe: support computed element on document + document[(remove ? 'remove' : 'add') + 'EventListener'](key, _this8._fullScreenMonitor); + }); + } /** * get the event handler for dom to bind */ @@ -29214,361 +7971,63 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: '_getEventHandler', value: function _getEventHandler(key, _ref) { - var _this6 = this; + var _this9 = this; var penetrate = _ref.penetrate; if (!penetrate || ['mouseenter', 'mouseleave'].indexOf(key) < 0) { - return function () { - var _dispatcher$bus4; - - for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - - (_dispatcher$bus4 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, [key].concat(args)); - }; - } - var insideVideo = function insideVideo(node) { - return _this6.__videoExtendedNodes.indexOf(node) > -1 || _this6.__videoExtendedNodes.reduce(function (flag, video) { - if (flag) return flag; - return isPosterityNode(video, node); - }, false); - }; - return function () { - for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; - } - - var _args$ = args[0], - toElement = _args$.toElement, - currentTarget = _args$.currentTarget, - relatedTarget = _args$.relatedTarget, - type = _args$.type; - - var to = toElement || relatedTarget; - if (_this6.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { - var _dispatcher$bus5; - - _this6.__mouseInVideo = false; - return (_dispatcher$bus5 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus5, ['mouseleave'].concat(args)); - } - if (!_this6.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { - var _dispatcher$bus6; - - _this6.__mouseInVideo = true; - return (_dispatcher$bus6 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus6, ['mouseenter'].concat(args)); - } - }; - } - }]); - - return Dom; -}(), (_applyDecoratedDescriptor$3(_class$3.prototype, 'setAttr', [_dec$3, _dec2$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'setAttr'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'getAttr', [_dec3$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'getAttr'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'setStyle', [_dec4$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'setStyle'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'getStyle', [_dec5$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'getStyle'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'requestFullScreen', [_dec6$2], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'requestFullScreen'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, '_focusToVideo', [autobind], _Object$getOwnPropertyDescriptor(_class$3.prototype, '_focusToVideo'), _class$3.prototype)), _class$3)); - -var _dec$4; -var _dec2$4; -var _dec3$4; -var _class$4; -var _descriptor$1; -var _descriptor2$1; -var _descriptor3$1; -var _descriptor4; -var _descriptor5; -var _descriptor6; -var _descriptor7; - -function _initDefineProp$1(target, property, descriptor, context) { - if (!descriptor) return; - - _Object$defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor$4(target, property, decorators, descriptor, context) { - var desc = {}; - Object['ke' + 'ys'](descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object['define' + 'Property'](target, property, desc); - desc = null; - } - - return desc; -} - -function numberOrVoid(value) { - return isNumber(value) ? value : undefined; -} -function stringOrVoid(value) { - return isString(value) ? value : undefined; -} - -function accessorVideoProperty(property) { - return accessor({ - get: function get(value) { - return this.dispatcher.videoConfigReady && this.inited ? this.videoElement[property] : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - this.videoElement[property] = value; - return value; - } - }); -} - -function accessorVideoAttribute(attribute) { - var _ref = isObject$1(attribute) ? attribute : { - set: attribute, - get: attribute, - isBoolean: false - }, - _set = _ref.set, - _get = _ref.get, - isBoolean$$1 = _ref.isBoolean; - - return accessor({ - get: function get(value) { - return this.dispatcher.videoConfigReady && this.inited ? this.videoElement[_get] : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - var val = isBoolean$$1 ? value ? '' : undefined : value; - this.dispatcher.dom.setAttr('video', _set, val); - return value; - } - }); -} - -function accessorCustomAttribute(attribute, isBoolean$$1) { - return accessor({ - get: function get(value) { - var attrValue = this.dispatcher.dom.getAttr('video', attribute); - return this.dispatcher.videoConfigReady && this.inited ? isBoolean$$1 ? !!attrValue : attrValue : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - var val = isBoolean$$1 ? value || undefined : value; - this.dispatcher.dom.setAttr('video', attribute, val); - return value; - } - }); -} - -var accessorMap = { - src: [string$1(), accessor({ - set: function set(val) { - if (this.needToLoadSrc) { - // unlock it at first, to avoid deadlock - this.needToLoadSrc = false; - this.dispatcher.bus.emit('load', val); - } - return val; - } - }, { preSet: false }), accessor({ - set: function set(val) { - // must check val !== this.src here - // as we will set config.src in the video - // the may cause dead lock - if (this.dispatcher.readySync && this.autoload && val !== this.src) this.needToLoadSrc = true; - return val; - } - })], - autoload: boolean$1(), - autoplay: [boolean$1(), accessorVideoProperty('autoplay')], - controls: [boolean$1(), accessorVideoProperty('controls')], - width: [accessor({ set: numberOrVoid }), accessorVideoAttribute('width')], - height: [accessor({ set: numberOrVoid }), accessorVideoAttribute('height')], - crossOrigin: [accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' })], - loop: [boolean$1(), accessorVideoProperty('loop')], - defaultMuted: [boolean$1(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true })], - muted: [boolean$1(), accessorVideoProperty('muted')], - preload: [accessor({ set: stringOrVoid }), accessorVideoAttribute('preload')], - poster: [accessor({ set: stringOrVoid }), accessorVideoAttribute('poster')], - playsInline: [accessor({ - get: function get(value) { - var playsInline = this.videoElement.playsInline; - return this.dispatcher.videoConfigReady && this.inited ? playsInline === undefined ? value : playsInline : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - this.videoElement.playsInline = value; - var val = value ? '' : undefined; - this.dispatcher.dom.setAttr('video', 'playsinline', val); - this.dispatcher.dom.setAttr('video', 'webkit-playsinline', val); - this.dispatcher.dom.setAttr('video', 'x5-video-player-type', value ? 'h5' : undefined); - return value; - } - }), boolean$1()], - x5VideoPlayerFullScreen: [accessor({ - set: function set(value) { - return !!value; - }, - get: function get(value) { - return !!value; - } - }), accessorCustomAttribute('x5-video-player-fullscreen', true)], - x5VideoOrientation: [accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], - xWebkitAirplay: [accessor({ - set: function set(value) { - return !!value; - }, - get: function get(value) { - return !!value; - } - }), accessorCustomAttribute('x-webkit-airplay', true)], - playbackRate: [number$1(1), accessorVideoProperty('playbackRate')], - defaultPlaybackRate: [accessorVideoProperty('defaultPlaybackRate'), number$1(1)], - disableRemotePlayback: [boolean$1(), accessorVideoProperty('disableRemotePlayback')], - volume: [number$1(1), accessorVideoProperty('volume')] -}; - -var VideoConfig = (_dec$4 = string(), _dec2$4 = string(function (str) { - return str.toLocaleLowerCase(); -}), _dec3$4 = array(), (_class$4 = function () { - _createClass(VideoConfig, [{ - key: 'lockKernelProperty', - value: function lockKernelProperty() { - applyDecorators(this, { - type: lock, - box: lock, - runtimeOrder: lock - }, { self: true }); - } - }]); - - function VideoConfig(dispatcher, config) { - _classCallCheck(this, VideoConfig); - - _initDefineProp$1(this, 'needToLoadSrc', _descriptor$1, this); - - _initDefineProp$1(this, 'inited', _descriptor2$1, this); - - this.src = ''; - - _initDefineProp$1(this, 'type', _descriptor3$1, this); - - _initDefineProp$1(this, 'box', _descriptor4, this); - - _initDefineProp$1(this, 'runtimeOrder', _descriptor5, this); - - this.autoload = true; - this.autoplay = false; - this.controls = false; - this.width = undefined; - this.height = undefined; - this.crossOrigin = undefined; - this.loop = false; - this.defaultMuted = false; - this.muted = false; - this.preload = 'auto'; - this.poster = undefined; - this.playsInline = false; - this.x5VideoPlayerFullScreen = false; - this.x5VideoOrientation = undefined; - this.xWebkitAirplay = false; - this.playbackRate = 1; - this.defaultPlaybackRate = 1; - this.disableRemotePlayback = false; - this.volume = 1; + return function () { + var _dispatcher$bus2; - _initDefineProp$1(this, '_kernelProperty', _descriptor6, this); + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } - _initDefineProp$1(this, '_realDomAttr', _descriptor7, this); + (_dispatcher$bus2 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus2, [key].concat(args)); + }; + } + var insideVideo = function insideVideo(node) { + return _this9.__videoExtendedNodes.indexOf(node) > -1 || _this9.__videoExtendedNodes.reduce(function (flag, video) { + if (flag) return flag; + return isPosterityNode(video, node); + }, false); + }; + return function () { + for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } - applyDecorators(this, accessorMap, { self: true }); - Object.defineProperty(this, 'dispatcher', { - value: dispatcher, - enumerable: false, - writable: false, - configurable: false - }); - Object.defineProperty(this, 'videoElement', { - value: dispatcher.dom.videoElement, - enumerable: false, - writable: false, - configurable: false - }); - deepAssign(this, config); - } + var _args$ = args[0], + toElement = _args$.toElement, + currentTarget = _args$.currentTarget, + relatedTarget = _args$.relatedTarget, + type = _args$.type; - _createClass(VideoConfig, [{ - key: 'init', - value: function init() { - var _this = this; + var to = toElement || relatedTarget; + if (_this9.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { + var _dispatcher$bus3; - this._realDomAttr.forEach(function (key) { - // $FlowFixMe: we have check the computed here - _this[key] = _this[key]; - }); - this.inited = true; + _this9.__mouseInVideo = false; + return (_dispatcher$bus3 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus3, ['mouseleave'].concat(args)); + } + if (!_this9.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { + var _dispatcher$bus4; + + _this9.__mouseInVideo = true; + return (_dispatcher$bus4 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, ['mouseenter'].concat(args)); + } + }; } }]); - return VideoConfig; -}(), (_descriptor$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'needToLoadSrc', [nonenumerable], { - enumerable: true, - initializer: function initializer() { - return false; - } -}), _descriptor2$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'inited', [nonenumerable], { - enumerable: true, - initializer: function initializer() { - return false; - } -}), _descriptor3$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'type', [_dec$4, nonconfigurable], { - enumerable: true, - initializer: function initializer() { - return 'vod'; - } -}), _descriptor4 = _applyDecoratedDescriptor$4(_class$4.prototype, 'box', [_dec2$4, nonconfigurable], { - enumerable: true, - initializer: function initializer() { - return ''; - } -}), _descriptor5 = _applyDecoratedDescriptor$4(_class$4.prototype, 'runtimeOrder', [_dec3$4, nonconfigurable], { - enumerable: true, - initializer: function initializer() { - return ['html5', 'flash']; - } -}), _descriptor6 = _applyDecoratedDescriptor$4(_class$4.prototype, '_kernelProperty', [frozen], { - enumerable: true, - initializer: function initializer() { - return ['type', 'box', 'runtimeOrder']; - } -}), _descriptor7 = _applyDecoratedDescriptor$4(_class$4.prototype, '_realDomAttr', [frozen], { - enumerable: true, - initializer: function initializer() { - return ['src', 'controls', 'width', 'height', 'crossOrigin', 'loop', 'muted', 'preload', 'poster', 'autoplay', 'playsInline', 'x5VideoPlayerFullScreen', 'x5VideoOrientation', 'xWebkitAirplay', 'playbackRate', 'defaultPlaybackRate', 'autoload', 'disableRemotePlayback', 'defaultMuted', 'volume']; - } -})), _class$4)); + return Dom; +}(), (_applyDecoratedDescriptor$4(_class$5.prototype, 'setAttr', [_dec$5, _dec2$3], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'setAttr'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'getAttr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'getAttr'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'setStyle', [_dec4$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'setStyle'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'getStyle', [_dec5$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'getStyle'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'requestFullScreen', [_dec6$1], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'requestFullScreen'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, '_focusToVideo', [autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, '_focusToVideo'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, '_fullScreenMonitor', [autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, '_fullScreenMonitor'), _class$5.prototype)), _class$5)); var _dec$1; -var _dec2$1; -var _dec3$1; -var _dec4$1; -var _dec5$1; +var _dec2; +var _dec3; +var _dec4; +var _dec5; var _class$1; function _applyDecoratedDescriptor$1(target, property, decorators, descriptor, context) { @@ -29624,7 +8083,7 @@ function checkPluginConfig(config) { * It also offer a bridge to let user handle video kernel. * </pre> */ -var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPluginConfig), _dec3$1 = before(convertNameIntoId), _dec4$1 = before(convertNameIntoId), _dec5$1 = before(convertNameIntoId), (_class$1 = function () { +var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2 = before(checkPluginConfig), _dec3 = before(convertNameIntoId), _dec4 = before(convertNameIntoId), _dec5 = before(convertNameIntoId), (_class$1 = function () { /** * @param {UserConfig} config UserConfig for whole Chimee player * @param {Chimee} vm referrence of outer class @@ -29632,15 +8091,15 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug */ /** - * the synchronous ready flag - * @type {boolean} - * @member readySync + * the z-index map of the dom, it contain some important infomation + * @type {Object} + * @member zIndexMap */ /** - * all plugins instance set - * @type {Object} - * @member plugins + * plugin's order + * @type {Array<string>} + * @member order */ function Dispatcher(config, vm) { var _this = this; @@ -29654,6 +8113,7 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug inner: [], outer: [] }; + this.changeWatchable = true; if (!isObject$1(config)) throw new TypeError('UserConfig must be an Object'); /** @@ -29714,15 +8174,15 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug */ /** - * the z-index map of the dom, it contain some important infomation - * @type {Object} - * @member zIndexMap + * the synchronous ready flag + * @type {boolean} + * @member readySync */ /** - * plugin's order - * @type {Array<string>} - * @member order + * all plugins instance set + * @type {Object} + * @member plugins */ @@ -29788,6 +8248,186 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug value: function throwError(error) { this.vm.__throwError(error); } + }, { + key: 'silentLoad', + value: function silentLoad(src) { + var _this2 = this; + + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _option$duration = option.duration, + duration = _option$duration === undefined ? 3 : _option$duration, + _option$bias = option.bias, + bias = _option$bias === undefined ? 0 : _option$bias, + _option$repeatTimes = option.repeatTimes, + repeatTimes = _option$repeatTimes === undefined ? 0 : _option$repeatTimes, + _option$increment = option.increment, + increment = _option$increment === undefined ? 0 : _option$increment, + _option$isLive = option.isLive, + isLive = _option$isLive === undefined ? this.videoConfig.isLive : _option$isLive, + _option$box = option.box, + box = _option$box === undefined ? this.videoConfig.box : _option$box, + _option$preset = option.preset, + preset = _option$preset === undefined ? this.videoConfig.preset : _option$preset; + // form the base config for kernel + // it should be the same as the config now + + var config = { isLive: isLive, box: box, src: src, preset: preset }; + // build tasks accroding repeat times + var tasks = new Array(repeatTimes + 1).fill(1).map(function (value, index) { + return function () { + return new _Promise(function (resolve, reject) { + // if abort, give up and reject + if (option.abort) reject({ error: true, message: 'user abort the mission' }); + var video = document.createElement('video'); + var idealTime = _this2.kernel.currentTime + duration + increment * index; + video.muted = true; + var newVideoReady = false; + // bind time update on old video + // when we bump into the switch point and ready + // we switch + var oldVideoTimeupdate = function oldVideoTimeupdate(evt) { + var currentTime = _this2.kernel.currentTime; + if (bias <= 0 && currentTime >= idealTime || bias > 0 && (Math.abs(idealTime - currentTime) <= bias && newVideoReady || currentTime - idealTime > bias)) { + removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + if (!newVideoReady) { + removeEvent(video, 'canplay', videoCanplay); + removeEvent(video, 'loadedmetadata', videoLoadedmetadata); + removeEvent(video, 'error', videoError); + kernel.destroy(); + return resolve(); + } + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + var videoCanplay = function videoCanplay(evt) { + newVideoReady = true; + // you can set it immediately run by yourself + if (option.immediate) { + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + var videoLoadedmetadata = function videoLoadedmetadata(evt) { + kernel.seek(idealTime); + }; + var videoError = function videoError(evt) { + removeEvent(video, 'canplay', videoCanplay, true); + removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + var error = !isEmpty(video.error) ? new Error(video.error.message) : new Error('unknow video error'); + Log.error("chimee's silentload", error.message); + kernel.destroy(); + return index === repeatTimes ? reject(error) : resolve(error); + }; + addEvent(video, 'canplay', videoCanplay, true); + addEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + addEvent(video, 'error', videoError, true); + addEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + var kernel = new Kernel(video, config); + kernel.load(); + }); + }; + }); + return runRejectableQueue(tasks).then(function () { + var message = 'The silentLoad for ' + src + ' timed out. Please set a longer duration or check your network'; + Log.warn("chimee's silentLoad", message); + return _Promise.reject(new Error(message)); + }).catch(function (data) { + if (isError(data)) { + return _Promise.reject(data); + } + if (data.error) { + Log.warn("chimee's silentLoad", data.message); + return _Promise.reject(new Error(data.message)); + } + var video = data.video, + kernel = data.kernel; + + if (option.abort) { + kernel.destroy(); + return _Promise.reject(new Error('user abort the mission')); + } + var paused = _this2.dom.videoElement.paused; + _this2.switchKernel({ video: video, kernel: kernel, config: config }); + if (!paused) _this2.dom.videoElement.play(); + return _Promise.resolve(); + }); + } + }, { + key: 'load', + value: function load(src) { + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!isEmpty(option)) { + var videoConfig = this.videoConfig; + + var _option$isLive2 = option.isLive, + _isLive = _option$isLive2 === undefined ? videoConfig.isLive : _option$isLive2, + _option$box2 = option.box, + _box = _option$box2 === undefined ? videoConfig.box : _option$box2, + _option$preset2 = option.preset, + _preset = _option$preset2 === undefined ? videoConfig.preset : _option$preset2; + + var video = document.createElement('video'); + var config = { isLive: _isLive, box: _box, preset: _preset, src: src }; + var _kernel = new Kernel(video, config); + this.switchKernel({ video: video, kernel: _kernel, config: config }); + } + this.kernel.load(src); + } + }, { + key: 'switchKernel', + value: function switchKernel(_ref) { + var _this3 = this; + + var video = _ref.video, + kernel = _ref.kernel, + config = _ref.config; + + var oldKernel = this.kernel; + oldKernel.destroy(); + var originVideoConfig = deepClone(this.videoConfig); + this.dom.removeVideo(); + this.dom.installVideo(video); + // as we will reset the currentVideoConfig on the new video + // it will trigger the watch function as they maybe differnet + // so we need to stop them + this.videoConfig.changeWatchable = false; + this.videoConfig.autoload = false; + this.videoConfig.src = config.src; + this.videoConfig._realDomAttr.forEach(function (key) { + // $FlowFixMe: support computed key here + if (key !== 'src') _this3.videoConfig[key] = originVideoConfig[key]; + }); + this.videoConfig.changeWatchable = true; + // bind the new config in new kernel to the videoConfig + applyDecorators(config, { + src: accessor({ + get: function get(value) { + return _this3.videoConfig.src; + }, + set: function set(value) { + _this3.videoConfig.src = value; + return value; + } + }) + }, { self: true }); + // the kernel's inner config would not be change according what we do + // so we have to load that + // applyDecorators(kernel.__proto__, { + // load: before(src => { + // return [src || this.videoConfig.src]; + // }) + // }, {self: true}); + this.kernel = kernel; + } /** * destroy function called when dispatcher destroyed */ @@ -29817,7 +8457,7 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug }, { key: '_initUserPlugin', value: function _initUserPlugin() { - var _this2 = this; + var _this4 = this; var configs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; @@ -29826,7 +8466,7 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug configs = []; } return configs.map(function (config) { - return _this2.use(config); + return _this4.use(config); }); } /** @@ -29836,10 +8476,10 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug }, { key: '_sortZIndex', value: function _sortZIndex() { - var _this3 = this; + var _this5 = this; var _order$reduce = this.order.reduce(function (levelSet, key) { - var plugin = _this3.plugins[key]; + var plugin = _this5.plugins[key]; if (isEmpty(plugin)) return levelSet; var set = levelSet[plugin.$inner ? 'inner' : 'outer']; var level = plugin.$level; @@ -29920,9 +8560,9 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug }]); return Dispatcher; -}(), (_applyDecoratedDescriptor$1(_class$1.prototype, 'unuse', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'unuse'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1, 'install', [_dec2$1], _Object$getOwnPropertyDescriptor(_class$1, 'install'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'hasInstalled', [_dec3$1], _Object$getOwnPropertyDescriptor(_class$1, 'hasInstalled'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'uninstall', [_dec4$1], _Object$getOwnPropertyDescriptor(_class$1, 'uninstall'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'getPluginConfig', [_dec5$1], _Object$getOwnPropertyDescriptor(_class$1, 'getPluginConfig'), _class$1)), _class$1)); +}(), (_applyDecoratedDescriptor$1(_class$1.prototype, 'unuse', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'unuse'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1, 'install', [_dec2], _Object$getOwnPropertyDescriptor(_class$1, 'install'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'hasInstalled', [_dec3], _Object$getOwnPropertyDescriptor(_class$1, 'hasInstalled'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'uninstall', [_dec4], _Object$getOwnPropertyDescriptor(_class$1, 'uninstall'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'getPluginConfig', [_dec5], _Object$getOwnPropertyDescriptor(_class$1, 'getPluginConfig'), _class$1)), _class$1)); -var _class$5; +var _class$6; var _descriptor$2; function _initDefineProp$2(target, property, descriptor, context) { @@ -29965,7 +8605,7 @@ function _applyDecoratedDescriptor$5(target, property, decorators, descriptor, c return desc; } -var GlobalConfig = (_class$5 = function () { +var GlobalConfig = (_class$6 = function () { _createClass(GlobalConfig, [{ key: 'silent', get: function get() { @@ -30016,21 +8656,14 @@ var GlobalConfig = (_class$5 = function () { } return GlobalConfig; -}(), (_descriptor$2 = _applyDecoratedDescriptor$5(_class$5.prototype, '_silent', [nonenumerable], { +}(), (_descriptor$2 = _applyDecoratedDescriptor$5(_class$6.prototype, '_silent', [nonenumerable], { enumerable: true, initializer: function initializer() { return false; } -})), _class$5); +})), _class$6); var _dec; -var _dec2; -var _dec3; -var _dec4; -var _dec5; -var _dec6; -var _dec7; -var _dec8; var _class; var _class2; var _descriptor; @@ -30085,7 +8718,7 @@ function _applyDecoratedDescriptor(target, property, decorators, descriptor, con return desc; } -var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = before(eventBinderCheck), _dec4 = before(eventBinderCheck), _dec5 = alias('removeEventListener'), _dec6 = before(eventBinderCheck), _dec7 = before(attrAndStyleCheck), _dec8 = before(attrAndStyleCheck), _dec(_class = (_class2 = (_temp = _class3 = function (_VideoWrapper) { +var Chimee = (_dec = autobindClass(), _dec(_class = (_class2 = (_temp = _class3 = function (_VideoWrapper) { _inherits(Chimee, _VideoWrapper); function Chimee(config) { @@ -30136,133 +8769,6 @@ var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = value: function unuse(name) { this.__dispatcher.unuse(name); } - /** - * bind event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'on', - value: function on(key, fn) { - this.__dispatcher.bus.on('_vm', key, fn); - return this; - } - /** - * remove event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'off', - value: function off(key, fn) { - return this.__dispatcher.bus.off('_vm', key, fn); - } - /** - * bind one time event handler - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'once', - value: function once(key, fn) { - return this.__dispatcher.bus.once('_vm', key, fn); - } - /** - * emit an event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: 'emit', - value: function emit(key) { - var _dispatcher$bus; - - if (!isString(key)) throw new TypeError('emit key parameter must be String'); - if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { - Log.warn('plugin', 'You are using emit to emit ' + key + ' event. As emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use emitSync'); - } - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return (_dispatcher$bus = this.__dispatcher.bus).emit.apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - } - /** - * emit a sync event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: 'emitSync', - value: function emitSync(key) { - var _dispatcher$bus2; - - if (!isString(key)) throw new TypeError('emitSync key parameter must be String'); - - for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - return (_dispatcher$bus2 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus2, [key].concat(_toConsumableArray(args))); - } - /** - * set style - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: 'css', - value: function css(method) { - var _dispatcher$dom; - - for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - // $FlowFixMe: we support this here - return (_dispatcher$dom = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom, args); - } - /** - * set attr - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue nameß - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: 'attr', - value: function attr(method) { - var _dispatcher$dom2; - - for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - if (method === 'set' && /video/.test(args[0])) { - if (!this.__dispatcher.videoConfigReady) { - Log.warn('plugin', 'You are tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); - return args[2]; - } - if (this.__dispatcher.videoConfig._realDomAttr.indexOf(args[1]) > -1) { - var key = args[1], - val = args[2]; - // $FlowFixMe: we have check the computed key - - this.__dispatcher.videoConfig[key] = val; - return val; - } - } - // $FlowFixMe: we support this here - return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom2, args); - } }, { key: '__throwError', value: function __throwError(error) { @@ -30283,7 +8789,7 @@ var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'version', [frozen], { enumerable: true, initializer: function initializer() { - return '0.1.3'; + return '0.2.0'; } }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'config', [frozen], { enumerable: true, @@ -30334,7 +8840,7 @@ var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = initializer: function initializer() { return _init6; } -}), _class2), _applyDecoratedDescriptor(_class2.prototype, 'on', [_dec2, _dec3], _Object$getOwnPropertyDescriptor(_class2.prototype, 'on'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'off', [_dec4, _dec5], _Object$getOwnPropertyDescriptor(_class2.prototype, 'off'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'once', [_dec6], _Object$getOwnPropertyDescriptor(_class2.prototype, 'once'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'css', [_dec7], _Object$getOwnPropertyDescriptor(_class2.prototype, 'css'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'attr', [_dec8], _Object$getOwnPropertyDescriptor(_class2.prototype, 'attr'), _class2.prototype)), _class2)) || _class); +}), _class2)), _class2)) || _class); return Chimee; diff --git a/lib/index.js b/lib/index.js index 654e6708..b7c11a17 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,6 +1,6 @@ /** - * chimee v0.1.3 + * chimee v0.2.0 * (c) 2017 toxic-johann * Released under MIT */ @@ -11,7 +11,6 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var _Object$defineProperty = _interopDefault(require('babel-runtime/core-js/object/define-property')); var _Object$getOwnPropertyDescriptor = _interopDefault(require('babel-runtime/core-js/object/get-own-property-descriptor')); -var _toConsumableArray = _interopDefault(require('babel-runtime/helpers/toConsumableArray')); var _Object$getPrototypeOf = _interopDefault(require('babel-runtime/core-js/object/get-prototype-of')); var _classCallCheck = _interopDefault(require('babel-runtime/helpers/classCallCheck')); var _createClass = _interopDefault(require('babel-runtime/helpers/createClass')); @@ -22,16 +21,20 @@ var _Promise = _interopDefault(require('babel-runtime/core-js/promise')); var chimeeHelper = require('chimee-helper'); var Kernel = _interopDefault(require('chimee-kernel')); var _Map = _interopDefault(require('babel-runtime/core-js/map')); +var _toConsumableArray = _interopDefault(require('babel-runtime/helpers/toConsumableArray')); var _Object$keys = _interopDefault(require('babel-runtime/core-js/object/keys')); var toxicDecorators = require('toxic-decorators'); var _JSON$stringify = _interopDefault(require('babel-runtime/core-js/json/stringify')); var _defineProperty = _interopDefault(require('babel-runtime/helpers/defineProperty')); var _typeof = _interopDefault(require('babel-runtime/helpers/typeof')); +var _Number$isNaN = _interopDefault(require('babel-runtime/core-js/number/is-nan')); var videoEvents = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'interruptbegin', 'interruptend', 'loadeddata', 'loadedmetadata', 'loadstart', 'mozaudioavailable', 'pause', 'play', 'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; -var videoReadOnlyProperties = ['buffered', 'currentSrc', 'duration', 'ended', 'networkState', 'paused', 'readyState', 'seekable', 'sinkId', 'controlsList']; +var videoReadOnlyProperties = ['buffered', 'currentSrc', 'duration', 'error', 'ended', 'networkState', 'paused', 'readyState', 'seekable', 'sinkId', 'controlsList', 'tabIndex', 'dataset', 'offsetHeight', 'offsetLeft', 'offsetParent', 'offsetTop', 'offsetWidth']; var domEvents = ['beforeinput', 'blur', 'click', 'compositionend', 'compositionstart', 'compositionupdate', 'dblclick', 'focus', 'focusin', 'focusout', 'input', 'keydown', 'keypress', 'keyup', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll', 'select', 'wheel', 'fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange', 'contextmenu']; -var kernelMethods = ['play', 'pause', 'load', 'seek']; +var selfProcessorEvents = ['silentLoad', 'fullScreen']; +var kernelMethods = ['play', 'pause', 'seek']; +var dispatcherMethods = ['load']; var domMethods = ['focus', 'fullScreen', 'requestFullScreen', 'exitFullScreen']; var videoMethods = ['canPlayType', 'captureStream', 'setSinkId']; @@ -163,10 +166,12 @@ var Bus = function () { } var event = this.events[key]; if (chimeeHelper.isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return _Promise.resolve(); return this._eventProcessor.apply(this, [key, { sync: false }].concat(_toConsumableArray(args))); } var beforeQueue = this._getEventQueue(event.before, this.__dispatcher.order); return chimeeHelper.runRejectableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))).then(function () { + if (selfProcessorEvents.indexOf(key) > -1) return; return _this._eventProcessor.apply(_this, [key, { sync: false }].concat(_toConsumableArray(args))); }).catch(function (error) { if (chimeeHelper.isError(error)) _this.__dispatcher.throwError(error); @@ -195,10 +200,11 @@ var Bus = function () { } if (chimeeHelper.isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return true; return this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args))); } var beforeQueue = this._getEventQueue(event.before, this.__dispatcher.order); - return chimeeHelper.runStoppableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))) && this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args))); + return chimeeHelper.runStoppableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))) && (selfProcessorEvents.indexOf(key) > -1 || this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args)))); } /** * [Can only be called in dispatcher]trigger an event, which will run main -> after -> side effect period @@ -419,15 +425,22 @@ var Bus = function () { var isKernelMethod = kernelMethods.indexOf(key) > -1; var isDomMethod = domMethods.indexOf(key) > -1; + var isDispatcherMethod = dispatcherMethods.indexOf(key) > -1; for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { args[_key5 - 2] = arguments[_key5]; } - if (isKernelMethod || isDomMethod) { - var _dispatcher; + if (isKernelMethod || isDomMethod || isDispatcherMethod) { + if (isDispatcherMethod) { + var _dispatcher; + + (_dispatcher = this.__dispatcher)[key].apply(_dispatcher, _toConsumableArray(args)); + } else { + var _dispatcher2; - (_dispatcher = this.__dispatcher[isKernelMethod ? 'kernel' : 'dom'])[key].apply(_dispatcher, _toConsumableArray(args)); + (_dispatcher2 = this.__dispatcher[isKernelMethod ? 'kernel' : 'dom'])[key].apply(_dispatcher2, _toConsumableArray(args)); + } if (videoEvents.indexOf(key) > -1 || domEvents.indexOf(key) > -1) return true; } // $FlowFixMe: flow do not support computed sytax on classs, but it's ok here @@ -490,180 +503,29 @@ function attrAndStyleCheck() { return ['get', 'container'].concat(args); } -var VideoWrapper = function () { - function VideoWrapper() { - _classCallCheck(this, VideoWrapper); - - this.__unwatchHandlers = []; - } - - _createClass(VideoWrapper, [{ - key: '__wrapAsVideo', - value: function __wrapAsVideo(videoConfig) { - var _this = this; - - // bind video read only properties on instance, so that you can get info like buffered - videoReadOnlyProperties.forEach(function (key) { - _Object$defineProperty(_this, key, { - get: function get() { - return this.__dispatcher.dom.videoElement[key]; - }, - - set: undefined, - configurable: false, - enumerable: false - }); - }); - // bind videoMethods like canplaytype on instance - videoMethods.forEach(function (key) { - _Object$defineProperty(_this, key, { - get: function get() { - var video = this.__dispatcher.dom.videoElement; - return chimeeHelper.bind(video[key], video); - }, - - set: undefined, - configurable: false, - enumerable: false - }); - }); - // bind video config properties on instance, so that you can just set src by this - var props = videoConfig._realDomAttr.concat(videoConfig._kernelProperty).reduce(function (props, key) { - props[key] = [toxicDecorators.accessor({ - get: function get() { - return videoConfig[key]; - }, - set: function set(value) { - videoConfig[key] = value; - return value; - } - }), toxicDecorators.nonenumerable]; - return props; - }, {}); - toxicDecorators.applyDecorators(this, props, { self: true }); - kernelMethods.forEach(function (key) { - _Object$defineProperty(_this, key, { - value: function value() { - var _this2 = this; - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return new _Promise(function (resolve, reject) { - var _dispatcher$bus; - - _this2.__dispatcher.bus.once(_this2.__id, '_' + key, resolve); - (_dispatcher$bus = _this2.__dispatcher.bus)[/^(seek)$/.test(key) ? 'emitSync' : 'emit'].apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - }); - }, - - configurable: true, - enumerable: false, - writable: true - }); - }); - domMethods.forEach(function (key) { - _Object$defineProperty(_this, key, { - value: function value() { - var _dispatcher$dom; - - return (_dispatcher$dom = this.__dispatcher.dom)[key].apply(_dispatcher$dom, arguments); - }, - - configurable: true, - enumerable: false, - writable: true - }); - }); - } - }, { - key: '$watch', - value: function $watch(key, handler) { - var _this3 = this; - - var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - deep = _ref.deep, - _ref$diff = _ref.diff, - diff = _ref$diff === undefined ? true : _ref$diff, - other = _ref.other, - _ref$proxy = _ref.proxy, - proxy = _ref$proxy === undefined ? false : _ref$proxy; - - if (!chimeeHelper.isString(key) && !chimeeHelper.isArray(key)) throw new TypeError('$watch only accept string and Array<string> as key to find the target to spy on, but not ' + key + ', whose type is ' + (typeof key === 'undefined' ? 'undefined' : _typeof(key))); - var watching = true; - var watcher = function watcher() { - if (watching) chimeeHelper.bind(handler, this).apply(undefined, arguments); - }; - var unwatcher = function unwatcher() { - watching = false; - var index = _this3.__unwatchHandlers.indexOf(unwatcher); - if (index > -1) _this3.__unwatchHandlers.splice(index, 1); - }; - var keys = chimeeHelper.isString(key) ? key.split('.') : key; - var property = keys.pop(); - var videoConfig = this.__dispatcher.videoConfig; - var target = keys.length === 0 && !other && videoConfig._realDomAttr.indexOf(property) > -1 ? videoConfig : chimeeHelper.getDeepProperty(other || this, keys, { throwError: true }); - toxicDecorators.applyDecorators(target, _defineProperty({}, property, toxicDecorators.watch(watcher, { deep: deep, diff: diff, proxy: proxy })), { self: true }); - this.__unwatchHandlers.push(unwatcher); - return unwatcher; - } - }, { - key: '$set', - value: function $set(obj, property, value) { - if (!chimeeHelper.isObject(obj) && !chimeeHelper.isArray(obj)) throw new TypeError('$set only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); - // $FlowFixMe: we have custom this function - if (!chimeeHelper.isFunction(obj.__set)) { - chimeeHelper.Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $set.'); - // $FlowFixMe: we support computed string on array here - obj[property] = value; - return; - } - obj.__set(property, value); - } - }, { - key: '$del', - value: function $del(obj, property) { - if (!chimeeHelper.isObject(obj) && !chimeeHelper.isArray(obj)) throw new TypeError('$del only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); - // $FlowFixMe: we have custom this function - if (!chimeeHelper.isFunction(obj.__del)) { - chimeeHelper.Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $del.'); - // $FlowFixMe: we support computed string on array here - delete obj[property]; - return; - } - obj.__del(property); - } - }, { - key: '__destroy', - value: function __destroy() { - this.__unwatchHandlers.forEach(function (unwatcher) { - return unwatcher(); - }); - } - }, { - key: 'currentTime', - get: function get() { - return this.__dispatcher.kernel.currentTime; - }, - set: function set(second) { - this.__dispatcher.bus.emitSync('seek', second); - } - }]); +var _dec$4; +var _dec2$2; +var _class$4; +var _descriptor$1; +var _descriptor2$1; +var _descriptor3$1; +var _descriptor4; +var _descriptor5; +var _descriptor6; +var _descriptor7; - return VideoWrapper; -}(); +function _initDefineProp$1(target, property, descriptor, context) { + if (!descriptor) return; -var _dec$2; -var _dec2$2; -var _dec3$2; -var _dec4$2; -var _dec5$2; -var _dec6$1; -var _class$2; -var _class2$1; + _Object$defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} -function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { +function _applyDecoratedDescriptor$3(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; @@ -692,67 +554,807 @@ function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, c return desc; } -/** - * <pre> - * Plugin is the class for plugin developer. - * When we use a plugin, we will generate an instance of plugin. - * Developer can do most of things base on this plugin - * </pre> - */ -var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec2$2 = toxicDecorators.before(attrAndStyleCheck), _dec3$2 = toxicDecorators.before(attrAndStyleCheck), _dec4$2 = toxicDecorators.before(eventBinderCheck), _dec5$2 = toxicDecorators.before(eventBinderCheck), _dec6$1 = toxicDecorators.before(eventBinderCheck), _dec$2(_class$2 = (_class2$1 = function (_VideoWrapper) { - _inherits(Plugin, _VideoWrapper); +function stringOrVoid(value) { + return chimeeHelper.isString(value) ? value : undefined; +} - /** - * <pre> - * to create a plugin, we need three parameter - * 1. the config of a plugin - * 2. the dispatcher - * 3. this option for plugin to read - * this is the plugin base class, which you can get on Chimee - * You can just extends it and then install - * But in that way you must remember to pass the arguments to super() - * </pre> - * @param {string} PluginConfig.id camelize from plugin's name or class name. - * @param {string} PluginConfig.name plugin's name or class name - * @param {Number} PluginConfig.level the level of z-index - * @param {Boolean} PluginConfig.operable to tell if the plugin can be operable, if not, we will add pointer-events: none on it. - * @param {Function} PluginConfig.create the create function which we will called when plugin is used. sth like constructor in object style. - * @param {Function} PluginConfig.destroy function to be called when we destroy a plugin - * @param {Object} PluginConfig.events You can set some events handler in this object, we will bind it once you use the plugin. - * @param {Object} PluginConfig.data dataset we will bind on data in object style - * @param {Object<{get: Function, set: Function}} PluginConfig.computed dataset we will handle by getter and setter - * @param {Object<Function>} PluginConfig.methods some function we will bind on plugin - * @param {string|HTMLElment} PluginConfig.el can be string or HTMLElement, we will use this to create the dom for plugin - * @param {boolean} PluginConfig.penetrate boolean to let us do we need to forward the dom events for this plugin. - * @param {Dispatcher} dispatcher referrence of dispatcher - * @param {Object} option PluginOption that will pass to the plugin - * @return {Plugin} plugin instance - */ - function Plugin() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - id = _ref.id, - name = _ref.name, - _ref$level = _ref.level, - level = _ref$level === undefined ? 0 : _ref$level, - _ref$operable = _ref.operable, - operable = _ref$operable === undefined ? true : _ref$operable, - beforeCreate = _ref.beforeCreate, - create = _ref.create, - init = _ref.init, - inited = _ref.inited, - destroy = _ref.destroy, - _ref$events = _ref.events, - events = _ref$events === undefined ? {} : _ref$events, - _ref$data = _ref.data, - data = _ref$data === undefined ? {} : _ref$data, - _ref$computed = _ref.computed, - computed = _ref$computed === undefined ? {} : _ref$computed, - _ref$methods = _ref.methods, - methods = _ref$methods === undefined ? {} : _ref$methods, - el = _ref.el, - _ref$penetrate = _ref.penetrate, - penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, - _ref$inner = _ref.inner, +function accessorVideoProperty(property) { + return toxicDecorators.accessor({ + get: function get(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement[property] : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + this.dom.videoElement[property] = value; + return value; + } + }); +} + +function accessorVideoAttribute(attribute) { + var _ref = chimeeHelper.isObject(attribute) ? attribute : { + set: attribute, + get: attribute, + isBoolean: false + }, + _set = _ref.set, + _get$$1 = _ref.get, + isBoolean$$1 = _ref.isBoolean; + + return toxicDecorators.accessor({ + get: function get(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement[_get$$1] : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = isBoolean$$1 ? value ? '' : undefined : value; + this.dom.setAttr('video', _set, val); + return value; + } + }); +} + +function accessorCustomAttribute(attribute, isBoolean$$1) { + return toxicDecorators.accessor({ + get: function get(value) { + var attrValue = this.dom.getAttr('video', attribute); + return this.dispatcher.videoConfigReady && this.inited ? isBoolean$$1 ? !!attrValue : attrValue : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = isBoolean$$1 ? value || undefined : value; + this.dom.setAttr('video', attribute, val); + return value; + } + }); +} + +function accessorWidthAndHeight(property) { + return toxicDecorators.accessor({ + get: function get(value) { + if (!this.dispatcher.videoConfigReady) return value; + var attr = this.dom.getAttr('video', property); + var prop = this.dom.videoElement[property]; + if (chimeeHelper.isNumeric(attr) && chimeeHelper.isNumber(prop)) return prop; + return attr || undefined; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = void 0; + if (value === undefined || chimeeHelper.isNumber(value)) { + val = value; + } else if (chimeeHelper.isString(value) && !_Number$isNaN(parseFloat(value))) { + val = value; + } + this.dom.setAttr('video', property, val); + return val; + } + }); +} + +var accessorMap = { + src: [toxicDecorators.alwaysString(), toxicDecorators.accessor({ + set: function set(val) { + // must check val !== this.src here + // as we will set config.src in the video + // the may cause dead lock + if (this.dispatcher.readySync && this.autoload && val !== this.src) this.needToLoadSrc = true; + return val; + } + }), toxicDecorators.accessor({ + set: function set(val) { + if (this.needToLoadSrc) { + // unlock it at first, to avoid deadlock + this.needToLoadSrc = false; + this.dispatcher.bus.emit('load', val); + } + return val; + } + }, { preSet: false })], + autoload: toxicDecorators.alwaysBoolean(), + autoplay: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('autoplay')], + controls: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('controls')], + width: [accessorWidthAndHeight('width')], + height: [accessorWidthAndHeight('height')], + crossOrigin: [toxicDecorators.accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' })], + loop: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('loop')], + defaultMuted: [toxicDecorators.alwaysBoolean(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true })], + muted: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('muted')], + preload: [toxicDecorators.accessor({ set: stringOrVoid }), accessorVideoAttribute('preload')], + poster: [toxicDecorators.accessor({ set: stringOrVoid }), accessorVideoAttribute('poster')], + playsInline: [toxicDecorators.accessor({ + get: function get(value) { + var playsInline = this.dom.videoElement.playsInline; + return this.dispatcher.videoConfigReady && this.inited ? playsInline === undefined ? value : playsInline : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + this.dom.videoElement.playsInline = value; + var val = value ? '' : undefined; + this.dom.setAttr('video', 'playsinline', val); + this.dom.setAttr('video', 'webkit-playsinline', val); + this.dom.setAttr('video', 'x5-video-player-type', value ? 'h5' : undefined); + return value; + } + }), toxicDecorators.alwaysBoolean()], + x5VideoPlayerFullScreen: [toxicDecorators.accessor({ + set: function set(value) { + return !!value; + }, + get: function get(value) { + return !!value; + } + }), accessorCustomAttribute('x5-video-player-fullscreen', true)], + x5VideoOrientation: [toxicDecorators.accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], + xWebkitAirplay: [toxicDecorators.accessor({ + set: function set(value) { + return !!value; + }, + get: function get(value) { + return !!value; + } + }), accessorCustomAttribute('x-webkit-airplay', true)], + playbackRate: [toxicDecorators.alwaysNumber(1), accessorVideoProperty('playbackRate')], + defaultPlaybackRate: [accessorVideoProperty('defaultPlaybackRate'), toxicDecorators.alwaysNumber(1)], + disableRemotePlayback: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('disableRemotePlayback')], + volume: [toxicDecorators.alwaysNumber(1), accessorVideoProperty('volume')] +}; + +var VideoConfig = (_dec$4 = toxicDecorators.initBoolean(), _dec2$2 = toxicDecorators.initString(function (str) { + return str.toLocaleLowerCase(); +}), (_class$4 = function () { + _createClass(VideoConfig, [{ + key: 'lockKernelProperty', + value: function lockKernelProperty() { + toxicDecorators.applyDecorators(this, { + isLive: toxicDecorators.lock, + box: toxicDecorators.lock, + preset: toxicDecorators.lock + }, { self: true }); + } + }]); + + function VideoConfig(dispatcher, config) { + _classCallCheck(this, VideoConfig); + + _initDefineProp$1(this, 'needToLoadSrc', _descriptor$1, this); + + _initDefineProp$1(this, 'changeWatchable', _descriptor2$1, this); + + _initDefineProp$1(this, 'inited', _descriptor3$1, this); + + this.src = ''; + + _initDefineProp$1(this, 'isLive', _descriptor4, this); + + _initDefineProp$1(this, 'box', _descriptor5, this); + + this.preset = {}; + this.autoload = true; + this.autoplay = false; + this.controls = false; + this.width = undefined; + this.height = undefined; + this.crossOrigin = undefined; + this.loop = false; + this.defaultMuted = false; + this.muted = false; + this.preload = 'auto'; + this.poster = undefined; + this.playsInline = false; + this.x5VideoPlayerFullScreen = false; + this.x5VideoOrientation = undefined; + this.xWebkitAirplay = false; + this.playbackRate = 1; + this.defaultPlaybackRate = 1; + this.disableRemotePlayback = false; + this.volume = 1; + + _initDefineProp$1(this, '_kernelProperty', _descriptor6, this); + + _initDefineProp$1(this, '_realDomAttr', _descriptor7, this); + + toxicDecorators.applyDecorators(this, accessorMap, { self: true }); + Object.defineProperty(this, 'dispatcher', { + value: dispatcher, + enumerable: false, + writable: false, + configurable: false + }); + Object.defineProperty(this, 'dom', { + value: dispatcher.dom, + enumerable: false, + writable: false, + configurable: false + }); + chimeeHelper.deepAssign(this, config); + } + + _createClass(VideoConfig, [{ + key: 'init', + value: function init() { + var _this = this; + + this._realDomAttr.forEach(function (key) { + // $FlowFixMe: we have check the computed here + _this[key] = _this[key]; + }); + this.inited = true; + } + }]); + + return VideoConfig; +}(), (_descriptor$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'needToLoadSrc', [toxicDecorators.nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor2$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'changeWatchable', [toxicDecorators.nonenumerable], { + enumerable: true, + initializer: function initializer() { + return true; + } +}), _descriptor3$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'inited', [toxicDecorators.nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor4 = _applyDecoratedDescriptor$3(_class$4.prototype, 'isLive', [_dec$4, toxicDecorators.configurable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor5 = _applyDecoratedDescriptor$3(_class$4.prototype, 'box', [_dec2$2, toxicDecorators.configurable], { + enumerable: true, + initializer: function initializer() { + return ''; + } +}), _descriptor6 = _applyDecoratedDescriptor$3(_class$4.prototype, '_kernelProperty', [toxicDecorators.frozen], { + enumerable: true, + initializer: function initializer() { + return ['isLive', 'box', 'preset']; + } +}), _descriptor7 = _applyDecoratedDescriptor$3(_class$4.prototype, '_realDomAttr', [toxicDecorators.frozen], { + enumerable: true, + initializer: function initializer() { + return ['src', 'controls', 'width', 'height', 'crossOrigin', 'loop', 'muted', 'preload', 'poster', 'autoplay', 'playsInline', 'x5VideoPlayerFullScreen', 'x5VideoOrientation', 'xWebkitAirplay', 'playbackRate', 'defaultPlaybackRate', 'autoload', 'disableRemotePlayback', 'defaultMuted', 'volume']; + } +})), _class$4)); + +var _dec$3; +var _dec2$1; +var _dec3$1; +var _dec4$1; +var _dec5$1; +var _dec6; +var _dec7; +var _dec8; +var _dec9; +var _dec10; +var _dec11; +var _dec12; +var _dec13; +var _dec14; +var _dec15; +var _dec16; +var _dec17; +var _class$3; +var _class2$1; + +function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; +} + +function propertyAccessibilityWarn(property) { + chimeeHelper.Log.warn('chimee', 'You are trying to obtain ' + property + ', we will return you the DOM node. It\'s not a good idea to handle this by yourself. If you have some requirement, you can tell use by https://github.com/Chimeejs/chimee/issues'); +} +var VideoWrapper = (_dec$3 = toxicDecorators.autobindClass(), _dec2$1 = toxicDecorators.alias('silentLoad'), _dec3$1 = toxicDecorators.alias('fullScreen'), _dec4$1 = toxicDecorators.alias('emit'), _dec5$1 = toxicDecorators.alias('emitSync'), _dec6 = toxicDecorators.alias('on'), _dec7 = toxicDecorators.alias('addEventListener'), _dec8 = toxicDecorators.before(eventBinderCheck), _dec9 = toxicDecorators.alias('off'), _dec10 = toxicDecorators.alias('removeEventListener'), _dec11 = toxicDecorators.before(eventBinderCheck), _dec12 = toxicDecorators.alias('once'), _dec13 = toxicDecorators.before(eventBinderCheck), _dec14 = toxicDecorators.alias('css'), _dec15 = toxicDecorators.before(attrAndStyleCheck), _dec16 = toxicDecorators.alias('attr'), _dec17 = toxicDecorators.before(attrAndStyleCheck), _dec$3(_class$3 = (_class2$1 = function () { + function VideoWrapper() { + _classCallCheck(this, VideoWrapper); + + this.__events = {}; + this.__unwatchHandlers = []; + } + + _createClass(VideoWrapper, [{ + key: '__wrapAsVideo', + value: function __wrapAsVideo(videoConfig) { + var _this = this; + + // bind video read only properties on instance, so that you can get info like buffered + videoReadOnlyProperties.forEach(function (key) { + _Object$defineProperty(_this, key, { + get: function get() { + return this.__dispatcher.dom.videoElement[key]; + }, + + set: undefined, + configurable: false, + enumerable: false + }); + }); + // bind videoMethods like canplaytype on instance + videoMethods.forEach(function (key) { + _Object$defineProperty(_this, key, { + get: function get() { + var video = this.__dispatcher.dom.videoElement; + return chimeeHelper.bind(video[key], video); + }, + + set: undefined, + configurable: false, + enumerable: false + }); + }); + // bind video config properties on instance, so that you can just set src by this + var props = videoConfig._realDomAttr.concat(videoConfig._kernelProperty).reduce(function (props, key) { + props[key] = [toxicDecorators.accessor({ + get: function get() { + // $FlowFixMe: support computed key here + return videoConfig[key]; + }, + set: function set(value) { + // $FlowFixMe: support computed key here + videoConfig[key] = value; + return value; + } + }), toxicDecorators.nonenumerable]; + return props; + }, {}); + toxicDecorators.applyDecorators(this, props, { self: true }); + kernelMethods.forEach(function (key) { + _Object$defineProperty(_this, key, { + value: function value() { + var _this2 = this; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return new _Promise(function (resolve, reject) { + var _dispatcher$bus; + + _this2.__dispatcher.bus.once(_this2.__id, '_' + key, resolve); + (_dispatcher$bus = _this2.__dispatcher.bus)[/^(seek)$/.test(key) ? 'emitSync' : 'emit'].apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); + }); + }, + + configurable: true, + enumerable: false, + writable: true + }); + }); + domMethods.forEach(function (key) { + if (key === 'fullScreen') return; + _Object$defineProperty(_this, key, { + value: function value() { + var _dispatcher$dom; + + return (_dispatcher$dom = this.__dispatcher.dom)[key].apply(_dispatcher$dom, arguments); + }, + + configurable: true, + enumerable: false, + writable: true + }); + }); + } + }, { + key: '$watch', + value: function $watch(key, handler) { + var _this3 = this; + + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + deep = _ref.deep, + _ref$diff = _ref.diff, + diff = _ref$diff === undefined ? true : _ref$diff, + other = _ref.other, + _ref$proxy = _ref.proxy, + proxy = _ref$proxy === undefined ? false : _ref$proxy; + + if (!chimeeHelper.isString(key) && !chimeeHelper.isArray(key)) throw new TypeError('$watch only accept string and Array<string> as key to find the target to spy on, but not ' + key + ', whose type is ' + (typeof key === 'undefined' ? 'undefined' : _typeof(key))); + var watching = true; + var watcher = function watcher() { + if (watching && (!(this instanceof VideoConfig) || this.dispatcher.changeWatchable)) chimeeHelper.bind(handler, this).apply(undefined, arguments); + }; + var unwatcher = function unwatcher() { + watching = false; + var index = _this3.__unwatchHandlers.indexOf(unwatcher); + if (index > -1) _this3.__unwatchHandlers.splice(index, 1); + }; + var keys = chimeeHelper.isString(key) ? key.split('.') : key; + var property = keys.pop(); + var videoConfig = this.__dispatcher.videoConfig; + var target = keys.length === 0 && !other && videoConfig._realDomAttr.indexOf(property) > -1 ? videoConfig : ['isFullScreen', 'fullScreenElement'].indexOf(property) > -1 ? this.__dispatcher.dom : chimeeHelper.getDeepProperty(other || this, keys, { throwError: true }); + toxicDecorators.applyDecorators(target, _defineProperty({}, property, toxicDecorators.watch(watcher, { deep: deep, diff: diff, proxy: proxy })), { self: true }); + this.__unwatchHandlers.push(unwatcher); + return unwatcher; + } + }, { + key: '$set', + value: function $set(obj, property, value) { + if (!chimeeHelper.isObject(obj) && !chimeeHelper.isArray(obj)) throw new TypeError('$set only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); + // $FlowFixMe: we have custom this function + if (!chimeeHelper.isFunction(obj.__set)) { + chimeeHelper.Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $set.'); + // $FlowFixMe: we support computed string on array here + obj[property] = value; + return; + } + obj.__set(property, value); + } + }, { + key: '$del', + value: function $del(obj, property) { + if (!chimeeHelper.isObject(obj) && !chimeeHelper.isArray(obj)) throw new TypeError('$del only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); + // $FlowFixMe: we have custom this function + if (!chimeeHelper.isFunction(obj.__del)) { + chimeeHelper.Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $del.'); + // $FlowFixMe: we support computed string on array here + delete obj[property]; + return; + } + obj.__del(property); + } + }, { + key: 'load', + value: function load() { + var _this4 = this; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return new _Promise(function (resolve, reject) { + var _dispatcher$bus2; + + _this4.__dispatcher.bus.once(_this4.__id, '_load', resolve); + (_dispatcher$bus2 = _this4.__dispatcher.bus).emit.apply(_dispatcher$bus2, ['load'].concat(args)); + }); + } + }, { + key: '$silentLoad', + value: function $silentLoad() { + var _this5 = this; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + return this.__dispatcher.bus.emit('silentLoad').then(function () { + var _dispatcher; + + return (_dispatcher = _this5.__dispatcher).silentLoad.apply(_dispatcher, args); + }).then(function (result) { + _this5.__dispatcher.bus.trigger('silentLoad', result); + }); + } + + /** + * call fullscreen api on some specific element + * @param {boolean} flag true means fullscreen and means exit fullscreen + * @param {string} element the element you want to fullscreen, default it's container, you can choose from video | container | wrapper + */ + + }, { + key: '$fullScreen', + value: function $fullScreen() { + var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; + + if (!this.__dispatcher.bus.emitSync('fullScreen', flag, element)) return false; + var result = this.__dispatcher.dom.fullScreen(flag, element); + this.__dispatcher.bus.triggerSync('fullScreen', flag, element); + return result; + } + + /** + * emit an event + * @param {string} key event's name + * @param {...args} args + */ + + }, { + key: '$emit', + value: function $emit(key) { + var _dispatcher$bus3; + + if (!chimeeHelper.isString(key)) throw new TypeError('emit key parameter must be String'); + if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { + chimeeHelper.Log.warn('plugin', 'You are try to emit ' + key + ' event. As emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use emitSync'); + } + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + (_dispatcher$bus3 = this.__dispatcher.bus).emit.apply(_dispatcher$bus3, [key].concat(_toConsumableArray(args))); + } + + /** + * emit a sync event + * @param {string} key event's name + * @param {...args} args + */ + + }, { + key: '$emitSync', + value: function $emitSync(key) { + var _dispatcher$bus4; + + if (!chimeeHelper.isString(key)) throw new TypeError('emitSync key parameter must be String'); + + for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + + return (_dispatcher$bus4 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus4, [key].concat(_toConsumableArray(args))); + } + + /** + * bind event handler through this function + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$on', + value: function $on(key, fn) { + this.__dispatcher.bus.on(this.__id, key, fn); + // set on __events as mark so that i can destroy it when i destroy + this.__addEvents(key, fn); + } + /** + * remove event handler through this function + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$off', + value: function $off(key, fn) { + this.__dispatcher.bus.off(this.__id, key, fn); + this.__removeEvents(key, fn); + } + /** + * bind one time event handler + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$once', + value: function $once(key, fn) { + var self = this; + var boundFn = function boundFn() { + chimeeHelper.bind(fn, this).apply(undefined, arguments); + self.__removeEvents(key, boundFn); + }; + self.__addEvents(key, boundFn); + this.__dispatcher.bus.once(this.__id, key, boundFn); + } + + /** + * set style + * @param {string} element optional, default to be video, you can choose from video | container | wrapper + * @param {string} attribute the atrribue name + * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; + */ + + }, { + key: '$css', + value: function $css(method) { + var _dispatcher$dom2; + + for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + args[_key6 - 1] = arguments[_key6]; + } + + return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom2, args); + } + + /** + * set attr + * @param {string} element optional, default to be video, you can choose from video | container | wrapper + * @param {string} attribute the atrribue nameß + * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; + */ + + }, { + key: '$attr', + value: function $attr(method) { + var _dispatcher$dom3; + + for (var _len7 = arguments.length, args = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + args[_key7 - 1] = arguments[_key7]; + } + + if (method === 'set' && /video/.test(args[0])) { + if (!this.__dispatcher.videoConfigReady) { + chimeeHelper.Log.warn('chimee', this.__id + ' is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); + return args[2]; + } + if (this.__dispatcher.videoConfig._realDomAttr.indexOf(args[1]) > -1) { + var key = args[1], + val = args[2]; + + this.__dispatcher.videoConfig[key] = val; + return val; + } + } + return (_dispatcher$dom3 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom3, args); + } + }, { + key: '__addEvents', + value: function __addEvents(key, fn) { + this.__events[key] = this.__events[key] || []; + this.__events[key].push(fn); + } + }, { + key: '__removeEvents', + value: function __removeEvents(key, fn) { + if (chimeeHelper.isEmpty(this.__events[key])) return; + var index = this.__events[key].indexOf(fn); + if (index < 0) return; + this.__events[key].splice(index, 1); + if (chimeeHelper.isEmpty(this.__events[key])) delete this.__events[key]; + } + }, { + key: '__destroy', + value: function __destroy() { + var _this6 = this; + + this.__unwatchHandlers.forEach(function (unwatcher) { + return unwatcher(); + }); + _Object$keys(this.__events).forEach(function (key) { + if (!chimeeHelper.isArray(_this6.__events[key])) return; + _this6.__events[key].forEach(function (fn) { + return _this6.$off(key, fn); + }); + }); + delete this.__events; + } + }, { + key: 'currentTime', + get: function get() { + return this.__dispatcher.kernel.currentTime; + }, + set: function set(second) { + this.__dispatcher.bus.emitSync('seek', second); + } + }, { + key: '$plugins', + get: function get() { + return this.__dispatcher.plugins; + } + }, { + key: '$pluginOrder', + get: function get() { + return this.__dispatcher.order; + } + }, { + key: '$wrapper', + get: function get() { + propertyAccessibilityWarn('wrapper'); + return this.__dispatcher.dom.wrapper; + } + }, { + key: '$container', + get: function get() { + propertyAccessibilityWarn('container'); + return this.__dispatcher.dom.container; + } + }, { + key: '$video', + get: function get() { + propertyAccessibilityWarn('video'); + return this.__dispatcher.dom.videoElement; + } + }, { + key: 'isFullScreen', + get: function get() { + return this.__dispatcher.dom.isFullScreen; + } + }, { + key: 'fullScreenElement', + get: function get() { + return this.__dispatcher.dom.fullScreenElement; + } + }]); + + return VideoWrapper; +}(), (_applyDecoratedDescriptor$2(_class2$1.prototype, '$silentLoad', [_dec2$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$silentLoad'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$fullScreen', [_dec3$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$fullScreen'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emit', [_dec4$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emit'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emitSync', [_dec5$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emitSync'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec6, _dec7, _dec8], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec9, _dec10, _dec11], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec12, _dec13], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec14, _dec15], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec16, _dec17], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [toxicDecorators.nonenumerable, toxicDecorators.nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [toxicDecorators.nonenumerable, toxicDecorators.nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$pluginOrder'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$wrapper', [toxicDecorators.nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$wrapper'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$container', [toxicDecorators.nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$container'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$video', [toxicDecorators.nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$video'), _class2$1.prototype)), _class2$1)) || _class$3); + +var _dec$2; +var _class$2; + +/** + * <pre> + * Plugin is the class for plugin developer. + * When we use a plugin, we will generate an instance of plugin. + * Developer can do most of things base on this plugin + * </pre> + */ +var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec$2(_class$2 = function (_VideoWrapper) { + _inherits(Plugin, _VideoWrapper); + + /** + * <pre> + * to create a plugin, we need three parameter + * 1. the config of a plugin + * 2. the dispatcher + * 3. this option for plugin to read + * this is the plugin base class, which you can get on Chimee + * You can just extends it and then install + * But in that way you must remember to pass the arguments to super() + * </pre> + * @param {string} PluginConfig.id camelize from plugin's name or class name. + * @param {string} PluginConfig.name plugin's name or class name + * @param {Number} PluginConfig.level the level of z-index + * @param {Boolean} PluginConfig.operable to tell if the plugin can be operable, if not, we will add pointer-events: none on it. + * @param {Function} PluginConfig.create the create function which we will called when plugin is used. sth like constructor in object style. + * @param {Function} PluginConfig.destroy function to be called when we destroy a plugin + * @param {Object} PluginConfig.events You can set some events handler in this object, we will bind it once you use the plugin. + * @param {Object} PluginConfig.data dataset we will bind on data in object style + * @param {Object<{get: Function, set: Function}} PluginConfig.computed dataset we will handle by getter and setter + * @param {Object<Function>} PluginConfig.methods some function we will bind on plugin + * @param {string|HTMLElment} PluginConfig.el can be string or HTMLElement, we will use this to create the dom for plugin + * @param {boolean} PluginConfig.penetrate boolean to let us do we need to forward the dom events for this plugin. + * @param {Dispatcher} dispatcher referrence of dispatcher + * @param {Object} option PluginOption that will pass to the plugin + * @return {Plugin} plugin instance + */ + function Plugin() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + id = _ref.id, + name = _ref.name, + _ref$level = _ref.level, + level = _ref$level === undefined ? 0 : _ref$level, + _ref$operable = _ref.operable, + operable = _ref$operable === undefined ? true : _ref$operable, + beforeCreate = _ref.beforeCreate, + create = _ref.create, + init = _ref.init, + inited = _ref.inited, + destroy = _ref.destroy, + _ref$events = _ref.events, + events = _ref$events === undefined ? {} : _ref$events, + _ref$data = _ref.data, + data = _ref$data === undefined ? {} : _ref$data, + _ref$computed = _ref.computed, + computed = _ref$computed === undefined ? {} : _ref$computed, + _ref$methods = _ref.methods, + methods = _ref$methods === undefined ? {} : _ref$methods, + el = _ref.el, + _ref$penetrate = _ref.penetrate, + penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, + _ref$inner = _ref.inner, inner = _ref$inner === undefined ? true : _ref$inner, autoFocus = _ref.autoFocus, className = _ref.className; @@ -765,9 +1367,8 @@ var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec2$2 = toxicDecorator var _this = _possibleConstructorReturn(this, (Plugin.__proto__ || _Object$getPrototypeOf(Plugin)).call(this)); _this.destroyed = false; - _this.VERSION = '0.1.3'; + _this.VERSION = '0.2.0'; _this.__operable = true; - _this.__events = {}; _this.__level = 0; if (chimeeHelper.isEmpty(dispatcher)) { @@ -930,69 +1531,7 @@ var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec2$2 = toxicDecorator }); return this.readySync || this.ready; } - /** - * set style - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: '$css', - value: function $css(method) { - var _dispatcher$dom; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return (_dispatcher$dom = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom, args); - } - /** - * set attr - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: '$attr', - value: function $attr(method) { - var _dispatcher$dom2; - - for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - if (method === 'set' && /video/.test(args[0])) { - if (!this.__dispatcher.videoConfigReady) { - chimeeHelper.Log.warn('plugin', 'Plugin ' + this.__id + ' is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); - return args[2]; - } - if (this.$videoConfig._realDomAttr.indexOf(args[1]) > -1) { - var key = args[1], - val = args[2]; - - this.$videoConfig[key] = val; - return val; - } - } - return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom2, args); - } - /** - * call fullscreen api on some specific element - * @param {boolean} flag true means fullscreen and means exit fullscreen - * @param {string} element the element you want to fullscreen, default it's container, you can choose from video | container | wrapper - */ - }, { - key: '$fullScreen', - value: function $fullScreen() { - var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; - - return this.__dispatcher.dom.fullScreen(flag, element); - } /** * set the plugin to be the top of all plugins */ @@ -1003,89 +1542,6 @@ var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec2$2 = toxicDecorator var topLevel = this.__dispatcher._getTopLevel(this.$inner); this.$level = topLevel + 1; } - /** - * bind event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$on', - value: function $on(key, fn) { - this.__dispatcher.bus.on(this.__id, key, fn); - // set on __events as mark so that i can destroy it when i destroy - this.__addEvents(key, fn); - } - /** - * remove event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$off', - value: function $off(key, fn) { - this.__dispatcher.bus.off(this.__id, key, fn); - this.__removeEvents(key, fn); - } - /** - * bind one time event handler - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$once', - value: function $once(key, fn) { - var self = this; - var boundFn = function boundFn() { - chimeeHelper.bind(fn, this).apply(undefined, arguments); - self.__removeEvents(key, boundFn); - }; - self.__addEvents(key, boundFn); - this.__dispatcher.bus.once(this.__id, key, boundFn); - } - /** - * emit an event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: '$emit', - value: function $emit(key) { - var _dispatcher$bus; - - if (!chimeeHelper.isString(key)) throw new TypeError('$emit key parameter must be String'); - if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { - chimeeHelper.Log.warn('plugin', 'You are using $emit to emit ' + key + ' event. As $emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use $emitSync'); - } - - for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - (_dispatcher$bus = this.__dispatcher.bus).emit.apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - } - /** - * emit a sync event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: '$emitSync', - value: function $emitSync(key) { - var _dispatcher$bus2; - - if (!chimeeHelper.isString(key)) throw new TypeError('$emitSync key parameter must be String'); - - for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - return (_dispatcher$bus2 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus2, [key].concat(_toConsumableArray(args))); - } }, { key: '$throwError', value: function $throwError(error) { @@ -1099,47 +1555,13 @@ var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec2$2 = toxicDecorator }, { key: '$destroy', value: function $destroy() { - var _this3 = this; - chimeeHelper.isFunction(this.destroy) && this.destroy(); _get(Plugin.prototype.__proto__ || _Object$getPrototypeOf(Plugin.prototype), '__destroy', this).call(this); - _Object$keys(this.__events).forEach(function (key) { - if (!chimeeHelper.isArray(_this3.__events[key])) return; - _this3.__events[key].forEach(function (fn) { - return _this3.$off(key, fn); - }); - }); - delete this.__events; this.__dispatcher.dom.removePlugin(this.__id); delete this.__dispatcher; delete this.$dom; this.destroyed = true; } - }, { - key: '__addEvents', - value: function __addEvents(key, fn) { - this.__events[key] = this.__events[key] || []; - this.__events[key].push(fn); - } - }, { - key: '__removeEvents', - value: function __removeEvents(key, fn) { - if (chimeeHelper.isEmpty(this.__events[key])) return; - var index = this.__events[key].indexOf(fn); - if (index < 0) return; - this.__events[key].splice(index, 1); - if (chimeeHelper.isEmpty(this.__events[key])) delete this.__events[key]; - } - }, { - key: '$plugins', - get: function get() { - return this.__dispatcher.plugins; - } - }, { - key: '$pluginOrder', - get: function get() { - return this.__dispatcher.order; - } /** * to tell us if the plugin can be operable, can be dynamic change * @type {boolean} @@ -1173,17 +1595,17 @@ var Plugin = (_dec$2 = toxicDecorators.autobindClass(), _dec2$2 = toxicDecorator }]); return Plugin; -}(VideoWrapper), (_applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec2$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec4$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec5$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec6$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [toxicDecorators.nonenumerable, toxicDecorators.nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [toxicDecorators.nonenumerable, toxicDecorators.nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$pluginOrder'), _class2$1.prototype)), _class2$1)) || _class$2); +}(VideoWrapper)) || _class$2); -var _dec$3; +var _dec$5; var _dec2$3; -var _dec3$3; -var _dec4$3; -var _dec5$3; -var _dec6$2; -var _class$3; +var _dec3$2; +var _dec4$2; +var _dec5$2; +var _dec6$1; +var _class$5; -function _applyDecoratedDescriptor$3(target, property, decorators, descriptor, context) { +function _applyDecoratedDescriptor$4(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; @@ -1233,7 +1655,7 @@ function attrOperationCheck(target, attr, val) { * It take charge of dom management of Dispatcher. * </pre> */ -var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), _dec2$3 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec3$3 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec4$3 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec5$3 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec6$2 = toxicDecorators.before(targetCheck), (_class$3 = function () { +var Dom = (_dec$5 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), _dec2$3 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec3$2 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec4$2 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec5$2 = toxicDecorators.before(attrOperationCheck, targetCheck), _dec6$1 = toxicDecorators.before(targetCheck), (_class$5 = function () { /** * to mark is the mouse in the video area * @type {boolean} @@ -1270,6 +1692,8 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), this.__domEventHandlerList = {}; this.__mouseInVideo = false; this.__videoExtendedNodes = []; + this.isFullScreen = false; + this.fullScreenElement = undefined; this.__dispatcher = dispatcher; if (!chimeeHelper.isElement(wrapper) && !chimeeHelper.isString(wrapper)) throw new TypeError('Illegal wrapper'); @@ -1294,77 +1718,14 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), * referrence of video's dom element * @type {Element} */ - this.videoElement = videoElement; - this.__videoExtendedNodes.push(videoElement); - this.setAttr('videoElement', 'tabindex', -1); - this._autoFocusToVideo(this.videoElement); - // create container - if (this.videoElement.parentElement && chimeeHelper.isElement(this.videoElement.parentElement) && this.videoElement.parentElement !== this.wrapper) { - this.container = this.videoElement.parentElement; - } else { - this.container = document.createElement('container'); - chimeeHelper.$(this.container).append(this.videoElement); - } - // check container.position - if (this.container.parentElement !== this.wrapper) { - $wrapper.append(this.container); - } - videoEvents.forEach(function (key) { - var fn = function fn() { - var _dispatcher$bus; - - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - return (_dispatcher$bus = _this.__dispatcher.bus).trigger.apply(_dispatcher$bus, [key].concat(args)); - }; - _this.videoEventHandlerList.push(fn); - chimeeHelper.addEvent(_this.videoElement, key, fn); - }); + this.installVideo(videoElement); domEvents.forEach(function (key) { var fn = _this._getEventHandler(key, { penetrate: true }); _this.videoDomEventHandlerList.push(fn); chimeeHelper.addEvent(_this.videoElement, key, fn); - var cfn = function cfn() { - var _dispatcher$bus2; - - for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - - return (_dispatcher$bus2 = _this.__dispatcher.bus).triggerSync.apply(_dispatcher$bus2, ['c_' + key].concat(args)); - }; - _this.containerDomEventHandlerList.push(cfn); - chimeeHelper.addEvent(_this.container, key, cfn); - var wfn = function wfn() { - var _dispatcher$bus3; - - for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - - return (_dispatcher$bus3 = _this.__dispatcher.bus).triggerSync.apply(_dispatcher$bus3, ['w_' + key].concat(args)); - }; - _this.wrapperDomEventHandlerList.push(wfn); - chimeeHelper.addEvent(_this.wrapper, key, wfn); }); + this._bindFullScreen(); } - /** - * <pre> - * each plugin has its own dom node, this function will create one or them. - * we support multiple kind of el - * 1. Element, we will append this dom node on wrapper straight - * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper - * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper - * 4. nothing, we will create a div and bind it on the wrapper - * </pre> - * @param {string} id plugin's id - * @param {string|Element} el(optional) the el can be custom dom element or html string to insert - * @param {boolean} inner if it's true, we will put it into conatiner, else we would put it into outer - * @return {Node} - */ - /** * Object to store different plugin's dom event handlers * @type {Object} @@ -1395,9 +1756,90 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), _createClass(Dom, [{ + key: 'installVideo', + value: function installVideo(videoElement) { + var _this2 = this; + + this.__videoExtendedNodes.push(videoElement); + chimeeHelper.setAttr(videoElement, 'tabindex', -1); + this._autoFocusToVideo(videoElement); + if (!chimeeHelper.isElement(this.container)) { + // create container + if (videoElement.parentElement && chimeeHelper.isElement(videoElement.parentElement) && videoElement.parentElement !== this.wrapper) { + this.container = videoElement.parentElement; + } else { + this.container = document.createElement('container'); + chimeeHelper.$(this.container).append(videoElement); + } + } else { + var container = this.container; + if (container.childNodes.length === 0) { + container.appendChild(videoElement); + } else { + container.insertBefore(videoElement, container.childNodes[0]); + } + } + // check container.position + if (this.container.parentElement !== this.wrapper) { + chimeeHelper.$(this.wrapper).append(this.container); + } + videoEvents.forEach(function (key) { + var fn = function fn() { + var _dispatcher$bus; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return (_dispatcher$bus = _this2.__dispatcher.bus).trigger.apply(_dispatcher$bus, [key].concat(args)); + }; + _this2.videoEventHandlerList.push(fn); + chimeeHelper.addEvent(videoElement, key, fn); + }); + domEvents.forEach(function (key) { + var fn = _this2._getEventHandler(key, { penetrate: true }); + _this2.videoDomEventHandlerList.push(fn); + chimeeHelper.addEvent(videoElement, key, fn); + }); + this.videoElement = videoElement; + return videoElement; + } + }, { + key: 'removeVideo', + value: function removeVideo() { + var _this3 = this; + + var videoElement = this.videoElement; + this._autoFocusToVideo(this.videoElement, false); + videoEvents.forEach(function (key, index) { + chimeeHelper.removeEvent(_this3.videoElement, key, _this3.videoEventHandlerList[index]); + }); + domEvents.forEach(function (key, index) { + chimeeHelper.removeEvent(_this3.videoElement, key, _this3.videoDomEventHandlerList[index]); + }); + chimeeHelper.$(videoElement).remove(); + delete this.videoElement; + return videoElement; + } + /** + * <pre> + * each plugin has its own dom node, this function will create one or them. + * we support multiple kind of el + * 1. Element, we will append this dom node on wrapper straight + * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper + * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper + * 4. nothing, we will create a div and bind it on the wrapper + * </pre> + * @param {string} id plugin's id + * @param {string|Element} el(optional) the el can be custom dom element or html string to insert + * @param {boolean} inner if it's true, we will put it into conatiner, else we would put it into outer + * @return {Node} + */ + + }, { key: 'insertPlugin', value: function insertPlugin(id, el) { - var _this2 = this; + var _this4 = this; var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -1439,9 +1881,9 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), if (penetrate) { this.__domEventHandlerList[id] = this.__domEventHandlerList[id] || []; domEvents.forEach(function (key) { - var fn = _this2._getEventHandler(key, { penetrate: penetrate }); + var fn = _this4._getEventHandler(key, { penetrate: penetrate }); chimeeHelper.addEvent(node, key, fn); - _this2.__domEventHandlerList[id].push(fn); + _this4.__domEventHandlerList[id].push(fn); }); this.__videoExtendedNodes.push(node); } @@ -1460,7 +1902,7 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), }, { key: 'removePlugin', value: function removePlugin(id) { - var _this3 = this; + var _this5 = this; if (!chimeeHelper.isString(id)) return; var dom = this.plugins[id]; @@ -1470,7 +1912,7 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), } if (!chimeeHelper.isEmpty(this.__domEventHandlerList[id])) { domEvents.forEach(function (key, index) { - chimeeHelper.removeEvent(_this3.plugins[id], key, _this3.__domEventHandlerList[id][index]); + chimeeHelper.removeEvent(_this5.plugins[id], key, _this5.__domEventHandlerList[id][index]); }); delete this.__domEventHandlerList[id]; } @@ -1484,11 +1926,11 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), }, { key: 'setPluginsZIndex', value: function setPluginsZIndex(plugins) { - var _this4 = this; + var _this6 = this; // $FlowFixMe: there are videoElment and container here plugins.forEach(function (key, index) { - return chimeeHelper.setStyle(key.match(/^(videoElement|container)$/) ? _this4[key] : _this4.plugins[key], 'z-index', ++index); + return chimeeHelper.setStyle(key.match(/^(videoElement|container)$/) ? _this6[key] : _this6.plugins[key], 'z-index', ++index); }); } /** @@ -1556,8 +1998,8 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), var request = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; - for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { - args[_key5 - 2] = arguments[_key5]; + for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { + args[_key3 - 2] = arguments[_key3]; } return request ? this.requestFullScreen.apply(this, [target].concat(_toConsumableArray(args))) : this.exitFullScreen.apply(this, _toConsumableArray(args)); @@ -1574,20 +2016,16 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), }, { key: 'destroy', value: function destroy() { - var _this5 = this; + var _this7 = this; - this._autoFocusToVideo(this.videoElement, false); - videoEvents.forEach(function (key, index) { - chimeeHelper.removeEvent(_this5.videoElement, key, _this5.videoEventHandlerList[index]); - }); + this.removeVideo(); domEvents.forEach(function (key, index) { - chimeeHelper.removeEvent(_this5.videoElement, key, _this5.videoDomEventHandlerList[index]); - chimeeHelper.removeEvent(_this5.container, key, _this5.containerDomEventHandlerList[index]); - chimeeHelper.removeEvent(_this5.wrapper, key, _this5.wrapperDomEventHandlerList[index]); + chimeeHelper.removeEvent(_this7.container, key, _this7.containerDomEventHandlerList[index]); + chimeeHelper.removeEvent(_this7.wrapper, key, _this7.wrapperDomEventHandlerList[index]); }); + this._bindFullScreen(true); this.wrapper.innerHTML = this.originHTML; delete this.wrapper; - delete this.videoElement; delete this.plugins; } }, { @@ -1606,368 +2044,96 @@ var Dom = (_dec$3 = toxicDecorators.waituntil('__dispatcher.videoConfigReady'), chimeeHelper.isFunction(this.videoElement.focus) && this.videoElement.focus(); window.scrollTo(x, y); } - /** - * get the event handler for dom to bind - */ - }, { - key: '_getEventHandler', - value: function _getEventHandler(key, _ref) { - var _this6 = this; - - var penetrate = _ref.penetrate; - - if (!penetrate || ['mouseenter', 'mouseleave'].indexOf(key) < 0) { - return function () { - var _dispatcher$bus4; - - for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - - (_dispatcher$bus4 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, [key].concat(args)); - }; - } - var insideVideo = function insideVideo(node) { - return _this6.__videoExtendedNodes.indexOf(node) > -1 || _this6.__videoExtendedNodes.reduce(function (flag, video) { - if (flag) return flag; - return chimeeHelper.isPosterityNode(video, node); - }, false); - }; - return function () { - for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; - } - - var _args$ = args[0], - toElement = _args$.toElement, - currentTarget = _args$.currentTarget, - relatedTarget = _args$.relatedTarget, - type = _args$.type; - - var to = toElement || relatedTarget; - if (_this6.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { - var _dispatcher$bus5; - - _this6.__mouseInVideo = false; - return (_dispatcher$bus5 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus5, ['mouseleave'].concat(args)); - } - if (!_this6.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { - var _dispatcher$bus6; - - _this6.__mouseInVideo = true; - return (_dispatcher$bus6 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus6, ['mouseenter'].concat(args)); - } - }; - } - }]); - - return Dom; -}(), (_applyDecoratedDescriptor$3(_class$3.prototype, 'setAttr', [_dec$3, _dec2$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'setAttr'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'getAttr', [_dec3$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'getAttr'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'setStyle', [_dec4$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'setStyle'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'getStyle', [_dec5$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'getStyle'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'requestFullScreen', [_dec6$2], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'requestFullScreen'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, '_focusToVideo', [toxicDecorators.autobind], _Object$getOwnPropertyDescriptor(_class$3.prototype, '_focusToVideo'), _class$3.prototype)), _class$3)); - -var _dec$4; -var _dec2$4; -var _dec3$4; -var _class$4; -var _descriptor$1; -var _descriptor2$1; -var _descriptor3$1; -var _descriptor4; -var _descriptor5; -var _descriptor6; -var _descriptor7; - -function _initDefineProp$1(target, property, descriptor, context) { - if (!descriptor) return; - - _Object$defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor$4(target, property, decorators, descriptor, context) { - var desc = {}; - Object['ke' + 'ys'](descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object['define' + 'Property'](target, property, desc); - desc = null; - } - - return desc; -} - -function numberOrVoid(value) { - return chimeeHelper.isNumber(value) ? value : undefined; -} -function stringOrVoid(value) { - return chimeeHelper.isString(value) ? value : undefined; -} - -function accessorVideoProperty(property) { - return toxicDecorators.accessor({ - get: function get(value) { - return this.dispatcher.videoConfigReady && this.inited ? this.videoElement[property] : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - this.videoElement[property] = value; - return value; - } - }); -} - -function accessorVideoAttribute(attribute) { - var _ref = chimeeHelper.isObject(attribute) ? attribute : { - set: attribute, - get: attribute, - isBoolean: false - }, - _set = _ref.set, - _get$$1 = _ref.get, - isBoolean$$1 = _ref.isBoolean; - - return toxicDecorators.accessor({ - get: function get(value) { - return this.dispatcher.videoConfigReady && this.inited ? this.videoElement[_get$$1] : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - var val = isBoolean$$1 ? value ? '' : undefined : value; - this.dispatcher.dom.setAttr('video', _set, val); - return value; - } - }); -} - -function accessorCustomAttribute(attribute, isBoolean$$1) { - return toxicDecorators.accessor({ - get: function get(value) { - var attrValue = this.dispatcher.dom.getAttr('video', attribute); - return this.dispatcher.videoConfigReady && this.inited ? isBoolean$$1 ? !!attrValue : attrValue : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - var val = isBoolean$$1 ? value || undefined : value; - this.dispatcher.dom.setAttr('video', attribute, val); - return value; - } - }); -} - -var accessorMap = { - src: [toxicDecorators.alwaysString(), toxicDecorators.accessor({ - set: function set(val) { - if (this.needToLoadSrc) { - // unlock it at first, to avoid deadlock - this.needToLoadSrc = false; - this.dispatcher.bus.emit('load', val); + key: '_fullScreenMonitor', + value: function _fullScreenMonitor() { + var element = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullScreenElement', 'msFullscreenElement'].reduce(function (element, key) { + // $FlowFixMe: support computed element on document + return element || document[key]; + }, null); + if (!element || !chimeeHelper.isPosterityNode(this.wrapper, element) && element !== this.wrapper) { + this.isFullScreen = false; + this.fullScreenElement = undefined; + return; } - return val; - } - }, { preSet: false }), toxicDecorators.accessor({ - set: function set(val) { - // must check val !== this.src here - // as we will set config.src in the video - // the may cause dead lock - if (this.dispatcher.readySync && this.autoload && val !== this.src) this.needToLoadSrc = true; - return val; - } - })], - autoload: toxicDecorators.alwaysBoolean(), - autoplay: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('autoplay')], - controls: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('controls')], - width: [toxicDecorators.accessor({ set: numberOrVoid }), accessorVideoAttribute('width')], - height: [toxicDecorators.accessor({ set: numberOrVoid }), accessorVideoAttribute('height')], - crossOrigin: [toxicDecorators.accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' })], - loop: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('loop')], - defaultMuted: [toxicDecorators.alwaysBoolean(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true })], - muted: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('muted')], - preload: [toxicDecorators.accessor({ set: stringOrVoid }), accessorVideoAttribute('preload')], - poster: [toxicDecorators.accessor({ set: stringOrVoid }), accessorVideoAttribute('poster')], - playsInline: [toxicDecorators.accessor({ - get: function get(value) { - var playsInline = this.videoElement.playsInline; - return this.dispatcher.videoConfigReady && this.inited ? playsInline === undefined ? value : playsInline : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - this.videoElement.playsInline = value; - var val = value ? '' : undefined; - this.dispatcher.dom.setAttr('video', 'playsinline', val); - this.dispatcher.dom.setAttr('video', 'webkit-playsinline', val); - this.dispatcher.dom.setAttr('video', 'x5-video-player-type', value ? 'h5' : undefined); - return value; - } - }), toxicDecorators.alwaysBoolean()], - x5VideoPlayerFullScreen: [toxicDecorators.accessor({ - set: function set(value) { - return !!value; - }, - get: function get(value) { - return !!value; - } - }), accessorCustomAttribute('x5-video-player-fullscreen', true)], - x5VideoOrientation: [toxicDecorators.accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], - xWebkitAirplay: [toxicDecorators.accessor({ - set: function set(value) { - return !!value; - }, - get: function get(value) { - return !!value; + this.isFullScreen = true; + this.fullScreenElement = this.wrapper === element ? 'wrapper' : this.container === element ? 'container' : this.videoElement === element ? 'video' : element; } - }), accessorCustomAttribute('x-webkit-airplay', true)], - playbackRate: [toxicDecorators.alwaysNumber(1), accessorVideoProperty('playbackRate')], - defaultPlaybackRate: [accessorVideoProperty('defaultPlaybackRate'), toxicDecorators.alwaysNumber(1)], - disableRemotePlayback: [toxicDecorators.alwaysBoolean(), accessorVideoProperty('disableRemotePlayback')], - volume: [toxicDecorators.alwaysNumber(1), accessorVideoProperty('volume')] -}; + }, { + key: '_bindFullScreen', + value: function _bindFullScreen(remove) { + var _this8 = this; -var VideoConfig = (_dec$4 = toxicDecorators.initString(), _dec2$4 = toxicDecorators.initString(function (str) { - return str.toLocaleLowerCase(); -}), _dec3$4 = toxicDecorators.initArray(), (_class$4 = function () { - _createClass(VideoConfig, [{ - key: 'lockKernelProperty', - value: function lockKernelProperty() { - toxicDecorators.applyDecorators(this, { - type: toxicDecorators.lock, - box: toxicDecorators.lock, - runtimeOrder: toxicDecorators.lock - }, { self: true }); + if (!remove) this._fullScreenMonitor(); + ['webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange', 'fullscreenchange'].forEach(function (key) { + // $FlowFixMe: support computed element on document + document[(remove ? 'remove' : 'add') + 'EventListener'](key, _this8._fullScreenMonitor); + }); } - }]); - - function VideoConfig(dispatcher, config) { - _classCallCheck(this, VideoConfig); - - _initDefineProp$1(this, 'needToLoadSrc', _descriptor$1, this); - - _initDefineProp$1(this, 'inited', _descriptor2$1, this); - - this.src = ''; - - _initDefineProp$1(this, 'type', _descriptor3$1, this); - - _initDefineProp$1(this, 'box', _descriptor4, this); - - _initDefineProp$1(this, 'runtimeOrder', _descriptor5, this); - - this.autoload = true; - this.autoplay = false; - this.controls = false; - this.width = undefined; - this.height = undefined; - this.crossOrigin = undefined; - this.loop = false; - this.defaultMuted = false; - this.muted = false; - this.preload = 'auto'; - this.poster = undefined; - this.playsInline = false; - this.x5VideoPlayerFullScreen = false; - this.x5VideoOrientation = undefined; - this.xWebkitAirplay = false; - this.playbackRate = 1; - this.defaultPlaybackRate = 1; - this.disableRemotePlayback = false; - this.volume = 1; + /** + * get the event handler for dom to bind + */ - _initDefineProp$1(this, '_kernelProperty', _descriptor6, this); + }, { + key: '_getEventHandler', + value: function _getEventHandler(key, _ref) { + var _this9 = this; - _initDefineProp$1(this, '_realDomAttr', _descriptor7, this); + var penetrate = _ref.penetrate; - toxicDecorators.applyDecorators(this, accessorMap, { self: true }); - Object.defineProperty(this, 'dispatcher', { - value: dispatcher, - enumerable: false, - writable: false, - configurable: false - }); - Object.defineProperty(this, 'videoElement', { - value: dispatcher.dom.videoElement, - enumerable: false, - writable: false, - configurable: false - }); - chimeeHelper.deepAssign(this, config); - } + if (!penetrate || ['mouseenter', 'mouseleave'].indexOf(key) < 0) { + return function () { + var _dispatcher$bus2; - _createClass(VideoConfig, [{ - key: 'init', - value: function init() { - var _this = this; + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } - this._realDomAttr.forEach(function (key) { - // $FlowFixMe: we have check the computed here - _this[key] = _this[key]; - }); - this.inited = true; + (_dispatcher$bus2 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus2, [key].concat(args)); + }; + } + var insideVideo = function insideVideo(node) { + return _this9.__videoExtendedNodes.indexOf(node) > -1 || _this9.__videoExtendedNodes.reduce(function (flag, video) { + if (flag) return flag; + return chimeeHelper.isPosterityNode(video, node); + }, false); + }; + return function () { + for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + + var _args$ = args[0], + toElement = _args$.toElement, + currentTarget = _args$.currentTarget, + relatedTarget = _args$.relatedTarget, + type = _args$.type; + + var to = toElement || relatedTarget; + if (_this9.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { + var _dispatcher$bus3; + + _this9.__mouseInVideo = false; + return (_dispatcher$bus3 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus3, ['mouseleave'].concat(args)); + } + if (!_this9.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { + var _dispatcher$bus4; + + _this9.__mouseInVideo = true; + return (_dispatcher$bus4 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, ['mouseenter'].concat(args)); + } + }; } }]); - return VideoConfig; -}(), (_descriptor$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'needToLoadSrc', [toxicDecorators.nonenumerable], { - enumerable: true, - initializer: function initializer() { - return false; - } -}), _descriptor2$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'inited', [toxicDecorators.nonenumerable], { - enumerable: true, - initializer: function initializer() { - return false; - } -}), _descriptor3$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'type', [_dec$4, toxicDecorators.configurable], { - enumerable: true, - initializer: function initializer() { - return 'vod'; - } -}), _descriptor4 = _applyDecoratedDescriptor$4(_class$4.prototype, 'box', [_dec2$4, toxicDecorators.configurable], { - enumerable: true, - initializer: function initializer() { - return ''; - } -}), _descriptor5 = _applyDecoratedDescriptor$4(_class$4.prototype, 'runtimeOrder', [_dec3$4, toxicDecorators.configurable], { - enumerable: true, - initializer: function initializer() { - return ['html5', 'flash']; - } -}), _descriptor6 = _applyDecoratedDescriptor$4(_class$4.prototype, '_kernelProperty', [toxicDecorators.frozen], { - enumerable: true, - initializer: function initializer() { - return ['type', 'box', 'runtimeOrder']; - } -}), _descriptor7 = _applyDecoratedDescriptor$4(_class$4.prototype, '_realDomAttr', [toxicDecorators.frozen], { - enumerable: true, - initializer: function initializer() { - return ['src', 'controls', 'width', 'height', 'crossOrigin', 'loop', 'muted', 'preload', 'poster', 'autoplay', 'playsInline', 'x5VideoPlayerFullScreen', 'x5VideoOrientation', 'xWebkitAirplay', 'playbackRate', 'defaultPlaybackRate', 'autoload', 'disableRemotePlayback', 'defaultMuted', 'volume']; - } -})), _class$4)); + return Dom; +}(), (_applyDecoratedDescriptor$4(_class$5.prototype, 'setAttr', [_dec$5, _dec2$3], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'setAttr'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'getAttr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'getAttr'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'setStyle', [_dec4$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'setStyle'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'getStyle', [_dec5$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'getStyle'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'requestFullScreen', [_dec6$1], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'requestFullScreen'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, '_focusToVideo', [toxicDecorators.autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, '_focusToVideo'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, '_fullScreenMonitor', [toxicDecorators.autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, '_fullScreenMonitor'), _class$5.prototype)), _class$5)); var _dec$1; -var _dec2$1; -var _dec3$1; -var _dec4$1; -var _dec5$1; +var _dec2; +var _dec3; +var _dec4; +var _dec5; var _class$1; function _applyDecoratedDescriptor$1(target, property, decorators, descriptor, context) { @@ -2023,7 +2189,7 @@ function checkPluginConfig(config) { * It also offer a bridge to let user handle video kernel. * </pre> */ -var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = toxicDecorators.before(checkPluginConfig), _dec3$1 = toxicDecorators.before(convertNameIntoId), _dec4$1 = toxicDecorators.before(convertNameIntoId), _dec5$1 = toxicDecorators.before(convertNameIntoId), (_class$1 = function () { +var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2 = toxicDecorators.before(checkPluginConfig), _dec3 = toxicDecorators.before(convertNameIntoId), _dec4 = toxicDecorators.before(convertNameIntoId), _dec5 = toxicDecorators.before(convertNameIntoId), (_class$1 = function () { /** * @param {UserConfig} config UserConfig for whole Chimee player * @param {Chimee} vm referrence of outer class @@ -2031,15 +2197,15 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = */ /** - * the synchronous ready flag - * @type {boolean} - * @member readySync + * the z-index map of the dom, it contain some important infomation + * @type {Object} + * @member zIndexMap */ /** - * all plugins instance set - * @type {Object} - * @member plugins + * plugin's order + * @type {Array<string>} + * @member order */ function Dispatcher(config, vm) { var _this = this; @@ -2053,6 +2219,7 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = inner: [], outer: [] }; + this.changeWatchable = true; if (!chimeeHelper.isObject(config)) throw new TypeError('UserConfig must be an Object'); /** @@ -2113,15 +2280,15 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = */ /** - * the z-index map of the dom, it contain some important infomation - * @type {Object} - * @member zIndexMap + * the synchronous ready flag + * @type {boolean} + * @member readySync */ /** - * plugin's order - * @type {Array<string>} - * @member order + * all plugins instance set + * @type {Object} + * @member plugins */ @@ -2187,6 +2354,186 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = value: function throwError(error) { this.vm.__throwError(error); } + }, { + key: 'silentLoad', + value: function silentLoad(src) { + var _this2 = this; + + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _option$duration = option.duration, + duration = _option$duration === undefined ? 3 : _option$duration, + _option$bias = option.bias, + bias = _option$bias === undefined ? 0 : _option$bias, + _option$repeatTimes = option.repeatTimes, + repeatTimes = _option$repeatTimes === undefined ? 0 : _option$repeatTimes, + _option$increment = option.increment, + increment = _option$increment === undefined ? 0 : _option$increment, + _option$isLive = option.isLive, + isLive = _option$isLive === undefined ? this.videoConfig.isLive : _option$isLive, + _option$box = option.box, + box = _option$box === undefined ? this.videoConfig.box : _option$box, + _option$preset = option.preset, + preset = _option$preset === undefined ? this.videoConfig.preset : _option$preset; + // form the base config for kernel + // it should be the same as the config now + + var config = { isLive: isLive, box: box, src: src, preset: preset }; + // build tasks accroding repeat times + var tasks = new Array(repeatTimes + 1).fill(1).map(function (value, index) { + return function () { + return new _Promise(function (resolve, reject) { + // if abort, give up and reject + if (option.abort) reject({ error: true, message: 'user abort the mission' }); + var video = document.createElement('video'); + var idealTime = _this2.kernel.currentTime + duration + increment * index; + video.muted = true; + var newVideoReady = false; + // bind time update on old video + // when we bump into the switch point and ready + // we switch + var oldVideoTimeupdate = function oldVideoTimeupdate(evt) { + var currentTime = _this2.kernel.currentTime; + if (bias <= 0 && currentTime >= idealTime || bias > 0 && (Math.abs(idealTime - currentTime) <= bias && newVideoReady || currentTime - idealTime > bias)) { + chimeeHelper.removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + if (!newVideoReady) { + chimeeHelper.removeEvent(video, 'canplay', videoCanplay); + chimeeHelper.removeEvent(video, 'loadedmetadata', videoLoadedmetadata); + chimeeHelper.removeEvent(video, 'error', videoError); + kernel.destroy(); + return resolve(); + } + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + var videoCanplay = function videoCanplay(evt) { + newVideoReady = true; + // you can set it immediately run by yourself + if (option.immediate) { + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + var videoLoadedmetadata = function videoLoadedmetadata(evt) { + kernel.seek(idealTime); + }; + var videoError = function videoError(evt) { + chimeeHelper.removeEvent(video, 'canplay', videoCanplay, true); + chimeeHelper.removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + chimeeHelper.removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + var error = !chimeeHelper.isEmpty(video.error) ? new Error(video.error.message) : new Error('unknow video error'); + chimeeHelper.Log.error("chimee's silentload", error.message); + kernel.destroy(); + return index === repeatTimes ? reject(error) : resolve(error); + }; + chimeeHelper.addEvent(video, 'canplay', videoCanplay, true); + chimeeHelper.addEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + chimeeHelper.addEvent(video, 'error', videoError, true); + chimeeHelper.addEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + var kernel = new Kernel(video, config); + kernel.load(); + }); + }; + }); + return chimeeHelper.runRejectableQueue(tasks).then(function () { + var message = 'The silentLoad for ' + src + ' timed out. Please set a longer duration or check your network'; + chimeeHelper.Log.warn("chimee's silentLoad", message); + return _Promise.reject(new Error(message)); + }).catch(function (data) { + if (chimeeHelper.isError(data)) { + return _Promise.reject(data); + } + if (data.error) { + chimeeHelper.Log.warn("chimee's silentLoad", data.message); + return _Promise.reject(new Error(data.message)); + } + var video = data.video, + kernel = data.kernel; + + if (option.abort) { + kernel.destroy(); + return _Promise.reject(new Error('user abort the mission')); + } + var paused = _this2.dom.videoElement.paused; + _this2.switchKernel({ video: video, kernel: kernel, config: config }); + if (!paused) _this2.dom.videoElement.play(); + return _Promise.resolve(); + }); + } + }, { + key: 'load', + value: function load(src) { + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!chimeeHelper.isEmpty(option)) { + var videoConfig = this.videoConfig; + + var _option$isLive2 = option.isLive, + _isLive = _option$isLive2 === undefined ? videoConfig.isLive : _option$isLive2, + _option$box2 = option.box, + _box = _option$box2 === undefined ? videoConfig.box : _option$box2, + _option$preset2 = option.preset, + _preset = _option$preset2 === undefined ? videoConfig.preset : _option$preset2; + + var video = document.createElement('video'); + var config = { isLive: _isLive, box: _box, preset: _preset, src: src }; + var _kernel = new Kernel(video, config); + this.switchKernel({ video: video, kernel: _kernel, config: config }); + } + this.kernel.load(src); + } + }, { + key: 'switchKernel', + value: function switchKernel(_ref) { + var _this3 = this; + + var video = _ref.video, + kernel = _ref.kernel, + config = _ref.config; + + var oldKernel = this.kernel; + oldKernel.destroy(); + var originVideoConfig = chimeeHelper.deepClone(this.videoConfig); + this.dom.removeVideo(); + this.dom.installVideo(video); + // as we will reset the currentVideoConfig on the new video + // it will trigger the watch function as they maybe differnet + // so we need to stop them + this.videoConfig.changeWatchable = false; + this.videoConfig.autoload = false; + this.videoConfig.src = config.src; + this.videoConfig._realDomAttr.forEach(function (key) { + // $FlowFixMe: support computed key here + if (key !== 'src') _this3.videoConfig[key] = originVideoConfig[key]; + }); + this.videoConfig.changeWatchable = true; + // bind the new config in new kernel to the videoConfig + toxicDecorators.applyDecorators(config, { + src: toxicDecorators.accessor({ + get: function get(value) { + return _this3.videoConfig.src; + }, + set: function set(value) { + _this3.videoConfig.src = value; + return value; + } + }) + }, { self: true }); + // the kernel's inner config would not be change according what we do + // so we have to load that + // applyDecorators(kernel.__proto__, { + // load: before(src => { + // return [src || this.videoConfig.src]; + // }) + // }, {self: true}); + this.kernel = kernel; + } /** * destroy function called when dispatcher destroyed */ @@ -2216,7 +2563,7 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = }, { key: '_initUserPlugin', value: function _initUserPlugin() { - var _this2 = this; + var _this4 = this; var configs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; @@ -2225,7 +2572,7 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = configs = []; } return configs.map(function (config) { - return _this2.use(config); + return _this4.use(config); }); } /** @@ -2235,10 +2582,10 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = }, { key: '_sortZIndex', value: function _sortZIndex() { - var _this3 = this; + var _this5 = this; var _order$reduce = this.order.reduce(function (levelSet, key) { - var plugin = _this3.plugins[key]; + var plugin = _this5.plugins[key]; if (chimeeHelper.isEmpty(plugin)) return levelSet; var set = levelSet[plugin.$inner ? 'inner' : 'outer']; var level = plugin.$level; @@ -2319,9 +2666,9 @@ var Dispatcher = (_dec$1 = toxicDecorators.before(convertNameIntoId), _dec2$1 = }]); return Dispatcher; -}(), (_applyDecoratedDescriptor$1(_class$1.prototype, 'unuse', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'unuse'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1, 'install', [_dec2$1], _Object$getOwnPropertyDescriptor(_class$1, 'install'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'hasInstalled', [_dec3$1], _Object$getOwnPropertyDescriptor(_class$1, 'hasInstalled'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'uninstall', [_dec4$1], _Object$getOwnPropertyDescriptor(_class$1, 'uninstall'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'getPluginConfig', [_dec5$1], _Object$getOwnPropertyDescriptor(_class$1, 'getPluginConfig'), _class$1)), _class$1)); +}(), (_applyDecoratedDescriptor$1(_class$1.prototype, 'unuse', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'unuse'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1, 'install', [_dec2], _Object$getOwnPropertyDescriptor(_class$1, 'install'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'hasInstalled', [_dec3], _Object$getOwnPropertyDescriptor(_class$1, 'hasInstalled'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'uninstall', [_dec4], _Object$getOwnPropertyDescriptor(_class$1, 'uninstall'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'getPluginConfig', [_dec5], _Object$getOwnPropertyDescriptor(_class$1, 'getPluginConfig'), _class$1)), _class$1)); -var _class$5; +var _class$6; var _descriptor$2; function _initDefineProp$2(target, property, descriptor, context) { @@ -2364,7 +2711,7 @@ function _applyDecoratedDescriptor$5(target, property, decorators, descriptor, c return desc; } -var GlobalConfig = (_class$5 = function () { +var GlobalConfig = (_class$6 = function () { _createClass(GlobalConfig, [{ key: 'silent', get: function get() { @@ -2415,21 +2762,14 @@ var GlobalConfig = (_class$5 = function () { } return GlobalConfig; -}(), (_descriptor$2 = _applyDecoratedDescriptor$5(_class$5.prototype, '_silent', [toxicDecorators.nonenumerable], { +}(), (_descriptor$2 = _applyDecoratedDescriptor$5(_class$6.prototype, '_silent', [toxicDecorators.nonenumerable], { enumerable: true, initializer: function initializer() { return false; } -})), _class$5); +})), _class$6); var _dec; -var _dec2; -var _dec3; -var _dec4; -var _dec5; -var _dec6; -var _dec7; -var _dec8; var _class; var _class2; var _descriptor; @@ -2484,7 +2824,7 @@ function _applyDecoratedDescriptor(target, property, decorators, descriptor, con return desc; } -var Chimee = (_dec = toxicDecorators.autobindClass(), _dec2 = toxicDecorators.alias('addEventListener'), _dec3 = toxicDecorators.before(eventBinderCheck), _dec4 = toxicDecorators.before(eventBinderCheck), _dec5 = toxicDecorators.alias('removeEventListener'), _dec6 = toxicDecorators.before(eventBinderCheck), _dec7 = toxicDecorators.before(attrAndStyleCheck), _dec8 = toxicDecorators.before(attrAndStyleCheck), _dec(_class = (_class2 = (_temp = _class3 = function (_VideoWrapper) { +var Chimee = (_dec = toxicDecorators.autobindClass(), _dec(_class = (_class2 = (_temp = _class3 = function (_VideoWrapper) { _inherits(Chimee, _VideoWrapper); function Chimee(config) { @@ -2535,133 +2875,6 @@ var Chimee = (_dec = toxicDecorators.autobindClass(), _dec2 = toxicDecorators.al value: function unuse(name) { this.__dispatcher.unuse(name); } - /** - * bind event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'on', - value: function on(key, fn) { - this.__dispatcher.bus.on('_vm', key, fn); - return this; - } - /** - * remove event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'off', - value: function off(key, fn) { - return this.__dispatcher.bus.off('_vm', key, fn); - } - /** - * bind one time event handler - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'once', - value: function once(key, fn) { - return this.__dispatcher.bus.once('_vm', key, fn); - } - /** - * emit an event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: 'emit', - value: function emit(key) { - var _dispatcher$bus; - - if (!chimeeHelper.isString(key)) throw new TypeError('emit key parameter must be String'); - if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { - chimeeHelper.Log.warn('plugin', 'You are using emit to emit ' + key + ' event. As emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use emitSync'); - } - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return (_dispatcher$bus = this.__dispatcher.bus).emit.apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - } - /** - * emit a sync event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: 'emitSync', - value: function emitSync(key) { - var _dispatcher$bus2; - - if (!chimeeHelper.isString(key)) throw new TypeError('emitSync key parameter must be String'); - - for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - return (_dispatcher$bus2 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus2, [key].concat(_toConsumableArray(args))); - } - /** - * set style - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: 'css', - value: function css(method) { - var _dispatcher$dom; - - for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - // $FlowFixMe: we support this here - return (_dispatcher$dom = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom, args); - } - /** - * set attr - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue nameß - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: 'attr', - value: function attr(method) { - var _dispatcher$dom2; - - for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - if (method === 'set' && /video/.test(args[0])) { - if (!this.__dispatcher.videoConfigReady) { - chimeeHelper.Log.warn('plugin', 'You are tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); - return args[2]; - } - if (this.__dispatcher.videoConfig._realDomAttr.indexOf(args[1]) > -1) { - var key = args[1], - val = args[2]; - // $FlowFixMe: we have check the computed key - - this.__dispatcher.videoConfig[key] = val; - return val; - } - } - // $FlowFixMe: we support this here - return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom2, args); - } }, { key: '__throwError', value: function __throwError(error) { @@ -2682,7 +2895,7 @@ var Chimee = (_dec = toxicDecorators.autobindClass(), _dec2 = toxicDecorators.al }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'version', [toxicDecorators.frozen], { enumerable: true, initializer: function initializer() { - return '0.1.3'; + return '0.2.0'; } }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'config', [toxicDecorators.frozen], { enumerable: true, @@ -2733,6 +2946,6 @@ var Chimee = (_dec = toxicDecorators.autobindClass(), _dec2 = toxicDecorators.al initializer: function initializer() { return _init6; } -}), _class2), _applyDecoratedDescriptor(_class2.prototype, 'on', [_dec2, _dec3], _Object$getOwnPropertyDescriptor(_class2.prototype, 'on'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'off', [_dec4, _dec5], _Object$getOwnPropertyDescriptor(_class2.prototype, 'off'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'once', [_dec6], _Object$getOwnPropertyDescriptor(_class2.prototype, 'once'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'css', [_dec7], _Object$getOwnPropertyDescriptor(_class2.prototype, 'css'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'attr', [_dec8], _Object$getOwnPropertyDescriptor(_class2.prototype, 'attr'), _class2.prototype)), _class2)) || _class); +}), _class2)), _class2)) || _class); module.exports = Chimee; diff --git a/lib/index.min.js b/lib/index.min.js index 2c92c7dd..0dda636c 100644 --- a/lib/index.min.js +++ b/lib/index.min.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Chimee=t()}(this,function(){"use strict";function e(e){return e&&e.__esModule?e.default:e}function t(e,t){return t={exports:{}},e(t,t.exports),t.exports}function r(e){return void 0===e||null===e}function i(e){return Array.isArray(e)}function n(e){return"function"==typeof e}function a(e){return Object(e)===e&&"[object Object]"===String(e)&&!n(e)&&!i(e)}function o(e){return"number"==typeof e}function s(e){return Ai(e)}function u(e){return i(e)?0===e.length:a(e)?0===wi(e).length:!e}function l(e){return"string"==typeof e||e instanceof String}function f(e){return"boolean"==typeof e}function c(e){return!!e&&("object"===(void 0===e?"undefined":_i(e))||"function"==typeof e)&&"function"==typeof e.then}function d(e){return r(e)||f(e)||l(e)||o(e)}function h(e){return!!("object"===("undefined"==typeof Node?"undefined":_i(Node))?e instanceof Node:e&&"object"===(void 0===e?"undefined":_i(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}function p(e){return!!("object"===("undefined"==typeof HTMLElement?"undefined":_i(HTMLElement))?e instanceof HTMLElement:e&&"object"===(void 0===e?"undefined":_i(e))&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)}function g(e,t){if(!h(e)||!h(t))return!1;for(;t.parentNode;)if((t=t.parentNode)===e)return!0;return!1}function y(e){return/<[^>]+?>/.test(e)}function m(e){return e instanceof Error}function b(e,t){if(!l(e))throw new TypeError("Log's method only acccept string as argument");return l(t)?"["+(e=Ui.FORCE_GLOBAL_TAG?Ui.GLOBAL_TAG:e||Ui.GLOBAL_TAG)+"] > "+t:"["+Ui.GLOBAL_TAG+"] > "+e}function _(e){if(d(e))throw new TypeError("deepClone only accept non primitive type");return un(e)}function E(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length<2)throw new Error("deepAssign accept two and more argument");for(var i=t.length-1;i>-1;i--)if(d(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return un(e,n)}),n}function k(e,t){return e.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g,function(e,r,i,n){return t||0!==n?i.toUpperCase():i.toLowerCase()})}function w(e){return k(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}function S(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.apply(t,i)}:function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.call.apply(e,[t].concat(sn(i)))}}function T(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=n.throwError,o=void 0!==a&&a,s=n.backup;if(l(t)&&(t=t.split(".")),!i(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var u=[],f=e,c=0,d=t.length;c<d;c++){var h=t[c];if(r(f)){if(o)throw new Error("obj"+(u.length>0?"."+u.join("."):" itself")+" is "+f);return s}f=f[h],u.push(h)}return f}function A(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return wi(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])}function R(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return new Jn(function(t,i){!function a(o){if(!(o>=e.length)){var s=n(e[o])?e[o].apply(e,sn(r)):e[o];return!1===s?i("stop"):Jn.resolve(s).then(function(){return a(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})}function L(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return function t(i){return i>=e.length||!1!==(n(e[i])?e[i].apply(e,sn(r)):e[i])&&t(++i)}(0)}function O(e,t,r,i){var n=void 0,a=void 0,o=void 0,s=null,u=0;r||(r={});var l=function(){u=!1===r.leading?0:new Date-0,s=null,o=e.apply(n,a),s||(n=a=null)};return t=t||0,function(){var f=new Date;u||!1!==r.leading||(u=f);var c=t-(f-u);return n=i||this,a=arguments,c<=0||c>t?(s&&(clearTimeout(s),s=null),u=f,o=e.apply(n,a),s||(n=a=null)):s||!1===r.trailing||(s=setTimeout(l,c)),o}}function D(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++ua.count);var i=r+"_"+t,n=ua[i];return n||(n=ua[i]=[]),n}function P(e,t,r){var i=sa(null);i.type=t,i.target=e,r&&ia(i,a(r)?r:{data:r}),D(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function x(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments[4];n(i)&&!a&&(a=i,i=void 0);var o=[r,void 0,i];i&&!a&&(a=function(){I(e,t,r,i);for(var n=arguments.length,a=Array(n),o=0;o<n;o++)a[o]=arguments[o];r.apply(e,a)}),a&&(o[1]=a),D(e,t).push(o)}function I(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=D(e,t);if(r||i){var a=-1,o=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return a=t,o=e[1],!0}),-1!==a&&n.splice(a,1),o}n.length=0}function C(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++fa.count);var i=r+"_"+t,n=fa[i];return n||(n=fa[i]=[]),n}function M(e,t,r){var i=sa(null);i.type=t,i.target=e,r&&ia(i,a(r)?r:{data:r}),C(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function F(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments[4];n(i)&&!a&&(a=i,i=void 0);var o=[r,void 0,i];i&&!a&&(a=function(){N(e,t,r,i);for(var n=arguments.length,a=Array(n),o=0;o<n;o++)a[o]=arguments[o];r.apply(e,a)}),a&&(o[1]=a),C(e,t).push(o)}function N(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=C(e,t);if(r||i){var a=-1,o=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return a=t,o=e[1],!0}),-1!==a&&n.splice(a,1),o}n.length=0}function U(e){return on(e)}function B(e,t){return e.getAttribute(t)}function G(e,t,r){void 0===r?e.removeAttribute(t):e.setAttribute(t,r)}function j(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.add(t)});else{var i=" "+(e.className||"")+" ";r.forEach(function(e){-1===i.indexOf(" "+e+" ")&&(i+=" "+e)}),e.className=i.trim()}}}function H(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.remove(t)});else{var i=" "+e.className+" ";r.forEach(function(e){for(var t=" "+e+" ";-1!==i.indexOf(t);)i=i.replace(t," ")}),e.className=i.trim()}}}function z(e,t){return new RegExp("(?:^|\\s)"+t+"(?=\\s|$)").test(e.className)}function V(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(i){var a=N(e,t+"_once",r);a&&(r=a)}e.removeEventListener(t,r,n)}function W(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(i){var a=r;F(e,t+"_once",a,r=function(){for(var o=arguments.length,s=Array(o),u=0;u<o;u++)s[u]=arguments[u];a.apply(this,s),V(e,t,r,i,n)})}e.addEventListener(t,r,n)}function K(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=function(r){var n=Z(r.srcElement,e,!0),a=X(t,e,!0).find(function(e){return n.find(function(t){return e===t})});a&&i.apply(a,arguments)};F(e,r+"_delegate_"+t,i,a),e.addEventListener(r,a,n)}function q(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=N(e,r+"_delegate_"+t,i);a&&e.removeEventListener(r,a,n)}function Y(e,t){return(e.currentStyle||document.defaultView.getComputedStyle(e,null))[t]||e.style[t]}function $(e,t,r){if(a(t))for(var i in t)$(e,i,t[i]);else e.style[t]=r}function X(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document,r=arguments[2],i=t.querySelectorAll(e);return r?on(i):i}function Q(e){e.parentNode.removeChild(e)}function Z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments[2],i=arguments[3],n=[];for(r&&n.push(e);e&&e.parentNode!==t;)(e=e.parentNode)&&n.push(e);return i&&n.push(t),n}function J(e,t){return e.constructor===va?e:new va(e,t)}function ee(e){for(var t=[],r=e,i=0,n=e.length;i<n;)if(r[i]<128)t.push(String.fromCharCode(r[i])),++i;else{if(r[i]<192);else if(r[i]<224){if(te(r,i,1)){var a=(31&r[i])<<6|63&r[i+1];if(a>=128){t.push(String.fromCharCode(65535&a)),i+=2;continue}}}else if(r[i]<240){if(te(r,i,2)){var o=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(o>=2048&&55296!=(63488&o)){t.push(String.fromCharCode(65535&o)),i+=3;continue}}}else if(r[i]<248&&te(r,i,3)){var s=(7&r[i])<<18|(63&r[i+1])<<12|(63&r[i+2])<<6|63&r[i+3];if(s>65536&&s<1114112){s-=65536,t.push(String.fromCharCode(s>>>10|55296)),t.push(String.fromCharCode(1023&s|56320)),i+=4;continue}}t.push(String.fromCharCode(65533)),++i}return t.join("")}function te(e,t,r){var i=e;if(t+r<i.length){for(;r--;)if(128!=(192&i[++t]))return!1;return!0}return!1}function re(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function ie(e){if(!e||!e.hasOwnProperty)return!1;for(var t=["value","initializer","get","set"],r=0,i=t.length;r<i;r++)if(e.hasOwnProperty(t[r]))return!0;return!1}function ne(e){return!!e&&(n(e.get)||n(e.set))&&f(e.configurable)&&f(e.enumerable)&&void 0===e.writable}function ae(e){return!!e&&e.hasOwnProperty("value")&&f(e.configurable)&&f(e.enumerable)&&f(e.writable)}function oe(e){return!!e&&n(e.initializer)&&f(e.configurable)&&f(e.enumerable)&&f(e.writable)}function se(e){return function(t){return yt(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t}),t}}function ue(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"You must pass me an array of function";if(!i(e)||e.length<1)throw new TypeError(t);if(1===e.length){if(!n(e[0]))throw new TypeError(t);return e[0]}return e.reduce(function(e,r){if(!n(r)||!n(e))throw new TypeError(t);return function(t){return S(r,this)(S(e,this)(t))}})}function le(){var e,t;if(n(console.warn))return(e=console).warn.apply(e,arguments);(t=console).log.apply(t,arguments)}function fe(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.forEach(function(e){if(!n(t[0]))throw new TypeError("compressMultipleDecorators only accept function")}),1===t.length?t[0]:function(e,r,i){return t.reduce(function(t,i){return i(e,r,t)},i)}}function ce(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.get,r=e.set,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=a.preGet,s=void 0!==o&&o,u=a.preSet,l=void 0===u||u;if(!(n(t)||n(r)||i(t)&&t.length>0||i(r)&&r.length>0))throw new TypeError("@accessor need a getter or setter. If you don't need to add setter/getter. You should remove @accessor");var f="@accessor only accept function or array of function as getter/setter";return t=i(t)?ue(t,f):t,r=i(r)?ue(r,f):r,function(e,i,a){var o=a||{},u=o.configurable,f=void 0===u||u,c=o.enumerable,d=void 0===c||c,h=n(t),v=n(r),p=function(e){return h?S(t,this)(e):e},g=function(e){return v?S(r,this)(e):e};if(ne(a)){var y=a.get,m=a.set,b=n(y),_=n(m);return!b&&h&&le("You are trying to set getter via @accessor on "+i+" without getter. That's not a good idea."),!_&&v&&le("You are trying to set setter via @accessor on "+i+" without setter. That's not a good idea."),{get:b||h?function(){var e=this,t=S(p,this),r=function(){return b?S(y,e)():void 0};return(s?[t,r]:[r,t]).reduce(function(e,t){return t(e)},void 0)}:void 0,set:_||v?function(e){var t=this,r=S(g,this),i=function(e){return _?S(m,t)(e):e};return(l?[r,i]:[i,r]).reduce(function(e,t){return t(e)},e)}:void 0,configurable:f,enumerable:d}}if(oe(a)){var E=a.initializer,k=void 0,w=!1;return{get:function(){var e=S(p,this);return w?e(k):(k=S(E,this)(),w=!0,e(k))},set:function(e){var t=S(g,this);return k=l?t(e):e,w=!0,l||t(k),k},configurable:f,enumerable:d}}var T=(a||{}).value;return{get:function(){return S(p,this)(T)},set:function(e){var t=S(g,this);return T=l?t(e):e,l||t(T),T},configurable:f,enumerable:d}}}function de(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@before accept at least one parameter. If you don't need to preprocess before your function, do not add @before decorators");if(t.length>2&&ie(t[2]))throw new Error("You may use @before straightly, @before return decorators, you need to call it");for(var a=t.length-1;a>-1;a--)if(!n(t[a]))throw new TypeError("@before only accept function parameter");return function(e,r,a){if(void 0===a)throw new Error("@before must used on descriptor, are you using it on undefined property?");var o=a.value,s=a.configurable,u=a.enumerable,l=a.writable;if(!n(o))throw new TypeError("@before can only be used on function");return{value:function(){for(var e=this,r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];var s=t.reduce(function(t,r){var n=S(r,e).apply(void 0,sn(t));return void 0===n?t:i(n)?n:[n]},n);return S(o,this).apply(void 0,sn(s))},configurable:s,enumerable:u,writable:l}}}function he(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@initialize accept at least one parameter. If you don't need to initialize your value, do not add @initialize.");if(t.length>2&&ie(t[2]))throw new Error("You may use @initialize straightly, @initialize return decorators, you need to call it");var i=ue(t,"@initialize only accept function parameter");return function(e,t,r){if(void 0===r)return{value:S(i,e)(),configurable:!0,writable:!0,enumerable:!0};if(ne(r)){var n=!1;return ce({get:function(e){return n?e:S(i,this)(e)},set:r.set?function(e){return n=!0,e}:void 0})(e,t,r)}if(oe(r)){var a=r.initializer;return{initializer:function(){return S(i,this)(S(a,this)())},configurable:r.configurable,writable:r.writable,enumerable:r.enumerable}}return{value:S(i,this)(r.value),writable:r.writable,configurable:r.configurable,enumerable:r.enumerable}}}function ve(e,t,r,i,n,a){var o=r.configurable,s=r.enumerable,u=a.force,l=a.omit,f=vu(i,n);if(void 0!==f){if(l)return;if(!u)throw new Error("@alias can't set alias on an existing attribute");if(!f.configurable)throw new Error("You are tring to set alias on an existing attribute which its configurable is false. That's impossible. Please check if you have set @frozen on it.")}pu(i,n,{get:function(){return e[t]},set:function(r){return e[t]=r,t},configurable:o,enumerable:s})}function pe(e,t,r){if(2===arguments.length?l(e)&&(r=t,t=e,e=void 0):1===arguments.length&&(t=e,e=void 0),!l(t))throw new TypeError("@alias need a string as a key to find the porperty to set alias on");var i="If you want to use @alias to set alias on other instance, you must pass in a legal instance";if(void 0!==e&&d(e))throw new TypeError(i);var n=a(r)?r:{force:!1,omit:!1},o=n.force,s=n.omit;return function(r,n,a){function u(e,t,r){var n=d(e)?t:e,a=r.split("."),o=a.slice(-1),s=Ho(o,1)[0];if(n=T(n,a.slice(0,-1),{throwError:!0}),d(n))throw new TypeError(i);return{target:n,name:s}}if(a=a||{value:void 0,configurable:!0,writable:!0,enumerable:!0},oe(a))return he(function(r){var i=u(e,this,t),l=i.target,f=i.name;return ve(this,n,a,l,f,{force:o,omit:s}),r})(r,n,a);if(ne(a)){var l=void 0,f=function(r){if(l)return r;var i=u(e,this,t),f=i.target,c=i.name;return ve(this,n,a,f,c,{force:o,omit:s}),l=!0,r};return ce({get:f,set:f})(r,n,a)}var c=u(e,r,t),h=c.target,v=c.name;return ve(r,n,a,h,v,{force:o,omit:s}),a}}function ge(e,t){if(void 0===as)throw new Error("Using @autobind on "+t.name+"() requires WeakMap support due to its use of super."+t.name+"()");mu||(mu=new as),!1===mu.has(e)&&mu.set(e,new as);var r=mu.get(e);return!1===r.has(t)&&r.set(t,S(t,e)),r.get(t)}function ye(e,t,r){if(1===arguments.length)return yu()(e);if(!ie(r))throw new Error("@autobind must used on descriptor, are you using it on undefined property?");var i=r.value,a=r.configurable;if(!n(i))throw new TypeError("@autobind can only be used on functions, not: "+i+")");var o=e.constructor;return{configurable:a,enumerable:!1,get:function(){var r=this,n=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return i.call.apply(i,[r].concat(sn(t)))};return this===e?i:this.constructor!==o&&ga(this).constructor===o?i:this.constructor!==o&&t in this.constructor.prototype?ge(this,i):(yt(this,t,{configurable:!0,writable:!0,enumerable:!1,value:n}),n)},set:se(t)}}function me(e,t,r){if(void 0===r)return le("You are using @frozen on an undefined property. This property will become a frozen undefined forever, which is meaningless"),{value:void 0,writable:!1,enumerable:!1,configurable:!1};if(r.enumerable=!1,r.configurable=!1,ne(r)){var i=r.get;return r.set=void 0,n(i)?{get:function(){var e=S(i,this)();return bu(this,t,{value:e,writable:!1,configurable:!1,enumerable:!1}),e},set:void 0,configurable:!1,enumerable:!1}:void le("You are using @frozen on one accessor descriptor without getter. This property will become a frozen undefined finally.Which maybe meaningless.")}return r.writable=!1,r}function be(e,t,r){if(void 0===r)return le("You are using @lock on an undefined property. This property will become a lock undefined forever, which is meaningless"),{value:void 0,writable:!1,enumerable:!0,configurable:!1};if(r.configurable=!1,ne(r)){var i=r.get;return r.set=void 0,n(i)?{get:function(){var e=S(i,this)();return ku(this,t,{value:e,writable:!1,configurable:!1,enumerable:r.enumerable}),e},set:void 0,configurable:!1,enumerable:r.enumerable}:void le("You are using @lock on one accessor descriptor without getter. This property will become a lock undefined finally.Which maybe meaningless.")}return r.writable=!1,r}function _e(e,t,r){return void 0===r?{value:void 0,enumerable:!1,configurable:!0,writable:!0}:(r.enumerable=!1,r)}function Ee(e,t){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=o.self,u=void 0!==s&&s,l=o.omit,f=void 0!==l&&l,c=n(t);if(c||i(t)){if(!n(e))throw new TypeError("If you want to decorator class, you must pass it a legal class");if(c)t(e);else for(var h=0,v=t.length;h<v;h++){var p=t[h];if(!n(p))throw new TypeError("If you want to decorate an class, you must pass it function or array of function");p(e)}return e}if(!u&&!n(e))throw new TypeError("applyDecorators only accept class as first arguments. If you want to modify instance, you should set options.self true.");if(u&&d(e))throw new TypeError("We can't apply docorators on a primitive value, even in self mode");if(!a(t))throw new TypeError("applyDecorators only accept object as second arguments");var g=u?e:e.prototype;if(r(g))throw new Error("The class muse have a prototype, please take a check");for(var y in t){var m=t[y],b=i(m)?m:[m],_=void 0;try{_=fe.apply(void 0,sn(b))}catch(e){throw le(e&&e.message),new Error("The decorators set on props must be Function or Array of Function")}var E=Su(g,y);if(!E||E.configurable)wu(g,y,_(g,y,E));else if(!f)throw new Error(y+" of "+g+" is unconfigurable")}return e}function ke(e,t,r){var n,o=r.diff,s=r.operationPrefix,u={},l=!1,f=new Proxy(e,{get:function(e,r,n){var f=e[r];if(i(e)&&Tu.indexOf(r)>-1)return function(){l=!0,S(f,n).apply(void 0,arguments),l=!1,t()};if(!0===u[r])return f;if(a(f)||i(f)){var c=u[r]||ke(f,t,{diff:o,operationPrefix:s});return u[r]=c,c}return u[r]=!0,f},set:function(e,r,n){var f=e[r],c=a(n)||i(n)?ke(n,t,{diff:o,operationPrefix:s}):n;return e[r]=c,u[r]=!0,!!(l||o&&f===c)||(t(),!0)},deleteProperty:function(e,r){return delete e[r],delete u[r],!!l||(t(),!0)}}),c=(n={},os(n,s+"set",[he(function(e){return function(e,t){f[e]=t}}),_e]),os(n,s+"del",[he(function(e){return function(e){delete f[e]}}),_e]),n);return Ee(f,c,{self:!0}),f}function we(e,t,r){function o(e){var r=void 0;return e.reduce(function(e,n){return e[n]=[ce({set:function(e){return r=this[n],e}}),ce({get:function(e){return c[n]?e:((a(e)||i(e))&&we(e,t,{operationPrefix:l,diff:f}),c[n]=!0,e)},set:function(e){return(a(e)||i(e))&&we(e,t,{operationPrefix:l,diff:f}),c[n]=!0,d||f&&r===e||t(),e}},{preSet:!1})],e},{})}var s,u=this,l=r.operationPrefix,f=r.diff,c={},d=!1,h=o(du(e));if(Ee(e,h,{self:!0,omit:!0}),i(e)){var v=Tu.reduce(function(r,i){return r[i]=[he(function(r){return r=n(r)?r:Array.prototype[i],function(){var i=e.length;if(d=!0,S(r,e).apply(void 0,arguments),d=!1,i<e.length){var n=o(new Array(e.length-i).fill(1).map(function(e,t){return(t+i).toString()}));Ee(e,n,{self:!0,omit:!0})}t()}}),_e],r},{});Ee(e,v,{self:!0})}var p=(s={},os(s,l+"set",[he(function(t){return function(r,i){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=a.disable,l=a.isNewVal;if(l=l||-1===du(e).indexOf(r),n(t)&&S(t,u)(r,i,{disable:!0,isNewVal:l}),l){var f=o([r]);Ee(e,f,{self:!0,omit:!0})}s||(e[r]=i)}}),_e]),os(s,l+"del",[he(function(r){return function(i){if(-1===du(e).indexOf(i)){var a=o([i]);Ee(e,a,{self:!0,omit:!0})}n(r)?S(r,u)(i):delete e[i],t()}}),_e]),s);return Ee(e,p,{self:!0}),e}function Se(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var o=a(t[t.length-1])?t[t.length-1]:{},s=o.deep,u=o.omit,f=o.other,c=o.operationPrefix,h=void 0===c?"__":c,v=o.diff,p=void 0===v||v,g=o.proxy;if(Proxy||(g=!1,le("You browser do not support Proxy, we will change back into observe mode.")),!t.length)throw new TypeError("You must pass a function or a string to find the hanlder function.");if(void 0!==f&&d(f))throw new TypeError("If you want us to trigger function on the other instance, you must pass in a legal instance");if(!l(h))throw new TypeError("operationPrefix must be an string");return function(e,r,o){var c=t.reduce(function(r,i,a){if(!l(i)&&!n(i)){if(!a||a!==t.length-1)throw new TypeError("You can only pass function or string as handler");return r}return r.push(l(i)?function(t,r){var a=T(f||e,i);if(n(a))return S(a,this)(t,r);if(!u)throw new Error("You pass in a function for us to trigger, please ensure the property to be a function or set omit flag true")}:i),r},[]),d=function(e,t){var r=this;c.forEach(function(i){return S(i,r)(e,t)})},v=!1,y=void 0,m=void 0,b=void 0;return fe(ce({set:function(e){var t=this;y=this[r],b=void 0;var n=function(){return S(d,t)(m,y)};return s&&(a(e)||i(e))?g?ke(e,n,{diff:p,operationPrefix:h}):we(e,n,{operationPrefix:h,diff:p}):e},get:function(e){var t=this;if(b)return b;if(!v){v=!0;var r=function(){return S(d,t)(m,y)};if(s&&(a(e)||i(e))){if(g)return b=ke(e,r,{diff:p,operationPrefix:h}),y=b,m=b,b;we(e,r,{operationPrefix:h,diff:p})}y=e,m=e}return e}},{preSet:!0}),ce({set:function(e){return m=e,p&&y===e||S(d,this)(m,y),y=e,e}},{preSet:!1}))(e,r,o)}}function Te(e,t,r){if(void 0===r)throw new Error("@nonextendable could not handle undefined");return he(function(e){return Au(e),e})(e,t,r)}function Ae(e,t,r){return void 0===r?{value:void 0,enumerable:!0,configurable:!0,writable:!0}:(r.configurable=!0,r)}function Re(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=l(t[0])?t.shift():"";return t.unshift(function(e){return l(e)?e:i}),he.apply(void 0,t)}function Le(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=!!f(t[0])&&t.shift();return t.unshift(function(e){return f(e)?e:i}),ce({set:t,get:t})}function Oe(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=o(t[0])?t.shift():0;return t.unshift(function(e){return o(e)?e:i}),ce({set:t,get:t})}function De(e,t){if(!l(e))throw new TypeError("key parameter must be String");if(!n(t))throw new TypeError("fn parameter must be Function")}function Pe(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.length>2?["set"].concat(t):2===t.length?["video","container","wrapper","videoElement"].indexOf(t[0])>-1?["get"].concat(t):["set","container"].concat(t):["get","container"].concat(t)}function xe(e,t,r,i,n){var a={};return Object.keys(i).forEach(function(e){a[e]=i[e]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}function Ie(e,t,r,i,n){var a={};return Object.keys(i).forEach(function(e){a[e]=i[e]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}function Ce(e){if("video"===e&&(e="videoElement"),!p(this[e]))throw new TypeError("Your target "+e+" is not a legal HTMLElement");for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return[e].concat(r)}function Me(e,t,r){if(!l(t))throw new TypeError("to handle dom's attribute or style, your attr parameter must be string");if(!l(e))throw new TypeError("to handle dom's attribute or style, your target parameter must be string");return[e,t,r]}function Fe(e,t,r,i){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(i):void 0})}function Ne(e,t,r,i,n){var a={};return Object.keys(i).forEach(function(e){a[e]=i[e]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}function Ue(e){return o(e)?e:void 0}function Be(e){return l(e)?e:void 0}function Ge(e){return ce({get:function(t){return this.dispatcher.videoConfigReady&&this.inited?this.videoElement[e]:t},set:function(t){return this.dispatcher.videoConfigReady?(this.videoElement[e]=t,t):t}})}function je(e){var t=a(e)?e:{set:e,get:e,isBoolean:!1},r=t.set,i=t.get,n=t.isBoolean;return ce({get:function(e){return this.dispatcher.videoConfigReady&&this.inited?this.videoElement[i]:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;var t=n?e?"":void 0:e;return this.dispatcher.dom.setAttr("video",r,t),e}})}function He(e,t){return ce({get:function(r){var i=this.dispatcher.dom.getAttr("video",e);return this.dispatcher.videoConfigReady&&this.inited?t?!!i:i:r},set:function(r){if(!this.dispatcher.videoConfigReady)return r;var i=t?r||void 0:r;return this.dispatcher.dom.setAttr("video",e,i),r}})}function ze(e,t,r,i,n){var a={};return Object.keys(i).forEach(function(e){a[e]=i[e]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}function Ve(e){if(!l(e))throw new Error("Plugin's name must be a string");return k(e)}function We(e,t,r,i){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(i):void 0})}function Ke(e,t,r,i){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(i):void 0})}function qe(e,t,r,i,n){var a={};return Object.keys(i).forEach(function(e){a[e]=i[e]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}var Ye=e(t(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}})),$e=t(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),Xe=t(function(e){var t=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=t)}),Qe=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},Ze=function(e,t,r){if(Qe(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},Je=function(e){return"object"==typeof e?null!==e:"function"==typeof e},et=function(e){if(!Je(e))throw TypeError(e+" is not an object!");return e},tt=function(e){try{return!!e()}catch(e){return!0}},rt=!tt(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),it=$e.document,nt=Je(it)&&Je(it.createElement),at=function(e){return nt?it.createElement(e):{}},ot=!rt&&!tt(function(){return 7!=Object.defineProperty(at("div"),"a",{get:function(){return 7}}).a}),st=function(e,t){if(!Je(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!Je(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!Je(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!Je(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},ut=Object.defineProperty,lt={f:rt?Object.defineProperty:function(e,t,r){if(et(e),t=st(t,!0),et(r),ot)try{return ut(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},ft=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},ct=rt?function(e,t,r){return lt.f(e,t,ft(1,r))}:function(e,t,r){return e[t]=r,e},dt=function(e,t,r){var i,n,a,o=e&dt.F,s=e&dt.G,u=e&dt.S,l=e&dt.P,f=e&dt.B,c=e&dt.W,d=s?Xe:Xe[t]||(Xe[t]={}),h=d.prototype,v=s?$e:u?$e[t]:($e[t]||{}).prototype;s&&(r=t);for(i in r)(n=!o&&v&&void 0!==v[i])&&i in d||(a=n?v[i]:r[i],d[i]=s&&"function"!=typeof v[i]?r[i]:f&&n?Ze(a,$e):c&&v[i]==a?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(a):l&&"function"==typeof a?Ze(Function.call,a):a,l&&((d.virtual||(d.virtual={}))[i]=a,e&dt.R&&h&&!h[i]&&ct(h,i,a)))};dt.F=1,dt.G=2,dt.S=4,dt.P=8,dt.B=16,dt.W=32,dt.U=64,dt.R=128;var ht=dt;ht(ht.S+ht.F*!rt,"Object",{defineProperty:lt.f});var vt=Xe.Object,pt=function(e,t,r){return vt.defineProperty(e,t,r)},gt=t(function(e){e.exports={default:pt,__esModule:!0}}),yt=e(gt),mt=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(gt);t.default=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,r.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),bt=Math.ceil,_t=Math.floor,Et=function(e){return isNaN(e=+e)?0:(e>0?_t:bt)(e)},kt=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},wt=ct,St={}.hasOwnProperty,Tt=function(e,t){return St.call(e,t)},At={},Rt={}.toString,Lt=function(e){return Rt.call(e).slice(8,-1)},Ot=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==Lt(e)?e.split(""):Object(e)},Dt=function(e){return Ot(kt(e))},Pt=Math.min,xt=function(e){return e>0?Pt(Et(e),9007199254740991):0},It=Math.max,Ct=Math.min,Mt=function(e,t){return(e=Et(e))<0?It(e+t,0):Ct(e,t)},Ft=$e["__core-js_shared__"]||($e["__core-js_shared__"]={}),Nt=function(e){return Ft[e]||(Ft[e]={})},Ut=0,Bt=Math.random(),Gt=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++Ut+Bt).toString(36))},jt=Nt("keys"),Ht=function(e){return jt[e]||(jt[e]=Gt(e))},zt=function(e){return function(t,r,i){var n,a=Dt(t),o=xt(a.length),s=Mt(i,o);if(e&&r!=r){for(;o>s;)if((n=a[s++])!=n)return!0}else for(;o>s;s++)if((e||s in a)&&a[s]===r)return e||s||0;return!e&&-1}}(!1),Vt=Ht("IE_PROTO"),Wt=function(e,t){var r,i=Dt(e),n=0,a=[];for(r in i)r!=Vt&&Tt(i,r)&&a.push(r);for(;t.length>n;)Tt(i,r=t[n++])&&(~zt(a,r)||a.push(r));return a},Kt="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),qt=Object.keys||function(e){return Wt(e,Kt)},Yt=rt?Object.defineProperties:function(e,t){et(e);for(var r,i=qt(t),n=i.length,a=0;n>a;)lt.f(e,r=i[a++],t[r]);return e},$t=$e.document&&document.documentElement,Xt=Ht("IE_PROTO"),Qt=function(){},Zt=function(){var e,t=at("iframe"),r=Kt.length;for(t.style.display="none",$t.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),Zt=e.F;r--;)delete Zt.prototype[Kt[r]];return Zt()},Jt=Object.create||function(e,t){var r;return null!==e?(Qt.prototype=et(e),r=new Qt,Qt.prototype=null,r[Xt]=e):r=Zt(),void 0===t?r:Yt(r,t)},er=t(function(e){var t=Nt("wks"),r=$e.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:Gt)("Symbol."+e))}).store=t}),tr=lt.f,rr=er("toStringTag"),ir=function(e,t,r){e&&!Tt(e=r?e:e.prototype,rr)&&tr(e,rr,{configurable:!0,value:t})},nr={};ct(nr,er("iterator"),function(){return this});var ar=function(e,t,r){e.prototype=Jt(nr,{next:ft(1,r)}),ir(e,t+" Iterator")},or=function(e){return Object(kt(e))},sr=Ht("IE_PROTO"),ur=Object.prototype,lr=Object.getPrototypeOf||function(e){return e=or(e),Tt(e,sr)?e[sr]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ur:null},fr=er("iterator"),cr=!([].keys&&"next"in[].keys()),dr=function(){return this},hr=function(e,t,r,i,n,a,o){ar(r,t,i);var s,u,l,f=function(e){if(!cr&&e in v)return v[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},c=t+" Iterator",d="values"==n,h=!1,v=e.prototype,p=v[fr]||v["@@iterator"]||n&&v[n],g=p||f(n),y=n?d?f("entries"):g:void 0,m="Array"==t?v.entries||p:p;if(m&&(l=lr(m.call(new e)))!==Object.prototype&&ir(l,c,!0),d&&p&&"values"!==p.name&&(h=!0,g=function(){return p.call(this)}),o&&(cr||h||!v[fr])&&ct(v,fr,g),At[t]=g,At[c]=dr,n)if(s={values:d?g:f("values"),keys:a?g:f("keys"),entries:y},o)for(u in s)u in v||wt(v,u,s[u]);else ht(ht.P+ht.F*(cr||h),t,s);return s},vr=function(e){return function(t,r){var i,n,a=String(kt(t)),o=Et(r),s=a.length;return o<0||o>=s?e?"":void 0:(i=a.charCodeAt(o))<55296||i>56319||o+1===s||(n=a.charCodeAt(o+1))<56320||n>57343?e?a.charAt(o):i:e?a.slice(o,o+2):n-56320+(i-55296<<10)+65536}}(!0);hr(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=vr(t,r),this._i+=e.length,{value:e,done:!1})});var pr=function(){},gr=function(e,t){return{value:t,done:!!e}};hr(Array,"Array",function(e,t){this._t=Dt(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,gr(1)):"keys"==t?gr(0,r):"values"==t?gr(0,e[r]):gr(0,[r,e[r]])},"values");At.Arguments=At.Array,pr(),pr(),pr();for(var yr=er("toStringTag"),mr=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],br=0;br<5;br++){var _r=mr[br],Er=$e[_r],kr=Er&&Er.prototype;kr&&!kr[yr]&&ct(kr,yr,_r),At[_r]=At.Array}var wr={f:er},Sr=wr.f("iterator"),Tr=t(function(e){e.exports={default:Sr,__esModule:!0}}),Ar=t(function(e){var t=Gt("meta"),r=lt.f,i=0,n=Object.isExtensible||function(){return!0},a=!tt(function(){return n(Object.preventExtensions({}))}),o=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!Je(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!Tt(e,t)){if(!n(e))return"F";if(!r)return"E";o(e)}return e[t].i},getWeak:function(e,r){if(!Tt(e,t)){if(!n(e))return!0;if(!r)return!1;o(e)}return e[t].w},onFreeze:function(e){return a&&s.NEED&&n(e)&&!Tt(e,t)&&o(e),e}}}),Rr=lt.f,Lr=function(e){var t=Xe.Symbol||(Xe.Symbol={});"_"==e.charAt(0)||e in t||Rr(t,e,{value:wr.f(e)})},Or=function(e,t){for(var r,i=Dt(e),n=qt(i),a=n.length,o=0;a>o;)if(i[r=n[o++]]===t)return r},Dr={f:Object.getOwnPropertySymbols},Pr={f:{}.propertyIsEnumerable},xr=function(e){var t=qt(e),r=Dr.f;if(r)for(var i,n=r(e),a=Pr.f,o=0;n.length>o;)a.call(e,i=n[o++])&&t.push(i);return t},Ir=Array.isArray||function(e){return"Array"==Lt(e)},Cr=Kt.concat("length","prototype"),Mr={f:Object.getOwnPropertyNames||function(e){return Wt(e,Cr)}},Fr=Mr.f,Nr={}.toString,Ur="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Br=function(e){try{return Fr(e)}catch(e){return Ur.slice()}},Gr={f:function(e){return Ur&&"[object Window]"==Nr.call(e)?Br(e):Fr(Dt(e))}},jr=Object.getOwnPropertyDescriptor,Hr={f:rt?jr:function(e,t){if(e=Dt(e),t=st(t,!0),ot)try{return jr(e,t)}catch(e){}if(Tt(e,t))return ft(!Pr.f.call(e,t),e[t])}},zr=Ar.KEY,Vr=Hr.f,Wr=lt.f,Kr=Gr.f,qr=$e.Symbol,Yr=$e.JSON,$r=Yr&&Yr.stringify,Xr=er("_hidden"),Qr=er("toPrimitive"),Zr={}.propertyIsEnumerable,Jr=Nt("symbol-registry"),ei=Nt("symbols"),ti=Nt("op-symbols"),ri=Object.prototype,ii="function"==typeof qr,ni=$e.QObject,ai=!ni||!ni.prototype||!ni.prototype.findChild,oi=rt&&tt(function(){return 7!=Jt(Wr({},"a",{get:function(){return Wr(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=Vr(ri,t);i&&delete ri[t],Wr(e,t,r),i&&e!==ri&&Wr(ri,t,i)}:Wr,si=function(e){var t=ei[e]=Jt(qr.prototype);return t._k=e,t},ui=ii&&"symbol"==typeof qr.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof qr},li=function(e,t,r){return e===ri&&li(ti,t,r),et(e),t=st(t,!0),et(r),Tt(ei,t)?(r.enumerable?(Tt(e,Xr)&&e[Xr][t]&&(e[Xr][t]=!1),r=Jt(r,{enumerable:ft(0,!1)})):(Tt(e,Xr)||Wr(e,Xr,ft(1,{})),e[Xr][t]=!0),oi(e,t,r)):Wr(e,t,r)},fi=function(e,t){et(e);for(var r,i=xr(t=Dt(t)),n=0,a=i.length;a>n;)li(e,r=i[n++],t[r]);return e},ci=function(e){var t=Zr.call(this,e=st(e,!0));return!(this===ri&&Tt(ei,e)&&!Tt(ti,e))&&(!(t||!Tt(this,e)||!Tt(ei,e)||Tt(this,Xr)&&this[Xr][e])||t)},di=function(e,t){if(e=Dt(e),t=st(t,!0),e!==ri||!Tt(ei,t)||Tt(ti,t)){var r=Vr(e,t);return!r||!Tt(ei,t)||Tt(e,Xr)&&e[Xr][t]||(r.enumerable=!0),r}},hi=function(e){for(var t,r=Kr(Dt(e)),i=[],n=0;r.length>n;)Tt(ei,t=r[n++])||t==Xr||t==zr||i.push(t);return i},vi=function(e){for(var t,r=e===ri,i=Kr(r?ti:Dt(e)),n=[],a=0;i.length>a;)!Tt(ei,t=i[a++])||r&&!Tt(ri,t)||n.push(ei[t]);return n};ii||(wt((qr=function(){if(this instanceof qr)throw TypeError("Symbol is not a constructor!");var e=Gt(arguments.length>0?arguments[0]:void 0),t=function(r){this===ri&&t.call(ti,r),Tt(this,Xr)&&Tt(this[Xr],e)&&(this[Xr][e]=!1),oi(this,e,ft(1,r))};return rt&&ai&&oi(ri,e,{configurable:!0,set:t}),si(e)}).prototype,"toString",function(){return this._k}),Hr.f=di,lt.f=li,Mr.f=Gr.f=hi,Pr.f=ci,Dr.f=vi,wr.f=function(e){return si(er(e))}),ht(ht.G+ht.W+ht.F*!ii,{Symbol:qr});for(var pi="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),gi=0;pi.length>gi;)er(pi[gi++]);for(var pi=qt(er.store),gi=0;pi.length>gi;)Lr(pi[gi++]);ht(ht.S+ht.F*!ii,"Symbol",{for:function(e){return Tt(Jr,e+="")?Jr[e]:Jr[e]=qr(e)},keyFor:function(e){if(ui(e))return Or(Jr,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){ai=!0},useSimple:function(){ai=!1}}),ht(ht.S+ht.F*!ii,"Object",{create:function(e,t){return void 0===t?Jt(e):fi(Jt(e),t)},defineProperty:li,defineProperties:fi,getOwnPropertyDescriptor:di,getOwnPropertyNames:hi,getOwnPropertySymbols:vi}),Yr&&ht(ht.S+ht.F*(!ii||tt(function(){var e=qr();return"[null]"!=$r([e])||"{}"!=$r({a:e})||"{}"!=$r(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!ui(e)){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);return"function"==typeof(t=i[1])&&(r=t),!r&&Ir(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!ui(t))return t}),i[1]=t,$r.apply(Yr,i)}}}),qr.prototype[Qr]||ct(qr.prototype,Qr,qr.prototype.valueOf),ir(qr,"Symbol"),ir(Math,"Math",!0),ir($e.JSON,"JSON",!0),Lr("asyncIterator"),Lr("observable");var yi=Xe.Symbol,mi=t(function(e){e.exports={default:yi,__esModule:!0}}),bi=t(function(e,t){function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=r(Tr),n=r(mi),a="function"==typeof n.default&&"symbol"==typeof i.default?function(e){return typeof e}:function(e){return e&&"function"==typeof n.default&&e.constructor===n.default&&e!==n.default.prototype?"symbol":typeof e};t.default="function"==typeof n.default&&"symbol"===a(i.default)?function(e){return void 0===e?"undefined":a(e)}:function(e){return e&&"function"==typeof n.default&&e.constructor===n.default&&e!==n.default.prototype?"symbol":void 0===e?"undefined":a(e)}}),_i=e(bi),Ei=function(e,t){var r=(Xe.Object||{})[e]||Object[e],i={};i[e]=t(r),ht(ht.S+ht.F*tt(function(){r(1)}),"Object",i)};Ei("keys",function(){return function(e){return qt(or(e))}});var ki=Xe.Object.keys,wi=e(t(function(e){e.exports={default:ki,__esModule:!0}})),Si=Math.floor;ht(ht.S,"Number",{isInteger:function(e){return!Je(e)&&isFinite(e)&&Si(e)===e}});var Ti=Xe.Number.isInteger,Ai=e(t(function(e){e.exports={default:Ti,__esModule:!0}})),Ri="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff",Li="["+Ri+"]",Oi=RegExp("^"+Li+Li+"*"),Di=RegExp(Li+Li+"*$"),Pi=function(e,t,r){var i={},n=tt(function(){return!!Ri[e]()||"​…"!="​…"[e]()}),a=i[e]=n?t(xi):Ri[e];r&&(i[r]=a),ht(ht.P+ht.F*n,"String",i)},xi=Pi.trim=function(e,t){return e=String(kt(e)),1&t&&(e=e.replace(Oi,"")),2&t&&(e=e.replace(Di,"")),e},Ii=Pi,Ci=$e.parseFloat,Mi=Ii.trim,Fi=1/Ci(Ri+"-0")!=-1/0?function(e){var t=Mi(String(e),3),r=Ci(t);return 0===r&&"-"==t.charAt(0)?-0:r}:Ci;ht(ht.S+ht.F*(Number.parseFloat!=Fi),"Number",{parseFloat:Fi});var Ni=parseFloat,Ui=(t(function(e){e.exports={default:Ni,__esModule:!0}}),function(){function e(){Ye(this,e)}return mt(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(b(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(b(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(b(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(b(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(b(t,r))}}]),e}());Ui.GLOBAL_TAG="chimee",Ui.FORCE_GLOBAL_TAG=!1,Ui.ENABLE_ERROR=!0,Ui.ENABLE_INFO=!0,Ui.ENABLE_WARN=!0,Ui.ENABLE_DEBUG=!0,Ui.ENABLE_VERBOSE=!0;var Bi=function(e,t,r,i){try{return i?t(et(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&et(n.call(e)),t}},Gi=er("iterator"),ji=Array.prototype,Hi=function(e){return void 0!==e&&(At.Array===e||ji[Gi]===e)},zi=function(e,t,r){t in e?lt.f(e,t,ft(0,r)):e[t]=r},Vi=er("toStringTag"),Wi="Arguments"==Lt(function(){return arguments}()),Ki=function(e,t){try{return e[t]}catch(e){}},qi=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=Ki(t=Object(e),Vi))?r:Wi?Lt(t):"Object"==(i=Lt(t))&&"function"==typeof t.callee?"Arguments":i},Yi=er("iterator"),$i=Xe.getIteratorMethod=function(e){if(void 0!=e)return e[Yi]||e["@@iterator"]||At[qi(e)]},Xi=er("iterator"),Qi=!1;try{var Zi=[7][Xi]();Zi.return=function(){Qi=!0},Array.from(Zi,function(){throw 2})}catch(e){}var Ji=function(e,t){if(!t&&!Qi)return!1;var r=!1;try{var i=[7],n=i[Xi]();n.next=function(){return{done:r=!0}},i[Xi]=function(){return n},e(i)}catch(e){}return r};ht(ht.S+ht.F*!Ji(function(e){Array.from(e)}),"Array",{from:function(e){var t,r,i,n,a=or(e),o="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,l=void 0!==u,f=0,c=$i(a);if(l&&(u=Ze(u,s>2?arguments[2]:void 0,2)),void 0==c||o==Array&&Hi(c))for(r=new o(t=xt(a.length));t>f;f++)zi(r,f,l?u(a[f],f):a[f]);else for(n=c.call(a),r=new o;!(i=n.next()).done;f++)zi(r,f,l?Bi(n,u,[i.value,f],!0):i.value);return r.length=f,r}});var en,tn,rn,nn=Xe.Array.from,an=t(function(e){e.exports={default:nn,__esModule:!0}}),on=e(an),sn=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(an);t.default=function(e){if(Array.isArray(e)){for(var t=0,i=Array(e.length);t<e.length;t++)i[t]=e[t];return i}return(0,r.default)(e)}})),un=function(e){function t(r,n,o){if(i(r)||a(r)){n=n||(a(r)?{}:[]);for(var s in r)n[s]=t(r[s],n[s],s);return n}return e(r,n,o)}return t}(function(e){return e}),ln=function(e,t,r,i){if(!(e instanceof t)||void 0!==i&&i in e)throw TypeError(r+": incorrect invocation!");return e},fn=t(function(e){var t={},r={},i=e.exports=function(e,i,n,a,o){var s,u,l,f,c=o?function(){return e}:$i(e),d=Ze(n,a,i?2:1),h=0;if("function"!=typeof c)throw TypeError(e+" is not iterable!");if(Hi(c)){for(s=xt(e.length);s>h;h++)if((f=i?d(et(u=e[h])[0],u[1]):d(e[h]))===t||f===r)return f}else for(l=c.call(e);!(u=l.next()).done;)if((f=Bi(l,d,u.value,i))===t||f===r)return f};i.BREAK=t,i.RETURN=r}),cn=er("species"),dn=function(e,t){var r,i=et(e).constructor;return void 0===i||void 0==(r=et(i)[cn])?t:Qe(r)},hn=function(e,t,r){var i=void 0===r;switch(t.length){case 0:return i?e():e.call(r);case 1:return i?e(t[0]):e.call(r,t[0]);case 2:return i?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return i?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return i?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}return e.apply(r,t)},vn=$e.process,pn=$e.setImmediate,gn=$e.clearImmediate,yn=$e.MessageChannel,mn=0,bn={},_n=function(){var e=+this;if(bn.hasOwnProperty(e)){var t=bn[e];delete bn[e],t()}},En=function(e){_n.call(e.data)};pn&&gn||(pn=function(e){for(var t=[],r=1;arguments.length>r;)t.push(arguments[r++]);return bn[++mn]=function(){hn("function"==typeof e?e:Function(e),t)},en(mn),mn},gn=function(e){delete bn[e]},"process"==Lt(vn)?en=function(e){vn.nextTick(Ze(_n,e,1))}:yn?(rn=(tn=new yn).port2,tn.port1.onmessage=En,en=Ze(rn.postMessage,rn,1)):$e.addEventListener&&"function"==typeof postMessage&&!$e.importScripts?(en=function(e){$e.postMessage(e+"","*")},$e.addEventListener("message",En,!1)):en="onreadystatechange"in at("script")?function(e){$t.appendChild(at("script")).onreadystatechange=function(){$t.removeChild(this),_n.call(e)}}:function(e){setTimeout(Ze(_n,e,1),0)});var kn,wn,Sn,Tn={set:pn,clear:gn},An=Tn.set,Rn=$e.MutationObserver||$e.WebKitMutationObserver,Ln=$e.process,On=$e.Promise,Dn="process"==Lt(Ln),Pn=function(e,t,r){for(var i in t)r&&e[i]?e[i]=t[i]:ct(e,i,t[i]);return e},xn=er("species"),In=Tn.set,Cn=function(){var e,t,r,i=function(){var i,n;for(Dn&&(i=Ln.domain)&&i.exit();e;){n=e.fn,e=e.next;try{n()}catch(i){throw e?r():t=void 0,i}}t=void 0,i&&i.enter()};if(Dn)r=function(){Ln.nextTick(i)};else if(Rn){var n=!0,a=document.createTextNode("");new Rn(i).observe(a,{characterData:!0}),r=function(){a.data=n=!n}}else if(On&&On.resolve){var o=On.resolve();r=function(){o.then(i)}}else r=function(){An.call($e,i)};return function(i){var n={fn:i,next:void 0};t&&(t.next=n),e||(e=n,r()),t=n}}(),Mn=$e.TypeError,Fn=$e.process,Nn=$e.Promise,Fn=$e.process,Un="process"==qi(Fn),Bn=function(){},Gn=!!function(){try{var e=Nn.resolve(1),t=(e.constructor={})[er("species")]=function(e){e(Bn,Bn)};return(Un||"function"==typeof PromiseRejectionEvent)&&e.then(Bn)instanceof t}catch(e){}}(),jn=function(e,t){return e===t||e===Nn&&t===Sn},Hn=function(e){var t;return!(!Je(e)||"function"!=typeof(t=e.then))&&t},zn=function(e){return jn(Nn,e)?new Vn(e):new wn(e)},Vn=wn=function(e){var t,r;this.promise=new e(function(e,i){if(void 0!==t||void 0!==r)throw Mn("Bad Promise constructor");t=e,r=i}),this.resolve=Qe(t),this.reject=Qe(r)},Wn=function(e){try{e()}catch(e){return{error:e}}},Kn=function(e,t){if(!e._n){e._n=!0;var r=e._c;Cn(function(){for(var i=e._v,n=1==e._s,a=0;r.length>a;)!function(t){var r,a,o=n?t.ok:t.fail,s=t.resolve,u=t.reject,l=t.domain;try{o?(n||(2==e._h&&$n(e),e._h=1),!0===o?r=i:(l&&l.enter(),r=o(i),l&&l.exit()),r===t.promise?u(Mn("Promise-chain cycle")):(a=Hn(r))?a.call(r,s,u):s(r)):u(i)}catch(e){u(e)}}(r[a++]);e._c=[],e._n=!1,t&&!e._h&&qn(e)})}},qn=function(e){In.call($e,function(){var t,r,i,n=e._v;if(Yn(e)&&(t=Wn(function(){Un?Fn.emit("unhandledRejection",n,e):(r=$e.onunhandledrejection)?r({promise:e,reason:n}):(i=$e.console)&&i.error&&i.error("Unhandled promise rejection",n)}),e._h=Un||Yn(e)?2:1),e._a=void 0,t)throw t.error})},Yn=function(e){if(1==e._h)return!1;for(var t,r=e._a||e._c,i=0;r.length>i;)if((t=r[i++]).fail||!Yn(t.promise))return!1;return!0},$n=function(e){In.call($e,function(){var t;Un?Fn.emit("rejectionHandled",e):(t=$e.onrejectionhandled)&&t({promise:e,reason:e._v})})},Xn=function(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),Kn(t,!0))},Qn=function(e){var t,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw Mn("Promise can't be resolved itself");(t=Hn(e))?Cn(function(){var i={_w:r,_d:!1};try{t.call(e,Ze(Qn,i,1),Ze(Xn,i,1))}catch(e){Xn.call(i,e)}}):(r._v=e,r._s=1,Kn(r,!1))}catch(e){Xn.call({_w:r,_d:!1},e)}}};Gn||(Nn=function(e){ln(this,Nn,"Promise","_h"),Qe(e),kn.call(this);try{e(Ze(Qn,this,1),Ze(Xn,this,1))}catch(e){Xn.call(this,e)}},(kn=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=Pn(Nn.prototype,{then:function(e,t){var r=zn(dn(this,Nn));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=Un?Fn.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&&Kn(this,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Vn=function(){var e=new kn;this.promise=e,this.resolve=Ze(Qn,e,1),this.reject=Ze(Xn,e,1)}),ht(ht.G+ht.W+ht.F*!Gn,{Promise:Nn}),ir(Nn,"Promise"),function(e){var t="function"==typeof Xe[e]?Xe[e]:$e[e];rt&&t&&!t[xn]&<.f(t,xn,{configurable:!0,get:function(){return this}})}("Promise"),Sn=Xe.Promise,ht(ht.S+ht.F*!Gn,"Promise",{reject:function(e){var t=zn(this);return(0,t.reject)(e),t.promise}}),ht(ht.S+!0*ht.F,"Promise",{resolve:function(e){if(e instanceof Nn&&jn(e.constructor,this))return e;var t=zn(this);return(0,t.resolve)(e),t.promise}}),ht(ht.S+ht.F*!(Gn&&Ji(function(e){Nn.all(e).catch(Bn)})),"Promise",{all:function(e){var t=this,r=zn(t),i=r.resolve,n=r.reject,a=Wn(function(){var r=[],a=0,o=1;fn(e,!1,function(e){var s=a++,u=!1;r.push(void 0),o++,t.resolve(e).then(function(e){u||(u=!0,r[s]=e,--o||i(r))},n)}),--o||i(r)});return a&&n(a.error),r.promise},race:function(e){var t=this,r=zn(t),i=r.reject,n=Wn(function(){fn(e,!1,function(e){t.resolve(e).then(r.resolve,i)})});return n&&i(n.error),r.promise}});var Zn=Xe.Promise,Jn=e(t(function(e){e.exports={default:Zn,__esModule:!0}})),ea=("undefined"!=typeof window&&Object.prototype.toString.call(window),Object.assign),ta=!ea||tt(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=ea({},e)[r]||Object.keys(ea({},t)).join("")!=i})?function(e,t){for(var r=or(e),i=arguments.length,n=1,a=Dr.f,o=Pr.f;i>n;)for(var s,u=Ot(arguments[n++]),l=a?qt(u).concat(a(u)):qt(u),f=l.length,c=0;f>c;)o.call(u,s=l[c++])&&(r[s]=u[s]);return r}:ea;ht(ht.S+ht.F,"Object",{assign:ta});var ra=Xe.Object.assign,ia=e(t(function(e){e.exports={default:ra,__esModule:!0}}));ht(ht.S,"Object",{create:Jt});var na=Xe.Object,aa=function(e,t){return na.create(e,t)},oa=t(function(e){e.exports={default:aa,__esModule:!0}}),sa=e(oa),ua=sa(null);ua.count=0;var la=function(){function e(t,r){var i=this;if(Ye(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":_i(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}return mt(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return x(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return I(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return P(this.__target,e,{data:t}),this}}]),e}(),fa=sa(null);fa.count=0;(function(){function e(t,r){var i=this;if(Ye(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":_i(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}mt(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return F(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return N(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return M(this.__target,e,{data:t}),this}}])})(),"undefined"!=typeof window&&Object.prototype.toString.call(window);var ca=document.createElement("div"),da="innerText";"textContent"in ca&&(da="textContent");var ha=Array.prototype,va=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;Ye(this,e);var n=this;n.selector=t;var a=void 0;t&&t.constructor===NodeList?a=U(t):i(t)?a=t:l(t)?0===t.indexOf("<")?(ca.innerHTML=t,a=X("*",ca,!0)):a=X(t,r,!0):a=[t],ia(n,a),n.length=a.length}return mt(e,[{key:"each",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return ha.forEach.apply(this,t),this}},{key:"push",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return ha.push.apply(this,t),this}},{key:"splice",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return J(ha.splice.apply(this,t))}},{key:"find",value:function(e){var t=[];this.each(function(r){t=t.concat(X(e,r,!0))});var r=J(t);return r.parent=this,r.selector=e,r}},{key:"append",value:function(e){var t=J(e),r=this[0];return t.each(function(e){return r.appendChild(e)}),this}},{key:"appendTo",value:function(e){return J(e).append(this),this}},{key:"text",value:function(e){return 0===arguments.length?this[0][da]:this.each(function(t){t[da]=e})}},{key:"html",value:function(e){return 0===arguments.length?this[0].innerHTML:this.each(function(t){t.innerHTML=e})}},{key:"attr",value:function(e,t){return 1===arguments.length?B(this[0],e):this.each(function(r){return G(r,e,t)})}},{key:"data",value:function(e,t){return 0===arguments.length?this[0].dataset||{}:1===arguments.length?(this[0].dataset||{})[e]:this.each(function(r){(r.dataset||(r.dataset={}))[e]=t})}},{key:"css",value:function(e,t){return 1!==arguments.length||a(e)?this.each(function(r){return $(r,e,t)}):Y(this[0],e)}},{key:"addClass",value:function(e){return this.each(function(t){return j(t,e)})}},{key:"removeClass",value:function(e){return this.each(function(t){return H(t,e)})}},{key:"hasClass",value:function(e){return z(this[0],e)}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return W(n,e,t,r,i)})}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return V(n,e,t,r,i)})}},{key:"delegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return K(n,e,t,r,i)})}},{key:"undelegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return q(n,e,t,r,i)})}},{key:"remove",value:function(){return this.each(function(e){return Q(e)})}}]),e}();Ei("getPrototypeOf",function(){return function(e){return lr(or(e))}});var pa=Xe.Object.getPrototypeOf,ga=e(t(function(e){e.exports={default:pa,__esModule:!0}})),ya=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(bi);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,r.default)(t))&&"function"!=typeof t?e:t}})),ma=function(e,t){if(et(e),!Je(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},ba={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=Ze(Function.call,Hr.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return ma(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:ma};ht(ht.S,"Object",{setPrototypeOf:ba.set});var _a=Xe.Object.setPrototypeOf,Ea=t(function(e){e.exports={default:_a,__esModule:!0}}),ka=e(t(function(e,t){function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=r(Ea),n=r(oa),a=r(bi);t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,a.default)(t)));e.prototype=(0,n.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i.default?(0,i.default)(e,t):e.__proto__=t)}})),wa=Hr.f;Ei("getOwnPropertyDescriptor",function(){return function(e,t){return wa(Dt(e),t)}});var Sa=Xe.Object,Ta=function(e,t){return Sa.getOwnPropertyDescriptor(e,t)},Aa=e(t(function(e){e.exports={default:Ta,__esModule:!0}})),Ra=arguments[3],La=arguments[4],Oa=arguments[5],Da=JSON.stringify,Pa=function(e,t){function r(e){d[e]=!0;for(var t in La[e][1]){var i=La[e][1][t];d[i]||r(i)}}for(var i,n=Object.keys(Oa),a=0,o=n.length;a<o;a++){var s=n[a],u=Oa[s].exports;if(u===e||u&&u.default===e){i=s;break}}if(!i){i=Math.floor(Math.pow(16,8)*Math.random()).toString(16);for(var l={},a=0,o=n.length;a<o;a++)l[s=n[a]]=s;La[i]=[Function(["require","module","exports"],"("+e+")(self)"),l]}var f=Math.floor(Math.pow(16,8)*Math.random()).toString(16),c={};c[i]=i,La[f]=[Function(["require"],"var f = require("+Da(i)+");(f.default ? f.default : f)(self);"),c];var d={};r(f);var h="("+Ra+")({"+Object.keys(d).map(function(e){return Da(e)+":["+La[e][0]+","+Da(La[e][1])+"]"}).join(",")+"},{},["+Da(f)+"])",v=window.URL||window.webkitURL||window.mozURL||window.msURL,p=new Blob([h],{type:"text/javascript"});if(t&&t.bare)return p;var g=v.createObjectURL(p),y=new Worker(g);return y.objectURL=g,y},xa={type:"vod",autoPlay:!1,box:"mp4",lockInternalProperty:!1,debug:!0},Ia=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.video=e,i.box="mp4",i.config=xa,E(i.config,r),i.bindEvents(),i}return ka(t,la),mt(t,[{key:"internalPropertyHandle",value:function(){if(Aa){var e=this,t=Aa(HTMLMediaElement.prototype,"currentTime");Object.defineProperty(this.video,"currentTime",{get:function(){return t.get.call(e.video)},set:function(r){if(e.currentTimeLock)return t.set.call(e.video,r);throw new Error("can not set currentTime by youself")}})}}},{key:"bindEvents",value:function(){var e=this;this.video&&this.config.lockInternalProperty&&this.video.addEventListener("canplay",function(){e.internalPropertyHandle()})}},{key:"load",value:function(e){this.config.src=e||this.config.src,this.video.src=this.config.src}},{key:"unload",value:function(){this.video.src="",this.video.removeAttribute("src")}},{key:"destroy",value:function(){this.video&&this.unload()}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}},{key:"attachMedia",value:function(){}},{key:"seek",value:function(e){this.currentTimeLock=!0,this.video.currentTime=e,this.currentTimeLock=!1}}]),t}(),Ca=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.video=e,i.config=r,i.tag="mse-controller",i.e={onSourceOpen:i.onSourceOpen.bind(i),onSourceEnded:i.onSourceEnded.bind(i),onSourceClose:i.onSourceClose.bind(i),onSourceBufferError:i.onSourceBufferError.bind(i)},i.queue=[],i.removeRangesList=[],i.mimeCodec='video/mp4; codecs="avc1.640020,mp4a.40.2"',i.init(),i}return ka(t,la),mt(t,[{key:"init",value:function(){if(this.mediaSource)throw Ui.Error(this.tag,"MediaSource has been attached to an HTMLMediaElement!"),new Error("MediaSource has been attached to an HTMLMediaElement!");var e=this.mediaSource=new window.MediaSource;e.addEventListener("sourceopen",this.e.onSourceOpen),e.addEventListener("sourceended",this.e.onSourceEnded),e.addEventListener("sourceclose",this.e.onSourceClose)}},{key:"onSourceOpen",value:function(){var e=this;Ui.verbose(this.tag,"MediaSource onSourceOpen"),this.mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this.sourceBuffer=this.mediaSource.addSourceBuffer(this.mimeCodec),this.sourceBuffer.addEventListener("error",this.e.onSourceBufferError),this.sourceBuffer.addEventListener("abort",function(){return console.log("sourceBuffer: abort")}),this.sourceBuffer.addEventListener("updateend",function(){if(e.queue.length>=1&&!e.sourceBuffer.updating){var t=e.queue.shift();e.appendBuffer(t)}e.emit("updateend")}),this.emit("source_open"),this.sourceBufferEvent()}},{key:"sourceBufferEvent",value:function(){var e=this;this.on("mediaSegment",function(t){var r=t.data;e.sourceBuffer.updating||e.queue.length>0?e.queue.push(r):e.appendBuffer(r)}),this.on("mediaSegmentInit",function(t){var r=t.data;e.sourceBuffer.updating||e.queue.length>0?e.queue.push(r):e.appendBuffer(r)})}},{key:"needCleanupSourceBuffer",value:function(){var e=this.video.currentTime,t=this.sourceBuffer.buffered;return t.length>=1&&e-t.start(0)>=this.config.autoCleanupMaxBackwardDuration}},{key:"doCleanupSourceBuffer",value:function(){Ui.verbose("执行了一次垃圾回收");for(var e=this.video.currentTime,t=this.sourceBuffer.buffered,r=!1,i=0;i<t.length;i++){var n=t.start(i),a=t.end(i);if(n<=e&&e<a+3){if(e-n>=this.config.autoCleanupMaxBackwardDuration){r=!0;var o=e-this._config.autoCleanupMinBackwardDuration;this.removeRangesList.push({start:n,end:o})}}else a<e&&(r=!0,this.removeRangesList.push({start:n,end:a}))}r&&!this.sourceBuffer.updating&&this.removeRangesList()}},{key:"removeRangesList",value:function(){for(var e=0;e<this.removeRangesListi.length;e++)if(!this.sourceBuffer.updating)for(var t=this.sourceBuffer,r=this.removeRangesList[e];r.length&&!t.updating;){var i=r.shift();t.remove(i.start,i.end)}}},{key:"appendBuffer",value:function(e){this.needCleanupSourceBuffer()&&this.doCleanupSourceBuffer();try{this.sourceBuffer.appendBuffer(e)}catch(e){22===e.code&&(Ui.verbose(this.TAG,"MediaSource bufferFull"),this.emit("bufferFull"))}}},{key:"onSourceEnded",value:function(){Ui.verbose(this.TAG,"MediaSource onSourceEnded")}},{key:"onSourceClose",value:function(){Ui.verbose(this.TAG,"MediaSource onSourceClose"),this.mediaSource&&null!==this.e&&(this.mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this.mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this.mediaSource.removeEventListener("sourceclose",this.e.onSourceClose))}},{key:"onSourceBufferError",value:function(e){Ui.Error(this.tag,"SourceBuffer Error: "+e)}},{key:"seek",value:function(e){}},{key:"destroy",value:function(){if(this.mediaSource){var e=this.mediaSource;this.queue=[];var t=this.sourceBuffer;if(t&&("closed"!==e.readyState&&(e.removeSourceBuffer(t),t.removeEventListener("error",this.e.onSourceBufferError),t.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)),this.sourceBuffer=null),"open"===e.readyState)try{e.endOfStream()}catch(e){Ui.e(this.TAG,e.message)}e.removeEventListener("sourceopen",this.e.onSourceOpen),e.removeEventListener("sourceended",this.e.onSourceEnded),e.removeEventListener("sourceclose",this.e.onSourceClose),this.mediaSource=null}this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src"),this._mediaElement=null),this._mediaSourceObjectURL&&(window.URL.revokeObjectURL(this._mediaSourceObjectURL),this._mediaSourceObjectURL=null)}}]),t}(),Ma=function(e){var t={},r=void 0;return r=-1!==e.to?"bytes="+e.from.toString()+"-"+e.to.toString():"bytes="+e.from.toString()+"-",t.Range=r,{headers:t}},Fa=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.fetching=!1,i.config=r,i.range={from:0,to:5e5},i.src=e,i.totalRange=null,i.block=5e5,i.reader=null,i.requestAbort=!1,i.arrivalDataCallback=null,i.bytesStart=0,i}return ka(t,la),mt(t,null,[{key:"isSupport",value:function(){return!(!window.fetch||!window.ReadableStream)}}]),mt(t,[{key:"open",value:function(e,t){var r=this;this.requestAbort=!1;var i=new Headers,n=e||{from:0,to:-1};if("vod"===this.config.type){this.range.from=n.from,this.range.to=n.to;var a=Ma(n).headers;for(var o in a)i.append(o,a[o])}t&&(this.bytesStart=0),this.req=new Request(this.src,{headers:i}),fetch(this.req).then(function(e){if(e.ok){var i=e.body.getReader();return r.pump(i,t)}})}},{key:"pause",value:function(){this.requestAbort=!0}},{key:"pump",value:function(e,t){var r=this;return e.read().then(function(i){if(!i.done){if(!0===r.requestAbort)return e.cancel();var n=i.value.buffer;return r.arrivalDataCallback&&(r.arrivalDataCallback(n,r.bytesStart,t),r.bytesStart+=n.byteLength),r.pump(e)}Ui.ver})}}]),t}(),Na=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.tag="RangeLoader",i.xhr=null,i.src=e,i.totalLength=null,i.chunkSizeKB=393216,i.range={},i.bytesStart=0,i}return ka(t,la),mt(t,null,[{key:"isSupport",value:function(){try{var e=new XMLHttpRequest;return e.open("GET","https://example.com",!0),e.responseType="arraybuffer","arraybuffer"===e.responseType}catch(e){return!1}}}]),mt(t,[{key:"open",value:function(e){var t=this.xhr=new XMLHttpRequest;t.open("GET",this.src,!0),t.responseType="arraybuffer",t.onreadystatechange=this.onReadyStateChange.bind(this),t.onprogress=this.onProgress.bind(this),t.onload=this.onLoad.bind(this),t.onerror=this.onXhrError.bind(this);var r=e||{from:0,to:-1};this.range.from=r.from,this.range.to=r.to;var i=Ma(r).headers;for(var n in i)t.setRequestHeader(n,i[n]);t.send()}},{key:"abort",value:function(){this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr.abort(),this.xhr=null}},{key:"destroy",value:function(){this.xhr&&(this.abort(),this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr=null),this.totalLength=null,this.bytesStart=null,this.range={}}},{key:"onReadyStateChange",value:function(e){var t=this.xhr;if(2===t.readyState&&t.status<200&&t.status>299){var r={from:this.range.from,to:this.range.to,url:this.src,msg:"http Error: http code "+t.status};this.emit(this.tag,r)}}},{key:"onProgress",value:function(e){this.totalLength||(this.totalLength=e.total,this.abort(),this.open({from:0,to:this.chunkSizeKB}))}},{key:"onLoad",value:function(e){if(this.totalLength&&(this.range.to,this.totalLength,this.arrivalDataCallback)){var t=e.target.response;this.arrivalDataCallback(t,this.bytesStart),this.bytesStart+=t.byteLength}}},{key:"onXhrError",value:function(e){var t={from:this.range.from,to:this.range.to,url:this.src,msg:e.constructor.name+" "+e.type};this.emit(this.tag,t)}}]),t}(),Ua=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.tag="mozChunkLoader",i.xhr=null,i.src=e,i.config=r,i.totalLength=null,i.chunkSizeKB=393216,i.range={},i.bytesStart=0,i}return ka(t,la),mt(t,null,[{key:"isSupport",value:function(){try{var e=new XMLHttpRequest;return e.open("GET","https://example.com",!0),e.responseType="moz-chunked-arraybuffer","moz-chunked-arraybuffer"===e.responseType}catch(e){return!1}}}]),mt(t,[{key:"open",value:function(e){var t=this.xhr=new XMLHttpRequest;if(t.open("GET",this.src,!0),t.responseType="moz-chunked-arraybuffer",t.onreadystatechange=this.onReadyStateChange.bind(this),t.onprogress=this.onProgress.bind(this),t.onload=this.onLoadEnd.bind(this),t.onerror=this.onXhrError.bind(this),"vod"===this.config.type){var r=e||{from:0,to:-1};this.range.from=r.from,this.range.to=r.to;var i=Ma(r).headers;for(var n in i)t.setRequestHeader(n,i[n])}t.send()}},{key:"abort",value:function(){this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr.abort(),this.xhr=null}},{key:"destroy",value:function(){this.xhr&&(this.abort(),this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr=null),this.totalLength=null,this.bytesStart=null,this.range={}}},{key:"onReadyStateChange",value:function(e){var t=this.xhr;if(2===t.readyState&&t.status<200&&t.status>299){var r={from:this.range.from,to:this.range.to,url:this.src,msg:"http Error: http code "+t.status};this.emit(this.tag,r)}}},{key:"onProgress",value:function(e){this.totalLength||(this.totalLength=e.total,null!==e.total&&0!==e.total&&(this.totalLength=e.total));var t=e.target.response;this.arrivalDataCallback(t,this.bytesStart),this.bytesStart+=t.byteLength}},{key:"onLoadEnd",value:function(e){this.emit(this.tag,"video load end")}},{key:"onXhrError",value:function(e){var t={from:this.range.from,to:this.range.to,url:this.src,msg:e.constructor.name+" "+e.type};this.emit(this.tag,t)}}]),t}(),Ba=function(e){function t(e){Ye(this,t);var r=ya(this,(t.__proto__||ga(t)).call(this));return r.loader=null,r.config={},ia(r.config,e),r.selectLoader(),r.bufferSize=3145728,r.cacheBuffer=new ArrayBuffer(r.bufferSize),r.cacheRemain=0,r.stashByteStart=0,r.enableStash=!0,r.stashSize=393216,r.resumeFrom=0,r.currentRange={},r.totalReceive=0,r.seekPonit=0,r}return ka(t,la),mt(t,[{key:"selectLoader",value:function(){var e=this.config,t=this.config.src;Fa.isSupport()?this.loader=new Fa(t,e):Ua.isSupport()?this.loader=new Ua(t,e):Na.isSupport()&&(this.loader=new Na(t,e)),this.loader.arrivalDataCallback=this.onLoaderChunkArrival.bind(this)}},{key:"onLoaderChunkArrival",value:function(e,t,r){if(r&&(this.seekPonit=r),this.arrivalDataCallback)if(this.totalReceive+=e.byteLength,0===this.cacheRemain&&0===this.stashByteStart&&(this.stashByteStart=t),this.cacheRemain+e.byteLength<=this.stashSize)new Uint8Array(this.cacheBuffer,0,this.stashSize).set(new Uint8Array(e),this.cacheRemain),this.cacheRemain+=e.byteLength;else{var i=new Uint8Array(this.cacheBuffer,0,this.bufferSize);if(this.cacheRemain>0){var n=this.cacheBuffer.slice(0,this.cacheRemain),a=0;if(this.seekPonit?(a=this.arrivalDataCallback(n,this.stashByteStart,this.seekPonit),this.seekPonit=0):a=this.arrivalDataCallback(n,this.stashByteStart),a<n.byteLength){if(a>0){var o=new Uint8Array(n,a);i.set(o,0),this.cacheRemain=o.byteLength,this.stashByteStart+=a}}else this.cacheRemain=0,this.stashByteStart+=a;this.cacheRemain+e.byteLength>this.bufferSize&&(this.expandBuffer(this.cacheRemain+e.byteLength),i=new Uint8Array(this.cacheBuffer,0,this.bufferSize)),i.set(new Uint8Array(e),this.cacheRemain),this.cacheRemain+=e.byteLength}else{var s=0;if(this.seekPonit?(s=this.arrivalDataCallback(e,t,this.seekPonit),this.seekPonit=0):s=this.arrivalDataCallback(e,t),s<e.byteLength){var u=e.byteLength-s;u>this.bufferSize&&(this.expandBuffer(u),i=new Uint8Array(this.cacheBuffer,0,this.bufferSize)),i.set(new Uint8Array(e,s),0),this.cacheRemain+=u,this.stashByteStart=t+s}}}}},{key:"initCacheBuffer",value:function(){this.cacheBuffer=new ArrayBuffer(this.bufferSize)}},{key:"expandBuffer",value:function(e){var t=this.bufferSize;t<e&&(t=e),this.cacheBuffer=new ArrayBuffer(t),this.bufferSize=t}},{key:"pause",value:function(){this.loader.pause()}},{key:"open",value:function(e){void 0===e&&(e=0),this.loader.open({from:e,to:-1})}},{key:"resume",value:function(){this.paused=!1;var e=this.totalReceive;this.open(e)}},{key:"seek",value:function(e,t,r){this.loader.open({from:e,to:-1},r)}},{key:"destroy",value:function(){this.pause(),this.cacheBuffer=null}}]),t}(),Ga=function(){function e(){Ye(this,e),this.tagType=-1,this.dataSize=-1,this.Timestamp=-1,this.StreamID=-1,this.body=-1,this.time=-1,this.arr=[]}return mt(e,[{key:"getTime",value:function(){this.arr=[];for(var e=0;e<this.Timestamp.length;e++)this.arr.push(1==this.Timestamp[e].toString(16).length?"0"+this.Timestamp[e].toString(16):this.Timestamp[e].toString(16));this.arr.pop();var t=this.arr.join("");return this.time=parseInt(t,16),parseInt(t,16)}}]),e}(),ja=function(){function e(t){Ye(this,e),this.TAG=this.constructor.name,this._buffer=t,this._buffer_index=0,this._total_bytes=t.byteLength,this._total_bits=8*t.byteLength,this._current_word=0,this._current_word_bits_left=0}return mt(e,[{key:"destroy",value:function(){this._buffer=null}},{key:"_fillCurrentWord",value:function(){var e=this._total_bytes-this._buffer_index;if(e<=0)throw new IllegalStateException("ExpGolomb: _fillCurrentWord() but no bytes available");var t=Math.min(4,e),r=new Uint8Array(4);r.set(this._buffer.subarray(this._buffer_index,this._buffer_index+t)),this._current_word=new DataView(r.buffer).getUint32(0,!1),this._buffer_index+=t,this._current_word_bits_left=8*t}},{key:"readBits",value:function(e){if(e>32)throw new InvalidArgumentException("ExpGolomb: readBits() bits exceeded max 32bits!");if(e<=this._current_word_bits_left){var t=this._current_word>>>32-e;return this._current_word<<=e,this._current_word_bits_left-=e,t}var r=this._current_word_bits_left?this._current_word:0;r>>>=32-this._current_word_bits_left;var i=e-this._current_word_bits_left;this._fillCurrentWord();var n=Math.min(i,this._current_word_bits_left),a=this._current_word>>>32-n;return this._current_word<<=n,this._current_word_bits_left-=n,r=r<<n|a}},{key:"readBool",value:function(){return 1===this.readBits(1)}},{key:"readByte",value:function(){return this.readBits(8)}},{key:"_skipLeadingZero",value:function(){var e=void 0;for(e=0;e<this._current_word_bits_left;e++)if(0!=(this._current_word&2147483648>>>e))return this._current_word<<=e,this._current_word_bits_left-=e,e;return this._fillCurrentWord(),e+this._skipLeadingZero()}},{key:"readUEG",value:function(){var e=this._skipLeadingZero();return this.readBits(e+1)-1}},{key:"readSEG",value:function(){var e=this.readUEG();return 1&e?e+1>>>1:-1*(e>>>1)}}]),e}(),Ha=function(){function e(){Ye(this,e)}return mt(e,null,[{key:"_ebsp2rbsp",value:function(e){for(var t=e,r=t.byteLength,i=new Uint8Array(r),n=0,a=0;a<r;a++)a>=2&&3===t[a]&&0===t[a-1]&&0===t[a-2]||(i[n]=t[a],n++);return new Uint8Array(i.buffer,0,n)}},{key:"parseSPS",value:function(t){var r=e._ebsp2rbsp(t),i=new ja(r);i.readByte();var n=i.readByte();i.readByte();var a=i.readByte();i.readUEG();var o=e.getProfileString(n),s=e.getLevelString(a),u=1,l=420,f=[0,420,422,444],c=8;if((100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n||138===n||144===n)&&(3===(u=i.readUEG())&&i.readBits(1),u<=3&&(l=f[u]),c=i.readUEG()+8,i.readUEG(),i.readBits(1),i.readBool()))for(var d=3!==u?8:12,h=0;h<d;h++)i.readBool()&&(h<6?e._skipScalingList(i,16):e._skipScalingList(i,64));i.readUEG();var v=i.readUEG();if(0===v)i.readUEG();else if(1===v){i.readBits(1),i.readSEG(),i.readSEG();for(var p=i.readUEG(),g=0;g<p;g++)i.readSEG()}i.readUEG(),i.readBits(1);var y=i.readUEG(),m=i.readUEG(),b=i.readBits(1);0===b&&i.readBits(1),i.readBits(1);var _=0,E=0,k=0,w=0;i.readBool()&&(_=i.readUEG(),E=i.readUEG(),k=i.readUEG(),w=i.readUEG());var S=1,T=1,A=0,R=!0,L=0,O=0;if(i.readBool()){if(i.readBool()){var D=i.readByte(),P=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];D>0&&D<16?(S=P[D-1],T=x[D-1]):255===D&&(S=i.readByte()<<8|i.readByte(),T=i.readByte()<<8|i.readByte())}if(i.readBool()&&i.readBool(),i.readBool()&&(i.readBits(4),i.readBool()&&i.readBits(24)),i.readBool()&&(i.readUEG(),i.readUEG()),i.readBool()){var I=i.readBits(32),C=i.readBits(32);R=i.readBool(),A=(L=C)/(O=2*I)}}var M=1;1===S&&1===T||(M=S/T);var F=0,N=0;0===u?(F=1,N=2-b):(F=3===u?1:2,N=(1===u?2:1)*(2-b));var U=16*(y+1),B=16*(m+1)*(2-b);U-=(_+E)*F,B-=(k+w)*N;var G=Math.ceil(U*M);return i.destroy(),i=null,{profile_string:o,level_string:s,bit_depth:c,chroma_format:l,chroma_format_string:e.getChromaFormatString(l),frame_rate:{fixed:R,fps:A,fps_den:O,fps_num:L},sar_ratio:{width:S,height:T},codec_size:{width:U,height:B},present_size:{width:G,height:B}}}},{key:"_skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<t;n++)0!==i&&(i=(r+e.readSEG()+256)%256),r=0===i?r:i}},{key:"getProfileString",value:function(e){switch(e){case 66:return"Baseline";case 77:return"Main";case 88:return"Extended";case 100:return"High";case 110:return"High10";case 122:return"High422";case 244:return"High444";default:return"Unknown"}}},{key:"getLevelString",value:function(e){return(e/10).toFixed(1)}},{key:"getChromaFormatString",value:function(e){switch(e){case 420:return"4:2:0";case 422:return"4:2:2";case 444:return"4:4:4";default:return"Unknown"}}}]),e}(),za=function(){var e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),256===new Int16Array(e)[0]}(),Va=function(){function e(){Ye(this,e)}return mt(e,null,[{key:"parseObject",value:function(t,r,i){var n=e.parseString(t,r,i),a=e.parseScript(t,r+n.size),o=a.objectEnd;return{data:{name:n.data,value:a.data},size:a.size,objectEnd:o}}},{key:"parseVariable",value:function(t,r,i){return e.parseObject(t,r,i)}},{key:"parseLongString",value:function(e,t,r){var i=new DataView(e,t).getUint32(0,!za),n=void 0;return n=i>0?ee(new Uint8Array(e,t+4,i)):"",{data:n,size:4+i}}},{key:"parseDate",value:function(e,t,r){var i=new DataView(e,t),n=i.getFloat64(0,!za);return n+=60*i.getInt16(8,!za)*1e3,{data:new Date(n),size:10}}},{key:"parseString",value:function(e,t,r){var i=new DataView(e,t).getUint16(0,!za),n=void 0;return n=i>0?ee(new Uint8Array(e,t+2,i)):"",{data:n,size:2+i}}},{key:"parseMetadata",value:function(t){var r=e.parseScript(t,0),i=e.parseScript(t,r.size,t.length-r.size),n={};return n[r.data]=i.data,n}},{key:"parseScript",value:function(t,r,i){var n=r,a=new Uint8Array(t).buffer,o=new DataView(a,0,i),s=null,u=o.getUint8(n);switch(n+=1,u){case 0:s=o.getFloat64(n,!za),n+=8;break;case 1:s=!!o.getUint8(n),n+=1;break;case 2:var l=e.parseString(a,n);s=l.data,n+=l.size;break;case 3:s={};var f=0;for(9==(16777215&o.getUint32(i-4,!za))&&(f=3);n<i-4;){var c=e.parseObject(a,n,i-r-f);if(c.objectEnd)break;s[c.data.name]=c.data.value,n=c.size}n<=i-3&&9===(16777215&v.getUint32(n-1,!za))&&(n+=3);break;case 8:s={},n+=4;for(9==(16777215&o.getUint32(i-4,!za))&&3;n<i-8;){var d=e.parseVariable(a,n);if(d.objectEnd)break;s[d.data.name]=d.data.value,n=d.size}n<=i-3&&9===(16777215&o.getUint32(n-1,!za))&&(n+=3);break;case 9:s=void 0,n=1,!0;break;case 10:s=[];var h=o.getUint32(n,!za);n+=4;for(var p=0;p<h;p++){var g=e.parseScript(a,n);s.push(g.data),n=g.size}break;case 11:var y=e.parseDate(a,n+1,i-1);s=y.data,n+=y.size;break;case 12:var m=e.parseString(a,n+1,i-1);s=m.data,n+=m.size;break;default:n=i,console.log("AMF","Unsupported AMF value type "+u)}return{data:s,size:n}}}]),e}(),Wa=function(){function e(){Ye(this,e),this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return mt(e,[{key:"isComplete",value:function(){var e=!1===this.hasAudio||!0===this.hasAudio&&null!=this.audioCodec&&null!=this.audioSampleRate&&null!=this.audioChannelCount,t=!1===this.hasVideo||!0===this.hasVideo&&null!=this.videoCodec&&null!=this.width&&null!=this.height&&null!=this.fps&&null!=this.profile&&null!=this.level&&null!=this.chromaFormat&&null!=this.sarNum&&null!=this.sarDen;return null!=this.mimeType&&null!=this.duration&&null!=this.metadata&&null!=this.hasKeyframesIndex&&e&&t}},{key:"isSeekable",value:function(){return!0===this.hasKeyframesIndex}}]),e}(),Ka=function e(t){Ye(this,e),this.type=t},qa=new(function(){function e(){Ye(this,e),this.TAG=this.constructor.name,this._config={},this._onError=null,this._onMediaInfo=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._dataOffset=0,this._firstParse=!0,this._dispatch=!1,this._hasAudio=!1,this._hasVideo=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new Wa,this._mediaInfo.hasAudio=this._hasAudio,this._mediaInfo.hasVideo=this._hasVideo,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._naluLengthSize=4,this._timestampBase=0,this._timescale=1e3,this._duration=0,this._durationOverrided=!1,this._referenceFrameRate={fixed:!0,fps:23.976,fps_num:23976,fps_den:1e3},this._videoTrack={type:"video",id:1,sequenceNumber:0,addcoefficient:2,samples:[],length:0},this._audioTrack={type:"audio",id:2,sequenceNumber:1,addcoefficient:2,samples:[],length:0},this._littleEndian=function(){var e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),256===new Int16Array(e)[0]}()}return mt(e,[{key:"onMediaInfo",value:function(e){this._onMediaInfo=e}},{key:"parseMetadata",value:function(e){var t=Va.parseMetadata(e);this._parseScriptData(t)}},{key:"_parseScriptData",value:function(e){var t=e;if(t.hasOwnProperty("onMetaData")){this._metadata&&console.log(this.TAG,"Found another onMetaData tag!"),this._metadata=t;var r=this._metadata.onMetaData;if("boolean"==typeof r.hasAudio&&(this._hasAudio=r.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),"boolean"==typeof r.hasVideo&&(this._hasVideo=r.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),"number"==typeof r.audiodatarate&&(this._mediaInfo.audioDataRate=r.audiodatarate),"number"==typeof r.videodatarate&&(this._mediaInfo.videoDataRate=r.videodatarate),"number"==typeof r.width&&(this._mediaInfo.width=r.width),"number"==typeof r.height&&(this._mediaInfo.height=r.height),"number"==typeof r.duration){if(!this._durationOverrided){var i=Math.floor(r.duration*this._timescale);this._duration=i,this._mediaInfo.duration=i}}else this._mediaInfo.duration=0;if("number"==typeof r.framerate){var n=Math.floor(1e3*r.framerate);if(n>0){var a=n/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=a,this._referenceFrameRate.fps_num=n,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=a}}if("object"===_i(r.keyframes)){this._mediaInfo.hasKeyframesIndex=!0;var o=r.keyframes;o.times=r.times,o.filepositions=r.filepositions,this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(o),r.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;return this._dispatch=!1,this._mediaInfo.metadata=r,console.log(this.TAG,"Parsed onMetaData"),this._mediaInfo}}},{key:"_parseKeyframesIndex",value:function(e){for(var t=[],r=[],i=1;i<e.times.length;i++){var n=this._timestampBase+Math.floor(1e3*e.times[i]);t.push(n),r.push(e.filepositions[i])}return{times:t,filepositions:r}}},{key:"moofTag",value:function(e){for(var t=0;t<e.length;t++)this._dispatch=!0,this.parseChunks(e[t]);this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack)}},{key:"parseChunks",value:function(e){switch(e.tagType){case 8:this._parseAudioData(e.body.buffer,0,e.body.length,e.getTime());break;case 9:this._parseVideoData(e.body.buffer,0,e.body.length,e.getTime(),0);break;case 18:this.parseMetadata(e.body)}}},{key:"_parseVideoData",value:function(e,t,r,i,n){if(i==this._timestampBase&&0!=this._timestampBase)throw new Ka(i+this._timestampBase+"夭寿啦这个视频不是从0开始");if(r<=1)console.log(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");else{var a=new Uint8Array(e,t,r)[0],o=(240&a)>>>4,s=15&a;if(7!==s)throw new Ka("Flv: Unsupported codec in video frame: "+s);this._parseAVCVideoPacket(e,t+1,r-1,i,n,o)}}},{key:"_parseAVCVideoPacket",value:function(e,t,r,i,n,a){if(r<4)console.log(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var o=this._littleEndian,s=new DataView(e,t,r),u=s.getUint8(0),l=16777215&s.getUint32(0,!o);if(0===u)this._parseAVCDecoderConfigurationRecord(e,t+4,r-4);else if(1===u)this._parseAVCVideoData(e,t+4,r-4,i,n,a,l);else if(2!==u)throw new Ka("Flv: Invalid video packet type "+u)}}},{key:"_parseAVCDecoderConfigurationRecord",value:function(e,t,r){if(r<7)console.log(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var i=this._videoMetadata,n=this._videoTrack,a=this._littleEndian,o=new DataView(e,t,r);i?void 0!==i.avcc&&console.log(this.TAG,"Found another AVCDecoderConfigurationRecord!"):((i=this._videoMetadata={}).type="video",i.id=n.id,i.timescale=this._timescale,i.duration=this._duration);var s=o.getUint8(0),u=o.getUint8(1);o.getUint8(2),o.getUint8(3);if(1===s&&0!==u)if(this._naluLengthSize=1+(3&o.getUint8(4)),3===this._naluLengthSize||4===this._naluLengthSize){var l=31&o.getUint8(5);if(0===l||l>1)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid H264 SPS count: "+l);else{for(var f=6,c=0;c<l;c++){var d=o.getUint16(f,!a);if(f+=2,0!==d){var h=new Uint8Array(e,t+f,d);f+=d;var v=Ha.parseSPS(h);i.codecWidth=v.codec_size.width,i.codecHeight=v.codec_size.height,i.presentWidth=v.present_size.width,i.presentHeight=v.present_size.height,i.profile=v.profile_string,i.level=v.level_string,i.bitDepth=v.bit_depth,i.chromaFormat=v.chroma_format,i.sarRatio=v.sar_ratio,i.frameRate=v.frame_rate,!1!==v.frame_rate.fixed&&0!==v.frame_rate.fps_num&&0!==v.frame_rate.fps_den||(i.frameRate=this._referenceFrameRate);var p=i.frameRate.fps_den,g=i.frameRate.fps_num;i.refSampleDuration=Math.floor(i.timescale*(p/g));for(var y=h.subarray(1,4),m="avc1.",b=0;b<3;b++){var _=y[b].toString(16);_.length<2&&(_="0"+_),m+=_}i.codec=m;var E=this._mediaInfo;E.width=i.codecWidth,E.height=i.codecHeight,E.fps=i.frameRate.fps,E.profile=i.profile,E.level=i.level,E.chromaFormat=v.chroma_format_string,E.sarNum=i.sarRatio.width,E.sarDen=i.sarRatio.height,E.videoCodec=m,E.hasAudio?null!=E.audioCodec&&(E.mimeType='video/x-flv; codecs="'+E.videoCodec+","+E.audioCodec+'"'):E.mimeType='video/x-flv; codecs="'+E.videoCodec+'"',E.isComplete()&&this._onMediaInfo(E)}}var k=o.getUint8(f);if(0===k||k>1)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid H264 PPS count: "+k);else{f++;for(var w=0;w<k;w++){var S=o.getUint16(f,!a);f+=2,0!==S&&(f+=S)}i.avcc=new Uint8Array(r),i.avcc.set(new Uint8Array(e,t,r),0),console.log(this.TAG,"Parsed AVCDecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",i)}}}else this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Strange NaluLengthSizeMinusOne: "+(this._naluLengthSize-1));else this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord")}}},{key:"timestampBase",value:function(e){this._timestampBase=e}},{key:"_parseAVCVideoData",value:function(e,t,r,i,n,a,o){for(var s=this._littleEndian,u=new DataView(e,t,r),l=[],f=0,c=0,d=this._naluLengthSize,h=this._timestampBase+i,v=1===a;c<r;){if(c+4>=r){console.log(this.TAG,"Malformed Nalu near timestamp "+h+", offset = "+c+", dataSize = "+r);break}var p=u.getUint32(c,!s);if(3===d&&(p>>>=8),p>r-d)return void console.log(this.TAG,"Malformed Nalus near timestamp "+h+", NaluSize > DataSize!");var g=31&u.getUint8(c+d);5===g&&(v=!0);var y=new Uint8Array(e,t+c,d+p),m={type:g,data:y};l.push(m),f+=y.byteLength,c+=d+p}if(l.length){var b=this._videoTrack,_={units:l,length:f,isKeyframe:v,dts:h,cts:o,pts:h+o};v&&(_.fileposition=n),b.samples.push(_),b.length+=f}}},{key:"_parseAudioData",value:function(e,t,r,i){if(i==this._timestampBase&&0!=this._timestampBase&&console.log(i,this._timestampBase,"夭寿啦这个视频不是从0开始"),r<=1)console.log(this.TAG,"Flv: Invalid audio packet, missing SoundData payload!");else{var n=this._audioMetadata,a=this._audioTrack;if(!n||!n.codec){(n=this._audioMetadata={}).type="audio",n.id=a.id,n.timescale=this._timescale,n.duration=this._duration;this._littleEndian;var o=new DataView(e,t,r).getUint8(0),s=o>>>4;if(10!==s)return void this._onError(DemuxErrors.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+s);var u=0,l=(12&o)>>>2,f=[5500,11025,22050,44100,48e3];if(!(l<f.length))return void this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+l);u=f[l];var c=1&o;n.audioSampleRate=u,n.channelCount=0===c?1:2,n.refSampleDuration=Math.floor(1024/n.audioSampleRate*n.timescale),n.codec="mp4a.40.5"}var d=this._parseAACAudioData(e,t+1,r-1);if(void 0!=d){if(0===d.packetType){n.config&&console.log(this.TAG,"Found another AudioSpecificConfig!");var h=d.data;n.audioSampleRate=h.samplingRate,n.channelCount=h.channelCount,n.codec=h.codec,n.config=h.config,n.refSampleDuration=Math.floor(1024/n.audioSampleRate*n.timescale),console.log(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",n);var v=this._mediaInfo;return v.audioCodec="mp4a.40."+h.originalAudioObjectType,v.audioSampleRate=n.audioSampleRate,v.audioChannelCount=n.channelCount,v.hasVideo?null!=v.videoCodec&&(v.mimeType='video/x-flv; codecs="'+v.videoCodec+","+v.audioCodec+'"'):v.mimeType='video/x-flv; codecs="'+v.audioCodec+'"',void(v.isComplete()&&this._onMediaInfo(v))}if(1===d.packetType){var p=this._timestampBase+i,g={unit:d.data,dts:p,pts:p};a.samples.push(g),a.length+=d.data.length}else console.log(this.TAG,"Flv: Unsupported AAC data type "+d.packetType)}}}},{key:"_parseAACAudioData",value:function(e,t,r){if(!(r<=1)){var i={},n=new Uint8Array(e,t,r);return i.packetType=n[0],0===n[0]?i.data=this._parseAACAudioSpecificConfig(e,t+1,r-1):i.data=n.subarray(1),i}console.log(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")}},{key:"_parseAACAudioSpecificConfig",value:function(e,t,r){var i=new Uint8Array(e,t,r),n=null,a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],o=0,s=0,u=0,l=null;if(o=s=i[0]>>>3,(u=(7&i[0])<<1|i[1]>>>7)<0||u>=a.length)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var f=a[u],c=(120&i[1])>>>3;if(!(c<0||c>=8)){5===o&&(l=(7&i[1])<<1|i[2]>>>7,(124&i[2])>>>2);var d=self.navigator.userAgent.toLowerCase();return-1!==d.indexOf("firefox")?u>=6?(o=5,n=new Array(4),l=u-3):(o=2,n=new Array(2),l=u):-1!==d.indexOf("android")?(o=2,n=new Array(2),l=u):(o=5,l=u,n=new Array(4),u>=6?l=u-3:1===c&&(o=2,n=new Array(2),l=u)),n[0]=o<<3,n[0]|=(15&u)>>>1,n[1]=(15&u)<<7,n[1]|=(15&c)<<3,5===o&&(n[1]|=(15&l)>>>1,n[2]=(1&l)<<7,n[2]|=8,n[3]=0),{config:n,samplingRate:f,channelCount:c,codec:"mp4a.40."+o,originalAudioObjectType:s}}this._onError(DemuxErrors.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}}},{key:"_isInitialMetadataDispatched",value:function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!this._hasAudio&&this._hasVideo?this._videoInitialMetadataDispatched:void 0}}]),e}()),Ya=new(function(){function e(){Ye(this,e),this.tempUint8=new Uint8Array,this.arrTag=[],this.index=0,this.tempArr=[],this.stop=!1,this.offset=0,this.frist=!0,this._hasAudio=!1,this._hasVideo=!1}return mt(e,[{key:"setFlv",value:function(e){return this.stop=!1,this.arrTag=[],this.index=0,this.tempUint8=e,this.tempUint8.length>13&&70==this.tempUint8[0]&&76==this.tempUint8[1]&&86==this.tempUint8[2]?(this.probe(this.tempUint8.buffer),this.read(9),this.read(4),this.parse(),this.frist=!1,this.offset):this.frist?this.offset:this.parse()}},{key:"probe",value:function(e){var t=new Uint8Array(e),r={match:!1};if(70!==t[0]||76!==t[1]||86!==t[2]||1!==t[3])return r;var i=(4&t[4])>>>2!=0,n=0!=(1&t[4]);return i||n?(this._hasAudio=qa._hasAudio=i,this._hasVideo=qa._hasVideo=n,{match:!0,hasAudioTrack:i,hasVideoTrack:n}):r}},{key:"parse",value:function(){for(;this.index<this.tempUint8.length&&!this.stop;){this.offset=this.index;var e=new Ga;if(this.tempUint8.length-this.index>=11){if(e.tagType=this.read(1)[0],e.dataSize=this.read(3),e.Timestamp=this.read(4),e.StreamID=this.read(3),18!=e.tagType&&8!=e.tagType&&9!=e.tagType)throw new Ka("wrong tagType"+e.tagType);this.tempUint8.length-this.index>=this.getBodySum(e.dataSize)+4?(e.body=this.read(this.getBodySum(e.dataSize)),9==e.tagType&&this._hasVideo&&this.arrTag.push(e),8==e.tagType&&this._hasAudio&&this.arrTag.push(e),18==e.tagType&&this.arrTag.push(e),this.read(4),this.offset=this.index):this.stop=!0}else this.stop=!0}return this.offset}},{key:"read",value:function(e){var t=this.tempUint8.slice(this.index,this.index+e);return this.index+=e,t}},{key:"getBodySum",value:function(e){var t="";return t+=1==e[0].toString(16).length?"0"+e[0].toString(16):e[0].toString(16),t+=1==e[1].toString(16).length?"0"+e[1].toString(16):e[1].toString(16),t+=1==e[2].toString(16).length?"0"+e[2].toString(16):e[2].toString(16),parseInt(t,16)}}]),e}()),$a=function(){function e(){Ye(this,e)}return mt(e,null,[{key:"init",value:function(){e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};for(var t in e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=e.constants={};r.FTYP=new Uint8Array([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),r.STSD_PREFIX=new Uint8Array([0,0,0,0,0,0,0,1]),r.STTS=new Uint8Array([0,0,0,0,0,0,0,0]),r.STSC=r.STCO=r.STTS,r.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),r.HDLR_VIDEO=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r.HDLR_AUDIO=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),r.DREF=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),r.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}},{key:"box",value:function(e){for(var t=8,r=null,i=Array.prototype.slice.call(arguments,1),n=i.length,a=0;a<n;a++)t+=i[a].byteLength;(r=new Uint8Array(t))[0]=t>>>24&255,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r.set(e,4);for(var o=8,s=0;s<n;s++)r.set(i[s],o),o+=i[s].byteLength;return r}},{key:"generateInitSegment",value:function(t){t.constructor!=Array&&(t=[t]);var r=e.box(e.types.ftyp,e.constants.FTYP),i=e.moov(t),n=new Uint8Array(r.byteLength+i.byteLength);return n.set(r,0),n.set(i,r.byteLength),n}},{key:"moov",value:function(t){var r=e.mvhd(t[0].timescale,t[0].duration),i=e.trak(t[0]),n=void 0;t.length>1&&(n=e.trak(t[1]));var a=e.mvex(t);return t.length>1?e.box(e.types.moov,r,i,n,a):e.box(e.types.moov,r,i,a)}},{key:"mvhd",value:function(t,r){return e.box(e.types.mvhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]))}},{key:"trak",value:function(t){return e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"tkhd",value:function(t){var r=t.id,i=t.duration,n=t.presentWidth,a=t.presentHeight;return e.box(e.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>>8&255,255&n,0,0,a>>>8&255,255&a,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t),e.hdlr(t),e.minf(t))}},{key:"mdhd",value:function(t){var r=t.timescale,i=t.duration;return e.box(e.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,i>>>24&255,i>>>16&255,i>>>8&255,255&i,85,196,0,0]))}},{key:"hdlr",value:function(t){var r=null;return r="audio"===t.type?e.constants.HDLR_AUDIO:e.constants.HDLR_VIDEO,e.box(e.types.hdlr,r)}},{key:"minf",value:function(t){var r=null;return r="audio"===t.type?e.box(e.types.smhd,e.constants.SMHD):e.box(e.types.vmhd,e.constants.VMHD),e.box(e.types.minf,r,e.dinf(),e.stbl(t))}},{key:"dinf",value:function(){return e.box(e.types.dinf,e.box(e.types.dref,e.constants.DREF))}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.constants.STTS),e.box(e.types.stsc,e.constants.STSC),e.box(e.types.stsz,e.constants.STSZ),e.box(e.types.stco,e.constants.STCO))}},{key:"stsd",value:function(t){return"audio"===t.type?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.mp4a(t)):e.box(e.types.stsd,e.constants.STSD_PREFIX,e.avc1(t))}},{key:"mp4a",value:function(t){var r=t.channelCount,i=t.audioSampleRate,n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,r,0,16,0,0,0,0,i>>>8&255,255&i,0,0]);return e.box(e.types.mp4a,n,e.esds(t))}},{key:"esds",value:function(t){var r=t.config,i=r.length,n=new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([i]).concat(r).concat([6,1,2]));return e.box(e.types.esds,n)}},{key:"avc1",value:function(t){var r=t.avcc,i=t.codecWidth,n=t.codecHeight,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,i>>>8&255,255&i,n>>>8&255,255&n,0,72,0,0,0,72,0,0,0,0,0,0,0,1,4,103,49,49,49,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return e.box(e.types.avc1,a,e.box(e.types.avcC,r))}},{key:"mvex",value:function(t){return t.length>1?e.box(e.types.mvex,e.trex(t[0]),e.trex(t[1])):e.box(e.types.mvex,e.trex(t[0]))}},{key:"trex",value:function(t){var r=t.id,i=new Uint8Array([0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return e.box(e.types.trex,i)}},{key:"moof",value:function(t,r){return e.box(e.types.moof,e.mfhd(t.sequenceNumber),e.traf(t,r))}},{key:"mfhd",value:function(t){var r=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t]);return e.box(e.types.mfhd,r)}},{key:"traf",value:function(t,r){var i=t.id,n=e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i])),a=e.box(e.types.tfdt,new Uint8Array([0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r])),o=e.sdtp(t),s=e.trun(t,o.byteLength+16+16+8+16+8+8);return e.box(e.types.traf,n,a,s,o)}},{key:"sdtp",value:function(t){for(var r=t.samples||[],i=r.length,n=new Uint8Array(4+i),a=0;a<i;a++){var o=r[a].flags;n[a+4]=o.isLeading<<6|o.dependsOn<<4|o.isDependedOn<<2|o.hasRedundancy}return e.box(e.types.sdtp,n)}},{key:"trun",value:function(t,r){var i=t.samples||[],n=i.length,a=12+16*n,o=new Uint8Array(a);r+=8+a,o.set([0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0);for(var s=0;s<n;s++){var u=i[s].duration,l=i[s].size,f=i[s].flags,c=i[s].cts;o.set([u>>>24&255,u>>>16&255,u>>>8&255,255&u,l>>>24&255,l>>>16&255,l>>>8&255,255&l,f.isLeading<<2|f.dependsOn,f.isDependedOn<<6|f.hasRedundancy<<4|f.isNonSync,0,0,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*s)}return e.box(e.types.trun,o)}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}}]),e}();$a.init();var Xa=function(){function e(){Ye(this,e)}return mt(e,null,[{key:"getSilentFrame",value:function(e){return 1===e?new Uint8Array([0,200,0,128,35,128]):2===e?new Uint8Array([33,0,73,144,2,25,0,35,128]):3===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]):4===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]):5===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]):6===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]):null}}]),e}(),Qa={};!function(){var e=self.navigator.userAgent.toLowerCase(),t=/(edge)\/([\w.]+)/.exec(e)||/(opr)[\/]([\w.]+)/.exec(e)||/(chrome)[ \/]([\w.]+)/.exec(e)||/(iemobile)[\/]([\w.]+)/.exec(e)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[],r=/(ipad)/.exec(e)||/(ipod)/.exec(e)||/(windows phone)/.exec(e)||/(iphone)/.exec(e)||/(kindle)/.exec(e)||/(android)/.exec(e)||/(windows)/.exec(e)||/(mac)/.exec(e)||/(linux)/.exec(e)||/(cros)/.exec(e)||[],i={browser:t[5]||t[3]||t[1]||"",version:t[2]||t[4]||"0",majorVersion:t[4]||t[2]||"0",platform:r[0]||""},n={};if(i.browser){n[i.browser]=!0;var a=i.majorVersion.split(".");n.version={major:parseInt(i.majorVersion,10),string:i.version},a.length>1&&(n.version.minor=parseInt(a[1],10)),a.length>2&&(n.version.build=parseInt(a[2],10))}i.platform&&(n[i.platform]=!0),(n.chrome||n.opr||n.safari)&&(n.webkit=!0),(n.rv||n.iemobile)&&(n.rv&&delete n.rv,i.browser="msie",n.msie=!0);n.edge&&(delete n.edge,i.browser="msedge",n.msedge=!0);n.opr&&(i.browser="opera",n.opera=!0);n.safari&&n.android&&(i.browser="android",n.android=!0);n.name=i.browser,n.platform=i.platform;for(var o in Qa)Qa.hasOwnProperty(o)&&delete Qa[o];ia(Qa,n)}();var Za=function e(t,r,i,n,a){Ye(this,e),this.dts=t,this.pts=r,this.duration=i,this.originalDts=n,this.isSyncPoint=a,this.fileposition=null},Ja=function(){function e(){Ye(this,e),this.beginDts=0,this.endDts=0,this.beginPts=0,this.endPts=0,this.originalBeginDts=0,this.originalEndDts=0,this.syncPoints=[],this.firstSample=null,this.lastSample=null}return mt(e,[{key:"appendSyncPoint",value:function(e){e.isSyncPoint=!0,this.syncPoints.push(e)}}]),e}(),eo=(function(){function e(){Ye(this,e),this._list=[]}mt(e,[{key:"clear",value:function(){this._list=[]}},{key:"appendArray",value:function(e){var t=this._list;0!==e.length&&(t.length>0&&e[0].originalDts<t[t.length-1].originalDts&&this.clear(),Array.prototype.push.apply(t,e))}},{key:"getLastSyncPointBeforeDts",value:function(e){if(0==this._list.length)return null;var t=this._list,r=0,i=t.length-1,n=0,a=0,o=i;for(e<t[0].dts&&(r=0,a=o+1);a<=o;){if((n=a+Math.floor((o-a)/2))===i||e>=t[n].dts&&e<t[n+1].dts){r=n;break}t[n].dts<e?a=n+1:o=n-1}return this._list[r]}}])}(),function(){function e(t){Ye(this,e),this._type=t,this._list=[],this._lastAppendLocation=-1}return mt(e,[{key:"isEmpty",value:function(){return 0===this._list.length}},{key:"clear",value:function(){this._list=[],this._lastAppendLocation=-1}},{key:"_searchNearestSegmentBefore",value:function(e){var t=this._list;if(0===t.length)return-2;var r=t.length-1,i=0,n=0,a=r,o=0;if(e<t[0].originalBeginDts)return o=-1;for(;n<=a;){if((i=n+Math.floor((a-n)/2))===r||e>t[i].lastSample.originalDts&&e<t[i+1].originalBeginDts){o=i;break}t[i].originalBeginDts<e?n=i+1:a=i-1}return o}},{key:"_searchNearestSegmentAfter",value:function(e){return this._searchNearestSegmentBefore(e)+1}},{key:"append",value:function(e){var t=this._list,r=e,i=this._lastAppendLocation,n=0;-1!==i&&i<t.length&&r.originalBeginDts>=t[i].lastSample.originalDts&&(i===t.length-1||i<t.length-1&&r.originalBeginDts<t[i+1].originalBeginDts)?n=i+1:t.length>0&&(n=this._searchNearestSegmentBefore(r.originalBeginDts)+1),this._lastAppendLocation=n,this._list.splice(n,0,r)}},{key:"getLastSegmentBefore",value:function(e){var t=this._searchNearestSegmentBefore(e);return t>=0?this._list[t]:null}},{key:"getLastSampleBefore",value:function(e){var t=this.getLastSegmentBefore(e);return null!=t?t.lastSample:null}},{key:"getLastSyncPointBefore",value:function(e){for(var t=this._searchNearestSegmentBefore(e),r=this._list[t].syncPoints;0===r.length&&t>0;)t--,r=this._list[t].syncPoints;return r.length>0?r[r.length-1]:null}},{key:"type",get:function(){return this._type}},{key:"length",get:function(){return this._list.length}}]),e}()),to=function(){function e(t){Ye(this,e),this.TAG=this.constructor.name,this._config=t,this._isLive=!0===t.isLive,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new eo("audio"),this._videoSegmentInfoList=new eo("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!Qa.chrome||!(Qa.version.major<50||50===Qa.version.major&&Qa.version.build<2661)),this._fillSilentAfterSeek=Qa.msedge||Qa.msie}return mt(e,[{key:"destroy",value:function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null}},{key:"bindDataSource",value:function(e){return e.onDataAvailable=this.remux.bind(this),e.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this}},{key:"insertDiscontinuity",value:function(){this._audioNextDts=this._videoNextDts=void 0}},{key:"seek",value:function(e){this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()}},{key:"remux",value:function(e,t){if(!this._onMediaSegment)throw new Ka("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(e,t),this._remuxVideo(t),this._remuxAudio(e)}},{key:"_onTrackMetadataReceived",value:function(e,t){var r=null;if("audio"===e)this._audioMeta=t,r=$a.generateInitSegment(t),console.log("msg+audio",t);else{if("video"!==e)return;this._videoMeta=t,r=$a.generateInitSegment(t),console.log("msg+video",t)}if(!this._onInitSegment)throw new Ka("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(e,{type:e,data:r.buffer,codec:t.codec,container:e+"/mp4"})}},{key:"_calculateDtsBase",value:function(e,t){this._dtsBaseInited||(e.samples&&e.samples.length&&(this._audioDtsBase=e.samples[0].dts),t.samples&&t.samples.length&&(this._videoDtsBase=t.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)}},{key:"_remuxAudio",value:function(e){var t=e,r=t.samples,i=void 0,n=-1,a=-1,o=!1,s=-1;if(r&&0!==r.length){var u=8+t.length,l=new Uint8Array(u);l[0]=u>>>24&255,l[1]=u>>>16&255,l[2]=u>>>8&255,l[3]=255&u,l.set($a.types.mdat,4);for(var f=8,c=[];r.length;){var d=r.shift(),h=d.unit,v=d.dts-this._dtsBase;if(void 0==i)if(void 0==this._audioNextDts)if(this._audioSegmentInfoList.isEmpty())i=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&(o=!0);else{var p=this._audioSegmentInfoList.getLastSampleBefore(v);if(null!=p){var g=v-(p.originalDts+p.duration);g<=3&&(g=0),i=v-(p.dts+p.duration+g)}else i=0}else i=v-this._audioNextDts;var y=v-i;if(o){var m=this._videoSegmentInfoList.getLastSegmentBefore(v);null!=m&&m.beginDts<y?(s=y-m.beginDts,y=m.beginDts):o=!1}if(-1===n&&(n=y),o){o=!1,r.unshift(d);var b=this._generateSilentAudio(y,s);if(null==b)continue;var _=b.mp4Sample,E=b.unit;c.push(_),u+=E.byteLength,(l=new Uint8Array(u))[0]=u>>>24&255,l[1]=u>>>16&255,l[2]=u>>>8&255,l[3]=255&u,l.set($a.types.mdat,4),l.set(E,f),f+=E.byteLength}else{var k=0;k=r.length>=1?r[0].dts-this._dtsBase-i-y:c.length>=1?c[c.length-1].duration:this._audioMeta.refSampleDuration;var w={dts:y,pts:y,cts:0,size:h.byteLength,duration:k,originalDts:v,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}};c.push(w),l.set(h,f),f+=h.byteLength}}var S=c[c.length-1];a=S.dts+S.duration,this._audioNextDts=a;var T=new Ja;T.beginDts=n,T.endDts=a,T.beginPts=n,T.endPts=a,T.originalBeginDts=c[0].originalDts,T.originalEndDts=S.originalDts+S.duration,T.firstSample=new Za(c[0].dts,c[0].pts,c[0].duration,c[0].originalDts,!1),T.lastSample=new Za(S.dts,S.pts,S.duration,S.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(T),t.samples=c,t.sequenceNumber+=t.addcoefficient;var A=$a.moof(t,n);t.samples=[],t.length=0,this._onMediaSegment("audio",{type:"audio",data:this._mergeBoxes(A,l).buffer,sampleCount:c.length,info:T})}}},{key:"_generateSilentAudio",value:function(e,t){console.log(this.TAG,"GenerateSilentAudio: dts = "+e+", duration = "+t);var r=Xa.getSilentFrame(this._audioMeta.channelCount);return null==r?(console.log(this.TAG,"Cannot generate silent aac frame for channelCount = "+this._audioMeta.channelCount),null):{unit:r,mp4Sample:{dts:e,pts:e,cts:0,size:r.byteLength,duration:t,originalDts:e,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}}}},{key:"_remuxVideo",value:function(e){var t=e,r=t.samples,i=void 0,n=-1,a=-1,o=-1,s=-1;if(r&&0!==r.length){var u=8+e.length,l=new Uint8Array(u);l[0]=u>>>24&255,l[1]=u>>>16&255,l[2]=u>>>8&255,l[3]=255&u,l.set($a.types.mdat,4);for(var f=8,c=[],d=new Ja;r.length;){var h=r.shift(),v=h.isKeyframe,p=h.dts-this._dtsBase;if(void 0==i)if(void 0==this._videoNextDts)if(this._videoSegmentInfoList.isEmpty())i=0;else{var g=this._videoSegmentInfoList.getLastSampleBefore(p);if(null!=g){var y=p-(g.originalDts+g.duration);y<=3&&(y=0),i=p-(g.dts+g.duration+y)}else i=0}else i=p-this._videoNextDts;var m=p-i,b=h.cts,_=m+b;-1===n&&(n=m,o=_);for(var E=0;h.units.length;){var k=h.units.shift().data;l.set(k,f),f+=k.byteLength,E+=k.byteLength}var w=0;if(w=r.length>=1?r[0].dts-this._dtsBase-i-m:c.length>=1?c[c.length-1].duration:this._videoMeta.refSampleDuration,v){var S=new Za(m,_,w,h.dts,!0);S.fileposition=h.fileposition,d.appendSyncPoint(S)}var T={dts:m,pts:_,cts:b,size:E,isKeyframe:v,duration:w,originalDts:p,flags:{isLeading:0,dependsOn:v?2:1,isDependedOn:v?1:0,hasRedundancy:0,isNonSync:v?0:1}};c.push(T)}var A=c[c.length-1];if(a=A.dts+A.duration,s=A.pts+A.duration,this._videoNextDts=a,d.beginDts=n,d.endDts=a,d.beginPts=o,d.endPts=s,d.originalBeginDts=c[0].originalDts,d.originalEndDts=A.originalDts+A.duration,d.firstSample=new Za(c[0].dts,c[0].pts,c[0].duration,c[0].originalDts,c[0].isKeyframe),d.lastSample=new Za(A.dts,A.pts,A.duration,A.originalDts,A.isKeyframe),this._isLive||this._videoSegmentInfoList.append(d),t.samples=c,t.sequenceNumber+=t.addcoefficient,this._forceFirstIDR){var R=c[0].flags;R.dependsOn=2,R.isNonSync=0}var L=$a.moof(t,n);t.samples=[],t.length=0,this._onMediaSegment("video",{type:"video",data:this._mergeBoxes(L,l).buffer,sampleCount:c.length,info:d})}}},{key:"_mergeBoxes",value:function(e,t){var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}},{key:"onInitSegment",get:function(){return this._onInitSegment},set:function(e){this._onInitSegment=e}},{key:"onMediaSegment",get:function(){return this._onMediaSegment},set:function(e){this._onMediaSegment=e}}]),e}(),ro=function(){function e(t){Ye(this,e),this._config={_isLive:!1},this._config=ia(this._config,t),this.onInitSegment=null,this.onMediaSegment=null,this.onMediaInfo=null,this.seekCallBack=null,this.loadmetadata=!1,this.ftyp_moov=null,this.metaSuccRun=!1,this.metas=[],this.parseChunk=null,this.hasVideo=!1,this.hasAudio=!1,this._error=null,this._pendingResolveSeekPoint=-1,this._tempBaseTime=0,this.setflvBase=this.setflvBasefrist,qa._onTrackMetadata=this.Metadata.bind(this),qa._onMediaInfo=this.metaSucc.bind(this),qa._onDataAvailable=this.onDataAvailable.bind(this),qa._onError=this.error.bind(this),this.m4mof=new to(this._config),this.m4mof.onMediaSegment=this.onMdiaSegment.bind(this)}return mt(e,[{key:"seek",value:function(e){this.setflvBase=this.setflvBasefrist,void 0!=e&&0!=e||(e=0,this._pendingResolveSeekPoint=-1),this._tempBaseTime!=e&&(this._tempBaseTime=e,qa._timestampBase=e,this.m4mof.seek(e),this.m4mof.insertDiscontinuity(),this._pendingResolveSeekPoint=e)}},{key:"setflvBasefrist",value:function(e,t){var r=0;try{r=Ya.setFlv(new Uint8Array(e))}catch(e){this.error(e)}if(Ya.arrTag.length>0){this.hasAudio=Ya._hasAudio,this.hasVideo=Ya._hasVideo,0!=this._tempBaseTime&&this._tempBaseTime==Ya.arrTag[0].getTime()&&(qa._timestampBase=0);try{qa.moofTag(Ya.arrTag)}catch(e){this.error(e)}this.setflvBase=this.setflvBaseUsually}return r}},{key:"setflvBaseUsually",value:function(e,t){var r=0;try{r=Ya.setFlv(new Uint8Array(e))}catch(e){this.error(e)}if(Ya.arrTag.length>0)try{qa.moofTag(Ya.arrTag)}catch(e){this.error(e)}return r}},{key:"onMdiaSegment",value:function(e,t){if(this.onMediaSegment&&this.onMediaSegment(new Uint8Array(t.data)),-1!=this._pendingResolveSeekPoint&&"video"==e){var r=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=-1,this.seekCallBack&&this.seekCallBack(r)}}},{key:"Metadata",value:function(e,t){switch(e){case"video":if(this.metas.push(t),this.m4mof._videoMeta=t,this.hasVideo&&!this.hasAudio)return void this.metaSucc();break;case"audio":if(this.metas.push(t),this.m4mof._audioMeta=t,!this.hasVideo&&this.hasAudio)return void this.metaSucc()}this.hasVideo&&this.hasAudio&&this.metaSuccRun&&this.metas.length>1&&this.metaSucc()}},{key:"metaSucc",value:function(e){this.onMediaInfo&&this.onMediaInfo(e,{hasAudio:this.hasAudio,hasVideo:this.hasVideo}),0!=this.metas.length?(this.ftyp_moov=$a.generateInitSegment(this.metas),this.onInitSegment&&0==this.loadmetadata&&(this.onInitSegment(this.ftyp_moov),this.loadmetadata=!0)):this.metaSuccRun=!0}},{key:"onDataAvailable",value:function(e,t){try{this.m4mof.remux(e,t)}catch(e){this.error(e)}}},{key:"setflv",value:function(e,t){return this.setflvBase(e,t)}},{key:"setflvloc",value:function(e){Ya.setFlv(new Uint8Array(e));if(Ya.arrTag.length>0)return Ya.arrTag}},{key:"error",value:function(e){this._error&&this._error(e)}}]),e}(),io=function(e){function t(e){Ye(this,t);var r=ya(this,(t.__proto__||ga(t)).call(this));return r.f2m=new ro(e),r.f2m._error=r.error,r._onInitSegment=null,r._onMediaSegment=null,r._onMediaInfo=null,r._seekCallBack=null,r}return ka(t,la),mt(t,[{key:"error",value:function(e){this.emit("error",e.type)}},{key:"seek",value:function(e){this.f2m.seek(e)}},{key:"setflv",value:function(e){return this.f2m.setflv(e,0)}},{key:"setflvloc",value:function(e){return this.f2m.setflvloc(e)}},{key:"onInitSegment",set:function(e){this._onInitSegment=e,this.f2m.onInitSegment=e}},{key:"onMediaSegment",set:function(e){this._onMediaSegment=e,this.f2m.onMediaSegment=e}},{key:"onMediaInfo",set:function(e){this._onMediaInfo=e,this.f2m.onMediaInfo=e}},{key:"seekCallBack",set:function(e){this._seekCallBack=e,this.f2m.seekCallBack=e}}]),t}(),no=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.config={},i.tag="transmuxer",i.loader=null,i.CPU=null,i.keyframePoint=!1,i.w=null,ia(i.config,r),i.config.webWorker&&(i.w=Pa("./transmuxer-worker"),i.w.postMessage({cmd:"init"}),i.w.addEventListener("message",function(e){i.parseCallback(e.data)})),i}return ka(t,la),mt(t,[{key:"loadSource",value:function(){this.config.webWorker?this.w.postMessage({cmd:"loadSource"}):(this.loader=new Ba(this.config),this.loader.arrivalDataCallback=this.arrivalDataCallback.bind(this),this.loader.open())}},{key:"arrivalDataCallback",value:function(e,t,r){return this.CPU||(this.CPU=new io,this.CPU.onInitSegment=this.onRemuxerInitSegmentArrival.bind(this),this.CPU.onMediaSegment=this.onRemuxerMediaSegmentArrival.bind(this),this.CPU.onError=this.onCPUError.bind(this),this.CPU.onMediaInfo=this.onMediaInfo.bind(this),this.CPU.seekCallBack=this.seekCallBack.bind(this)),r&&(this.keyframePoint=!0,this.CPU.seek(r)),this.CPU.setflv(e)}},{key:"parseCallback",value:function(e){switch(e.cmd){case"pipeCallback":e.source;break;case"mediaSegmentInit":this.emit("mediaSegmentInit",e.source);break;case"mediaSegment":this.emit("mediaSegment",e.source);break;case"mediainfo":this.emit("mediainfo",e.source)}}},{key:"onDemuxError",value:function(e,t){Ui.error(this.tag,"DemuxError: type = "+e+", info = "+t),this.emit("DemuxError",e,t)}},{key:"onMediaInfo",value:function(e,t){this.mediaInfo=e,this.emit("mediaInfo",e)}},{key:"seekCallBack",value:function(e){}},{key:"onRemuxerInitSegmentArrival",value:function(e){this.emit("mediaSegmentInit",e)}},{key:"onRemuxerMediaSegmentArrival",value:function(e){this.emit("mediaSegment",e)}},{key:"onCPUError",value:function(e){this.emit("ERROR",e.data)}},{key:"getMediaInfo",value:function(){return this.mediaInfo}},{key:"pause",value:function(){this.loader.pause()}},{key:"resume",value:function(){this.loader.resume()}},{key:"isSeekable",value:function(){return this.mediaInfo.hasKeyframesIndex}},{key:"seek",value:function(e){if(!this.isSeekable())return this.emit("ERROR","这个flv视频不支持seek"),!1;this.loader=new Ba(this.config),this.loader.arrivalDataCallback=this.arrivalDataCallback.bind(this),this.loader.seek(e.keyframePoint,!1,e.keyframetime)}},{key:"destroy",value:function(){this.loader.destroy(),this.loader=null,this.CPU=null}},{key:"getNearlestKeyframe",value:function(e){if(this.mediaInfo&&this.mediaInfo.keyframesIndex){var t=this.mediaInfo.keyframesIndex.times,r=this.mediaInfo.keyframesIndex.filepositions;return function e(i,n){var a=i.length,o=Math.floor(a/2);if(1===a){var s=t.indexOf(i[0]);return{keyframetime:i[0],keyframePoint:r[s]}}if(i[o]>n)return e(i.slice(0,o),n);if(i[o]<n)return e(i.slice(o),n);var u=t.indexOf(i[0]);return{keyframetime:i[0],keyframePoint:r[u]}}(t,e)}return 0}}]),t}(),ao={type:"vod",autoPlay:!1,box:"flv",prestrain:30,alwaysSeekKeyframe:!0,lazyLoadMaxDuration:120,lazyLoadRecoverDuration:30,lockInternalProperty:!1,debug:!0,webWorker:!1,autoCleanupSourceBuffer:!0},oo=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.tag="FLV-player",i.video=e,i.box="flv",i.config=ao,i.timer=null,E(i.config,r),i.requestSetTime=!1,i.bindEvents(),i.attachMedia(),i}return ka(t,la),mt(t,[{key:"internalPropertyHandle",value:function(){if(Aa){var e=this,t=Aa(HTMLMediaElement.prototype,"currentTime");Object.defineProperty(this.video,"currentTime",{get:function(){return t.get.call(e.video)},set:function(r){if(e.currentTimeLock)return t.set.call(e.video,r);throw new Error("can not set currentTime by youself")}})}}},{key:"bindEvents",value:function(){var e=this;this.video&&this.video.addEventListener("canplay",function(){"live"===e.config.type&&e.video.play(),e.config.lockInternalProperty&&e.internalPropertyHandle()})}},{key:"attachMedia",value:function(){var e=this;this.mediaSource=new Ca(this.video,this.config),this.mediaSource.on("source_open",function(){e.transmuxer.loadSource()}),this.mediaSource.on("bufferFull",function(){e.pauseTransmuxer()}),this.mediaSource.on("mediaInfo",function(t){e.emit("mediaInfo",t)}),this.mediaSource.on("updateend",this.onmseUpdateEnd.bind(this))}},{key:"load",value:function(){var e=this;this.video.src=URL.createObjectURL(this.mediaSource.mediaSource),this.video.addEventListener("seeking",O(this._seek.bind(this),200,{leading:!1})),this.transmuxer=new no(this.mediaSource,this.config),this.transmuxer.on("mediaSegment",function(t){e.mediaSource.emit("mediaSegment",t.data)}),this.transmuxer.on("mediaSegmentInit",function(t){e.mediaSource.emit("mediaSegmentInit",t.data)}),this.transmuxer.on("error",function(t){e.emit("error",t.data)})}},{key:"isTimeinBuffered",value:function(e){for(var t=this.video.buffered,r=0;r<t.length;r++){var i=t.start(r),n=t.end(r);if(e>=i&&e<n)return!0}return!1}},{key:"getCurrentBufferEnd",value:function(){for(var e=this.video.buffered,t=this.video.currentTime,r=0;r<e.length;r++){var i=e.start(r),n=e.end(r);if(i<=t&&t<n)return n}}},{key:"_seek",value:function(e,t){this.currentTimeLock=!0,this.timer=null;var r=t||this.video.currentTime;if(this.requestSetTime)return this.requestSetTime=!1,void(this.currentTimeLock=!1);if(this.isTimeinBuffered(r)){if(this.config.alwaysSeekKeyframe){var i=this.transmuxer.getNearlestKeyframe(Math.floor(1e3*r));i&&(this.requestSetTime=!0,this.video.currentTime=i.keyframetime/1e3)}}else{this.transmuxer.pause();var n=this.transmuxer.getNearlestKeyframe(Math.floor(1e3*r));r=n.keyframetime/1e3,this.transmuxer.seek(n),this.mediaSource.seek(r),this.requestSetTime=!0,this.video.currentTime=r,window.clearInterval(this.timer),this.timer=null}return this.currentTimeLock=!1,r}},{key:"onmseUpdateEnd",value:function(){this.config.isLive||this.getCurrentBufferEnd()>=this.video.currentTime+this.config.lazyLoadMaxDuration&&null===this.timer&&(Ui.verbose(this.tag,"Maximum buffering duration exceeded, suspend transmuxing task"),this.pauseTransmuxer())}},{key:"heartbeat",value:function(){for(var e=this.video.currentTime,t=this.video.buffered,r=!1,i=0;i<t.length;i++){var n=t.start(i),a=t.end(i);if(e>=n&&e<a){e>=a-this.config.lazyLoadRecoverDuration&&(r=!0);break}}r&&(window.clearInterval(this.timer),this.timer=null,Ui.verbose(this.TAG,"Continue loading from paused position"),this.transmuxer.resume())}},{key:"pauseTransmuxer",value:function(){this.transmuxer.pause(),this.timer||(this.timer=setInterval(this.heartbeat.bind(this),1e3))}},{key:"resume",value:function(){}},{key:"destroy",value:function(){this.video&&(this.video.src="",this.video.removeAttribute("src"),this.transmuxer.destroy(),this.transmuxer=null,this.mediaSource.destroy(),this.mediaSource=null)}},{key:"seek",value:function(e){return this._seek(null,e)}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}}]),t}(),so=function(e){return e&&e.__esModule?e.default:e}(function(e,t){return t={exports:{}},e(t,t.exports),t.exports}(function(e,t){!function(t){e.exports=t()}(function(){return function e(t,r,i){function n(o,s){if(!r[o]){if(!t[o]){var u="function"==typeof re&&re;if(!s&&u)return u(o,!0);if(a)return a(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var f=r[o]={exports:{}};t[o][0].call(f.exports,function(e){var r=t[o][1][e];return n(r||e)},f,f.exports,e,t,r,i)}return r[o].exports}for(var a="function"==typeof re&&re,o=0;o<i.length;o++)n(i[o]);return n}({1:[function(e,t,r){function i(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function a(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=i,i.EventEmitter=i,i.prototype._events=void 0,i.prototype._maxListeners=void 0,i.defaultMaxListeners=10,i.prototype.setMaxListeners=function(e){if(!a(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},i.prototype.emit=function(e){var t,r,i,a,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var f=new Error('Uncaught, unspecified "error" event. ('+t+")");throw f.context=t,f}if(r=this._events[e],s(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(o(r))for(a=Array.prototype.slice.call(arguments,1),i=(l=r.slice()).length,u=0;u<i;u++)l[u].apply(this,a);return!0},i.prototype.addListener=function(e,t){var r;if(!n(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,n(t.listener)?t.listener:t),this._events[e]?o(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,o(this._events[e])&&!this._events[e].warned&&(r=s(this._maxListeners)?i.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},i.prototype.on=i.prototype.addListener,i.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},i.prototype.removeListener=function(e,t){var r,i,a,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],a=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},i.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},i.prototype.listeners=function(e){return this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},i.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},i.listenerCount=function(e,t){return e.listenerCount(t)}},{}],2:[function(e,t,r){!function(e){var i=/^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,n=/^([^\/;?#]*)(.*)$/,a=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,s={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=this.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");return i.path=s.normalizePath(i.path),s.buildURLFromParts(i)}var a=this.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=this.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var u=n.exec(o.path);o.netLoc=u[1],o.path=u[2]}o.netLoc&&!o.path&&(o.path="/");var l={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var f=o.path,c=f.substring(0,f.lastIndexOf("/")+1)+a.path;l.path=s.normalizePath(c)}else l.path=o.path,a.params||(l.params=o.params,a.query||(l.query=o.query));return null===l.path&&(l.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(l)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(a,"");e.length!==(e=e.replace(o,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};"object"==typeof r&&"object"==typeof t?t.exports=s:"object"==typeof r?r.URLToolkit=s:e.URLToolkit=s}(this)},{}],3:[function(e,t,r){var i=arguments[3],n=arguments[4],a=arguments[5],o=JSON.stringify;t.exports=function(e,t){function r(e){g[e]=!0;for(var t in n[e][1]){var i=n[e][1][t];g[i]||r(i)}}for(var s,u=Object.keys(a),l=0,f=u.length;l<f;l++){var c=u[l],d=a[c].exports;if(d===e||d&&d.default===e){s=c;break}}if(!s){s=Math.floor(Math.pow(16,8)*Math.random()).toString(16);for(var h={},l=0,f=u.length;l<f;l++)h[c=u[l]]=c;n[s]=[Function(["require","module","exports"],"("+e+")(self)"),h]}var v=Math.floor(Math.pow(16,8)*Math.random()).toString(16),p={};p[s]=s,n[v]=[Function(["require"],"var f = require("+o(s)+");(f.default ? f.default : f)(self);"),p];var g={};r(v);var y="("+i+")({"+Object.keys(g).map(function(e){return o(e)+":["+n[e][0]+","+o(n[e][1])+"]"}).join(",")+"},{},["+o(v)+"])",m=window.URL||window.webkitURL||window.mozURL||window.msURL,b=new Blob([y],{type:"text/javascript"});if(t&&t.bare)return b;var _=m.createObjectURL(b),E=new Worker(_);return E.objectURL=_,E}},{}],4:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0}),r.hlsDefaultConfig=void 0;var n=i(e(5)),a=i(e(8)),o=i(e(9)),s=i(e(10)),u=i(e(59)),l=i(e(7)),f=i(e(6)),c=i(e(50)),d=i(e(16)),h=i(e(15)),v=i(e(14));r.hlsDefaultConfig={autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,maxSeekHole:2,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,startLevel:void 0,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,fragLoadingLoopThreshold:3,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:u.default,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,fetchSetup:void 0,abrController:n.default,bufferController:a.default,capLevelController:o.default,fpsController:s.default,audioStreamController:f.default,audioTrackController:l.default,subtitleStreamController:v.default,subtitleTrackController:h.default,timelineController:d.default,cueHandler:c.default,enableCEA708Captions:!0,enableWebVTT:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",stretchShortVideoTrack:!1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0}},{10:10,14:14,15:15,16:16,5:5,50:50,59:59,6:6,7:7,8:8,9:9}],5:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=i(e(37)),c=e(33),d=e(54),h=i(e(52)),v=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.FRAG_LOADING,u.default.FRAG_LOADED,u.default.FRAG_BUFFERED,u.default.ERROR));return r.lastLoadedFragLevel=0,r._nextAutoLevel=-1,r.hls=e,r.timer=null,r._bwEstimator=null,r.onCheck=r._abandonRulesCheck.bind(r),r}return o(t,l.default),s(t,[{key:"destroy",value:function(){this.clearTimer(),l.default.prototype.destroy.call(this)}},{key:"onFragLoading",value:function(e){var t=e.frag;if("main"===t.type){if(this.timer||(this.timer=setInterval(this.onCheck,100)),!this._bwEstimator){var r=this.hls,i=e.frag.level,n=r.levels[i].details.live,a=r.config,o=void 0,s=void 0;n?(o=a.abrEwmaFastLive,s=a.abrEwmaSlowLive):(o=a.abrEwmaFastVoD,s=a.abrEwmaSlowVoD),this._bwEstimator=new h.default(r,s,o,a.abrEwmaDefaultEstimate)}this.fragCurrent=t}}},{key:"_abandonRulesCheck",value:function(){var e=this.hls,t=e.media,r=this.fragCurrent,i=r.loader,n=e.minAutoLevel;if(!i||i.stats&&i.stats.aborted)return d.logger.warn("frag loader destroy or aborted, disarm abandonRules"),void this.clearTimer();var a=i.stats;if(t&&(!t.paused&&0!==t.playbackRate||!t.readyState)&&r.autoLevel&&r.level){var o=performance.now()-a.trequest,s=Math.abs(t.playbackRate);if(o>500*r.duration/s){var l=e.levels,c=Math.max(1,a.bw?a.bw/8:1e3*a.loaded/o),h=l[r.level],v=h.realBitrate?Math.max(h.realBitrate,h.bitrate):h.bitrate,p=a.total?a.total:Math.max(a.loaded,Math.round(r.duration*v/8)),g=t.currentTime,y=(p-a.loaded)/c,m=(f.default.bufferInfo(t,g,e.config.maxBufferHole).end-g)/s;if(m<2*r.duration/s&&y>m){var b=void 0,_=void 0;for(_=r.level-1;_>n;_--){var E=l[_].realBitrate?Math.max(l[_].realBitrate,l[_].bitrate):l[_].bitrate;if((b=r.duration*E/(6.4*c))<m)break}b<y&&(d.logger.warn("loading too slow, abort fragment loading and switch to level "+_+":fragLoadedDelay["+_+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+b.toFixed(1)+"<"+y.toFixed(1)+":"+m.toFixed(1)),e.nextLoadLevel=_,this._bwEstimator.sample(o,a.loaded),i.abort(),this.clearTimer(),e.trigger(u.default.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,stats:a}))}}}}},{key:"onFragLoaded",value:function(e){var t=e.frag;if("main"===t.type&&!isNaN(t.sn)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var r=this.hls.levels[t.level],i=(r.loaded?r.loaded.bytes:0)+e.stats.loaded,n=(r.loaded?r.loaded.duration:0)+e.frag.duration;r.loaded={bytes:i,duration:n},r.realBitrate=Math.round(8*i/n)}if(e.frag.bitrateTest){var a=e.stats;a.tparsed=a.tbuffered=a.tload,this.onFragBuffered(e)}}}},{key:"onFragBuffered",value:function(e){var t=e.stats,r=e.frag;if(!(!0===t.aborted||1!==r.loadCounter||"main"!==r.type||isNaN(r.sn)||r.bitrateTest&&t.tload!==t.tbuffered)){var i=t.tparsed-t.trequest;d.logger.log("latency/loading/parsing/append/kbps:"+Math.round(t.tfirst-t.trequest)+"/"+Math.round(t.tload-t.tfirst)+"/"+Math.round(t.tparsed-t.tload)+"/"+Math.round(t.tbuffered-t.tparsed)+"/"+Math.round(8*t.loaded/(t.tbuffered-t.trequest))),this._bwEstimator.sample(i,t.loaded),t.bwEstimate=this._bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}}},{key:"onError",value:function(e){switch(e.details){case c.ErrorDetails.FRAG_LOAD_ERROR:case c.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}}},{key:"clearTimer",value:function(){clearInterval(this.timer),this.timer=null}},{key:"_findBestLevel",value:function(e,t,r,i,n,a,o,s,u){for(var l=n;l>=i;l--){var f=u[l].details,c=f?f.totalduration/f.fragments.length:t,h=!!f&&f.live,v=void 0;v=l<=e?o*r:s*r;var p=u[l].realBitrate?Math.max(u[l].realBitrate,u[l].bitrate):u[l].bitrate,g=p*c/v;if(d.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+l+"/"+Math.round(v)+"/"+p+"/"+c+"/"+a+"/"+g),v>p&&(!g||h&&!this.bitrateTestDelay||g<a))return l}return-1}},{key:"nextAutoLevel",get:function(){var e=this._nextAutoLevel,t=this._bwEstimator;if(!(-1===e||t&&t.canEstimate()))return e;var r=this._nextABRAutoLevel;return-1!==e&&(r=Math.min(e,r)),r},set:function(e){this._nextAutoLevel=e}},{key:"_nextABRAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.levels,i=e.config,n=e.minAutoLevel,a=e.media,o=this.lastLoadedFragLevel,s=this.fragCurrent?this.fragCurrent.duration:0,u=a?a.currentTime:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,c=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,h=(f.default.bufferInfo(a,u,i.maxBufferHole).end-u)/l,v=this._findBestLevel(o,s,c,n,t,h,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(v>=0)return v;d.logger.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var p=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay,g=i.abrBandWidthFactor,y=i.abrBandWidthUpFactor;if(0===h){var m=this.bitrateTestDelay;m&&(p=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-m,d.logger.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*p)+" ms"),g=y=1)}return v=this._findBestLevel(o,s,c,n,t,h+p,g,y,r),Math.max(v,0)}}]),t}();r.default=v},{33:33,34:34,35:35,37:37,52:52,54:54}],6:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(48)),l=i(e(37)),f=i(e(25)),c=i(e(35)),d=i(e(34)),h=i(e(38)),v=i(e(55)),p=e(33),g=e(54),y=e(51),m={STOPPED:"STOPPED",STARTING:"STARTING",IDLE:"IDLE",PAUSED:"PAUSED",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",BUFFER_FLUSHING:"BUFFER_FLUSHING",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS"},b=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,c.default.MEDIA_ATTACHED,c.default.MEDIA_DETACHING,c.default.AUDIO_TRACKS_UPDATED,c.default.AUDIO_TRACK_SWITCHING,c.default.AUDIO_TRACK_LOADED,c.default.KEY_LOADED,c.default.FRAG_LOADED,c.default.FRAG_PARSING_INIT_SEGMENT,c.default.FRAG_PARSING_DATA,c.default.FRAG_PARSED,c.default.ERROR,c.default.BUFFER_CREATED,c.default.BUFFER_APPENDED,c.default.BUFFER_FLUSHED,c.default.INIT_PTS_FOUND));return r.config=e.config,r.audioCodecSwap=!1,r.ticks=0,r._state=m.STOPPED,r.ontick=r.tick.bind(r),r.initPTS=[],r.waitingFragment=null,r.videoTrackCC=null,r}return o(t,d.default),s(t,[{key:"destroy",value:function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),d.default.prototype.destroy.call(this),this.state=m.STOPPED}},{key:"onInitPtsFound",value:function(e){var t=e.id,r=e.frag.cc,i=e.initPTS;"main"===t&&(this.initPTS[r]=i,this.videoTrackCC=r,g.logger.log("InitPTS for cc:"+r+" found from video track:"+i),this.state===m.WAITING_INIT_PTS&&this.tick())}},{key:"startLoad",value:function(e){if(this.tracks){var t=this.lastCurrentTime;this.stopLoad(),this.timer||(this.timer=setInterval(this.ontick,100)),this.fragLoadError=0,t>0&&-1===e?(g.logger.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=m.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=m.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=m.STOPPED}},{key:"stopLoad",value:function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=m.STOPPED}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){var e,t,r,i=this.hls,n=i.config;switch(this.state){case m.ERROR:case m.PAUSED:case m.BUFFER_FLUSHING:break;case m.STARTING:this.state=m.WAITING_TRACK,this.loadedmetadata=!1;break;case m.IDLE:var a=this.tracks;if(!a)break;if(!this.media&&(this.startFragRequested||!n.startFragPrefetch))break;if(this.loadedmetadata)e=this.media.currentTime;else if(void 0===(e=this.nextLoadPosition))break;var o=this.mediaBuffer?this.mediaBuffer:this.media,s=l.default.bufferInfo(o,e,n.maxBufferHole),f=s.len,d=s.end,h=this.fragPrevious,v=n.maxMaxBufferLength,b=this.audioSwitch,_=this.trackId;if((f<v||b)&&_<a.length){if(void 0===(r=a[_].details)){this.state=m.WAITING_TRACK;break}if(!b&&!r.live&&h&&h.sn===r.endSN&&(!this.media.seeking||this.media.duration-d<h.duration/2)){this.hls.trigger(c.default.BUFFER_EOS,{type:"audio"}),this.state=m.ENDED;break}var E=r.fragments,k=E.length,w=E[0].start,S=E[k-1].start+E[k-1].duration,T=void 0;if(b)if(r.live&&!r.PTSKnown)g.logger.log("switching audiotrack, live stream, unknown PTS,load first fragment"),d=0;else if(d=e,r.PTSKnown&&e<w){if(!(s.end>w||s.nextStart))return;g.logger.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=w+.05}if(r.initSegment&&!r.initSegment.data)T=r.initSegment;else if(d<=w){if(T=E[0],null!==this.videoTrackCC&&T.cc!==this.videoTrackCC&&(T=(0,y.findFragWithCC)(E,this.videoTrackCC)),r.live&&T.loadIdx&&T.loadIdx===this.fragLoadIdx){var A=s.nextStart?s.nextStart:w;return g.logger.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(A+.05)),void(this.media.currentTime=A+.05)}}else{var R=void 0,L=n.maxFragLookUpTolerance,O=h?E[h.sn-E[0].sn+1]:void 0,D=function(e){var t=Math.min(L,e.duration);return e.start+e.duration-t<=d?1:e.start-t>d&&e.start?-1:0};d<S?(d>S-L&&(L=0),R=O&&!D(O)?O:u.default.search(E,D)):R=E[k-1],R&&(T=R,w=R.start,h&&T.level===h.level&&T.sn===h.sn&&(T.sn<r.endSN?(T=E[T.sn+1-r.startSN],g.logger.log("SN just loaded, load next one: "+T.sn)):T=null))}if(T)if(T.decryptdata&&null!=T.decryptdata.uri&&null==T.decryptdata.key)g.logger.log("Loading key for "+T.sn+" of ["+r.startSN+" ,"+r.endSN+"],track "+_),this.state=m.KEY_LOADING,i.trigger(c.default.KEY_LOADING,{frag:T});else{if(g.logger.log("Loading "+T.sn+", cc: "+T.cc+" of ["+r.startSN+" ,"+r.endSN+"],track "+_+", currentTime:"+e+",bufferEnd:"+d.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,T.loadCounter){T.loadCounter++;var P=n.fragLoadingLoopThreshold;if(T.loadCounter>P&&Math.abs(this.fragLoadIdx-T.loadIdx)<P)return void i.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:T})}else T.loadCounter=1;T.loadIdx=this.fragLoadIdx,this.fragCurrent=T,this.startFragRequested=!0,isNaN(T.sn)||(this.nextLoadPosition=T.start+T.duration),i.trigger(c.default.FRAG_LOADING,{frag:T}),this.state=m.FRAG_LOADING}}break;case m.WAITING_TRACK:(t=this.tracks[this.trackId])&&t.details&&(this.state=m.IDLE);break;case m.FRAG_LOADING_WAITING_RETRY:var x=performance.now(),I=this.retryDate,C=(o=this.media)&&o.seeking;(!I||x>=I||C)&&(g.logger.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=m.IDLE);break;case m.WAITING_INIT_PTS:if(void 0===this.initPTS[this.videoTrackCC])break;var M=this.waitingFragment;if(M){var F=M.frag.cc;this.videoTrackCC!==F?(g.logger.warn("Waiting fragment CC ("+F+") does not match video track CC ("+this.videoTrackCC+")"),this.waitingFragment=null,this.state=m.IDLE):(this.state=m.FRAG_LOADING,this.onFragLoaded(this.waitingFragment),this.waitingFragment=null)}else this.state=m.IDLE;break;case m.STOPPED:case m.FRAG_LOADING:case m.PARSING:case m.PARSED:case m.ENDED:}}},{key:"onMediaAttached",value:function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(g.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.tracks;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){this.state===m.ENDED&&(this.state=m.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()}},{key:"onMediaEnded",value:function(){this.startPosition=this.lastCurrentTime=0}},{key:"onAudioTracksUpdated",value:function(e){g.logger.log("audio tracks updated"),this.tracks=e.audioTracks}},{key:"onAudioTrackSwitching",value:function(e){var t=!!e.url;this.trackId=e.id,this.fragCurrent=null,this.state=m.PAUSED,this.waitingFragment=null,t?this.timer||(this.timer=setInterval(this.ontick,100)):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),t&&(this.audioSwitch=!0,this.state=m.IDLE,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold)),this.tick()}},{key:"onAudioTrackLoaded",value:function(e){var t=e.details,r=e.id,i=this.tracks[r],n=t.totalduration,a=0;if(g.logger.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+n),t.live){var o=i.details;o&&t.fragments.length>0?(h.default.mergeDetails(o,t),a=t.fragments[0].start,t.PTSKnown?g.logger.log("live audio playlist sliding:"+a.toFixed(3)):g.logger.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,g.logger.log("live audio playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,!this.startFragRequested){if(-1===this.startPosition){var s=t.startTimeOffset;isNaN(s)?this.startPosition=0:(g.logger.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s)}this.nextLoadPosition=this.startPosition}this.state===m.WAITING_TRACK&&(this.state=m.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===m.KEY_LOADING&&(this.state=m.IDLE,this.tick())}},{key:"onFragLoaded",value:function(e){var t=this.fragCurrent,r=e.frag;if(this.state===m.FRAG_LOADING&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var i=this.tracks[this.trackId],n=i.details,a=n.totalduration,o=t.level,s=t.sn,u=t.cc,l=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",d=this.stats=e.stats;if("initSegment"===s)this.state=m.IDLE,d.tparsed=d.tbuffered=performance.now(),n.initSegment.data=e.payload,this.hls.trigger(c.default.FRAG_BUFFERED,{stats:d,frag:t,id:"audio"}),this.tick();else{this.state=m.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new f.default(this.hls,"audio"));var h=this.initPTS[u],v=n.initSegment?n.initSegment.data:[];if(n.initSegment||void 0!==h){this.pendingBuffering=!0,g.logger.log("Demuxing "+s+" of ["+n.startSN+" ,"+n.endSN+"],track "+o);this.demuxer.push(e.payload,v,l,null,t,a,!1,h)}else g.logger.log("unknown video PTS for continuity counter "+u+", waiting for video PTS before demuxing audio frag "+s+" of ["+n.startSN+" ,"+n.endSN+"],track "+o),this.waitingFragment=e,this.state=m.WAITING_INIT_PTS}}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===m.PARSING){var i=e.tracks,n=void 0;if(i.video&&delete i.video,n=i.audio){n.levelCodec=n.codec,n.id=e.id,this.hls.trigger(c.default.BUFFER_CODECS,i),g.logger.log("audio track:audio,container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var a=n.initSegment;if(a){var o={type:"audio",data:a,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[o]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(c.default.BUFFER_APPENDING,o))}this.tick()}}}},{key:"onFragParsingData",value:function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"audio"===e.id&&"audio"===e.type&&i.sn===r.sn&&i.level===r.level&&this.state===m.PARSING){var n=this.trackId,a=this.tracks[n],o=this.hls;isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),g.logger.log("parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb),h.default.updateFragPTSDTS(a.details,r,e.startPTS,e.endPTS);var s=this.audioSwitch,u=this.media,l=!1;if(s&&u)if(u.readyState){var f=u.currentTime;g.logger.log("switching audio track : currentTime:"+f),f>=e.startPTS&&(g.logger.log("switching audio track : flushing all audio"),this.state=m.BUFFER_FLUSHING,o.trigger(c.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),l=!0,this.audioSwitch=!1,o.trigger(c.default.AUDIO_TRACK_SWITCHED,{id:n}))}else this.audioSwitch=!1,o.trigger(c.default.AUDIO_TRACK_SWITCHED,{id:n});var d=this.pendingData;this.audioSwitch||([e.data1,e.data2].forEach(function(t){t&&t.length&&d.push({type:e.type,data:t,parent:"audio",content:"data"})}),!l&&d.length&&(d.forEach(function(e){t.state===m.PARSING&&(t.pendingBuffering=!0,t.hls.trigger(c.default.BUFFER_APPENDING,e))}),this.pendingData=[],this.appended=!0)),this.tick()}}},{key:"onFragParsed",value:function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===m.PARSING&&(this.stats.tparsed=performance.now(),this.state=m.PARSED,this._checkAppendedParsed())}},{key:"onBufferCreated",value:function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0)}},{key:"onBufferAppended",value:function(e){if("audio"===e.parent){var t=this.state;t!==m.PARSING&&t!==m.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}}},{key:"_checkAppendedParsed",value:function(){if(!(this.state!==m.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent,t=this.stats,r=this.hls;if(e){this.fragPrevious=e,t.tbuffered=performance.now(),r.trigger(c.default.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;g.logger.log("audio buffered : "+v.default.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(c.default.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=m.IDLE}this.tick()}}},{key:"onError",value:function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case p.ErrorDetails.FRAG_LOAD_ERROR:case p.ErrorDetails.FRAG_LOAD_TIMEOUT:if(!e.fatal){var r=this.fragLoadError;r?r++:r=1;var i=this.config;if(r<=i.fragLoadingMaxRetry){this.fragLoadError=r,t.loadCounter=0;var n=Math.min(Math.pow(2,r-1)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);g.logger.warn("audioStreamController: frag loading failed, retry in "+n+" ms"),this.retryDate=performance.now()+n,this.state=m.FRAG_LOADING_WAITING_RETRY}else g.logger.error("audioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=m.ERROR}break;case p.ErrorDetails.FRAG_LOOP_LOADING_ERROR:case p.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case p.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case p.ErrorDetails.KEY_LOAD_ERROR:case p.ErrorDetails.KEY_LOAD_TIMEOUT:this.state!==m.ERROR&&(this.state=e.fatal?m.ERROR:m.IDLE,g.logger.warn("audioStreamController: "+e.details+" while loading frag,switch to "+this.state+" state ..."));break;case p.ErrorDetails.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===m.PARSING||this.state===m.PARSED)){var a=this.mediaBuffer,o=this.media.currentTime;if(a&&l.default.isBuffered(a,o)&&l.default.isBuffered(a,o+.5)){var s=this.config;s.maxMaxBufferLength>=s.maxBufferLength&&(s.maxMaxBufferLength/=2,g.logger.warn("audio:reduce max buffer length to "+s.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*s.fragLoadingLoopThreshold),this.state=m.IDLE}else g.logger.warn("buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=m.BUFFER_FLUSHING,this.hls.trigger(c.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}}},{key:"onBufferFlushed",value:function(){var e=this,t=this.pendingData;t&&t.length?(g.logger.log("appending pending audio data on Buffer Flushed"),t.forEach(function(t){e.hls.trigger(c.default.BUFFER_APPENDING,t)}),this.appended=!0,this.pendingData=[],this.state=m.PARSED):(this.state=m.IDLE,this.fragPrevious=null,this.tick())}},{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,g.logger.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}]),t}();r.default=b},{25:25,33:33,34:34,35:35,37:37,38:38,48:48,51:51,54:54,55:55}],7:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(54),c=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.MANIFEST_LOADING,u.default.MANIFEST_LOADED,u.default.AUDIO_TRACK_LOADED));return r.ticks=0,r.ontick=r.tick.bind(r),r}return o(t,l.default),s(t,[{key:"destroy",value:function(){l.default.prototype.destroy.call(this)}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){this.updateTrack(this.trackId)}},{key:"onManifestLoading",value:function(){this.tracks=[],this.trackId=-1}},{key:"onManifestLoaded",value:function(e){var t=this,r=e.audioTracks||[],i=!1;this.tracks=r,this.hls.trigger(u.default.AUDIO_TRACKS_UPDATED,{audioTracks:r});var n=0;r.forEach(function(e){if(e.default)return t.audioTrack=n,void(i=!0);n++}),!1===i&&r.length&&(f.logger.log("no default audio track defined, use first audio track as default"),this.audioTrack=0)}},{key:"onAudioTrackLoaded",value:function(e){e.id<this.tracks.length&&(f.logger.log("audioTrack "+e.id+" loaded"),this.tracks[e.id].details=e.details,e.details.live&&!this.timer&&(this.timer=setInterval(this.ontick,1e3*e.details.targetduration)),!e.details.live&&this.timer&&(clearInterval(this.timer),this.timer=null))}},{key:"setAudioTrackInternal",value:function(e){if(e>=0&&e<this.tracks.length){this.timer&&(clearInterval(this.timer),this.timer=null),this.trackId=e,f.logger.log("switching to audioTrack "+e);var t=this.tracks[e],r=this.hls,i=t.type,n=t.url,a={id:e,type:i,url:n};r.trigger(u.default.AUDIO_TRACK_SWITCH,a),r.trigger(u.default.AUDIO_TRACK_SWITCHING,a);var o=t.details;!n||void 0!==o&&!0!==o.live||(f.logger.log("(re)loading playlist for audioTrack "+e),r.trigger(u.default.AUDIO_TRACK_LOADING,{url:n,id:e}))}}},{key:"updateTrack",value:function(e){if(e>=0&&e<this.tracks.length){this.timer&&(clearInterval(this.timer),this.timer=null),this.trackId=e,f.logger.log("updating audioTrack "+e);var t=this.tracks[e],r=t.url,i=t.details;!r||void 0!==i&&!0!==i.live||(f.logger.log("(re)loading playlist for audioTrack "+e),this.hls.trigger(u.default.AUDIO_TRACK_LOADING,{url:r,id:e}))}}},{key:"audioTracks",get:function(){return this.tracks}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.trackId===e&&void 0!==this.tracks[e].details||this.setAudioTrackInternal(e)}}]),t}();r.default=c},{34:34,35:35,54:54}],8:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(54),c=e(33),d=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.MEDIA_ATTACHING,u.default.MEDIA_DETACHING,u.default.MANIFEST_PARSED,u.default.BUFFER_RESET,u.default.BUFFER_APPENDING,u.default.BUFFER_CODECS,u.default.BUFFER_EOS,u.default.BUFFER_FLUSHING,u.default.LEVEL_PTS_UPDATED,u.default.LEVEL_UPDATED));return r._msDuration=null,r._levelDuration=null,r.onsbue=r.onSBUpdateEnd.bind(r),r.onsbe=r.onSBUpdateError.bind(r),r.pendingTracks={},r.tracks={},r}return o(t,l.default),s(t,[{key:"destroy",value:function(){l.default.prototype.destroy.call(this)}},{key:"onLevelPtsUpdated",value:function(e){var t=e.type,r=this.tracks.audio;if("audio"===t&&r&&"audio/mpeg"===r.container){var i=this.sourceBuffer.audio;if(Math.abs(i.timestampOffset-e.start)>.1){var n=i.updating;try{i.abort()}catch(e){n=!0,f.logger.warn("can not abort audio buffer: "+e)}n?this.audioTimestampOffset=e.start:(f.logger.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}}},{key:"onManifestParsed",value:function(e){var t=e.audio,r=e.video,i=0;e.altAudio&&(t||r)&&(i=(t?1:0)+(r?1:0),f.logger.log(i+" sourceBuffer(s) expected")),this.sourceBufferNb=i}},{key:"onMediaAttaching",value:function(e){var t=this.media=e.media;if(t){var r=this.mediaSource=new MediaSource;this.onmso=this.onMediaSourceOpen.bind(this),this.onmse=this.onMediaSourceEnded.bind(this),this.onmsc=this.onMediaSourceClose.bind(this),r.addEventListener("sourceopen",this.onmso),r.addEventListener("sourceended",this.onmse),r.addEventListener("sourceclose",this.onmsc),t.src=URL.createObjectURL(r)}}},{key:"onMediaDetaching",value:function(){f.logger.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){f.logger.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this.onmso),e.removeEventListener("sourceended",this.onmse),e.removeEventListener("sourceclose",this.onmsc),this.media&&(URL.revokeObjectURL(this.media.src),this.media.removeAttribute("src"),this.media.load()),this.mediaSource=null,this.media=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(u.default.MEDIA_DETACHED)}},{key:"onMediaSourceOpen",value:function(){f.logger.log("media source opened"),this.hls.trigger(u.default.MEDIA_ATTACHED,{media:this.media});var e=this.mediaSource;e&&e.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()}},{key:"checkPendingTracks",value:function(){var e=this.pendingTracks,t=Object.keys(e).length;t&&(this.sourceBufferNb<=t||0===this.sourceBufferNb)&&(this.createSourceBuffers(e),this.pendingTracks={},this.doAppending())}},{key:"onMediaSourceClose",value:function(){f.logger.log("media source closed")}},{key:"onMediaSourceEnded",value:function(){f.logger.log("media source ended")}},{key:"onSBUpdateEnd",value:function(){if(this.audioTimestampOffset){var e=this.sourceBuffer.audio;f.logger.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+this.audioTimestampOffset),e.timestampOffset=this.audioTimestampOffset,delete this.audioTimestampOffset}this._needsFlush&&this.doFlush(),this._needsEos&&this.checkEos(),this.appending=!1;var t=this.parent,r=this.segments.reduce(function(e,r){return r.parent===t?e+1:e},0);this.hls.trigger(u.default.BUFFER_APPENDED,{parent:t,pending:r}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()}},{key:"onSBUpdateError",value:function(e){f.logger.error("sourceBuffer error:",e),this.hls.trigger(u.default.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})}},{key:"onBufferReset",value:function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this.onsbue),r.removeEventListener("error",this.onsbe)}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}},{key:"onBufferCodecs",value:function(e){if(0===Object.keys(this.sourceBuffer).length){for(var t in e)this.pendingTracks[t]=e[t];var r=this.mediaSource;r&&"open"===r.readyState&&this.checkPendingTracks()}}},{key:"createSourceBuffers",value:function(e){var t=this.sourceBuffer,r=this.mediaSource;for(var i in e)if(!t[i]){var n=e[i],a=n.levelCodec||n.codec,o=n.container+";codecs="+a;f.logger.log("creating sourceBuffer("+o+")");try{var s=t[i]=r.addSourceBuffer(o);s.addEventListener("updateend",this.onsbue),s.addEventListener("error",this.onsbe),this.tracks[i]={codec:a,container:n.container},n.buffer=s}catch(e){f.logger.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(u.default.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:o})}}this.hls.trigger(u.default.BUFFER_CREATED,{tracks:e})}},{key:"onBufferAppending",value:function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())}},{key:"onBufferAppendFail",value:function(e){f.logger.error("sourceBuffer error:",e.event),this.hls.trigger(u.default.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})}},{key:"onBufferEos",value:function(e){var t=this.sourceBuffer,r=e.type;for(var i in t)r&&i!==r||t[i].ended||(t[i].ended=!0,f.logger.log(i+" sourceBuffer now EOS"));this.checkEos()}},{key:"checkEos",value:function(){var e=this.sourceBuffer,t=this.mediaSource;if(t&&"open"===t.readyState){for(var r in e){var i=e[r];if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}f.logger.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){f.logger.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}else this._needsEos=!1}},{key:"onBufferFlushing",value:function(e){this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}),this.flushBufferCounter=0,this.doFlush()}},{key:"onLevelUpdated",value:function(e){var t=e.details;0!==t.fragments.length&&(this._levelDuration=t.totalduration+t.fragments[0].start,this.updateMediaElementDuration())}},{key:"updateMediaElementDuration",value:function(){var e=this.media,t=this.mediaSource,r=this.sourceBuffer,i=this._levelDuration;if(null!==i&&e&&t&&r&&0!==e.readyState&&"open"===t.readyState){for(var n in r)if(r[n].updating)return;null===this._msDuration&&(this._msDuration=t.duration);var a=e.duration;(i>this._msDuration&&i>a||a===1/0||isNaN(a))&&(f.logger.log("Updating mediasource duration to "+i.toFixed(3)),this._msDuration=t.duration=i)}}},{key:"doFlush",value:function(){for(;this.flushRange.length;){var e=this.flushRange[0];if(!this.flushBuffer(e.start,e.end,e.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var t=0,r=this.sourceBuffer;try{for(var i in r)t+=r[i].buffered.length}catch(e){f.logger.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(u.default.BUFFER_FLUSHED)}}},{key:"doAppending",value:function(){var e=this.hls,t=this.sourceBuffer,r=this.segments;if(Object.keys(t).length){if(this.media.error)return this.segments=[],void f.logger.error("trying to append although a media error occured, flush segment and abort");if(this.appending)return;if(r&&r.length){var i=r.shift();try{var n=t[i.type];n?n.updating?r.unshift(i):(n.ended=!1,this.parent=i.parent,n.appendBuffer(i.data),this.appendError=0,this.appended++,this.appending=!0):this.onSBUpdateEnd()}catch(t){f.logger.error("error while trying to append buffer:"+t.message),r.unshift(i);var a={type:c.ErrorTypes.MEDIA_ERROR,parent:i.parent};if(22===t.code)return this.segments=[],a.details=c.ErrorDetails.BUFFER_FULL_ERROR,a.fatal=!1,void e.trigger(u.default.ERROR,a);if(this.appendError?this.appendError++:this.appendError=1,a.details=c.ErrorDetails.BUFFER_APPEND_ERROR,this.appendError>e.config.appendErrorMaxRetry)return f.logger.log("fail "+e.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],a.fatal=!0,void e.trigger(u.default.ERROR,a);a.fatal=!1,e.trigger(u.default.ERROR,a)}}}}},{key:"flushBuffer",value:function(e,t,r){var i,n,a,o,s,u,l=this.sourceBuffer;if(Object.keys(l).length){if(f.logger.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+e+"/"+t),this.flushBufferCounter<this.appended){for(var c in l)if(!r||c===r){if(i=l[c],i.ended=!1,i.updating)return f.logger.warn("cannot flush, sb updating in progress"),!1;try{for(n=0;n<i.buffered.length;n++)if(a=i.buffered.start(n),o=i.buffered.end(n),-1!==navigator.userAgent.toLowerCase().indexOf("firefox")&&t===Number.POSITIVE_INFINITY?(s=e,u=t):(s=Math.max(a,e),u=Math.min(o,t)),Math.min(u,o)-s>.5)return this.flushBufferCounter++,f.logger.log("flush "+c+" ["+s+","+u+"], of ["+a+","+o+"], pos:"+this.media.currentTime),i.remove(s,u),!1}catch(e){f.logger.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else f.logger.warn("abort flushing too many retries");f.logger.log("buffer flushed")}return!0}}]),t}();r.default=d},{33:33,34:34,35:35,54:54}],9:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=function(e){function t(e){return n(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.FPS_DROP_LEVEL_CAPPING,u.default.MEDIA_ATTACHING,u.default.MANIFEST_PARSED))}return o(t,l.default),s(t,[{key:"destroy",value:function(){this.hls.config.capLevelToPlayerSize&&(this.media=this.restrictedLevels=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer)))}},{key:"onFpsDropLevelCapping",value:function(e){t.isLevelAllowed(e.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(e.droppedLevel)}},{key:"onMediaAttaching",value:function(e){this.media=e.media instanceof HTMLVideoElement?e.media:null}},{key:"onManifestParsed",value:function(e){var t=this.hls;this.restrictedLevels=[],t.config.capLevelToPlayerSize&&(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.levels=e.levels,t.firstLevel=this.getMaxLevel(e.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}},{key:"detectPlayerSize",value:function(){if(this.media){var e=this.levels?this.levels.length:0;if(e){var t=this.hls;t.autoLevelCapping=this.getMaxLevel(e-1),t.autoLevelCapping>this.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(e){var r=this;if(!this.levels)return-1;var i=this.levels.filter(function(i,n){return t.isLevelAllowed(n,r.restrictedLevels)&&n<=e});return t.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}},{key:"mediaWidth",get:function(){var e=void 0,r=this.media;return r&&(e=r.width||r.clientWidth||r.offsetWidth,e*=t.contentScaleFactor),e}},{key:"mediaHeight",get:function(){var e=void 0,r=this.media;return r&&(e=r.height||r.clientHeight||r.offsetHeight,e*=t.contentScaleFactor),e}}],[{key:"isLevelAllowed",value:function(e){return-1===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).indexOf(e)}},{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(!e||e&&!e.length)return-1;for(var i=e.length-1,n=0;n<e.length;n+=1){var a=e[n];if((a.width>=t||a.height>=r)&&function(e,t){return!t||e.width!==t.width||e.height!==t.height}(a,e[n+1])){i=n;break}}return i}},{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}]),t}();r.default=f},{34:34,35:35}],10:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(54),c=function(e){function t(e){return n(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.MEDIA_ATTACHING))}return o(t,l.default),s(t,[{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1}},{key:"onMediaAttaching",value:function(e){var t=this.hls.config;t.capLevelOnFPSDrop&&("function"==typeof(this.video=e.media instanceof HTMLVideoElement?e.media:null).getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),clearInterval(this.timer),this.timer=setInterval(this.checkFPSInterval.bind(this),t.fpsDroppedMonitoringPeriod))}},{key:"checkFPS",value:function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,o=t-this.lastDecodedFrames,s=1e3*a/n,l=this.hls;if(l.trigger(u.default.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:r}),s>0&&a>l.config.fpsDroppedMonitoringThreshold*o){var c=l.currentLevel;f.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=c)&&(c-=1,l.trigger(u.default.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:l.currentLevel}),l.autoLevelCapping=c,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.video;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}]),t}();r.default=c},{34:34,35:35,54:54}],11:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=i(e(27)),c=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.MEDIA_ATTACHED,u.default.MEDIA_DETACHING,u.default.FRAG_PARSING_METADATA));return r.id3Track=void 0,r.media=void 0,r}return o(t,l.default),s(t,[{key:"destroy",value:function(){l.default.prototype.destroy.call(this)}},{key:"onMediaAttached",value:function(e){this.media=e.media,this.media&&(this.id3Track=this.media.addTextTrack("metadata","id3"),this.id3Track.mode="hidden")}},{key:"onMediaDetaching",value:function(){this.media=void 0}},{key:"onFragParsingMetadata",value:function(e){for(var t=e.frag,r=e.samples,i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,n=0;n<r.length;n++){var a=f.default.getID3Frames(r[n].data);if(a){var o=r[n].pts,s=n<r.length-1?r[n+1].pts:t.endPTS;o===s&&(s+=1e-4);for(var u=0;u<a.length;u++){var l=a[u];if(!f.default.isTimeStampFrame(l)){var c=new i(o,s,"");c.value=l,this.id3Track.addCue(c)}}}}}}]),t}();r.default=c},{27:27,34:34,35:35}],12:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(54),c=e(33),d=i(e(37)),h=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.MANIFEST_LOADED,u.default.LEVEL_LOADED,u.default.FRAG_LOADED,u.default.ERROR));return r.ontick=r.tick.bind(r),r._manualLevel=-1,r}return o(t,l.default),s(t,[{key:"destroy",value:function(){this.timer&&(clearTimeout(this.timer),this.timer=null),this._manualLevel=-1}},{key:"startLoad",value:function(){this.canload=!0;var e=this._levels;e&&e.forEach(function(e){e.loadError=0;var t=e.details;t&&t.live&&(e.details=void 0)}),this.timer&&this.tick()}},{key:"stopLoad",value:function(){this.canload=!1}},{key:"onManifestLoaded",value:function(e){var t,r=[],i=[],n={},a=!1,o=!1,s=this.hls,l=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),d=function(e,t){return MediaSource.isTypeSupported(e+"/mp4;codecs="+t)};if(e.levels.forEach(function(e){e.videoCodec&&(a=!0),l&&e.audioCodec&&-1!==e.audioCodec.indexOf("mp4a.40.34")&&(e.audioCodec=void 0),(e.audioCodec||e.attrs&&e.attrs.AUDIO)&&(o=!0);var t=n[e.bitrate];void 0===t?(n[e.bitrate]=r.length,e.url=[e.url],e.urlId=0,r.push(e)):r[t].url.push(e.url)}),a&&o?r.forEach(function(e){e.videoCodec&&i.push(e)}):i=r,(i=i.filter(function(e){var t=e.audioCodec,r=e.videoCodec;return(!t||d("audio",t))&&(!r||d("video",r))})).length){t=i[0].bitrate,i.sort(function(e,t){return e.bitrate-t.bitrate}),this._levels=i;for(var h=0;h<i.length;h++)if(i[h].bitrate===t){this._firstLevel=h,f.logger.log("manifest loaded,"+i.length+" level(s) found, first bitrate:"+t);break}s.trigger(u.default.MANIFEST_PARSED,{levels:i,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:a,altAudio:e.audioTracks.length>0})}else s.trigger(u.default.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:s.url,reason:"no level with compatible codecs found in manifest"})}},{key:"setLevelInternal",value:function(e){var t=this._levels,r=this.hls;if(e>=0&&e<t.length){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this._level!==e){f.logger.log("switching to level "+e),this._level=e;var i=t[e];i.level=e,r.trigger(u.default.LEVEL_SWITCH,i),r.trigger(u.default.LEVEL_SWITCHING,i)}var n=t[e],a=n.details;if(!a||!0===a.live){var o=n.urlId;r.trigger(u.default.LEVEL_LOADING,{url:n.url[o],level:e,id:o})}}else r.trigger(u.default.ERROR,{type:c.ErrorTypes.OTHER_ERROR,details:c.ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:!1,reason:"invalid level idx"})}},{key:"onError",value:function(e){if(!e.fatal){var t=e.details,r=this.hls,i=void 0,n=void 0,a=!1;switch(t){case c.ErrorDetails.FRAG_LOAD_ERROR:case c.ErrorDetails.FRAG_LOAD_TIMEOUT:case c.ErrorDetails.FRAG_LOOP_LOADING_ERROR:case c.ErrorDetails.KEY_LOAD_ERROR:case c.ErrorDetails.KEY_LOAD_TIMEOUT:i=e.frag.level;break;case c.ErrorDetails.LEVEL_LOAD_ERROR:case c.ErrorDetails.LEVEL_LOAD_TIMEOUT:i=e.context.level,a=!0;break;case c.ErrorDetails.REMUX_ALLOC_ERROR:i=e.level}if(void 0!==i){(n=this._levels[i]).loadError?n.loadError++:n.loadError=1;var o=n.url.length;if(o>1&&n.loadError<o)n.urlId=(n.urlId+1)%o,n.details=void 0,f.logger.warn("level controller,"+t+" for level "+i+": switching to redundant stream id "+n.urlId);else if(-1===this._manualLevel&&i)f.logger.warn("level controller,"+t+": switch-down for next fragment"),r.nextAutoLevel=Math.max(0,i-1);else if(n&&n.details&&n.details.live)f.logger.warn("level controller,"+t+" on live stream, discard"),a&&(this._level=void 0);else if(t===c.ErrorDetails.LEVEL_LOAD_ERROR||t===c.ErrorDetails.LEVEL_LOAD_TIMEOUT){var s=r.media;if(s&&d.default.isBuffered(s,s.currentTime)&&d.default.isBuffered(s,s.currentTime+.5)){var u=r.config.levelLoadingRetryDelay;f.logger.warn("level controller,"+t+", but media buffered, retry in "+u+"ms"),this.timer=setTimeout(this.ontick,u),e.levelRetry=!0}else f.logger.error("cannot recover "+t+" error"),this._level=void 0,this.timer&&(clearTimeout(this.timer),this.timer=null),e.fatal=!0}}}}},{key:"onFragLoaded",value:function(e){var t=e.frag;if(t&&"main"===t.type){var r=this._levels[t.level];r&&(r.loadError=0)}}},{key:"onLevelLoaded",value:function(e){var t=e.level;if(t===this._level){var r=this._levels[t];r.loadError=0;var i=e.details;if(i.live){var n=1e3*(i.averagetargetduration?i.averagetargetduration:i.targetduration),a=r.details;a&&i.endSN===a.endSN&&(n/=2,f.logger.log("same live playlist, reload twice faster")),n-=performance.now()-e.stats.trequest,n=Math.max(1e3,Math.round(n)),f.logger.log("live playlist, reload in "+n+" ms"),this.timer=setTimeout(this.ontick,n)}else this.timer=null}}},{key:"tick",value:function(){var e=this._level;if(void 0!==e&&this.canload){var t=this._levels[e];if(t&&t.url){var r=t.urlId;this.hls.trigger(u.default.LEVEL_LOADING,{url:t.url[r],level:e,id:r})}}}},{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this._level},set:function(e){var t=this._levels;t&&t.length>e&&(this._level===e&&void 0!==t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this._manualLevel},set:function(e){this._manualLevel=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this._manualLevel?this._manualLevel:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this._manualLevel&&(this.hls.nextAutoLevel=e)}}]),t}();r.default=h},{33:33,34:34,35:35,37:37,54:54}],13:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(48)),l=i(e(37)),f=i(e(25)),c=i(e(35)),d=i(e(34)),h=i(e(38)),v=i(e(55)),p=e(33),g=e(54),y={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_LEVEL:"WAITING_LEVEL",PARSING:"PARSING",PARSED:"PARSED",BUFFER_FLUSHING:"BUFFER_FLUSHING",ENDED:"ENDED",ERROR:"ERROR"},m=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,c.default.MEDIA_ATTACHED,c.default.MEDIA_DETACHING,c.default.MANIFEST_LOADING,c.default.MANIFEST_PARSED,c.default.LEVEL_LOADED,c.default.KEY_LOADED,c.default.FRAG_LOADED,c.default.FRAG_LOAD_EMERGENCY_ABORTED,c.default.FRAG_PARSING_INIT_SEGMENT,c.default.FRAG_PARSING_DATA,c.default.FRAG_PARSED,c.default.ERROR,c.default.AUDIO_TRACK_SWITCHING,c.default.AUDIO_TRACK_SWITCHED,c.default.BUFFER_CREATED,c.default.BUFFER_APPENDED,c.default.BUFFER_FLUSHED));return r.config=e.config,r.audioCodecSwap=!1,r.ticks=0,r._state=y.STOPPED,r.ontick=r.tick.bind(r),r}return o(t,d.default),s(t,[{key:"destroy",value:function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),d.default.prototype.destroy.call(this),this.state=y.STOPPED}},{key:"startLoad",value:function(e){if(this.levels){var t=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.timer||(this.timer=setInterval(this.ontick,100)),this.level=-1,this.fragLoadError=0,!this.startFragRequested){var i=r.startLevel;-1===i&&(i=0,this.bitrateTest=!0),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&-1===e&&(g.logger.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=y.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=y.STOPPED}},{key:"stopLoad",value:function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=y.STOPPED,this.forceStartLoad=!1}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){switch(this.state){case y.ERROR:break;case y.BUFFER_FLUSHING:this.fragLoadError=0;break;case y.IDLE:this._doTickIdle();break;case y.WAITING_LEVEL:var e=this.levels[this.level];e&&e.details&&(this.state=y.IDLE);break;case y.FRAG_LOADING_WAITING_RETRY:var t=performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(g.logger.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=y.IDLE);break;case y.ERROR:case y.STOPPED:case y.FRAG_LOADING:case y.PARSING:case y.PARSED:case y.ENDED:}this._checkBuffer(),this._checkFragmentChanged()}},{key:"_doTickIdle",value:function(){var e=this.hls,t=e.config,r=this.media;if(void 0===this.levelLastLoaded||r||!this.startFragRequested&&t.startFragPrefetch){var i=void 0;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var n=e.nextLoadLevel,a=this.levels[n];if(a){var o=a.bitrate,s=void 0;s=o?Math.max(8*t.maxBufferSize/o,t.maxBufferLength):t.maxBufferLength,s=Math.min(s,t.maxMaxBufferLength);var u=l.default.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,t.maxBufferHole),f=u.len;if(!(f>=s)){g.logger.trace("buffer length of "+f.toFixed(3)+" is below max of "+s.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=n;var d=a.details;if(void 0===d||d.live&&this.levelLastLoaded!==n)this.state=y.WAITING_LEVEL;else{var h=this.fragPrevious;if(!d.live&&h&&h.sn===d.endSN&&f&&!u.nextStart&&Math.min(r.duration,h.start+h.duration)-Math.max(u.end,h.start)<=Math.max(.2,h.duration)){var v={};return this.altAudio&&(v.type="video"),this.hls.trigger(c.default.BUFFER_EOS,v),void(this.state=y.ENDED)}this._fetchPayloadOrEos(i,u,d)}}}}}},{key:"_fetchPayloadOrEos",value:function(e,t,r){var i=this.fragPrevious,n=this.level,a=r.fragments,o=a.length;if(0!==o){var s=a[0].start,u=a[o-1].start+a[o-1].duration,l=t.end,f=void 0;if(r.initSegment&&!r.initSegment.data)f=r.initSegment;else if(r.live){var c=this.config.initialLiveManifestSize;if(o<c)return void g.logger.warn("Can not start playback of a level, reason: not enough fragments "+o+" < "+c);if(null===(f=this._ensureFragmentAtLivePoint(r,l,s,u,i,a,o)))return}else l<s&&(f=a[0]);f||(f=this._findFragment(s,i,o,a,l,u,r)),f&&this._loadFragmentOrKey(f,n,r,e,l)}}},{key:"_ensureFragmentAtLivePoint",value:function(e,t,r,i,n,a,o){var s=this.hls.config,u=this.media,l=void 0,f=void 0!==s.liveMaxLatencyDuration?s.liveMaxLatencyDuration:s.liveMaxLatencyDurationCount*e.targetduration;if(t<Math.max(r-s.maxFragLookUpTolerance,i-f)){var c=this.liveSyncPosition=this.computeLivePosition(r,e);g.logger.log("buffer end: "+t.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+c.toFixed(3)),t=c,u&&u.readyState&&u.duration>c&&(u.currentTime=c),this.nextLoadPosition=c}if(e.PTSKnown&&t>i&&u&&u.readyState)return null;if(this.startFragRequested&&!e.PTSKnown){if(n){var d=n.sn+1;d>=e.startSN&&d<=e.endSN&&(l=a[d-e.startSN],g.logger.log("live playlist, switching playlist, load frag with next SN: "+l.sn))}l||(l=a[Math.min(o-1,Math.round(o/2))],g.logger.log("live playlist, switching playlist, unknown, load middle frag : "+l.sn))}return l}},{key:"_findFragment",value:function(e,t,r,i,n,a,o){var s=this.hls.config,l=void 0,f=void 0,c=s.maxFragLookUpTolerance,d=t?i[t.sn-i[0].sn+1]:void 0,h=function(e){var t=Math.min(c,e.duration);return e.start+e.duration-t<=n?1:e.start-t>n&&e.start?-1:0};if(n<a?(n>a-c&&(c=0),f=d&&!h(d)?d:u.default.search(i,h)):f=i[r-1],f){var v=(l=f).sn-o.startSN,p=t&&l.level===t.level,y=i[v-1],m=i[v+1];if(t&&l.sn===t.sn)if(p&&!l.backtracked)if(l.sn<o.endSN){var b=t.deltaPTS;b&&b>s.maxBufferHole&&t.dropped&&v?(l=y,g.logger.warn("SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this"),t.loadCounter--):(l=m,g.logger.log("SN just loaded, load next one: "+l.sn))}else l=null;else l.backtracked&&(m&&m.backtracked?(g.logger.warn("Already backtracked from fragment "+m.sn+", will not backtrack to fragment "+l.sn+". Loading fragment "+m.sn),l=m):(g.logger.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),l.dropped=0,y?(y.loadCounter&&y.loadCounter--,(l=y).backtracked=!0):v&&(l=null)))}return l}},{key:"_loadFragmentOrKey",value:function(e,t,r,i,n){var a=this.hls,o=a.config;if(!e.decryptdata||null==e.decryptdata.uri||null!=e.decryptdata.key){if(g.logger.log("Loading "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t+", currentTime:"+i.toFixed(3)+",bufferEnd:"+n.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,e.loadCounter){e.loadCounter++;var s=o.fragLoadingLoopThreshold;if(e.loadCounter>s&&Math.abs(this.fragLoadIdx-e.loadIdx)<s)return void a.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:e})}else e.loadCounter=1;return e.loadIdx=this.fragLoadIdx,this.fragCurrent=e,this.startFragRequested=!0,isNaN(e.sn)||(this.nextLoadPosition=e.start+e.duration),e.autoLevel=a.autoLevelEnabled,e.bitrateTest=this.bitrateTest,a.trigger(c.default.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new f.default(a,"main")),void(this.state=y.FRAG_LOADING)}g.logger.log("Loading key for "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t),this.state=y.KEY_LOADING,a.trigger(c.default.KEY_LOADING,{frag:e})}},{key:"getBufferedFrag",value:function(e){return u.default.search(this._bufferedFrags,function(t){return e<t.startPTS?-1:e>t.endPTS?1:0})}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.endPTS+.5):null}},{key:"_checkFragmentChanged",value:function(){var e,t,r=this.media;if(r&&r.readyState&&!1===r.seeking&&((t=r.currentTime)>r.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=t),l.default.isBuffered(r,t)?e=this.getBufferedFrag(t):l.default.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(c.default.FRAG_CHANGED,{frag:i});var n=i.level;this.fragPlaying&&this.fragPlaying.level===n||this.hls.trigger(c.default.LEVEL_SWITCHED,{level:n}),this.fragPlaying=i}}}},{key:"immediateLevelSwitch",value:function(){if(g.logger.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e=this.media,t=void 0;e?(t=e.paused,e.pause()):t=!0,this.previouslyPaused=t}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{key:"immediateLevelSwitchEnd",value:function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,l.default.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())}},{key:"nextLevelSwitch",value:function(){var e=this.media;if(e&&e.readyState){var t=void 0,r=void 0,i=void 0;if(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,(r=this.getBufferedFrag(e.currentTime))&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var n=this.hls.nextLoadLevel,a=this.levels[n],o=this.fragLastKbps;t=o&&this.fragCurrent?this.fragCurrent.duration*a.bitrate/(1e3*o)+1:0}if((i=this.getBufferedFrag(e.currentTime+t))&&(i=this.followingBufferedFrag(i))){var s=this.fragCurrent;s&&s.loader&&s.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(i.maxStartPTS,Number.POSITIVE_INFINITY)}}}},{key:"flushMainBuffer",value:function(e,t){this.state=y.BUFFER_FLUSHING;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(c.default.BUFFER_FLUSHING,r)}},{key:"onMediaAttached",value:function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("seeked",this.onvseeked),t.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(g.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.levels;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0,e.backtracked=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){var e=this.media,t=e?e.currentTime:void 0,r=this.config;isNaN(t)||g.logger.log("media seeking to "+t.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:e,n=l.default.bufferInfo(i,t,this.config.maxBufferHole);if(this.state===y.FRAG_LOADING){var a=this.fragCurrent;if(0===n.len&&a){var o=r.maxFragLookUpTolerance,s=a.start-o,u=a.start+a.duration+o;t<s||t>u?(a.loader&&(g.logger.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=y.IDLE):g.logger.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===y.ENDED&&(0===n.len&&(this.fragPrevious=0),this.state=y.IDLE);e&&(this.lastCurrentTime=t),this.state!==y.FRAG_LOADING&&void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*r.fragLoadingLoopThreshold),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=t),this.tick()}},{key:"onMediaSeeked",value:function(){var e=this.media,t=e?e.currentTime:void 0;isNaN(t)||g.logger.log("media seeked to "+t.toFixed(3)),this.tick()}},{key:"onMediaEnded",value:function(){g.logger.log("media ended"),this.startPosition=this.lastCurrentTime=0}},{key:"onManifestLoading",value:function(){g.logger.log("trigger BUFFER_RESET"),this.hls.trigger(c.default.BUFFER_RESET),this._bufferedFrags=[],this.stalled=!1,this.startPosition=this.lastCurrentTime=0}},{key:"onManifestParsed",value:function(e){var t,r=!1,i=!1;e.levels.forEach(function(e){(t=e.audioCodec)&&(-1!==t.indexOf("mp4a.40.2")&&(r=!0),-1!==t.indexOf("mp4a.40.5")&&(i=!0))}),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&g.logger.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startLevelLoaded=!1,this.startFragRequested=!1;var n=this.config;(n.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(n.startPosition)}},{key:"onLevelLoaded",value:function(e){var t=e.details,r=e.level,i=this.levels[r],n=t.totalduration,a=0;if(g.logger.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+n),this.levelLastLoaded=r,t.live){var o=i.details;o&&t.fragments.length>0?(h.default.mergeDetails(o,t),a=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(a,o),t.PTSKnown?g.logger.log("live playlist sliding:"+a.toFixed(3)):g.logger.log("live playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,g.logger.log("live playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,this.hls.trigger(c.default.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var s=t.startTimeOffset;isNaN(s)?t.live?(this.startPosition=this.computeLivePosition(a,t),g.logger.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(s<0&&(g.logger.log("negative start time offset "+s+", count from end of last fragment"),s=a+n+s),g.logger.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===y.WAITING_LEVEL&&(this.state=y.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===y.KEY_LOADING&&(this.state=y.IDLE,this.tick())}},{key:"onFragLoaded",value:function(e){var t=this.fragCurrent,r=e.frag;if(this.state===y.FRAG_LOADING&&t&&"main"===r.type&&r.level===t.level&&r.sn===t.sn){var i=e.stats,n=this.levels[t.level],a=n.details;if(g.logger.log("Loaded "+t.sn+" of ["+a.startSN+" ,"+a.endSN+"],level "+t.level),this.bitrateTest=!1,this.stats=i,!0===r.bitrateTest&&this.hls.nextLoadLevel)this.state=y.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=performance.now(),this.hls.trigger(c.default.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=y.IDLE,i.tparsed=i.tbuffered=performance.now(),a.initSegment.data=e.payload,this.hls.trigger(c.default.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else{this.state=y.PARSING;var o=a.totalduration,s=t.level,u=t.sn,l=this.config.defaultAudioCodec||n.audioCodec;this.audioCodecSwap&&(g.logger.log("swapping playlist audio codec"),void 0===l&&(l=this.lastAudioCodec),l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,g.logger.log("Parsing "+u+" of ["+a.startSN+" ,"+a.endSN+"],level "+s+", cc "+t.cc);var d=this.demuxer;d||(d=this.demuxer=new f.default(this.hls,"main"));var h=this.media,v=!(h&&h.seeking)&&(a.PTSKnown||!a.live),p=a.initSegment?a.initSegment.data:[];d.push(e.payload,p,l,n.videoCodec,t,o,v,void 0)}}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===y.PARSING){var i,n,a=e.tracks;if(a.audio&&this.altAudio&&delete a.audio,n=a.audio){var o=this.levels[this.level].audioCodec,s=navigator.userAgent.toLowerCase();o&&this.audioCodecSwap&&(g.logger.log("swapping playlist audio codec"),o=-1!==o.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===s.indexOf("firefox")&&(o="mp4a.40.5"),-1!==s.indexOf("android")&&"audio/mpeg"!==n.container&&(o="mp4a.40.2",g.logger.log("Android: force audio codec to "+o)),n.levelCodec=o,n.id=e.id}(n=a.video)&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=e.id),this.hls.trigger(c.default.BUFFER_CODECS,a);for(i in a){n=a[i],g.logger.log("main track:"+i+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var u=n.initSegment;u&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(c.default.BUFFER_APPENDING,{type:i,data:u,parent:"main",content:"initSegment"}))}this.tick()}}},{key:"onFragParsingData",value:function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===y.PARSING){var n=this.levels[this.level],a=r;if(isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),g.logger.log("Parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb+",dropped:"+(e.dropped||0)),"video"===e.type)if(a.dropped=e.dropped,a.dropped){if(!a.backtracked)return g.logger.warn("missing video frame(s), backtracking fragment"),a.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=y.IDLE,this.fragPrevious=a,void this.tick();g.logger.warn("Already backtracked on this fragment, appending with the gap")}else a.backtracked=!1;var o=h.default.updateFragPTSDTS(n.details,a,e.startPTS,e.endPTS,e.startDTS,e.endDTS),s=this.hls;s.trigger(c.default.LEVEL_PTS_UPDATED,{details:n.details,level:this.level,drift:o,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach(function(r){r&&r.length&&t.state===y.PARSING&&(t.appended=!0,t.pendingBuffering=!0,s.trigger(c.default.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))}),this.tick()}}},{key:"onFragParsed",value:function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===y.PARSING&&(this.stats.tparsed=performance.now(),this.state=y.PARSED,this._checkAppendedParsed())}},{key:"onAudioTrackSwitching",value:function(e){var t=!!e.url,r=e.id;if(!t){if(this.mediaBuffer!==this.media){g.logger.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(g.logger.log("switching to main audio track, cancel main fragment load"),i.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=y.IDLE}var n=this.hls;n.trigger(c.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),n.trigger(c.default.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}}},{key:"onAudioTrackSwitched",value:function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(g.logger.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()}},{key:"onBufferCreated",value:function(e){var t=e.tracks,r=void 0,i=void 0,n=!1;for(var a in t){var o=t[a];"main"===o.id?(i=a,r=o,"video"===a&&(this.videoBuffer=t[a].buffer)):n=!0}n&&r?(g.logger.log("alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onBufferAppended",value:function(e){if("main"===e.parent){var t=this.state;t!==y.PARSING&&t!==y.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}}},{key:"_checkAppendedParsed",value:function(){if(!(this.state!==y.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;g.logger.log("main buffered : "+v.default.toString(t.buffered));var r=this._bufferedFrags.filter(function(e){return l.default.isBuffered(t,(e.startPTS+e.endPTS)/2)});r.push(e),this._bufferedFrags=r.sort(function(e,t){return e.startPTS-t.startPTS}),this.fragPrevious=e;var i=this.stats;i.tbuffered=performance.now(),this.fragLastKbps=Math.round(8*i.total/(i.tbuffered-i.tfirst)),this.hls.trigger(c.default.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.state=y.IDLE}this.tick()}}},{key:"onError",value:function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=this.media,i=r&&l.default.isBuffered(r,r.currentTime)&&l.default.isBuffered(r,r.currentTime+.5);switch(e.details){case p.ErrorDetails.FRAG_LOAD_ERROR:case p.ErrorDetails.FRAG_LOAD_TIMEOUT:case p.ErrorDetails.KEY_LOAD_ERROR:case p.ErrorDetails.KEY_LOAD_TIMEOUT:if(!e.fatal){var n=this.fragLoadError;n?n++:n=1;var a=this.config;if(n<=a.fragLoadingMaxRetry||i||t.autoLevel&&t.level){this.fragLoadError=n,t.loadCounter=0;var o=Math.min(Math.pow(2,n-1)*a.fragLoadingRetryDelay,a.fragLoadingMaxRetryTimeout);g.logger.warn("mediaController: frag loading failed, retry in "+o+" ms"),this.retryDate=performance.now()+o,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.state=y.FRAG_LOADING_WAITING_RETRY}else g.logger.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=y.ERROR}break;case p.ErrorDetails.FRAG_LOOP_LOADING_ERROR:e.fatal||(i?(this._reduceMaxBufferLength(t.duration),this.state=y.IDLE):t.autoLevel&&0!==t.level||(e.fatal=!0,this.state=y.ERROR));break;case p.ErrorDetails.LEVEL_LOAD_ERROR:case p.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==y.ERROR&&(e.fatal?(this.state=y.ERROR,g.logger.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==y.WAITING_LEVEL||(this.state=y.IDLE));break;case p.ErrorDetails.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==y.PARSING&&this.state!==y.PARSED||(i?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=y.IDLE):(g.logger.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}}},{key:"_reduceMaxBufferLength",value:function(e){var t=this.config;t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,g.logger.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*t.fragLoadingLoopThreshold)}},{key:"_checkBuffer",value:function(){var e=this.media,t=this.config;if(e&&e.readyState){var r=e.currentTime,i=this.mediaBuffer?this.mediaBuffer:e,n=i.buffered;if(!this.loadedmetadata&&n.length){this.loadedmetadata=!0;var a=e.seeking?r:this.startPosition,o=l.default.isBuffered(i,a),s=n.start(0);(r!==a||!o&&Math.abs(a-s)<t.maxSeekHole)&&(g.logger.log("target start position:"+a),o||(a=s,g.logger.log("target start position not buffered, seek to buffered.start(0) "+a)),g.logger.log("adjust currentTime from "+r+" to "+a),e.currentTime=a)}else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var u=l.default.bufferInfo(e,r,0),f=!(e.paused||e.ended||0===e.buffered.length);if(r!==this.lastCurrentTime)this.stallReported&&(g.logger.warn("playback not stuck anymore @"+r+", after "+Math.round(performance.now()-this.stalled)+"ms"),this.stallReported=!1),this.stalled=void 0,this.nudgeRetry=0;else if(f){var d=performance.now(),h=this.hls;if(this.stalled){var v=d-this.stalled,y=u.len,m=this.nudgeRetry||0;if(y<=.5&&v>1e3*t.lowBufferWatchdogPeriod){this.stallReported||(this.stallReported=!0,g.logger.warn("playback stalling in low buffer @"+r),h.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:y}));var b=u.nextStart,_=b-r;if(b&&_<t.maxSeekHole&&_>0){this.nudgeRetry=++m;var E=m*t.nudgeOffset;g.logger.log("adjust currentTime from "+e.currentTime+" to next buffered @ "+b+" + nudge "+E),e.currentTime=b+E,this.stalled=void 0,h.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,hole:b+E-r})}}else if(y>.5&&v>1e3*t.highBufferWatchdogPeriod)if(this.stallReported||(this.stallReported=!0,g.logger.warn("playback stalling in high buffer @"+r),h.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:y})),this.stalled=void 0,this.nudgeRetry=++m,m<t.nudgeMaxRetry){var k=e.currentTime,w=k+m*t.nudgeOffset;g.logger.log("adjust currentTime from "+k+" to "+w),e.currentTime=w,h.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.BUFFER_NUDGE_ON_STALL,fatal:!1})}else g.logger.error("still stuck in high buffer @"+r+" after "+t.nudgeMaxRetry+", raise fatal error"),h.trigger(c.default.ERROR,{type:p.ErrorTypes.MEDIA_ERROR,details:p.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!0})}else this.stalled=d,this.stallReported=!1}}}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=y.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()}},{key:"onBufferFlushed",value:function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;this._bufferedFrags=this._bufferedFrags.filter(function(t){return l.default.isBuffered(e,(t.startPTS+t.endPTS)/2)}),this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,this.state=y.IDLE,this.fragPrevious=null}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"computeLivePosition",value:function(e,t){var r=void 0!==this.config.liveSyncDuration?this.config.liveSyncDuration:this.config.liveSyncDurationCount*t.targetduration;return e+Math.max(0,t.totalduration-r)}},{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,g.logger.log("main stream:"+t+"->"+e),this.hls.trigger(c.default.STREAM_STATE_TRANSITION,{previousState:t,nextState:e})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getBufferedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;return e?this.followingBufferedFrag(this.getBufferedFrag(e.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(e){this._liveSyncPosition=e}}]),t}();r.default=m},{25:25,33:33,34:34,35:35,37:37,38:38,48:48,54:54,55:55}],14:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(54),c=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.ERROR,u.default.SUBTITLE_TRACKS_UPDATED,u.default.SUBTITLE_TRACK_SWITCH,u.default.SUBTITLE_TRACK_LOADED,u.default.SUBTITLE_FRAG_PROCESSED));return r.config=e.config,r.vttFragSNsProcessed={},r.vttFragQueues=void 0,r.currentlyProcessing=null,r.currentTrackId=-1,r}return o(t,l.default),s(t,[{key:"destroy",value:function(){l.default.prototype.destroy.call(this)}},{key:"clearVttFragQueues",value:function(){var e=this;this.vttFragQueues={},this.tracks.forEach(function(t){e.vttFragQueues[t.id]=[]})}},{key:"nextFrag",value:function(){if(null===this.currentlyProcessing&&this.currentTrackId>-1&&this.vttFragQueues[this.currentTrackId].length){var e=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.hls.trigger(u.default.FRAG_LOADING,{frag:e})}}},{key:"onSubtitleFragProcessed",value:function(e){e.success&&this.vttFragSNsProcessed[e.frag.trackId].push(e.frag.sn),this.currentlyProcessing=null,this.nextFrag()}},{key:"onError",value:function(e){var t=e.frag;t&&"subtitle"!==t.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())}},{key:"onSubtitleTracksUpdated",value:function(e){var t=this;f.logger.log("subtitle tracks updated"),this.tracks=e.subtitleTracks,this.clearVttFragQueues(),this.vttFragSNsProcessed={},this.tracks.forEach(function(e){t.vttFragSNsProcessed[e.id]=[]})}},{key:"onSubtitleTrackSwitch",value:function(e){this.currentTrackId=e.id,this.clearVttFragQueues()}},{key:"onSubtitleTrackLoaded",value:function(e){var t=this.vttFragSNsProcessed[e.id],r=this.vttFragQueues[e.id],i=this.currentlyProcessing?this.currentlyProcessing.sn:-1,n=function(e){return t.indexOf(e.sn)>-1},a=function(e){return r.some(function(t){return t.sn===e.sn})};e.details.fragments.forEach(function(t){n(t)||t.sn===i||a(t)||(t.trackId=e.id,r.push(t))}),this.nextFrag()}}]),t}();r.default=c},{34:34,35:35,54:54}],15:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){for(var t=[],r=0;r<e.length;r++)"subtitles"===e[r].kind&&t.push(e[r]);return t}Object.defineProperty(r,"__esModule",{value:!0});var u=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),l=i(e(35)),f=i(e(34)),c=e(54),d=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,l.default.MEDIA_ATTACHED,l.default.MEDIA_DETACHING,l.default.MANIFEST_LOADING,l.default.MANIFEST_LOADED,l.default.SUBTITLE_TRACK_LOADED));return r.tracks=[],r.trackId=-1,r.media=void 0,r}return o(t,f.default),u(t,[{key:"_onTextTracksChanged",value:function(){if(this.media){for(var e=-1,t=s(this.media.textTracks),r=0;r<t.length;r++)"showing"===t[r].mode&&(e=r);this.subtitleTrack=e}}},{key:"destroy",value:function(){f.default.prototype.destroy.call(this)}},{key:"onMediaAttached",value:function(e){this.media=e.media,this.media&&(this.trackChangeListener=this._onTextTracksChanged.bind(this),this.media.textTracks.addEventListener("change",this.trackChangeListener))}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.textTracks.removeEventListener("change",this.trackChangeListener),this.media=void 0)}},{key:"onManifestLoading",value:function(){this.tracks=[],this.trackId=-1}},{key:"onManifestLoaded",value:function(e){var t=this,r=e.subtitles||[],i=!1;this.tracks=r,this.trackId=-1,this.hls.trigger(l.default.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:r}),r.forEach(function(e){e.default&&(t.subtitleTrack=e.id,i=!0)})}},{key:"onTick",value:function(){var e=this.trackId,t=this.tracks[e];if(t){var r=t.details;void 0!==r&&!0!==r.live||(c.logger.log("(re)loading playlist for subtitle track "+e),this.hls.trigger(l.default.SUBTITLE_TRACK_LOADING,{url:t.url,id:e}))}}},{key:"onSubtitleTrackLoaded",value:function(e){var t=this;e.id<this.tracks.length&&(c.logger.log("subtitle track "+e.id+" loaded"),this.tracks[e.id].details=e.details,e.details.live&&!this.timer&&(this.timer=setInterval(function(){t.onTick()},1e3*e.details.targetduration,this)),!e.details.live&&this.timer&&(clearInterval(this.timer),this.timer=null))}},{key:"setSubtitleTrackInternal",value:function(e){if(e>=0&&e<this.tracks.length){this.timer&&(clearInterval(this.timer),this.timer=null),this.trackId=e,c.logger.log("switching to subtitle track "+e);var t=this.tracks[e];this.hls.trigger(l.default.SUBTITLE_TRACK_SWITCH,{id:e});var r=t.details;void 0!==r&&!0!==r.live||(c.logger.log("(re)loading playlist for subtitle track "+e),this.hls.trigger(l.default.SUBTITLE_TRACK_LOADING,{url:t.url,id:e}))}}},{key:"subtitleTracks",get:function(){return this.tracks}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.trackId!==e&&this.setSubtitleTrackInternal(e)}}]),t}();r.default=d},{34:34,35:35,54:54}],16:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){if(e&&e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}function u(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}function l(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}Object.defineProperty(r,"__esModule",{value:!0});var f=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),c=i(e(35)),d=i(e(34)),h=i(e(49)),v=i(e(58)),p=e(54),g=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,c.default.MEDIA_ATTACHING,c.default.MEDIA_DETACHING,c.default.FRAG_PARSING_USERDATA,c.default.MANIFEST_LOADING,c.default.MANIFEST_LOADED,c.default.FRAG_LOADED,c.default.LEVEL_SWITCHING,c.default.INIT_PTS_FOUND));if(r.hls=e,r.config=e.config,r.enabled=!0,r.Cues=e.config.cueHandler,r.textTracks=[],r.tracks=[],r.unparsedVttFrags=[],r.initPTS=void 0,r.cueRanges=[],r.config.enableCEA708Captions){var i=r,o=function(e,t){var r=null;try{r=new window.Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)},u={newCue:function(e,t,r){if(!i.textTrack1){var n=i.getExistingTrack("1");if(n)i.textTrack1=n,s(i.textTrack1),o(i.textTrack1,i.media);else{var a=i.createTextTrack("captions",i.config.captionsTextTrack1Label,i.config.captionsTextTrack1LanguageCode);a&&(a.textTrack1=!0,i.textTrack1=a)}}i.addCues("textTrack1",e,t,r)}},l={newCue:function(e,t,r){if(!i.textTrack2){var n=i.getExistingTrack("2");if(n)i.textTrack2=n,s(i.textTrack2),o(i.textTrack2,i.media);else{var a=i.createTextTrack("captions",i.config.captionsTextTrack2Label,i.config.captionsTextTrack1LanguageCode);a&&(a.textTrack2=!0,i.textTrack2=a)}}i.addCues("textTrack2",e,t,r)}};r.cea608Parser=new h.default(0,u,l)}return r}return o(t,d.default),f(t,[{key:"addCues",value:function(e,t,r,i){for(var n=this.cueRanges,a=!1,o=n.length;o--;){var s=n[o],u=l(s[0],s[1],t,r);if(u>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],r),a=!0,u/(r-t)>.5))return}a||n.push([t,r]),this.Cues.newCue(this[e],t,r,i)}},{key:"onInitPtsFound",value:function(e){var t=this;void 0===this.initPTS&&(this.initPTS=e.initPTS),this.unparsedVttFrags.length&&(this.unparsedVttFrags.forEach(function(e){t.onFragLoaded(e)}),this.unparsedVttFrags=[])}},{key:"getExistingTrack",value:function(e){var t=this.media;if(t)for(var r=0;r<t.textTracks.length;r++){var i=t.textTracks[r];if(!0===i["textTrack"+e])return i}return null}},{key:"createTextTrack",value:function(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)}},{key:"destroy",value:function(){d.default.prototype.destroy.call(this)}},{key:"onMediaAttaching",value:function(e){this.media=e.media}},{key:"onMediaDetaching",value:function(){s(this.textTrack1),s(this.textTrack2)}},{key:"onManifestLoading",value:function(){this.lastSn=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0};var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)s(t[r])}}},{key:"onManifestLoaded",value:function(e){var t=this;if(this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=void 0,this.cueRanges=[],this.config.enableWebVTT){this.tracks=e.subtitles||[];var r=this.media?this.media.textTracks:[];this.tracks.forEach(function(e,i){var n=void 0;if(i<r.length){var a=r[i];u(a,e)&&(n=a)}n||(n=t.createTextTrack("subtitles",e.name,e.lang)),n.mode=e.default?"showing":"hidden",t.textTracks.push(n)})}}},{key:"onLevelSwitching",value:function(){this.enabled="NONE"!==this.hls.currentLevel.closedCaptions}},{key:"onFragLoaded",value:function(e){var t=e.frag,r=e.payload;if("main"===t.type){var i=t.sn;if(i!==this.lastSn+1){var n=this.cea608Parser;n&&n.reset()}this.lastSn=i}else if("subtitle"===t.type)if(r.byteLength){if(void 0===this.initPTS)return void this.unparsedVttFrags.push(e);var a=this.vttCCs;a[t.cc]||(a[t.cc]={start:t.start,prevCC:this.prevCC,new:!0},this.prevCC=t.cc);var o=this.textTracks,s=this.hls;v.default.parse(r,this.initPTS,a,t.cc,function(e){var r=o[t.trackId];e.forEach(function(e){r.cues.getCueById(e.id)||r.addCue(e)}),s.trigger(c.default.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},function(e){p.logger.log("Failed to parse VTT cue: "+e),s.trigger(c.default.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t})})}else this.hls.trigger(c.default.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t})}},{key:"onFragParsingUserdata",value:function(e){if(this.enabled&&this.config.enableCEA708Captions)for(var t=0;t<e.samples.length;t++){var r=this.extractCea608Data(e.samples[t].bytes);this.cea608Parser.addData(e.samples[t].pts,r)}}},{key:"extractCea608Data",value:function(e){for(var t,r,i,n,a,o=31&e[0],s=2,u=[],l=0;l<o;l++)t=e[s++],r=127&e[s++],i=127&e[s++],n=0!=(4&t),a=3&t,0===r&&0===i||n&&0===a&&(u.push(r),u.push(i));return u}}]),t}();r.default=g},{34:34,35:35,49:49,54:54,58:58}],17:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(){function e(t,r){i(this,e),this.subtle=t,this.aesIV=r}return n(e,[{key:"decrypt",value:function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}]),e}();r.default=a},{}],18:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(){function e(){i(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.initTable()}return n(e,[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],o=r[3],s=this.invSubMix,u=s[0],l=s[1],f=s[2],c=s[3],d=new Uint32Array(256),h=0,v=0,p=0;for(p=0;p<256;p++)d[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var g=v^v<<1^v<<2^v<<3^v<<4;g=g>>>8^255&g^99,e[h]=g,t[g]=h;var y=d[h],m=d[y],b=d[m],_=257*d[g]^16843008*g;i[h]=_<<24|_>>>8,n[h]=_<<16|_>>>16,a[h]=_<<8|_>>>24,o[h]=_,_=16843009*b^65537*m^257*y^16843008*h,u[g]=_<<24|_>>>8,l[g]=_<<16|_>>>16,f[g]=_<<8|_>>>24,c[g]=_,h?(h=y^d[d[d[b^y]]],v^=d[d[v]]):h=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a=this.ksRows=4*(n+6+1),o=void 0,s=void 0,u=this.keySchedule=new Uint32Array(a),l=this.invKeySchedule=new Uint32Array(a),f=this.sBox,c=this.rcon,d=this.invSubMix,h=d[0],v=d[1],p=d[2],g=d[3],y=void 0,m=void 0;for(o=0;o<a;o++)o<n?y=u[o]=t[o]:(m=y,o%n==0?(m=f[(m=m<<8|m>>>24)>>>24]<<24|f[m>>>16&255]<<16|f[m>>>8&255]<<8|f[255&m],m^=c[o/n|0]<<24):n>6&&o%n==4&&(m=f[m>>>24]<<24|f[m>>>16&255]<<16|f[m>>>8&255]<<8|f[255&m]),u[o]=y=(u[o-n]^m)>>>0);for(s=0;s<a;s++)o=a-s,m=3&s?u[o]:u[o-4],l[s]=s<4||o<=4?m:h[f[m>>>24]]^v[f[m>>>16&255]]^p[f[m>>>8&255]]^g[f[255&m]],l[s]=l[s]>>>0}}},{key:"networkToHostOrderSwap",value:function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,n,a=this.keySize+6,o=this.invKeySchedule,s=this.invSBox,u=this.invSubMix,l=u[0],f=u[1],c=u[2],d=u[3],h=this.uint8ArrayToUint32Array_(r),v=h[0],p=h[1],g=h[2],y=h[3],m=new Int32Array(e),b=new Int32Array(m.length),_=void 0,E=void 0,k=void 0,w=void 0,S=void 0,T=void 0,A=void 0,R=void 0,L=void 0,O=void 0,D=void 0,P=void 0,x=this.networkToHostOrderSwap;t<m.length;){for(L=x(m[t]),O=x(m[t+1]),D=x(m[t+2]),P=x(m[t+3]),S=L^o[0],T=P^o[1],A=D^o[2],R=O^o[3],i=4,n=1;n<a;n++)_=l[S>>>24]^f[T>>16&255]^c[A>>8&255]^d[255&R]^o[i],E=l[T>>>24]^f[A>>16&255]^c[R>>8&255]^d[255&S]^o[i+1],k=l[A>>>24]^f[R>>16&255]^c[S>>8&255]^d[255&T]^o[i+2],w=l[R>>>24]^f[S>>16&255]^c[T>>8&255]^d[255&A]^o[i+3],S=_,T=E,A=k,R=w,i+=4;_=s[S>>>24]<<24^s[T>>16&255]<<16^s[A>>8&255]<<8^s[255&R]^o[i],E=s[T>>>24]<<24^s[A>>16&255]<<16^s[R>>8&255]<<8^s[255&S]^o[i+1],k=s[A>>>24]<<24^s[R>>16&255]<<16^s[S>>8&255]<<8^s[255&T]^o[i+2],w=s[R>>>24]<<24^s[S>>16&255]<<16^s[T>>8&255]<<8^s[255&A]^o[i+3],i+=3,b[t]=x(_^v),b[t+1]=x(w^p),b[t+2]=x(k^g),b[t+3]=x(E^y),v=L,p=O,g=D,y=P,t+=4}return b.buffer}},{key:"destroy",value:function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0}}]),e}();r.default=a},{}],19:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(17)),s=i(e(20)),u=i(e(18)),l=e(33),f=e(54),c=function(){function e(t,r){n(this,e),this.observer=t,this.config=r,this.logEnabled=!0;try{var i=crypto||self.crypto;this.subtle=i.subtle||i.webkitSubtle}catch(e){}this.disableWebCrypto=!this.subtle}return a(e,[{key:"isSync",value:function(){return this.disableWebCrypto&&this.config.enableSoftwareAES}},{key:"decrypt",value:function(e,t,r,i){var n=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(f.logger.log("JS AES decrypt"),this.logEnabled=!1);var a=this.decryptor;a||(this.decryptor=a=new u.default),a.expandKey(t),i(a.decrypt(e,0,r))}else{this.logEnabled&&(f.logger.log("WebCrypto AES decrypt"),this.logEnabled=!1);var l=this.subtle;this.key!==t&&(this.key=t,this.fastAesKey=new s.default(l,t)),this.fastAesKey.expandKey().then(function(a){new o.default(l,r).decrypt(e,a).catch(function(a){n.onWebCryptoError(a,e,t,r,i)}).then(function(e){i(e)})}).catch(function(a){n.onWebCryptoError(a,e,t,r,i)})}}},{key:"onWebCryptoError",value:function(e,t,r,i,n){this.config.enableSoftwareAES?(f.logger.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(t,r,i,n)):(f.logger.error("decrypting error : "+e.message),this.observer.trigger(Event.ERROR,{type:l.ErrorTypes.MEDIA_ERROR,details:l.ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!0,reason:e.message}))}},{key:"destroy",value:function(){var e=this.decryptor;e&&(e.destroy(),this.decryptor=void 0)}}]),e}();r.default=c},{17:17,18:18,20:20,33:33,54:54}],20:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(){function e(t,r){i(this,e),this.subtle=t,this.key=r}return n(e,[{key:"expandKey",value:function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}]),e}();r.default=a},{}],21:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(22)),s=e(54),u=i(e(27)),l=function(){function e(t,r,i){n(this,e),this.observer=t,this.config=i,this.remuxer=r}return a(e,[{key:"resetInitSegment",value:function(e,t,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:-1,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}}},{key:"resetTimeStamp",value:function(){}},{key:"append",value:function(e,t,r,i){for(var n=this._audioTrack,a=u.default.getID3Data(e,0),l=90*u.default.getTimeStamp(a),f=0,c=l,d=e.length,h=a.length,v=[{pts:c,dts:c,data:a}];h<d-1;)if(o.default.isHeader(e,h)&&h+5<d){o.default.initTrackConfig(n,this.observer,e,h,n.manifestCodec);var p=o.default.appendFrame(n,e,h,l,f);if(!p){s.logger.log("Unable to parse AAC frame");break}h+=p.length,c=p.sample.pts,f++}else u.default.isHeader(e,h)?(a=u.default.getID3Data(e,h),v.push({pts:c,dts:c,data:a}),h+=a.length):h++;this.remuxer.remux(n,{samples:[]},{samples:v,inputTimeScale:9e4},{samples:[]},t,r,i)}},{key:"destroy",value:function(){}}],[{key:"probe",value:function(e){var t,r,i=u.default.getID3Data(e,0);if(i&&void 0!==u.default.getTimeStamp(i))for(t=i.length,r=Math.min(e.length-1,t+100);t<r;t++)if(o.default.probe(e,t))return s.logger.log("ADTS sync word found !"),!0;return!1}}]),e}();r.default=l},{22:22,27:27,54:54}],22:[function(e,t,r){var i=e(54),n=e(33),a={getAudioConfig:function(e,t,r,a){var o,s,u,l,f,c=navigator.userAgent.toLowerCase(),d=a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];if(o=1+((192&t[r+2])>>>6),!((s=(60&t[r+2])>>>2)>h.length-1))return l=(1&t[r+2])<<2,l|=(192&t[r+3])>>>6,i.logger.log("manifest codec:"+a+",ADTS data:type:"+o+",sampleingIndex:"+s+"["+h[s]+"Hz],channelConfig:"+l),/firefox/i.test(c)?s>=6?(o=5,f=new Array(4),u=s-3):(o=2,f=new Array(2),u=s):-1!==c.indexOf("android")?(o=2,f=new Array(2),u=s):(o=5,f=new Array(4),a&&(-1!==a.indexOf("mp4a.40.29")||-1!==a.indexOf("mp4a.40.5"))||!a&&s>=6?u=s-3:((a&&-1!==a.indexOf("mp4a.40.2")&&s>=6&&1===l||!a&&1===l)&&(o=2,f=new Array(2)),u=s)),f[0]=o<<3,f[0]|=(14&s)>>1,f[1]|=(1&s)<<7,f[1]|=l<<3,5===o&&(f[1]|=(14&u)>>1,f[2]=(1&u)<<7,f[2]|=8,f[3]=0),{config:f,samplerate:h[s],channelCount:l,codec:"mp4a.40."+o,manifestCodec:d};e.trigger(Event.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+s})},isHeaderPattern:function(e,t){return 255===e[t]&&240==(246&e[t+1])},getHeaderLength:function(e,t){return 1&e[t+1]?7:9},getFullFrameLength:function(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5},isHeader:function(e,t){return!!(t+1<e.length&&this.isHeaderPattern(e,t))},probe:function(e,t){if(t+1<e.length&&this.isHeaderPattern(e,t)){var r=this.getHeaderLength(e,t);t+5<e.length&&(r=this.getFullFrameLength(e,t));var i=t+r;if(i===e.length||i+1<e.length&&this.isHeaderPattern(e,i))return!0}return!1},initTrackConfig:function(e,t,r,n,a){if(!e.samplerate){var o=this.getAudioConfig(t,r,n,a);e.config=o.config,e.samplerate=o.samplerate,e.channelCount=o.channelCount,e.codec=o.codec,e.manifestCodec=o.manifestCodec,i.logger.log("parsed codec:"+e.codec+",rate:"+o.samplerate+",nb channel:"+o.channelCount)}},getFrameDuration:function(e){return 9216e4/e},appendFrame:function(e,t,r,i,n){var a=this.getFrameDuration(e.samplerate),o=this.parseFrameHeader(t,r,i,n,a);if(o){var s=o.stamp,u=o.headerLength,l=o.frameLength,f={unit:t.subarray(r+u,r+u+l),pts:s,dts:s};return e.samples.push(f),e.len+=l,{sample:f,length:l+u}}},parseFrameHeader:function(e,t,r,i,n){var a,o,s,u=e.length;if(a=this.getHeaderLength(e,t),o=this.getFullFrameLength(e,t),(o-=a)>0&&t+a+o<=u)return s=r+i*n,{headerLength:a,frameLength:o,stamp:s}}};t.exports=a},{33:33,54:54}],23:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(35)),s=e(33),u=i(e(19)),l=i(e(21)),f=i(e(29)),c=i(e(32)),d=i(e(28)),h=i(e(45)),v=i(e(46)),p=function(){function e(t,r,i,a){n(this,e),this.observer=t,this.typeSupported=r,this.config=i,this.vendor=a}return a(e,[{key:"destroy",value:function(){var e=this.demuxer;e&&e.destroy()}},{key:"push",value:function(e,t,r,i,n,a,s,l,f,c,d,h){if(e.byteLength>0&&null!=t&&null!=t.key&&"AES-128"===t.method){var v=this.decrypter;null==v&&(v=this.decrypter=new u.default(this.observer,this.config));var p,g=this;try{p=performance.now()}catch(e){p=Date.now()}v.decrypt(e,t.key.buffer,t.iv.buffer,function(e){var u;try{u=performance.now()}catch(e){u=Date.now()}g.observer.trigger(o.default.FRAG_DECRYPTED,{stats:{tstart:p,tdecrypt:u}}),g.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),i,n,a,s,l,f,c,d,h)})}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),i,n,a,s,l,f,c,d,h)}},{key:"pushDecrypted",value:function(e,t,r,i,n,a,u,p,g,y,m,b){var _=this.demuxer;if(!_||u&&!this.probe(e)){for(var E=this.observer,k=this.typeSupported,w=this.config,S=[{demux:l.default,remux:h.default},{demux:d.default,remux:h.default},{demux:c.default,remux:h.default},{demux:f.default,remux:v.default}],T=0,A=S.length;T<A;T++){var R=S[T],L=R.demux.probe;if(L(e)){var O=this.remuxer=new R.remux(E,w,k,this.vendor);_=new R.demux(E,O,w,k),this.probe=L;break}}if(!_)return void E.trigger(o.default.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=_}var D=this.remuxer;(u||p)&&(_.resetInitSegment(r,i,n,y),D.resetInitSegment()),u&&(_.resetTimeStamp(b),D.resetTimeStamp(b)),"function"==typeof _.setDecryptData&&_.setDecryptData(t),_.append(e,a,g,m)}}]),e}();r.default=p},{19:19,21:21,28:28,29:29,32:32,33:33,35:35,45:45,46:46}],24:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var n=i(e(23)),a=i(e(35)),o=e(54),s=i(e(1));r.default=function(e){var t=new s.default;t.trigger=function(e){for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.emit.apply(t,[e,e].concat(i))},t.off=function(e){for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.removeListener.apply(t,[e].concat(i))};var r=function(t,r){e.postMessage({event:t,data:r})};e.addEventListener("message",function(i){var a=i.data;switch(a.cmd){case"init":var s=JSON.parse(a.config);e.demuxer=new n.default(t,a.typeSupported,s,a.vendor);try{(0,o.enableLogs)(!0===s.debug)}catch(e){console.warn("demuxerWorker: unable to enable logs")}r("init",null);break;case"demux":e.demuxer.push(a.data,a.decryptdata,a.initSegment,a.audioCodec,a.videoCodec,a.timeOffset,a.discontinuity,a.trackSwitch,a.contiguous,a.duration,a.accurateTimeOffset,a.defaultInitPTS)}}),t.on(a.default.FRAG_DECRYPTED,r),t.on(a.default.FRAG_PARSING_INIT_SEGMENT,r),t.on(a.default.FRAG_PARSED,r),t.on(a.default.ERROR,r),t.on(a.default.FRAG_PARSING_METADATA,r),t.on(a.default.FRAG_PARSING_USERDATA,r),t.on(a.default.INIT_PTS_FOUND,r),t.on(a.default.FRAG_PARSING_DATA,function(t,r){var i=[],n={event:t,data:r};r.data1&&(n.data1=r.data1.buffer,i.push(r.data1.buffer),delete r.data1),r.data2&&(n.data2=r.data2.buffer,i.push(r.data2.buffer),delete r.data2),e.postMessage(n,i)})}},{1:1,23:23,35:35,54:54}],25:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(35)),s=i(e(23)),u=i(e(24)),l=e(54),f=e(33),c=i(e(1)),d=function(){function t(r,i){n(this,t),this.hls=r,this.id=i;var a=this.observer=new c.default,d=r.config;a.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];a.emit.apply(a,[e,e].concat(r))},a.off=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];a.removeListener.apply(a,[e].concat(r))};var h=function(e,t){(t=t||{}).frag=this.frag,t.id=this.id,r.trigger(e,t)}.bind(this);a.on(o.default.FRAG_DECRYPTED,h),a.on(o.default.FRAG_PARSING_INIT_SEGMENT,h),a.on(o.default.FRAG_PARSING_DATA,h),a.on(o.default.FRAG_PARSED,h),a.on(o.default.ERROR,h),a.on(o.default.FRAG_PARSING_METADATA,h),a.on(o.default.FRAG_PARSING_USERDATA,h),a.on(o.default.INIT_PTS_FOUND,h);var v={mp4:MediaSource.isTypeSupported("video/mp4"),mpeg:MediaSource.isTypeSupported("audio/mpeg"),mp3:MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')},p=navigator.vendor;if(d.enableWorker&&"undefined"!=typeof Worker){l.logger.log("demuxing in webworker");var g=void 0;try{var y=e(3);g=this.w=y(u.default),this.onwmsg=this.onWorkerMessage.bind(this),g.addEventListener("message",this.onwmsg),g.onerror=function(e){r.trigger(o.default.ERROR,{type:f.ErrorTypes.OTHER_ERROR,details:f.ErrorDetails.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:e.message+" ("+e.filename+":"+e.lineno+")"}})},g.postMessage({cmd:"init",typeSupported:v,vendor:p,id:i,config:JSON.stringify(d)})}catch(e){l.logger.error("error while initializing DemuxerWorker, fallback on DemuxerInline"),g&&URL.revokeObjectURL(g.objectURL),this.demuxer=new s.default(a,v,d,p),this.w=void 0}}else this.demuxer=new s.default(a,v,d,p)}return a(t,[{key:"destroy",value:function(){var e=this.w;if(e)e.removeEventListener("message",this.onwmsg),e.terminate(),this.w=null;else{var t=this.demuxer;t&&(t.destroy(),this.demuxer=null)}var r=this.observer;r&&(r.removeAllListeners(),this.observer=null)}},{key:"push",value:function(e,t,r,i,n,a,o,s){var u=this.w,f=isNaN(n.startDTS)?n.start:n.startDTS,c=n.decryptdata,d=this.frag,h=!(d&&n.cc===d.cc),v=!(d&&n.level===d.level),p=d&&n.sn===d.sn+1,g=!v&&p;if(h&&l.logger.log(this.id+":discontinuity detected"),v&&l.logger.log(this.id+":switch detected"),this.frag=n,u)u.postMessage({cmd:"demux",data:e,decryptdata:c,initSegment:t,audioCodec:r,videoCodec:i,timeOffset:f,discontinuity:h,trackSwitch:v,contiguous:g,duration:a,accurateTimeOffset:o,defaultInitPTS:s},[e]);else{var y=this.demuxer;y&&y.push(e,c,t,r,i,f,h,v,g,a,o,s)}}},{key:"onWorkerMessage",value:function(e){var t=e.data,r=this.hls;switch(t.event){case"init":URL.revokeObjectURL(this.w.objectURL);break;case o.default.FRAG_PARSING_DATA:t.data.data1=new Uint8Array(t.data1),t.data2&&(t.data.data2=new Uint8Array(t.data2));default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}}}]),t}();r.default=d},{1:1,23:23,24:24,3:3,33:33,35:35,54:54}],26:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=e(54),o=function(){function e(t){i(this,e),this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}return n(e,[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}},{key:"skipBits",value:function(e){var t;this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&a.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}},{key:"skipScalingList",value:function(e){var t,r=8,i=8;for(t=0;t<e;t++)0!==i&&(i=(r+this.readEG()+256)%256),r=0===i?r:i}},{key:"readSPS",value:function(){var e,t,r,i,n,a,o,s=0,u=0,l=0,f=0,c=this.readUByte.bind(this),d=this.readBits.bind(this),h=this.readUEG.bind(this),v=this.readBoolean.bind(this),p=this.skipBits.bind(this),g=this.skipEG.bind(this),y=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);if(c(),e=c(),d(5),p(3),c(),y(),100===e||110===e||122===e||244===e||44===e||83===e||86===e||118===e||128===e){var b=h();if(3===b&&p(1),y(),y(),p(1),v())for(a=3!==b?8:12,o=0;o<a;o++)v()&&m(o<6?16:64)}y();var _=h();if(0===_)h();else if(1===_)for(p(1),g(),g(),t=h(),o=0;o<t;o++)g();y(),p(1),r=h(),i=h(),0===(n=d(1))&&p(1),p(1),v()&&(s=h(),u=h(),l=h(),f=h());var E=[1,1];if(v()&&v())switch(c()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:E=[c()<<8|c(),c()<<8|c()]}return{width:Math.ceil(16*(r+1)-2*s-2*u),height:(2-n)*(i+1)*16-(n?2:4)*(l+f),pixelRatio:E}}},{key:"readSliceType",value:function(){return this.readUByte(),this.readUEG(),this.readUEG()}}]),e}();r.default=o},{54:54}],27:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(){function e(){i(this,e)}return n(e,null,[{key:"isHeader",value:function(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}},{key:"isFooter",value:function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}},{key:"getID3Data",value:function(t,r){for(var i=r,n=0;e.isHeader(t,r);)n+=10,n+=e._readSize(t,r+6),e.isFooter(t,r+10)&&(n+=10),r+=n;if(n>0)return t.subarray(i,i+n)}},{key:"_readSize",value:function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}},{key:"getTimeStamp",value:function(t){for(var r=e.getID3Frames(t),i=0;i<r.length;i++){var n=r[i];if(e.isTimeStampFrame(n))return e._readTimeStamp(n)}}},{key:"isTimeStampFrame",value:function(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}},{key:"_getFrameData",value:function(t){var r=String.fromCharCode(t[0],t[1],t[2],t[3]),i=e._readSize(t,4);return{type:r,size:i,data:t.subarray(10,10+i)}}},{key:"getID3Frames",value:function(t){for(var r=0,i=[];e.isHeader(t,r);){for(var n=e._readSize(t,r+6),a=(r+=10)+n;r+8<a;){var o=e._getFrameData(t.subarray(r)),s=e._decodeFrame(o);s&&i.push(s),r+=o.size+10}e.isFooter(t,r)&&(r+=10)}return i}},{key:"_decodeFrame",value:function(t){return"PRIV"===t.type?e._decodePrivFrame(t):"T"===t.type[0]?e._decodeTextFrame(t):"W"===t.type[0]?e._decodeURLFrame(t):void 0}},{key:"_readTimeStamp",value:function(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}},{key:"_decodePrivFrame",value:function(t){if(!(t.size<2)){var r=e._utf8ArrayToStr(t.data),i=new Uint8Array(t.data.subarray(r.length+1));return{key:t.type,info:r,data:i.buffer}}}},{key:"_decodeTextFrame",value:function(t){if(!(t.size<2)){if("TXXX"===t.type){var r=1,i=e._utf8ArrayToStr(t.data.subarray(r));r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var a=e._utf8ArrayToStr(t.data.subarray(1));return{key:t.type,data:a}}}},{key:"_decodeURLFrame",value:function(t){if("WXXX"===t.type){if(t.size<2)return;var r=1,i=e._utf8ArrayToStr(t.data.subarray(r));r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var a=e._utf8ArrayToStr(t.data);return{key:t.type,data:a}}},{key:"_utf8ArrayToStr",value:function(e){for(var t=void 0,r=void 0,i="",n=0,a=e.length;n<a;){var o=e[n++];switch(o>>4){case 0:return i;case 1:case 2:case 3:case 4:case 5:case 6:case 7:i+=String.fromCharCode(o);break;case 12:case 13:t=e[n++],i+=String.fromCharCode((31&o)<<6|63&t);break;case 14:t=e[n++],r=e[n++],i+=String.fromCharCode((15&o)<<12|(63&t)<<6|(63&r)<<0)}}return i}}]),e}();r.default=a},{}],28:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(27)),s=e(54),u=i(e(30)),l=function(){function e(t,r,i){n(this,e),this.observer=t,this.config=i,this.remuxer=r}return a(e,[{key:"resetInitSegment",value:function(e,t,r,i){this._audioTrack={container:"audio/mpeg",type:"audio",id:-1,sequenceNumber:0,isAAC:!1,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}}},{key:"resetTimeStamp",value:function(){}},{key:"append",value:function(e,t,r,i){for(var n=o.default.getID3Data(e,0),a=90*o.default.getTimeStamp(n),s=n.length,l=e.length,f=0,c=0,d=this._audioTrack,h=[{pts:a,dts:a,data:n}];s<l;)if(u.default.isHeader(e,s)){var v=u.default.appendFrame(d,e,s,a,f);if(!v)break;s+=v.length,c=v.sample.pts,f++}else o.default.isHeader(e,s)?(n=o.default.getID3Data(e,s),h.push({pts:c,dts:c,data:n}),s+=n.length):s++;this.remuxer.remux(d,{samples:[]},{samples:h,inputTimeScale:9e4},{samples:[]},t,r,i)}},{key:"destroy",value:function(){}}],[{key:"probe",value:function(e){var t,r,i=o.default.getID3Data(e,0);if(i&&void 0!==o.default.getTimeStamp(i))for(t=i.length,r=Math.min(e.length-1,t+100);t<r;t++)if(u.default.probe(e,t))return s.logger.log("MPEG Audio sync word found !"),!0;return!1}}]),e}();r.default=l},{27:27,30:30,54:54}],29:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(e){return e&&e.__esModule?e:{default:e}}(e(35)),o=Math.pow(2,32)-1,s=function(){function e(t,r){i(this,e),this.observer=t,this.remuxer=r}return n(e,[{key:"resetTimeStamp",value:function(e){this.initPTS=e}},{key:"resetInitSegment",value:function(t,r,i,n){if(t&&t.byteLength){var o=this.initData=e.parseInitSegment(t),s={};o.audio&&(s.audio={container:"audio/mp4",codec:r,initSegment:n?t:null}),o.video&&(s.video={container:"video/mp4",codec:i,initSegment:n?t:null}),this.observer.trigger(a.default.FRAG_PARSING_INIT_SEGMENT,{tracks:s})}else r&&(this.audioCodec=r),i&&(this.videoCodec=i)}},{key:"append",value:function(t,r,i,n){var o=this.initData;o||(this.resetInitSegment(t,this.audioCodec,this.videoCodec),o=this.initData);var s=void 0,u=this.initPTS;if(void 0===u){var l=e.getStartDTS(o,t);this.initPTS=u=l-r,this.observer.trigger(a.default.INIT_PTS_FOUND,{initPTS:u})}e.offsetStartDTS(o,t,u),s=e.getStartDTS(o,t),this.remuxer.remux(o.audio,o.video,null,null,s,i,n,t)}},{key:"destroy",value:function(){}}],[{key:"probe",value:function(t){if(t.length>=8){var r=e.bin2str(t.subarray(4,8));return["moof","ftyp","styp"].indexOf(r)>=0}return!1}},{key:"bin2str",value:function(e){return String.fromCharCode.apply(null,e)}},{key:"readUint32",value:function(e,t){e.data&&(t+=e.start,e=e.data);var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}},{key:"writeUint32",value:function(e,t,r){e.data&&(t+=e.start,e=e.data),e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}},{key:"findBox",value:function(t,r){var i,n,a,o,s,u,l,f=[];if(t.data?(u=t.start,o=t.end,t=t.data):(u=0,o=t.byteLength),!r.length)return null;for(i=u;i<o;)n=e.readUint32(t,i),a=e.bin2str(t.subarray(i+4,i+8)),l=n>1?i+n:o,a===r[0]&&(1===r.length?f.push({data:t,start:i+8,end:l}):(s=e.findBox({data:t,start:i+8,end:l},r.slice(1))).length&&(f=f.concat(s))),i=l;return f}},{key:"parseInitSegment",value:function(t){var r=[];return e.findBox(t,["moov","trak"]).forEach(function(t){var i=e.findBox(t,["tkhd"])[0];if(i){var n=i.data[i.start],a=0===n?12:20,o=e.readUint32(i,a),s=e.findBox(t,["mdia","mdhd"])[0];if(s){a=0===(n=s.data[s.start])?12:20;var u=e.readUint32(s,a),l=e.findBox(t,["mdia","hdlr"])[0];if(l){var f={soun:"audio",vide:"video"}[e.bin2str(l.data.subarray(l.start+8,l.start+12))];f&&(r[o]={timescale:u,type:f},r[f]={timescale:u,id:o})}}}}),r}},{key:"getStartDTS",value:function(t,r){var i,n,a;return i=e.findBox(r,["moof","traf"]),n=[].concat.apply([],i.map(function(r){return e.findBox(r,["tfhd"]).map(function(i){var n,a,o;return n=e.readUint32(i,4),a=t[n].timescale||9e4,o=e.findBox(r,["tfdt"]).map(function(t){var r,i;return r=t.data[t.start],i=e.readUint32(t,4),1===r&&(i*=Math.pow(2,32),i+=e.readUint32(t,8)),i})[0],(o=o||1/0)/a})})),a=Math.min.apply(null,n),isFinite(a)?a:0}},{key:"offsetStartDTS",value:function(t,r,i){e.findBox(r,["moof","traf"]).map(function(r){return e.findBox(r,["tfhd"]).map(function(n){var a=e.readUint32(n,4),s=t[a].timescale||9e4;e.findBox(r,["tfdt"]).map(function(t){var r=t.data[t.start],n=e.readUint32(t,4);if(0===r)e.writeUint32(t,4,n-i*s);else{n*=Math.pow(2,32),n+=e.readUint32(t,8),n-=i*s;var a=Math.floor(n/(o+1)),u=Math.floor(n%(o+1));e.writeUint32(t,4,a),e.writeUint32(t,8,u)}})})})}}]),e}();r.default=s},{35:35}],30:[function(e,t,r){var i={BitratesMap:[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],SamplingRateMap:[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],appendFrame:function(e,t,r,i,n){if(!(r+24>t.length)){var a=this.parseHeader(t,r);if(a&&r+a.frameLength<=t.length){var o=i+n*(10368e4/a.sampleRate),s={unit:t.subarray(r,r+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),e.len+=a.frameLength,{sample:s,length:a.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,n=e[t+1]>>1&3,a=e[t+2]>>4&15,o=e[t+2]>>2&3,s=!!(2&e[t+2]);if(1!==r&&0!==a&&15!==a&&3!==o){var u=3===r?3-n:3===n?3:4,l=1e3*i.BitratesMap[14*u+a-1],f=3===r?0:2===r?1:2,c=i.SamplingRateMap[3*f+o],d=s?1:0;return{sampleRate:c,channelCount:e[t+3]>>6==3?1:2,frameLength:3===n?(3===r?12:6)*l/c+d<<2:(3===r?144:72)*l/c+d|0}}},isHeaderPattern:function(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])},isHeader:function(e,t){return!!(t+1<e.length&&this.isHeaderPattern(e,t))},probe:function(e,t){if(t+1<e.length&&this.isHeaderPattern(e,t)){var r=this.parseHeader(e,t),i=4;r&&r.frameLength&&(i=r.frameLength);var n=t+i;if(n===e.length||n+1<e.length&&this.isHeaderPattern(e,n))return!0}return!1}};t.exports=i},{}],31:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(e){return e&&e.__esModule?e:{default:e}}(e(19)),o=function(){function e(t,r,n,o){i(this,e),this.decryptdata=n,this.discardEPB=o,this.decrypter=new a.default(t,r)}return n(e,[{key:"decryptBuffer",value:function(e,t){this.decrypter.decrypt(e,this.decryptdata.key.buffer,this.decryptdata.iv.buffer,t)}},{key:"decryptAacSample",value:function(e,t,r,i){var n=e[t].unit,a=n.subarray(16,n.length-n.length%16),o=a.buffer.slice(a.byteOffset,a.byteOffset+a.length),s=this;this.decryptBuffer(o,function(a){a=new Uint8Array(a),n.set(a,16),i||s.decryptAacSamples(e,t+1,r)})}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<=e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,n,a){var o=this.discardEPB(n.data),s=this.getAvcEncryptedData(o),u=this;this.decryptBuffer(s.buffer,function(s){n.data=u.getAvcDecryptedUnit(o,s),a||u.decryptAvcSamples(e,t,r+1,i)})}},{key:"decryptAvcSamples",value:function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.length<=48||1!==a.type&&5!==a.type)){var o=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,a,o),!o)return}}}}}]),e}();r.default=o},{19:19}],32:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(22)),s=i(e(30)),u=i(e(35)),l=i(e(26)),f=i(e(31)),c=e(54),d=e(33),h=function(){function e(t,r,i,a){n(this,e),this.observer=t,this.config=i,this.typeSupported=a,this.remuxer=r,this.sampleAes=null}return a(e,[{key:"setDecryptData",value:function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new f.default(this.observer,this.config,e,this.discardEPB):this.sampleAes=null}},{key:"resetInitSegment",value:function(e,t,r,i){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack={container:"video/mp2t",type:"video",id:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],len:0,dropped:0},this._audioTrack={container:"video/mp2t",type:"audio",id:-1,inputTimeScale:9e4,duration:i,sequenceNumber:0,samples:[],len:0,isAAC:!0},this._id3Track={type:"id3",id:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],len:0},this._txtTrack={type:"text",id:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],len:0},this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=t,this.videoCodec=r,this._duration=i}},{key:"resetTimeStamp",value:function(){}},{key:"append",value:function(e,t,r,i){var n,a,o,s,l,f=e.length,h=!1;this.contiguous=r;var v=this.pmtParsed,p=this._avcTrack,g=this._audioTrack,y=this._id3Track,m=p.id,b=g.id,_=y.id,E=this._pmtId,k=p.pesData,w=g.pesData,S=y.pesData,T=this._parsePAT,A=this._parsePMT,R=this._parsePES,L=this._parseAVCPES.bind(this),O=this._parseAACPES.bind(this),D=this._parseMPEGPES.bind(this),P=this._parseID3PES.bind(this);for(f-=f%188,n=0;n<f;n+=188)if(71===e[n]){if(a=!!(64&e[n+1]),o=((31&e[n+1])<<8)+e[n+2],(48&e[n+3])>>4>1){if((s=n+5+e[n+4])===n+188)continue}else s=n+4;switch(o){case m:a&&(k&&(l=R(k))&&L(l,!1),k={data:[],size:0}),k&&(k.data.push(e.subarray(s,n+188)),k.size+=n+188-s);break;case b:a&&(w&&(l=R(w))&&(g.isAAC?O(l):D(l)),w={data:[],size:0}),w&&(w.data.push(e.subarray(s,n+188)),w.size+=n+188-s);break;case _:a&&(S&&(l=R(S))&&P(l),S={data:[],size:0}),S&&(S.data.push(e.subarray(s,n+188)),S.size+=n+188-s);break;case 0:a&&(s+=e[s]+1),E=this._pmtId=T(e,s);break;case E:a&&(s+=e[s]+1);var x=A(e,s,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);(m=x.avc)>0&&(p.id=m),(b=x.audio)>0&&(g.id=b,g.isAAC=x.isAAC),(_=x.id3)>0&&(y.id=_),h&&!v&&(c.logger.log("reparse from beginning"),h=!1,n=-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:h=!0}}else this.observer.trigger(u.default.ERROR,{type:d.ErrorTypes.MEDIA_ERROR,details:d.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});k&&(l=R(k))?(L(l,!0),p.pesData=null):p.pesData=k,w&&(l=R(w))?(g.isAAC?O(l):D(l),g.pesData=null):(w&&w.size&&c.logger.log("last AAC PES packet truncated,might overlap between fragments"),g.pesData=w),S&&(l=R(S))?(P(l),y.pesData=null):y.pesData=S,null==this.sampleAes?this.remuxer.remux(g,p,y,this._txtTrack,t,r,i):this.decryptAndRemux(g,p,y,this._txtTrack,t,r,i)}},{key:"decryptAndRemux",value:function(e,t,r,i,n,a,o){if(e.samples&&e.isAAC){var s=this;this.sampleAes.decryptAacSamples(e.samples,0,function(){s.decryptAndRemuxAvc(e,t,r,i,n,a,o)})}else this.decryptAndRemuxAvc(e,t,r,i,n,a,o)}},{key:"decryptAndRemuxAvc",value:function(e,t,r,i,n,a,o){if(t.samples){var s=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,function(){s.remuxer.remux(e,t,r,i,n,a,o)})}else this.remuxer.remux(e,t,r,i,n,a,o)}},{key:"destroy",value:function(){this._initPTS=this._initDTS=void 0,this._duration=0}},{key:"_parsePAT",value:function(e,t){return(31&e[t+10])<<8|e[t+11]}},{key:"_parsePMT",value:function(e,t,r,i){var n,a,o={audio:-1,avc:-1,id3:-1,isAAC:!0};for(n=t+3+((15&e[t+1])<<8|e[t+2])-4,t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){switch(a=(31&e[t+1])<<8|e[t+2],e[t]){case 207:if(!i){c.logger.log("unkown stream type:"+e[t]);break}case 15:-1===o.audio&&(o.audio=a);break;case 21:-1===o.id3&&(o.id3=a);break;case 219:if(!i){c.logger.log("unkown stream type:"+e[t]);break}case 27:-1===o.avc&&(o.avc=a);break;case 3:case 4:r?-1===o.audio&&(o.audio=a,o.isAAC=!1):c.logger.log("MPEG audio found, not supported in this browser for now");break;case 36:c.logger.warn("HEVC stream type found, not supported for now");break;default:c.logger.log("unkown stream type:"+e[t])}t+=5+((15&e[t+3])<<8|e[t+4])}return o}},{key:"_parsePES",value:function(e){var t,r,i,n,a,o,s,u,l=0,f=e.data;if(!e||0===e.size)return null;for(;f[0].length<19&&f.length>1;){var d=new Uint8Array(f[0].length+f[1].length);d.set(f[0]),d.set(f[1],f[0].length),f[0]=d,f.splice(1,1)}if(t=f[0],1===(t[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;192&(r=t[7])&&((o=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2)>4294967295&&(o-=8589934592),64&r?((s=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>4294967295&&(s-=8589934592),o-s>54e5&&(c.logger.warn(Math.round((o-s)/9e4)+"s delta between PTS and DTS, align them"),o=s)):s=o),u=(n=t[8])+9,e.size-=u,a=new Uint8Array(e.size);for(var h=0,v=f.length;h<v;h++){var p=(t=f[h]).byteLength;if(u){if(u>p){u-=p;continue}t=t.subarray(u),p-=u,u=0}a.set(t,l),l+=p}return i&&(i-=n+3),{data:a,pts:o,dts:s,len:i}}return null}},{key:"pushAccesUnit",value:function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;!this.config.forceKeyFrameOnDiscontinuity||!0===e.key||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&c.logger.log(e.pts+"/"+e.dts+":"+e.debug)}},{key:"_parseAVCPES",value:function(e,t){var r,i,n,a=this,o=this._avcTrack,s=this._parseAVCNALu(e.data),u=this.avcSample,f=!1;e.data=null,s.forEach(function(t){switch(t.type){case 1:i=!0,u.frame=!0;var s=t.data;if(f&&s.length>4){var c=new l.default(s).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(u.key=!0)}break;case 5:i=!0,u||(u=a.avcSample=a._createAVCSample(!0,e.pts,e.dts,"")),u.key=!0,u.frame=!0;break;case 6:i=!0,(r=new l.default(a.discardEPB(t.data))).readUByte();for(var d=0,h=0,v=!1,p=0;!v&&r.bytesAvailable>1;){d=0;do{d+=p=r.readUByte()}while(255===p);h=0;do{h+=p=r.readUByte()}while(255===p);if(4===d&&0!==r.bytesAvailable){if(v=!0,181===r.readUByte()&&49===r.readUShort()&&1195456820===r.readUInt()&&3===r.readUByte()){var g=r.readUByte(),y=31&g,m=[g,r.readUByte()];for(n=0;n<y;n++)m.push(r.readUByte()),m.push(r.readUByte()),m.push(r.readUByte());a._insertSampleInOrder(a._txtTrack.samples,{type:3,pts:e.pts,bytes:m})}}else if(h<r.bytesAvailable)for(n=0;n<h;n++)r.readUByte()}break;case 7:if(i=!0,f=!0,!o.sps){var b=(r=new l.default(t.data)).readSPS();o.width=b.width,o.height=b.height,o.pixelRatio=b.pixelRatio,o.sps=[t.data],o.duration=a._duration;var _=t.data.subarray(1,4),E="avc1.";for(n=0;n<3;n++){var k=_[n].toString(16);k.length<2&&(k="0"+k),E+=k}o.codec=E}break;case 8:i=!0,o.pps||(o.pps=[t.data]);break;case 9:i=!1,u&&a.pushAccesUnit(u,o),u=a.avcSample=a._createAVCSample(!1,e.pts,e.dts,"");break;case 12:i=!1;break;default:i=!1,u&&(u.debug+="unknown NAL "+t.type+" ")}u&&i&&u.units.push(t)}),t&&u&&(this.pushAccesUnit(u,o),this.avcSample=null)}},{key:"_createAVCSample",value:function(e,t,r,i){return{key:e,pts:t,dts:r,units:[],debug:i}}},{key:"_insertSampleInOrder",value:function(e,t){var r=e.length;if(r>0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts<e[i].pts){e.splice(i,0,t);break}}else e.push(t)}},{key:"_getLastNalUnit",value:function(){var e=this.avcSample,t=void 0;if(!e||0===e.units.length){var r=this._avcTrack.samples;e=r[r.length-1]}if(e){var i=e.units;t=i[i.length-1]}return t}},{key:"_parseAVCNALu",value:function(e){var t,r,i,n,a=0,o=e.byteLength,s=this._avcTrack,u=s.naluState||0,l=u,f=[],c=-1;for(-1===u&&(c=0,n=31&e[0],u=0,a=1);a<o;)if(t=e[a++],u)if(1!==u)if(t)if(1===t){if(c>=0)i={data:e.subarray(c,a-u-1),type:n},f.push(i);else{var d=this._getLastNalUnit();if(d&&(l&&a<=4-l&&d.state&&(d.data=d.data.subarray(0,d.data.byteLength-l)),(r=a-u-1)>0)){var h=new Uint8Array(d.data.byteLength+r);h.set(d.data,0),h.set(e.subarray(0,r),d.data.byteLength),d.data=h}}a<o?(c=a,n=31&e[a],u=0):u=-1}else u=0;else u=3;else u=t?0:2;else u=t?0:1;if(c>=0&&u>=0&&(i={data:e.subarray(c,o),type:n,state:u},f.push(i)),0===f.length){var v=this._getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+e.byteLength);p.set(v.data,0),p.set(e,v.data.byteLength),v.data=p}}return s.naluState=u,f}},{key:"discardEPB",value:function(e){for(var t,r,i=e.byteLength,n=[],a=1;a<i-2;)0===e[a]&&0===e[a+1]&&3===e[a+2]?(n.push(a+2),a+=2):a++;if(0===n.length)return e;t=i-n.length,r=new Uint8Array(t);var o=0;for(a=0;a<t;o++,a++)o===n[0]&&(o++,n.shift()),r[a]=e[o];return r}},{key:"_parseAACPES",value:function(e){var t,r,i,n,a,s=this._audioTrack,l=e.data,f=e.pts,h=this.aacOverFlow,v=this.aacLastPTS;if(h){var p=new Uint8Array(h.byteLength+l.byteLength);p.set(h,0),p.set(l,h.byteLength),l=p}for(i=0,a=l.length;i<a-1&&!o.default.isHeader(l,i);i++);if(i){var g,y;if(i<a-1?(g="AAC PES did not start with ADTS header,offset:"+i,y=!1):(g="no ADTS header found in AAC PES",y=!0),c.logger.warn("parsing error:"+g),this.observer.trigger(u.default.ERROR,{type:d.ErrorTypes.MEDIA_ERROR,details:d.ErrorDetails.FRAG_PARSING_ERROR,fatal:y,reason:g}),y)return}if(o.default.initTrackConfig(s,this.observer,l,i,this.audioCodec),r=0,t=o.default.getFrameDuration(s.samplerate),h&&v){var m=v+t;Math.abs(m-f)>1&&(c.logger.log("AAC: align PTS for overlapping frames by "+Math.round((m-f)/90)),f=m)}for(;i<a;)if(o.default.isHeader(l,i)&&i+5<a){var b=o.default.appendFrame(s,l,i,f,r);if(!b)break;i+=b.length,n=b.sample.pts,r++}else i++;h=i<a?l.subarray(i,a):null,this.aacOverFlow=h,this.aacLastPTS=n}},{key:"_parseMPEGPES",value:function(e){for(var t=e.data,r=t.length,i=0,n=0,a=e.pts;n<r;)if(s.default.isHeader(t,n)){var o=s.default.appendFrame(this._audioTrack,t,n,a,i);if(!o)break;n+=o.length,i++}else n++}},{key:"_parseID3PES",value:function(e){this._id3Track.samples.push(e)}}],[{key:"probe",value:function(e){return e.length>=564&&71===e[0]&&71===e[188]&&71===e[376]}}]),e}();r.default=h},{22:22,26:26,30:30,31:31,33:33,35:35,54:54}],33:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});r.ErrorTypes={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},r.ErrorDetails={MANIFEST_LOAD_ERROR:"manifestLoadError",MANIFEST_LOAD_TIMEOUT:"manifestLoadTimeOut",MANIFEST_PARSING_ERROR:"manifestParsingError",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"manifestIncompatibleCodecsError",LEVEL_LOAD_ERROR:"levelLoadError",LEVEL_LOAD_TIMEOUT:"levelLoadTimeOut",LEVEL_SWITCH_ERROR:"levelSwitchError",AUDIO_TRACK_LOAD_ERROR:"audioTrackLoadError",AUDIO_TRACK_LOAD_TIMEOUT:"audioTrackLoadTimeOut",FRAG_LOAD_ERROR:"fragLoadError",FRAG_LOOP_LOADING_ERROR:"fragLoopLoadingError",FRAG_LOAD_TIMEOUT:"fragLoadTimeOut",FRAG_DECRYPT_ERROR:"fragDecryptError",FRAG_PARSING_ERROR:"fragParsingError",REMUX_ALLOC_ERROR:"remuxAllocError",KEY_LOAD_ERROR:"keyLoadError",KEY_LOAD_TIMEOUT:"keyLoadTimeOut",BUFFER_ADD_CODEC_ERROR:"bufferAddCodecError",BUFFER_APPEND_ERROR:"bufferAppendError",BUFFER_APPENDING_ERROR:"bufferAppendingError",BUFFER_STALLED_ERROR:"bufferStalledError",BUFFER_FULL_ERROR:"bufferFullError",BUFFER_SEEK_OVER_HOLE:"bufferSeekOverHole",BUFFER_NUDGE_ON_STALL:"bufferNudgeOnStall",INTERNAL_EXCEPTION:"internalException",WEBVTT_EXCEPTION:"webVTTException"}},{}],34:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=e(54),s=e(33),u=function(e){return e&&e.__esModule?e:{default:e}}(e(35)),l=function(){function e(t){i(this,e),this.hls=t,this.onEvent=this.onEvent.bind(this);for(var r=arguments.length,n=Array(r>1?r-1:0),a=1;a<r;a++)n[a-1]=arguments[a];this.handledEvents=n,this.useGenericHandler=!0,this.registerListeners()}return a(e,[{key:"destroy",value:function(){this.unregisterListeners()}},{key:"isEventHandler",value:function(){return"object"===n(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent}},{key:"registerListeners",value:function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){if("hlsEventGeneric"===e)throw new Error("Forbidden event name: "+e);this.hls.on(e,this.onEvent)},this)}},{key:"unregisterListeners",value:function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){this.hls.off(e,this.onEvent)},this)}},{key:"onEvent",value:function(e,t){this.onEventGeneric(e,t)}},{key:"onEventGeneric",value:function(e,t){try{(function(e,t){var r="on"+e.replace("hls","");if("function"!=typeof this[r])throw new Error("Event "+e+" has no generic handler in this "+this.constructor.name+" class (tried "+r+")");return this[r].bind(this,t)}).call(this,e,t).call()}catch(t){o.logger.error("internal error happened while processing "+e+":"+t.message),this.hls.trigger(u.default.ERROR,{type:s.ErrorTypes.OTHER_ERROR,details:s.ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:e,err:t})}}}]),e}();r.default=l},{33:33,35:35,54:54}],35:[function(e,t,r){t.exports={MEDIA_ATTACHING:"hlsMediaAttaching",MEDIA_ATTACHED:"hlsMediaAttached",MEDIA_DETACHING:"hlsMediaDetaching",MEDIA_DETACHED:"hlsMediaDetached",BUFFER_RESET:"hlsBufferReset",BUFFER_CODECS:"hlsBufferCodecs",BUFFER_CREATED:"hlsBufferCreated",BUFFER_APPENDING:"hlsBufferAppending",BUFFER_APPENDED:"hlsBufferAppended",BUFFER_EOS:"hlsBufferEos",BUFFER_FLUSHING:"hlsBufferFlushing",BUFFER_FLUSHED:"hlsBufferFlushed",MANIFEST_LOADING:"hlsManifestLoading",MANIFEST_LOADED:"hlsManifestLoaded",MANIFEST_PARSED:"hlsManifestParsed",LEVEL_SWITCH:"hlsLevelSwitch",LEVEL_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",AUDIO_TRACK_SWITCH:"hlsAudioTrackSwitch",AUDIO_TRACK_SWITCHING:"hlsAudioTrackSwitching",AUDIO_TRACK_SWITCHED:"hlsAudioTrackSwitched",AUDIO_TRACK_LOADING:"hlsAudioTrackLoading",AUDIO_TRACK_LOADED:"hlsAudioTrackLoaded",SUBTITLE_TRACKS_UPDATED:"hlsSubtitleTracksUpdated",SUBTITLE_TRACK_SWITCH:"hlsSubtitleTrackSwitch",SUBTITLE_TRACK_LOADING:"hlsSubtitleTrackLoading",SUBTITLE_TRACK_LOADED:"hlsSubtitleTrackLoaded",SUBTITLE_FRAG_PROCESSED:"hlsSubtitleFragProcessed",INIT_PTS_FOUND:"hlsInitPtsFound",FRAG_LOADING:"hlsFragLoading",FRAG_LOAD_PROGRESS:"hlsFragLoadProgress",FRAG_LOAD_EMERGENCY_ABORTED:"hlsFragLoadEmergencyAborted",FRAG_LOADED:"hlsFragLoaded",FRAG_DECRYPTED:"hlsFragDecrypted",FRAG_PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:"hlsFragParsed",FRAG_BUFFERED:"hlsFragBuffered",FRAG_CHANGED:"hlsFragChanged",FPS_DROP:"hlsFpsDrop",FPS_DROP_LEVEL_CAPPING:"hlsFpsDropLevelCapping",ERROR:"hlsError",DESTROYING:"hlsDestroying",KEY_LOADING:"hlsKeyLoading",KEY_LOADED:"hlsKeyLoaded",STREAM_STATE_TRANSITION:"hlsStreamStateTransition"}},{}],36:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(){function e(){i(this,e)}return n(e,null,[{key:"getSilentFrame",value:function(e,t){switch(e){case"mp4a.40.2":if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null}}]),e}();r.default=a},{}],37:[function(e,t,r){var i={isBuffered:function(e,t){if(e)for(var r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)&&t<=r.end(i))return!0;return!1},bufferInfo:function(e,t,r){if(e){var i,n=e.buffered,a=[];for(i=0;i<n.length;i++)a.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(a,t,r)}return{len:0,start:t,end:t,nextStart:void 0}},bufferedInfo:function(e,t,r){var i,n,a,o,s,u=[];for(e.sort(function(e,t){var r=e.start-t.start;return r||t.end-e.end}),s=0;s<e.length;s++){var l=u.length;if(l){var f=u[l-1].end;e[s].start-f<r?e[s].end>f&&(u[l-1].end=e[s].end):u.push(e[s])}else u.push(e[s])}for(s=0,i=0,n=a=t;s<u.length;s++){var c=u[s].start,d=u[s].end;if(t+r>=c&&t<d)n=c,i=(a=d)-t;else if(t+r<c){o=c;break}}return{len:i,start:n,end:a,nextStart:o}}};t.exports=i},{}],38:[function(e,t,r){var i=e(54),n={mergeDetails:function(e,t){var r,a=Math.max(e.startSN,t.startSN)-t.startSN,o=Math.min(e.endSN,t.endSN)-t.startSN,s=t.startSN-e.startSN,u=e.fragments,l=t.fragments,f=0;if(o<a)t.PTSKnown=!1;else{for(var c=a;c<=o;c++){var d=u[s+c],h=l[c];h&&d&&(f=d.cc-h.cc,isNaN(d.startPTS)||(h.start=h.startPTS=d.startPTS,h.endPTS=d.endPTS,h.duration=d.duration,h.backtracked=d.backtracked,h.dropped=d.dropped,r=h))}if(f)for(i.logger.log("discontinuity sliding from playlist, take drift into account"),c=0;c<l.length;c++)l[c].cc+=f;if(r)n.updateFragPTSDTS(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS);else if(s>=0&&s<u.length){var v=u[s].start;for(c=0;c<l.length;c++)l[c].start+=v}t.PTSKnown=e.PTSKnown}},updateFragPTSDTS:function(e,t,r,i,a,o){var s=r;if(!isNaN(t.startPTS)){var u=Math.abs(t.startPTS-r);isNaN(t.deltaPTS)?t.deltaPTS=u:t.deltaPTS=Math.max(u,t.deltaPTS),s=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),i=Math.max(i,t.endPTS),a=Math.min(a,t.startDTS),o=Math.max(o,t.endDTS)}var l=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=s,t.endPTS=i,t.startDTS=a,t.endDTS=o,t.duration=i-r;var f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;var c,d,h;for(c=f-e.startSN,t=(d=e.fragments)[c],h=c;h>0;h--)n.updatePTS(d,h,h-1);for(h=c;h<d.length-1;h++)n.updatePTS(d,h,h+1);return e.PTSKnown=!0,l},updatePTS:function(e,t,r){var n=e[t],a=e[r],o=a.startPTS;isNaN(o)?a.start=r>t?n.start+n.duration:Math.max(n.start-a.duration,0):r>t?(n.duration=o-n.start,n.duration<0&&i.logger.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!")):(a.duration=n.start-o,a.duration<0&&i.logger.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!"))}};t.exports=n},{54:54}],39:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(2)),s=i(e(35)),u=e(33),l=i(e(43)),f=i(e(41)),c=i(e(42)),d=i(e(13)),h=i(e(12)),v=i(e(11)),p=e(54),g=i(e(1)),y=e(4),m=function(){function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};n(this,e);var i=e.DefaultConfig;if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");for(var a in i)a in r||(r[a]=i[a]);if(void 0!==r.liveMaxLatencyDurationCount&&r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(r.liveMaxLatencyDuration<=r.liveSyncDuration||void 0===r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');(0,p.enableLogs)(r.debug),this.config=r,this._autoLevelCapping=-1;var o=this.observer=new g.default;o.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];o.emit.apply(o,[e,e].concat(r))},o.off=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];o.removeListener.apply(o,[e].concat(r))},this.on=o.on.bind(o),this.off=o.off.bind(o),this.trigger=o.trigger.bind(o);var s=this.abrController=new r.abrController(this),u=new r.bufferController(this),y=new r.capLevelController(this),m=new r.fpsController(this),b=new l.default(this),_=new f.default(this),E=new c.default(this),k=new v.default(this),w=[this.levelController=new h.default(this),this.streamController=new d.default(this)],S=r.audioStreamController;S&&w.push(new S(this)),this.networkControllers=w;var T=[b,_,E,s,u,y,m,k];if(S=r.audioTrackController){var A=new S(this);this.audioTrackController=A,T.push(A)}if(S=r.subtitleTrackController){var R=new S(this);this.subtitleTrackController=R,T.push(R)}[r.subtitleStreamController,r.timelineController].forEach(function(e){e&&T.push(new e(t))}),this.coreComponents=T}return a(e,null,[{key:"isSupported",value:function(){var e=window.MediaSource=window.MediaSource||window.WebKitMediaSource,t=window.SourceBuffer=window.SourceBuffer||window.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return r&&i}},{key:"version",get:function(){return"0.7.10"}},{key:"Events",get:function(){return s.default}},{key:"ErrorTypes",get:function(){return u.ErrorTypes}},{key:"ErrorDetails",get:function(){return u.ErrorDetails}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:y.hlsDefaultConfig},set:function(t){e.defaultConfig=t}}]),a(e,[{key:"destroy",value:function(){p.logger.log("destroy"),this.trigger(s.default.DESTROYING),this.detachMedia(),this.coreComponents.concat(this.networkControllers).forEach(function(e){e.destroy()}),this.url=null,this.observer.removeAllListeners(),this._autoLevelCapping=-1}},{key:"attachMedia",value:function(e){p.logger.log("attachMedia"),this.media=e,this.trigger(s.default.MEDIA_ATTACHING,{media:e})}},{key:"detachMedia",value:function(){p.logger.log("detachMedia"),this.trigger(s.default.MEDIA_DETACHING),this.media=null}},{key:"loadSource",value:function(e){e=o.default.buildAbsoluteURL(window.location.href,e,{alwaysNormalize:!0}),p.logger.log("loadSource:"+e),this.url=e,this.trigger(s.default.MANIFEST_LOADING,{url:e})}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;p.logger.log("startLoad("+e+")"),this.networkControllers.forEach(function(t){t.startLoad(e)})}},{key:"stopLoad",value:function(){p.logger.log("stopLoad"),this.networkControllers.forEach(function(e){e.stopLoad()})}},{key:"swapAudioCodec",value:function(){p.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){p.logger.log("recoverMediaError");var e=this.media;this.detachMedia(),this.attachMedia(e)}},{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){p.logger.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){p.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){p.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){p.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){p.logger.log("set startLevel:"+e);var t=this;-1!==e&&(e=Math.max(e,t.minAutoLevel)),t.levelController.startLevel=e}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){p.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){for(var e=this,t=e.levels,r=e.config.minAutoBitrate,i=t?t.length:0,n=0;n<i;n++)if((t[n].realBitrate?Math.max(t[n].realBitrate,t[n].bitrate):t[n].bitrate)>r)return n;return 0}},{key:"maxAutoLevel",get:function(){var e=this,t=e.levels,r=e.autoLevelCapping;return-1===r&&t&&t.length?t.length-1:r}},{key:"nextAutoLevel",get:function(){var e=this;return Math.min(Math.max(e.abrController.nextAutoLevel,e.minAutoLevel),e.maxAutoLevel)},set:function(e){var t=this;t.abrController.nextAutoLevel=Math.max(t.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}}]),e}();r.default=m},{1:1,11:11,12:12,13:13,2:2,33:33,35:35,4:4,41:41,42:42,43:43,54:54}],40:[function(e,t,r){t.exports=e(39).default},{39:39}],41:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(33),c=e(54),d=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.FRAG_LOADING));return r.loaders={},r}return o(t,l.default),s(t,[{key:"destroy",value:function(){var e=this.loaders;for(var t in e){var r=e[t];r&&r.destroy()}this.loaders={},l.default.prototype.destroy.call(this)}},{key:"onFragLoading",value:function(e){var t=e.frag,r=t.type,i=this.loaders[r],n=this.hls.config;t.loaded=0,i&&(c.logger.warn("abort previous fragment loader for type:"+r),i.abort()),i=this.loaders[r]=t.loader=void 0!==n.fLoader?new n.fLoader(n):new n.loader(n);var a=void 0,o=void 0,s=void 0;a={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var u=t.byteRangeStartOffset,l=t.byteRangeEndOffset;isNaN(u)||isNaN(l)||(a.rangeStart=u,a.rangeEnd=l),o={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout},s={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},i.load(a,o,s)}},{key:"loadsuccess",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=e.data,a=r.frag;a.loader=void 0,this.loaders[a.type]=void 0,this.hls.trigger(u.default.FRAG_LOADED,{payload:n,frag:a,stats:t,networkDetails:i})}},{key:"loaderror",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=t.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(u.default.ERROR,{type:f.ErrorTypes.NETWORK_ERROR,details:f.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})}},{key:"loadtimeout",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=t.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(u.default.ERROR,{type:f.ErrorTypes.NETWORK_ERROR,details:f.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})}},{key:"loadprogress",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=t.frag;n.loaded=e.loaded,this.hls.trigger(u.default.FRAG_LOAD_PROGRESS,{frag:n,stats:e,networkDetails:i})}}]),t}();r.default=d},{33:33,34:34,35:35,54:54}],42:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(35)),l=i(e(34)),f=e(33),c=e(54),d=function(e){function t(e){n(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,u.default.KEY_LOADING));return r.loaders={},r.decryptkey=null,r.decrypturl=null,r}return o(t,l.default),s(t,[{key:"destroy",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},l.default.prototype.destroy.call(this)}},{key:"onKeyLoading",value:function(e){var t=e.frag,r=t.type,i=this.loaders[r],n=t.decryptdata,a=n.uri;if(a!==this.decrypturl||null===this.decryptkey){var o=this.hls.config;i&&(c.logger.warn("abort previous key loader for type:"+r),i.abort()),t.loader=this.loaders[r]=new o.loader(o),this.decrypturl=a,this.decryptkey=null;var s=void 0,l=void 0,f=void 0;s={url:a,frag:t,responseType:"arraybuffer"},l={timeout:o.fragLoadingTimeOut,maxRetry:o.fragLoadingMaxRetry,retryDelay:o.fragLoadingRetryDelay,maxRetryDelay:o.fragLoadingMaxRetryTimeout},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},t.loader.load(s,l,f)}else this.decryptkey&&(n.key=this.decryptkey,this.hls.trigger(u.default.KEY_LOADED,{frag:t}))}},{key:"loadsuccess",value:function(e,t,r){var i=r.frag;this.decryptkey=i.decryptdata.key=new Uint8Array(e.data),i.loader=void 0,this.loaders[i.type]=void 0,this.hls.trigger(u.default.KEY_LOADED,{frag:i})}},{key:"loaderror",value:function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(u.default.ERROR,{type:f.ErrorTypes.NETWORK_ERROR,details:f.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})}},{key:"loadtimeout",value:function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(u.default.ERROR,{type:f.ErrorTypes.NETWORK_ERROR,details:f.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})}}]),t}();r.default=d},{33:33,34:34,35:35,54:54}],43:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),u=i(e(2)),l=i(e(35)),f=i(e(34)),c=e(33),d=i(e(47)),h=e(54),v=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,p=/#EXT-X-MEDIA:(.*)/g,g=new RegExp([/#EXTINF:(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),y=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,m=function(){function e(){o(this,e),this.method=null,this.key=null,this.iv=null,this._uri=null}return s(e,[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=u.default.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}]),e}(),b=function(){function e(){o(this,e),this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[]}return s(e,[{key:"createInitializationVector",value:function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}},{key:"fragmentDecryptdataFromLevelkey",value:function(e,t){var r=e;return e&&e.method&&e.uri&&!e.iv&&((r=new m).method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}},{key:"cloneObj",value:function(e){return JSON.parse(JSON.stringify(e))}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=u.default.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"programDateTime",get:function(){return!this._programDateTime&&this.rawProgramDateTime&&(this._programDateTime=new Date(Date.parse(this.rawProgramDateTime))),this._programDateTime}},{key:"byteRange",get:function(){if(!this._byteRange){var e=this._byteRange=[];if(this.rawByteRange){var t=this.rawByteRange.split("@",2);if(1===t.length){var r=this.lastByteRangeEndOffset;e[0]=r||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0]}}return this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}}]),e}(),_=function(e){function t(e){o(this,t);var r=n(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,l.default.MANIFEST_LOADING,l.default.LEVEL_LOADING,l.default.AUDIO_TRACK_LOADING,l.default.SUBTITLE_TRACK_LOADING));return r.loaders={},r}return a(t,f.default),s(t,[{key:"destroy",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},f.default.prototype.destroy.call(this)}},{key:"onManifestLoading",value:function(e){this.load(e.url,{type:"manifest"})}},{key:"onLevelLoading",value:function(e){this.load(e.url,{type:"level",level:e.level,id:e.id})}},{key:"onAudioTrackLoading",value:function(e){this.load(e.url,{type:"audioTrack",id:e.id})}},{key:"onSubtitleTrackLoading",value:function(e){this.load(e.url,{type:"subtitleTrack",id:e.id})}},{key:"load",value:function(e,t){var r=this.loaders[t.type];if(r){var i=r.context;if(i&&i.url===e)return void h.logger.trace("playlist request ongoing");h.logger.warn("abort previous loader for type:"+t.type),r.abort()}var n=this.hls.config,a=void 0,o=void 0,s=void 0,u=void 0;"manifest"===t.type?(a=n.manifestLoadingMaxRetry,o=n.manifestLoadingTimeOut,s=n.manifestLoadingRetryDelay,u=n.manifestLoadingMaxRetryTimeout):(a=n.levelLoadingMaxRetry,o=n.levelLoadingTimeOut,s=n.levelLoadingRetryDelay,u=n.levelLoadingMaxRetryTimeout,h.logger.log("loading playlist for "+t.type+" "+(t.level||t.id))),r=this.loaders[t.type]=t.loader=void 0!==n.pLoader?new n.pLoader(n):new n.loader(n),t.url=e,t.responseType="";var l=void 0,f=void 0;l={timeout:o,maxRetry:a,retryDelay:s,maxRetryDelay:u},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},r.load(t,l,f)}},{key:"resolve",value:function(e,t){return u.default.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"parseMasterPlaylist",value:function(e,t){var r=[],i=void 0;for(v.lastIndex=0;null!=(i=v.exec(e));){var n={},a=n.attrs=new d.default(i[1]);n.url=this.resolve(i[2],t);var o=a.decimalResolution("RESOLUTION");o&&(n.width=o.width,n.height=o.height),n.bitrate=a.decimalInteger("AVERAGE-BANDWIDTH")||a.decimalInteger("BANDWIDTH"),n.name=a.NAME;var s=a.CODECS;if(s){s=s.split(/[ ,]+/);for(var u=0;u<s.length;u++){var l=s[u];-1!==l.indexOf("avc1")?n.videoCodec=this.avc1toavcoti(l):-1!==l.indexOf("hvc1")?n.videoCodec=l:n.audioCodec=l}}r.push(n)}return r}},{key:"parseMasterPlaylistMedia",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=void 0,a=[],o=0;for(p.lastIndex=0;null!=(n=p.exec(e));){var s={},u=new d.default(n[1]);u.TYPE===r&&(s.groupId=u["GROUP-ID"],s.name=u.NAME,s.type=r,s.default="YES"===u.DEFAULT,s.autoselect="YES"===u.AUTOSELECT,s.forced="YES"===u.FORCED,u.URI&&(s.url=this.resolve(u.URI,t)),s.lang=u.LANGUAGE,s.name||(s.name=s.lang),i&&(s.audioCodec=i),s.id=o++,a.push(s))}return a}},{key:"avc1toavcoti",value:function(e){var t,r=e.split(".");return r.length>2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}},{key:"parseLevelPlaylist",value:function(e,t,r,i){var n,a,o=0,s=0,u={type:null,version:null,url:t,fragments:[],live:!0,startSN:0},l=new m,f=0,c=null,v=new b;for(g.lastIndex=0;null!==(n=g.exec(e));){var p=n[1];if(p){v.duration=parseFloat(p);var _=(" "+n[2]).slice(1);v.title=_||null,v.tagList.push(_?["INF",p,_]:["INF",p])}else if(n[3]){if(!isNaN(v.duration)){var E=o++;v.type=i,v.start=s,v.levelkey=l,v.sn=E,v.level=r,v.cc=f,v.baseurl=t,v.relurl=(" "+n[3]).slice(1),u.fragments.push(v),c=v,s+=v.duration,v=new b}}else if(n[4]){if(v.rawByteRange=(" "+n[4]).slice(1),c){var k=c.byteRangeEndOffset;k&&(v.lastByteRangeEndOffset=k)}}else if(n[5])v.rawProgramDateTime=(" "+n[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]);else{for(n=n[0].match(y),a=1;a<n.length&&void 0===n[a];a++);var w=(" "+n[a+1]).slice(1),S=(" "+n[a+2]).slice(1);switch(n[a]){case"#":v.tagList.push(S?[w,S]:[w]);break;case"PLAYLIST-TYPE":u.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":o=u.startSN=parseInt(w);break;case"TARGETDURATION":u.targetduration=parseFloat(w);break;case"VERSION":u.version=parseInt(w);break;case"EXTM3U":break;case"ENDLIST":u.live=!1;break;case"DIS":f++,v.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":f=parseInt(w);break;case"KEY":var T=w,A=new d.default(T),R=A.enumeratedString("METHOD"),L=A.URI,O=A.hexadecimalInteger("IV");R&&(l=new m,L&&["AES-128","SAMPLE-AES"].indexOf(R)>=0&&(l.method=R,l.baseuri=t,l.reluri=L,l.key=null,l.iv=O));break;case"START":var D=w,P=new d.default(D).decimalFloatingPoint("TIME-OFFSET");isNaN(P)||(u.startTimeOffset=P);break;case"MAP":var x=new d.default(w);v.relurl=x.URI,v.rawByteRange=x.BYTERANGE,v.baseurl=t,v.level=r,v.type=i,v.sn="initSegment",u.initSegment=v,v=new b;break;default:h.logger.warn("line parsed but not handled: "+n)}}}return(v=c)&&!v.relurl&&(u.fragments.pop(),s-=v.duration),u.totalduration=s,u.averagetargetduration=s/u.fragments.length,u.endSN=o-1,u}},{key:"loadsuccess",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=e.data,a=e.url,o=r.type,s=r.id,u=r.level,f=this.hls;if(this.loaders[o]=void 0,void 0!==a&&0!==a.indexOf("data:")||(a=r.url),t.tload=performance.now(),0===n.indexOf("#EXTM3U"))if(n.indexOf("#EXTINF:")>0){var d="audioTrack"!==o&&"subtitleTrack"!==o,v=isNaN(u)?isNaN(s)?0:s:u,p=this.parseLevelPlaylist(n,a,v,"audioTrack"===o?"audio":"subtitleTrack"===o?"subtitle":"main");p.tload=t.tload,"manifest"===o&&f.trigger(l.default.MANIFEST_LOADED,{levels:[{url:a,details:p}],audioTracks:[],url:a,stats:t,networkDetails:i}),t.tparsed=performance.now(),p.targetduration?d?f.trigger(l.default.LEVEL_LOADED,{details:p,level:u||0,id:s||0,stats:t,networkDetails:i}):"audioTrack"===o?f.trigger(l.default.AUDIO_TRACK_LOADED,{details:p,id:s,stats:t,networkDetails:i}):"subtitleTrack"===o&&f.trigger(l.default.SUBTITLE_TRACK_LOADED,{details:p,id:s,stats:t,networkDetails:i}):f.trigger(l.default.ERROR,{type:c.ErrorTypes.NETWORK_ERROR,details:c.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"invalid targetduration",networkDetails:i})}else{var g=this.parseMasterPlaylist(n,a);if(g.length){var y=this.parseMasterPlaylistMedia(n,a,"AUDIO",g[0].audioCodec),m=this.parseMasterPlaylistMedia(n,a,"SUBTITLES");if(y.length){var b=!1;y.forEach(function(e){e.url||(b=!0)}),!1===b&&g[0].audioCodec&&!g[0].attrs.AUDIO&&(h.logger.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main"}))}f.trigger(l.default.MANIFEST_LOADED,{levels:g,audioTracks:y,subtitles:m,url:a,stats:t,networkDetails:i})}else f.trigger(l.default.ERROR,{type:c.ErrorTypes.NETWORK_ERROR,details:c.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"no level found in manifest",networkDetails:i})}else f.trigger(l.default.ERROR,{type:c.ErrorTypes.NETWORK_ERROR,details:c.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"no EXTM3U delimiter",networkDetails:i})}},{key:"loaderror",value:function(e,t){var r,i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=t.loader;switch(t.type){case"manifest":r=c.ErrorDetails.MANIFEST_LOAD_ERROR,i=!0;break;case"level":r=c.ErrorDetails.LEVEL_LOAD_ERROR,i=!1;break;case"audioTrack":r=c.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,i=!1}a&&(a.abort(),this.loaders[t.type]=void 0),this.hls.trigger(l.default.ERROR,{type:c.ErrorTypes.NETWORK_ERROR,details:r,fatal:i,url:a.url,loader:a,response:e,context:t,networkDetails:n})}},{key:"loadtimeout",value:function(e,t){var r,i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=t.loader;switch(t.type){case"manifest":r=c.ErrorDetails.MANIFEST_LOAD_TIMEOUT,i=!0;break;case"level":r=c.ErrorDetails.LEVEL_LOAD_TIMEOUT,i=!1;break;case"audioTrack":r=c.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT,i=!1}a&&(a.abort(),this.loaders[t.type]=void 0),this.hls.trigger(l.default.ERROR,{type:c.ErrorTypes.NETWORK_ERROR,details:r,fatal:i,url:a.url,loader:a,context:t,networkDetails:n})}}]),t}();r.default=_},{2:2,33:33,34:34,35:35,47:47,54:54}],44:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=Math.pow(2,32)-1,o=function(){function e(){i(this,e)}return n(e,null,[{key:"init",value:function(){e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};var t;for(t in e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var o=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,o,u,o,s),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}},{key:"box",value:function(e){for(var t,r=Array.prototype.slice.call(arguments,1),i=8,n=r.length,a=n;n--;)i+=r[n].byteLength;for((t=new Uint8Array(i))[0]=i>>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),n=0,i=8;n<a;n++)t.set(r[n],i),i+=r[n].byteLength;return t}},{key:"hdlr",value:function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var i=Math.floor(r/(a+1)),n=Math.floor(r%(a+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(a+1)),n=Math.floor(r%(a+1)),o=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,o)}},{key:"sdtp",value:function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,a[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,a)}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}},{key:"avc1",value:function(t){var r,i,n,a=[],o=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,o.push(n>>>8&255),o.push(255&n),o=o.concat(Array.prototype.slice.call(i));var s=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(o))),u=t.width,l=t.height,f=t.pixelRatio[0],c=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,255&u,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,255&f,c>>24,c>>16&255,c>>8&255,255&c])))}},{key:"esds",value:function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}},{key:"mp4a",value:function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))}},{key:"mp3",value:function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))}},{key:"stsd",value:function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}},{key:"tkhd",value:function(t){var r=t.id,i=t.duration*t.timescale,n=t.width,o=t.height,s=Math.floor(i/(a+1)),u=Math.floor(i%(a+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,u>>24,u>>16&255,u>>8&255,255&u,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,o>>8&255,255&o,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),n=t.id,o=Math.floor(r/(a+1)),s=Math.floor(r%(a+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,n,a,o,s,u,l=t.samples||[],f=l.length,c=12+16*f,d=new Uint8Array(c);for(r+=8+c,d.set([0,0,15,1,f>>>24&255,f>>>16&255,f>>>8&255,255&f,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<f;i++)a=(n=l[i]).duration,o=n.size,s=n.flags,u=n.cts,d.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,o>>>24&255,o>>>16&255,o>>>8&255,255&o,s.isLeading<<2|s.dependsOn,s.isDependedOn<<6|s.hasRedundancy<<4|s.paddingValue<<1|s.isNonSync,61440&s.degradPrio,15&s.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*i);return e.box(e.types.trun,d)}},{key:"initSegment",value:function(t){e.types||e.init();var r,i=e.moov(t);return(r=new Uint8Array(e.FTYP.byteLength+i.byteLength)).set(e.FTYP),r.set(i,e.FTYP.byteLength),r}}]),e}();r.default=o},{}],45:[function(e,t,r){function i(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=i(e(36)),s=i(e(35)),u=e(54),l=i(e(44)),f=e(33),c=function(){function e(t,r,i,a){n(this,e),this.observer=t,this.config=r,this.typeSupported=i;var o=navigator.userAgent;this.isSafari=a&&a.indexOf("Apple")>-1&&o&&!o.match("CriOS"),this.ISGenerated=!1}return a(e,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(e){this._initPTS=this._initDTS=e}},{key:"resetInitSegment",value:function(){this.ISGenerated=!1}},{key:"remux",value:function(e,t,r,i,n,a,o){if(this.ISGenerated){if(o){var l=this._initPTS,f=this._PTSNormalize,c=e.inputTimeScale||t.inputTimeScale,d=1/0,h=1/0,v=e.samples;if(v.length&&(d=h=f(v[0].pts-c*n,l)),(v=t.samples).length){var p=v[0];d=Math.min(d,f(p.pts-c*n,l)),h=Math.min(h,f(p.dts-c*n,l))}if(d!==1/0){var g=l-d;Math.abs(g)>10*c&&(u.logger.warn("timestamp inconsistency, "+(g/c).toFixed(3)+"s delta against expected value: missing discontinuity ? reset initPTS/initDTS"),this._initPTS=d,this._initDTS=h,this.observer.trigger(s.default.INIT_PTS_FOUND,{initPTS:d}))}}}else this.generateIS(e,t,n);if(this.ISGenerated)if(e.samples.length){e.timescale||(u.logger.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,n));var y=this.remuxAudio(e,n,a,o);if(t.samples.length){var m=void 0;y&&(m=y.endPTS-y.startPTS),t.timescale||(u.logger.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,n)),this.remuxVideo(t,n,a,m,o)}}else{var b=void 0;t.samples.length&&(b=this.remuxVideo(t,n,a,o)),b&&e.codec&&this.remuxEmptyAudio(e,n,a,b)}r.samples.length&&this.remuxID3(r,n),i.samples.length&&this.remuxText(i,n),this.observer.trigger(s.default.FRAG_PARSED)}},{key:"generateIS",value:function(e,t,r){var i,n,a=this.observer,o=e.samples,c=t.samples,d=this.typeSupported,h="audio/mp4",v={},p={tracks:v},g=void 0===this._initPTS;if(g&&(i=n=1/0),e.config&&o.length&&(e.timescale=e.samplerate,u.logger.log("audio sampling rate : "+e.samplerate),e.isAAC||(d.mpeg?(h="audio/mpeg",e.codec=""):d.mp3&&(e.codec="mp3")),v.audio={container:h,codec:e.codec,initSegment:!e.isAAC&&d.mpeg?new Uint8Array:l.default.initSegment([e]),metadata:{channelCount:e.channelCount}},g&&(i=n=o[0].pts-e.inputTimeScale*r)),t.sps&&t.pps&&c.length){var y=t.inputTimeScale;t.timescale=y,v.video={container:"video/mp4",codec:t.codec,initSegment:l.default.initSegment([t]),metadata:{width:t.width,height:t.height}},g&&(i=Math.min(i,c[0].pts-y*r),n=Math.min(n,c[0].dts-y*r),this.observer.trigger(s.default.INIT_PTS_FOUND,{initPTS:i}))}Object.keys(v).length?(a.trigger(s.default.FRAG_PARSING_INIT_SEGMENT,p),this.ISGenerated=!0,g&&(this._initPTS=i,this._initDTS=n)):a.trigger(s.default.ERROR,{type:f.ErrorTypes.MEDIA_ERROR,details:f.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})}},{key:"remuxVideo",value:function(e,t,r,i,n){var a,o,c,d,h,v,p,g=8,y=e.timescale,m=e.samples,b=[],_=m.length,E=this._PTSNormalize,k=this._initDTS,w=this.nextAvcDts,S=this.isSafari;S&&(r|=m.length&&w&&(n&&Math.abs(t-w/y)<.1||Math.abs(m[0].pts-w-k)<y/5)),r||(w=t*y),m.forEach(function(e){e.pts=E(e.pts-k,w),e.dts=E(e.dts-k,w)}),m.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||(i||e.id-t.id)});var T=m.reduce(function(e,t){return Math.max(Math.min(e,t.pts-t.dts),-18e3)},0);if(T<0){u.logger.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(T/90)+" ms to overcome this issue");for(var A=0;A<m.length;A++)m[A].dts+=T}var R=m[0];h=Math.max(R.dts,0),d=Math.max(R.pts,0);var L=Math.round((h-w)/90);r&&L&&(L>1?u.logger.log("AVC:"+L+" ms hole between fragments detected,filling it"):L<-1&&u.logger.log("AVC:"+-L+" ms overlapping between fragments detected"),h=w,m[0].dts=h,d=Math.max(d-L,w),m[0].pts=d,u.logger.log("Video/PTS/DTS adjusted: "+Math.round(d/90)+"/"+Math.round(h/90)+",delta:"+L+" ms")),R=m[m.length-1],p=Math.max(R.dts,0),v=Math.max(R.pts,0,p),S&&(a=Math.round((p-h)/(m.length-1)));for(var O=0,D=0,P=0;P<_;P++){for(var x=m[P],I=x.units,C=I.length,M=0,F=0;F<C;F++)M+=I[F].data.length;D+=M,O+=C,x.length=M,x.dts=S?h+P*a:Math.max(x.dts,h),x.pts=Math.max(x.pts,x.dts)}var N=D+4*O+8;try{o=new Uint8Array(N)}catch(e){return void this.observer.trigger(s.default.ERROR,{type:f.ErrorTypes.MUX_ERROR,details:f.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating video mdat "+N})}var U=new DataView(o.buffer);U.setUint32(0,N),o.set(l.default.types.mdat,4);for(var B=0;B<_;B++){for(var G=m[B],j=G.units,H=0,z=void 0,V=0,W=j.length;V<W;V++){var K=j[V],q=K.data,Y=K.data.byteLength;U.setUint32(g,Y),g+=4,o.set(q,g),g+=Y,H+=4+Y}if(S)z=Math.max(0,a*Math.round((G.pts-G.dts)/a));else{if(B<_-1)a=m[B+1].dts-G.dts;else{var $=this.config,X=G.dts-m[B>0?B-1:B].dts;if($.stretchShortVideoTrack){var Q=$.maxBufferHole,Z=$.maxSeekHole,J=Math.floor(Math.min(Q,Z)*y),ee=(i?d+i*y:this.nextAudioPts)-G.pts;ee>J?((a=ee-X)<0&&(a=X),u.logger.log("It is approximately "+ee/90+" ms to the next segment; using duration "+a/90+" ms for the last video frame.")):a=X}else a=X}z=Math.round(G.pts-G.dts)}b.push({size:H,duration:a,cts:z,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:G.key?2:1,isNonSync:G.key?0:1}})}this.nextAvcDts=p+a;var te=e.dropped;if(e.len=0,e.nbNalu=0,e.dropped=0,b.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var re=b[0].flags;re.dependsOn=2,re.isNonSync=0}e.samples=b,c=l.default.moof(e.sequenceNumber++,h,e),e.samples=[];var ie={data1:c,data2:o,startPTS:d/y,endPTS:(v+a)/y,startDTS:h/y,endDTS:this.nextAvcDts/y,type:"video",nb:b.length,dropped:te};return this.observer.trigger(s.default.FRAG_PARSING_DATA,ie),ie}},{key:"remuxAudio",value:function(e,t,r,i){var n,a,c,d,h,v,p,g=e.inputTimeScale,y=g/e.timescale,m=(e.isAAC?1024:1152)*y,b=this._PTSNormalize,_=this._initDTS,E=!e.isAAC&&this.typeSupported.mpeg,k=e.samples,w=[],S=this.nextAudioPts;if((r|=k.length&&S&&(i&&Math.abs(t-S/g)<.1||Math.abs(k[0].pts-S-_)<20*m))||(S=t*g),k.forEach(function(e){e.pts=e.dts=b(e.pts-_,S)}),k.sort(function(e,t){return e.pts-t.pts}),i&&e.isAAC)for(var T=0,A=S;T<k.length;){var R,L=k[T];R=L.pts-A;var O=Math.abs(1e3*R/g);if(R<=-m)u.logger.warn("Dropping 1 audio frame @ "+(A/g).toFixed(3)+"s due to "+O+" ms overlap."),k.splice(T,1),e.len-=L.unit.length;else if(R>=m&&O<1e4&&A){var D=Math.round(R/m);u.logger.warn("Injecting "+D+" audio frame @ "+(A/g).toFixed(3)+"s due to "+Math.round(1e3*R/g)+" ms gap.");for(var P=0;P<D;P++){var x=Math.max(A,0);(c=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(u.logger.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),c=L.unit.subarray()),k.splice(T,0,{unit:c,pts:x,dts:x}),e.len+=c.length,A+=m,T++}L.pts=L.dts=A,A+=m,T++}else Math.abs(R),L.pts=L.dts=A,A+=m,T++}for(var I=0,C=k.length;I<C;I++){var M=k[I],F=M.unit,N=M.pts;if(void 0!==p)a.duration=Math.round((N-p)/y);else{var U=Math.round(1e3*(N-S)/g),B=0;if(r&&e.isAAC&&U){if(U>0&&U<1e4)B=Math.round((N-S)/m),u.logger.log(U+" ms hole between AAC samples detected,filling it"),B>0&&((c=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(c=F.subarray()),e.len+=B*c.length);else if(U<-12){u.logger.log("drop overlapping AAC sample, expected/parsed/delta:"+(S/g).toFixed(3)+"s/"+(N/g).toFixed(3)+"s/"+-U+"ms"),e.len-=F.byteLength;continue}N=S}if(v=Math.max(0,N),!(e.len>0))return;var G=E?e.len:e.len+8;n=E?0:8;try{d=new Uint8Array(G)}catch(e){return void this.observer.trigger(s.default.ERROR,{type:f.ErrorTypes.MUX_ERROR,details:f.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:G,reason:"fail allocating audio mdat "+G})}E||(new DataView(d.buffer).setUint32(0,G),d.set(l.default.types.mdat,4));for(var j=0;j<B;j++)(c=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(u.logger.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),c=F.subarray()),d.set(c,n),n+=c.byteLength,a={size:c.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},w.push(a)}d.set(F,n);var H=F.byteLength;n+=H,a={size:H,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},w.push(a),p=N}var z=0,V=w.length;if(V>=2&&(z=w[V-2].duration,a.duration=z),V){this.nextAudioPts=S=p+y*z,e.len=0,e.samples=w,h=E?new Uint8Array:l.default.moof(e.sequenceNumber++,v/y,e),e.samples=[];var W=v/g,K=S/g,q={data1:h,data2:d,startPTS:W,endPTS:K,startDTS:W,endDTS:K,type:"audio",nb:V};return this.observer.trigger(s.default.FRAG_PARSING_DATA,q),q}return null}},{key:"remuxEmptyAudio",value:function(e,t,r,i){var n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),s=this.nextAudioPts,l=(void 0!==s?s:i.startDTS*n)+this._initDTS,f=i.endDTS*n+this._initDTS,c=1024*a,d=Math.ceil((f-l)/c),h=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(u.logger.warn("remux empty Audio"),h){for(var v=[],p=0;p<d;p++){var g=l+p*c;v.push({unit:h,pts:g,dts:g}),e.len+=h.length}e.samples=v,this.remuxAudio(e,t,r)}else u.logger.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!")}},{key:"remuxID3",value:function(e,t){var r,i=e.samples.length,n=e.inputTimeScale,a=this._initPTS,o=this._initDTS;if(i){for(var u=0;u<i;u++)(r=e.samples[u]).pts=(r.pts-a)/n,r.dts=(r.dts-o)/n;this.observer.trigger(s.default.FRAG_PARSING_METADATA,{samples:e.samples})}e.samples=[],t=t}},{key:"remuxText",value:function(e,t){e.samples.sort(function(e,t){return e.pts-t.pts});var r,i=e.samples.length,n=e.inputTimeScale,a=this._initPTS;if(i){for(var o=0;o<i;o++)(r=e.samples[o]).pts=(r.pts-a)/n;this.observer.trigger(s.default.FRAG_PARSING_USERDATA,{samples:e.samples})}e.samples=[],t=t}},{key:"_PTSNormalize",value:function(e,t){var r;if(void 0===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}}]),e}();r.default=c},{33:33,35:35,36:36,44:44,54:54}],46:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(e){return e&&e.__esModule?e:{default:e}}(e(35)),o=function(){function e(t){i(this,e),this.observer=t}return n(e,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(){}},{key:"remux",value:function(e,t,r,i,n,o,s,u){var l=this.observer,f="";e&&(f+="audio"),t&&(f+="video"),l.trigger(a.default.FRAG_PARSING_DATA,{data1:u,startPTS:n,startDTS:n,type:f,nb:1,dropped:0}),l.trigger(a.default.FRAG_PARSED)}}]),e}();r.default=o},{35:35}],47:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=/^(\d+)x(\d+)$/,o=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,s=function(){function e(t){i(this,e),"string"==typeof t&&(t=e.parseAttrList(t));for(var r in t)t.hasOwnProperty(r)&&(this[r]=t[r])}return n(e,[{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"decimalResolution",value:function(e){var t=a.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e){var t,r={};for(o.lastIndex=0;null!==(t=o.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r}}]),e}();r.default=s},{}],48:[function(e,t,r){var i={search:function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var o=t(a=e[n=(r+i)/2|0]);if(o>0)r=n+1;else{if(!(o<0))return a;i=n-1}}return null}};t.exports=i},{}],49:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},o=function(e){var t=e;return a.hasOwnProperty(e)&&(t=a[e]),String.fromCharCode(t)},s=15,u=100,l={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},f={17:2,18:4,21:6,22:8,23:10,19:13,20:15},c={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},d={25:2,26:4,29:6,30:8,31:10,27:13,28:15},h=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],v={verboseFilter:{DATA:3,DEBUG:3,INFO:2,WARNING:2,TEXT:1,ERROR:0},time:null,verboseLevel:0,setTime:function(e){this.time=e},log:function(e,t){var r=this.verboseFilter[e];this.verboseLevel>=r&&console.log(this.time+" ["+e+"] "+t)}},p=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},g=function(){function e(t,r,n,a,o){i(this,e),this.foreground=t||"white",this.underline=r||!1,this.italics=n||!1,this.background=a||"black",this.flash=o||!1}return n(e,[{key:"reset",value:function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}},{key:"setStyles",value:function(e){for(var t=["foreground","underline","italics","background","flash"],r=0;r<t.length;r++){var i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}}},{key:"isDefault",value:function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}},{key:"equals",value:function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}},{key:"copy",value:function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}]),e}(),y=function(){function e(t,r,n,a,o,s){i(this,e),this.uchar=t||" ",this.penState=new g(r,n,a,o,s)}return n(e,[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.copy(t)}},{key:"setPenState",value:function(e){this.penState.copy(e)}},{key:"equals",value:function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.copy(e.penState)}},{key:"isEmpty",value:function(){return" "===this.uchar&&this.penState.isDefault()}}]),e}(),m=function(){function e(){i(this,e),this.chars=[];for(var t=0;t<u;t++)this.chars.push(new y);this.pos=0,this.currPenState=new g}return n(e,[{key:"equals",value:function(e){for(var t=!0,r=0;r<u;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<u;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<u;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}},{key:"setCursor",value:function(e){this.pos!==e&&(this.pos=e),this.pos<0?(v.log("ERROR","Negative cursor position "+this.pos),this.pos=0):this.pos>u&&(v.log("ERROR","Too large cursor position "+this.pos),this.pos=u)}},{key:"moveCursor",value:function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){e>=144&&this.backSpace();var t=o(e);this.pos>=u?v.log("ERROR","Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<u;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<u;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}]),e}(),b=function(){function e(){i(this,e),this.rows=[];for(var t=0;t<s;t++)this.rows.push(new m);this.currRow=s-1,this.nrRollUpRows=null,this.reset()}return n(e,[{key:"reset",value:function(){for(var e=0;e<s;e++)this.rows[e].clear();this.currRow=s-1}},{key:"equals",value:function(e){for(var t=!0,r=0;r<s;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<s;t++)this.rows[t].copy(e.rows[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<s;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}},{key:"backSpace",value:function(){this.rows[this.currRow].backSpace()}},{key:"clearToEndOfRow",value:function(){this.rows[this.currRow].clearToEndOfRow()}},{key:"insertChar",value:function(e){this.rows[this.currRow].insertChar(e)}},{key:"setPen",value:function(e){this.rows[this.currRow].setPenStyles(e)}},{key:"moveCursor",value:function(e){this.rows[this.currRow].moveCursor(e)}},{key:"setCursor",value:function(e){v.log("INFO","setCursor: "+e),this.rows[this.currRow].setCursor(e)}},{key:"setPAC",value:function(e){v.log("INFO","pacData = "+JSON.stringify(e));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<s;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime;if(a&&a<v.time)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var u=this.rows[this.currRow];if(null!==e.indent){var l=e.indent,f=Math.max(l-1,0);u.setCursor(e.indent),e.color=u.chars[f].penState.foreground}var c={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(c)}},{key:"setBkgData",value:function(e){v.log("INFO","bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){if(null!==this.nrRollUpRows){v.log("TEXT",this.getDisplayText());var e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),v.log("INFO","Rolling up")}else v.log("DEBUG","roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<s;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}]),e}(),_=function(){function e(t,r){i(this,e),this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new b,this.nonDisplayedMemory=new b,this.lastOutputScreen=new b,this.currRollUpRow=this.displayedMemory.rows[s-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return n(e,[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[s-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,v.log("INFO","MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";v.log("INFO",r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(v.log("TEXT","DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}},{key:"ccRCL",value:function(){v.log("INFO","RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){v.log("INFO","BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){v.log("INFO","DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){v.log("INFO","RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){v.log("INFO","FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){v.log("INFO","RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){v.log("INFO","TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){v.log("INFO","RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){v.log("INFO","EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate()}},{key:"ccCR",value:function(){v.log("CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate()}},{key:"ccENM",value:function(){v.log("INFO","ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){if(v.log("INFO","EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,v.log("TEXT","DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate()}},{key:"ccTO",value:function(e){v.log("INFO","TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[r]}v.log("INFO","MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=v.time;null!==e&&this.outputFilter&&(this.outputFilter.updateData&&this.outputFilter.updateData(e,this.displayedMemory),null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}]),e}(),E=function(){function e(t,r,n){i(this,e),this.field=t||1,this.outputs=[r,n],this.channels=[new _(1,r),new _(2,n)],this.currChNr=-1,this.lastCmdA=null,this.lastCmdB=null,this.bufferedData=[],this.startTime=null,this.lastTime=null,this.dataCounters={padding:0,char:0,cmd:0,other:0}}return n(e,[{key:"getHandler",value:function(e){return this.channels[e].getHandler()}},{key:"setHandler",value:function(e,t){this.channels[e].setHandler(t)}},{key:"addData",value:function(e,t){var r,i,n,a=!1;this.lastTime=e,v.setTime(e);for(var o=0;o<t.length;o+=2)i=127&t[o],n=127&t[o+1],0!==i||0!==n?(v.log("DATA","["+p([t[o],t[o+1]])+"] -> ("+p([i,n])+")"),(r=this.parseCmd(i,n))||(r=this.parseMidrow(i,n)),r||(r=this.parsePAC(i,n)),r||(r=this.parseBackgroundAttributes(i,n)),r||(a=this.parseChars(i,n))&&(this.currChNr&&this.currChNr>=0?this.channels[this.currChNr-1].insertChars(a):v.log("WARNING","No channel found yet. TEXT-MODE?")),r?this.dataCounters.cmd+=2:a?this.dataCounters.char+=2:(this.dataCounters.other+=2,v.log("WARNING","Couldn't parse cleaned data "+p([i,n])+" orig: "+p([t[o],t[o+1]])))):this.dataCounters.padding+=2}},{key:"parseCmd",value:function(e,t){var r=null,i=(20===e||28===e)&&32<=t&&t<=47,n=(23===e||31===e)&&33<=t&&t<=35;if(!i&&!n)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,v.log("DEBUG","Repeated command ("+p([e,t])+") is dropped"),!0;r=20===e||23===e?1:2;var a=this.channels[r-1];return 20===e||28===e?32===t?a.ccRCL():33===t?a.ccBS():34===t?a.ccAOF():35===t?a.ccAON():36===t?a.ccDER():37===t?a.ccRU(2):38===t?a.ccRU(3):39===t?a.ccRU(4):40===t?a.ccFON():41===t?a.ccRDC():42===t?a.ccTR():43===t?a.ccRTD():44===t?a.ccEDM():45===t?a.ccCR():46===t?a.ccENM():47===t&&a.ccEOC():a.ccTO(t-32),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0}},{key:"parseMidrow",value:function(e,t){var r=null;return(17===e||25===e)&&32<=t&&t<=47&&((r=17===e?1:2)!==this.currChNr?(v.log("ERROR","Mismatch channel in midrow parsing"),!1):(this.channels[r-1].ccMIDROW(t),v.log("DEBUG","MIDROW ("+p([e,t])+")"),!0))}},{key:"parsePAC",value:function(e,t){var r=null,i=null,n=(17<=e&&e<=23||25<=e&&e<=31)&&64<=t&&t<=127,a=(16===e||24===e)&&64<=t&&t<=95;if(!n&&!a)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,!0;r=e<=23?1:2,i=64<=t&&t<=95?1===r?l[e]:c[e]:1===r?f[e]:d[e];var o=this.interpretPAC(i,t);return this.channels[r-1].setPAC(o),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0}},{key:"interpretPAC",value:function(e,t){var r=t,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r=null,i=null,n=null;if(e>=25?(r=2,n=e-8):(r=1,n=e),17<=n&&n<=19){var a=t;a=17===n?t+80:18===n?t+112:t+144,v.log("INFO","Special char '"+o(a)+"' in channel "+r),i=[a]}else 32<=e&&e<=127&&(i=0===t?[e]:[e,t]);if(i){var s=p(i);v.log("DEBUG","Char codes = "+s.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i}},{key:"parseBackgroundAttributes",value:function(e,t){var r,i,n,a=(16===e||24===e)&&32<=t&&t<=47,o=(23===e||31===e)&&45<=t&&t<=47;return!(!a&&!o)&&(r={},16===e||24===e?(i=Math.floor((t-32)/2),r.background=h[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0)),n=e<24?1:2,this.channels[n-1].setBkgData(r),this.lastCmdA=null,this.lastCmdB=null,!0)}},{key:"reset",value:function(){for(var e=0;e<this.channels.length;e++)this.channels[e]&&this.channels[e].reset();this.lastCmdA=null,this.lastCmdB=null}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++)this.channels[t]&&this.channels[t].cueSplitAtTime(e)}}]),e}();r.default=E},{}],50:[function(e,t,r){var i=e(57),n={newCue:function(e,t,r,n){for(var a,o,s,u,l,f=window.VTTCue||window.TextTrackCue,c=0;c<n.rows.length;c++)if(a=n.rows[c],s=!0,u=0,l="",!a.isEmpty()){for(var d=0;d<a.chars.length;d++)a.chars[d].uchar.match(/\s/)&&s?u++:(l+=a.chars[d].uchar,s=!1);a.cueStartTime=t,t===r&&(r+=1e-4),o=new f(t,r,(0,i.fixLineBreaks)(l.trim())),u>=16?u--:u++,navigator.userAgent.match(/Firefox\//)?o.line=c+1:o.line=c>7?c-2:c+1,o.align="left",o.position=Math.max(0,Math.min(100,u/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),e.addCue(o)}}};t.exports=n},{57:57}],51:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.findFragWithCC=function(e,t){return i.default.search(e,function(e){return e.cc<t?1:e.cc>t?-1:0})};var i=function(e){return e&&e.__esModule?e:{default:e}}(e(48))},{48:48}],52:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(e){return e&&e.__esModule?e:{default:e}}(e(53)),o=function(){function e(t,r,n,o){i(this,e),this.hls=t,this.defaultEstimate_=o,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new a.default(r),this.fast_=new a.default(n)}return n(e,[{key:"sample",value:function(e,t){var r=8e3*t/(e=Math.max(e,this.minDelayMs_)),i=e/1e3;this.fast_.sample(i,r),this.slow_.sample(i,r)}},{key:"canEstimate",value:function(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"destroy",value:function(){}}]),e}();r.default=o},{53:53}],53:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=function(){function e(t){i(this,e),this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=0,this.totalWeight_=0}return n(e,[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}return this.estimate_}}]),e}();r.default=a},{}],54:[function(e,t,r){function i(){}function n(e,t){return t="["+e+"] > "+t}function a(e){var t=self.console[e];return t?function(){for(var r=arguments.length,i=Array(r),a=0;a<r;a++)i[a]=arguments[a];i[0]&&(i[0]=n(e,i[0])),t.apply(self.console,i)}:i}function o(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];r.forEach(function(t){l[t]=e[t]?e[t].bind(e):a(t)})}Object.defineProperty(r,"__esModule",{value:!0});var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u={trace:i,debug:i,log:i,warn:i,info:i,error:i},l=u;r.enableLogs=function(e){if(!0===e||"object"===(void 0===e?"undefined":s(e))){o(e,"debug","log","info","warn","error");try{l.log()}catch(e){l=u}}else l=u},r.logger=l},{}],55:[function(e,t,r){var i={toString:function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+","+e.end(i).toFixed(3)+"]";return t}};t.exports=i},{}],56:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(){function e(e){return"string"==typeof e&&(!!a[e.toLowerCase()]&&e.toLowerCase())}function t(e){return"string"==typeof e&&(!!o[e.toLowerCase()]&&e.toLowerCase())}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)e[i]=r[i]}return e}function i(i,a,o){var s=this,u=function(){if("undefined"!=typeof navigator)return/MSIE\s8\.0/.test(navigator.userAgent)}(),l={};u?s=document.createElement("custom"):l.enumerable=!0,s.hasBeenReset=!1;var f="",c=!1,d=i,h=a,v=o,p=null,g="",y=!0,m="auto",b="start",_=50,E="middle",k=50,w="middle";if(Object.defineProperty(s,"id",r({},l,{get:function(){return f},set:function(e){f=""+e}})),Object.defineProperty(s,"pauseOnExit",r({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(s,"startTime",r({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"endTime",r({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"text",r({},l,{get:function(){return v},set:function(e){v=""+e,this.hasBeenReset=!0}})),Object.defineProperty(s,"region",r({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"vertical",r({},l,{get:function(){return g},set:function(t){var r=e(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"snapToLines",r({},l,{get:function(){return y},set:function(e){y=!!e,this.hasBeenReset=!0}})),Object.defineProperty(s,"line",r({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&e!==n)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"lineAlign",r({},l,{get:function(){return b},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");b=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"position",r({},l,{get:function(){return _},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");_=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"positionAlign",r({},l,{get:function(){return E},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");E=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"size",r({},l,{get:function(){return k},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",r({},l,{get:function(){return w},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");w=r,this.hasBeenReset=!0}})),s.displayState=void 0,u)return s}if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var n="auto",a={"":!0,lr:!0,rl:!0},o={start:!0,middle:!0,end:!0,left:!0,right:!0};return i.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},i}()},{}],57:[function(e,t,r){function i(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new f,this.regionList=[]}function n(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+(0|i)/1e3}var r=e.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}function a(){this.values=Object.create(null)}function o(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var o=n[a].split(r);2===o.length&&t(o[0],o[1])}}function s(e,t,r){function i(){var t=n(e);if(null===t)throw new Error("Malformed timestamp: "+u);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function s(){e=e.replace(/^\s+/,"")}var u=e;if(s(),t.startTime=i(),s(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+u);e=e.substr(3),s(),t.endTime=i(),s(),function(e,t){var i=new a;o(e,function(e,t){switch(e){case"region":for(var n=r.length-1;n>=0;n--)if(r[n].id===t){i.set(e,r[n].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":var a=t.split(","),o=a[0];i.integer(e,o),i.percent(e,o)&&i.set("snapToLines",!1),i.alt(e,o,["auto"]),2===a.length&&i.alt("lineAlign",a[1],["start",d,"end"]);break;case"position":a=t.split(","),i.percent(e,a[0]),2===a.length&&i.alt("positionAlign",a[1],["start",d,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",d,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===c.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",d);var s=i.get("position","auto");"auto"===s&&50===c.position&&(s="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=s}(e,t)}function u(e){return e.replace(/<br(?: \/)?>/gi,"\n")}Object.defineProperty(r,"__esModule",{value:!0}),r.fixLineBreaks=void 0;var l=function(e){return e&&e.__esModule?e:{default:e}}(e(56)),f=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};a.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}},integer:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},percent:function(e,t){return!!(t.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(t=parseFloat(t))>=0&&t<=100)&&(this.set(e,t),!0)}};var c=new l.default(0,0,0),d="middle"===c.align?"middle":"center";i.prototype={parse:function(e){function t(){var e=r.buffer,t=0;for(e=u(e);t<e.length&&"\r"!==e[t]&&"\n"!==e[t];)++t;var i=e.substr(0,t);return"\r"===e[t]&&++t,"\n"===e[t]&&++t,r.buffer=e.substr(t),i}var r=this;e&&(r.buffer+=r.decoder.decode(e,{stream:!0}));try{var i;if("INITIAL"===r.state){if(!/\r\n|\n/.test(r.buffer))return this;var n=(i=t()).match(/^WEBVTT([ \t].*)?$/);if(!n||!n[0])throw new Error("Malformed WebVTT signature.");r.state="HEADER"}for(var a=!1;r.buffer;){if(!/\r\n|\n/.test(r.buffer))return this;switch(a?a=!1:i=t(),r.state){case"HEADER":/:/.test(i)?function(e){o(e,function(e,t){switch(e){case"Region":console.log("parse region",t)}},/:/)}(i):i||(r.state="ID");continue;case"NOTE":i||(r.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){r.state="NOTE";break}if(!i)continue;if(r.cue=new l.default(0,0,""),r.state="CUE",-1===i.indexOf("--\x3e")){r.cue.id=i;continue}case"CUE":try{s(i,r.cue,r.regionList)}catch(e){r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":var f=-1!==i.indexOf("--\x3e");if(!i||f&&(a=!0)){r.oncue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}r.cue.text&&(r.cue.text+="\n"),r.cue.text+=i;continue;case"BADCUE":i||(r.state="ID");continue}}}catch(e){"CUETEXT"===r.state&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state="INITIAL"===r.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){var e=this;try{if(e.buffer+=e.decoder.decode(),(e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state)throw new Error("Malformed WebVTT signature.")}catch(e){throw e}return e.onflush&&e.onflush(),this}},r.fixLineBreaks=u,r.default=i},{56:56}],58:[function(e,t,r){var i=function(e){return e&&e.__esModule?e:{default:e}}(e(57)),n=function(e,t,r){return e.substr(r||0,t.length)===t},a=function(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),i=parseInt(e.substr(-9,2)),n=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;return isNaN(t)||isNaN(r)||isNaN(i)||isNaN(n)?-1:(t+=1e3*r,t+=6e4*i,t+=36e5*n)},o=function(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()},s=function(e,t,r){var i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;n&&n.new;)e.ccOffset+=i.start-n.start,i.new=!1,n=e[(i=n).prevCC];e.presentationOffset=r},u={parse:function(e,t,r,u,l,f){var c=/\r\n|\n\r|\n|\r/g,d=String.fromCharCode.apply(null,new Uint8Array(e)).trim().replace(c,"\n").split("\n"),h="00:00.000",v=0,p=0,g=0,y=[],m=void 0,b=!0,_=new i.default;_.oncue=function(e){var t=r[u],i=r.ccOffset;t&&t.new&&(void 0!==p?i=r.ccOffset=t.start:s(r,u,g)),g&&(i=g+r.ccOffset-r.presentationOffset),e.startTime+=i-p,e.endTime+=i-p,e.id=o(e.startTime)+o(e.endTime)+o(e.text),e.text=decodeURIComponent(escape(e.text)),e.endTime>0&&y.push(e)},_.onparsingerror=function(e){m=e},_.onflush=function(){m&&f?f(m):l(y)},d.forEach(function(e){if(b){if(n(e,"X-TIMESTAMP-MAP=")){b=!1,e.substr(16).split(",").forEach(function(e){n(e,"LOCAL:")?h=e.substr(6):n(e,"MPEGTS:")&&(v=parseInt(e.substr(7)))});try{v-=t=t<0?t+8589934592:t,p=a(h)/1e3,g=v/9e4,-1===p&&(m=new Error("Malformed X-TIMESTAMP-MAP: "+e))}catch(t){m=new Error("Malformed X-TIMESTAMP-MAP: "+e)}return}""===e&&(b=!1)}_.parse(e+"\n")}),_.flush()}};t.exports=u},{57:57}],59:[function(e,t,r){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),a=e(54),o=function(){function e(t){i(this,e),t&&t.xhrSetup&&(this.xhrSetup=t.xhrSetup)}return n(e,[{key:"destroy",value:function(){this.abort(),this.loader=null}},{key:"abort",value:function(){var e=this.loader;e&&4!==e.readyState&&(this.stats.aborted=!0,e.abort()),window.clearTimeout(this.requestTimeout),this.requestTimeout=null,window.clearTimeout(this.retryTimeout),this.retryTimeout=null}},{key:"load",value:function(e,t,r){this.context=e,this.config=t,this.callbacks=r,this.stats={trequest:performance.now(),retry:0},this.retryDelay=t.retryDelay,this.loadInternal()}},{key:"loadInternal",value:function(){var e,t=this.context;e="undefined"!=typeof XDomainRequest?this.loader=new XDomainRequest:this.loader=new XMLHttpRequest;var r=this.stats;r.tfirst=0,r.loaded=0;var i=this.xhrSetup;try{if(i)try{i(e,t.url)}catch(r){e.open("GET",t.url,!0),i(e,t.url)}e.readyState||e.open("GET",t.url,!0)}catch(r){return void this.callbacks.onError({code:e.status,text:r.message},t,e)}t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),this.config.timeout),e.send()}},{key:"readystatechange",value:function(e){var t=e.currentTarget,r=t.readyState,i=this.stats,n=this.context,o=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(performance.now(),i.trequest)),4===r){var s=t.status;if(s>=200&&s<300){i.tload=Math.max(i.tfirst,performance.now());var u=void 0,l=void 0;l="arraybuffer"===n.responseType?(u=t.response).byteLength:(u=t.responseText).length,i.loaded=i.total=l;var f={url:t.responseURL,data:u};this.callbacks.onSuccess(f,i,n,t)}else i.retry>=o.maxRetry||s>=400&&s<499?(a.logger.error(s+" while loading "+n.url),this.callbacks.onError({code:s,text:t.statusText},n,t)):(a.logger.warn(s+" while loading "+n.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,o.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),o.timeout)}},{key:"loadtimeout",value:function(){a.logger.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)}},{key:"loadprogress",value:function(e){var t=e.currentTarget,r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total);var i=this.callbacks.onProgress;i&&i(r,this.context,null,t)}}]),e}();r.default=o},{54:54}]},{},[40])(40)})})),uo={type:"vod",autoPlay:!1,box:"hls",lockInternalProperty:!1,debug:!0,enableWorker:!0},lo=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.tag="HLS-player",i.video=e,i.box="hls",i.config=uo,E(i.config,r),i.hls=new so,i.bindEvents(i.hls),i.attachMedia(),i}return ka(t,la),mt(t,[{key:"internalPropertyHandle",value:function(){if(Aa){var e=this,t=Aa(HTMLMediaElement.prototype,"currentTime");Object.defineProperty(this.video,"currentTime",{get:function(){return t.get.call(e.video)},set:function(r){if(e.currentTimeLock)return t.set.call(e.video,r);throw new Error("can not set currentTime by youself")}})}}},{key:"bindEvents",value:function(e){var t=this;e&&(e.on(so.Events.ERROR,function(e,t){}),e.on(so.Events.LEVEL,function(e,t){})),this.video&&this.config.lockInternalProperty&&this.video.addEventListener("canplay",function(){t.internalPropertyHandle()})}},{key:"load",value:function(){this.hls.loadSource(this.config.src)}},{key:"attachMedia",value:function(){this.hls.attachMedia(this.video)}},{key:"play",value:function(){return this.video.play()}},{key:"destroy",value:function(){return this.hls.destroy()}},{key:"seek",value:function(e){this.currentTimeLock=!0,this._seek(e),this.currentTimeLock=!1}},{key:"_seek",value:function(e){this.video.currentTime=e}},{key:"pause",value:function(){return this.video.pause()}}]),t}(),fo=function(e){function t(e,r){Ye(this,t);var i=ya(this,(t.__proto__||ga(t)).call(this));return i.tag="kernel",i.config=r,i.video=e,i.videokernel=i.selectKernel(),i.bindEvents(i.videokernel),i}return ka(t,la),mt(t,[{key:"bindEvents",value:function(e){var t=this;e&&e.on("mediaInfo",function(e){t.emit("mediaInfo",e)})}},{key:"selectKernel",value:function(){var e=this.config,t=e.box?e.box:-1!==e.src.indexOf(".flv")?"flv":-1!==e.src.indexOf(".m3u8")?"hls":"mp4";return"mp4"===t?new Ia(this.video,e):"flv"===t?new oo(this.video,e):"hls"===t?(console.log(e),new lo(this.video,e)):(Ui.error(this.tag,"not mactch any player, please check your config"),null)}},{key:"attachMedia",value:function(){this.videokernel?this.videokernel.attachMedia():Ui.error(this.tag,"video player is not already, must init player")}},{key:"load",value:function(e){this.config.src=e||this.config.src,this.videokernel&&this.config.src?this.videokernel.load(e):Ui.error(this.tag,"video player is not already, must init player")}},{key:"destroy",value:function(){this.videokernel?this.videokernel.destroy():Ui.error(this.tag,"player is not exit")}},{key:"play",value:function(){this.videokernel?this.videokernel.play():Ui.error(this.tag,"video player is not already, must init player")}},{key:"pause",value:function(){this.videokernel&&this.config.src?this.videokernel.pause():Ui.error(this.tag,"video player is not already, must init player")}},{key:"seek",value:function(e){if(o(e))return this.videokernel.seek(e);Ui.error(this.tag,"seek params must be a number")}},{key:"currentTime",get:function(){return this.videokernel?this.video.currentTime:0}},{key:"duration",get:function(){return this.video.duration}},{key:"volume",get:function(){return this.video.volume},set:function(e){this.video.volume=e}},{key:"muted",get:function(){return this.video.muted},set:function(e){this.video.muted=e}},{key:"buffered",get:function(){return this.video.buffered}}]),t}(),co=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","interruptbegin","interruptend","loadeddata","loadedmetadata","loadstart","mozaudioavailable","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting"],ho=["buffered","currentSrc","duration","ended","networkState","paused","readyState","seekable","sinkId","controlsList"],vo=["beforeinput","blur","click","compositionend","compositionstart","compositionupdate","dblclick","focus","focusin","focusout","input","keydown","keypress","keyup","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","resize","scroll","select","wheel","fullscreenchange","webkitfullscreenchange","mozfullscreenchange","msfullscreenchange","contextmenu"],po=["play","pause","load","seek"],go=["focus","fullScreen","requestFullScreen","exitFullScreen"],yo=["canPlayType","captureStream","setSinkId"],mo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bo=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},_o=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),Eo=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},ko=function e(t,r,i){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var a=Object.getPrototypeOf(t);return null===a?void 0:e(a,r,i)}if("value"in n)return n.value;var o=n.get;if(void 0!==o)return o.call(i)},wo=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},So=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},To=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},Ao=/^(before|after|_)/,Ro=function(){function e(t){bo(this,e),this.events={},this.onceMap={},this.__dispatcher=t}return _o(e,[{key:"on",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,a=i.key;this._addEvent([a,n,e],r)}},{key:"off",value:function(e,t,r){var i=this._getEventStage(t),a=i.stage,o=[i.key,a,e];if(!this._removeEvent(o,r)){var s=this._getHandlerFromOnceMap(o,r);n(s)&&this._removeEvent(o,s)&&this._removeFromOnceMap(o,r,s)}}},{key:"once",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,a=this,o=[i.key,n,e],s=function e(){S(r,this).apply(void 0,arguments),a._removeEvent(o,e),a._removeFromOnceMap(o,r,e)};this._addEvent(o,s),this._addToOnceMap(o,r,s)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if(!e.match(Ao)){var a=this.events[e];if(u(a))return this._eventProcessor.apply(this,[e,{sync:!1}].concat(To(i)));var o=this._getEventQueue(a.before,this.__dispatcher.order);return R.apply(void 0,[o].concat(To(i))).then(function(){return t._eventProcessor.apply(t,[e,{sync:!1}].concat(To(i)))}).catch(function(e){return m(e)&&t.__dispatcher.throwError(e),Promise.reject(e)})}Ui.warn("bus","Secondary Event could not be emit")}},{key:"emitSync",value:function(e){if(e.match(Ao))return Ui.warn("bus","Secondary Event could not be emit"),!1;for(var t=this.events[e],r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if(u(t))return this._eventProcessor.apply(this,[e,{sync:!0}].concat(To(i)));var a=this._getEventQueue(t.before,this.__dispatcher.order);return L.apply(void 0,[a].concat(To(i)))&&this._eventProcessor.apply(this,[e,{sync:!0}].concat(To(i)))}},{key:"trigger",value:function(e){for(var t=this,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if(!e.match(Ao)){var a=this.events[e];if(u(a))return Promise.resolve(!0);var o=this._getEventQueue(a.main,this.__dispatcher.order);return R.apply(void 0,[o].concat(To(i))).then(function(){var e=t._getEventQueue(a.after,t.__dispatcher.order);return R.apply(void 0,[e].concat(To(i)))}).then(function(){return t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(To(i)))}).catch(function(r){return m(r)&&t.__dispatcher.throwError(r),t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(To(i)))})}Ui.warn("bus","Secondary Event could not be emit")}},{key:"triggerSync",value:function(e){if(e.match(Ao))return Ui.warn("bus","Secondary Event could not be emit"),!1;var t=this.events[e];if(u(t))return!0;for(var r=this._getEventQueue(t.main,this.__dispatcher.order),i=this._getEventQueue(t.after,this.__dispatcher.order),n=arguments.length,a=Array(n>1?n-1:0),o=1;o<n;o++)a[o-1]=arguments[o];var s=L.apply(void 0,[r].concat(To(a)))&&L.apply(void 0,[i].concat(To(a)));return this._runSideEffectEvent.apply(this,[e,this.__dispatcher.order].concat(To(a))),s}},{key:"destroy",value:function(){delete this.events,delete this.__dispatcher}},{key:"_addEvent",value:function(e,t){var r=(e=_(e)).pop(),i=e.reduce(function(e,t){return e[t]=e[t]||{},e[t]},this.events);i[r]=i[r]||[],i[r].push(t)}},{key:"_removeEvent",value:function(e,t){for(var r=(e=_(e)).pop(),i=this.events,n=0,a=e.length;n<a;n++){var o=i[e[n]];if(u(o))return;i=o}var s=i[r]||[],l=s.indexOf(t),f=l>-1;return f&&s.splice(l,1),s.length<1&&delete i[r],f}},{key:"_addToOnceMap",value:function(e,t,r){var i=e.join("-"),n=this.onceMap[i]=this.onceMap[i]||new Map;n.has(t)||n.set(t,[]),n.get(t).push(r)}},{key:"_removeFromOnceMap",value:function(e,t,r){var i=e.join("-"),n=this.onceMap[i],a=n.get(t),o=a.indexOf(r);a.splice(o,1),u(a)&&n.delete(t)}},{key:"_getHandlerFromOnceMap",value:function(e,t){var i=e.join("-"),n=this.onceMap[i];if(!r(n)&&n.has(t))return n.get(t)[0]}},{key:"_getEventStage",value:function(e){var t=e.match(Ao),r=t&&t[0]||"main";return t&&(e=k(e.replace(Ao,""))),{stage:r,key:e}}},{key:"_getEventQueue",value:function(e,t){var r=this;return t=i(t)?t.concat(["_vm"]):["_vm"],u(e)?[]:t.reduce(function(t,n){return u(e[n])||!i(e[n])||!r.__dispatcher.plugins[n]&&"_vm"!==n?t:t.concat(e[n].map(function(e){return S(e,r.__dispatcher.plugins[n]||r.__dispatcher.vm)}))},[])}},{key:"_eventProcessor",value:function(e,t){for(var r=t.sync,i=po.indexOf(e)>-1,n=go.indexOf(e)>-1,a=arguments.length,o=Array(a>2?a-2:0),s=2;s<a;s++)o[s-2]=arguments[s];if(i||n){var u;if((u=this.__dispatcher[i?"kernel":"dom"])[e].apply(u,To(o)),co.indexOf(e)>-1||vo.indexOf(e)>-1)return!0}return this[r?"triggerSync":"trigger"].apply(this,[e].concat(To(o)))}},{key:"_runSideEffectEvent",value:function(e,t){for(var r=arguments.length,i=Array(r>2?r-2:0),n=2;n<r;n++)i[n-2]=arguments[n];var a=this.events[e];if(!u(a))return this._getEventQueue(a._,t).forEach(function(e){return e.apply(void 0,To(i))}),!0}}]),e}(),Lo=$e.Reflect,Oo=Lo&&Lo.ownKeys||function(e){var t=Mr.f(et(e)),r=Dr.f;return r?t.concat(r(e)):t};ht(ht.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,r=Dt(e),i=Hr.f,n=Oo(r),a={},o=0;n.length>o;)zi(a,t=n[o++],i(r,t));return a}});var Do=Xe.Object.getOwnPropertyDescriptors,Po=e(t(function(e){e.exports={default:Do,__esModule:!0}})),xo=Xe.Object.getOwnPropertySymbols,Io=e(t(function(e){e.exports={default:xo,__esModule:!0}}));Ei("getOwnPropertyNames",function(){return Gr.f});var Co=Xe.Object,Mo=function(e){return Co.getOwnPropertyNames(e)},Fo=e(t(function(e){e.exports={default:Mo,__esModule:!0}})),No=er("iterator"),Uo=Xe.isIterable=function(e){var t=Object(e);return void 0!==t[No]||"@@iterator"in t||At.hasOwnProperty(qi(t))},Bo=t(function(e){e.exports={default:Uo,__esModule:!0}}),Go=Xe.getIterator=function(e){var t=$i(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return et(t.call(e))},jo=t(function(e){e.exports={default:Go,__esModule:!0}}),Ho=e(t(function(e,t){function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=r(Bo),n=r(jo);t.default=function(){function e(e,t){var r=[],i=!0,a=!1,o=void 0;try{for(var s,u=(0,n.default)(e);!(i=(s=u.next()).done)&&(r.push(s.value),!t||r.length!==t);i=!0);}catch(e){a=!0,o=e}finally{try{!i&&u.return&&u.return()}finally{if(a)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if((0,i.default)(Object(t)))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()})),zo=er("species"),Vo=function(e){var t;return Ir(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!Ir(t.prototype)||(t=void 0),Je(t)&&null===(t=t[zo])&&(t=void 0)),void 0===t?Array:t},Wo=function(e,t){return new(Vo(e))(t)},Ko=function(e,t){var r=1==e,i=2==e,n=3==e,a=4==e,o=6==e,s=5==e||o,u=t||Wo;return function(t,l,f){for(var c,d,h=or(t),v=Ot(h),p=Ze(l,f,3),g=xt(v.length),y=0,m=r?u(t,g):i?u(t,0):void 0;g>y;y++)if((s||y in v)&&(c=v[y],d=p(c,y,h),e))if(r)m[y]=d;else if(d)switch(e){case 3:return!0;case 5:return c;case 6:return y;case 2:m.push(c)}else if(a)return!1;return o?-1:n||a?a:m}},qo=Ar.getWeak,Yo=Ko(5),$o=Ko(6),Xo=0,Qo=function(e){return e._l||(e._l=new Zo)},Zo=function(){this.a=[]},Jo=function(e,t){return Yo(e.a,function(e){return e[0]===t})};Zo.prototype={get:function(e){var t=Jo(this,e);if(t)return t[1]},has:function(e){return!!Jo(this,e)},set:function(e,t){var r=Jo(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=$o(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}};var es={getConstructor:function(e,t,r,i){var n=e(function(e,a){ln(e,n,t,"_i"),e._i=Xo++,e._l=void 0,void 0!=a&&fn(a,r,e[i],e)});return Pn(n.prototype,{delete:function(e){if(!Je(e))return!1;var t=qo(e);return!0===t?Qo(this).delete(e):t&&Tt(t,this._i)&&delete t[this._i]},has:function(e){if(!Je(e))return!1;var t=qo(e);return!0===t?Qo(this).has(e):t&&Tt(t,this._i)}}),n},def:function(e,t,r){var i=qo(et(t),!0);return!0===i?Qo(e).set(t,r):i[e._i]=r,e},ufstore:Qo},ts=lt.f,rs=Ko(0),is=function(e,t,r,i,n,a){var o=$e[e],s=o,u=n?"set":"add",l=s&&s.prototype,f={};return rt&&"function"==typeof s&&(a||l.forEach&&!tt(function(){(new s).entries().next()}))?(s=t(function(t,r){ln(t,s,e,"_c"),t._c=new o,void 0!=r&&fn(r,n,t[u],t)}),rs("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in l&&(!a||"clear"!=e)&&ct(s.prototype,e,function(r,i){if(ln(this,s,e),!t&&a&&!Je(r))return"get"==e&&void 0;var n=this._c[e](0===r?0:r,i);return t?this:n})}),"size"in l&&ts(s.prototype,"size",{get:function(){return this._c.size}})):(s=i.getConstructor(t,e,n,u),Pn(s.prototype,r),Ar.NEED=!0),ir(s,e),f[e]=s,ht(ht.G+ht.W+ht.F,f),a||i.setStrong(s,e,n),s},ns=(t(function(e){var t,r=Ko(0),i=Ar.getWeak,n=Object.isExtensible,a=es.ufstore,o={},s=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},u={get:function(e){if(Je(e)){var t=i(e);return!0===t?a(this).get(e):t?t[this._i]:void 0}},set:function(e,t){return es.def(this,e,t)}},l=e.exports=is("WeakMap",s,u,es,!0,!0);7!=(new l).set((Object.freeze||Object)(o),7).get(o)&&(t=es.getConstructor(s),ta(t.prototype,u),Ar.NEED=!0,r(["delete","has","get","set"],function(e){var r=l.prototype,i=r[e];wt(r,e,function(r,a){if(Je(r)&&!n(r)){this._f||(this._f=new t);var o=this._f[e](r,a);return"set"==e?this:o}return i.call(this,r,a)})}))}),Xe.WeakMap),as=e(t(function(e){e.exports={default:ns,__esModule:!0}})),os=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(gt);t.default=function(e,t,i){return t in e?(0,r.default)(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}})),ss=Ar.onFreeze;Ei("preventExtensions",function(e){return function(t){return e&&Je(t)?e(ss(t)):t}});var us,ls,fs,cs,ds,hs,vs,ps,gs,ys,ms,bs,_s,Es,ks,ws,Ss,Ts,As,Rs,Ls,Os,Ds,Ps,xs,Is,Cs,Ms,Fs,Ns,Us,Bs,Gs,js,Hs,zs,Vs,Ws,Ks,qs,Ys,$s,Xs,Qs,Zs,Js,eu,tu,ru,iu,nu,au,ou,su,uu,lu=Xe.Object.preventExtensions,fu=e(t(function(e){e.exports={default:lu,__esModule:!0}})),cu=Aa,du=function(){var e=Fo,t=Io;return n(t)?function(r){return on(e(r).concat(t(r)))}:e}(),hu=n(Po)?Po:function(e){return du(e).reduce(function(t,r){return t[r]=cu(e,r),t},{})},vu=Aa,pu=yt,gu=yt,yu=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=t.requirement,o=t.customArgs,s=void 0!==o&&o;return function(){for(var t=arguments.length,o=Array(t>1?t-1:0),u=1;u<t;u++)o[u-1]=arguments[u];var l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},f=l.exclude,c=void 0===f?[]:f,h=l.include,v=void 0===h?[]:h,p=l.construct,g=void 0!==p&&p,y=l.self,m=void 0!==y&&y;if(!i(c))throw new TypeError("options.exclude must be an array");if(!i(v))throw new TypeError("options.include must be an array");return function(t){var i=n(t);if(!m&&!i)throw new TypeError("@"+e.name+"Class can only be used on class");if(m&&d(t))throw new TypeError("@"+e.name+"Class must be used on non-primitive type value in 'self' mode");var u=m?t:t.prototype;if(r(u))throw new Error("The prototype of the "+t.name+" is empty, please check it");var l=hu(u);du(u).concat(v).forEach(function(t){var r=l[t];"constructor"===t&&!g||m&&i&&["name","length","prototype"].indexOf(t)>-1||c.indexOf(t)>-1||n(a)&&!1===a(u,t,r,{self:m})||gu(u,t,(s?e.apply(void 0,sn(o)):e)(u,t,r))})}}}(ye,{requirement:function(e,t,r){return ae(r)&&n(r.value)}}),mu=void 0,bu=yt,_u=Aa,Eu=yt,ku=yt,wu=yt,Su=Aa,Tu=["push","pop","unshift","shift","splice","sort","reverse"],Au=fu,Ru=function(){function e(){bo(this,e),this.__unwatchHandlers=[]}return _o(e,[{key:"__wrapAsVideo",value:function(e){var t=this;ho.forEach(function(e){Object.defineProperty(t,e,{get:function(){return this.__dispatcher.dom.videoElement[e]},set:void 0,configurable:!1,enumerable:!1})}),yo.forEach(function(e){Object.defineProperty(t,e,{get:function(){var t=this.__dispatcher.dom.videoElement;return S(t[e],t)},set:void 0,configurable:!1,enumerable:!1})}),Ee(this,e._realDomAttr.concat(e._kernelProperty).reduce(function(t,r){return t[r]=[ce({get:function(){return e[r]},set:function(t){return e[r]=t,t}}),_e],t},{}),{self:!0}),po.forEach(function(e){Object.defineProperty(t,e,{value:function(){for(var t=this,r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return new Promise(function(r,n){var a;t.__dispatcher.bus.once(t.__id,"_"+e,r),(a=t.__dispatcher.bus)[/^(seek)$/.test(e)?"emitSync":"emit"].apply(a,[e].concat(To(i)))})},configurable:!0,enumerable:!1,writable:!0})}),go.forEach(function(e){Object.defineProperty(t,e,{value:function(){var t;return(t=this.__dispatcher.dom)[e].apply(t,arguments)},configurable:!0,enumerable:!1,writable:!0})})}},{key:"$watch",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=n.deep,o=n.diff,s=void 0===o||o,u=n.other,f=n.proxy,c=void 0!==f&&f;if(!l(e)&&!i(e))throw new TypeError("$watch only accept string and Array<string> as key to find the target to spy on, but not "+e+", whose type is "+(void 0===e?"undefined":mo(e)));var d=!0,h=function e(){d=!1;var t=r.__unwatchHandlers.indexOf(e);t>-1&&r.__unwatchHandlers.splice(t,1)},v=l(e)?e.split("."):e,p=v.pop(),g=this.__dispatcher.videoConfig;return Ee(0===v.length&&!u&&g._realDomAttr.indexOf(p)>-1?g:T(u||this,v,{throwError:!0}),Eo({},p,Se(function(){d&&S(t,this).apply(void 0,arguments)},{deep:a,diff:s,proxy:c})),{self:!0}),this.__unwatchHandlers.push(h),h}},{key:"$set",value:function(e,t,r){if(!a(e)&&!i(e))throw new TypeError("$set only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":mo(e)));if(!n(e.__set))return Ui.warn("chimee",JSON.stringify(e)+" has not been deep watch. There is no need to use $set."),void(e[t]=r);e.__set(t,r)}},{key:"$del",value:function(e,t){if(!a(e)&&!i(e))throw new TypeError("$del only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":mo(e)));if(!n(e.__del))return Ui.warn("chimee",JSON.stringify(e)+" has not been deep watch. There is no need to use $del."),void delete e[t];e.__del(t)}},{key:"__destroy",value:function(){this.__unwatchHandlers.forEach(function(e){return e()})}},{key:"currentTime",get:function(){return this.__dispatcher.kernel.currentTime},set:function(e){this.__dispatcher.bus.emitSync("seek",e)}}]),e}(),Lu=(us=yu(),ls=de(Pe),fs=de(Pe),cs=de(De),ds=de(De),hs=de(De),us((ps=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.id,i=e.name,o=e.level,c=void 0===o?0:o,d=e.operable,h=void 0===d||d,v=e.beforeCreate,p=e.create,g=e.init,y=e.inited,m=e.destroy,b=e.events,_=void 0===b?{}:b,k=e.data,w=void 0===k?{}:k,T=e.computed,A=void 0===T?{}:T,R=e.methods,L=void 0===R?{}:R,O=e.el,D=e.penetrate,P=void 0!==D&&D,x=e.inner,I=void 0===x||x,C=e.autoFocus,M=e.className,F=arguments[1],N=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{name:i};bo(this,t);var U=So(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));if(U.destroyed=!1,U.VERSION="0.1.3",U.__operable=!0,U.__events={},U.__level=0,u(F))throw Ui.error("Dispatcher.plugin","lack of dispatcher. Do you forget to pass arguments to super in plugin?"),new TypeError("lack of dispatcher");if(!l(r))throw new TypeError("id of PluginConfig must be string");U.__id=r,U.__dispatcher=F,U.$videoConfig=U.__dispatcher.videoConfig,U.__wrapAsVideo(U.$videoConfig),U.beforeCreate=U.beforeCreate||v;try{n(U.beforeCreate)&&U.beforeCreate({events:_,data:w,computed:A,methods:L},N)}catch(e){U.$throwError(e)}if(!u(L)&&a(L)&&Object.keys(L).forEach(function(e){var t=L[e];if(!n(t))throw new TypeError("plugins methods must be Function");Object.defineProperty(U,e,{value:S(t,U),writable:!0,enumerable:!1,configurable:!0})}),!u(_)&&a(_)&&Object.keys(_).forEach(function(e){if(!n(_[e]))throw new TypeError("plugins events hook must bind with Function");U.$on(e,_[e])}),!u(w)&&a(w)&&E(U,w),!u(A)&&a(A)){var B=Object.keys(A).reduce(function(e,t){var r=A[t];return n(r)?(e[t]=ce({get:r}),e):a(r)&&(n(r.get)||n(r.set))?(e[t]=ce(r),e):(Ui.warn("Dispatcher.plugin","Wrong computed member '"+t+"' defination in Plugin "+i),e)},{});Ee(U,B,{self:!0})}U.create=U.create||p,U.init=U.init||g,U.inited=U.inited||y,U.destroy=U.destroy||m,U.$dom=U.__dispatcher.dom.insertPlugin(U.__id,O,{penetrate:P,inner:I,autoFocus:C,className:M}),U.$inner=I,U.$autoFocus=C,U.$penetrate=P,Ee(U,{$inner:me,$autoFocus:me,$penetrate:me},{self:!0}),U.$operable=f(N.operable)?N.operable:h,U.__level=s(N.level)?N.level:c,U.$config=N;try{n(U.create)&&U.create()}catch(e){U.$throwError(e)}return U}return wo(t,Ru),_o(t,[{key:"__init",value:function(e){try{n(this.init)&&this.init(e)}catch(e){this.$throwError(e)}}},{key:"__inited",value:function(){var e=this,t=void 0;try{t=n(this.inited)&&this.inited()}catch(e){this.$throwError(e)}return this.readySync=!c(t),this.ready=this.readySync?Promise.resolve():t.then(function(t){return e.readySync=!0,t}).catch(function(t){return m(t)?e.$throwError(t):Promise.reject(t)}),this.readySync||this.ready}},{key:"$css",value:function(e){for(var t,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.dom)[e+"Style"].apply(t,i)}},{key:"$attr",value:function(e){for(var t,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if("set"===e&&/video/.test(i[0])){if(!this.__dispatcher.videoConfigReady)return Ui.warn("plugin","Plugin "+this.__id+" is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger"),i[2];if(this.$videoConfig._realDomAttr.indexOf(i[1])>-1){var a=i[1],o=i[2];return this.$videoConfig[a]=o,o}}return(t=this.__dispatcher.dom)[e+"Attr"].apply(t,i)}},{key:"$fullScreen",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"container";return this.__dispatcher.dom.fullScreen(e,t)}},{key:"$bumpToTop",value:function(){var e=this.__dispatcher._getTopLevel(this.$inner);this.$level=e+1}},{key:"$on",value:function(e,t){this.__dispatcher.bus.on(this.__id,e,t),this.__addEvents(e,t)}},{key:"$off",value:function(e,t){this.__dispatcher.bus.off(this.__id,e,t),this.__removeEvents(e,t)}},{key:"$once",value:function(e,t){var r=this,i=function i(){S(t,this).apply(void 0,arguments),r.__removeEvents(e,i)};r.__addEvents(e,i),this.__dispatcher.bus.once(this.__id,e,i)}},{key:"$emit",value:function(e){var t;if(!l(e))throw new TypeError("$emit key parameter must be String");vo.indexOf(e.replace(/^\w_/,""))>-1&&Ui.warn("plugin","You are using $emit to emit "+e+" event. As $emit is wrapped in Promise. It make you can't use event.preventDefault and event.stopPropagation. So we advice you to use $emitSync");for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];(t=this.__dispatcher.bus).emit.apply(t,[e].concat(To(i)))}},{key:"$emitSync",value:function(e){var t;if(!l(e))throw new TypeError("$emitSync key parameter must be String");for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.bus).emitSync.apply(t,[e].concat(To(i)))}},{key:"$throwError",value:function(e){this.__dispatcher.throwError(e)}},{key:"$destroy",value:function(){var e=this;n(this.destroy)&&this.destroy(),ko(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"__destroy",this).call(this),Object.keys(this.__events).forEach(function(t){i(e.__events[t])&&e.__events[t].forEach(function(r){return e.$off(t,r)})}),delete this.__events,this.__dispatcher.dom.removePlugin(this.__id),delete this.__dispatcher,delete this.$dom,this.destroyed=!0}},{key:"__addEvents",value:function(e,t){this.__events[e]=this.__events[e]||[],this.__events[e].push(t)}},{key:"__removeEvents",value:function(e,t){if(!u(this.__events[e])){var r=this.__events[e].indexOf(t);r<0||(this.__events[e].splice(r,1),u(this.__events[e])&&delete this.__events[e])}}},{key:"$plugins",get:function(){return this.__dispatcher.plugins}},{key:"$pluginOrder",get:function(){return this.__dispatcher.order}},{key:"$operable",set:function(e){f(e)&&(this.$dom.style.pointerEvents=e?"auto":"none",this.__operable=e)},get:function(){return this.__operable}},{key:"$level",set:function(e){s(e)&&(this.__level=e,this.__dispatcher._sortZIndex())},get:function(){return this.__level}}]),t}(),xe(ps.prototype,"$css",[ls],Object.getOwnPropertyDescriptor(ps.prototype,"$css"),ps.prototype),xe(ps.prototype,"$attr",[fs],Object.getOwnPropertyDescriptor(ps.prototype,"$attr"),ps.prototype),xe(ps.prototype,"$on",[cs],Object.getOwnPropertyDescriptor(ps.prototype,"$on"),ps.prototype),xe(ps.prototype,"$off",[ds],Object.getOwnPropertyDescriptor(ps.prototype,"$off"),ps.prototype),xe(ps.prototype,"$once",[hs],Object.getOwnPropertyDescriptor(ps.prototype,"$once"),ps.prototype),xe(ps.prototype,"$plugins",[_e,Te],Object.getOwnPropertyDescriptor(ps.prototype,"$plugins"),ps.prototype),xe(ps.prototype,"$pluginOrder",[_e,Te],Object.getOwnPropertyDescriptor(ps.prototype,"$pluginOrder"),ps.prototype),vs=ps))||vs),Ou=(gs=function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).other;if(!n(e)&&!c(e)&&!l(e))throw new TypeError("@waitUntil only accept Function, Promise or String");return function(i,a,o){if(void 0===o)throw new Error("@waituntil must used on descriptor, are you using it on undefined property?");var s=o.value,u=o.configurable;if(!n(s))throw new TypeError("@waituntil can only be used on function, but not "+s);var l=!1,f=[],h=c(e)?function(){return e}:n(e)?e:function(){var i=e.split("."),n=i.slice(-1),a=d(t)?this:t;if(!l){var o=T(a,i.slice(0,-1));if(r(o))return o;var s=_u(o,n),u=function(e){if(!0===e)for(;f.length>0;)f[0](),f.shift();return e},c=ie(s)?ce({set:u})(o,n,s):ce({set:u})(o,n,{value:void 0,configurable:!0,enumerable:!0,writable:!0});Eu(o,n,c),l=!0}return T(a,i)};return{value:function(){for(var e=this,t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];var n=S(s,this),a=S(h,this).apply(void 0,r);return c(a)?Jn.resolve(a).then(function(){return S(s,e).apply(void 0,r)}):!0===a?S(s,this).apply(void 0,r):new Jn(function(e){f.push(function(){n.apply(void 0,r),e()})})},enumerable:!1,configurable:u,writable:!1}}}("__dispatcher.videoConfigReady"),ys=de(Me,Ce),ms=de(Me,Ce),bs=de(Me,Ce),_s=de(Me,Ce),Es=de(Ce),ks=function(){function e(t,r){var i=this;if(bo(this,e),this.plugins={},this.originHTML="",this.videoEventHandlerList=[],this.videoDomEventHandlerList=[],this.containerDomEventHandlerList=[],this.wrapperDomEventHandlerList=[],this.__domEventHandlerList={},this.__mouseInVideo=!1,this.__videoExtendedNodes=[],this.__dispatcher=r,!p(t)&&!l(t))throw new TypeError("Illegal wrapper");var n=J(t);if(0===n.length)throw new TypeError("Can not get dom node accroding wrapper. Please check your wrapper");this.wrapper=n[0],this.originHTML=this.wrapper.innerHTML;var a=n.find("video")[0];a||(a=document.createElement("video")),this.videoElement=a,this.__videoExtendedNodes.push(a),this.setAttr("videoElement","tabindex",-1),this._autoFocusToVideo(this.videoElement),this.videoElement.parentElement&&p(this.videoElement.parentElement)&&this.videoElement.parentElement!==this.wrapper?this.container=this.videoElement.parentElement:(this.container=document.createElement("container"),J(this.container).append(this.videoElement)),this.container.parentElement!==this.wrapper&&n.append(this.container),co.forEach(function(e){var t=function(){for(var t,r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];return(t=i.__dispatcher.bus).trigger.apply(t,[e].concat(n))};i.videoEventHandlerList.push(t),W(i.videoElement,e,t)}),vo.forEach(function(e){var t=i._getEventHandler(e,{penetrate:!0});i.videoDomEventHandlerList.push(t),W(i.videoElement,e,t);var r=function(){for(var t,r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];return(t=i.__dispatcher.bus).triggerSync.apply(t,["c_"+e].concat(n))};i.containerDomEventHandlerList.push(r),W(i.container,e,r);var n=function(){for(var t,r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];return(t=i.__dispatcher.bus).triggerSync.apply(t,["w_"+e].concat(n))};i.wrapperDomEventHandlerList.push(n),W(i.wrapper,e,n)})}return _o(e,[{key:"insertPlugin",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!l(e))throw new TypeError("insertPlugin id parameter must be string");if(p(this.plugins[e])&&(Ui.warn("Dispatcher.dom","Plugin "+e+" have already had a dom node. Now it will be replaced"),this.removePlugin(e)),l(t))if(y(t)){var o=document.createElement("div");o.innerHTML=t,t=o.children[0]}else t=document.createElement(w(t));else a(t)&&(n=t);var s=n,u=s.inner,c=s.penetrate,d=s.autoFocus,h=n.className,v=t&&p(t)?t:document.createElement("div");i(h)&&(h=h.join(" ")),l(h)&&j(v,h),this.plugins[e]=v;var g=u?this.container:this.wrapper,m=u?this.videoElement:this.container;return(f(d)?d:u)&&this._autoFocusToVideo(v),c&&(this.__domEventHandlerList[e]=this.__domEventHandlerList[e]||[],vo.forEach(function(t){var i=r._getEventHandler(t,{penetrate:c});W(v,t,i),r.__domEventHandlerList[e].push(i)}),this.__videoExtendedNodes.push(v)),g.lastChild===m?(g.appendChild(v),v):(g.insertBefore(v,m.nextSibling),v)}},{key:"removePlugin",value:function(e){var t=this;if(l(e)){var r=this.plugins[e];p(r)&&(r.parentNode&&r.parentNode.removeChild(r),this._autoFocusToVideo(r,!0)),u(this.__domEventHandlerList[e])||(vo.forEach(function(r,i){V(t.plugins[e],r,t.__domEventHandlerList[e][i])}),delete this.__domEventHandlerList[e]),delete this.plugins[e]}}},{key:"setPluginsZIndex",value:function(e){var t=this;e.forEach(function(e,r){return $(e.match(/^(videoElement|container)$/)?t[e]:t.plugins[e],"z-index",++r)})}},{key:"setAttr",value:function(e,t,r){G(this[e],t,r)}},{key:"getAttr",value:function(e,t){return B(this[e],t)}},{key:"setStyle",value:function(e,t,r){$(this[e],t,r)}},{key:"getStyle",value:function(e,t){return Y(this[e],t)}},{key:"requestFullScreen",value:function(e){for(var t=["requestFullscreen","mozRequestFullScreen","webkitRequestFullscreen","msRequestFullscreen"],r=0,i=t.length;r<i;r++)if(n(this[e][t[r]]))return this[e][t[r]](),!0;return!1}},{key:"exitFullScreen",value:function(){for(var e=["exitFullscreen","msExitFullscreen","mozCancelFullScreen","webkitExitFullscreen"],t=0,r=e.length;t<r;t++)if(n(document[e[t]]))return document[e[t]](),!0;return!1}},{key:"fullScreen",value:function(){for(var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"container",r=arguments.length,i=Array(r>2?r-2:0),n=2;n<r;n++)i[n-2]=arguments[n];return e?this.requestFullScreen.apply(this,[t].concat(To(i))):this.exitFullScreen.apply(this,To(i))}},{key:"focus",value:function(){this.videoElement.focus()}},{key:"destroy",value:function(){var e=this;this._autoFocusToVideo(this.videoElement,!1),co.forEach(function(t,r){V(e.videoElement,t,e.videoEventHandlerList[r])}),vo.forEach(function(t,r){V(e.videoElement,t,e.videoDomEventHandlerList[r]),V(e.container,t,e.containerDomEventHandlerList[r]),V(e.wrapper,t,e.wrapperDomEventHandlerList[r])}),this.wrapper.innerHTML=this.originHTML,delete this.wrapper,delete this.videoElement,delete this.plugins}},{key:"_autoFocusToVideo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];(t?V:W)(e,"mouseup",this._focusToVideo,!1,!0),(t?V:W)(e,"touchend",this._focusToVideo,!1,!0)}},{key:"_focusToVideo",value:function(e){var t=window.scrollX,r=window.scrollY;n(this.videoElement.focus)&&this.videoElement.focus(),window.scrollTo(t,r)}},{key:"_getEventHandler",value:function(e,t){var r=this;if(!t.penetrate||["mouseenter","mouseleave"].indexOf(e)<0)return function(){for(var t,i=arguments.length,n=Array(i),a=0;a<i;a++)n[a]=arguments[a];(t=r.__dispatcher.bus).triggerSync.apply(t,[e].concat(n))};var i=function(e){return r.__videoExtendedNodes.indexOf(e)>-1||r.__videoExtendedNodes.reduce(function(t,r){return t||g(r,e)},!1)};return function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var a=t[0],o=a.toElement,s=a.currentTarget,u=a.relatedTarget,l=a.type,f=o||u;if(r.__mouseInVideo&&"mouseleave"===l&&!i(f)){var c;return r.__mouseInVideo=!1,(c=r.__dispatcher.bus).triggerSync.apply(c,["mouseleave"].concat(t))}if(!r.__mouseInVideo&&"mouseenter"===l&&i(s)){var d;return r.__mouseInVideo=!0,(d=r.__dispatcher.bus).triggerSync.apply(d,["mouseenter"].concat(t))}}}}]),e}(),Ie(ks.prototype,"setAttr",[gs,ys],Object.getOwnPropertyDescriptor(ks.prototype,"setAttr"),ks.prototype),Ie(ks.prototype,"getAttr",[ms],Object.getOwnPropertyDescriptor(ks.prototype,"getAttr"),ks.prototype),Ie(ks.prototype,"setStyle",[bs],Object.getOwnPropertyDescriptor(ks.prototype,"setStyle"),ks.prototype),Ie(ks.prototype,"getStyle",[_s],Object.getOwnPropertyDescriptor(ks.prototype,"getStyle"),ks.prototype),Ie(ks.prototype,"requestFullScreen",[Es],Object.getOwnPropertyDescriptor(ks.prototype,"requestFullScreen"),ks.prototype),Ie(ks.prototype,"_focusToVideo",[ye],Object.getOwnPropertyDescriptor(ks.prototype,"_focusToVideo"),ks.prototype),ks),Du={src:[function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=l(t[0])?t.shift():"";return t.unshift(function(e){return l(e)?e:i}),ce({set:t,get:t})}(),ce({set:function(e){return this.needToLoadSrc&&(this.needToLoadSrc=!1,this.dispatcher.bus.emit("load",e)),e}},{preSet:!1}),ce({set:function(e){return this.dispatcher.readySync&&this.autoload&&e!==this.src&&(this.needToLoadSrc=!0),e}})],autoload:Le(),autoplay:[Le(),Ge("autoplay")],controls:[Le(),Ge("controls")],width:[ce({set:Ue}),je("width")],height:[ce({set:Ue}),je("height")],crossOrigin:[ce({set:Be}),je({set:"crossorigin",get:"crossOrigin"})],loop:[Le(),Ge("loop")],defaultMuted:[Le(),je({get:"defaultMuted",set:"muted",isBoolean:!0})],muted:[Le(),Ge("muted")],preload:[ce({set:Be}),je("preload")],poster:[ce({set:Be}),je("poster")],playsInline:[ce({get:function(e){var t=this.videoElement.playsInline;return this.dispatcher.videoConfigReady&&this.inited?void 0===t?e:t:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;this.videoElement.playsInline=e;var t=e?"":void 0;return this.dispatcher.dom.setAttr("video","playsinline",t),this.dispatcher.dom.setAttr("video","webkit-playsinline",t),this.dispatcher.dom.setAttr("video","x5-video-player-type",e?"h5":void 0),e}}),Le()],x5VideoPlayerFullScreen:[ce({set:function(e){return!!e},get:function(e){return!!e}}),He("x5-video-player-fullscreen",!0)],x5VideoOrientation:[ce({set:Be}),He("x5-video-orientation")],xWebkitAirplay:[ce({set:function(e){return!!e},get:function(e){return!!e}}),He("x-webkit-airplay",!0)],playbackRate:[Oe(1),Ge("playbackRate")],defaultPlaybackRate:[Ge("defaultPlaybackRate"),Oe(1)],disableRemotePlayback:[Le(),Ge("disableRemotePlayback")],volume:[Oe(1),Ge("volume")]},Pu=(ws=Re(),Ss=Re(function(e){return e.toLocaleLowerCase()}),Ts=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=i(t[0])?t.shift():[];return t.unshift(function(e){return i(e)?e:n}),he.apply(void 0,t)}(),As=function(){function e(t,r){bo(this,e),Fe(this,"needToLoadSrc",Rs,this),Fe(this,"inited",Ls,this),this.src="",Fe(this,"type",Os,this),Fe(this,"box",Ds,this),Fe(this,"runtimeOrder",Ps,this),this.autoload=!0,this.autoplay=!1,this.controls=!1,this.width=void 0,this.height=void 0,this.crossOrigin=void 0,this.loop=!1,this.defaultMuted=!1,this.muted=!1,this.preload="auto",this.poster=void 0,this.playsInline=!1,this.x5VideoPlayerFullScreen=!1,this.x5VideoOrientation=void 0,this.xWebkitAirplay=!1,this.playbackRate=1,this.defaultPlaybackRate=1,this.disableRemotePlayback=!1,this.volume=1,Fe(this,"_kernelProperty",xs,this),Fe(this,"_realDomAttr",Is,this),Ee(this,Du,{self:!0}),Object.defineProperty(this,"dispatcher",{value:t,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(this,"videoElement",{value:t.dom.videoElement,enumerable:!1,writable:!1,configurable:!1}),E(this,r)}return _o(e,[{key:"lockKernelProperty",value:function(){Ee(this,{type:be,box:be,runtimeOrder:be},{self:!0})}}]),_o(e,[{key:"init",value:function(){var e=this;this._realDomAttr.forEach(function(t){e[t]=e[t]}),this.inited=!0}}]),e}(),Rs=Ne(As.prototype,"needToLoadSrc",[_e],{enumerable:!0,initializer:function(){return!1}}),Ls=Ne(As.prototype,"inited",[_e],{enumerable:!0,initializer:function(){return!1}}),Os=Ne(As.prototype,"type",[ws,Ae],{enumerable:!0,initializer:function(){return"vod"}}),Ds=Ne(As.prototype,"box",[Ss,Ae],{enumerable:!0,initializer:function(){return""}}),Ps=Ne(As.prototype,"runtimeOrder",[Ts,Ae],{enumerable:!0,initializer:function(){return["html5","flash"]}}),xs=Ne(As.prototype,"_kernelProperty",[me],{enumerable:!0,initializer:function(){return["type","box","runtimeOrder"]}}),Is=Ne(As.prototype,"_realDomAttr",[me],{enumerable:!0,initializer:function(){return["src","controls","width","height","crossOrigin","loop","muted","preload","poster","autoplay","playsInline","x5VideoPlayerFullScreen","x5VideoOrientation","xWebkitAirplay","playbackRate","defaultPlaybackRate","autoload","disableRemotePlayback","defaultMuted","volume"]}}),As),xu={},Iu=(Cs=de(Ve),Ms=de(function(e){if(n(e)){if(!(e.prototype instanceof Lu))throw new TypeError("If you pass a function as plugin config, this class must extends from Chimee.plugin")}else{if(!a(e)||u(e))throw new TypeError("plugin's config must be an Object");var t=e.name;if(!l(t)||t.length<1)throw new TypeError("plugin must have a legal name")}}),Fs=de(Ve),Ns=de(Ve),Us=de(Ve),Bs=function(){function e(t,r){var i=this;if(bo(this,e),this.plugins={},this.order=[],this.readySync=!1,this.zIndexMap={inner:[],outer:[]},!a(t))throw new TypeError("UserConfig must be an Object");this.dom=new Ou(t.wrapper,this),this.bus=new Ro(this),this.vm=r,this.videoConfigReady=!1,this.videoConfig=new Pu(this,t),this._initUserPlugin(t.plugin),this.order.forEach(function(e){return i.plugins[e].__init(i.videoConfig)}),this.videoConfig.lockKernelProperty(),this.videoConfigReady=!0,this.videoConfig.init(),this.kernel=new fo(this.dom.videoElement,this.videoConfig);var n=[];this.order.forEach(function(e){var t=i.plugins[e].__inited();c(t)&&n.push(t)}),this.readySync=0===n.length,this.ready=this.readySync?Promise.resolve():Promise.all(n).then(function(){i.readySync=!0,i.bus.trigger("ready"),i._autoloadVideoSrcAtFirst()}),this.readySync&&this._autoloadVideoSrcAtFirst()}return _o(e,[{key:"use",value:function(t){if(l(t)&&(t={name:t,alias:void 0}),!a(t)||a(t)&&!l(t.name))throw new TypeError("pluginConfig do not match requirement");l(t.alias)||(t.alias=void 0);var r=t,i=r.name,o=r.alias;t.name=o||i,delete t.alias;var s=k(i),f=k(o||i),c=t,d=e.getPluginConfig(s);if(u(d))throw new TypeError("You have not installed plugin "+s);a(d)&&(d.id=f);var h=n(d)?new d({id:f},this,c):new Lu(d,this,c);return this.plugins[f]=h,Object.defineProperty(this.vm,f,{value:h,configurable:!0,enumerable:!1,writable:!1}),this.order.push(f),this._sortZIndex(),this.videoConfigReady&&h.__inited(),h.ready}},{key:"unuse",value:function(e){var t=this.plugins[e];if(a(t)&&n(t.$destroy)){t.$destroy();var r=this.order.indexOf(e);r>-1&&this.order.splice(r,1),delete this.plugins[e],delete this.vm[e]}else delete this.plugins[e]}},{key:"throwError",value:function(e){this.vm.__throwError(e)}},{key:"destroy",value:function(){for(var e in this.plugins)this.unuse(e);this.bus.destroy(),delete this.bus,this.dom.destroy(),delete this.dom,this.kernel.destroy(),delete this.kernel,delete this.vm,delete this.plugins,delete this.order}},{key:"_initUserPlugin",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return i(t)||(Ui.warn("Dispatcher","UserConfig.plugin can only by an Array"),t=[]),t.map(function(t){return e.use(t)})}},{key:"_sortZIndex",value:function(){var e=this,t=this.order.reduce(function(t,r){var i=e.plugins[r];if(u(i))return t;var n=t[i.$inner?"inner":"outer"],a=i.$level;return n[a]=n[a]||[],n[a].push(r),t},{inner:{},outer:{}}),r=t.inner,i=t.outer;r[0]=r[0]||[],r[0].unshift("videoElement"),i[0]=i[0]||[],i[0].unshift("container");var n=A(r),a=A(i);this.dom.setPluginsZIndex(n),this.dom.setPluginsZIndex(a),this.zIndexMap.inner=n,this.zIndexMap.outer=a}},{key:"_getTopLevel",value:function(e){var t=this.zIndexMap[e?"inner":"outer"],r=this.plugins[t[t.length-1]];return u(r)?0:r.$level}},{key:"_autoloadVideoSrcAtFirst",value:function(){this.videoConfig.autoload&&this.bus.emit("load",this.videoConfig.src)}}],[{key:"install",value:function(e){var t=e.name,r=k(t);u(xu[r])||Ui.warn("Dispatcher","You have installed "+t+" again. And the older one will be replaced");var i=n(e)?e:E({id:r},e);return xu[r]=i,r}},{key:"hasInstalled",value:function(e){return!u(xu[e])}},{key:"uninstall",value:function(e){delete xu[e]}},{key:"getPluginConfig",value:function(e){return xu[e]}}]),e}(),ze(Bs.prototype,"unuse",[Cs],Object.getOwnPropertyDescriptor(Bs.prototype,"unuse"),Bs.prototype),ze(Bs,"install",[Ms],Object.getOwnPropertyDescriptor(Bs,"install"),Bs),ze(Bs,"hasInstalled",[Fs],Object.getOwnPropertyDescriptor(Bs,"hasInstalled"),Bs),ze(Bs,"uninstall",[Ns],Object.getOwnPropertyDescriptor(Bs,"uninstall"),Bs),ze(Bs,"getPluginConfig",[Us],Object.getOwnPropertyDescriptor(Bs,"getPluginConfig"),Bs),Bs),Cu=(Gs=function(){function e(){bo(this,e),this.log={error:!0,info:!0,warn:!0,debug:!0,verbose:!0},We(this,"_silent",js,this),this.errorHandler=void 0;var t=Object.keys(this.log).reduce(function(e,t){return e[t]=ce({get:function(){return Ui["ENABLE_"+t.toUpperCase()]},set:function(e){return Ui["ENABLE_"+t.toUpperCase()]=e,!0===e&&(this.silent=!1),e}}),e},{});Ee(this.log,t,{self:!0})}return _o(e,[{key:"silent",get:function(){return this._silent},set:function(e){var t=this;e=!!e,this._silent=e,Object.keys(this.log).forEach(function(r){t.log[r]=!e})}}]),e}(),js=function(e,t,r,i,n){var a={};return Object.keys(i).forEach(function(e){a[e]=i[e]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}(Gs.prototype,"_silent",[_e],{enumerable:!0,initializer:function(){return!1}}),Gs);return Hs=yu(),zs=pe("addEventListener"),Vs=de(De),Ws=de(De),Ks=pe("removeEventListener"),qs=de(De),Ys=de(Pe),$s=de(Pe),Hs((uu=su=function(e){function t(e){bo(this,t);var r=So(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));if(r.destroyed=!1,Ke(r,"__id",Zs,r),Ke(r,"version",Js,r),Ke(r,"config",eu,r),l(e)||p(e))e={wrapper:e,controls:!0};else{if(!a(e))throw new Error("You must pass in an Object containing wrapper or string or element to new a Chimee");if(!e.wrapper)throw new Error("You must pass in an legal object")}return r.__dispatcher=new Iu(e,r),r.__dispatcher.kernel.on("error",r.__throwError),r.ready=r.__dispatcher.ready,r.readySync=r.__dispatcher.readySync,r.__wrapAsVideo(r.__dispatcher.videoConfig),r}return wo(t,Ru),_o(t,[{key:"destroy",value:function(){ko(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"__destroy",this).call(this),this.__dispatcher.destroy(),this.destroyed=!0}},{key:"use",value:function(e){this.__dispatcher.use(e)}},{key:"unuse",value:function(e){this.__dispatcher.unuse(e)}},{key:"on",value:function(e,t){return this.__dispatcher.bus.on("_vm",e,t),this}},{key:"off",value:function(e,t){return this.__dispatcher.bus.off("_vm",e,t)}},{key:"once",value:function(e,t){return this.__dispatcher.bus.once("_vm",e,t)}},{key:"emit",value:function(e){var t;if(!l(e))throw new TypeError("emit key parameter must be String");vo.indexOf(e.replace(/^\w_/,""))>-1&&Ui.warn("plugin","You are using emit to emit "+e+" event. As emit is wrapped in Promise. It make you can't use event.preventDefault and event.stopPropagation. So we advice you to use emitSync");for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.bus).emit.apply(t,[e].concat(To(i)))}},{key:"emitSync",value:function(e){var t;if(!l(e))throw new TypeError("emitSync key parameter must be String");for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.bus).emitSync.apply(t,[e].concat(To(i)))}},{key:"css",value:function(e){for(var t,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.dom)[e+"Style"].apply(t,i)}},{key:"attr",value:function(e){for(var t,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if("set"===e&&/video/.test(i[0])){if(!this.__dispatcher.videoConfigReady)return Ui.warn("plugin","You are tring to set attribute on video before video inited. Please wait until the inited event has benn trigger"),i[2];if(this.__dispatcher.videoConfig._realDomAttr.indexOf(i[1])>-1){var a=i[1],o=i[2];return this.__dispatcher.videoConfig[a]=o,o}}return(t=this.__dispatcher.dom)[e+"Attr"].apply(t,i)}},{key:"__throwError",value:function(e){l(e)&&(e=new Error(e));var r=this.config.errorHandler||t.config.errorHandler;if(n(r))return r(e);if(!t.config.silent)throw e}}]),t}(),su.plugin=Lu,su.config=new Cu,su.install=Iu.install,su.uninstall=Iu.uninstall,su.hasInstalled=Iu.hasInstalled,su.getPluginConfig=Iu.getPluginConfig,Qs=uu,Zs=qe(Qs.prototype,"__id",[me],{enumerable:!0,initializer:function(){return"_vm"}}),Js=qe(Qs.prototype,"version",[me],{enumerable:!0,initializer:function(){return"0.1.3"}}),eu=qe(Qs.prototype,"config",[me],{enumerable:!0,initializer:function(){return{errorHandler:void 0}}}),qe(Qs,"plugin",[me],(tu=Object.getOwnPropertyDescriptor(Qs,"plugin"),tu=tu?tu.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return tu}}),Qs),qe(Qs,"config",[me],(ru=Object.getOwnPropertyDescriptor(Qs,"config"),ru=ru?ru.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return ru}}),Qs),qe(Qs,"install",[me],(iu=Object.getOwnPropertyDescriptor(Qs,"install"),iu=iu?iu.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return iu}}),Qs),qe(Qs,"uninstall",[me],(nu=Object.getOwnPropertyDescriptor(Qs,"uninstall"),nu=nu?nu.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return nu}}),Qs),qe(Qs,"hasInstalled",[me],(au=Object.getOwnPropertyDescriptor(Qs,"hasInstalled"),au=au?au.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return au}}),Qs),qe(Qs,"getPluginConfig",[me],(ou=Object.getOwnPropertyDescriptor(Qs,"getPluginConfig"),ou=ou?ou.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return ou}}),Qs),qe(Qs.prototype,"on",[zs,Vs],Object.getOwnPropertyDescriptor(Qs.prototype,"on"),Qs.prototype),qe(Qs.prototype,"off",[Ws,Ks],Object.getOwnPropertyDescriptor(Qs.prototype,"off"),Qs.prototype),qe(Qs.prototype,"once",[qs],Object.getOwnPropertyDescriptor(Qs.prototype,"once"),Qs.prototype),qe(Qs.prototype,"css",[Ys],Object.getOwnPropertyDescriptor(Qs.prototype,"css"),Qs.prototype),qe(Qs.prototype,"attr",[$s],Object.getOwnPropertyDescriptor(Qs.prototype,"attr"),Qs.prototype),Xs=Qs))||Xs}); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Chimee=t()}(this,function(){"use strict";function e(e){return e&&e.__esModule?e.default:e}function t(e,t){return t={exports:{}},e(t,t.exports),t.exports}function r(e){return void 0===e||null===e}function n(e){return Array.isArray(e)}function i(e){return"function"==typeof e}function o(e){return Object(e)===e&&"[object Object]"===String(e)&&!i(e)&&!n(e)}function u(e){return"number"==typeof e}function a(e){return!n(e)&&e-Fn(e)+1>=0}function s(e){return kn(e)}function c(e){return n(e)?0===e.length:o(e)?0===bn(e).length:!e}function l(e){return"string"==typeof e||e instanceof String}function f(e){return"boolean"==typeof e}function d(e){return!!e&&("object"===(void 0===e?"undefined":gn(e))||"function"==typeof e)&&"function"==typeof e.then}function h(e){return r(e)||f(e)||l(e)||u(e)}function p(e){return!!("object"===("undefined"==typeof Node?"undefined":gn(Node))?e instanceof Node:e&&"object"===(void 0===e?"undefined":gn(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}function v(e){return!!("object"===("undefined"==typeof HTMLElement?"undefined":gn(HTMLElement))?e instanceof HTMLElement:e&&"object"===(void 0===e?"undefined":gn(e))&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)}function y(e,t){if(!p(e)||!p(t))return!1;for(;t.parentNode;)if((t=t.parentNode)===e)return!0;return!1}function g(e){return/<[^>]+?>/.test(e)}function m(e){return e instanceof Error}function _(e,t){if(!l(e))throw new TypeError("Log's method only acccept string as argument");return l(t)?"["+(e=$n.FORCE_GLOBAL_TAG?$n.GLOBAL_TAG:e||$n.GLOBAL_TAG)+"] > "+t:"["+$n.GLOBAL_TAG+"] > "+e}function b(e){if(h(e))throw new TypeError("deepClone only accept non primitive type");return oi(e)}function w(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length<2)throw new Error("deepAssign accept two and more argument");for(var n=t.length-1;n>-1;n--)if(h(t[n]))throw new TypeError("deepAssign only accept non primitive type");var i=t.shift();return t.forEach(function(e){return oi(e,i)}),i}function E(e,t){return e.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g,function(e,r,n,i){return t||0!==i?n.toUpperCase():n.toLowerCase()})}function k(e){return E(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}function O(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];return e.apply(t,n)}:function(){for(var r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];return e.call.apply(e,[t].concat(ii(n)))}}function P(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=i.throwError,u=void 0!==o&&o,a=i.backup;if(l(t)&&(t=t.split(".")),!n(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var s=[],c=e,f=0,d=t.length;f<d;f++){var h=t[f];if(r(c)){if(u)throw new Error("obj"+(s.length>0?"."+s.join("."):" itself")+" is "+c);return a}c=c[h],s.push(h)}return c}function S(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return bn(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])}function j(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new Qi(function(t,n){!function o(u){if(!(u>=e.length)){var a=i(e[u])?e[u].apply(e,ii(r)):e[u];return!1===a?n("stop"):Qi.resolve(a).then(function(){return o(u+1)}).catch(function(e){return n(e||"stop")})}t()}(0)})}function x(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return function t(n){return n>=e.length||!1!==(i(e[n])?e[n].apply(e,ii(r)):e[n])&&t(++n)}(0)}function A(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++oo.count);var n=r+"_"+t,i=oo[n];return i||(i=oo[n]=[]),i}function T(e,t,r){var n=io(null);n.type=t,n.target=e,r&&eo(n,o(r)?r:{data:r}),A(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[n])})}function L(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments[4];i(n)&&!o&&(o=n,n=void 0);var u=[r,void 0,n];n&&!o&&(o=function(){M(e,t,r,n);for(var i=arguments.length,o=Array(i),u=0;u<i;u++)o[u]=arguments[u];r.apply(e,o)}),o&&(u[1]=o),A(e,t).push(u)}function M(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=A(e,t);if(r||n){var o=-1,u=void 0;return i.find(function(e,t){if((!r||e[0]===r)&&(!n||e[2]))return o=t,u=e[1],!0}),-1!==o&&i.splice(o,1),u}i.length=0}function C(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++ao.count);var n=r+"_"+t,i=ao[n];return i||(i=ao[n]=[]),i}function z(e,t,r){var n=io(null);n.type=t,n.target=e,r&&eo(n,o(r)?r:{data:r}),C(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[n])})}function F(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments[4];i(n)&&!o&&(o=n,n=void 0);var u=[r,void 0,n];n&&!o&&(o=function(){$(e,t,r,n);for(var i=arguments.length,o=Array(i),u=0;u<i;u++)o[u]=arguments[u];r.apply(e,o)}),o&&(u[1]=o),C(e,t).push(u)}function $(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=C(e,t);if(r||n){var o=-1,u=void 0;return i.find(function(e,t){if((!r||e[0]===r)&&(!n||e[2]))return o=t,u=e[1],!0}),-1!==o&&i.splice(o,1),u}i.length=0}function N(e){return ni(e)}function D(e,t){return e.getAttribute(t)}function I(e,t,r){void 0===r?e.removeAttribute(t):e.setAttribute(t,r)}function R(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.add(t)});else{var n=" "+(e.className||"")+" ";r.forEach(function(e){-1===n.indexOf(" "+e+" ")&&(n+=" "+e)}),e.className=n.trim()}}}function H(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.remove(t)});else{var n=" "+e.className+" ";r.forEach(function(e){for(var t=" "+e+" ";-1!==n.indexOf(t);)n=n.replace(t," ")}),e.className=n.trim()}}}function V(e,t){return new RegExp("(?:^|\\s)"+t+"(?=\\s|$)").test(e.className)}function B(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(n){var o=$(e,t+"_once",r);o&&(r=o)}e.removeEventListener(t,r,i)}function W(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(n){var o=r;F(e,t+"_once",o,r=function(){for(var u=arguments.length,a=Array(u),s=0;s<u;s++)a[s]=arguments[s];o.apply(this,a),B(e,t,r,n,i)})}e.addEventListener(t,r,i)}function Y(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=function(r){var i=Z(r.target||r.srcElement,e,!0),o=K(t,e,!0).find(function(e){return i.find(function(t){return e===t})});o&&n.apply(o,arguments)};F(e,r+"_delegate_"+t,n,o),e.addEventListener(r,o,i)}function G(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=$(e,r+"_delegate_"+t,n);o&&e.removeEventListener(r,o,i)}function q(e,t){return(e.currentStyle||document.defaultView.getComputedStyle(e,null))[t]||e.style[t]}function U(e,t,r){if(o(t))for(var n in t)U(e,n,t[n]);else e.style[t]=r}function K(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document,r=arguments[2],n=t.querySelectorAll(e);return r?ni(n):n}function Q(e){e.parentNode.removeChild(e)}function Z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments[2],n=arguments[3],i=[];for(r&&i.push(e);e&&e.parentNode!==t;)(e=e.parentNode)&&i.push(e);return n&&i.push(t),i}function J(e,t){return e.constructor===fo?e:new fo(e,t)}function X(e){if(!e||!e.hasOwnProperty)return!1;for(var t=["value","initializer","get","set"],r=0,n=t.length;r<n;r++)if(e.hasOwnProperty(t[r]))return!0;return!1}function ee(e){return!!e&&(i(e.get)||i(e.set))&&f(e.configurable)&&f(e.enumerable)&&void 0===e.writable}function te(e){return!!e&&e.hasOwnProperty("value")&&f(e.configurable)&&f(e.enumerable)&&f(e.writable)}function re(e){return!!e&&i(e.initializer)&&f(e.configurable)&&f(e.enumerable)&&f(e.writable)}function ne(e){return function(t){return ht(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t}),t}}function ie(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"You must pass me an array of function";if(!n(e)||e.length<1)throw new TypeError(t);if(1===e.length){if(!i(e[0]))throw new TypeError(t);return e[0]}return e.reduce(function(e,r){if(!i(r)||!i(e))throw new TypeError(t);return function(t){return O(r,this)(O(e,this)(t))}})}function oe(){var e,t;if(i(console.warn))return(e=console).warn.apply(e,arguments);(t=console).log.apply(t,arguments)}function ue(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.forEach(function(e){if(!i(t[0]))throw new TypeError("compressMultipleDecorators only accept function")}),1===t.length?t[0]:function(e,r,n){return t.reduce(function(t,n){return n(e,r,t)},n)}}function ae(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.get,r=e.set,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},u=o.preGet,a=void 0!==u&&u,s=o.preSet,c=void 0===s||s;if(!(i(t)||i(r)||n(t)&&t.length>0||n(r)&&r.length>0))throw new TypeError("@accessor need a getter or setter. If you don't need to add setter/getter. You should remove @accessor");var l="@accessor only accept function or array of function as getter/setter";return t=n(t)?ie(t,l):t,r=n(r)?ie(r,l):r,function(e,n,o){var u=o||{},s=u.configurable,l=void 0===s||s,f=u.enumerable,d=void 0===f||f,h=i(t),p=i(r),v=function(e){return h?O(t,this)(e):e},y=function(e){return p?O(r,this)(e):e};if(ee(o)){var g=o.get,m=o.set,_=i(g),b=i(m);return!_&&h&&oe("You are trying to set getter via @accessor on "+n+" without getter. That's not a good idea."),!b&&p&&oe("You are trying to set setter via @accessor on "+n+" without setter. That's not a good idea."),{get:_||h?function(){var e=this,t=O(v,this),r=function(){return _?O(g,e)():void 0};return(a?[t,r]:[r,t]).reduce(function(e,t){return t(e)},void 0)}:void 0,set:b||p?function(e){var t=this,r=O(y,this),n=function(e){return b?O(m,t)(e):e};return(c?[r,n]:[n,r]).reduce(function(e,t){return t(e)},e)}:void 0,configurable:l,enumerable:d}}if(re(o)){var w=o.initializer,E=void 0,k=!1;return{get:function(){var e=O(v,this);return k?e(E):(E=O(w,this)(),k=!0,e(E))},set:function(e){var t=O(y,this);return E=c?t(e):e,k=!0,c||t(E),E},configurable:l,enumerable:d}}var P=(o||{}).value;return{get:function(){return O(v,this)(P)},set:function(e){var t=O(y,this);return P=c?t(e):e,c||t(P),P},configurable:l,enumerable:d}}}function se(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@before accept at least one parameter. If you don't need to preprocess before your function, do not add @before decorators");if(t.length>2&&X(t[2]))throw new Error("You may use @before straightly, @before return decorators, you need to call it");for(var o=t.length-1;o>-1;o--)if(!i(t[o]))throw new TypeError("@before only accept function parameter");return function(e,r,o){if(void 0===o)throw new Error("@before must used on descriptor, are you using it on undefined property?");var u=o.value,a=o.configurable,s=o.enumerable,c=o.writable;if(!i(u))throw new TypeError("@before can only be used on function");return{value:function(){for(var e=this,r=arguments.length,i=Array(r),o=0;o<r;o++)i[o]=arguments[o];var a=t.reduce(function(t,r){var i=O(r,e).apply(void 0,ii(t));return void 0===i?t:n(i)?i:[i]},i);return O(u,this).apply(void 0,ii(a))},configurable:a,enumerable:s,writable:c}}}function ce(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@initialize accept at least one parameter. If you don't need to initialize your value, do not add @initialize.");if(t.length>2&&X(t[2]))throw new Error("You may use @initialize straightly, @initialize return decorators, you need to call it");var n=ie(t,"@initialize only accept function parameter");return function(e,t,r){if(void 0===r)return{value:O(n,e)(),configurable:!0,writable:!0,enumerable:!0};if(ee(r)){var i=!1;return ae({get:function(e){return i?e:O(n,this)(e)},set:r.set?function(e){return i=!0,e}:void 0})(e,t,r)}if(re(r)){var o=r.initializer;return{initializer:function(){return O(n,this)(O(o,this)())},configurable:r.configurable,writable:r.writable,enumerable:r.enumerable}}return{value:O(n,this)(r.value),writable:r.writable,configurable:r.configurable,enumerable:r.enumerable}}}function le(e,t,r,n,i,o){var u=r.configurable,a=r.enumerable,s=o.force,c=o.omit,l=$a(n,i);if(void 0!==l){if(c)return;if(!s)throw new Error("@alias can't set alias on an existing attribute");if(!l.configurable)throw new Error("You are tring to set alias on an existing attribute which its configurable is false. That's impossible. Please check if you have set @frozen on it.")}Na(n,i,{get:function(){return e[t]},set:function(r){return e[t]=r,t},configurable:u,enumerable:a})}function fe(e,t,r){if(2===arguments.length?l(e)&&(r=t,t=e,e=void 0):1===arguments.length&&(t=e,e=void 0),!l(t))throw new TypeError("@alias need a string as a key to find the porperty to set alias on");var n="If you want to use @alias to set alias on other instance, you must pass in a legal instance";if(void 0!==e&&h(e))throw new TypeError(n);var i=o(r)?r:{force:!1,omit:!1},u=i.force,a=i.omit;return function(r,i,o){function s(e,t,r){var i=h(e)?t:e,o=r.split("."),u=o.slice(-1),a=uu(u,1)[0];if(i=P(i,o.slice(0,-1),{throwError:!0}),h(i))throw new TypeError(n);return{target:i,name:a}}if(o=o||{value:void 0,configurable:!0,writable:!0,enumerable:!0},re(o))return ce(function(r){var n=s(e,this,t),c=n.target,l=n.name;return le(this,i,o,c,l,{force:u,omit:a}),r})(r,i,o);if(ee(o)){var c=void 0,l=function(r){if(c)return r;var n=s(e,this,t),l=n.target,f=n.name;return le(this,i,o,l,f,{force:u,omit:a}),c=!0,r};return ae({get:l,set:l})(r,i,o)}var f=s(e,r,t),d=f.target,p=f.name;return le(r,i,o,d,p,{force:u,omit:a}),o}}function de(e,t){if(void 0===ku)throw new Error("Using @autobind on "+t.name+"() requires WeakMap support due to its use of super."+t.name+"()");Ra||(Ra=new ku),!1===Ra.has(e)&&Ra.set(e,new ku);var r=Ra.get(e);return!1===r.has(t)&&r.set(t,O(t,e)),r.get(t)}function he(e,t,r){if(1===arguments.length)return Ia()(e);if(!X(r))throw new Error("@autobind must used on descriptor, are you using it on undefined property?");var n=r.value,o=r.configurable;if(!i(n))throw new TypeError("@autobind can only be used on functions, not: "+n+")");var u=e.constructor;return{configurable:o,enumerable:!1,get:function(){var r=this,i=function(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];return n.call.apply(n,[r].concat(ii(t)))};return this===e?n:this.constructor!==u&&po(this).constructor===u?n:this.constructor!==u&&t in this.constructor.prototype?de(this,n):(ht(this,t,{configurable:!0,writable:!0,enumerable:!1,value:i}),i)},set:ne(t)}}function pe(e,t,r){if(void 0===r)return oe("You are using @frozen on an undefined property. This property will become a frozen undefined forever, which is meaningless"),{value:void 0,writable:!1,enumerable:!1,configurable:!1};if(r.enumerable=!1,r.configurable=!1,ee(r)){var n=r.get;return r.set=void 0,i(n)?{get:function(){var e=O(n,this)();return Ha(this,t,{value:e,writable:!1,configurable:!1,enumerable:!1}),e},set:void 0,configurable:!1,enumerable:!1}:void oe("You are using @frozen on one accessor descriptor without getter. This property will become a frozen undefined finally.Which maybe meaningless.")}return r.writable=!1,r}function ve(e,t,r){if(void 0===r)return oe("You are using @lock on an undefined property. This property will become a lock undefined forever, which is meaningless"),{value:void 0,writable:!1,enumerable:!0,configurable:!1};if(r.configurable=!1,ee(r)){var n=r.get;return r.set=void 0,i(n)?{get:function(){var e=O(n,this)();return Wa(this,t,{value:e,writable:!1,configurable:!1,enumerable:r.enumerable}),e},set:void 0,configurable:!1,enumerable:r.enumerable}:void oe("You are using @lock on one accessor descriptor without getter. This property will become a lock undefined finally.Which maybe meaningless.")}return r.writable=!1,r}function ye(e,t,r){return void 0===r?{value:void 0,enumerable:!1,configurable:!0,writable:!0}:(r.enumerable=!1,r)}function ge(e,t){var u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=u.self,s=void 0!==a&&a,c=u.omit,l=void 0!==c&&c,f=i(t);if(f||n(t)){if(!i(e))throw new TypeError("If you want to decorator class, you must pass it a legal class");if(f)t(e);else for(var d=0,p=t.length;d<p;d++){var v=t[d];if(!i(v))throw new TypeError("If you want to decorate an class, you must pass it function or array of function");v(e)}return e}if(!s&&!i(e))throw new TypeError("applyDecorators only accept class as first arguments. If you want to modify instance, you should set options.self true.");if(s&&h(e))throw new TypeError("We can't apply docorators on a primitive value, even in self mode");if(!o(t))throw new TypeError("applyDecorators only accept object as second arguments");var y=s?e:e.prototype;if(r(y))throw new Error("The class muse have a prototype, please take a check");for(var g in t){var m=t[g],_=n(m)?m:[m],b=void 0;try{b=ue.apply(void 0,ii(_))}catch(e){throw oe(e&&e.message),new Error("The decorators set on props must be Function or Array of Function")}var w=Ga(y,g);if(!w||w.configurable)Ya(y,g,b(y,g,w));else if(!l)throw new Error(g+" of "+y+" is unconfigurable")}return e}function me(e,t,r){var i,u=r.diff,a=r.operationPrefix,s={},c=!1,l=new Proxy(e,{get:function(e,r,i){var l=e[r];if(n(e)&&qa.indexOf(r)>-1)return function(){c=!0,O(l,i).apply(void 0,arguments),c=!1,t()};if(!0===s[r])return l;if(o(l)||n(l)){var f=s[r]||me(l,t,{diff:u,operationPrefix:a});return s[r]=f,f}return s[r]=!0,l},set:function(e,r,i){var l=e[r],f=o(i)||n(i)?me(i,t,{diff:u,operationPrefix:a}):i;return e[r]=f,s[r]=!0,!!(c||u&&l===f)||(t(),!0)},deleteProperty:function(e,r){return delete e[r],delete s[r],!!c||(t(),!0)}}),f=(i={},Ou(i,a+"set",[ce(function(e){return function(e,t){l[e]=t}}),ye]),Ou(i,a+"del",[ce(function(e){return function(e){delete l[e]}}),ye]),i);return ge(l,f,{self:!0}),l}function _e(e,t,r){function u(e){var r=void 0;return e.reduce(function(e,i){return e[i]=[ae({set:function(e){return r=this[i],e}}),ae({get:function(e){return f[i]?e:((o(e)||n(e))&&_e(e,t,{operationPrefix:c,diff:l}),f[i]=!0,e)},set:function(e){return(o(e)||n(e))&&_e(e,t,{operationPrefix:c,diff:l}),f[i]=!0,d||l&&r===e||t(),e}},{preSet:!1})],e},{})}var a,s=this,c=r.operationPrefix,l=r.diff,f={},d=!1,h=u(za(e));if(ge(e,h,{self:!0,omit:!0}),n(e)){var p=qa.reduce(function(r,n){return r[n]=[ce(function(r){return r=i(r)?r:Array.prototype[n],function(){var n=e.length;if(d=!0,O(r,e).apply(void 0,arguments),d=!1,n<e.length){var i=u(new Array(e.length-n).fill(1).map(function(e,t){return(t+n).toString()}));ge(e,i,{self:!0,omit:!0})}t()}}),ye],r},{});ge(e,p,{self:!0})}var v=(a={},Ou(a,c+"set",[ce(function(t){return function(r,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=o.disable,c=o.isNewVal;if(c=c||-1===za(e).indexOf(r),i(t)&&O(t,s)(r,n,{disable:!0,isNewVal:c}),c){var l=u([r]);ge(e,l,{self:!0,omit:!0})}a||(e[r]=n)}}),ye]),Ou(a,c+"del",[ce(function(r){return function(n){if(-1===za(e).indexOf(n)){var o=u([n]);ge(e,o,{self:!0,omit:!0})}i(r)?O(r,s)(n):delete e[n],t()}}),ye]),a);return ge(e,v,{self:!0}),e}function be(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var u=o(t[t.length-1])?t[t.length-1]:{},a=u.deep,s=u.omit,c=u.other,f=u.operationPrefix,d=void 0===f?"__":f,p=u.diff,v=void 0===p||p,y=u.proxy;if(Proxy||(y=!1,oe("You browser do not support Proxy, we will change back into observe mode.")),!t.length)throw new TypeError("You must pass a function or a string to find the hanlder function.");if(void 0!==c&&h(c))throw new TypeError("If you want us to trigger function on the other instance, you must pass in a legal instance");if(!l(d))throw new TypeError("operationPrefix must be an string");return function(e,r,u){var f=t.reduce(function(r,n,o){if(!l(n)&&!i(n)){if(!o||o!==t.length-1)throw new TypeError("You can only pass function or string as handler");return r}return r.push(l(n)?function(t,r){var o=P(c||e,n);if(i(o))return O(o,this)(t,r);if(!s)throw new Error("You pass in a function for us to trigger, please ensure the property to be a function or set omit flag true")}:n),r},[]),h=function(e,t){var r=this;f.forEach(function(n){return O(n,r)(e,t)})},p=!1,g=void 0,m=void 0,_=void 0;return ue(ae({set:function(e){var t=this;g=this[r],_=void 0;var i=function(){return O(h,t)(m,g)};return a&&(o(e)||n(e))?y?me(e,i,{diff:v,operationPrefix:d}):_e(e,i,{operationPrefix:d,diff:v}):e},get:function(e){var t=this;if(_)return _;if(!p){p=!0;var r=function(){return O(h,t)(m,g)};if(a&&(o(e)||n(e))){if(y)return _=me(e,r,{diff:v,operationPrefix:d}),g=_,m=_,_;_e(e,r,{operationPrefix:d,diff:v})}g=e,m=e}return e}},{preSet:!0}),ae({set:function(e){return m=e,v&&g===e||O(h,this)(m,g),g=e,e}},{preSet:!1}))(e,r,u)}}function we(e,t,r){if(void 0===r)throw new Error("@nonextendable could not handle undefined");return ce(function(e){return Ua(e),e})(e,t,r)}function Ee(e,t,r){return void 0===r?{value:void 0,enumerable:!0,configurable:!0,writable:!0}:(r.configurable=!0,r)}function ke(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=!!f(t[0])&&t.shift();return t.unshift(function(e){return f(e)?e:n}),ae({set:t,get:t})}function Oe(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=u(t[0])?t.shift():0;return t.unshift(function(e){return u(e)?e:n}),ae({set:t,get:t})}function Pe(e,t){if(!l(e))throw new TypeError("key parameter must be String");if(!i(t))throw new TypeError("fn parameter must be Function")}function Se(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.length>2?["set"].concat(t):2===t.length?["video","container","wrapper","videoElement"].indexOf(t[0])>-1?["get"].concat(t):["set","container"].concat(t):["get","container"].concat(t)}function je(e,t,r,n){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(n):void 0})}function xe(e,t,r,n,i){var o={};return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function Ae(e){return l(e)?e:void 0}function Te(e){return ae({get:function(t){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement[e]:t},set:function(t){return this.dispatcher.videoConfigReady?(this.dom.videoElement[e]=t,t):t}})}function Le(e){var t=o(e)?e:{set:e,get:e,isBoolean:!1},r=t.set,n=t.get,i=t.isBoolean;return ae({get:function(e){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement[n]:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;var t=i?e?"":void 0:e;return this.dom.setAttr("video",r,t),e}})}function Me(e,t){return ae({get:function(r){var n=this.dom.getAttr("video",e);return this.dispatcher.videoConfigReady&&this.inited?t?!!n:n:r},set:function(r){if(!this.dispatcher.videoConfigReady)return r;var n=t?r||void 0:r;return this.dom.setAttr("video",e,n),r}})}function Ce(e){return ae({get:function(t){if(!this.dispatcher.videoConfigReady)return t;var r=this.dom.getAttr("video",e),n=this.dom.videoElement[e];return a(r)&&u(n)?n:r||void 0},set:function(t){if(!this.dispatcher.videoConfigReady)return t;var r=void 0;return void 0===t||u(t)?r=t:l(t)&&!Number.isNaN(parseFloat(t))&&(r=t),this.dom.setAttr("video",e,r),r}})}function ze(e,t,r,n,i){var o={};return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function Fe(e){$n.warn("chimee","You are trying to obtain "+e+", we will return you the DOM node. It's not a good idea to handle this by yourself. If you have some requirement, you can tell use by https://github.com/Chimeejs/chimee/issues")}function $e(e,t,r,n,i){var o={};return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function Ne(e){if("video"===e&&(e="videoElement"),!v(this[e]))throw new TypeError("Your target "+e+" is not a legal HTMLElement");for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return[e].concat(r)}function De(e,t,r){if(!l(t))throw new TypeError("to handle dom's attribute or style, your attr parameter must be string");if(!l(e))throw new TypeError("to handle dom's attribute or style, your target parameter must be string");return[e,t,r]}function Ie(e,t,r,n,i){var o={};return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function Re(e){if(!l(e))throw new Error("Plugin's name must be a string");return E(e)}function He(e,t,r,n){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(n):void 0})}function Ve(e,t,r,n){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(n):void 0})}function Be(e,t,r,n,i){var o={};return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var We=e(t(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}})),Ye=t(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),Ge=t(function(e){var t=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=t)}),qe=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},Ue=function(e,t,r){if(qe(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,i){return e.call(t,r,n,i)}}return function(){return e.apply(t,arguments)}},Ke=function(e){return"object"==typeof e?null!==e:"function"==typeof e},Qe=function(e){if(!Ke(e))throw TypeError(e+" is not an object!");return e},Ze=function(e){try{return!!e()}catch(e){return!0}},Je=!Ze(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),Xe=Ye.document,et=Ke(Xe)&&Ke(Xe.createElement),tt=function(e){return et?Xe.createElement(e):{}},rt=!Je&&!Ze(function(){return 7!=Object.defineProperty(tt("div"),"a",{get:function(){return 7}}).a}),nt=function(e,t){if(!Ke(e))return e;var r,n;if(t&&"function"==typeof(r=e.toString)&&!Ke(n=r.call(e)))return n;if("function"==typeof(r=e.valueOf)&&!Ke(n=r.call(e)))return n;if(!t&&"function"==typeof(r=e.toString)&&!Ke(n=r.call(e)))return n;throw TypeError("Can't convert object to primitive value")},it=Object.defineProperty,ot={f:Je?Object.defineProperty:function(e,t,r){if(Qe(e),t=nt(t,!0),Qe(r),rt)try{return it(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},ut=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},at=Je?function(e,t,r){return ot.f(e,t,ut(1,r))}:function(e,t,r){return e[t]=r,e},st=function(e,t,r){var n,i,o,u=e&st.F,a=e&st.G,s=e&st.S,c=e&st.P,l=e&st.B,f=e&st.W,d=a?Ge:Ge[t]||(Ge[t]={}),h=d.prototype,p=a?Ye:s?Ye[t]:(Ye[t]||{}).prototype;a&&(r=t);for(n in r)(i=!u&&p&&void 0!==p[n])&&n in d||(o=i?p[n]:r[n],d[n]=a&&"function"!=typeof p[n]?r[n]:l&&i?Ue(o,Ye):f&&p[n]==o?function(e){var t=function(t,r,n){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,n)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(o):c&&"function"==typeof o?Ue(Function.call,o):o,c&&((d.virtual||(d.virtual={}))[n]=o,e&st.R&&h&&!h[n]&&at(h,n,o)))};st.F=1,st.G=2,st.S=4,st.P=8,st.B=16,st.W=32,st.U=64,st.R=128;var ct=st;ct(ct.S+ct.F*!Je,"Object",{defineProperty:ot.f});var lt=Ge.Object,ft=function(e,t,r){return lt.defineProperty(e,t,r)},dt=t(function(e){e.exports={default:ft,__esModule:!0}}),ht=e(dt),pt=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(dt);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),(0,r.default)(e,i.key,i)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}()})),vt=Math.ceil,yt=Math.floor,gt=function(e){return isNaN(e=+e)?0:(e>0?yt:vt)(e)},mt=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},_t=at,bt={}.hasOwnProperty,wt=function(e,t){return bt.call(e,t)},Et={},kt={}.toString,Ot=function(e){return kt.call(e).slice(8,-1)},Pt=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==Ot(e)?e.split(""):Object(e)},St=function(e){return Pt(mt(e))},jt=Math.min,xt=function(e){return e>0?jt(gt(e),9007199254740991):0},At=Math.max,Tt=Math.min,Lt=function(e,t){return(e=gt(e))<0?At(e+t,0):Tt(e,t)},Mt=Ye["__core-js_shared__"]||(Ye["__core-js_shared__"]={}),Ct=function(e){return Mt[e]||(Mt[e]={})},zt=0,Ft=Math.random(),$t=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++zt+Ft).toString(36))},Nt=Ct("keys"),Dt=function(e){return Nt[e]||(Nt[e]=$t(e))},It=function(e){return function(t,r,n){var i,o=St(t),u=xt(o.length),a=Lt(n,u);if(e&&r!=r){for(;u>a;)if((i=o[a++])!=i)return!0}else for(;u>a;a++)if((e||a in o)&&o[a]===r)return e||a||0;return!e&&-1}}(!1),Rt=Dt("IE_PROTO"),Ht=function(e,t){var r,n=St(e),i=0,o=[];for(r in n)r!=Rt&&wt(n,r)&&o.push(r);for(;t.length>i;)wt(n,r=t[i++])&&(~It(o,r)||o.push(r));return o},Vt="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),Bt=Object.keys||function(e){return Ht(e,Vt)},Wt=Je?Object.defineProperties:function(e,t){Qe(e);for(var r,n=Bt(t),i=n.length,o=0;i>o;)ot.f(e,r=n[o++],t[r]);return e},Yt=Ye.document&&document.documentElement,Gt=Dt("IE_PROTO"),qt=function(){},Ut=function(){var e,t=tt("iframe"),r=Vt.length;for(t.style.display="none",Yt.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),Ut=e.F;r--;)delete Ut.prototype[Vt[r]];return Ut()},Kt=Object.create||function(e,t){var r;return null!==e?(qt.prototype=Qe(e),r=new qt,qt.prototype=null,r[Gt]=e):r=Ut(),void 0===t?r:Wt(r,t)},Qt=t(function(e){var t=Ct("wks"),r=Ye.Symbol,n="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=n&&r[e]||(n?r:$t)("Symbol."+e))}).store=t}),Zt=ot.f,Jt=Qt("toStringTag"),Xt=function(e,t,r){e&&!wt(e=r?e:e.prototype,Jt)&&Zt(e,Jt,{configurable:!0,value:t})},er={};at(er,Qt("iterator"),function(){return this});var tr=function(e,t,r){e.prototype=Kt(er,{next:ut(1,r)}),Xt(e,t+" Iterator")},rr=function(e){return Object(mt(e))},nr=Dt("IE_PROTO"),ir=Object.prototype,or=Object.getPrototypeOf||function(e){return e=rr(e),wt(e,nr)?e[nr]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ir:null},ur=Qt("iterator"),ar=!([].keys&&"next"in[].keys()),sr=function(){return this},cr=function(e,t,r,n,i,o,u){tr(r,t,n);var a,s,c,l=function(e){if(!ar&&e in p)return p[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},f=t+" Iterator",d="values"==i,h=!1,p=e.prototype,v=p[ur]||p["@@iterator"]||i&&p[i],y=v||l(i),g=i?d?l("entries"):y:void 0,m="Array"==t?p.entries||v:v;if(m&&(c=or(m.call(new e)))!==Object.prototype&&Xt(c,f,!0),d&&v&&"values"!==v.name&&(h=!0,y=function(){return v.call(this)}),u&&(ar||h||!p[ur])&&at(p,ur,y),Et[t]=y,Et[f]=sr,i)if(a={values:d?y:l("values"),keys:o?y:l("keys"),entries:g},u)for(s in a)s in p||_t(p,s,a[s]);else ct(ct.P+ct.F*(ar||h),t,a);return a},lr=function(e){return function(t,r){var n,i,o=String(mt(t)),u=gt(r),a=o.length;return u<0||u>=a?e?"":void 0:(n=o.charCodeAt(u))<55296||n>56319||u+1===a||(i=o.charCodeAt(u+1))<56320||i>57343?e?o.charAt(u):n:e?o.slice(u,u+2):i-56320+(n-55296<<10)+65536}}(!0);cr(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=lr(t,r),this._i+=e.length,{value:e,done:!1})});var fr=function(){},dr=function(e,t){return{value:t,done:!!e}};cr(Array,"Array",function(e,t){this._t=St(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,dr(1)):"keys"==t?dr(0,r):"values"==t?dr(0,e[r]):dr(0,[r,e[r]])},"values");Et.Arguments=Et.Array,fr(),fr(),fr();for(var hr=Qt("toStringTag"),pr=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],vr=0;vr<5;vr++){var yr=pr[vr],gr=Ye[yr],mr=gr&&gr.prototype;mr&&!mr[hr]&&at(mr,hr,yr),Et[yr]=Et.Array}var _r={f:Qt},br=_r.f("iterator"),wr=t(function(e){e.exports={default:br,__esModule:!0}}),Er=t(function(e){var t=$t("meta"),r=ot.f,n=0,i=Object.isExtensible||function(){return!0},o=!Ze(function(){return i(Object.preventExtensions({}))}),u=function(e){r(e,t,{value:{i:"O"+ ++n,w:{}}})},a=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!Ke(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!wt(e,t)){if(!i(e))return"F";if(!r)return"E";u(e)}return e[t].i},getWeak:function(e,r){if(!wt(e,t)){if(!i(e))return!0;if(!r)return!1;u(e)}return e[t].w},onFreeze:function(e){return o&&a.NEED&&i(e)&&!wt(e,t)&&u(e),e}}}),kr=ot.f,Or=function(e){var t=Ge.Symbol||(Ge.Symbol={});"_"==e.charAt(0)||e in t||kr(t,e,{value:_r.f(e)})},Pr=function(e,t){for(var r,n=St(e),i=Bt(n),o=i.length,u=0;o>u;)if(n[r=i[u++]]===t)return r},Sr={f:Object.getOwnPropertySymbols},jr={f:{}.propertyIsEnumerable},xr=function(e){var t=Bt(e),r=Sr.f;if(r)for(var n,i=r(e),o=jr.f,u=0;i.length>u;)o.call(e,n=i[u++])&&t.push(n);return t},Ar=Array.isArray||function(e){return"Array"==Ot(e)},Tr=Vt.concat("length","prototype"),Lr={f:Object.getOwnPropertyNames||function(e){return Ht(e,Tr)}},Mr=Lr.f,Cr={}.toString,zr="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Fr=function(e){try{return Mr(e)}catch(e){return zr.slice()}},$r={f:function(e){return zr&&"[object Window]"==Cr.call(e)?Fr(e):Mr(St(e))}},Nr=Object.getOwnPropertyDescriptor,Dr={f:Je?Nr:function(e,t){if(e=St(e),t=nt(t,!0),rt)try{return Nr(e,t)}catch(e){}if(wt(e,t))return ut(!jr.f.call(e,t),e[t])}},Ir=Er.KEY,Rr=Dr.f,Hr=ot.f,Vr=$r.f,Br=Ye.Symbol,Wr=Ye.JSON,Yr=Wr&&Wr.stringify,Gr=Qt("_hidden"),qr=Qt("toPrimitive"),Ur={}.propertyIsEnumerable,Kr=Ct("symbol-registry"),Qr=Ct("symbols"),Zr=Ct("op-symbols"),Jr=Object.prototype,Xr="function"==typeof Br,en=Ye.QObject,tn=!en||!en.prototype||!en.prototype.findChild,rn=Je&&Ze(function(){return 7!=Kt(Hr({},"a",{get:function(){return Hr(this,"a",{value:7}).a}})).a})?function(e,t,r){var n=Rr(Jr,t);n&&delete Jr[t],Hr(e,t,r),n&&e!==Jr&&Hr(Jr,t,n)}:Hr,nn=function(e){var t=Qr[e]=Kt(Br.prototype);return t._k=e,t},on=Xr&&"symbol"==typeof Br.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof Br},un=function(e,t,r){return e===Jr&&un(Zr,t,r),Qe(e),t=nt(t,!0),Qe(r),wt(Qr,t)?(r.enumerable?(wt(e,Gr)&&e[Gr][t]&&(e[Gr][t]=!1),r=Kt(r,{enumerable:ut(0,!1)})):(wt(e,Gr)||Hr(e,Gr,ut(1,{})),e[Gr][t]=!0),rn(e,t,r)):Hr(e,t,r)},an=function(e,t){Qe(e);for(var r,n=xr(t=St(t)),i=0,o=n.length;o>i;)un(e,r=n[i++],t[r]);return e},sn=function(e){var t=Ur.call(this,e=nt(e,!0));return!(this===Jr&&wt(Qr,e)&&!wt(Zr,e))&&(!(t||!wt(this,e)||!wt(Qr,e)||wt(this,Gr)&&this[Gr][e])||t)},cn=function(e,t){if(e=St(e),t=nt(t,!0),e!==Jr||!wt(Qr,t)||wt(Zr,t)){var r=Rr(e,t);return!r||!wt(Qr,t)||wt(e,Gr)&&e[Gr][t]||(r.enumerable=!0),r}},ln=function(e){for(var t,r=Vr(St(e)),n=[],i=0;r.length>i;)wt(Qr,t=r[i++])||t==Gr||t==Ir||n.push(t);return n},fn=function(e){for(var t,r=e===Jr,n=Vr(r?Zr:St(e)),i=[],o=0;n.length>o;)!wt(Qr,t=n[o++])||r&&!wt(Jr,t)||i.push(Qr[t]);return i};Xr||(_t((Br=function(){if(this instanceof Br)throw TypeError("Symbol is not a constructor!");var e=$t(arguments.length>0?arguments[0]:void 0),t=function(r){this===Jr&&t.call(Zr,r),wt(this,Gr)&&wt(this[Gr],e)&&(this[Gr][e]=!1),rn(this,e,ut(1,r))};return Je&&tn&&rn(Jr,e,{configurable:!0,set:t}),nn(e)}).prototype,"toString",function(){return this._k}),Dr.f=cn,ot.f=un,Lr.f=$r.f=ln,jr.f=sn,Sr.f=fn,_r.f=function(e){return nn(Qt(e))}),ct(ct.G+ct.W+ct.F*!Xr,{Symbol:Br});for(var dn="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),hn=0;dn.length>hn;)Qt(dn[hn++]);for(var dn=Bt(Qt.store),hn=0;dn.length>hn;)Or(dn[hn++]);ct(ct.S+ct.F*!Xr,"Symbol",{for:function(e){return wt(Kr,e+="")?Kr[e]:Kr[e]=Br(e)},keyFor:function(e){if(on(e))return Pr(Kr,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){tn=!0},useSimple:function(){tn=!1}}),ct(ct.S+ct.F*!Xr,"Object",{create:function(e,t){return void 0===t?Kt(e):an(Kt(e),t)},defineProperty:un,defineProperties:an,getOwnPropertyDescriptor:cn,getOwnPropertyNames:ln,getOwnPropertySymbols:fn}),Wr&&ct(ct.S+ct.F*(!Xr||Ze(function(){var e=Br();return"[null]"!=Yr([e])||"{}"!=Yr({a:e})||"{}"!=Yr(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!on(e)){for(var t,r,n=[e],i=1;arguments.length>i;)n.push(arguments[i++]);return"function"==typeof(t=n[1])&&(r=t),!r&&Ar(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!on(t))return t}),n[1]=t,Yr.apply(Wr,n)}}}),Br.prototype[qr]||at(Br.prototype,qr,Br.prototype.valueOf),Xt(Br,"Symbol"),Xt(Math,"Math",!0),Xt(Ye.JSON,"JSON",!0),Or("asyncIterator"),Or("observable");var pn=Ge.Symbol,vn=t(function(e){e.exports={default:pn,__esModule:!0}}),yn=t(function(e,t){function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var n=r(wr),i=r(vn),o="function"==typeof i.default&&"symbol"==typeof n.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};t.default="function"==typeof i.default&&"symbol"===o(n.default)?function(e){return void 0===e?"undefined":o(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":o(e)}}),gn=e(yn),mn=function(e,t){var r=(Ge.Object||{})[e]||Object[e],n={};n[e]=t(r),ct(ct.S+ct.F*Ze(function(){r(1)}),"Object",n)};mn("keys",function(){return function(e){return Bt(rr(e))}});var _n=Ge.Object.keys,bn=e(t(function(e){e.exports={default:_n,__esModule:!0}})),wn=Math.floor;ct(ct.S,"Number",{isInteger:function(e){return!Ke(e)&&isFinite(e)&&wn(e)===e}});var En=Ge.Number.isInteger,kn=e(t(function(e){e.exports={default:En,__esModule:!0}})),On="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff",Pn="["+On+"]",Sn=RegExp("^"+Pn+Pn+"*"),jn=RegExp(Pn+Pn+"*$"),xn=function(e,t,r){var n={},i=Ze(function(){return!!On[e]()||"​…"!="​…"[e]()}),o=n[e]=i?t(An):On[e];r&&(n[r]=o),ct(ct.P+ct.F*i,"String",n)},An=xn.trim=function(e,t){return e=String(mt(e)),1&t&&(e=e.replace(Sn,"")),2&t&&(e=e.replace(jn,"")),e},Tn=xn,Ln=Ye.parseFloat,Mn=Tn.trim,Cn=1/Ln(On+"-0")!=-1/0?function(e){var t=Mn(String(e),3),r=Ln(t);return 0===r&&"-"==t.charAt(0)?-0:r}:Ln;ct(ct.S+ct.F*(Number.parseFloat!=Cn),"Number",{parseFloat:Cn});var zn=parseFloat,Fn=e(t(function(e){e.exports={default:zn,__esModule:!0}})),$n=function(){function e(){We(this,e)}return pt(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(_(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(_(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(_(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(_(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(_(t,r))}}]),e}();$n.GLOBAL_TAG="chimee",$n.FORCE_GLOBAL_TAG=!1,$n.ENABLE_ERROR=!0,$n.ENABLE_INFO=!0,$n.ENABLE_WARN=!0,$n.ENABLE_DEBUG=!0,$n.ENABLE_VERBOSE=!0;var Nn=function(e,t,r,n){try{return n?t(Qe(r)[0],r[1]):t(r)}catch(t){var i=e.return;throw void 0!==i&&Qe(i.call(e)),t}},Dn=Qt("iterator"),In=Array.prototype,Rn=function(e){return void 0!==e&&(Et.Array===e||In[Dn]===e)},Hn=function(e,t,r){t in e?ot.f(e,t,ut(0,r)):e[t]=r},Vn=Qt("toStringTag"),Bn="Arguments"==Ot(function(){return arguments}()),Wn=function(e,t){try{return e[t]}catch(e){}},Yn=function(e){var t,r,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=Wn(t=Object(e),Vn))?r:Bn?Ot(t):"Object"==(n=Ot(t))&&"function"==typeof t.callee?"Arguments":n},Gn=Qt("iterator"),qn=Ge.getIteratorMethod=function(e){if(void 0!=e)return e[Gn]||e["@@iterator"]||Et[Yn(e)]},Un=Qt("iterator"),Kn=!1;try{var Qn=[7][Un]();Qn.return=function(){Kn=!0},Array.from(Qn,function(){throw 2})}catch(e){}var Zn=function(e,t){if(!t&&!Kn)return!1;var r=!1;try{var n=[7],i=n[Un]();i.next=function(){return{done:r=!0}},n[Un]=function(){return i},e(n)}catch(e){}return r};ct(ct.S+ct.F*!Zn(function(e){Array.from(e)}),"Array",{from:function(e){var t,r,n,i,o=rr(e),u="function"==typeof this?this:Array,a=arguments.length,s=a>1?arguments[1]:void 0,c=void 0!==s,l=0,f=qn(o);if(c&&(s=Ue(s,a>2?arguments[2]:void 0,2)),void 0==f||u==Array&&Rn(f))for(r=new u(t=xt(o.length));t>l;l++)Hn(r,l,c?s(o[l],l):o[l]);else for(i=f.call(o),r=new u;!(n=i.next()).done;l++)Hn(r,l,c?Nn(i,s,[n.value,l],!0):n.value);return r.length=l,r}});var Jn,Xn,ei,ti=Ge.Array.from,ri=t(function(e){e.exports={default:ti,__esModule:!0}}),ni=e(ri),ii=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(ri);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,r.default)(e)}})),oi=function(e){function t(r,i,u){if(n(r)||o(r)){i=i||(o(r)?{}:[]);for(var a in r)i[a]=t(r[a],i[a],a);return i}return e(r,i,u)}return t}(function(e){return e}),ui=function(e,t,r,n){if(!(e instanceof t)||void 0!==n&&n in e)throw TypeError(r+": incorrect invocation!");return e},ai=t(function(e){var t={},r={},n=e.exports=function(e,n,i,o,u){var a,s,c,l,f=u?function(){return e}:qn(e),d=Ue(i,o,n?2:1),h=0;if("function"!=typeof f)throw TypeError(e+" is not iterable!");if(Rn(f)){for(a=xt(e.length);a>h;h++)if((l=n?d(Qe(s=e[h])[0],s[1]):d(e[h]))===t||l===r)return l}else for(c=f.call(e);!(s=c.next()).done;)if((l=Nn(c,d,s.value,n))===t||l===r)return l};n.BREAK=t,n.RETURN=r}),si=Qt("species"),ci=function(e,t){var r,n=Qe(e).constructor;return void 0===n||void 0==(r=Qe(n)[si])?t:qe(r)},li=function(e,t,r){var n=void 0===r;switch(t.length){case 0:return n?e():e.call(r);case 1:return n?e(t[0]):e.call(r,t[0]);case 2:return n?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return n?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return n?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}return e.apply(r,t)},fi=Ye.process,di=Ye.setImmediate,hi=Ye.clearImmediate,pi=Ye.MessageChannel,vi=0,yi={},gi=function(){var e=+this;if(yi.hasOwnProperty(e)){var t=yi[e];delete yi[e],t()}},mi=function(e){gi.call(e.data)};di&&hi||(di=function(e){for(var t=[],r=1;arguments.length>r;)t.push(arguments[r++]);return yi[++vi]=function(){li("function"==typeof e?e:Function(e),t)},Jn(vi),vi},hi=function(e){delete yi[e]},"process"==Ot(fi)?Jn=function(e){fi.nextTick(Ue(gi,e,1))}:pi?(ei=(Xn=new pi).port2,Xn.port1.onmessage=mi,Jn=Ue(ei.postMessage,ei,1)):Ye.addEventListener&&"function"==typeof postMessage&&!Ye.importScripts?(Jn=function(e){Ye.postMessage(e+"","*")},Ye.addEventListener("message",mi,!1)):Jn="onreadystatechange"in tt("script")?function(e){Yt.appendChild(tt("script")).onreadystatechange=function(){Yt.removeChild(this),gi.call(e)}}:function(e){setTimeout(Ue(gi,e,1),0)});var _i,bi,wi,Ei={set:di,clear:hi},ki=Ei.set,Oi=Ye.MutationObserver||Ye.WebKitMutationObserver,Pi=Ye.process,Si=Ye.Promise,ji="process"==Ot(Pi),xi=function(e,t,r){for(var n in t)r&&e[n]?e[n]=t[n]:at(e,n,t[n]);return e},Ai=Qt("species"),Ti=Ei.set,Li=function(){var e,t,r,n=function(){var n,i;for(ji&&(n=Pi.domain)&&n.exit();e;){i=e.fn,e=e.next;try{i()}catch(n){throw e?r():t=void 0,n}}t=void 0,n&&n.enter()};if(ji)r=function(){Pi.nextTick(n)};else if(Oi){var i=!0,o=document.createTextNode("");new Oi(n).observe(o,{characterData:!0}),r=function(){o.data=i=!i}}else if(Si&&Si.resolve){var u=Si.resolve();r=function(){u.then(n)}}else r=function(){ki.call(Ye,n)};return function(n){var i={fn:n,next:void 0};t&&(t.next=i),e||(e=i,r()),t=i}}(),Mi=Ye.TypeError,Ci=Ye.process,zi=Ye.Promise,Ci=Ye.process,Fi="process"==Yn(Ci),$i=function(){},Ni=!!function(){try{var e=zi.resolve(1),t=(e.constructor={})[Qt("species")]=function(e){e($i,$i)};return(Fi||"function"==typeof PromiseRejectionEvent)&&e.then($i)instanceof t}catch(e){}}(),Di=function(e,t){return e===t||e===zi&&t===wi},Ii=function(e){var t;return!(!Ke(e)||"function"!=typeof(t=e.then))&&t},Ri=function(e){return Di(zi,e)?new Hi(e):new bi(e)},Hi=bi=function(e){var t,r;this.promise=new e(function(e,n){if(void 0!==t||void 0!==r)throw Mi("Bad Promise constructor");t=e,r=n}),this.resolve=qe(t),this.reject=qe(r)},Vi=function(e){try{e()}catch(e){return{error:e}}},Bi=function(e,t){if(!e._n){e._n=!0;var r=e._c;Li(function(){for(var n=e._v,i=1==e._s,o=0;r.length>o;)!function(t){var r,o,u=i?t.ok:t.fail,a=t.resolve,s=t.reject,c=t.domain;try{u?(i||(2==e._h&&Gi(e),e._h=1),!0===u?r=n:(c&&c.enter(),r=u(n),c&&c.exit()),r===t.promise?s(Mi("Promise-chain cycle")):(o=Ii(r))?o.call(r,a,s):a(r)):s(n)}catch(e){s(e)}}(r[o++]);e._c=[],e._n=!1,t&&!e._h&&Wi(e)})}},Wi=function(e){Ti.call(Ye,function(){var t,r,n,i=e._v;if(Yi(e)&&(t=Vi(function(){Fi?Ci.emit("unhandledRejection",i,e):(r=Ye.onunhandledrejection)?r({promise:e,reason:i}):(n=Ye.console)&&n.error&&n.error("Unhandled promise rejection",i)}),e._h=Fi||Yi(e)?2:1),e._a=void 0,t)throw t.error})},Yi=function(e){if(1==e._h)return!1;for(var t,r=e._a||e._c,n=0;r.length>n;)if((t=r[n++]).fail||!Yi(t.promise))return!1;return!0},Gi=function(e){Ti.call(Ye,function(){var t;Fi?Ci.emit("rejectionHandled",e):(t=Ye.onrejectionhandled)&&t({promise:e,reason:e._v})})},qi=function(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),Bi(t,!0))},Ui=function(e){var t,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw Mi("Promise can't be resolved itself");(t=Ii(e))?Li(function(){var n={_w:r,_d:!1};try{t.call(e,Ue(Ui,n,1),Ue(qi,n,1))}catch(e){qi.call(n,e)}}):(r._v=e,r._s=1,Bi(r,!1))}catch(e){qi.call({_w:r,_d:!1},e)}}};Ni||(zi=function(e){ui(this,zi,"Promise","_h"),qe(e),_i.call(this);try{e(Ue(Ui,this,1),Ue(qi,this,1))}catch(e){qi.call(this,e)}},(_i=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=xi(zi.prototype,{then:function(e,t){var r=Ri(ci(this,zi));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=Fi?Ci.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&&Bi(this,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Hi=function(){var e=new _i;this.promise=e,this.resolve=Ue(Ui,e,1),this.reject=Ue(qi,e,1)}),ct(ct.G+ct.W+ct.F*!Ni,{Promise:zi}),Xt(zi,"Promise"),function(e){var t="function"==typeof Ge[e]?Ge[e]:Ye[e];Je&&t&&!t[Ai]&&ot.f(t,Ai,{configurable:!0,get:function(){return this}})}("Promise"),wi=Ge.Promise,ct(ct.S+ct.F*!Ni,"Promise",{reject:function(e){var t=Ri(this);return(0,t.reject)(e),t.promise}}),ct(ct.S+!0*ct.F,"Promise",{resolve:function(e){if(e instanceof zi&&Di(e.constructor,this))return e;var t=Ri(this);return(0,t.resolve)(e),t.promise}}),ct(ct.S+ct.F*!(Ni&&Zn(function(e){zi.all(e).catch($i)})),"Promise",{all:function(e){var t=this,r=Ri(t),n=r.resolve,i=r.reject,o=Vi(function(){var r=[],o=0,u=1;ai(e,!1,function(e){var a=o++,s=!1;r.push(void 0),u++,t.resolve(e).then(function(e){s||(s=!0,r[a]=e,--u||n(r))},i)}),--u||n(r)});return o&&i(o.error),r.promise},race:function(e){var t=this,r=Ri(t),n=r.reject,i=Vi(function(){ai(e,!1,function(e){t.resolve(e).then(r.resolve,n)})});return i&&n(i.error),r.promise}});var Ki=Ge.Promise,Qi=e(t(function(e){e.exports={default:Ki,__esModule:!0}})),Zi=("undefined"!=typeof window&&Object.prototype.toString.call(window),Object.assign),Ji=!Zi||Ze(function(){var e={},t={},r=Symbol(),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(e){t[e]=e}),7!=Zi({},e)[r]||Object.keys(Zi({},t)).join("")!=n})?function(e,t){for(var r=rr(e),n=arguments.length,i=1,o=Sr.f,u=jr.f;n>i;)for(var a,s=Pt(arguments[i++]),c=o?Bt(s).concat(o(s)):Bt(s),l=c.length,f=0;l>f;)u.call(s,a=c[f++])&&(r[a]=s[a]);return r}:Zi;ct(ct.S+ct.F,"Object",{assign:Ji});var Xi=Ge.Object.assign,eo=e(t(function(e){e.exports={default:Xi,__esModule:!0}}));ct(ct.S,"Object",{create:Kt});var to=Ge.Object,ro=function(e,t){return to.create(e,t)},no=t(function(e){e.exports={default:ro,__esModule:!0}}),io=e(no),oo=io(null);oo.count=0;var uo=function(){function e(t,r){var n=this;if(We(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":gn(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=n[e]})}}return pt(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return L(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return M(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return T(this.__target,e,{data:t}),this}}]),e}(),ao=io(null);ao.count=0;(function(){function e(t,r){var n=this;if(We(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":gn(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=n[e]})}}pt(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return F(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return $(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return z(this.__target,e,{data:t}),this}}])})(),"undefined"!=typeof window&&Object.prototype.toString.call(window);var so=document.createElement("div"),co="innerText";"textContent"in so&&(co="textContent");var lo=Array.prototype,fo=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;We(this,e);var i=this;i.selector=t;var o=void 0;t&&t.constructor===NodeList?o=N(t):n(t)?o=t:l(t)?0===t.indexOf("<")?(so.innerHTML=t,o=K("*",so,!0)):o=K(t,r,!0):o=[t],eo(i,o),i.length=o.length}return pt(e,[{key:"each",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return lo.forEach.apply(this,t),this}},{key:"push",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return lo.push.apply(this,t),this}},{key:"splice",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return J(lo.splice.apply(this,t))}},{key:"find",value:function(e){var t=[];this.each(function(r){t=t.concat(K(e,r,!0))});var r=J(t);return r.parent=this,r.selector=e,r}},{key:"append",value:function(e){var t=J(e),r=this[0];return t.each(function(e){return r.appendChild(e)}),this}},{key:"appendTo",value:function(e){return J(e).append(this),this}},{key:"text",value:function(e){return 0===arguments.length?this[0][co]:this.each(function(t){t[co]=e})}},{key:"html",value:function(e){return 0===arguments.length?this[0].innerHTML:this.each(function(t){t.innerHTML=e})}},{key:"attr",value:function(e,t){return 1===arguments.length?D(this[0],e):this.each(function(r){return I(r,e,t)})}},{key:"data",value:function(e,t){return 0===arguments.length?this[0].dataset||{}:1===arguments.length?(this[0].dataset||{})[e]:this.each(function(r){(r.dataset||(r.dataset={}))[e]=t})}},{key:"css",value:function(e,t){return 1!==arguments.length||o(e)?this.each(function(r){return U(r,e,t)}):q(this[0],e)}},{key:"addClass",value:function(e){return this.each(function(t){return R(t,e)})}},{key:"removeClass",value:function(e){return this.each(function(t){return H(t,e)})}},{key:"hasClass",value:function(e){return V(this[0],e)}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(i){return W(i,e,t,r,n)})}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(i){return B(i,e,t,r,n)})}},{key:"delegate",value:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(i){return Y(i,e,t,r,n)})}},{key:"undelegate",value:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(i){return G(i,e,t,r,n)})}},{key:"remove",value:function(){return this.each(function(e){return Q(e)})}}]),e}();mn("getPrototypeOf",function(){return function(e){return or(rr(e))}});var ho=Ge.Object.getPrototypeOf,po=e(t(function(e){e.exports={default:ho,__esModule:!0}})),vo=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(yn);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,r.default)(t))&&"function"!=typeof t?e:t}})),yo=function(e,t){if(Qe(e),!Ke(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},go={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=Ue(Function.call,Dr.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return yo(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:yo};ct(ct.S,"Object",{setPrototypeOf:go.set});var mo=Ge.Object.setPrototypeOf,_o=t(function(e){e.exports={default:mo,__esModule:!0}}),bo=e(t(function(e,t){function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var n=r(_o),i=r(no),o=r(yn);t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,o.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(n.default?(0,n.default)(e,t):e.__proto__=t)}})),wo=Dr.f;mn("getOwnPropertyDescriptor",function(){return function(e,t){return wo(St(e),t)}});var Eo=Ge.Object,ko=function(e,t){return Eo.getOwnPropertyDescriptor(e,t)},Oo=e(t(function(e){e.exports={default:ko,__esModule:!0}})),Po={type:"vod",autoPlay:!1,box:"native",lockInternalProperty:!1,debug:!0},So=function(e){function t(e,r){We(this,t);var n=vo(this,(t.__proto__||po(t)).call(this));return n.video=e,n.box="Native",n.config=Po,w(n.config,r),n.bindEvents(),n}return bo(t,uo),pt(t,[{key:"internalPropertyHandle",value:function(){if(Oo){var e=this,t=Oo(HTMLMediaElement.prototype,"currentTime");Object.defineProperty(this.video,"currentTime",{get:function(){return t.get.call(e.video)},set:function(r){if(e.currentTimeLock)return t.set.call(e.video,r);throw new Error("can not set currentTime by youself")}})}}},{key:"bindEvents",value:function(){var e=this;this.video&&this.config.lockInternalProperty&&this.video.addEventListener("canplay",function(){e.internalPropertyHandle()})}},{key:"load",value:function(e){this.config.src=e||this.config.src,this.video.src=this.config.src}},{key:"unload",value:function(){this.video.src="",this.video.removeAttribute("src")}},{key:"destroy",value:function(){this.video&&this.unload()}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}},{key:"attachMedia",value:function(){}},{key:"seek",value:function(e){this.currentTimeLock=!0,this.video.currentTime=e,this.currentTimeLock=!1}}]),t}(),jo=function(e){function t(e,r){We(this,t);var n=vo(this,(t.__proto__||po(t)).call(this));return n.tag="kernel",n.config=r,n.video=e,n.videokernel=n.selectKernel(),n.bindEvents(n.videokernel,n.video),n.timer=null,n}return bo(t,uo),pt(t,[{key:"bindEvents",value:function(e,t){var r=this;e&&(e.on("mediaInfo",function(e){r.emit("mediaInfo",e)}),t.addEventListener("canplay",function(){clearTimeout(r.timer),r.timer=null}))}},{key:"selectKernel",value:function(){var e=this.config,t=e.box?e.box:-1!==e.src.indexOf(".flv")?"flv":-1!==e.src.indexOf(".m3u8")?"hls":"native";return"native"===t?new So(this.video,e):"flv"===t?new e.preset[t](this.video,e):"hls"===t?new e.preset[t](this.video,e):($n.error(this.tag,"not mactch any player, please check your config"),null)}},{key:"attachMedia",value:function(){this.videokernel?this.videokernel.attachMedia():$n.error(this.tag,"video player is not already, must init player")}},{key:"load",value:function(e){var t=this;this.config.src=e||this.config.src,this.videokernel&&this.config.src?(this.videokernel.load(e),this.timer||(this.timer=setTimeout(function(){t.timer=null,t.pause(),t.refresh()},1e3))):$n.error(this.tag,"video player is not already, must init player")}},{key:"destroy",value:function(){this.videokernel?this.videokernel.destroy():$n.error(this.tag,"player is not exit")}},{key:"play",value:function(){this.videokernel?this.videokernel.play():$n.error(this.tag,"video player is not already, must init player")}},{key:"pause",value:function(){this.videokernel&&this.config.src?this.videokernel.pause():$n.error(this.tag,"video player is not already, must init player")}},{key:"seek",value:function(e){if(u(e))return this.videokernel.seek(e);$n.error(this.tag,"seek params must be a number")}},{key:"refresh",value:function(){this.videokernel.refresh()}},{key:"currentTime",get:function(){return this.videokernel?this.video.currentTime:0}},{key:"duration",get:function(){return this.video.duration}},{key:"volume",get:function(){return this.video.volume},set:function(e){this.video.volume=e}},{key:"muted",get:function(){return this.video.muted},set:function(e){this.video.muted=e}},{key:"buffered",get:function(){return this.video.buffered}}]),t}(),xo=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","interruptbegin","interruptend","loadeddata","loadedmetadata","loadstart","mozaudioavailable","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting"],Ao=["buffered","currentSrc","duration","error","ended","networkState","paused","readyState","seekable","sinkId","controlsList","tabIndex","dataset","offsetHeight","offsetLeft","offsetParent","offsetTop","offsetWidth"],To=["beforeinput","blur","click","compositionend","compositionstart","compositionupdate","dblclick","focus","focusin","focusout","input","keydown","keypress","keyup","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","resize","scroll","select","wheel","fullscreenchange","webkitfullscreenchange","mozfullscreenchange","msfullscreenchange","contextmenu"],Lo=["silentLoad","fullScreen"],Mo=["play","pause","seek"],Co=["load"],zo=["focus","fullScreen","requestFullScreen","exitFullScreen"],Fo=["canPlayType","captureStream","setSinkId"],$o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},No=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Do=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),Io=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},Ro=function e(t,r,n){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,r);if(void 0===i){var o=Object.getPrototypeOf(t);return null===o?void 0:e(o,r,n)}if("value"in i)return i.value;var u=i.get;if(void 0!==u)return u.call(n)},Ho=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},Vo=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},Bo=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},Wo=/^(before|after|_)/,Yo=function(){function e(t){No(this,e),this.events={},this.onceMap={},this.__dispatcher=t}return Do(e,[{key:"on",value:function(e,t,r){var n=this._getEventStage(t),i=n.stage,o=n.key;this._addEvent([o,i,e],r)}},{key:"off",value:function(e,t,r){var n=this._getEventStage(t),o=n.stage,u=[n.key,o,e];if(!this._removeEvent(u,r)){var a=this._getHandlerFromOnceMap(u,r);i(a)&&this._removeEvent(u,a)&&this._removeFromOnceMap(u,r,a)}}},{key:"once",value:function(e,t,r){var n=this._getEventStage(t),i=n.stage,o=this,u=[n.key,i,e],a=function e(){O(r,this).apply(void 0,arguments),o._removeEvent(u,e),o._removeFromOnceMap(u,r,e)};this._addEvent(u,a),this._addToOnceMap(u,r,a)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];if(!e.match(Wo)){var o=this.events[e];if(c(o))return Lo.indexOf(e)>-1?Promise.resolve():this._eventProcessor.apply(this,[e,{sync:!1}].concat(Bo(n)));var u=this._getEventQueue(o.before,this.__dispatcher.order);return j.apply(void 0,[u].concat(Bo(n))).then(function(){if(!(Lo.indexOf(e)>-1))return t._eventProcessor.apply(t,[e,{sync:!1}].concat(Bo(n)))}).catch(function(e){return m(e)&&t.__dispatcher.throwError(e),Promise.reject(e)})}$n.warn("bus","Secondary Event could not be emit")}},{key:"emitSync",value:function(e){if(e.match(Wo))return $n.warn("bus","Secondary Event could not be emit"),!1;for(var t=this.events[e],r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];if(c(t))return Lo.indexOf(e)>-1||this._eventProcessor.apply(this,[e,{sync:!0}].concat(Bo(n)));var o=this._getEventQueue(t.before,this.__dispatcher.order);return x.apply(void 0,[o].concat(Bo(n)))&&(Lo.indexOf(e)>-1||this._eventProcessor.apply(this,[e,{sync:!0}].concat(Bo(n))))}},{key:"trigger",value:function(e){for(var t=this,r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];if(!e.match(Wo)){var o=this.events[e];if(c(o))return Promise.resolve(!0);var u=this._getEventQueue(o.main,this.__dispatcher.order);return j.apply(void 0,[u].concat(Bo(n))).then(function(){var e=t._getEventQueue(o.after,t.__dispatcher.order);return j.apply(void 0,[e].concat(Bo(n)))}).then(function(){return t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(Bo(n)))}).catch(function(r){return m(r)&&t.__dispatcher.throwError(r),t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(Bo(n)))})}$n.warn("bus","Secondary Event could not be emit")}},{key:"triggerSync",value:function(e){if(e.match(Wo))return $n.warn("bus","Secondary Event could not be emit"),!1;var t=this.events[e];if(c(t))return!0;for(var r=this._getEventQueue(t.main,this.__dispatcher.order),n=this._getEventQueue(t.after,this.__dispatcher.order),i=arguments.length,o=Array(i>1?i-1:0),u=1;u<i;u++)o[u-1]=arguments[u];var a=x.apply(void 0,[r].concat(Bo(o)))&&x.apply(void 0,[n].concat(Bo(o)));return this._runSideEffectEvent.apply(this,[e,this.__dispatcher.order].concat(Bo(o))),a}},{key:"destroy",value:function(){delete this.events,delete this.__dispatcher}},{key:"_addEvent",value:function(e,t){var r=(e=b(e)).pop(),n=e.reduce(function(e,t){return e[t]=e[t]||{},e[t]},this.events);n[r]=n[r]||[],n[r].push(t)}},{key:"_removeEvent",value:function(e,t){for(var r=(e=b(e)).pop(),n=this.events,i=0,o=e.length;i<o;i++){var u=n[e[i]];if(c(u))return;n=u}var a=n[r]||[],s=a.indexOf(t),l=s>-1;return l&&a.splice(s,1),a.length<1&&delete n[r],l}},{key:"_addToOnceMap",value:function(e,t,r){var n=e.join("-"),i=this.onceMap[n]=this.onceMap[n]||new Map;i.has(t)||i.set(t,[]),i.get(t).push(r)}},{key:"_removeFromOnceMap",value:function(e,t,r){var n=e.join("-"),i=this.onceMap[n],o=i.get(t),u=o.indexOf(r);o.splice(u,1),c(o)&&i.delete(t)}},{key:"_getHandlerFromOnceMap",value:function(e,t){var n=e.join("-"),i=this.onceMap[n];if(!r(i)&&i.has(t))return i.get(t)[0]}},{key:"_getEventStage",value:function(e){var t=e.match(Wo),r=t&&t[0]||"main";return t&&(e=E(e.replace(Wo,""))),{stage:r,key:e}}},{key:"_getEventQueue",value:function(e,t){var r=this;return t=n(t)?t.concat(["_vm"]):["_vm"],c(e)?[]:t.reduce(function(t,i){return c(e[i])||!n(e[i])||!r.__dispatcher.plugins[i]&&"_vm"!==i?t:t.concat(e[i].map(function(e){return O(e,r.__dispatcher.plugins[i]||r.__dispatcher.vm)}))},[])}},{key:"_eventProcessor",value:function(e,t){for(var r=t.sync,n=Mo.indexOf(e)>-1,i=zo.indexOf(e)>-1,o=Co.indexOf(e)>-1,u=arguments.length,a=Array(u>2?u-2:0),s=2;s<u;s++)a[s-2]=arguments[s];if(n||i||o){if(o){var c;(c=this.__dispatcher)[e].apply(c,Bo(a))}else{var l;(l=this.__dispatcher[n?"kernel":"dom"])[e].apply(l,Bo(a))}if(xo.indexOf(e)>-1||To.indexOf(e)>-1)return!0}return this[r?"triggerSync":"trigger"].apply(this,[e].concat(Bo(a)))}},{key:"_runSideEffectEvent",value:function(e,t){for(var r=arguments.length,n=Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];var o=this.events[e];if(!c(o))return this._getEventQueue(o._,t).forEach(function(e){return e.apply(void 0,Bo(n))}),!0}}]),e}(),Go=Ye.Reflect,qo=Go&&Go.ownKeys||function(e){var t=Lr.f(Qe(e)),r=Sr.f;return r?t.concat(r(e)):t};ct(ct.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,r=St(e),n=Dr.f,i=qo(r),o={},u=0;i.length>u;)Hn(o,t=i[u++],n(r,t));return o}});var Uo=Ge.Object.getOwnPropertyDescriptors,Ko=e(t(function(e){e.exports={default:Uo,__esModule:!0}})),Qo=Ge.Object.getOwnPropertySymbols,Zo=e(t(function(e){e.exports={default:Qo,__esModule:!0}}));mn("getOwnPropertyNames",function(){return $r.f});var Jo=Ge.Object,Xo=function(e){return Jo.getOwnPropertyNames(e)},eu=e(t(function(e){e.exports={default:Xo,__esModule:!0}})),tu=Qt("iterator"),ru=Ge.isIterable=function(e){var t=Object(e);return void 0!==t[tu]||"@@iterator"in t||Et.hasOwnProperty(Yn(t))},nu=t(function(e){e.exports={default:ru,__esModule:!0}}),iu=Ge.getIterator=function(e){var t=qn(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return Qe(t.call(e))},ou=t(function(e){e.exports={default:iu,__esModule:!0}}),uu=e(t(function(e,t){function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var n=r(nu),i=r(ou);t.default=function(){function e(e,t){var r=[],n=!0,o=!1,u=void 0;try{for(var a,s=(0,i.default)(e);!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){o=!0,u=e}finally{try{!n&&s.return&&s.return()}finally{if(o)throw u}}return r}return function(t,r){if(Array.isArray(t))return t;if((0,n.default)(Object(t)))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()})),au=Qt("species"),su=function(e){var t;return Ar(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!Ar(t.prototype)||(t=void 0),Ke(t)&&null===(t=t[au])&&(t=void 0)),void 0===t?Array:t},cu=function(e,t){return new(su(e))(t)},lu=function(e,t){var r=1==e,n=2==e,i=3==e,o=4==e,u=6==e,a=5==e||u,s=t||cu;return function(t,c,l){for(var f,d,h=rr(t),p=Pt(h),v=Ue(c,l,3),y=xt(p.length),g=0,m=r?s(t,y):n?s(t,0):void 0;y>g;g++)if((a||g in p)&&(f=p[g],d=v(f,g,h),e))if(r)m[g]=d;else if(d)switch(e){case 3:return!0;case 5:return f;case 6:return g;case 2:m.push(f)}else if(o)return!1;return u?-1:i||o?o:m}},fu=Er.getWeak,du=lu(5),hu=lu(6),pu=0,vu=function(e){return e._l||(e._l=new yu)},yu=function(){this.a=[]},gu=function(e,t){return du(e.a,function(e){return e[0]===t})};yu.prototype={get:function(e){var t=gu(this,e);if(t)return t[1]},has:function(e){return!!gu(this,e)},set:function(e,t){var r=gu(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=hu(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}};var mu={getConstructor:function(e,t,r,n){var i=e(function(e,o){ui(e,i,t,"_i"),e._i=pu++,e._l=void 0,void 0!=o&&ai(o,r,e[n],e)});return xi(i.prototype,{delete:function(e){if(!Ke(e))return!1;var t=fu(e);return!0===t?vu(this).delete(e):t&&wt(t,this._i)&&delete t[this._i]},has:function(e){if(!Ke(e))return!1;var t=fu(e);return!0===t?vu(this).has(e):t&&wt(t,this._i)}}),i},def:function(e,t,r){var n=fu(Qe(t),!0);return!0===n?vu(e).set(t,r):n[e._i]=r,e},ufstore:vu},_u=ot.f,bu=lu(0),wu=function(e,t,r,n,i,o){var u=Ye[e],a=u,s=i?"set":"add",c=a&&a.prototype,l={};return Je&&"function"==typeof a&&(o||c.forEach&&!Ze(function(){(new a).entries().next()}))?(a=t(function(t,r){ui(t,a,e,"_c"),t._c=new u,void 0!=r&&ai(r,i,t[s],t)}),bu("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in c&&(!o||"clear"!=e)&&at(a.prototype,e,function(r,n){if(ui(this,a,e),!t&&o&&!Ke(r))return"get"==e&&void 0;var i=this._c[e](0===r?0:r,n);return t?this:i})}),"size"in c&&_u(a.prototype,"size",{get:function(){return this._c.size}})):(a=n.getConstructor(t,e,i,s),xi(a.prototype,r),Er.NEED=!0),Xt(a,e),l[e]=a,ct(ct.G+ct.W+ct.F,l),o||n.setStrong(a,e,i),a},Eu=(t(function(e){var t,r=lu(0),n=Er.getWeak,i=Object.isExtensible,o=mu.ufstore,u={},a=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},s={get:function(e){if(Ke(e)){var t=n(e);return!0===t?o(this).get(e):t?t[this._i]:void 0}},set:function(e,t){return mu.def(this,e,t)}},c=e.exports=wu("WeakMap",a,s,mu,!0,!0);7!=(new c).set((Object.freeze||Object)(u),7).get(u)&&(t=mu.getConstructor(a),Ji(t.prototype,s),Er.NEED=!0,r(["delete","has","get","set"],function(e){var r=c.prototype,n=r[e];_t(r,e,function(r,o){if(Ke(r)&&!i(r)){this._f||(this._f=new t);var u=this._f[e](r,o);return"set"==e?this:u}return n.call(this,r,o)})}))}),Ge.WeakMap),ku=e(t(function(e){e.exports={default:Eu,__esModule:!0}})),Ou=e(t(function(e,t){t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(dt);t.default=function(e,t,n){return t in e?(0,r.default)(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}})),Pu=Er.onFreeze;mn("preventExtensions",function(e){return function(t){return e&&Ke(t)?e(Pu(t)):t}});var Su,ju,xu,Au,Tu,Lu,Mu,Cu,zu,Fu,$u,Nu,Du,Iu,Ru,Hu,Vu,Bu,Wu,Yu,Gu,qu,Uu,Ku,Qu,Zu,Ju,Xu,ea,ta,ra,na,ia,oa,ua,aa,sa,ca,la,fa,da,ha,pa,va,ya,ga,ma,_a,ba,wa,Ea,ka,Oa,Pa,Sa,ja,xa,Aa,Ta,La=Ge.Object.preventExtensions,Ma=e(t(function(e){e.exports={default:La,__esModule:!0}})),Ca=Oo,za=function(){var e=eu,t=Zo;return i(t)?function(r){return ni(e(r).concat(t(r)))}:e}(),Fa=i(Ko)?Ko:function(e){return za(e).reduce(function(t,r){return t[r]=Ca(e,r),t},{})},$a=Oo,Na=ht,Da=ht,Ia=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=t.requirement,u=t.customArgs,a=void 0!==u&&u;return function(){for(var t=arguments.length,u=Array(t>1?t-1:0),s=1;s<t;s++)u[s-1]=arguments[s];var c=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},l=c.exclude,f=void 0===l?[]:l,d=c.include,p=void 0===d?[]:d,v=c.construct,y=void 0!==v&&v,g=c.self,m=void 0!==g&&g;if(!n(f))throw new TypeError("options.exclude must be an array");if(!n(p))throw new TypeError("options.include must be an array");return function(t){var n=i(t);if(!m&&!n)throw new TypeError("@"+e.name+"Class can only be used on class");if(m&&h(t))throw new TypeError("@"+e.name+"Class must be used on non-primitive type value in 'self' mode");var s=m?t:t.prototype;if(r(s))throw new Error("The prototype of the "+t.name+" is empty, please check it");var c=Fa(s);za(s).concat(p).forEach(function(t){var r=c[t];"constructor"===t&&!y||m&&n&&["name","length","prototype"].indexOf(t)>-1||f.indexOf(t)>-1||i(o)&&!1===o(s,t,r,{self:m})||Da(s,t,(a?e.apply(void 0,ii(u)):e)(s,t,r))})}}}(he,{requirement:function(e,t,r){return te(r)&&i(r.value)}}),Ra=void 0,Ha=ht,Va=Oo,Ba=ht,Wa=ht,Ya=ht,Ga=Oo,qa=["push","pop","unshift","shift","splice","sort","reverse"],Ua=Ma,Ka={src:[function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=l(t[0])?t.shift():"";return t.unshift(function(e){return l(e)?e:n}),ae({set:t,get:t})}(),ae({set:function(e){return this.dispatcher.readySync&&this.autoload&&e!==this.src&&(this.needToLoadSrc=!0),e}}),ae({set:function(e){return this.needToLoadSrc&&(this.needToLoadSrc=!1,this.dispatcher.bus.emit("load",e)),e}},{preSet:!1})],autoload:ke(),autoplay:[ke(),Te("autoplay")],controls:[ke(),Te("controls")],width:[Ce("width")],height:[Ce("height")],crossOrigin:[ae({set:Ae}),Le({set:"crossorigin",get:"crossOrigin"})],loop:[ke(),Te("loop")],defaultMuted:[ke(),Le({get:"defaultMuted",set:"muted",isBoolean:!0})],muted:[ke(),Te("muted")],preload:[ae({set:Ae}),Le("preload")],poster:[ae({set:Ae}),Le("poster")],playsInline:[ae({get:function(e){var t=this.dom.videoElement.playsInline;return this.dispatcher.videoConfigReady&&this.inited?void 0===t?e:t:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;this.dom.videoElement.playsInline=e;var t=e?"":void 0;return this.dom.setAttr("video","playsinline",t),this.dom.setAttr("video","webkit-playsinline",t),this.dom.setAttr("video","x5-video-player-type",e?"h5":void 0),e}}),ke()],x5VideoPlayerFullScreen:[ae({set:function(e){return!!e},get:function(e){return!!e}}),Me("x5-video-player-fullscreen",!0)],x5VideoOrientation:[ae({set:Ae}),Me("x5-video-orientation")],xWebkitAirplay:[ae({set:function(e){return!!e},get:function(e){return!!e}}),Me("x-webkit-airplay",!0)],playbackRate:[Oe(1),Te("playbackRate")],defaultPlaybackRate:[Te("defaultPlaybackRate"),Oe(1)],disableRemotePlayback:[ke(),Te("disableRemotePlayback")],volume:[Oe(1),Te("volume")]},Qa=(Su=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=!!f(t[0])&&t.shift();return t.unshift(function(e){return f(e)?e:n}),ce.apply(void 0,t)}(),ju=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=l(t[0])?t.shift():"";return t.unshift(function(e){return l(e)?e:n}),ce.apply(void 0,t)}(function(e){return e.toLocaleLowerCase()}),xu=function(){function e(t,r){No(this,e),je(this,"needToLoadSrc",Au,this),je(this,"changeWatchable",Tu,this),je(this,"inited",Lu,this),this.src="",je(this,"isLive",Mu,this),je(this,"box",Cu,this),this.preset={},this.autoload=!0,this.autoplay=!1,this.controls=!1,this.width=void 0,this.height=void 0,this.crossOrigin=void 0,this.loop=!1,this.defaultMuted=!1,this.muted=!1,this.preload="auto",this.poster=void 0,this.playsInline=!1,this.x5VideoPlayerFullScreen=!1,this.x5VideoOrientation=void 0,this.xWebkitAirplay=!1,this.playbackRate=1,this.defaultPlaybackRate=1,this.disableRemotePlayback=!1,this.volume=1,je(this,"_kernelProperty",zu,this),je(this,"_realDomAttr",Fu,this),ge(this,Ka,{self:!0}),Object.defineProperty(this,"dispatcher",{value:t,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(this,"dom",{value:t.dom,enumerable:!1,writable:!1,configurable:!1}),w(this,r)}return Do(e,[{key:"lockKernelProperty",value:function(){ge(this,{isLive:ve,box:ve,preset:ve},{self:!0})}}]),Do(e,[{key:"init",value:function(){var e=this;this._realDomAttr.forEach(function(t){e[t]=e[t]}),this.inited=!0}}]),e}(),Au=xe(xu.prototype,"needToLoadSrc",[ye],{enumerable:!0,initializer:function(){return!1}}),Tu=xe(xu.prototype,"changeWatchable",[ye],{enumerable:!0,initializer:function(){return!0}}),Lu=xe(xu.prototype,"inited",[ye],{enumerable:!0,initializer:function(){return!1}}),Mu=xe(xu.prototype,"isLive",[Su,Ee],{enumerable:!0,initializer:function(){return!1}}),Cu=xe(xu.prototype,"box",[ju,Ee],{enumerable:!0,initializer:function(){return""}}),zu=xe(xu.prototype,"_kernelProperty",[pe],{enumerable:!0,initializer:function(){return["isLive","box","preset"]}}),Fu=xe(xu.prototype,"_realDomAttr",[pe],{enumerable:!0,initializer:function(){return["src","controls","width","height","crossOrigin","loop","muted","preload","poster","autoplay","playsInline","x5VideoPlayerFullScreen","x5VideoOrientation","xWebkitAirplay","playbackRate","defaultPlaybackRate","autoload","disableRemotePlayback","defaultMuted","volume"]}}),xu),Za=($u=Ia(),Nu=fe("silentLoad"),Du=fe("fullScreen"),Iu=fe("emit"),Ru=fe("emitSync"),Hu=fe("on"),Vu=fe("addEventListener"),Bu=se(Pe),Wu=fe("off"),Yu=fe("removeEventListener"),Gu=se(Pe),qu=fe("once"),Uu=se(Pe),Ku=fe("css"),Qu=se(Se),Zu=fe("attr"),Ju=se(Se),$u((ea=function(){function e(){No(this,e),this.__events={},this.__unwatchHandlers=[]}return Do(e,[{key:"__wrapAsVideo",value:function(e){var t=this;Ao.forEach(function(e){Object.defineProperty(t,e,{get:function(){return this.__dispatcher.dom.videoElement[e]},set:void 0,configurable:!1,enumerable:!1})}),Fo.forEach(function(e){Object.defineProperty(t,e,{get:function(){var t=this.__dispatcher.dom.videoElement;return O(t[e],t)},set:void 0,configurable:!1,enumerable:!1})}),ge(this,e._realDomAttr.concat(e._kernelProperty).reduce(function(t,r){return t[r]=[ae({get:function(){return e[r]},set:function(t){return e[r]=t,t}}),ye],t},{}),{self:!0}),Mo.forEach(function(e){Object.defineProperty(t,e,{value:function(){for(var t=this,r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];return new Promise(function(r,i){var o;t.__dispatcher.bus.once(t.__id,"_"+e,r),(o=t.__dispatcher.bus)[/^(seek)$/.test(e)?"emitSync":"emit"].apply(o,[e].concat(Bo(n)))})},configurable:!0,enumerable:!1,writable:!0})}),zo.forEach(function(e){"fullScreen"!==e&&Object.defineProperty(t,e,{value:function(){var t;return(t=this.__dispatcher.dom)[e].apply(t,arguments)},configurable:!0,enumerable:!1,writable:!0})})}},{key:"$watch",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=i.deep,u=i.diff,a=void 0===u||u,s=i.other,c=i.proxy,f=void 0!==c&&c;if(!l(e)&&!n(e))throw new TypeError("$watch only accept string and Array<string> as key to find the target to spy on, but not "+e+", whose type is "+(void 0===e?"undefined":$o(e)));var d=!0,h=function e(){d=!1;var t=r.__unwatchHandlers.indexOf(e);t>-1&&r.__unwatchHandlers.splice(t,1)},p=l(e)?e.split("."):e,v=p.pop(),y=this.__dispatcher.videoConfig;return ge(0===p.length&&!s&&y._realDomAttr.indexOf(v)>-1?y:["isFullScreen","fullScreenElement"].indexOf(v)>-1?this.__dispatcher.dom:P(s||this,p,{throwError:!0}),Io({},v,be(function(){!d||this instanceof Qa&&!this.dispatcher.changeWatchable||O(t,this).apply(void 0,arguments)},{deep:o,diff:a,proxy:f})),{self:!0}),this.__unwatchHandlers.push(h),h}},{key:"$set",value:function(e,t,r){if(!o(e)&&!n(e))throw new TypeError("$set only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":$o(e)));if(!i(e.__set))return $n.warn("chimee",JSON.stringify(e)+" has not been deep watch. There is no need to use $set."),void(e[t]=r);e.__set(t,r)}},{key:"$del",value:function(e,t){if(!o(e)&&!n(e))throw new TypeError("$del only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":$o(e)));if(!i(e.__del))return $n.warn("chimee",JSON.stringify(e)+" has not been deep watch. There is no need to use $del."),void delete e[t];e.__del(t)}},{key:"load",value:function(){for(var e=this,t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];return new Promise(function(t,n){var i;e.__dispatcher.bus.once(e.__id,"_load",t),(i=e.__dispatcher.bus).emit.apply(i,["load"].concat(r))})}},{key:"$silentLoad",value:function(){for(var e=this,t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];return this.__dispatcher.bus.emit("silentLoad").then(function(){var t;return(t=e.__dispatcher).silentLoad.apply(t,r)}).then(function(t){e.__dispatcher.bus.trigger("silentLoad",t)})}},{key:"$fullScreen",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"container";if(!this.__dispatcher.bus.emitSync("fullScreen",e,t))return!1;var r=this.__dispatcher.dom.fullScreen(e,t);return this.__dispatcher.bus.triggerSync("fullScreen",e,t),r}},{key:"$emit",value:function(e){var t;if(!l(e))throw new TypeError("emit key parameter must be String");To.indexOf(e.replace(/^\w_/,""))>-1&&$n.warn("plugin","You are try to emit "+e+" event. As emit is wrapped in Promise. It make you can't use event.preventDefault and event.stopPropagation. So we advice you to use emitSync");for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];(t=this.__dispatcher.bus).emit.apply(t,[e].concat(Bo(n)))}},{key:"$emitSync",value:function(e){var t;if(!l(e))throw new TypeError("emitSync key parameter must be String");for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return(t=this.__dispatcher.bus).emitSync.apply(t,[e].concat(Bo(n)))}},{key:"$on",value:function(e,t){this.__dispatcher.bus.on(this.__id,e,t),this.__addEvents(e,t)}},{key:"$off",value:function(e,t){this.__dispatcher.bus.off(this.__id,e,t),this.__removeEvents(e,t)}},{key:"$once",value:function(e,t){var r=this,n=function n(){O(t,this).apply(void 0,arguments),r.__removeEvents(e,n)};r.__addEvents(e,n),this.__dispatcher.bus.once(this.__id,e,n)}},{key:"$css",value:function(e){for(var t,r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return(t=this.__dispatcher.dom)[e+"Style"].apply(t,n)}},{key:"$attr",value:function(e){for(var t,r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];if("set"===e&&/video/.test(n[0])){if(!this.__dispatcher.videoConfigReady)return $n.warn("chimee",this.__id+" is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger"),n[2];if(this.__dispatcher.videoConfig._realDomAttr.indexOf(n[1])>-1){var o=n[1],u=n[2];return this.__dispatcher.videoConfig[o]=u,u}}return(t=this.__dispatcher.dom)[e+"Attr"].apply(t,n)}},{key:"__addEvents",value:function(e,t){this.__events[e]=this.__events[e]||[],this.__events[e].push(t)}},{key:"__removeEvents",value:function(e,t){if(!c(this.__events[e])){var r=this.__events[e].indexOf(t);r<0||(this.__events[e].splice(r,1),c(this.__events[e])&&delete this.__events[e])}}},{key:"__destroy",value:function(){var e=this;this.__unwatchHandlers.forEach(function(e){return e()}),Object.keys(this.__events).forEach(function(t){n(e.__events[t])&&e.__events[t].forEach(function(r){return e.$off(t,r)})}),delete this.__events}},{key:"currentTime",get:function(){return this.__dispatcher.kernel.currentTime},set:function(e){this.__dispatcher.bus.emitSync("seek",e)}},{key:"$plugins",get:function(){return this.__dispatcher.plugins}},{key:"$pluginOrder",get:function(){return this.__dispatcher.order}},{key:"$wrapper",get:function(){return Fe("wrapper"),this.__dispatcher.dom.wrapper}},{key:"$container",get:function(){return Fe("container"),this.__dispatcher.dom.container}},{key:"$video",get:function(){return Fe("video"),this.__dispatcher.dom.videoElement}},{key:"isFullScreen",get:function(){return this.__dispatcher.dom.isFullScreen}},{key:"fullScreenElement",get:function(){return this.__dispatcher.dom.fullScreenElement}}]),e}(),ze(ea.prototype,"$silentLoad",[Nu],Object.getOwnPropertyDescriptor(ea.prototype,"$silentLoad"),ea.prototype),ze(ea.prototype,"$fullScreen",[Du],Object.getOwnPropertyDescriptor(ea.prototype,"$fullScreen"),ea.prototype),ze(ea.prototype,"$emit",[Iu],Object.getOwnPropertyDescriptor(ea.prototype,"$emit"),ea.prototype),ze(ea.prototype,"$emitSync",[Ru],Object.getOwnPropertyDescriptor(ea.prototype,"$emitSync"),ea.prototype),ze(ea.prototype,"$on",[Hu,Vu,Bu],Object.getOwnPropertyDescriptor(ea.prototype,"$on"),ea.prototype),ze(ea.prototype,"$off",[Wu,Yu,Gu],Object.getOwnPropertyDescriptor(ea.prototype,"$off"),ea.prototype),ze(ea.prototype,"$once",[qu,Uu],Object.getOwnPropertyDescriptor(ea.prototype,"$once"),ea.prototype),ze(ea.prototype,"$css",[Ku,Qu],Object.getOwnPropertyDescriptor(ea.prototype,"$css"),ea.prototype),ze(ea.prototype,"$attr",[Zu,Ju],Object.getOwnPropertyDescriptor(ea.prototype,"$attr"),ea.prototype),ze(ea.prototype,"$plugins",[ye,we],Object.getOwnPropertyDescriptor(ea.prototype,"$plugins"),ea.prototype),ze(ea.prototype,"$pluginOrder",[ye,we],Object.getOwnPropertyDescriptor(ea.prototype,"$pluginOrder"),ea.prototype),ze(ea.prototype,"$wrapper",[ye],Object.getOwnPropertyDescriptor(ea.prototype,"$wrapper"),ea.prototype),ze(ea.prototype,"$container",[ye],Object.getOwnPropertyDescriptor(ea.prototype,"$container"),ea.prototype),ze(ea.prototype,"$video",[ye],Object.getOwnPropertyDescriptor(ea.prototype,"$video"),ea.prototype),Xu=ea))||Xu),Ja=(ta=Ia())(ra=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.id,n=e.name,u=e.level,a=void 0===u?0:u,d=e.operable,h=void 0===d||d,p=e.beforeCreate,v=e.create,y=e.init,g=e.inited,m=e.destroy,_=e.events,b=void 0===_?{}:_,E=e.data,k=void 0===E?{}:E,P=e.computed,S=void 0===P?{}:P,j=e.methods,x=void 0===j?{}:j,A=e.el,T=e.penetrate,L=void 0!==T&&T,M=e.inner,C=void 0===M||M,z=e.autoFocus,F=e.className,$=arguments[1],N=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{name:n};No(this,t);var D=Vo(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));if(D.destroyed=!1,D.VERSION="0.2.0",D.__operable=!0,D.__level=0,c($))throw $n.error("Dispatcher.plugin","lack of dispatcher. Do you forget to pass arguments to super in plugin?"),new TypeError("lack of dispatcher");if(!l(r))throw new TypeError("id of PluginConfig must be string");D.__id=r,D.__dispatcher=$,D.$videoConfig=D.__dispatcher.videoConfig,D.__wrapAsVideo(D.$videoConfig),D.beforeCreate=D.beforeCreate||p;try{i(D.beforeCreate)&&D.beforeCreate({events:b,data:k,computed:S,methods:x},N)}catch(e){D.$throwError(e)}if(!c(x)&&o(x)&&Object.keys(x).forEach(function(e){var t=x[e];if(!i(t))throw new TypeError("plugins methods must be Function");Object.defineProperty(D,e,{value:O(t,D),writable:!0,enumerable:!1,configurable:!0})}),!c(b)&&o(b)&&Object.keys(b).forEach(function(e){if(!i(b[e]))throw new TypeError("plugins events hook must bind with Function");D.$on(e,b[e])}),!c(k)&&o(k)&&w(D,k),!c(S)&&o(S)){var I=Object.keys(S).reduce(function(e,t){var r=S[t];return i(r)?(e[t]=ae({get:r}),e):o(r)&&(i(r.get)||i(r.set))?(e[t]=ae(r),e):($n.warn("Dispatcher.plugin","Wrong computed member '"+t+"' defination in Plugin "+n),e)},{});ge(D,I,{self:!0})}D.create=D.create||v,D.init=D.init||y,D.inited=D.inited||g,D.destroy=D.destroy||m,D.$dom=D.__dispatcher.dom.insertPlugin(D.__id,A,{penetrate:L,inner:C,autoFocus:z,className:F}),D.$inner=C,D.$autoFocus=z,D.$penetrate=L,ge(D,{$inner:pe,$autoFocus:pe,$penetrate:pe},{self:!0}),D.$operable=f(N.operable)?N.operable:h,D.__level=s(N.level)?N.level:a,D.$config=N;try{i(D.create)&&D.create()}catch(e){D.$throwError(e)}return D}return Ho(t,Za),Do(t,[{key:"__init",value:function(e){try{i(this.init)&&this.init(e)}catch(e){this.$throwError(e)}}},{key:"__inited",value:function(){var e=this,t=void 0;try{t=i(this.inited)&&this.inited()}catch(e){this.$throwError(e)}return this.readySync=!d(t),this.ready=this.readySync?Promise.resolve():t.then(function(t){return e.readySync=!0,t}).catch(function(t){return m(t)?e.$throwError(t):Promise.reject(t)}),this.readySync||this.ready}},{key:"$bumpToTop",value:function(){var e=this.__dispatcher._getTopLevel(this.$inner);this.$level=e+1}},{key:"$throwError",value:function(e){this.__dispatcher.throwError(e)}},{key:"$destroy",value:function(){i(this.destroy)&&this.destroy(),Ro(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"__destroy",this).call(this),this.__dispatcher.dom.removePlugin(this.__id),delete this.__dispatcher,delete this.$dom,this.destroyed=!0}},{key:"$operable",set:function(e){f(e)&&(this.$dom.style.pointerEvents=e?"auto":"none",this.__operable=e)},get:function(){return this.__operable}},{key:"$level",set:function(e){s(e)&&(this.__level=e,this.__dispatcher._sortZIndex())},get:function(){return this.__level}}]),t}())||ra,Xa=(na=function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).other;if(!i(e)&&!d(e)&&!l(e))throw new TypeError("@waitUntil only accept Function, Promise or String");return function(n,o,u){if(void 0===u)throw new Error("@waituntil must used on descriptor, are you using it on undefined property?");var a=u.value,s=u.configurable;if(!i(a))throw new TypeError("@waituntil can only be used on function, but not "+a);var c=!1,l=[],f=d(e)?function(){return e}:i(e)?e:function(){var n=e.split("."),i=n.slice(-1),o=h(t)?this:t;if(!c){var u=P(o,n.slice(0,-1));if(r(u))return u;var a=Va(u,i),s=function(e){if(!0===e)for(;l.length>0;)l[0](),l.shift();return e},f=X(a)?ae({set:s})(u,i,a):ae({set:s})(u,i,{value:void 0,configurable:!0,enumerable:!0,writable:!0});Ba(u,i,f),c=!0}return P(o,n)};return{value:function(){for(var e=this,t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=O(a,this),o=O(f,this).apply(void 0,r);return d(o)?Qi.resolve(o).then(function(){return O(a,e).apply(void 0,r)}):!0===o?O(a,this).apply(void 0,r):new Qi(function(e){l.push(function(){i.apply(void 0,r),e()})})},enumerable:!1,configurable:s,writable:!1}}}("__dispatcher.videoConfigReady"),ia=se(De,Ne),oa=se(De,Ne),ua=se(De,Ne),aa=se(De,Ne),sa=se(Ne),ca=function(){function e(t,r){var n=this;if(No(this,e),this.plugins={},this.originHTML="",this.videoEventHandlerList=[],this.videoDomEventHandlerList=[],this.containerDomEventHandlerList=[],this.wrapperDomEventHandlerList=[],this.__domEventHandlerList={},this.__mouseInVideo=!1,this.__videoExtendedNodes=[],this.isFullScreen=!1,this.fullScreenElement=void 0,this.__dispatcher=r,!v(t)&&!l(t))throw new TypeError("Illegal wrapper");var i=J(t);if(0===i.length)throw new TypeError("Can not get dom node accroding wrapper. Please check your wrapper");this.wrapper=i[0],this.originHTML=this.wrapper.innerHTML;var o=i.find("video")[0];o||(o=document.createElement("video")),this.installVideo(o),To.forEach(function(e){var t=n._getEventHandler(e,{penetrate:!0});n.videoDomEventHandlerList.push(t),W(n.videoElement,e,t)}),this._bindFullScreen()}return Do(e,[{key:"installVideo",value:function(e){var t=this;if(this.__videoExtendedNodes.push(e),I(e,"tabindex",-1),this._autoFocusToVideo(e),v(this.container)){var r=this.container;0===r.childNodes.length?r.appendChild(e):r.insertBefore(e,r.childNodes[0])}else e.parentElement&&v(e.parentElement)&&e.parentElement!==this.wrapper?this.container=e.parentElement:(this.container=document.createElement("container"),J(this.container).append(e));return this.container.parentElement!==this.wrapper&&J(this.wrapper).append(this.container),xo.forEach(function(r){var n=function(){for(var e,n=arguments.length,i=Array(n),o=0;o<n;o++)i[o]=arguments[o];return(e=t.__dispatcher.bus).trigger.apply(e,[r].concat(i))};t.videoEventHandlerList.push(n),W(e,r,n)}),To.forEach(function(r){var n=t._getEventHandler(r,{penetrate:!0});t.videoDomEventHandlerList.push(n),W(e,r,n)}),this.videoElement=e,e}},{key:"removeVideo",value:function(){var e=this,t=this.videoElement;return this._autoFocusToVideo(this.videoElement,!1),xo.forEach(function(t,r){B(e.videoElement,t,e.videoEventHandlerList[r])}),To.forEach(function(t,r){B(e.videoElement,t,e.videoDomEventHandlerList[r])}),J(t).remove(),delete this.videoElement,t}},{key:"insertPlugin",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!l(e))throw new TypeError("insertPlugin id parameter must be string");if(v(this.plugins[e])&&($n.warn("Dispatcher.dom","Plugin "+e+" have already had a dom node. Now it will be replaced"),this.removePlugin(e)),l(t))if(g(t)){var u=document.createElement("div");u.innerHTML=t,t=u.children[0]}else t=document.createElement(k(t));else o(t)&&(i=t);var a=i,s=a.inner,c=a.penetrate,d=a.autoFocus,h=i.className,p=t&&v(t)?t:document.createElement("div");n(h)&&(h=h.join(" ")),l(h)&&R(p,h),this.plugins[e]=p;var y=s?this.container:this.wrapper,m=s?this.videoElement:this.container;return(f(d)?d:s)&&this._autoFocusToVideo(p),c&&(this.__domEventHandlerList[e]=this.__domEventHandlerList[e]||[],To.forEach(function(t){var n=r._getEventHandler(t,{penetrate:c});W(p,t,n),r.__domEventHandlerList[e].push(n)}),this.__videoExtendedNodes.push(p)),y.lastChild===m?(y.appendChild(p),p):(y.insertBefore(p,m.nextSibling),p)}},{key:"removePlugin",value:function(e){var t=this;if(l(e)){var r=this.plugins[e];v(r)&&(r.parentNode&&r.parentNode.removeChild(r),this._autoFocusToVideo(r,!0)),c(this.__domEventHandlerList[e])||(To.forEach(function(r,n){B(t.plugins[e],r,t.__domEventHandlerList[e][n])}),delete this.__domEventHandlerList[e]),delete this.plugins[e]}}},{key:"setPluginsZIndex",value:function(e){var t=this;e.forEach(function(e,r){return U(e.match(/^(videoElement|container)$/)?t[e]:t.plugins[e],"z-index",++r)})}},{key:"setAttr",value:function(e,t,r){I(this[e],t,r)}},{key:"getAttr",value:function(e,t){return D(this[e],t)}},{key:"setStyle",value:function(e,t,r){U(this[e],t,r)}},{key:"getStyle",value:function(e,t){return q(this[e],t)}},{key:"requestFullScreen",value:function(e){for(var t=["requestFullscreen","mozRequestFullScreen","webkitRequestFullscreen","msRequestFullscreen"],r=0,n=t.length;r<n;r++)if(i(this[e][t[r]]))return this[e][t[r]](),!0;return!1}},{key:"exitFullScreen",value:function(){for(var e=["exitFullscreen","msExitFullscreen","mozCancelFullScreen","webkitExitFullscreen"],t=0,r=e.length;t<r;t++)if(i(document[e[t]]))return document[e[t]](),!0;return!1}},{key:"fullScreen",value:function(){for(var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"container",r=arguments.length,n=Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return e?this.requestFullScreen.apply(this,[t].concat(Bo(n))):this.exitFullScreen.apply(this,Bo(n))}},{key:"focus",value:function(){this.videoElement.focus()}},{key:"destroy",value:function(){var e=this;this.removeVideo(),To.forEach(function(t,r){B(e.container,t,e.containerDomEventHandlerList[r]),B(e.wrapper,t,e.wrapperDomEventHandlerList[r])}),this._bindFullScreen(!0),this.wrapper.innerHTML=this.originHTML,delete this.wrapper,delete this.plugins}},{key:"_autoFocusToVideo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];(t?B:W)(e,"mouseup",this._focusToVideo,!1,!0),(t?B:W)(e,"touchend",this._focusToVideo,!1,!0)}},{key:"_focusToVideo",value:function(e){var t=window.scrollX,r=window.scrollY;i(this.videoElement.focus)&&this.videoElement.focus(),window.scrollTo(t,r)}},{key:"_fullScreenMonitor",value:function(){var e=["fullscreenElement","webkitFullscreenElement","mozFullScreenElement","msFullscreenElement"].reduce(function(e,t){return e||document[t]},null);if(!e||!y(this.wrapper,e)&&e!==this.wrapper)return this.isFullScreen=!1,void(this.fullScreenElement=void 0);this.isFullScreen=!0,this.fullScreenElement=this.wrapper===e?"wrapper":this.container===e?"container":this.videoElement===e?"video":e}},{key:"_bindFullScreen",value:function(e){var t=this;e||this._fullScreenMonitor(),["webkitfullscreenchange","mozfullscreenchange","msfullscreenchange","fullscreenchange"].forEach(function(r){document[(e?"remove":"add")+"EventListener"](r,t._fullScreenMonitor)})}},{key:"_getEventHandler",value:function(e,t){var r=this;if(!t.penetrate||["mouseenter","mouseleave"].indexOf(e)<0)return function(){for(var t,n=arguments.length,i=Array(n),o=0;o<n;o++)i[o]=arguments[o];(t=r.__dispatcher.bus).triggerSync.apply(t,[e].concat(i))};var n=function(e){return r.__videoExtendedNodes.indexOf(e)>-1||r.__videoExtendedNodes.reduce(function(t,r){return t||y(r,e)},!1)};return function(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];var o=t[0],u=o.toElement,a=o.currentTarget,s=o.relatedTarget,c=o.type,l=u||s;if(r.__mouseInVideo&&"mouseleave"===c&&!n(l)){var f;return r.__mouseInVideo=!1,(f=r.__dispatcher.bus).triggerSync.apply(f,["mouseleave"].concat(t))}if(!r.__mouseInVideo&&"mouseenter"===c&&n(a)){var d;return r.__mouseInVideo=!0,(d=r.__dispatcher.bus).triggerSync.apply(d,["mouseenter"].concat(t))}}}}]),e}(),$e(ca.prototype,"setAttr",[na,ia],Object.getOwnPropertyDescriptor(ca.prototype,"setAttr"),ca.prototype),$e(ca.prototype,"getAttr",[oa],Object.getOwnPropertyDescriptor(ca.prototype,"getAttr"),ca.prototype),$e(ca.prototype,"setStyle",[ua],Object.getOwnPropertyDescriptor(ca.prototype,"setStyle"),ca.prototype),$e(ca.prototype,"getStyle",[aa],Object.getOwnPropertyDescriptor(ca.prototype,"getStyle"),ca.prototype),$e(ca.prototype,"requestFullScreen",[sa],Object.getOwnPropertyDescriptor(ca.prototype,"requestFullScreen"),ca.prototype),$e(ca.prototype,"_focusToVideo",[he],Object.getOwnPropertyDescriptor(ca.prototype,"_focusToVideo"),ca.prototype),$e(ca.prototype,"_fullScreenMonitor",[he],Object.getOwnPropertyDescriptor(ca.prototype,"_fullScreenMonitor"),ca.prototype),ca),es={},ts=(la=se(Re),fa=se(function(e){if(i(e)){if(!(e.prototype instanceof Ja))throw new TypeError("If you pass a function as plugin config, this class must extends from Chimee.plugin")}else{if(!o(e)||c(e))throw new TypeError("plugin's config must be an Object");var t=e.name;if(!l(t)||t.length<1)throw new TypeError("plugin must have a legal name")}}),da=se(Re),ha=se(Re),pa=se(Re),va=function(){function e(t,r){var n=this;if(No(this,e),this.plugins={},this.order=[],this.readySync=!1,this.zIndexMap={inner:[],outer:[]},this.changeWatchable=!0,!o(t))throw new TypeError("UserConfig must be an Object");this.dom=new Xa(t.wrapper,this),this.bus=new Yo(this),this.vm=r,this.videoConfigReady=!1,this.videoConfig=new Qa(this,t),this._initUserPlugin(t.plugin),this.order.forEach(function(e){return n.plugins[e].__init(n.videoConfig)}),this.videoConfig.lockKernelProperty(),this.videoConfigReady=!0,this.videoConfig.init(),this.kernel=new jo(this.dom.videoElement,this.videoConfig);var i=[];this.order.forEach(function(e){var t=n.plugins[e].__inited();d(t)&&i.push(t)}),this.readySync=0===i.length,this.ready=this.readySync?Promise.resolve():Promise.all(i).then(function(){n.readySync=!0,n.bus.trigger("ready"),n._autoloadVideoSrcAtFirst()}),this.readySync&&this._autoloadVideoSrcAtFirst()}return Do(e,[{key:"use",value:function(t){if(l(t)&&(t={name:t,alias:void 0}),!o(t)||o(t)&&!l(t.name))throw new TypeError("pluginConfig do not match requirement");l(t.alias)||(t.alias=void 0);var r=t,n=r.name,u=r.alias;t.name=u||n,delete t.alias;var a=E(n),s=E(u||n),f=t,d=e.getPluginConfig(a);if(c(d))throw new TypeError("You have not installed plugin "+a);o(d)&&(d.id=s);var h=i(d)?new d({id:s},this,f):new Ja(d,this,f);return this.plugins[s]=h,Object.defineProperty(this.vm,s,{value:h,configurable:!0,enumerable:!1,writable:!1}),this.order.push(s),this._sortZIndex(),this.videoConfigReady&&h.__inited(),h.ready}},{key:"unuse",value:function(e){var t=this.plugins[e];if(o(t)&&i(t.$destroy)){t.$destroy();var r=this.order.indexOf(e);r>-1&&this.order.splice(r,1),delete this.plugins[e],delete this.vm[e]}else delete this.plugins[e]}},{key:"throwError",value:function(e){this.vm.__throwError(e)}},{key:"silentLoad",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.duration,i=void 0===n?3:n,o=r.bias,u=void 0===o?0:o,a=r.repeatTimes,s=void 0===a?0:a,l=r.increment,f=void 0===l?0:l,d=r.isLive,h=void 0===d?this.videoConfig.isLive:d,p=r.box,v=void 0===p?this.videoConfig.box:p,y=r.preset,g=void 0===y?this.videoConfig.preset:y,_={isLive:h,box:v,src:e,preset:g};return j(new Array(s+1).fill(1).map(function(e,n){return function(){return new Promise(function(e,o){r.abort&&o({error:!0,message:"user abort the mission"});var a=document.createElement("video"),l=t.kernel.currentTime+i+f*n;a.muted=!0;var d=!1,h=function r(n){var i=t.kernel.currentTime;if(u<=0&&i>=l||u>0&&(Math.abs(l-i)<=u&&d||i-l>u))return B(t.dom.videoElement,"timeupdate",r),d?o({error:!1,video:a,kernel:g}):(B(a,"canplay",p),B(a,"loadedmetadata",v),B(a,"error",y),g.destroy(),e())},p=function(e){if(d=!0,r.immediate)return o({error:!1,video:a,kernel:g})},v=function(e){g.seek(l)},y=function(r){B(a,"canplay",p,!0),B(a,"loadedmetadata",v,!0),B(t.dom.videoElement,"timeupdate",h);var i=c(a.error)?new Error("unknow video error"):new Error(a.error.message);return $n.error("chimee's silentload",i.message),g.destroy(),n===s?o(i):e(i)};W(a,"canplay",p,!0),W(a,"loadedmetadata",v,!0),W(a,"error",y,!0),W(t.dom.videoElement,"timeupdate",h);var g=new jo(a,_);g.load()})}})).then(function(){var t="The silentLoad for "+e+" timed out. Please set a longer duration or check your network";return $n.warn("chimee's silentLoad",t),Promise.reject(new Error(t))}).catch(function(e){if(m(e))return Promise.reject(e);if(e.error)return $n.warn("chimee's silentLoad",e.message),Promise.reject(new Error(e.message));var n=e.video,i=e.kernel;if(r.abort)return i.destroy(),Promise.reject(new Error("user abort the mission"));var o=t.dom.videoElement.paused;return t.switchKernel({video:n,kernel:i,config:_}),o||t.dom.videoElement.play(),Promise.resolve()})}},{key:"load",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!c(t)){var r=this.videoConfig,n=t.isLive,i=void 0===n?r.isLive:n,o=t.box,u=void 0===o?r.box:o,a=t.preset,s=void 0===a?r.preset:a,l=document.createElement("video"),f={isLive:i,box:u,preset:s,src:e},d=new jo(l,f);this.switchKernel({video:l,kernel:d,config:f})}this.kernel.load(e)}},{key:"switchKernel",value:function(e){var t=this,r=e.video,n=e.kernel,i=e.config;this.kernel.destroy();var o=b(this.videoConfig);this.dom.removeVideo(),this.dom.installVideo(r),this.videoConfig.changeWatchable=!1,this.videoConfig.autoload=!1,this.videoConfig.src=i.src,this.videoConfig._realDomAttr.forEach(function(e){"src"!==e&&(t.videoConfig[e]=o[e])}),this.videoConfig.changeWatchable=!0,ge(i,{src:ae({get:function(e){return t.videoConfig.src},set:function(e){return t.videoConfig.src=e,e}})},{self:!0}),this.kernel=n}},{key:"destroy",value:function(){for(var e in this.plugins)this.unuse(e);this.bus.destroy(),delete this.bus,this.dom.destroy(),delete this.dom,this.kernel.destroy(),delete this.kernel,delete this.vm,delete this.plugins,delete this.order}},{key:"_initUserPlugin",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return n(t)||($n.warn("Dispatcher","UserConfig.plugin can only by an Array"),t=[]),t.map(function(t){return e.use(t)})}},{key:"_sortZIndex",value:function(){var e=this,t=this.order.reduce(function(t,r){var n=e.plugins[r];if(c(n))return t;var i=t[n.$inner?"inner":"outer"],o=n.$level;return i[o]=i[o]||[],i[o].push(r),t},{inner:{},outer:{}}),r=t.inner,n=t.outer;r[0]=r[0]||[],r[0].unshift("videoElement"),n[0]=n[0]||[],n[0].unshift("container");var i=S(r),o=S(n);this.dom.setPluginsZIndex(i),this.dom.setPluginsZIndex(o),this.zIndexMap.inner=i,this.zIndexMap.outer=o}},{key:"_getTopLevel",value:function(e){var t=this.zIndexMap[e?"inner":"outer"],r=this.plugins[t[t.length-1]];return c(r)?0:r.$level}},{key:"_autoloadVideoSrcAtFirst",value:function(){this.videoConfig.autoload&&this.bus.emit("load",this.videoConfig.src)}}],[{key:"install",value:function(e){var t=e.name,r=E(t);c(es[r])||$n.warn("Dispatcher","You have installed "+t+" again. And the older one will be replaced");var n=i(e)?e:w({id:r},e);return es[r]=n,r}},{key:"hasInstalled",value:function(e){return!c(es[e])}},{key:"uninstall",value:function(e){delete es[e]}},{key:"getPluginConfig",value:function(e){return es[e]}}]),e}(),Ie(va.prototype,"unuse",[la],Object.getOwnPropertyDescriptor(va.prototype,"unuse"),va.prototype),Ie(va,"install",[fa],Object.getOwnPropertyDescriptor(va,"install"),va),Ie(va,"hasInstalled",[da],Object.getOwnPropertyDescriptor(va,"hasInstalled"),va),Ie(va,"uninstall",[ha],Object.getOwnPropertyDescriptor(va,"uninstall"),va),Ie(va,"getPluginConfig",[pa],Object.getOwnPropertyDescriptor(va,"getPluginConfig"),va),va),rs=(ya=function(){function e(){No(this,e),this.log={error:!0,info:!0,warn:!0,debug:!0,verbose:!0},He(this,"_silent",ga,this),this.errorHandler=void 0;var t=Object.keys(this.log).reduce(function(e,t){return e[t]=ae({get:function(){return $n["ENABLE_"+t.toUpperCase()]},set:function(e){return $n["ENABLE_"+t.toUpperCase()]=e,!0===e&&(this.silent=!1),e}}),e},{});ge(this.log,t,{self:!0})}return Do(e,[{key:"silent",get:function(){return this._silent},set:function(e){var t=this;e=!!e,this._silent=e,Object.keys(this.log).forEach(function(r){t.log[r]=!e})}}]),e}(),ga=function(e,t,r,n,i){var o={};return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}(ya.prototype,"_silent",[ye],{enumerable:!0,initializer:function(){return!1}}),ya);return Ia()((Ta=Aa=function(e){function t(e){No(this,t);var r=Vo(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));if(r.destroyed=!1,Ve(r,"__id",ba,r),Ve(r,"version",wa,r),Ve(r,"config",Ea,r),l(e)||v(e))e={wrapper:e,controls:!0};else{if(!o(e))throw new Error("You must pass in an Object containing wrapper or string or element to new a Chimee");if(!e.wrapper)throw new Error("You must pass in an legal object")}return r.__dispatcher=new ts(e,r),r.__dispatcher.kernel.on("error",r.__throwError),r.ready=r.__dispatcher.ready,r.readySync=r.__dispatcher.readySync,r.__wrapAsVideo(r.__dispatcher.videoConfig),r}return Ho(t,Za),Do(t,[{key:"destroy",value:function(){Ro(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"__destroy",this).call(this),this.__dispatcher.destroy(),this.destroyed=!0}},{key:"use",value:function(e){this.__dispatcher.use(e)}},{key:"unuse",value:function(e){this.__dispatcher.unuse(e)}},{key:"__throwError",value:function(e){l(e)&&(e=new Error(e));var r=this.config.errorHandler||t.config.errorHandler;if(i(r))return r(e);if(!t.config.silent)throw e}}]),t}(),Aa.plugin=Ja,Aa.config=new rs,Aa.install=ts.install,Aa.uninstall=ts.uninstall,Aa.hasInstalled=ts.hasInstalled,Aa.getPluginConfig=ts.getPluginConfig,_a=Ta,ba=Be(_a.prototype,"__id",[pe],{enumerable:!0,initializer:function(){return"_vm"}}),wa=Be(_a.prototype,"version",[pe],{enumerable:!0,initializer:function(){return"0.2.0"}}),Ea=Be(_a.prototype,"config",[pe],{enumerable:!0,initializer:function(){return{errorHandler:void 0}}}),Be(_a,"plugin",[pe],(ka=Object.getOwnPropertyDescriptor(_a,"plugin"),ka=ka?ka.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return ka}}),_a),Be(_a,"config",[pe],(Oa=Object.getOwnPropertyDescriptor(_a,"config"),Oa=Oa?Oa.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return Oa}}),_a),Be(_a,"install",[pe],(Pa=Object.getOwnPropertyDescriptor(_a,"install"),Pa=Pa?Pa.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return Pa}}),_a),Be(_a,"uninstall",[pe],(Sa=Object.getOwnPropertyDescriptor(_a,"uninstall"),Sa=Sa?Sa.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return Sa}}),_a),Be(_a,"hasInstalled",[pe],(ja=Object.getOwnPropertyDescriptor(_a,"hasInstalled"),ja=ja?ja.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return ja}}),_a),Be(_a,"getPluginConfig",[pe],(xa=Object.getOwnPropertyDescriptor(_a,"getPluginConfig"),xa=xa?xa.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return xa}}),_a),ma=_a))||ma}); diff --git a/lib/index.mjs b/lib/index.mjs index dd3d3a84..99cac38c 100644 --- a/lib/index.mjs +++ b/lib/index.mjs @@ -1,13 +1,12 @@ /** - * chimee v0.1.3 + * chimee v0.2.0 * (c) 2017 toxic-johann * Released under MIT */ import _Object$defineProperty from 'babel-runtime/core-js/object/define-property'; import _Object$getOwnPropertyDescriptor from 'babel-runtime/core-js/object/get-own-property-descriptor'; -import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray'; import _Object$getPrototypeOf from 'babel-runtime/core-js/object/get-prototype-of'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; @@ -15,19 +14,23 @@ import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructo import _get from 'babel-runtime/helpers/get'; import _inherits from 'babel-runtime/helpers/inherits'; import _Promise from 'babel-runtime/core-js/promise'; -import { $, Log, addClassName, addEvent, bind, camelize, deepAssign, deepClone, getAttr, getDeepProperty, getStyle, hypenate, isArray, isBoolean, isElement, isEmpty, isError, isFunction, isHTMLString, isInteger, isNumber, isObject, isPosterityNode, isPromise, isString, isVoid, removeEvent, runRejectableQueue, runStoppableQueue, setAttr, setStyle, transObjectAttrIntoArray } from 'chimee-helper'; +import { $, Log, addClassName, addEvent, bind, camelize, deepAssign, deepClone, getAttr, getDeepProperty, getStyle, hypenate, isArray, isBoolean, isElement, isEmpty, isError, isFunction, isHTMLString, isInteger, isNumber, isNumeric, isObject, isPosterityNode, isPromise, isString, isVoid, removeEvent, runRejectableQueue, runStoppableQueue, setAttr, setStyle, transObjectAttrIntoArray } from 'chimee-helper'; import Kernel from 'chimee-kernel'; import _Map from 'babel-runtime/core-js/map'; +import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray'; import _Object$keys from 'babel-runtime/core-js/object/keys'; -import { accessor, alias, alwaysBoolean, alwaysNumber, alwaysString, applyDecorators, autobind, autobindClass, before, configurable, frozen, initArray, initString, lock, nonenumerable, nonextendable, waituntil, watch } from 'toxic-decorators'; +import { accessor, alias, alwaysBoolean, alwaysNumber, alwaysString, applyDecorators, autobind, autobindClass, before, configurable, frozen, initBoolean, initString, lock, nonenumerable, nonextendable, waituntil, watch } from 'toxic-decorators'; import _JSON$stringify from 'babel-runtime/core-js/json/stringify'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _typeof from 'babel-runtime/helpers/typeof'; +import _Number$isNaN from 'babel-runtime/core-js/number/is-nan'; var videoEvents = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'interruptbegin', 'interruptend', 'loadeddata', 'loadedmetadata', 'loadstart', 'mozaudioavailable', 'pause', 'play', 'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; -var videoReadOnlyProperties = ['buffered', 'currentSrc', 'duration', 'ended', 'networkState', 'paused', 'readyState', 'seekable', 'sinkId', 'controlsList']; +var videoReadOnlyProperties = ['buffered', 'currentSrc', 'duration', 'error', 'ended', 'networkState', 'paused', 'readyState', 'seekable', 'sinkId', 'controlsList', 'tabIndex', 'dataset', 'offsetHeight', 'offsetLeft', 'offsetParent', 'offsetTop', 'offsetWidth']; var domEvents = ['beforeinput', 'blur', 'click', 'compositionend', 'compositionstart', 'compositionupdate', 'dblclick', 'focus', 'focusin', 'focusout', 'input', 'keydown', 'keypress', 'keyup', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll', 'select', 'wheel', 'fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange', 'contextmenu']; -var kernelMethods = ['play', 'pause', 'load', 'seek']; +var selfProcessorEvents = ['silentLoad', 'fullScreen']; +var kernelMethods = ['play', 'pause', 'seek']; +var dispatcherMethods = ['load']; var domMethods = ['focus', 'fullScreen', 'requestFullScreen', 'exitFullScreen']; var videoMethods = ['canPlayType', 'captureStream', 'setSinkId']; @@ -159,10 +162,12 @@ var Bus = function () { } var event = this.events[key]; if (isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return _Promise.resolve(); return this._eventProcessor.apply(this, [key, { sync: false }].concat(_toConsumableArray(args))); } var beforeQueue = this._getEventQueue(event.before, this.__dispatcher.order); return runRejectableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))).then(function () { + if (selfProcessorEvents.indexOf(key) > -1) return; return _this._eventProcessor.apply(_this, [key, { sync: false }].concat(_toConsumableArray(args))); }).catch(function (error) { if (isError(error)) _this.__dispatcher.throwError(error); @@ -191,10 +196,11 @@ var Bus = function () { } if (isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return true; return this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args))); } var beforeQueue = this._getEventQueue(event.before, this.__dispatcher.order); - return runStoppableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))) && this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args))); + return runStoppableQueue.apply(undefined, [beforeQueue].concat(_toConsumableArray(args))) && (selfProcessorEvents.indexOf(key) > -1 || this._eventProcessor.apply(this, [key, { sync: true }].concat(_toConsumableArray(args)))); } /** * [Can only be called in dispatcher]trigger an event, which will run main -> after -> side effect period @@ -415,15 +421,22 @@ var Bus = function () { var isKernelMethod = kernelMethods.indexOf(key) > -1; var isDomMethod = domMethods.indexOf(key) > -1; + var isDispatcherMethod = dispatcherMethods.indexOf(key) > -1; for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { args[_key5 - 2] = arguments[_key5]; } - if (isKernelMethod || isDomMethod) { - var _dispatcher; + if (isKernelMethod || isDomMethod || isDispatcherMethod) { + if (isDispatcherMethod) { + var _dispatcher; + + (_dispatcher = this.__dispatcher)[key].apply(_dispatcher, _toConsumableArray(args)); + } else { + var _dispatcher2; - (_dispatcher = this.__dispatcher[isKernelMethod ? 'kernel' : 'dom'])[key].apply(_dispatcher, _toConsumableArray(args)); + (_dispatcher2 = this.__dispatcher[isKernelMethod ? 'kernel' : 'dom'])[key].apply(_dispatcher2, _toConsumableArray(args)); + } if (videoEvents.indexOf(key) > -1 || domEvents.indexOf(key) > -1) return true; } // $FlowFixMe: flow do not support computed sytax on classs, but it's ok here @@ -486,180 +499,29 @@ function attrAndStyleCheck() { return ['get', 'container'].concat(args); } -var VideoWrapper = function () { - function VideoWrapper() { - _classCallCheck(this, VideoWrapper); - - this.__unwatchHandlers = []; - } - - _createClass(VideoWrapper, [{ - key: '__wrapAsVideo', - value: function __wrapAsVideo(videoConfig) { - var _this = this; - - // bind video read only properties on instance, so that you can get info like buffered - videoReadOnlyProperties.forEach(function (key) { - _Object$defineProperty(_this, key, { - get: function get() { - return this.__dispatcher.dom.videoElement[key]; - }, - - set: undefined, - configurable: false, - enumerable: false - }); - }); - // bind videoMethods like canplaytype on instance - videoMethods.forEach(function (key) { - _Object$defineProperty(_this, key, { - get: function get() { - var video = this.__dispatcher.dom.videoElement; - return bind(video[key], video); - }, - - set: undefined, - configurable: false, - enumerable: false - }); - }); - // bind video config properties on instance, so that you can just set src by this - var props = videoConfig._realDomAttr.concat(videoConfig._kernelProperty).reduce(function (props, key) { - props[key] = [accessor({ - get: function get() { - return videoConfig[key]; - }, - set: function set(value) { - videoConfig[key] = value; - return value; - } - }), nonenumerable]; - return props; - }, {}); - applyDecorators(this, props, { self: true }); - kernelMethods.forEach(function (key) { - _Object$defineProperty(_this, key, { - value: function value() { - var _this2 = this; - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return new _Promise(function (resolve, reject) { - var _dispatcher$bus; - - _this2.__dispatcher.bus.once(_this2.__id, '_' + key, resolve); - (_dispatcher$bus = _this2.__dispatcher.bus)[/^(seek)$/.test(key) ? 'emitSync' : 'emit'].apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - }); - }, - - configurable: true, - enumerable: false, - writable: true - }); - }); - domMethods.forEach(function (key) { - _Object$defineProperty(_this, key, { - value: function value() { - var _dispatcher$dom; - - return (_dispatcher$dom = this.__dispatcher.dom)[key].apply(_dispatcher$dom, arguments); - }, - - configurable: true, - enumerable: false, - writable: true - }); - }); - } - }, { - key: '$watch', - value: function $watch(key, handler) { - var _this3 = this; - - var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - deep = _ref.deep, - _ref$diff = _ref.diff, - diff = _ref$diff === undefined ? true : _ref$diff, - other = _ref.other, - _ref$proxy = _ref.proxy, - proxy = _ref$proxy === undefined ? false : _ref$proxy; - - if (!isString(key) && !isArray(key)) throw new TypeError('$watch only accept string and Array<string> as key to find the target to spy on, but not ' + key + ', whose type is ' + (typeof key === 'undefined' ? 'undefined' : _typeof(key))); - var watching = true; - var watcher = function watcher() { - if (watching) bind(handler, this).apply(undefined, arguments); - }; - var unwatcher = function unwatcher() { - watching = false; - var index = _this3.__unwatchHandlers.indexOf(unwatcher); - if (index > -1) _this3.__unwatchHandlers.splice(index, 1); - }; - var keys = isString(key) ? key.split('.') : key; - var property = keys.pop(); - var videoConfig = this.__dispatcher.videoConfig; - var target = keys.length === 0 && !other && videoConfig._realDomAttr.indexOf(property) > -1 ? videoConfig : getDeepProperty(other || this, keys, { throwError: true }); - applyDecorators(target, _defineProperty({}, property, watch(watcher, { deep: deep, diff: diff, proxy: proxy })), { self: true }); - this.__unwatchHandlers.push(unwatcher); - return unwatcher; - } - }, { - key: '$set', - value: function $set(obj, property, value) { - if (!isObject(obj) && !isArray(obj)) throw new TypeError('$set only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); - // $FlowFixMe: we have custom this function - if (!isFunction(obj.__set)) { - Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $set.'); - // $FlowFixMe: we support computed string on array here - obj[property] = value; - return; - } - obj.__set(property, value); - } - }, { - key: '$del', - value: function $del(obj, property) { - if (!isObject(obj) && !isArray(obj)) throw new TypeError('$del only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); - // $FlowFixMe: we have custom this function - if (!isFunction(obj.__del)) { - Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $del.'); - // $FlowFixMe: we support computed string on array here - delete obj[property]; - return; - } - obj.__del(property); - } - }, { - key: '__destroy', - value: function __destroy() { - this.__unwatchHandlers.forEach(function (unwatcher) { - return unwatcher(); - }); - } - }, { - key: 'currentTime', - get: function get() { - return this.__dispatcher.kernel.currentTime; - }, - set: function set(second) { - this.__dispatcher.bus.emitSync('seek', second); - } - }]); +var _dec$4; +var _dec2$2; +var _class$4; +var _descriptor$1; +var _descriptor2$1; +var _descriptor3$1; +var _descriptor4; +var _descriptor5; +var _descriptor6; +var _descriptor7; - return VideoWrapper; -}(); +function _initDefineProp$1(target, property, descriptor, context) { + if (!descriptor) return; -var _dec$2; -var _dec2$2; -var _dec3$2; -var _dec4$2; -var _dec5$2; -var _dec6$1; -var _class$2; -var _class2$1; + _Object$defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} -function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { +function _applyDecoratedDescriptor$3(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; @@ -688,67 +550,807 @@ function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, c return desc; } -/** - * <pre> - * Plugin is the class for plugin developer. - * When we use a plugin, we will generate an instance of plugin. - * Developer can do most of things base on this plugin - * </pre> - */ -var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _dec3$2 = before(attrAndStyleCheck), _dec4$2 = before(eventBinderCheck), _dec5$2 = before(eventBinderCheck), _dec6$1 = before(eventBinderCheck), _dec$2(_class$2 = (_class2$1 = function (_VideoWrapper) { - _inherits(Plugin, _VideoWrapper); +function stringOrVoid(value) { + return isString(value) ? value : undefined; +} - /** - * <pre> - * to create a plugin, we need three parameter - * 1. the config of a plugin - * 2. the dispatcher - * 3. this option for plugin to read - * this is the plugin base class, which you can get on Chimee - * You can just extends it and then install - * But in that way you must remember to pass the arguments to super() - * </pre> - * @param {string} PluginConfig.id camelize from plugin's name or class name. - * @param {string} PluginConfig.name plugin's name or class name - * @param {Number} PluginConfig.level the level of z-index - * @param {Boolean} PluginConfig.operable to tell if the plugin can be operable, if not, we will add pointer-events: none on it. - * @param {Function} PluginConfig.create the create function which we will called when plugin is used. sth like constructor in object style. - * @param {Function} PluginConfig.destroy function to be called when we destroy a plugin - * @param {Object} PluginConfig.events You can set some events handler in this object, we will bind it once you use the plugin. - * @param {Object} PluginConfig.data dataset we will bind on data in object style - * @param {Object<{get: Function, set: Function}} PluginConfig.computed dataset we will handle by getter and setter - * @param {Object<Function>} PluginConfig.methods some function we will bind on plugin - * @param {string|HTMLElment} PluginConfig.el can be string or HTMLElement, we will use this to create the dom for plugin - * @param {boolean} PluginConfig.penetrate boolean to let us do we need to forward the dom events for this plugin. - * @param {Dispatcher} dispatcher referrence of dispatcher - * @param {Object} option PluginOption that will pass to the plugin - * @return {Plugin} plugin instance - */ - function Plugin() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - id = _ref.id, - name = _ref.name, - _ref$level = _ref.level, - level = _ref$level === undefined ? 0 : _ref$level, - _ref$operable = _ref.operable, - operable = _ref$operable === undefined ? true : _ref$operable, - beforeCreate = _ref.beforeCreate, - create = _ref.create, - init = _ref.init, - inited = _ref.inited, - destroy = _ref.destroy, - _ref$events = _ref.events, - events = _ref$events === undefined ? {} : _ref$events, - _ref$data = _ref.data, - data = _ref$data === undefined ? {} : _ref$data, - _ref$computed = _ref.computed, - computed = _ref$computed === undefined ? {} : _ref$computed, - _ref$methods = _ref.methods, - methods = _ref$methods === undefined ? {} : _ref$methods, - el = _ref.el, - _ref$penetrate = _ref.penetrate, - penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, - _ref$inner = _ref.inner, +function accessorVideoProperty(property) { + return accessor({ + get: function get(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement[property] : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + this.dom.videoElement[property] = value; + return value; + } + }); +} + +function accessorVideoAttribute(attribute) { + var _ref = isObject(attribute) ? attribute : { + set: attribute, + get: attribute, + isBoolean: false + }, + _set = _ref.set, + _get$$1 = _ref.get, + isBoolean$$1 = _ref.isBoolean; + + return accessor({ + get: function get(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement[_get$$1] : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = isBoolean$$1 ? value ? '' : undefined : value; + this.dom.setAttr('video', _set, val); + return value; + } + }); +} + +function accessorCustomAttribute(attribute, isBoolean$$1) { + return accessor({ + get: function get(value) { + var attrValue = this.dom.getAttr('video', attribute); + return this.dispatcher.videoConfigReady && this.inited ? isBoolean$$1 ? !!attrValue : attrValue : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = isBoolean$$1 ? value || undefined : value; + this.dom.setAttr('video', attribute, val); + return value; + } + }); +} + +function accessorWidthAndHeight(property) { + return accessor({ + get: function get(value) { + if (!this.dispatcher.videoConfigReady) return value; + var attr = this.dom.getAttr('video', property); + var prop = this.dom.videoElement[property]; + if (isNumeric(attr) && isNumber(prop)) return prop; + return attr || undefined; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = void 0; + if (value === undefined || isNumber(value)) { + val = value; + } else if (isString(value) && !_Number$isNaN(parseFloat(value))) { + val = value; + } + this.dom.setAttr('video', property, val); + return val; + } + }); +} + +var accessorMap = { + src: [alwaysString(), accessor({ + set: function set(val) { + // must check val !== this.src here + // as we will set config.src in the video + // the may cause dead lock + if (this.dispatcher.readySync && this.autoload && val !== this.src) this.needToLoadSrc = true; + return val; + } + }), accessor({ + set: function set(val) { + if (this.needToLoadSrc) { + // unlock it at first, to avoid deadlock + this.needToLoadSrc = false; + this.dispatcher.bus.emit('load', val); + } + return val; + } + }, { preSet: false })], + autoload: alwaysBoolean(), + autoplay: [alwaysBoolean(), accessorVideoProperty('autoplay')], + controls: [alwaysBoolean(), accessorVideoProperty('controls')], + width: [accessorWidthAndHeight('width')], + height: [accessorWidthAndHeight('height')], + crossOrigin: [accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' })], + loop: [alwaysBoolean(), accessorVideoProperty('loop')], + defaultMuted: [alwaysBoolean(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true })], + muted: [alwaysBoolean(), accessorVideoProperty('muted')], + preload: [accessor({ set: stringOrVoid }), accessorVideoAttribute('preload')], + poster: [accessor({ set: stringOrVoid }), accessorVideoAttribute('poster')], + playsInline: [accessor({ + get: function get(value) { + var playsInline = this.dom.videoElement.playsInline; + return this.dispatcher.videoConfigReady && this.inited ? playsInline === undefined ? value : playsInline : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + this.dom.videoElement.playsInline = value; + var val = value ? '' : undefined; + this.dom.setAttr('video', 'playsinline', val); + this.dom.setAttr('video', 'webkit-playsinline', val); + this.dom.setAttr('video', 'x5-video-player-type', value ? 'h5' : undefined); + return value; + } + }), alwaysBoolean()], + x5VideoPlayerFullScreen: [accessor({ + set: function set(value) { + return !!value; + }, + get: function get(value) { + return !!value; + } + }), accessorCustomAttribute('x5-video-player-fullscreen', true)], + x5VideoOrientation: [accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], + xWebkitAirplay: [accessor({ + set: function set(value) { + return !!value; + }, + get: function get(value) { + return !!value; + } + }), accessorCustomAttribute('x-webkit-airplay', true)], + playbackRate: [alwaysNumber(1), accessorVideoProperty('playbackRate')], + defaultPlaybackRate: [accessorVideoProperty('defaultPlaybackRate'), alwaysNumber(1)], + disableRemotePlayback: [alwaysBoolean(), accessorVideoProperty('disableRemotePlayback')], + volume: [alwaysNumber(1), accessorVideoProperty('volume')] +}; + +var VideoConfig = (_dec$4 = initBoolean(), _dec2$2 = initString(function (str) { + return str.toLocaleLowerCase(); +}), (_class$4 = function () { + _createClass(VideoConfig, [{ + key: 'lockKernelProperty', + value: function lockKernelProperty() { + applyDecorators(this, { + isLive: lock, + box: lock, + preset: lock + }, { self: true }); + } + }]); + + function VideoConfig(dispatcher, config) { + _classCallCheck(this, VideoConfig); + + _initDefineProp$1(this, 'needToLoadSrc', _descriptor$1, this); + + _initDefineProp$1(this, 'changeWatchable', _descriptor2$1, this); + + _initDefineProp$1(this, 'inited', _descriptor3$1, this); + + this.src = ''; + + _initDefineProp$1(this, 'isLive', _descriptor4, this); + + _initDefineProp$1(this, 'box', _descriptor5, this); + + this.preset = {}; + this.autoload = true; + this.autoplay = false; + this.controls = false; + this.width = undefined; + this.height = undefined; + this.crossOrigin = undefined; + this.loop = false; + this.defaultMuted = false; + this.muted = false; + this.preload = 'auto'; + this.poster = undefined; + this.playsInline = false; + this.x5VideoPlayerFullScreen = false; + this.x5VideoOrientation = undefined; + this.xWebkitAirplay = false; + this.playbackRate = 1; + this.defaultPlaybackRate = 1; + this.disableRemotePlayback = false; + this.volume = 1; + + _initDefineProp$1(this, '_kernelProperty', _descriptor6, this); + + _initDefineProp$1(this, '_realDomAttr', _descriptor7, this); + + applyDecorators(this, accessorMap, { self: true }); + Object.defineProperty(this, 'dispatcher', { + value: dispatcher, + enumerable: false, + writable: false, + configurable: false + }); + Object.defineProperty(this, 'dom', { + value: dispatcher.dom, + enumerable: false, + writable: false, + configurable: false + }); + deepAssign(this, config); + } + + _createClass(VideoConfig, [{ + key: 'init', + value: function init() { + var _this = this; + + this._realDomAttr.forEach(function (key) { + // $FlowFixMe: we have check the computed here + _this[key] = _this[key]; + }); + this.inited = true; + } + }]); + + return VideoConfig; +}(), (_descriptor$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'needToLoadSrc', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor2$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'changeWatchable', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return true; + } +}), _descriptor3$1 = _applyDecoratedDescriptor$3(_class$4.prototype, 'inited', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor4 = _applyDecoratedDescriptor$3(_class$4.prototype, 'isLive', [_dec$4, configurable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor5 = _applyDecoratedDescriptor$3(_class$4.prototype, 'box', [_dec2$2, configurable], { + enumerable: true, + initializer: function initializer() { + return ''; + } +}), _descriptor6 = _applyDecoratedDescriptor$3(_class$4.prototype, '_kernelProperty', [frozen], { + enumerable: true, + initializer: function initializer() { + return ['isLive', 'box', 'preset']; + } +}), _descriptor7 = _applyDecoratedDescriptor$3(_class$4.prototype, '_realDomAttr', [frozen], { + enumerable: true, + initializer: function initializer() { + return ['src', 'controls', 'width', 'height', 'crossOrigin', 'loop', 'muted', 'preload', 'poster', 'autoplay', 'playsInline', 'x5VideoPlayerFullScreen', 'x5VideoOrientation', 'xWebkitAirplay', 'playbackRate', 'defaultPlaybackRate', 'autoload', 'disableRemotePlayback', 'defaultMuted', 'volume']; + } +})), _class$4)); + +var _dec$3; +var _dec2$1; +var _dec3$1; +var _dec4$1; +var _dec5$1; +var _dec6; +var _dec7; +var _dec8; +var _dec9; +var _dec10; +var _dec11; +var _dec12; +var _dec13; +var _dec14; +var _dec15; +var _dec16; +var _dec17; +var _class$3; +var _class2$1; + +function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; +} + +function propertyAccessibilityWarn(property) { + Log.warn('chimee', 'You are trying to obtain ' + property + ', we will return you the DOM node. It\'s not a good idea to handle this by yourself. If you have some requirement, you can tell use by https://github.com/Chimeejs/chimee/issues'); +} +var VideoWrapper = (_dec$3 = autobindClass(), _dec2$1 = alias('silentLoad'), _dec3$1 = alias('fullScreen'), _dec4$1 = alias('emit'), _dec5$1 = alias('emitSync'), _dec6 = alias('on'), _dec7 = alias('addEventListener'), _dec8 = before(eventBinderCheck), _dec9 = alias('off'), _dec10 = alias('removeEventListener'), _dec11 = before(eventBinderCheck), _dec12 = alias('once'), _dec13 = before(eventBinderCheck), _dec14 = alias('css'), _dec15 = before(attrAndStyleCheck), _dec16 = alias('attr'), _dec17 = before(attrAndStyleCheck), _dec$3(_class$3 = (_class2$1 = function () { + function VideoWrapper() { + _classCallCheck(this, VideoWrapper); + + this.__events = {}; + this.__unwatchHandlers = []; + } + + _createClass(VideoWrapper, [{ + key: '__wrapAsVideo', + value: function __wrapAsVideo(videoConfig) { + var _this = this; + + // bind video read only properties on instance, so that you can get info like buffered + videoReadOnlyProperties.forEach(function (key) { + _Object$defineProperty(_this, key, { + get: function get() { + return this.__dispatcher.dom.videoElement[key]; + }, + + set: undefined, + configurable: false, + enumerable: false + }); + }); + // bind videoMethods like canplaytype on instance + videoMethods.forEach(function (key) { + _Object$defineProperty(_this, key, { + get: function get() { + var video = this.__dispatcher.dom.videoElement; + return bind(video[key], video); + }, + + set: undefined, + configurable: false, + enumerable: false + }); + }); + // bind video config properties on instance, so that you can just set src by this + var props = videoConfig._realDomAttr.concat(videoConfig._kernelProperty).reduce(function (props, key) { + props[key] = [accessor({ + get: function get() { + // $FlowFixMe: support computed key here + return videoConfig[key]; + }, + set: function set(value) { + // $FlowFixMe: support computed key here + videoConfig[key] = value; + return value; + } + }), nonenumerable]; + return props; + }, {}); + applyDecorators(this, props, { self: true }); + kernelMethods.forEach(function (key) { + _Object$defineProperty(_this, key, { + value: function value() { + var _this2 = this; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return new _Promise(function (resolve, reject) { + var _dispatcher$bus; + + _this2.__dispatcher.bus.once(_this2.__id, '_' + key, resolve); + (_dispatcher$bus = _this2.__dispatcher.bus)[/^(seek)$/.test(key) ? 'emitSync' : 'emit'].apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); + }); + }, + + configurable: true, + enumerable: false, + writable: true + }); + }); + domMethods.forEach(function (key) { + if (key === 'fullScreen') return; + _Object$defineProperty(_this, key, { + value: function value() { + var _dispatcher$dom; + + return (_dispatcher$dom = this.__dispatcher.dom)[key].apply(_dispatcher$dom, arguments); + }, + + configurable: true, + enumerable: false, + writable: true + }); + }); + } + }, { + key: '$watch', + value: function $watch(key, handler) { + var _this3 = this; + + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + deep = _ref.deep, + _ref$diff = _ref.diff, + diff = _ref$diff === undefined ? true : _ref$diff, + other = _ref.other, + _ref$proxy = _ref.proxy, + proxy = _ref$proxy === undefined ? false : _ref$proxy; + + if (!isString(key) && !isArray(key)) throw new TypeError('$watch only accept string and Array<string> as key to find the target to spy on, but not ' + key + ', whose type is ' + (typeof key === 'undefined' ? 'undefined' : _typeof(key))); + var watching = true; + var watcher = function watcher() { + if (watching && (!(this instanceof VideoConfig) || this.dispatcher.changeWatchable)) bind(handler, this).apply(undefined, arguments); + }; + var unwatcher = function unwatcher() { + watching = false; + var index = _this3.__unwatchHandlers.indexOf(unwatcher); + if (index > -1) _this3.__unwatchHandlers.splice(index, 1); + }; + var keys = isString(key) ? key.split('.') : key; + var property = keys.pop(); + var videoConfig = this.__dispatcher.videoConfig; + var target = keys.length === 0 && !other && videoConfig._realDomAttr.indexOf(property) > -1 ? videoConfig : ['isFullScreen', 'fullScreenElement'].indexOf(property) > -1 ? this.__dispatcher.dom : getDeepProperty(other || this, keys, { throwError: true }); + applyDecorators(target, _defineProperty({}, property, watch(watcher, { deep: deep, diff: diff, proxy: proxy })), { self: true }); + this.__unwatchHandlers.push(unwatcher); + return unwatcher; + } + }, { + key: '$set', + value: function $set(obj, property, value) { + if (!isObject(obj) && !isArray(obj)) throw new TypeError('$set only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); + // $FlowFixMe: we have custom this function + if (!isFunction(obj.__set)) { + Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $set.'); + // $FlowFixMe: we support computed string on array here + obj[property] = value; + return; + } + obj.__set(property, value); + } + }, { + key: '$del', + value: function $del(obj, property) { + if (!isObject(obj) && !isArray(obj)) throw new TypeError('$del only support Array or Object, but not ' + obj + ', whose type is ' + (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))); + // $FlowFixMe: we have custom this function + if (!isFunction(obj.__del)) { + Log.warn('chimee', _JSON$stringify(obj) + ' has not been deep watch. There is no need to use $del.'); + // $FlowFixMe: we support computed string on array here + delete obj[property]; + return; + } + obj.__del(property); + } + }, { + key: 'load', + value: function load() { + var _this4 = this; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return new _Promise(function (resolve, reject) { + var _dispatcher$bus2; + + _this4.__dispatcher.bus.once(_this4.__id, '_load', resolve); + (_dispatcher$bus2 = _this4.__dispatcher.bus).emit.apply(_dispatcher$bus2, ['load'].concat(args)); + }); + } + }, { + key: '$silentLoad', + value: function $silentLoad() { + var _this5 = this; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + return this.__dispatcher.bus.emit('silentLoad').then(function () { + var _dispatcher; + + return (_dispatcher = _this5.__dispatcher).silentLoad.apply(_dispatcher, args); + }).then(function (result) { + _this5.__dispatcher.bus.trigger('silentLoad', result); + }); + } + + /** + * call fullscreen api on some specific element + * @param {boolean} flag true means fullscreen and means exit fullscreen + * @param {string} element the element you want to fullscreen, default it's container, you can choose from video | container | wrapper + */ + + }, { + key: '$fullScreen', + value: function $fullScreen() { + var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; + + if (!this.__dispatcher.bus.emitSync('fullScreen', flag, element)) return false; + var result = this.__dispatcher.dom.fullScreen(flag, element); + this.__dispatcher.bus.triggerSync('fullScreen', flag, element); + return result; + } + + /** + * emit an event + * @param {string} key event's name + * @param {...args} args + */ + + }, { + key: '$emit', + value: function $emit(key) { + var _dispatcher$bus3; + + if (!isString(key)) throw new TypeError('emit key parameter must be String'); + if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { + Log.warn('plugin', 'You are try to emit ' + key + ' event. As emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use emitSync'); + } + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + (_dispatcher$bus3 = this.__dispatcher.bus).emit.apply(_dispatcher$bus3, [key].concat(_toConsumableArray(args))); + } + + /** + * emit a sync event + * @param {string} key event's name + * @param {...args} args + */ + + }, { + key: '$emitSync', + value: function $emitSync(key) { + var _dispatcher$bus4; + + if (!isString(key)) throw new TypeError('emitSync key parameter must be String'); + + for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + + return (_dispatcher$bus4 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus4, [key].concat(_toConsumableArray(args))); + } + + /** + * bind event handler through this function + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$on', + value: function $on(key, fn) { + this.__dispatcher.bus.on(this.__id, key, fn); + // set on __events as mark so that i can destroy it when i destroy + this.__addEvents(key, fn); + } + /** + * remove event handler through this function + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$off', + value: function $off(key, fn) { + this.__dispatcher.bus.off(this.__id, key, fn); + this.__removeEvents(key, fn); + } + /** + * bind one time event handler + * @param {string} key event's name + * @param {Function} fn event's handler + */ + + }, { + key: '$once', + value: function $once(key, fn) { + var self = this; + var boundFn = function boundFn() { + bind(fn, this).apply(undefined, arguments); + self.__removeEvents(key, boundFn); + }; + self.__addEvents(key, boundFn); + this.__dispatcher.bus.once(this.__id, key, boundFn); + } + + /** + * set style + * @param {string} element optional, default to be video, you can choose from video | container | wrapper + * @param {string} attribute the atrribue name + * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; + */ + + }, { + key: '$css', + value: function $css(method) { + var _dispatcher$dom2; + + for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + args[_key6 - 1] = arguments[_key6]; + } + + return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom2, args); + } + + /** + * set attr + * @param {string} element optional, default to be video, you can choose from video | container | wrapper + * @param {string} attribute the atrribue nameß + * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; + */ + + }, { + key: '$attr', + value: function $attr(method) { + var _dispatcher$dom3; + + for (var _len7 = arguments.length, args = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + args[_key7 - 1] = arguments[_key7]; + } + + if (method === 'set' && /video/.test(args[0])) { + if (!this.__dispatcher.videoConfigReady) { + Log.warn('chimee', this.__id + ' is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); + return args[2]; + } + if (this.__dispatcher.videoConfig._realDomAttr.indexOf(args[1]) > -1) { + var key = args[1], + val = args[2]; + + this.__dispatcher.videoConfig[key] = val; + return val; + } + } + return (_dispatcher$dom3 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom3, args); + } + }, { + key: '__addEvents', + value: function __addEvents(key, fn) { + this.__events[key] = this.__events[key] || []; + this.__events[key].push(fn); + } + }, { + key: '__removeEvents', + value: function __removeEvents(key, fn) { + if (isEmpty(this.__events[key])) return; + var index = this.__events[key].indexOf(fn); + if (index < 0) return; + this.__events[key].splice(index, 1); + if (isEmpty(this.__events[key])) delete this.__events[key]; + } + }, { + key: '__destroy', + value: function __destroy() { + var _this6 = this; + + this.__unwatchHandlers.forEach(function (unwatcher) { + return unwatcher(); + }); + _Object$keys(this.__events).forEach(function (key) { + if (!isArray(_this6.__events[key])) return; + _this6.__events[key].forEach(function (fn) { + return _this6.$off(key, fn); + }); + }); + delete this.__events; + } + }, { + key: 'currentTime', + get: function get() { + return this.__dispatcher.kernel.currentTime; + }, + set: function set(second) { + this.__dispatcher.bus.emitSync('seek', second); + } + }, { + key: '$plugins', + get: function get() { + return this.__dispatcher.plugins; + } + }, { + key: '$pluginOrder', + get: function get() { + return this.__dispatcher.order; + } + }, { + key: '$wrapper', + get: function get() { + propertyAccessibilityWarn('wrapper'); + return this.__dispatcher.dom.wrapper; + } + }, { + key: '$container', + get: function get() { + propertyAccessibilityWarn('container'); + return this.__dispatcher.dom.container; + } + }, { + key: '$video', + get: function get() { + propertyAccessibilityWarn('video'); + return this.__dispatcher.dom.videoElement; + } + }, { + key: 'isFullScreen', + get: function get() { + return this.__dispatcher.dom.isFullScreen; + } + }, { + key: 'fullScreenElement', + get: function get() { + return this.__dispatcher.dom.fullScreenElement; + } + }]); + + return VideoWrapper; +}(), (_applyDecoratedDescriptor$2(_class2$1.prototype, '$silentLoad', [_dec2$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$silentLoad'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$fullScreen', [_dec3$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$fullScreen'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emit', [_dec4$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emit'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emitSync', [_dec5$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emitSync'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec6, _dec7, _dec8], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec9, _dec10, _dec11], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec12, _dec13], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec14, _dec15], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec16, _dec17], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$pluginOrder'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$wrapper', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$wrapper'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$container', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$container'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$video', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$video'), _class2$1.prototype)), _class2$1)) || _class$3); + +var _dec$2; +var _class$2; + +/** + * <pre> + * Plugin is the class for plugin developer. + * When we use a plugin, we will generate an instance of plugin. + * Developer can do most of things base on this plugin + * </pre> + */ +var Plugin = (_dec$2 = autobindClass(), _dec$2(_class$2 = function (_VideoWrapper) { + _inherits(Plugin, _VideoWrapper); + + /** + * <pre> + * to create a plugin, we need three parameter + * 1. the config of a plugin + * 2. the dispatcher + * 3. this option for plugin to read + * this is the plugin base class, which you can get on Chimee + * You can just extends it and then install + * But in that way you must remember to pass the arguments to super() + * </pre> + * @param {string} PluginConfig.id camelize from plugin's name or class name. + * @param {string} PluginConfig.name plugin's name or class name + * @param {Number} PluginConfig.level the level of z-index + * @param {Boolean} PluginConfig.operable to tell if the plugin can be operable, if not, we will add pointer-events: none on it. + * @param {Function} PluginConfig.create the create function which we will called when plugin is used. sth like constructor in object style. + * @param {Function} PluginConfig.destroy function to be called when we destroy a plugin + * @param {Object} PluginConfig.events You can set some events handler in this object, we will bind it once you use the plugin. + * @param {Object} PluginConfig.data dataset we will bind on data in object style + * @param {Object<{get: Function, set: Function}} PluginConfig.computed dataset we will handle by getter and setter + * @param {Object<Function>} PluginConfig.methods some function we will bind on plugin + * @param {string|HTMLElment} PluginConfig.el can be string or HTMLElement, we will use this to create the dom for plugin + * @param {boolean} PluginConfig.penetrate boolean to let us do we need to forward the dom events for this plugin. + * @param {Dispatcher} dispatcher referrence of dispatcher + * @param {Object} option PluginOption that will pass to the plugin + * @return {Plugin} plugin instance + */ + function Plugin() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + id = _ref.id, + name = _ref.name, + _ref$level = _ref.level, + level = _ref$level === undefined ? 0 : _ref$level, + _ref$operable = _ref.operable, + operable = _ref$operable === undefined ? true : _ref$operable, + beforeCreate = _ref.beforeCreate, + create = _ref.create, + init = _ref.init, + inited = _ref.inited, + destroy = _ref.destroy, + _ref$events = _ref.events, + events = _ref$events === undefined ? {} : _ref$events, + _ref$data = _ref.data, + data = _ref$data === undefined ? {} : _ref$data, + _ref$computed = _ref.computed, + computed = _ref$computed === undefined ? {} : _ref$computed, + _ref$methods = _ref.methods, + methods = _ref$methods === undefined ? {} : _ref$methods, + el = _ref.el, + _ref$penetrate = _ref.penetrate, + penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, + _ref$inner = _ref.inner, inner = _ref$inner === undefined ? true : _ref$inner, autoFocus = _ref.autoFocus, className = _ref.className; @@ -761,9 +1363,8 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de var _this = _possibleConstructorReturn(this, (Plugin.__proto__ || _Object$getPrototypeOf(Plugin)).call(this)); _this.destroyed = false; - _this.VERSION = '0.1.3'; + _this.VERSION = '0.2.0'; _this.__operable = true; - _this.__events = {}; _this.__level = 0; if (isEmpty(dispatcher)) { @@ -926,69 +1527,7 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de }); return this.readySync || this.ready; } - /** - * set style - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: '$css', - value: function $css(method) { - var _dispatcher$dom; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return (_dispatcher$dom = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom, args); - } - /** - * set attr - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: '$attr', - value: function $attr(method) { - var _dispatcher$dom2; - - for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - if (method === 'set' && /video/.test(args[0])) { - if (!this.__dispatcher.videoConfigReady) { - Log.warn('plugin', 'Plugin ' + this.__id + ' is tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); - return args[2]; - } - if (this.$videoConfig._realDomAttr.indexOf(args[1]) > -1) { - var key = args[1], - val = args[2]; - - this.$videoConfig[key] = val; - return val; - } - } - return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom2, args); - } - /** - * call fullscreen api on some specific element - * @param {boolean} flag true means fullscreen and means exit fullscreen - * @param {string} element the element you want to fullscreen, default it's container, you can choose from video | container | wrapper - */ - }, { - key: '$fullScreen', - value: function $fullScreen() { - var flag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; - - return this.__dispatcher.dom.fullScreen(flag, element); - } /** * set the plugin to be the top of all plugins */ @@ -999,89 +1538,6 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de var topLevel = this.__dispatcher._getTopLevel(this.$inner); this.$level = topLevel + 1; } - /** - * bind event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$on', - value: function $on(key, fn) { - this.__dispatcher.bus.on(this.__id, key, fn); - // set on __events as mark so that i can destroy it when i destroy - this.__addEvents(key, fn); - } - /** - * remove event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$off', - value: function $off(key, fn) { - this.__dispatcher.bus.off(this.__id, key, fn); - this.__removeEvents(key, fn); - } - /** - * bind one time event handler - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: '$once', - value: function $once(key, fn) { - var self = this; - var boundFn = function boundFn() { - bind(fn, this).apply(undefined, arguments); - self.__removeEvents(key, boundFn); - }; - self.__addEvents(key, boundFn); - this.__dispatcher.bus.once(this.__id, key, boundFn); - } - /** - * emit an event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: '$emit', - value: function $emit(key) { - var _dispatcher$bus; - - if (!isString(key)) throw new TypeError('$emit key parameter must be String'); - if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { - Log.warn('plugin', 'You are using $emit to emit ' + key + ' event. As $emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use $emitSync'); - } - - for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - (_dispatcher$bus = this.__dispatcher.bus).emit.apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - } - /** - * emit a sync event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: '$emitSync', - value: function $emitSync(key) { - var _dispatcher$bus2; - - if (!isString(key)) throw new TypeError('$emitSync key parameter must be String'); - - for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - return (_dispatcher$bus2 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus2, [key].concat(_toConsumableArray(args))); - } }, { key: '$throwError', value: function $throwError(error) { @@ -1095,47 +1551,13 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de }, { key: '$destroy', value: function $destroy() { - var _this3 = this; - isFunction(this.destroy) && this.destroy(); _get(Plugin.prototype.__proto__ || _Object$getPrototypeOf(Plugin.prototype), '__destroy', this).call(this); - _Object$keys(this.__events).forEach(function (key) { - if (!isArray(_this3.__events[key])) return; - _this3.__events[key].forEach(function (fn) { - return _this3.$off(key, fn); - }); - }); - delete this.__events; this.__dispatcher.dom.removePlugin(this.__id); delete this.__dispatcher; delete this.$dom; this.destroyed = true; } - }, { - key: '__addEvents', - value: function __addEvents(key, fn) { - this.__events[key] = this.__events[key] || []; - this.__events[key].push(fn); - } - }, { - key: '__removeEvents', - value: function __removeEvents(key, fn) { - if (isEmpty(this.__events[key])) return; - var index = this.__events[key].indexOf(fn); - if (index < 0) return; - this.__events[key].splice(index, 1); - if (isEmpty(this.__events[key])) delete this.__events[key]; - } - }, { - key: '$plugins', - get: function get() { - return this.__dispatcher.plugins; - } - }, { - key: '$pluginOrder', - get: function get() { - return this.__dispatcher.order; - } /** * to tell us if the plugin can be operable, can be dynamic change * @type {boolean} @@ -1169,17 +1591,17 @@ var Plugin = (_dec$2 = autobindClass(), _dec2$2 = before(attrAndStyleCheck), _de }]); return Plugin; -}(VideoWrapper), (_applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec2$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec4$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec5$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec6$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [nonenumerable, nonextendable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$pluginOrder'), _class2$1.prototype)), _class2$1)) || _class$2); +}(VideoWrapper)) || _class$2); -var _dec$3; +var _dec$5; var _dec2$3; -var _dec3$3; -var _dec4$3; -var _dec5$3; -var _dec6$2; -var _class$3; +var _dec3$2; +var _dec4$2; +var _dec5$2; +var _dec6$1; +var _class$5; -function _applyDecoratedDescriptor$3(target, property, decorators, descriptor, context) { +function _applyDecoratedDescriptor$4(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; @@ -1229,7 +1651,7 @@ function attrOperationCheck(target, attr, val) { * It take charge of dom management of Dispatcher. * </pre> */ -var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before(attrOperationCheck, targetCheck), _dec3$3 = before(attrOperationCheck, targetCheck), _dec4$3 = before(attrOperationCheck, targetCheck), _dec5$3 = before(attrOperationCheck, targetCheck), _dec6$2 = before(targetCheck), (_class$3 = function () { +var Dom = (_dec$5 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before(attrOperationCheck, targetCheck), _dec3$2 = before(attrOperationCheck, targetCheck), _dec4$2 = before(attrOperationCheck, targetCheck), _dec5$2 = before(attrOperationCheck, targetCheck), _dec6$1 = before(targetCheck), (_class$5 = function () { /** * to mark is the mouse in the video area * @type {boolean} @@ -1266,6 +1688,8 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before this.__domEventHandlerList = {}; this.__mouseInVideo = false; this.__videoExtendedNodes = []; + this.isFullScreen = false; + this.fullScreenElement = undefined; this.__dispatcher = dispatcher; if (!isElement(wrapper) && !isString(wrapper)) throw new TypeError('Illegal wrapper'); @@ -1290,77 +1714,14 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before * referrence of video's dom element * @type {Element} */ - this.videoElement = videoElement; - this.__videoExtendedNodes.push(videoElement); - this.setAttr('videoElement', 'tabindex', -1); - this._autoFocusToVideo(this.videoElement); - // create container - if (this.videoElement.parentElement && isElement(this.videoElement.parentElement) && this.videoElement.parentElement !== this.wrapper) { - this.container = this.videoElement.parentElement; - } else { - this.container = document.createElement('container'); - $(this.container).append(this.videoElement); - } - // check container.position - if (this.container.parentElement !== this.wrapper) { - $wrapper.append(this.container); - } - videoEvents.forEach(function (key) { - var fn = function fn() { - var _dispatcher$bus; - - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - return (_dispatcher$bus = _this.__dispatcher.bus).trigger.apply(_dispatcher$bus, [key].concat(args)); - }; - _this.videoEventHandlerList.push(fn); - addEvent(_this.videoElement, key, fn); - }); + this.installVideo(videoElement); domEvents.forEach(function (key) { var fn = _this._getEventHandler(key, { penetrate: true }); _this.videoDomEventHandlerList.push(fn); addEvent(_this.videoElement, key, fn); - var cfn = function cfn() { - var _dispatcher$bus2; - - for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - - return (_dispatcher$bus2 = _this.__dispatcher.bus).triggerSync.apply(_dispatcher$bus2, ['c_' + key].concat(args)); - }; - _this.containerDomEventHandlerList.push(cfn); - addEvent(_this.container, key, cfn); - var wfn = function wfn() { - var _dispatcher$bus3; - - for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - - return (_dispatcher$bus3 = _this.__dispatcher.bus).triggerSync.apply(_dispatcher$bus3, ['w_' + key].concat(args)); - }; - _this.wrapperDomEventHandlerList.push(wfn); - addEvent(_this.wrapper, key, wfn); }); + this._bindFullScreen(); } - /** - * <pre> - * each plugin has its own dom node, this function will create one or them. - * we support multiple kind of el - * 1. Element, we will append this dom node on wrapper straight - * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper - * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper - * 4. nothing, we will create a div and bind it on the wrapper - * </pre> - * @param {string} id plugin's id - * @param {string|Element} el(optional) the el can be custom dom element or html string to insert - * @param {boolean} inner if it's true, we will put it into conatiner, else we would put it into outer - * @return {Node} - */ - /** * Object to store different plugin's dom event handlers * @type {Object} @@ -1391,9 +1752,90 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before _createClass(Dom, [{ + key: 'installVideo', + value: function installVideo(videoElement) { + var _this2 = this; + + this.__videoExtendedNodes.push(videoElement); + setAttr(videoElement, 'tabindex', -1); + this._autoFocusToVideo(videoElement); + if (!isElement(this.container)) { + // create container + if (videoElement.parentElement && isElement(videoElement.parentElement) && videoElement.parentElement !== this.wrapper) { + this.container = videoElement.parentElement; + } else { + this.container = document.createElement('container'); + $(this.container).append(videoElement); + } + } else { + var container = this.container; + if (container.childNodes.length === 0) { + container.appendChild(videoElement); + } else { + container.insertBefore(videoElement, container.childNodes[0]); + } + } + // check container.position + if (this.container.parentElement !== this.wrapper) { + $(this.wrapper).append(this.container); + } + videoEvents.forEach(function (key) { + var fn = function fn() { + var _dispatcher$bus; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return (_dispatcher$bus = _this2.__dispatcher.bus).trigger.apply(_dispatcher$bus, [key].concat(args)); + }; + _this2.videoEventHandlerList.push(fn); + addEvent(videoElement, key, fn); + }); + domEvents.forEach(function (key) { + var fn = _this2._getEventHandler(key, { penetrate: true }); + _this2.videoDomEventHandlerList.push(fn); + addEvent(videoElement, key, fn); + }); + this.videoElement = videoElement; + return videoElement; + } + }, { + key: 'removeVideo', + value: function removeVideo() { + var _this3 = this; + + var videoElement = this.videoElement; + this._autoFocusToVideo(this.videoElement, false); + videoEvents.forEach(function (key, index) { + removeEvent(_this3.videoElement, key, _this3.videoEventHandlerList[index]); + }); + domEvents.forEach(function (key, index) { + removeEvent(_this3.videoElement, key, _this3.videoDomEventHandlerList[index]); + }); + $(videoElement).remove(); + delete this.videoElement; + return videoElement; + } + /** + * <pre> + * each plugin has its own dom node, this function will create one or them. + * we support multiple kind of el + * 1. Element, we will append this dom node on wrapper straight + * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper + * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper + * 4. nothing, we will create a div and bind it on the wrapper + * </pre> + * @param {string} id plugin's id + * @param {string|Element} el(optional) the el can be custom dom element or html string to insert + * @param {boolean} inner if it's true, we will put it into conatiner, else we would put it into outer + * @return {Node} + */ + + }, { key: 'insertPlugin', value: function insertPlugin(id, el) { - var _this2 = this; + var _this4 = this; var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -1435,9 +1877,9 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before if (penetrate) { this.__domEventHandlerList[id] = this.__domEventHandlerList[id] || []; domEvents.forEach(function (key) { - var fn = _this2._getEventHandler(key, { penetrate: penetrate }); + var fn = _this4._getEventHandler(key, { penetrate: penetrate }); addEvent(node, key, fn); - _this2.__domEventHandlerList[id].push(fn); + _this4.__domEventHandlerList[id].push(fn); }); this.__videoExtendedNodes.push(node); } @@ -1456,7 +1898,7 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: 'removePlugin', value: function removePlugin(id) { - var _this3 = this; + var _this5 = this; if (!isString(id)) return; var dom = this.plugins[id]; @@ -1466,7 +1908,7 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before } if (!isEmpty(this.__domEventHandlerList[id])) { domEvents.forEach(function (key, index) { - removeEvent(_this3.plugins[id], key, _this3.__domEventHandlerList[id][index]); + removeEvent(_this5.plugins[id], key, _this5.__domEventHandlerList[id][index]); }); delete this.__domEventHandlerList[id]; } @@ -1480,11 +1922,11 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: 'setPluginsZIndex', value: function setPluginsZIndex(plugins) { - var _this4 = this; + var _this6 = this; // $FlowFixMe: there are videoElment and container here plugins.forEach(function (key, index) { - return setStyle(key.match(/^(videoElement|container)$/) ? _this4[key] : _this4.plugins[key], 'z-index', ++index); + return setStyle(key.match(/^(videoElement|container)$/) ? _this6[key] : _this6.plugins[key], 'z-index', ++index); }); } /** @@ -1552,8 +1994,8 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before var request = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'container'; - for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { - args[_key5 - 2] = arguments[_key5]; + for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { + args[_key3 - 2] = arguments[_key3]; } return request ? this.requestFullScreen.apply(this, [target].concat(_toConsumableArray(args))) : this.exitFullScreen.apply(this, _toConsumableArray(args)); @@ -1570,20 +2012,16 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before }, { key: 'destroy', value: function destroy() { - var _this5 = this; + var _this7 = this; - this._autoFocusToVideo(this.videoElement, false); - videoEvents.forEach(function (key, index) { - removeEvent(_this5.videoElement, key, _this5.videoEventHandlerList[index]); - }); + this.removeVideo(); domEvents.forEach(function (key, index) { - removeEvent(_this5.videoElement, key, _this5.videoDomEventHandlerList[index]); - removeEvent(_this5.container, key, _this5.containerDomEventHandlerList[index]); - removeEvent(_this5.wrapper, key, _this5.wrapperDomEventHandlerList[index]); + removeEvent(_this7.container, key, _this7.containerDomEventHandlerList[index]); + removeEvent(_this7.wrapper, key, _this7.wrapperDomEventHandlerList[index]); }); + this._bindFullScreen(true); this.wrapper.innerHTML = this.originHTML; delete this.wrapper; - delete this.videoElement; delete this.plugins; } }, { @@ -1602,368 +2040,96 @@ var Dom = (_dec$3 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before isFunction(this.videoElement.focus) && this.videoElement.focus(); window.scrollTo(x, y); } - /** - * get the event handler for dom to bind - */ - }, { - key: '_getEventHandler', - value: function _getEventHandler(key, _ref) { - var _this6 = this; - - var penetrate = _ref.penetrate; - - if (!penetrate || ['mouseenter', 'mouseleave'].indexOf(key) < 0) { - return function () { - var _dispatcher$bus4; - - for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - - (_dispatcher$bus4 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, [key].concat(args)); - }; - } - var insideVideo = function insideVideo(node) { - return _this6.__videoExtendedNodes.indexOf(node) > -1 || _this6.__videoExtendedNodes.reduce(function (flag, video) { - if (flag) return flag; - return isPosterityNode(video, node); - }, false); - }; - return function () { - for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; - } - - var _args$ = args[0], - toElement = _args$.toElement, - currentTarget = _args$.currentTarget, - relatedTarget = _args$.relatedTarget, - type = _args$.type; - - var to = toElement || relatedTarget; - if (_this6.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { - var _dispatcher$bus5; - - _this6.__mouseInVideo = false; - return (_dispatcher$bus5 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus5, ['mouseleave'].concat(args)); - } - if (!_this6.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { - var _dispatcher$bus6; - - _this6.__mouseInVideo = true; - return (_dispatcher$bus6 = _this6.__dispatcher.bus).triggerSync.apply(_dispatcher$bus6, ['mouseenter'].concat(args)); - } - }; - } - }]); - - return Dom; -}(), (_applyDecoratedDescriptor$3(_class$3.prototype, 'setAttr', [_dec$3, _dec2$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'setAttr'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'getAttr', [_dec3$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'getAttr'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'setStyle', [_dec4$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'setStyle'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'getStyle', [_dec5$3], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'getStyle'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, 'requestFullScreen', [_dec6$2], _Object$getOwnPropertyDescriptor(_class$3.prototype, 'requestFullScreen'), _class$3.prototype), _applyDecoratedDescriptor$3(_class$3.prototype, '_focusToVideo', [autobind], _Object$getOwnPropertyDescriptor(_class$3.prototype, '_focusToVideo'), _class$3.prototype)), _class$3)); - -var _dec$4; -var _dec2$4; -var _dec3$4; -var _class$4; -var _descriptor$1; -var _descriptor2$1; -var _descriptor3$1; -var _descriptor4; -var _descriptor5; -var _descriptor6; -var _descriptor7; - -function _initDefineProp$1(target, property, descriptor, context) { - if (!descriptor) return; - - _Object$defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor$4(target, property, decorators, descriptor, context) { - var desc = {}; - Object['ke' + 'ys'](descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object['define' + 'Property'](target, property, desc); - desc = null; - } - - return desc; -} - -function numberOrVoid(value) { - return isNumber(value) ? value : undefined; -} -function stringOrVoid(value) { - return isString(value) ? value : undefined; -} - -function accessorVideoProperty(property) { - return accessor({ - get: function get(value) { - return this.dispatcher.videoConfigReady && this.inited ? this.videoElement[property] : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - this.videoElement[property] = value; - return value; - } - }); -} - -function accessorVideoAttribute(attribute) { - var _ref = isObject(attribute) ? attribute : { - set: attribute, - get: attribute, - isBoolean: false - }, - _set = _ref.set, - _get$$1 = _ref.get, - isBoolean$$1 = _ref.isBoolean; - - return accessor({ - get: function get(value) { - return this.dispatcher.videoConfigReady && this.inited ? this.videoElement[_get$$1] : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - var val = isBoolean$$1 ? value ? '' : undefined : value; - this.dispatcher.dom.setAttr('video', _set, val); - return value; - } - }); -} - -function accessorCustomAttribute(attribute, isBoolean$$1) { - return accessor({ - get: function get(value) { - var attrValue = this.dispatcher.dom.getAttr('video', attribute); - return this.dispatcher.videoConfigReady && this.inited ? isBoolean$$1 ? !!attrValue : attrValue : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - var val = isBoolean$$1 ? value || undefined : value; - this.dispatcher.dom.setAttr('video', attribute, val); - return value; - } - }); -} - -var accessorMap = { - src: [alwaysString(), accessor({ - set: function set(val) { - if (this.needToLoadSrc) { - // unlock it at first, to avoid deadlock - this.needToLoadSrc = false; - this.dispatcher.bus.emit('load', val); + key: '_fullScreenMonitor', + value: function _fullScreenMonitor() { + var element = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullScreenElement', 'msFullscreenElement'].reduce(function (element, key) { + // $FlowFixMe: support computed element on document + return element || document[key]; + }, null); + if (!element || !isPosterityNode(this.wrapper, element) && element !== this.wrapper) { + this.isFullScreen = false; + this.fullScreenElement = undefined; + return; } - return val; - } - }, { preSet: false }), accessor({ - set: function set(val) { - // must check val !== this.src here - // as we will set config.src in the video - // the may cause dead lock - if (this.dispatcher.readySync && this.autoload && val !== this.src) this.needToLoadSrc = true; - return val; - } - })], - autoload: alwaysBoolean(), - autoplay: [alwaysBoolean(), accessorVideoProperty('autoplay')], - controls: [alwaysBoolean(), accessorVideoProperty('controls')], - width: [accessor({ set: numberOrVoid }), accessorVideoAttribute('width')], - height: [accessor({ set: numberOrVoid }), accessorVideoAttribute('height')], - crossOrigin: [accessor({ set: stringOrVoid }), accessorVideoAttribute({ set: 'crossorigin', get: 'crossOrigin' })], - loop: [alwaysBoolean(), accessorVideoProperty('loop')], - defaultMuted: [alwaysBoolean(), accessorVideoAttribute({ get: 'defaultMuted', set: 'muted', isBoolean: true })], - muted: [alwaysBoolean(), accessorVideoProperty('muted')], - preload: [accessor({ set: stringOrVoid }), accessorVideoAttribute('preload')], - poster: [accessor({ set: stringOrVoid }), accessorVideoAttribute('poster')], - playsInline: [accessor({ - get: function get(value) { - var playsInline = this.videoElement.playsInline; - return this.dispatcher.videoConfigReady && this.inited ? playsInline === undefined ? value : playsInline : value; - }, - set: function set(value) { - if (!this.dispatcher.videoConfigReady) return value; - this.videoElement.playsInline = value; - var val = value ? '' : undefined; - this.dispatcher.dom.setAttr('video', 'playsinline', val); - this.dispatcher.dom.setAttr('video', 'webkit-playsinline', val); - this.dispatcher.dom.setAttr('video', 'x5-video-player-type', value ? 'h5' : undefined); - return value; - } - }), alwaysBoolean()], - x5VideoPlayerFullScreen: [accessor({ - set: function set(value) { - return !!value; - }, - get: function get(value) { - return !!value; - } - }), accessorCustomAttribute('x5-video-player-fullscreen', true)], - x5VideoOrientation: [accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], - xWebkitAirplay: [accessor({ - set: function set(value) { - return !!value; - }, - get: function get(value) { - return !!value; + this.isFullScreen = true; + this.fullScreenElement = this.wrapper === element ? 'wrapper' : this.container === element ? 'container' : this.videoElement === element ? 'video' : element; } - }), accessorCustomAttribute('x-webkit-airplay', true)], - playbackRate: [alwaysNumber(1), accessorVideoProperty('playbackRate')], - defaultPlaybackRate: [accessorVideoProperty('defaultPlaybackRate'), alwaysNumber(1)], - disableRemotePlayback: [alwaysBoolean(), accessorVideoProperty('disableRemotePlayback')], - volume: [alwaysNumber(1), accessorVideoProperty('volume')] -}; + }, { + key: '_bindFullScreen', + value: function _bindFullScreen(remove) { + var _this8 = this; -var VideoConfig = (_dec$4 = initString(), _dec2$4 = initString(function (str) { - return str.toLocaleLowerCase(); -}), _dec3$4 = initArray(), (_class$4 = function () { - _createClass(VideoConfig, [{ - key: 'lockKernelProperty', - value: function lockKernelProperty() { - applyDecorators(this, { - type: lock, - box: lock, - runtimeOrder: lock - }, { self: true }); + if (!remove) this._fullScreenMonitor(); + ['webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange', 'fullscreenchange'].forEach(function (key) { + // $FlowFixMe: support computed element on document + document[(remove ? 'remove' : 'add') + 'EventListener'](key, _this8._fullScreenMonitor); + }); } - }]); - - function VideoConfig(dispatcher, config) { - _classCallCheck(this, VideoConfig); - - _initDefineProp$1(this, 'needToLoadSrc', _descriptor$1, this); - - _initDefineProp$1(this, 'inited', _descriptor2$1, this); - - this.src = ''; - - _initDefineProp$1(this, 'type', _descriptor3$1, this); - - _initDefineProp$1(this, 'box', _descriptor4, this); - - _initDefineProp$1(this, 'runtimeOrder', _descriptor5, this); - - this.autoload = true; - this.autoplay = false; - this.controls = false; - this.width = undefined; - this.height = undefined; - this.crossOrigin = undefined; - this.loop = false; - this.defaultMuted = false; - this.muted = false; - this.preload = 'auto'; - this.poster = undefined; - this.playsInline = false; - this.x5VideoPlayerFullScreen = false; - this.x5VideoOrientation = undefined; - this.xWebkitAirplay = false; - this.playbackRate = 1; - this.defaultPlaybackRate = 1; - this.disableRemotePlayback = false; - this.volume = 1; + /** + * get the event handler for dom to bind + */ - _initDefineProp$1(this, '_kernelProperty', _descriptor6, this); + }, { + key: '_getEventHandler', + value: function _getEventHandler(key, _ref) { + var _this9 = this; - _initDefineProp$1(this, '_realDomAttr', _descriptor7, this); + var penetrate = _ref.penetrate; - applyDecorators(this, accessorMap, { self: true }); - Object.defineProperty(this, 'dispatcher', { - value: dispatcher, - enumerable: false, - writable: false, - configurable: false - }); - Object.defineProperty(this, 'videoElement', { - value: dispatcher.dom.videoElement, - enumerable: false, - writable: false, - configurable: false - }); - deepAssign(this, config); - } + if (!penetrate || ['mouseenter', 'mouseleave'].indexOf(key) < 0) { + return function () { + var _dispatcher$bus2; - _createClass(VideoConfig, [{ - key: 'init', - value: function init() { - var _this = this; + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } - this._realDomAttr.forEach(function (key) { - // $FlowFixMe: we have check the computed here - _this[key] = _this[key]; - }); - this.inited = true; + (_dispatcher$bus2 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus2, [key].concat(args)); + }; + } + var insideVideo = function insideVideo(node) { + return _this9.__videoExtendedNodes.indexOf(node) > -1 || _this9.__videoExtendedNodes.reduce(function (flag, video) { + if (flag) return flag; + return isPosterityNode(video, node); + }, false); + }; + return function () { + for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + + var _args$ = args[0], + toElement = _args$.toElement, + currentTarget = _args$.currentTarget, + relatedTarget = _args$.relatedTarget, + type = _args$.type; + + var to = toElement || relatedTarget; + if (_this9.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { + var _dispatcher$bus3; + + _this9.__mouseInVideo = false; + return (_dispatcher$bus3 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus3, ['mouseleave'].concat(args)); + } + if (!_this9.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { + var _dispatcher$bus4; + + _this9.__mouseInVideo = true; + return (_dispatcher$bus4 = _this9.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, ['mouseenter'].concat(args)); + } + }; } }]); - return VideoConfig; -}(), (_descriptor$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'needToLoadSrc', [nonenumerable], { - enumerable: true, - initializer: function initializer() { - return false; - } -}), _descriptor2$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'inited', [nonenumerable], { - enumerable: true, - initializer: function initializer() { - return false; - } -}), _descriptor3$1 = _applyDecoratedDescriptor$4(_class$4.prototype, 'type', [_dec$4, configurable], { - enumerable: true, - initializer: function initializer() { - return 'vod'; - } -}), _descriptor4 = _applyDecoratedDescriptor$4(_class$4.prototype, 'box', [_dec2$4, configurable], { - enumerable: true, - initializer: function initializer() { - return ''; - } -}), _descriptor5 = _applyDecoratedDescriptor$4(_class$4.prototype, 'runtimeOrder', [_dec3$4, configurable], { - enumerable: true, - initializer: function initializer() { - return ['html5', 'flash']; - } -}), _descriptor6 = _applyDecoratedDescriptor$4(_class$4.prototype, '_kernelProperty', [frozen], { - enumerable: true, - initializer: function initializer() { - return ['type', 'box', 'runtimeOrder']; - } -}), _descriptor7 = _applyDecoratedDescriptor$4(_class$4.prototype, '_realDomAttr', [frozen], { - enumerable: true, - initializer: function initializer() { - return ['src', 'controls', 'width', 'height', 'crossOrigin', 'loop', 'muted', 'preload', 'poster', 'autoplay', 'playsInline', 'x5VideoPlayerFullScreen', 'x5VideoOrientation', 'xWebkitAirplay', 'playbackRate', 'defaultPlaybackRate', 'autoload', 'disableRemotePlayback', 'defaultMuted', 'volume']; - } -})), _class$4)); + return Dom; +}(), (_applyDecoratedDescriptor$4(_class$5.prototype, 'setAttr', [_dec$5, _dec2$3], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'setAttr'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'getAttr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'getAttr'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'setStyle', [_dec4$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'setStyle'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'getStyle', [_dec5$2], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'getStyle'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'requestFullScreen', [_dec6$1], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'requestFullScreen'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, '_focusToVideo', [autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, '_focusToVideo'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, '_fullScreenMonitor', [autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, '_fullScreenMonitor'), _class$5.prototype)), _class$5)); var _dec$1; -var _dec2$1; -var _dec3$1; -var _dec4$1; -var _dec5$1; +var _dec2; +var _dec3; +var _dec4; +var _dec5; var _class$1; function _applyDecoratedDescriptor$1(target, property, decorators, descriptor, context) { @@ -2019,7 +2185,7 @@ function checkPluginConfig(config) { * It also offer a bridge to let user handle video kernel. * </pre> */ -var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPluginConfig), _dec3$1 = before(convertNameIntoId), _dec4$1 = before(convertNameIntoId), _dec5$1 = before(convertNameIntoId), (_class$1 = function () { +var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2 = before(checkPluginConfig), _dec3 = before(convertNameIntoId), _dec4 = before(convertNameIntoId), _dec5 = before(convertNameIntoId), (_class$1 = function () { /** * @param {UserConfig} config UserConfig for whole Chimee player * @param {Chimee} vm referrence of outer class @@ -2027,15 +2193,15 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug */ /** - * the synchronous ready flag - * @type {boolean} - * @member readySync + * the z-index map of the dom, it contain some important infomation + * @type {Object} + * @member zIndexMap */ /** - * all plugins instance set - * @type {Object} - * @member plugins + * plugin's order + * @type {Array<string>} + * @member order */ function Dispatcher(config, vm) { var _this = this; @@ -2049,6 +2215,7 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug inner: [], outer: [] }; + this.changeWatchable = true; if (!isObject(config)) throw new TypeError('UserConfig must be an Object'); /** @@ -2109,15 +2276,15 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug */ /** - * the z-index map of the dom, it contain some important infomation - * @type {Object} - * @member zIndexMap + * the synchronous ready flag + * @type {boolean} + * @member readySync */ /** - * plugin's order - * @type {Array<string>} - * @member order + * all plugins instance set + * @type {Object} + * @member plugins */ @@ -2183,6 +2350,186 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug value: function throwError(error) { this.vm.__throwError(error); } + }, { + key: 'silentLoad', + value: function silentLoad(src) { + var _this2 = this; + + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _option$duration = option.duration, + duration = _option$duration === undefined ? 3 : _option$duration, + _option$bias = option.bias, + bias = _option$bias === undefined ? 0 : _option$bias, + _option$repeatTimes = option.repeatTimes, + repeatTimes = _option$repeatTimes === undefined ? 0 : _option$repeatTimes, + _option$increment = option.increment, + increment = _option$increment === undefined ? 0 : _option$increment, + _option$isLive = option.isLive, + isLive = _option$isLive === undefined ? this.videoConfig.isLive : _option$isLive, + _option$box = option.box, + box = _option$box === undefined ? this.videoConfig.box : _option$box, + _option$preset = option.preset, + preset = _option$preset === undefined ? this.videoConfig.preset : _option$preset; + // form the base config for kernel + // it should be the same as the config now + + var config = { isLive: isLive, box: box, src: src, preset: preset }; + // build tasks accroding repeat times + var tasks = new Array(repeatTimes + 1).fill(1).map(function (value, index) { + return function () { + return new _Promise(function (resolve, reject) { + // if abort, give up and reject + if (option.abort) reject({ error: true, message: 'user abort the mission' }); + var video = document.createElement('video'); + var idealTime = _this2.kernel.currentTime + duration + increment * index; + video.muted = true; + var newVideoReady = false; + // bind time update on old video + // when we bump into the switch point and ready + // we switch + var oldVideoTimeupdate = function oldVideoTimeupdate(evt) { + var currentTime = _this2.kernel.currentTime; + if (bias <= 0 && currentTime >= idealTime || bias > 0 && (Math.abs(idealTime - currentTime) <= bias && newVideoReady || currentTime - idealTime > bias)) { + removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + if (!newVideoReady) { + removeEvent(video, 'canplay', videoCanplay); + removeEvent(video, 'loadedmetadata', videoLoadedmetadata); + removeEvent(video, 'error', videoError); + kernel.destroy(); + return resolve(); + } + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + var videoCanplay = function videoCanplay(evt) { + newVideoReady = true; + // you can set it immediately run by yourself + if (option.immediate) { + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + var videoLoadedmetadata = function videoLoadedmetadata(evt) { + kernel.seek(idealTime); + }; + var videoError = function videoError(evt) { + removeEvent(video, 'canplay', videoCanplay, true); + removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + var error = !isEmpty(video.error) ? new Error(video.error.message) : new Error('unknow video error'); + Log.error("chimee's silentload", error.message); + kernel.destroy(); + return index === repeatTimes ? reject(error) : resolve(error); + }; + addEvent(video, 'canplay', videoCanplay, true); + addEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + addEvent(video, 'error', videoError, true); + addEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + var kernel = new Kernel(video, config); + kernel.load(); + }); + }; + }); + return runRejectableQueue(tasks).then(function () { + var message = 'The silentLoad for ' + src + ' timed out. Please set a longer duration or check your network'; + Log.warn("chimee's silentLoad", message); + return _Promise.reject(new Error(message)); + }).catch(function (data) { + if (isError(data)) { + return _Promise.reject(data); + } + if (data.error) { + Log.warn("chimee's silentLoad", data.message); + return _Promise.reject(new Error(data.message)); + } + var video = data.video, + kernel = data.kernel; + + if (option.abort) { + kernel.destroy(); + return _Promise.reject(new Error('user abort the mission')); + } + var paused = _this2.dom.videoElement.paused; + _this2.switchKernel({ video: video, kernel: kernel, config: config }); + if (!paused) _this2.dom.videoElement.play(); + return _Promise.resolve(); + }); + } + }, { + key: 'load', + value: function load(src) { + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!isEmpty(option)) { + var videoConfig = this.videoConfig; + + var _option$isLive2 = option.isLive, + _isLive = _option$isLive2 === undefined ? videoConfig.isLive : _option$isLive2, + _option$box2 = option.box, + _box = _option$box2 === undefined ? videoConfig.box : _option$box2, + _option$preset2 = option.preset, + _preset = _option$preset2 === undefined ? videoConfig.preset : _option$preset2; + + var video = document.createElement('video'); + var config = { isLive: _isLive, box: _box, preset: _preset, src: src }; + var _kernel = new Kernel(video, config); + this.switchKernel({ video: video, kernel: _kernel, config: config }); + } + this.kernel.load(src); + } + }, { + key: 'switchKernel', + value: function switchKernel(_ref) { + var _this3 = this; + + var video = _ref.video, + kernel = _ref.kernel, + config = _ref.config; + + var oldKernel = this.kernel; + oldKernel.destroy(); + var originVideoConfig = deepClone(this.videoConfig); + this.dom.removeVideo(); + this.dom.installVideo(video); + // as we will reset the currentVideoConfig on the new video + // it will trigger the watch function as they maybe differnet + // so we need to stop them + this.videoConfig.changeWatchable = false; + this.videoConfig.autoload = false; + this.videoConfig.src = config.src; + this.videoConfig._realDomAttr.forEach(function (key) { + // $FlowFixMe: support computed key here + if (key !== 'src') _this3.videoConfig[key] = originVideoConfig[key]; + }); + this.videoConfig.changeWatchable = true; + // bind the new config in new kernel to the videoConfig + applyDecorators(config, { + src: accessor({ + get: function get(value) { + return _this3.videoConfig.src; + }, + set: function set(value) { + _this3.videoConfig.src = value; + return value; + } + }) + }, { self: true }); + // the kernel's inner config would not be change according what we do + // so we have to load that + // applyDecorators(kernel.__proto__, { + // load: before(src => { + // return [src || this.videoConfig.src]; + // }) + // }, {self: true}); + this.kernel = kernel; + } /** * destroy function called when dispatcher destroyed */ @@ -2212,7 +2559,7 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug }, { key: '_initUserPlugin', value: function _initUserPlugin() { - var _this2 = this; + var _this4 = this; var configs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; @@ -2221,7 +2568,7 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug configs = []; } return configs.map(function (config) { - return _this2.use(config); + return _this4.use(config); }); } /** @@ -2231,10 +2578,10 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug }, { key: '_sortZIndex', value: function _sortZIndex() { - var _this3 = this; + var _this5 = this; var _order$reduce = this.order.reduce(function (levelSet, key) { - var plugin = _this3.plugins[key]; + var plugin = _this5.plugins[key]; if (isEmpty(plugin)) return levelSet; var set = levelSet[plugin.$inner ? 'inner' : 'outer']; var level = plugin.$level; @@ -2315,9 +2662,9 @@ var Dispatcher = (_dec$1 = before(convertNameIntoId), _dec2$1 = before(checkPlug }]); return Dispatcher; -}(), (_applyDecoratedDescriptor$1(_class$1.prototype, 'unuse', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'unuse'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1, 'install', [_dec2$1], _Object$getOwnPropertyDescriptor(_class$1, 'install'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'hasInstalled', [_dec3$1], _Object$getOwnPropertyDescriptor(_class$1, 'hasInstalled'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'uninstall', [_dec4$1], _Object$getOwnPropertyDescriptor(_class$1, 'uninstall'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'getPluginConfig', [_dec5$1], _Object$getOwnPropertyDescriptor(_class$1, 'getPluginConfig'), _class$1)), _class$1)); +}(), (_applyDecoratedDescriptor$1(_class$1.prototype, 'unuse', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'unuse'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1, 'install', [_dec2], _Object$getOwnPropertyDescriptor(_class$1, 'install'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'hasInstalled', [_dec3], _Object$getOwnPropertyDescriptor(_class$1, 'hasInstalled'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'uninstall', [_dec4], _Object$getOwnPropertyDescriptor(_class$1, 'uninstall'), _class$1), _applyDecoratedDescriptor$1(_class$1, 'getPluginConfig', [_dec5], _Object$getOwnPropertyDescriptor(_class$1, 'getPluginConfig'), _class$1)), _class$1)); -var _class$5; +var _class$6; var _descriptor$2; function _initDefineProp$2(target, property, descriptor, context) { @@ -2360,7 +2707,7 @@ function _applyDecoratedDescriptor$5(target, property, decorators, descriptor, c return desc; } -var GlobalConfig = (_class$5 = function () { +var GlobalConfig = (_class$6 = function () { _createClass(GlobalConfig, [{ key: 'silent', get: function get() { @@ -2411,21 +2758,14 @@ var GlobalConfig = (_class$5 = function () { } return GlobalConfig; -}(), (_descriptor$2 = _applyDecoratedDescriptor$5(_class$5.prototype, '_silent', [nonenumerable], { +}(), (_descriptor$2 = _applyDecoratedDescriptor$5(_class$6.prototype, '_silent', [nonenumerable], { enumerable: true, initializer: function initializer() { return false; } -})), _class$5); +})), _class$6); var _dec; -var _dec2; -var _dec3; -var _dec4; -var _dec5; -var _dec6; -var _dec7; -var _dec8; var _class; var _class2; var _descriptor; @@ -2480,7 +2820,7 @@ function _applyDecoratedDescriptor(target, property, decorators, descriptor, con return desc; } -var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = before(eventBinderCheck), _dec4 = before(eventBinderCheck), _dec5 = alias('removeEventListener'), _dec6 = before(eventBinderCheck), _dec7 = before(attrAndStyleCheck), _dec8 = before(attrAndStyleCheck), _dec(_class = (_class2 = (_temp = _class3 = function (_VideoWrapper) { +var Chimee = (_dec = autobindClass(), _dec(_class = (_class2 = (_temp = _class3 = function (_VideoWrapper) { _inherits(Chimee, _VideoWrapper); function Chimee(config) { @@ -2531,133 +2871,6 @@ var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = value: function unuse(name) { this.__dispatcher.unuse(name); } - /** - * bind event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'on', - value: function on(key, fn) { - this.__dispatcher.bus.on('_vm', key, fn); - return this; - } - /** - * remove event handler through this function - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'off', - value: function off(key, fn) { - return this.__dispatcher.bus.off('_vm', key, fn); - } - /** - * bind one time event handler - * @param {string} key event's name - * @param {Function} fn event's handler - */ - - }, { - key: 'once', - value: function once(key, fn) { - return this.__dispatcher.bus.once('_vm', key, fn); - } - /** - * emit an event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: 'emit', - value: function emit(key) { - var _dispatcher$bus; - - if (!isString(key)) throw new TypeError('emit key parameter must be String'); - if (domEvents.indexOf(key.replace(/^\w_/, '')) > -1) { - Log.warn('plugin', 'You are using emit to emit ' + key + ' event. As emit is wrapped in Promise. It make you can\'t use event.preventDefault and event.stopPropagation. So we advice you to use emitSync'); - } - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return (_dispatcher$bus = this.__dispatcher.bus).emit.apply(_dispatcher$bus, [key].concat(_toConsumableArray(args))); - } - /** - * emit a sync event - * @param {string} key event's name - * @param {...args} args - */ - - }, { - key: 'emitSync', - value: function emitSync(key) { - var _dispatcher$bus2; - - if (!isString(key)) throw new TypeError('emitSync key parameter must be String'); - - for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - return (_dispatcher$bus2 = this.__dispatcher.bus).emitSync.apply(_dispatcher$bus2, [key].concat(_toConsumableArray(args))); - } - /** - * set style - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue name - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: 'css', - value: function css(method) { - var _dispatcher$dom; - - for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - // $FlowFixMe: we support this here - return (_dispatcher$dom = this.__dispatcher.dom)[method + 'Style'].apply(_dispatcher$dom, args); - } - /** - * set attr - * @param {string} element optional, default to be video, you can choose from video | container | wrapper - * @param {string} attribute the atrribue nameß - * @param {any} value optional, when it's no offer, we consider you want to get the attribute's value. When it's offered, we consider you to set the attribute's value, if the value you passed is undefined, that means you want to remove the value; - */ - - }, { - key: 'attr', - value: function attr(method) { - var _dispatcher$dom2; - - for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - if (method === 'set' && /video/.test(args[0])) { - if (!this.__dispatcher.videoConfigReady) { - Log.warn('plugin', 'You are tring to set attribute on video before video inited. Please wait until the inited event has benn trigger'); - return args[2]; - } - if (this.__dispatcher.videoConfig._realDomAttr.indexOf(args[1]) > -1) { - var key = args[1], - val = args[2]; - // $FlowFixMe: we have check the computed key - - this.__dispatcher.videoConfig[key] = val; - return val; - } - } - // $FlowFixMe: we support this here - return (_dispatcher$dom2 = this.__dispatcher.dom)[method + 'Attr'].apply(_dispatcher$dom2, args); - } }, { key: '__throwError', value: function __throwError(error) { @@ -2678,7 +2891,7 @@ var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'version', [frozen], { enumerable: true, initializer: function initializer() { - return '0.1.3'; + return '0.2.0'; } }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'config', [frozen], { enumerable: true, @@ -2729,6 +2942,6 @@ var Chimee = (_dec = autobindClass(), _dec2 = alias('addEventListener'), _dec3 = initializer: function initializer() { return _init6; } -}), _class2), _applyDecoratedDescriptor(_class2.prototype, 'on', [_dec2, _dec3], _Object$getOwnPropertyDescriptor(_class2.prototype, 'on'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'off', [_dec4, _dec5], _Object$getOwnPropertyDescriptor(_class2.prototype, 'off'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'once', [_dec6], _Object$getOwnPropertyDescriptor(_class2.prototype, 'once'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'css', [_dec7], _Object$getOwnPropertyDescriptor(_class2.prototype, 'css'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'attr', [_dec8], _Object$getOwnPropertyDescriptor(_class2.prototype, 'attr'), _class2.prototype)), _class2)) || _class); +}), _class2)), _class2)) || _class); export default Chimee; diff --git a/package.json b/package.json index eef690ee..b74219db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "chimee", - "version": "0.1.3", + "version": "0.2.0", "description": "a video-player aims to bing wonderful experience on browser", "main": "lib/index.js", "module": "lib/index.mjs",