diff --git a/libs/chimee-player/1.3.1/chimee-player.browser.js b/libs/chimee-player/1.3.1/chimee-player.browser.js new file mode 100644 index 000000000..ebdb84601 --- /dev/null +++ b/libs/chimee-player/1.3.1/chimee-player.browser.js @@ -0,0 +1,48015 @@ + +/** chimeePlayer + * chimee-player v1.3.1 + * (c) 2017 huzunjie + * Released under MIT + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ChimeePlayer = factory()); +}(this, (function () { 'use strict'; + +var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +// 7.2.1 RequireObjectCoercible(argument) +var _defined = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +// 7.1.13 ToObject(argument) + +var _toObject = function (it) { + return Object(_defined(it)); +}; + +var hasOwnProperty = {}.hasOwnProperty; +var _has = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +var _global = createCommonjsModule(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef +}); + +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; +}; + +var _core = createCommonjsModule(function (module) { +var core = module.exports = { version: '2.5.3' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef +}); +var _core_1 = _core.version; + +var _aFunction = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx = function (fn, that, length) { + _aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +var _isObject = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject = function (it) { + if (!_isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors = !_fails(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +var document$1 = _global.document; +// typeof document.createElement is 'object' in old IE +var is = _isObject(document$1) && _isObject(document$1.createElement); +var _domCreate = function (it) { + return is ? document$1.createElement(it) : {}; +}; + +var _ie8DomDefine = !_descriptors && !_fails(function () { + return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive = function (it, S) { + if (!_isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP = Object.defineProperty; + +var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject(O); + P = _toPrimitive(P, true); + _anObject(Attributes); + if (_ie8DomDefine) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +var _objectDp = { + f: f +}; + +var _propertyDesc = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +var _hide = _descriptors ? function (object, key, value) { + return _objectDp.f(object, key, _propertyDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? _ctx(out, _global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) _hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +var _export = $export; + +// most Object methods by ES6 should accept primitives + + + +var _objectSap = function (KEY, exec) { + var fn = (_core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp); +}; + +// 19.1.2.9 Object.getPrototypeOf(O) + + + +_objectSap('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return _objectGpo(_toObject(it)); + }; +}); + +var getPrototypeOf = _core.Object.getPrototypeOf; + +var getPrototypeOf$1 = createCommonjsModule(function (module) { +module.exports = { "default": getPrototypeOf, __esModule: true }; +}); + +var _Object$getPrototypeOf = unwrapExports(getPrototypeOf$1); + +var classCallCheck = createCommonjsModule(function (module, exports) { + +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); + +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +var _toInteger = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +// true -> String#at +// false -> String#codePointAt +var _stringAt = function (TO_STRING) { + return function (that, pos) { + var s = String(_defined(that)); + var i = _toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +var _library = true; + +var _redefine = _hide; + +var _iterators = {}; + +var toString = {}.toString; + +var _cof = function (it) { + return toString.call(it).slice(8, -1); +}; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings + +// eslint-disable-next-line no-prototype-builtins +var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return _cof(it) == 'String' ? it.split('') : Object(it); +}; + +// to indexed object, toObject with fallback for non-array-like ES3 strings + + +var _toIobject = function (it) { + return _iobject(_defined(it)); +}; + +// 7.1.15 ToLength + +var min = Math.min; +var _toLength = function (it) { + return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +var max = Math.max; +var min$1 = Math.min; +var _toAbsoluteIndex = function (index, length) { + index = _toInteger(index); + return index < 0 ? max(index + length, 0) : min$1(index, length); +}; + +// false -> Array#indexOf +// true -> Array#includes + + + +var _arrayIncludes = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = _toIobject($this); + var length = _toLength(O.length); + var index = _toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +var arrayIndexOf = _arrayIncludes(false); +var IE_PROTO$1 = _sharedKey('IE_PROTO'); + +var _objectKeysInternal = function (object, names) { + var O = _toIobject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO$1) _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); + } + return result; +}; + +// IE 8- don't enum bug keys +var _enumBugKeys = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) + + + +var _objectKeys = Object.keys || function keys(O) { + return _objectKeysInternal(O, _enumBugKeys); +}; + +var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties) { + _anObject(O); + var keys = _objectKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) _objectDp.f(O, P = keys[i++], Properties[P]); + return O; +}; + +var document$2 = _global.document; +var _html = document$2 && document$2.documentElement; + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + + + +var IE_PROTO$2 = _sharedKey('IE_PROTO'); +var Empty = function () { /* empty */ }; +var PROTOTYPE$1 = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = _domCreate('iframe'); + var i = _enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + _html.appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; + return createDict(); +}; + +var _objectCreate = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE$1] = _anObject(O); + result = new Empty(); + Empty[PROTOTYPE$1] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO$2] = O; + } else result = createDict(); + return Properties === undefined ? result : _objectDps(result, Properties); +}; + +var _wks = createCommonjsModule(function (module) { +var store = _shared('wks'); + +var Symbol = _global.Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); +}; + +$exports.store = store; +}); + +var def = _objectDp.f; + +var TAG = _wks('toStringTag'); + +var _setToStringTag = function (it, tag, stat) { + if (it && !_has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); +}; + +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_hide(IteratorPrototype, _wks('iterator'), function () { return this; }); + +var _iterCreate = function (Constructor, NAME, next) { + Constructor.prototype = _objectCreate(IteratorPrototype, { next: _propertyDesc(1, next) }); + _setToStringTag(Constructor, NAME + ' Iterator'); +}; + +var ITERATOR = _wks('iterator'); +var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR = '@@iterator'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function () { return this; }; + +var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + _iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = (!BUGGY && $native) || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = _objectGpo($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + _setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!_library && !_has(IteratorPrototype, ITERATOR)) _hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!_library || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + _hide(proto, ITERATOR, $default); + } + // Plug for library + _iterators[NAME] = $default; + _iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) _redefine(proto, key, methods[key]); + } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; + +var $at = _stringAt(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_iterDefine(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +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; + var kind = this._k; + var 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; + +var TO_STRING_TAG = _wks('toStringTag'); + +var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i = 0; i < DOMIterables.length; i++) { + var NAME = DOMIterables[i]; + var Collection = _global[NAME]; + var proto = Collection && Collection.prototype; + if (proto && !proto[TO_STRING_TAG]) _hide(proto, TO_STRING_TAG, NAME); + _iterators[NAME] = _iterators.Array; +} + +var f$1 = _wks; + +var _wksExt = { + f: f$1 +}; + +var iterator = _wksExt.f('iterator'); + +var iterator$1 = createCommonjsModule(function (module) { +module.exports = { "default": iterator, __esModule: true }; +}); + +unwrapExports(iterator$1); + +var _meta = createCommonjsModule(function (module) { +var META = _uid('meta'); + + +var setDesc = _objectDp.f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !_fails(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!_isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; +}); +var _meta_1 = _meta.KEY; +var _meta_2 = _meta.NEED; +var _meta_3 = _meta.fastKey; +var _meta_4 = _meta.getWeak; +var _meta_5 = _meta.onFreeze; + +var defineProperty = _objectDp.f; +var _wksDefine = function (name) { + var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: _wksExt.f(name) }); +}; + +var f$2 = Object.getOwnPropertySymbols; + +var _objectGops = { + f: f$2 +}; + +var f$3 = {}.propertyIsEnumerable; + +var _objectPie = { + f: f$3 +}; + +// all enumerable object keys, includes symbols + + + +var _enumKeys = function (it) { + var result = _objectKeys(it); + var getSymbols = _objectGops.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = _objectPie.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +// 7.2.2 IsArray(argument) + +var _isArray = Array.isArray || function isArray(arg) { + return _cof(arg) == 'Array'; +}; + +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + +var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); + +var f$4 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return _objectKeysInternal(O, hiddenKeys); +}; + +var _objectGopn = { + f: f$4 +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + +var gOPN = _objectGopn.f; +var toString$1 = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } +}; + +var f$5 = function getOwnPropertyNames(it) { + return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(_toIobject(it)); +}; + +var _objectGopnExt = { + f: f$5 +}; + +var gOPD = Object.getOwnPropertyDescriptor; + +var f$6 = _descriptors ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = _toIobject(O); + P = _toPrimitive(P, true); + if (_ie8DomDefine) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]); +}; + +var _objectGopd = { + f: f$6 +}; + +// ECMAScript 6 symbols shim + + + + + +var META = _meta.KEY; + + + + + + + + + + + + + + + + + + + +var gOPD$1 = _objectGopd.f; +var dP$1 = _objectDp.f; +var gOPN$1 = _objectGopnExt.f; +var $Symbol = _global.Symbol; +var $JSON = _global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE$2 = 'prototype'; +var HIDDEN = _wks('_hidden'); +var TO_PRIMITIVE = _wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = _shared('symbol-registry'); +var AllSymbols = _shared('symbols'); +var OPSymbols = _shared('op-symbols'); +var ObjectProto$1 = Object[PROTOTYPE$2]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = _global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = _descriptors && _fails(function () { + return _objectCreate(dP$1({}, 'a', { + get: function () { return dP$1(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD$1(ObjectProto$1, key); + if (protoDesc) delete ObjectProto$1[key]; + dP$1(it, key, D); + if (protoDesc && it !== ObjectProto$1) dP$1(ObjectProto$1, key, protoDesc); +} : dP$1; + +var wrap = function (tag) { + var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto$1) $defineProperty(OPSymbols, key, D); + _anObject(it); + key = _toPrimitive(key, true); + _anObject(D); + if (_has(AllSymbols, key)) { + if (!D.enumerable) { + if (!_has(it, HIDDEN)) dP$1(it, HIDDEN, _propertyDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (_has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _objectCreate(D, { enumerable: _propertyDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP$1(it, key, D); +}; +var $defineProperties = function defineProperties(it, P) { + _anObject(it); + var keys = _enumKeys(P = _toIobject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P) { + return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = _toPrimitive(key, true)); + if (this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return false; + return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = _toIobject(it); + key = _toPrimitive(key, true); + if (it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return; + var D = gOPD$1(it, key); + if (D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN$1(_toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto$1; + var names = gOPN$1(IS_OP ? OPSymbols : _toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true)) result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto$1) $set.call(OPSymbols, value); + if (_has(this, HIDDEN) && _has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, _propertyDesc(1, value)); + }; + if (_descriptors && setter) setSymbolDesc(ObjectProto$1, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + _redefine($Symbol[PROTOTYPE$2], 'toString', function toString() { + return this._k; + }); + + _objectGopd.f = $getOwnPropertyDescriptor; + _objectDp.f = $defineProperty; + _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; + _objectPie.f = $propertyIsEnumerable; + _objectGops.f = $getOwnPropertySymbols; + + if (_descriptors && !_library) { + _redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + _wksExt.f = function (name) { + return wrap(_wks(name)); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE, { Symbol: $Symbol }); + +for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j = 0; es6Symbols.length > j;)_wks(es6Symbols[j++]); + +for (var wellKnownSymbols = _objectKeys(_wks.store), k = 0; wellKnownSymbols.length > k;) _wksDefine(wellKnownSymbols[k++]); + +_export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return _has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } +}); + +_export(_export.S + _export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!_isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!_isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +_setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +_setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +_setToStringTag(_global.JSON, 'JSON', true); + +_wksDefine('asyncIterator'); + +_wksDefine('observable'); + +var symbol = _core.Symbol; + +var symbol$1 = createCommonjsModule(function (module) { +module.exports = { "default": symbol, __esModule: true }; +}); + +unwrapExports(symbol$1); + +var _typeof_1 = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _iterator2 = _interopRequireDefault(iterator$1); + + + +var _symbol2 = _interopRequireDefault(symbol$1); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +}); + +var _typeof = unwrapExports(_typeof_1); + +var possibleConstructorReturn = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _typeof3 = _interopRequireDefault(_typeof_1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +}); + +var _possibleConstructorReturn = unwrapExports(possibleConstructorReturn); + +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ + + +var check = function (O, proto) { + _anObject(O); + if (!_isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); +}; +var _setProto = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = _ctx(Function.call, _objectGopd.f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check +}; + +// 19.1.3.19 Object.setPrototypeOf(O, proto) + +_export(_export.S, 'Object', { setPrototypeOf: _setProto.set }); + +var setPrototypeOf = _core.Object.setPrototypeOf; + +var setPrototypeOf$1 = createCommonjsModule(function (module) { +module.exports = { "default": setPrototypeOf, __esModule: true }; +}); + +unwrapExports(setPrototypeOf$1); + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +_export(_export.S, 'Object', { create: _objectCreate }); + +var $Object = _core.Object; +var create = function create(P, D) { + return $Object.create(P, D); +}; + +var create$1 = createCommonjsModule(function (module) { +module.exports = { "default": create, __esModule: true }; +}); + +var _Object$create = unwrapExports(create$1); + +var inherits = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _setPrototypeOf2 = _interopRequireDefault(setPrototypeOf$1); + + + +var _create2 = _interopRequireDefault(create$1); + + + +var _typeof3 = _interopRequireDefault(_typeof_1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } + + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +}); + +var _inherits = unwrapExports(inherits); + +// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + +var $getOwnPropertyDescriptor$1 = _objectGopd.f; + +_objectSap('getOwnPropertyDescriptor', function () { + return function getOwnPropertyDescriptor(it, key) { + return $getOwnPropertyDescriptor$1(_toIobject(it), key); + }; +}); + +var $Object$1 = _core.Object; +var getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + return $Object$1.getOwnPropertyDescriptor(it, key); +}; + +var getOwnPropertyDescriptor$1 = createCommonjsModule(function (module) { +module.exports = { "default": getOwnPropertyDescriptor, __esModule: true }; +}); + +var _Object$getOwnPropertyDescriptor = unwrapExports(getOwnPropertyDescriptor$1); + +var _redefineAll = function (target, src, safe) { + for (var key in src) { + if (safe && target[key]) target[key] = src[key]; + else _hide(target, key, src[key]); + } return target; +}; + +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); +}; + +// getting tag from 19.1.3.6 Object.prototype.toString() + +var TAG$1 = _wks('toStringTag'); +// ES3 wrong here +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 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 = {}; +var RETURN = {}; +var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : core_getIteratorMethod(iterable); + var f = _ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (_isArrayIter(iterFn)) for (length = _toLength(iterable.length); length > index; index++) { + result = entries ? f(_anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = _iterCall(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } +}; +exports.BREAK = BREAK; +exports.RETURN = RETURN; +}); + +var SPECIES = _wks('species'); + +var _setSpecies = function (KEY) { + var C = typeof _core[KEY] == 'function' ? _core[KEY] : _global[KEY]; + if (_descriptors && C && !C[SPECIES]) _objectDp.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); +}; + +var _validateCollection = function (it, TYPE) { + if (!_isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); + return it; +}; + +var dP$2 = _objectDp.f; + + + + + + + + + +var fastKey = _meta.fastKey; + +var SIZE = _descriptors ? '_s' : 'size'; + +var getEntry = function (that, key) { + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return that._i[index]; + // frozen object case + for (entry = that._f; entry; entry = entry.n) { + if (entry.k == key) return entry; + } +}; + +var _collectionStrong = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + _anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = _objectCreate(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if (iterable != undefined) _forOf(iterable, IS_MAP, that[ADDER], that); + }); + _redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + for (var that = _validateCollection(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { + entry.r = true; + if (entry.p) entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = _validateCollection(this, NAME); + var entry = getEntry(that, key); + if (entry) { + var next = entry.n; + var prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if (prev) prev.n = next; + if (next) next.p = prev; + if (that._f == entry) that._f = next; + if (that._l == entry) that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */) { + _validateCollection(this, NAME); + var f = _ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.n : this._f) { + f(entry.v, entry.k, this); + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(_validateCollection(this, NAME), key); + } + }); + if (_descriptors) dP$2(C.prototype, 'size', { + get: function () { + return _validateCollection(this, NAME)[SIZE]; + } + }); + return C; + }, + def: function (that, key, value) { + var entry = getEntry(that, key); + var prev, index; + // change existing entry + if (entry) { + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if (!that._f) that._f = entry; + if (prev) prev.n = entry; + that[SIZE]++; + // add to index + if (index !== 'F') that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function (C, NAME, IS_MAP) { + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + _iterDefine(C, NAME, function (iterated, kind) { + this._t = _validateCollection(iterated, NAME); // target + this._k = kind; // kind + this._l = undefined; // previous + }, function () { + var that = this; + var kind = that._k; + var entry = that._l; + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + // get next entry + if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { + // or finish the iteration + that._t = undefined; + return _iterStep(1); + } + // return step by kind + if (kind == 'keys') return _iterStep(0, entry.k); + if (kind == 'values') return _iterStep(0, entry.v); + return _iterStep(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + _setSpecies(NAME); + } +}; + +var SPECIES$1 = _wks('species'); + +var _arraySpeciesConstructor = function (original) { + var C; + if (_isArray(original)) { + C = original.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || _isArray(C.prototype))) C = undefined; + if (_isObject(C)) { + C = C[SPECIES$1]; + if (C === null) C = undefined; + } + } return C === undefined ? Array : C; +}; + +// 9.4.2.3 ArraySpeciesCreate(originalArray, length) + + +var _arraySpeciesCreate = function (original, length) { + return new (_arraySpeciesConstructor(original))(length); +}; + +// 0 -> Array#forEach +// 1 -> Array#map +// 2 -> Array#filter +// 3 -> Array#some +// 4 -> Array#every +// 5 -> Array#find +// 6 -> Array#findIndex + + + + + +var _arrayMethods = function (TYPE, $create) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + var create = $create || _arraySpeciesCreate; + return function ($this, callbackfn, that) { + var O = _toObject($this); + var self = _iobject(O); + var f = _ctx(callbackfn, that, 3); + var length = _toLength(self.length); + var index = 0; + var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var val, res; + for (;length > index; index++) if (NO_HOLES || index in self) { + val = self[index]; + res = f(val, index, O); + if (TYPE) { + if (IS_MAP) result[index] = res; // map + else if (res) switch (TYPE) { + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; +}; + +var dP$3 = _objectDp.f; +var each = _arrayMethods(0); + + +var _collection = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { + var Base = _global[NAME]; + var C = Base; + var ADDER = IS_MAP ? 'set' : 'add'; + var proto = C && C.prototype; + var O = {}; + if (!_descriptors || typeof C != 'function' || !(IS_WEAK || proto.forEach && !_fails(function () { + new C().entries().next(); + }))) { + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + _redefineAll(C.prototype, methods); + _meta.NEED = true; + } else { + C = wrapper(function (target, iterable) { + _anInstance(target, C, NAME, '_c'); + target._c = new Base(); + if (iterable != undefined) _forOf(iterable, IS_MAP, target[ADDER], target); + }); + each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','), function (KEY) { + var IS_ADDER = KEY == 'add' || KEY == 'set'; + if (KEY in proto && !(IS_WEAK && KEY == 'clear')) _hide(C.prototype, KEY, function (a, b) { + _anInstance(this, C, KEY); + if (!IS_ADDER && IS_WEAK && !_isObject(a)) return KEY == 'get' ? undefined : false; + var result = this._c[KEY](a === 0 ? 0 : a, b); + return IS_ADDER ? this : result; + }); + }); + IS_WEAK || dP$3(C.prototype, 'size', { + get: function () { + return this._c.size; + } + }); + } + + _setToStringTag(C, NAME); + + O[NAME] = C; + _export(_export.G + _export.W + _export.F, O); + + if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); + + return C; +}; + +var MAP = 'Map'; + +// 23.1 Map Objects +var es6_map = _collection(MAP, function (get) { + return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; +}, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = _collectionStrong.getEntry(_validateCollection(this, MAP), key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return _collectionStrong.def(_validateCollection(this, MAP), key === 0 ? 0 : key, value); + } +}, _collectionStrong, true); + +var _arrayFromIterable = function (iter, ITERATOR) { + var result = []; + _forOf(iter, false, result.push, result, ITERATOR); + return result; +}; + +// https://github.com/DavidBruant/Map-Set.prototype.toJSON + + +var _collectionToJson = function (NAME) { + return function toJSON() { + if (_classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); + return _arrayFromIterable(this); + }; +}; + +// https://github.com/DavidBruant/Map-Set.prototype.toJSON + + +_export(_export.P + _export.R, 'Map', { toJSON: _collectionToJson('Map') }); + +// https://tc39.github.io/proposal-setmap-offrom/ + + +var _setCollectionOf = function (COLLECTION) { + _export(_export.S, COLLECTION, { of: function of() { + var length = arguments.length; + var A = new Array(length); + while (length--) A[length] = arguments[length]; + return new this(A); + } }); +}; + +// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of +_setCollectionOf('Map'); + +// https://tc39.github.io/proposal-setmap-offrom/ + + + + + +var _setCollectionFrom = function (COLLECTION) { + _export(_export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { + var mapFn = arguments[1]; + var mapping, A, n, cb; + _aFunction(this); + mapping = mapFn !== undefined; + if (mapping) _aFunction(mapFn); + if (source == undefined) return new this(); + A = []; + if (mapping) { + n = 0; + cb = _ctx(mapFn, arguments[2], 2); + _forOf(source, false, function (nextItem) { + A.push(cb(nextItem, n++)); + }); + } else { + _forOf(source, false, A.push, A); + } + return new this(A); + } }); +}; + +// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from +_setCollectionFrom('Map'); + +var map = _core.Map; + +var map$1 = createCommonjsModule(function (module) { +module.exports = { "default": map, __esModule: true }; +}); + +var _Map = unwrapExports(map$1); + +var _createProperty = function (object, index, value) { + if (index in object) _objectDp.f(object, index, _propertyDesc(0, value)); + else object[index] = value; +}; + +var ITERATOR$3 = _wks('iterator'); +var SAFE_CLOSING = false; + +try { + var riter = [7][ITERATOR$3](); + riter['return'] = function () { SAFE_CLOSING = true; }; +} catch (e) { /* empty */ } + +var _iterDetect = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var 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', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = _toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = core_getIteratorMethod(O); + var 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 = _core.Array.from; + +var from$1 = createCommonjsModule(function (module) { +module.exports = { "default": from, __esModule: true }; +}); + +var _Array$from = unwrapExports(from$1); + +var toConsumableArray = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _from2 = _interopRequireDefault(from$1); + +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); + +// 7.3.20 SpeciesConstructor(O, defaultConstructor) + + +var SPECIES$2 = _wks('species'); +var _speciesConstructor = function (O, D) { + var C = _anObject(O).constructor; + var S; + return C === undefined || (S = _anObject(C)[SPECIES$2]) == undefined ? D : _aFunction(S); +}; + +// fast apply, http://jsperf.lnkit.com/fast-apply/5 +var _invoke = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); +}; + +var process = _global.process; +var setTask = _global.setImmediate; +var clearTask = _global.clearImmediate; +var MessageChannel = _global.MessageChannel; +var Dispatch = _global.Dispatch; +var counter = 0; +var queue = {}; +var ONREADYSTATECHANGE = 'onreadystatechange'; +var defer, channel, port; +var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } +}; +var listener = function (event) { + run.call(event.data); +}; +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + _invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (_cof(process) == 'process') { + defer = function (id) { + process.nextTick(_ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(_ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = _ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (_global.addEventListener && typeof postMessage == 'function' && !_global.importScripts) { + defer = function (id) { + _global.postMessage(id + '', '*'); + }; + _global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in _domCreate('script')) { + defer = function (id) { + _html.appendChild(_domCreate('script'))[ONREADYSTATECHANGE] = function () { + _html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(_ctx(run, id, 1), 0); + }; + } +} +var _task = { + set: setTask, + clear: clearTask +}; + +var macrotask = _task.set; +var Observer = _global.MutationObserver || _global.WebKitMutationObserver; +var process$1 = _global.process; +var Promise = _global.Promise; +var isNode = _cof(process$1) == 'process'; + +var _microtask = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode && (parent = process$1.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode) { + notify = function () { + process$1.nextTick(flush); + }; + // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 + } else if (Observer && !(_global.navigator && _global.navigator.standalone)) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + var promise = Promise.resolve(); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(_global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; +}; + +// 25.4.1.5 NewPromiseCapability(C) + + +function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = _aFunction(resolve); + this.reject = _aFunction(reject); +} + +var f$7 = function (C) { + return new PromiseCapability(C); +}; + +var _newPromiseCapability = { + f: f$7 +}; + +var _perform = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } +}; + +var _promiseResolve = function (C, x) { + _anObject(C); + if (_isObject(x) && x.constructor === C) return x; + var promiseCapability = _newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; +}; + +var task = _task.set; +var microtask = _microtask(); + + + +var PROMISE = 'Promise'; +var TypeError$1 = _global.TypeError; +var process$2 = _global.process; +var $Promise = _global[PROMISE]; +var isNode$1 = _classof(process$2) == 'process'; +var empty = function () { /* empty */ }; +var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; +var newPromiseCapability = newGenericPromiseCapability = _newPromiseCapability.f; + +var USE_NATIVE$1 = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[_wks('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode$1 || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; + } catch (e) { /* empty */ } +}(); + +// helpers +var isThenable = function (it) { + var then; + return _isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; +var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); + if (domain) domain.exit(); + } + if (result === reaction.promise) { + reject(TypeError$1('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); +}; +var onUnhandled = function (promise) { + task.call(_global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = _perform(function () { + if (isNode$1) { + process$2.emit('unhandledRejection', value, promise); + } else if (handler = _global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = _global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode$1 || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); +}; +var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; +}; +var onHandleUnhandled = function (promise) { + task.call(_global, function () { + var handler; + if (isNode$1) { + process$2.emit('rejectionHandled', promise); + } else if (handler = _global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); +}; +var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); +}; +var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError$1("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, _ctx($resolve, wrapper, 1), _ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } +}; + +// constructor polyfill +if (!USE_NATIVE$1) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + _anInstance(this, $Promise, PROMISE, '_h'); + _aFunction(executor); + Internal.call(this); + try { + executor(_ctx($resolve, this, 1), _ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = _redefineAll($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(_speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode$1 ? process$2.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = _ctx($resolve, promise, 1); + this.reject = _ctx($reject, promise, 1); + }; + _newPromiseCapability.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE$1, { Promise: $Promise }); +_setToStringTag($Promise, PROMISE); +_setSpecies(PROMISE); +Wrapper = _core[PROMISE]; + +// statics +_export(_export.S + _export.F * !USE_NATIVE$1, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } +}); +_export(_export.S + _export.F * (_library || !USE_NATIVE$1), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return _promiseResolve(_library && this === Wrapper ? $Promise : this, x); + } +}); +_export(_export.S + _export.F * !(USE_NATIVE$1 && _iterDetect(function (iter) { + $Promise.all(iter)['catch'](empty); +})), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = _perform(function () { + var values = []; + var index = 0; + var remaining = 1; + _forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = _perform(function () { + _forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } +}); + +_export(_export.P + _export.R, 'Promise', { 'finally': function (onFinally) { + var C = _speciesConstructor(this, _core.Promise || _global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return _promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return _promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); +} }); + +// https://github.com/tc39/proposal-promise-try + + + + +_export(_export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = _newPromiseCapability.f(this); + var result = _perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; +} }); + +var promise = _core.Promise; + +var promise$1 = createCommonjsModule(function (module) { +module.exports = { "default": promise, __esModule: true }; +}); + +var _Promise = unwrapExports(promise$1); + +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +_export(_export.S + _export.F * !_descriptors, 'Object', { defineProperty: _objectDp.f }); + +var $Object$2 = _core.Object; +var defineProperty$1 = function defineProperty(it, key, desc) { + return $Object$2.defineProperty(it, key, desc); +}; + +var defineProperty$2 = createCommonjsModule(function (module) { +module.exports = { "default": defineProperty$1, __esModule: true }; +}); + +var _Object$defineProperty = unwrapExports(defineProperty$2); + +var createClass = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty$2); + +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); + +// 19.1.2.14 Object.keys(O) + + + +_objectSap('keys', function () { + return function keys(it) { + return _objectKeys(_toObject(it)); + }; +}); + +var keys = _core.Object.keys; + +var keys$1 = createCommonjsModule(function (module) { +module.exports = { "default": keys, __esModule: true }; +}); + +var _Object$keys = unwrapExports(keys$1); + +// 20.1.2.3 Number.isInteger(number) + +var floor$1 = Math.floor; +var _isInteger = function isInteger(it) { + return !_isObject(it) && isFinite(it) && floor$1(it) === it; +}; + +// 20.1.2.3 Number.isInteger(number) + + +_export(_export.S, 'Number', { isInteger: _isInteger }); + +var isInteger = _core.Number.isInteger; + +var isInteger$1 = createCommonjsModule(function (module) { +module.exports = { "default": isInteger, __esModule: true }; +}); + +var _Number$isInteger = unwrapExports(isInteger$1); + +var _stringWs = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +var space = '[' + _stringWs + ']'; +var non = '\u200b\u0085'; +var ltrim = RegExp('^' + space + space + '*'); +var rtrim = RegExp(space + space + '*$'); + +var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = _fails(function () { + return !!_stringWs[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : _stringWs[KEY]; + if (ALIAS) exp[ALIAS] = fn; + _export(_export.P + _export.F * FORCE, 'String', exp); +}; + +// 1 -> String#trimLeft +// 2 -> String#trimRight +// 3 -> String#trim +var trim = exporter.trim = function (string, TYPE) { + string = String(_defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; +}; + +var _stringTrim = exporter; + +var $parseFloat = _global.parseFloat; +var $trim = _stringTrim.trim; + +var _parseFloat = 1 / $parseFloat(_stringWs + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; +} : $parseFloat; + +// 20.1.2.12 Number.parseFloat(string) +_export(_export.S + _export.F * (Number.parseFloat != _parseFloat), 'Number', { parseFloat: _parseFloat }); + +var _parseFloat$1 = parseFloat; + +var _parseFloat$2 = createCommonjsModule(function (module) { +module.exports = { "default": _parseFloat$1, __esModule: true }; +}); + +var _Number$parseFloat = unwrapExports(_parseFloat$2); + +/** + * to check whether the object is defined or not + */ +function defined(obj) { + return typeof obj !== 'undefined'; +} +/** + * is void element or not ? Means it will return true when val is undefined or null + */ +function isVoid(obj) { + return obj === undefined || obj === null; +} +/** + * to check whether a variable is array + */ +function isArray(arr) { + return Array.isArray(arr); +} + +/** + * is it a function or not + */ +function isFunction(obj) { + return typeof obj === 'function'; +} + +/** + * is it an object or not + */ +function isObject(obj) { + // incase of arrow function and array + return Object(obj) === obj && String(obj) === '[object Object]' && !isFunction(obj) && !isArray(obj); +} +/** + * to tell you if it's a real number + */ +function isNumber(obj) { + return typeof obj === 'number'; +} +/** + * to tell you if the val can be transfer into number + */ +function isNumeric(obj) { + return !isArray(obj) && obj - _Number$parseFloat(obj) + 1 >= 0; +} +/** + * is it an interget or not + */ +function isInteger$2(num) { + return _Number$isInteger(num); +} + +/** + * return true when the value is "", {}, [], 0, null, undefined, false. + */ +function isEmpty(obj) { + if (isArray(obj)) { + return obj.length === 0; + } else if (isObject(obj)) { + return _Object$keys(obj).length === 0; + } else { + return !obj; + } +} +/** + * is it an event or not + */ +function isEvent(obj) { + return obj instanceof Event || (obj && obj.originalEvent) instanceof Event; +} +/** + * is it a blob + */ +function isBlob(obj) { + return obj instanceof Blob; +} +/** + * is it a file uploaded by user through file inpue + */ +function isFile(obj) { + return isBlob(obj) && isString(obj.name); +} +/** + * is it a date + */ +function isDate(obj) { + return Object.prototype.toString.call(obj) === '[object Date]'; +} +/** + * is it a string + */ +function isString(str) { + return typeof str === 'string' || str instanceof String; +} +/** + * is Boolean or not + */ +function isBoolean(bool) { + return typeof bool === 'boolean'; +} +/** + * is a promise or not + */ +function isPromise(obj) { + return !!obj && ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +} +/** + * is Primitive type or not, whick means it will return true when data is number/string/boolean/undefined/null + */ +function isPrimitive(val) { + return isVoid(val) || isBoolean(val) || isString(val) || isNumber(val); +} +/** + * is it an url, but this test require the url to have an protocol + */ +function isUrl(str) { + return isString(str) && !!str.match(/^((https?|ftp|rtsp|mms):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6}|localhost)(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i); +} +/** + * to test if a HTML node + */ +function isNode$2(obj) { + return !!((typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? obj instanceof Node : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'); +} +/** + * to test if a HTML element + */ +function isElement(obj) { + return !!((typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === 'object' ? obj instanceof HTMLElement : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string'); +} +/** + * check if node A is node B's parent or not + */ +function isChildNode(parent, child) { + if (!isNode$2(parent) || !isNode$2(child)) { + return false; + } + return child.parentNode === parent; +} +/** + * check if node B is node A's posterrity or not + */ +function isPosterityNode(parent, child) { + if (!isNode$2(parent) || !isNode$2(child)) { + return false; + } + while (child.parentNode) { + child = child.parentNode; + if (child === parent) { + return true; + } + } + return false; +} +/** + * check if the string is an HTMLString + */ +function isHTMLString(str) { + return (/<[^>]+?>/.test(str) + ); +} +/** + * check if is an error + */ +function isError(val) { + return val instanceof Error; +} +/** + * check if is an RegExp + */ +function isRegExp(val) { + return val instanceof RegExp; +} + +function formatter(tag, msg) { + if (!isString(tag)) throw new TypeError('Log\'s method only acccept string as argument, but not ' + tag + ' in ' + (typeof tag === 'undefined' ? 'undefined' : _typeof(tag))); + if (!isString(msg)) return '[' + Log$1.GLOBAL_TAG + '] > ' + tag; + tag = Log$1.FORCE_GLOBAL_TAG ? Log$1.GLOBAL_TAG : tag || Log$1.GLOBAL_TAG; + return '[' + tag + '] > ' + msg; +} +/** + * Log Object + */ + +var Log$1 = function () { + function Log() { + _classCallCheck(this, Log); + } + + _createClass(Log, null, [{ + key: 'error', + + /** + * equal to console.error, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + value: function error(tag, msg) { + if (!Log.ENABLE_ERROR) { + return; + } + + (console.error || console.warn || console.log)(formatter(tag, msg)); + } + /** + * equal to console.info, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {string} + */ + + }, { + key: 'info', + value: function info(tag, msg) { + if (!Log.ENABLE_INFO) { + return; + } + (console.info || console.log)(formatter(tag, msg)); + } + /** + * equal to console.warn, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'warn', + value: function warn(tag, msg) { + if (!Log.ENABLE_WARN) { + return; + } + (console.warn || console.log)(formatter(tag, msg)); + } + /** + * equal to console.debug, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'debug', + value: function debug(tag, msg) { + if (!Log.ENABLE_DEBUG) { + return; + } + (console.debug || console.log)(formatter(tag, msg)); + } + /** + * equal to console.verbose, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'verbose', + value: function verbose(tag, msg) { + if (!Log.ENABLE_VERBOSE) { + return; + } + console.log(formatter(tag, msg)); + } + }]); + + return Log; +}(); + +Log$1.GLOBAL_TAG = 'chimee'; +Log$1.FORCE_GLOBAL_TAG = false; +Log$1.ENABLE_ERROR = true; +Log$1.ENABLE_INFO = true; +Log$1.ENABLE_WARN = true; +Log$1.ENABLE_DEBUG = true; +Log$1.ENABLE_VERBOSE = true; + +var uaParser = createCommonjsModule(function (module, exports) { +/** + * UAParser.js v0.7.17 + * Lightweight JavaScript-based User-Agent string parser + * https://github.com/faisalman/ua-parser-js + * + * Copyright © 2012-2016 Faisal Salman + * Dual licensed under GPLv2 & MIT + */ + +(function (window, undefined) { + + ////////////// + // Constants + ///////////// + + + var LIBVERSION = '0.7.17', + EMPTY = '', + UNKNOWN = '?', + FUNC_TYPE = 'function', + UNDEF_TYPE = 'undefined', + OBJ_TYPE = 'object', + STR_TYPE = 'string', + MAJOR = 'major', // deprecated + MODEL = 'model', + NAME = 'name', + TYPE = 'type', + VENDOR = 'vendor', + VERSION = 'version', + ARCHITECTURE= 'architecture', + CONSOLE = 'console', + MOBILE = 'mobile', + TABLET = 'tablet', + SMARTTV = 'smarttv', + WEARABLE = 'wearable', + EMBEDDED = 'embedded'; + + + /////////// + // Helper + ////////// + + + var util = { + extend : function (regexes, extensions) { + var margedRegexes = {}; + for (var i in regexes) { + if (extensions[i] && extensions[i].length % 2 === 0) { + margedRegexes[i] = extensions[i].concat(regexes[i]); + } else { + margedRegexes[i] = regexes[i]; + } + } + return margedRegexes; + }, + has : function (str1, str2) { + if (typeof str1 === "string") { + return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; + } else { + return false; + } + }, + lowerize : function (str) { + return str.toLowerCase(); + }, + major : function (version) { + return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g,'').split(".")[0] : undefined; + }, + trim : function (str) { + return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + } + }; + + + /////////////// + // Map helper + ////////////// + + + var mapper = { + + rgx : function (ua, arrays) { + + //var result = {}, + var i = 0, j, k, p, q, matches, match;//, args = arguments; + + /*// construct object barebones + for (p = 0; p < args[1].length; p++) { + q = args[1][p]; + result[typeof q === OBJ_TYPE ? q[0] : q] = undefined; + }*/ + + // loop through all regexes maps + while (i < arrays.length && !matches) { + + var regex = arrays[i], // even sequence (0,2,4,..) + props = arrays[i + 1]; // odd sequence (1,3,5,..) + j = k = 0; + + // try matching uastring with regexes + while (j < regex.length && !matches) { + + matches = regex[j++].exec(ua); + + if (!!matches) { + for (p = 0; p < props.length; p++) { + match = matches[++k]; + q = props[p]; + // check if given property is actually array + if (typeof q === OBJ_TYPE && q.length > 0) { + if (q.length == 2) { + if (typeof q[1] == FUNC_TYPE) { + // assign modified match + this[q[0]] = q[1].call(this, match); + } else { + // assign given value, ignore regex match + this[q[0]] = q[1]; + } + } else if (q.length == 3) { + // check whether function or regex + if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) { + // call function (usually string mapper) + this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; + } else { + // sanitize match using given regex + this[q[0]] = match ? match.replace(q[1], q[2]) : undefined; + } + } else if (q.length == 4) { + this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; + } + } else { + this[q] = match ? match : undefined; + } + } + } + } + i += 2; + } + // console.log(this); + //return this; + }, + + str : function (str, map) { + + for (var i in map) { + // check if array + if (typeof map[i] === OBJ_TYPE && map[i].length > 0) { + for (var j = 0; j < map[i].length; j++) { + if (util.has(map[i][j], str)) { + return (i === UNKNOWN) ? undefined : i; + } + } + } else if (util.has(map[i], str)) { + return (i === UNKNOWN) ? undefined : i; + } + } + return str; + } + }; + + + /////////////// + // String map + ////////////// + + + var maps = { + + browser : { + oldsafari : { + version : { + '1.0' : '/8', + '1.2' : '/1', + '1.3' : '/3', + '2.0' : '/412', + '2.0.2' : '/416', + '2.0.3' : '/417', + '2.0.4' : '/419', + '?' : '/' + } + } + }, + + device : { + amazon : { + model : { + 'Fire Phone' : ['SD', 'KF'] + } + }, + sprint : { + model : { + 'Evo Shift 4G' : '7373KT' + }, + vendor : { + 'HTC' : 'APA', + 'Sprint' : 'Sprint' + } + } + }, + + os : { + windows : { + version : { + 'ME' : '4.90', + 'NT 3.11' : 'NT3.51', + 'NT 4.0' : 'NT4.0', + '2000' : 'NT 5.0', + 'XP' : ['NT 5.1', 'NT 5.2'], + 'Vista' : 'NT 6.0', + '7' : 'NT 6.1', + '8' : 'NT 6.2', + '8.1' : 'NT 6.3', + '10' : ['NT 6.4', 'NT 10.0'], + 'RT' : 'ARM' + } + } + } + }; + + + ////////////// + // Regex map + ///////////// + + + var regexes = { + + browser : [[ + + // Presto based + /(opera\smini)\/([\w\.-]+)/i, // Opera Mini + /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet + /(opera).+version\/([\w\.]+)/i, // Opera > 9.80 + /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80 + ], [NAME, VERSION], [ + + /(opios)[\/\s]+([\w\.]+)/i // Opera mini on iphone >= 8.0 + ], [[NAME, 'Opera Mini'], VERSION], [ + + /\s(opr)\/([\w\.]+)/i // Opera Webkit + ], [[NAME, 'Opera'], VERSION], [ + + // Mixed + /(kindle)\/([\w\.]+)/i, // Kindle + /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i, + // Lunascape/Maxthon/Netfront/Jasmine/Blazer + + // Trident based + /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i, + // Avant/IEMobile/SlimBrowser/Baidu + /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer + + // Webkit/KHTML based + /(rekonq)\/([\w\.]+)*/i, // Rekonq + /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i + // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser + ], [NAME, VERSION], [ + + /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11 + ], [[NAME, 'IE'], VERSION], [ + + /(edge)\/((\d+)?[\w\.]+)/i // Microsoft Edge + ], [NAME, VERSION], [ + + /(yabrowser)\/([\w\.]+)/i // Yandex + ], [[NAME, 'Yandex'], VERSION], [ + + /(puffin)\/([\w\.]+)/i // Puffin + ], [[NAME, 'Puffin'], VERSION], [ + + /((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i + // UCBrowser + ], [[NAME, 'UCBrowser'], VERSION], [ + + /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon + ], [[NAME, /_/g, ' '], VERSION], [ + + /(micromessenger)\/([\w\.]+)/i // WeChat + ], [[NAME, 'WeChat'], VERSION], [ + + /(QQ)\/([\d\.]+)/i // QQ, aka ShouQ + ], [NAME, VERSION], [ + + /m?(qqbrowser)[\/\s]?([\w\.]+)/i // QQBrowser + ], [NAME, VERSION], [ + + /xiaomi\/miuibrowser\/([\w\.]+)/i // MIUI Browser + ], [VERSION, [NAME, 'MIUI Browser']], [ + + /;fbav\/([\w\.]+);/i // Facebook App for iOS & Android + ], [VERSION, [NAME, 'Facebook']], [ + + /headlesschrome(?:\/([\w\.]+)|\s)/i // Chrome Headless + ], [VERSION, [NAME, 'Chrome Headless']], [ + + /\swv\).+(chrome)\/([\w\.]+)/i // Chrome WebView + ], [[NAME, /(.+)/, '$1 WebView'], VERSION], [ + + /((?:oculus|samsung)browser)\/([\w\.]+)/i + ], [[NAME, /(.+(?:g|us))(.+)/, '$1 $2'], VERSION], [ // Oculus / Samsung Browser + + /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i // Android Browser + ], [VERSION, [NAME, 'Android Browser']], [ + + /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i + // Chrome/OmniWeb/Arora/Tizen/Nokia + ], [NAME, VERSION], [ + + /(dolfin)\/([\w\.]+)/i // Dolphin + ], [[NAME, 'Dolphin'], VERSION], [ + + /((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS + ], [[NAME, 'Chrome'], VERSION], [ + + /(coast)\/([\w\.]+)/i // Opera Coast + ], [[NAME, 'Opera Coast'], VERSION], [ + + /fxios\/([\w\.-]+)/i // Firefox for iOS + ], [VERSION, [NAME, 'Firefox']], [ + + /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari + ], [VERSION, [NAME, 'Mobile Safari']], [ + + /version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile + ], [VERSION, NAME], [ + + /webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Google Search Appliance on iOS + ], [[NAME, 'GSA'], VERSION], [ + + /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0 + ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [ + + /(konqueror)\/([\w\.]+)/i, // Konqueror + /(webkit|khtml)\/([\w\.]+)/i + ], [NAME, VERSION], [ + + // Gecko based + /(navigator|netscape)\/([\w\.-]+)/i // Netscape + ], [[NAME, 'Netscape'], VERSION], [ + /(swiftfox)/i, // Swiftfox + /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i, + // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror + /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i, + // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix + /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla + + // Other + /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i, + // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir + /(links)\s\(([\w\.]+)/i, // Links + /(gobrowser)\/?([\w\.]+)*/i, // GoBrowser + /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser + /(mosaic)[\/\s]([\w\.]+)/i // Mosaic + ], [NAME, VERSION] + + /* ///////////////////// + // Media players BEGIN + //////////////////////// + + , [ + + /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i, // Generic Apple CoreMedia + /(coremedia) v((\d+)[\w\._]+)/i + ], [NAME, VERSION], [ + + /(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i // Aqualung/Lyssna/BSPlayer + ], [NAME, VERSION], [ + + /(ares|ossproxy)\s((\d+)[\w\.-]+)/i // Ares/OSSProxy + ], [NAME, VERSION], [ + + /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i, + // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC + // NSPlayer/PSP-InternetRadioPlayer/Videos + /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i, // Clementine/MPD + /(lg player|nexplayer)\s((\d+)[\d\.]+)/i, + /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i // NexPlayer/LG Player + ], [NAME, VERSION], [ + /(nexplayer)\s((\d+)[\w\.-]+)/i // Nexplayer + ], [NAME, VERSION], [ + + /(flrp)\/((\d+)[\w\.-]+)/i // Flip Player + ], [[NAME, 'Flip Player'], VERSION], [ + + /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i + // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit + ], [NAME], [ + + /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i + // Gstreamer + ], [NAME, VERSION], [ + + /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i, // HTC Streaming Player + /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i, + // Java/urllib/requests/wget/cURL + /(lavf)((\d+)[\d\.]+)/i // Lavf (FFMPEG) + ], [NAME, VERSION], [ + + /(htc_one_s)\/((\d+)[\d\.]+)/i // HTC One S + ], [[NAME, /_/g, ' '], VERSION], [ + + /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i + // MPlayer SVN + ], [NAME, VERSION], [ + + /(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i // MPlayer + ], [NAME, VERSION], [ + + /(mplayer)/i, // MPlayer (no other info) + /(yourmuze)/i, // YourMuze + /(media player classic|nero showtime)/i // Media Player Classic/Nero ShowTime + ], [NAME], [ + + /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i // Nero Home/Nero Scout + ], [NAME, VERSION], [ + + /(nokia\d+)\/((\d+)[\w\.-]+)/i // Nokia + ], [NAME, VERSION], [ + + /\s(songbird)\/((\d+)[\w\.-]+)/i // Songbird/Philips-Songbird + ], [NAME, VERSION], [ + + /(winamp)3 version ((\d+)[\w\.-]+)/i, // Winamp + /(winamp)\s((\d+)[\w\.-]+)/i, + /(winamp)mpeg\/((\d+)[\w\.-]+)/i + ], [NAME, VERSION], [ + + /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info) + // inlight radio + ], [NAME], [ + + /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i + // QuickTime/RealMedia/RadioApp/RadioClientApplication/ + // SoundTap/Totem/Stagefright/Streamium + ], [NAME, VERSION], [ + + /(smp)((\d+)[\d\.]+)/i // SMP + ], [NAME, VERSION], [ + + /(vlc) media player - version ((\d+)[\w\.]+)/i, // VLC Videolan + /(vlc)\/((\d+)[\w\.-]+)/i, + /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i, // XBMC/gvfs/Xine/XMMS/irapp + /(foobar2000)\/((\d+)[\d\.]+)/i, // Foobar2000 + /(itunes)\/((\d+)[\d\.]+)/i // iTunes + ], [NAME, VERSION], [ + + /(wmplayer)\/((\d+)[\w\.-]+)/i, // Windows Media Player + /(windows-media-player)\/((\d+)[\w\.-]+)/i + ], [[NAME, /-/g, ' '], VERSION], [ + + /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i + // Windows Media Server + ], [VERSION, [NAME, 'Windows']], [ + + /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i // RiseUP Radio Alarm + ], [NAME, VERSION], [ + + /(rad.io)\s((\d+)[\d\.]+)/i, // Rad.io + /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i + ], [[NAME, 'rad.io'], VERSION] + + ////////////////////// + // Media players END + ////////////////////*/ + + ], + + cpu : [[ + + /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64 + ], [[ARCHITECTURE, 'amd64']], [ + + /(ia32(?=;))/i // IA32 (quicktime) + ], [[ARCHITECTURE, util.lowerize]], [ + + /((?:i[346]|x)86)[;\)]/i // IA32 + ], [[ARCHITECTURE, 'ia32']], [ + + // PocketPC mistakenly identified as PowerPC + /windows\s(ce|mobile);\sppc;/i + ], [[ARCHITECTURE, 'arm']], [ + + /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC + ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [ + + /(sun4\w)[;\)]/i // SPARC + ], [[ARCHITECTURE, 'sparc']], [ + + /((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i + // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC + ], [[ARCHITECTURE, util.lowerize]] + ], + + device : [[ + + /\((ipad|playbook);[\w\s\);-]+(rim|apple)/i // iPad/PlayBook + ], [MODEL, VENDOR, [TYPE, TABLET]], [ + + /applecoremedia\/[\w\.]+ \((ipad)/ // iPad + ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [ + + /(apple\s{0,1}tv)/i // Apple TV + ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [ + + /(archos)\s(gamepad2?)/i, // Archos + /(hp).+(touchpad)/i, // HP TouchPad + /(hp).+(tablet)/i, // HP Tablet + /(kindle)\/([\w\.]+)/i, // Kindle + /\s(nook)[\w\s]+build\/(\w+)/i, // Nook + /(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i // Kindle Fire HD + ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [ + /(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i // Fire Phone + ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [ + + /\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone + ], [MODEL, VENDOR, [TYPE, MOBILE]], [ + /\((ip[honed|\s\w*]+);/i // iPod/iPhone + ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [ + + /(blackberry)[\s-]?(\w+)/i, // BlackBerry + /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i, + // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron + /(hp)\s([\w\s]+\w)/i, // HP iPAQ + /(asus)-?(\w+)/i // Asus + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + /\(bb10;\s(\w+)/i // BlackBerry 10 + ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [ + // Asus Tablets + /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i + ], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [ + + /(sony)\s(tablet\s[ps])\sbuild\//i, // Sony + /(sony)?(?:sgp.+)\sbuild\//i + ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [ + /android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i + ], [MODEL, [VENDOR, 'Sony'], [TYPE, MOBILE]], [ + + /\s(ouya)\s/i, // Ouya + /(nintendo)\s([wids3u]+)/i // Nintendo + ], [VENDOR, MODEL, [TYPE, CONSOLE]], [ + + /android.+;\s(shield)\sbuild/i // Nvidia + ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [ + + /(playstation\s[34portablevi]+)/i // Playstation + ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [ + + /(sprint\s(\w+))/i // Sprint Phones + ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [ + + /(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i // Lenovo tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i, // HTC + /(zte)-(\w+)*/i, // ZTE + /(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i + // Alcatel/GeeksPhone/Lenovo/Nexian/Panasonic/Sony + ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [ + + /(nexus\s9)/i // HTC Nexus 9 + ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [ + + /d\/huawei([\w\s-]+)[;\)]/i, + /(nexus\s6p)/i // Huawei + ], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [ + + /(microsoft);\s(lumia[\s\w]+)/i // Microsoft Lumia + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + + /[\s\(;](xbox(?:\sone)?)[\s\);]/i // Microsoft Xbox + ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [ + /(kin\.[onetw]{3})/i // Microsoft Kin + ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [ + + // Motorola + /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i, + /mot[\s-]?(\w+)*/i, + /(XT\d{3,4}) build\//i, + /(nexus\s6)/i + ], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [ + /android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i + ], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [ + + /hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i // HbbTV devices + ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [ + + /hbbtv.+maple;(\d+)/i + ], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [ + + /\(dtv[\);].+(aquos)/i // Sharp + ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [ + + /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i, + /((SM-T\w+))/i + ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [ // Samsung + /smart-tv.+(samsung)/i + ], [VENDOR, [TYPE, SMARTTV], MODEL], [ + /((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i, + /(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i, + /sec-((sgh\w+))/i + ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [ + + /sie-(\w+)*/i // Siemens + ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [ + + /(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia + /(nokia)[\s_-]?([\w-]+)*/i + ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [ + + /android\s3\.[\s\w;-]{10}(a\d{3})/i // Acer + ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [ + + /android.+([vl]k\-?\d{3})\s+build/i // LG Tablet + ], [MODEL, [VENDOR, 'LG'], [TYPE, TABLET]], [ + /android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i // LG Tablet + ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [ + /(lg) netcast\.tv/i // LG SmartTV + ], [VENDOR, MODEL, [TYPE, SMARTTV]], [ + /(nexus\s[45])/i, // LG + /lg[e;\s\/-]+(\w+)*/i, + /android.+lg(\-?[\d\w]+)\s+build/i + ], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [ + + /android.+(ideatab[a-z0-9\-\s]+)/i // Lenovo + ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [ + + /linux;.+((jolla));/i // Jolla + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + + /((pebble))app\/[\d\.]+\s/i // Pebble + ], [VENDOR, MODEL, [TYPE, WEARABLE]], [ + + /android.+;\s(oppo)\s?([\w\s]+)\sbuild/i // OPPO + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + + /crkey/i // Google Chromecast + ], [[MODEL, 'Chromecast'], [VENDOR, 'Google']], [ + + /android.+;\s(glass)\s\d/i // Google Glass + ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [ + + /android.+;\s(pixel c)\s/i // Google Pixel C + ], [MODEL, [VENDOR, 'Google'], [TYPE, TABLET]], [ + + /android.+;\s(pixel xl|pixel)\s/i // Google Pixel + ], [MODEL, [VENDOR, 'Google'], [TYPE, MOBILE]], [ + + /android.+(\w+)\s+build\/hm\1/i, // Xiaomi Hongmi 'numeric' models + /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Hongmi + /android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Mi + /android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i // Redmi Phones + ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [ + /android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i // Mi Pad tablets + ],[[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, TABLET]], [ + /android.+;\s(m[1-5]\snote)\sbuild/i // Meizu Tablet + ], [MODEL, [VENDOR, 'Meizu'], [TYPE, TABLET]], [ + + /android.+a000(1)\s+build/i // OnePlus + ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [ + + /android.+[;\/]\s*(RCT[\d\w]+)\s+build/i // RCA Tablets + ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Venue[\d\s]*)\s+build/i // Dell Venue Tablets + ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i // Verizon Tablet + ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [ + + /android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i // Barnes & Noble Tablet + ], [[VENDOR, 'Barnes & Noble'], MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i // Barnes & Noble Tablet + ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i // ZTE K Series Tablet + ], [[VENDOR, 'ZTE'], MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*(gen\d{3})\s+build.*49h/i // Swiss GEN Mobile + ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [ + + /android.+[;\/]\s*(zur\d{3})\s+build/i // Swiss ZUR Tablet + ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i // Zeki Tablets + ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [ + + /(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i, + /android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i // Dragon Touch Tablet + ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*(NS-?.+)\s+build/i // Insignia Tablets + ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*((NX|Next)-?.+)\s+build/i // NextBook Tablets + ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i + ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [ // Voice Xtreme Phones + + /android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i // LvTel Phones + ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [ + + /android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i // Envizen Tablets + ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i // Le Pan Tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i // MachSpeed Tablets + ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i // Trinity Tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*TU_(1491)\s+build/i // Rotor Tablets + ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [ + + /android.+(KS(.+))\s+build/i // Amazon Kindle Tablets + ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [ + + /android.+(Gigaset)[\s\-]+(Q.+)\s+build/i // Gigaset Tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /\s(tablet|tab)[;\/]/i, // Unidentifiable Tablet + /\s(mobile)(?:[;\/]|\ssafari)/i // Unidentifiable Mobile + ], [[TYPE, util.lowerize], VENDOR, MODEL], [ + + /(android.+)[;\/].+build/i // Generic Android Device + ], [MODEL, [VENDOR, 'Generic']] + + + /*////////////////////////// + // TODO: move to string map + //////////////////////////// + + /(C6603)/i // Sony Xperia Z C6603 + ], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ + /(C6903)/i // Sony Xperia Z 1 + ], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ + + /(SM-G900[F|H])/i // Samsung Galaxy S5 + ], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-G7102)/i // Samsung Galaxy Grand 2 + ], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-G530H)/i // Samsung Galaxy Grand Prime + ], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-G313HZ)/i // Samsung Galaxy V + ], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-T805)/i // Samsung Galaxy Tab S 10.5 + ], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ + /(SM-G800F)/i // Samsung Galaxy S5 Mini + ], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-T311)/i // Samsung Galaxy Tab 3 8.0 + ], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ + + /(T3C)/i // Advan Vandroid T3C + ], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [ + /(ADVAN T1J\+)/i // Advan Vandroid T1J+ + ], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [ + /(ADVAN S4A)/i // Advan Vandroid S4A + ], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [ + + /(V972M)/i // ZTE V972M + ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [ + + /(i-mobile)\s(IQ\s[\d\.]+)/i // i-mobile IQ + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + /(IQ6.3)/i // i-mobile IQ IQ 6.3 + ], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ + /(i-mobile)\s(i-style\s[\d\.]+)/i // i-mobile i-STYLE + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + /(i-STYLE2.1)/i // i-mobile i-STYLE 2.1 + ], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ + + /(mobiistar touch LAI 512)/i // mobiistar touch LAI 512 + ], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [ + + ///////////// + // END TODO + ///////////*/ + + ], + + engine : [[ + + /windows.+\sedge\/([\w\.]+)/i // EdgeHTML + ], [VERSION, [NAME, 'EdgeHTML']], [ + + /(presto)\/([\w\.]+)/i, // Presto + /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m + /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links + /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab + ], [NAME, VERSION], [ + + /rv\:([\w\.]+).*(gecko)/i // Gecko + ], [VERSION, NAME] + ], + + os : [[ + + // Windows based + /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes) + ], [NAME, VERSION], [ + /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT + /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i, // Windows Phone + /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i + ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ + /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i + ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ + + // Mobile/Embedded OS + /\((bb)(10);/i // BlackBerry 10 + ], [[NAME, 'BlackBerry'], VERSION], [ + /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry + /(tizen)[\/\s]([\w\.]+)/i, // Tizen + /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i, + // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki + /linux;.+(sailfish);/i // Sailfish OS + ], [NAME, VERSION], [ + /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian + ], [[NAME, 'Symbian'], VERSION], [ + /\((series40);/i // Series 40 + ], [NAME], [ + /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS + ], [[NAME, 'Firefox OS'], VERSION], [ + + // Console + /(nintendo|playstation)\s([wids34portablevu]+)/i, // Nintendo/Playstation + + // GNU/Linux based + /(mint)[\/\s\(]?(\w+)*/i, // Mint + /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux + /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i, + // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware + // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus + /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux + /(gnu)\s?([\w\.]+)*/i // GNU + ], [NAME, VERSION], [ + + /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS + ], [[NAME, 'Chromium OS'], VERSION],[ + + // Solaris + /(sunos)\s?([\w\.]+\d)*/i // Solaris + ], [[NAME, 'Solaris'], VERSION], [ + + // BSD based + /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly + ], [NAME, VERSION],[ + + /(haiku)\s(\w+)/i // Haiku + ], [NAME, VERSION],[ + + /cfnetwork\/.+darwin/i, + /ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i // iOS + ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [ + + /(mac\sos\sx)\s?([\w\s\.]+\w)*/i, + /(macintosh|mac(?=_powerpc)\s)/i // Mac OS + ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [ + + // Other + /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i, // Solaris + /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX + /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i, + // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS + /(unix)\s?([\w\.]+)*/i // UNIX + ], [NAME, VERSION] + ] + }; + + + ///////////////// + // Constructor + //////////////// + /* + var Browser = function (name, version) { + this[NAME] = name; + this[VERSION] = version; + }; + var CPU = function (arch) { + this[ARCHITECTURE] = arch; + }; + var Device = function (vendor, model, type) { + this[VENDOR] = vendor; + this[MODEL] = model; + this[TYPE] = type; + }; + var Engine = Browser; + var OS = Browser; + */ + var UAParser = function (uastring, extensions) { + + if (typeof uastring === 'object') { + extensions = uastring; + uastring = undefined; + } + + if (!(this instanceof UAParser)) { + return new UAParser(uastring, extensions).getResult(); + } + + var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); + var rgxmap = extensions ? util.extend(regexes, extensions) : regexes; + //var browser = new Browser(); + //var cpu = new CPU(); + //var device = new Device(); + //var engine = new Engine(); + //var os = new OS(); + + this.getBrowser = function () { + var browser = { name: undefined, version: undefined }; + mapper.rgx.call(browser, ua, rgxmap.browser); + browser.major = util.major(browser.version); // deprecated + return browser; + }; + this.getCPU = function () { + var cpu = { architecture: undefined }; + mapper.rgx.call(cpu, ua, rgxmap.cpu); + return cpu; + }; + this.getDevice = function () { + var device = { vendor: undefined, model: undefined, type: undefined }; + mapper.rgx.call(device, ua, rgxmap.device); + return device; + }; + this.getEngine = function () { + var engine = { name: undefined, version: undefined }; + mapper.rgx.call(engine, ua, rgxmap.engine); + return engine; + }; + this.getOS = function () { + var os = { name: undefined, version: undefined }; + mapper.rgx.call(os, ua, rgxmap.os); + return os; + }; + this.getResult = function () { + return { + ua : this.getUA(), + browser : this.getBrowser(), + engine : this.getEngine(), + os : this.getOS(), + device : this.getDevice(), + cpu : this.getCPU() + }; + }; + this.getUA = function () { + return ua; + }; + this.setUA = function (uastring) { + ua = uastring; + //browser = new Browser(); + //cpu = new CPU(); + //device = new Device(); + //engine = new Engine(); + //os = new OS(); + return this; + }; + return this; + }; + + UAParser.VERSION = LIBVERSION; + UAParser.BROWSER = { + NAME : NAME, + MAJOR : MAJOR, // deprecated + VERSION : VERSION + }; + UAParser.CPU = { + ARCHITECTURE : ARCHITECTURE + }; + UAParser.DEVICE = { + MODEL : MODEL, + VENDOR : VENDOR, + TYPE : TYPE, + CONSOLE : CONSOLE, + MOBILE : MOBILE, + SMARTTV : SMARTTV, + TABLET : TABLET, + WEARABLE: WEARABLE, + EMBEDDED: EMBEDDED + }; + UAParser.ENGINE = { + NAME : NAME, + VERSION : VERSION + }; + UAParser.OS = { + NAME : NAME, + VERSION : VERSION + }; + //UAParser.Utils = util; + + /////////// + // Export + ////////// + + + // check js environment + if ('object' !== UNDEF_TYPE) { + // nodejs env + if ('object' !== UNDEF_TYPE && module.exports) { + exports = module.exports = UAParser; + } + // TODO: test!!!!!!!! + /* + if (require && require.main === module && process) { + // cli + var jsonize = function (arr) { + var res = []; + for (var i in arr) { + res.push(new UAParser(arr[i]).getResult()); + } + process.stdout.write(JSON.stringify(res, null, 2) + '\n'); + }; + if (process.stdin.isTTY) { + // via args + jsonize(process.argv.slice(2)); + } else { + // via pipe + var str = ''; + process.stdin.on('readable', function() { + var read = process.stdin.read(); + if (read !== null) { + str += read; + } + }); + process.stdin.on('end', function () { + jsonize(str.replace(/\n$/, '').split('\n')); + }); + } + } + */ + exports.UAParser = UAParser; + } else { + // requirejs env (optional) + if (typeof(undefined) === FUNC_TYPE && undefined.amd) { + undefined(function () { + return UAParser; + }); + } else if (window) { + // browser env + window.UAParser = UAParser; + } + } + + // jQuery/Zepto specific (optional) + // Note: + // In AMD env the global scope should be kept clean, but jQuery is an exception. + // jQuery always exports to global scope, unless jQuery.noConflict(true) is used, + // and we should catch that. + var $ = window && (window.jQuery || window.Zepto); + if (typeof $ !== UNDEF_TYPE) { + var parser = new UAParser(); + $.ua = parser.getResult(); + $.ua.get = function () { + return parser.getUA(); + }; + $.ua.set = function (uastring) { + parser.setUA(uastring); + var result = parser.getResult(); + for (var prop in result) { + $.ua[prop] = result[prop]; + } + }; + } + +})(typeof window === 'object' ? window : commonjsGlobal); +}); +var uaParser_1 = uaParser.UAParser; + +/** + * the handler to generate an deep traversal handler + * @param {Function} fn the function you wanna run when you reach in the deep property + * @return {Function} the handler + */ +function genTraversalHandler(fn) { + var setter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (target, key, value) { + target[key] = value; + }; + + // use recursive to move what in source to the target + // if you do not provide a target, we will create a new target + function recursiveFn(source, target, key) { + if (isArray(source) || isObject(source)) { + target = isPrimitive(target) ? isObject(source) ? {} : [] : target; + for (var _key in source) { + // $FlowFixMe: support computed key here + setter(target, _key, recursiveFn(source[_key], target[_key], _key)); + // target[key] = recursiveFn(source[key], target[key], key); + } + return target; + } + return fn(source, target, key); + } + return recursiveFn; +} +var _deepAssign = genTraversalHandler(function (val) { + return val; +}); +/** + * deeply clone an object + * @param {Array|Object} source if you pass in other type, it will throw an error + * @return {clone-target} the new Object + */ +function deepClone(source) { + if (isPrimitive(source)) { + throw new TypeError('deepClone only accept non primitive type'); + } + return _deepAssign(source); +} +/** + * merge multiple objects + * @param {...Object} args [description] + * @return {merge-object} [description] + */ +function deepAssign() { + for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { + args[_key2] = arguments[_key2]; + } + + if (args.length < 2) { + throw new Error('deepAssign accept two and more argument'); + } + for (var i = args.length - 1; i > -1; i--) { + if (isPrimitive(args[i])) { + throw new TypeError('deepAssign only accept non primitive type'); + } + } + var target = args.shift(); + args.forEach(function (source) { + return _deepAssign(source, target); + }); + return target; +} + +/** + * camelize any string, e.g hello world -> helloWorld + * @param {string} str only accept string! + * @return {string} camelize string + */ +function camelize(str, isBig) { + return str.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g, function (match, spilt, initials, index) { + return !isBig && index === 0 ? initials.toLowerCase() : initials.toUpperCase(); + }); +} +/** + * hypenate any string e.g hello world -> hello-world + * @param {string} str only accept string + * @return {string} + */ +function hypenate(str) { + return camelize(str).replace(/([A-Z])/g, function (match) { + return '-' + match.toLowerCase(); + }); +} + +/** + * bind the function with some context. we have some fallback strategy here + * @param {function} fn the function which we need to bind the context on + * @param {any} context the context object + */ +function bind(fn, context) { + if (fn.bind) { + return fn.bind(context); + } else if (fn.apply) { + return function __autobind__() { + for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { + args[_key3] = arguments[_key3]; + } + + return fn.apply(context, args); + }; + } else { + return function __autobind__() { + for (var _len3 = arguments.length, args = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { + args[_key4] = arguments[_key4]; + } + + return fn.call.apply(fn, [context].concat(_toConsumableArray(args))); + }; + } +} + +/** + * generate an uuid + */ +function uuid() { + return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); +} +/** + * generate an random number which length is 4 + */ +function S4() { + return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1); +} + +/** + * get an deep property + */ +function getDeepProperty(obj, keys) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$throwError = _ref.throwError, + throwError = _ref$throwError === undefined ? false : _ref$throwError, + backup = _ref.backup; + + if (isString(keys)) { + keys = keys.split('.'); + } + if (!isArray(keys)) { + throw new TypeError('keys of getDeepProperty must be string or Array'); + } + var read = []; + var target = obj; + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + if (isVoid(target)) { + if (throwError) { + throw new Error('obj' + (read.length > 0 ? '.' + read.join('.') : ' itself') + ' is ' + target); + } else { + return backup; + } + } + target = target[key]; + read.push(key); + } + return target; +} + +// ********************** judgement ************************ +/** + * check if the code running in browser environment (not include worker env) + * @returns {Boolean} + */ +var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; + +// ********************** 对象操作 ************************ +/** + * 转变一个类数组对象为数组 + */ +function makeArray(obj) { + return _Array$from(obj); +} + +/** + * sort Object attributes by function + * and transfer them into array + * @param {Object} obj Object form from numric + * @param {Function} fn sort function + * @return {Array} the sorted attirbutes array + */ +function transObjectAttrIntoArray(obj) { + var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) { + return +a - +b; + }; + + return _Object$keys(obj).sort(fn).reduce(function (order, key) { + return order.concat(obj[key]); + }, []); +} +/** + * run a queue one by one.If include function reject or return false it will stop + * @param {Array} queue the queue which we want to run one by one + * @return {Promise} tell us whether a queue run finished + */ +function runRejectableQueue(queue) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + return new _Promise(function (resolve, reject) { + var step = function step(index) { + if (index >= queue.length) { + resolve(); + return; + } + var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; + if (result === false) return reject('stop'); + return _Promise.resolve(result).then(function () { + return step(index + 1); + }).catch(function (err) { + return reject(err || 'stop'); + }); + }; + step(0); + }); +} +/** + * run a queue one by one.If include function return false it will stop + * @param {Array} queue the queue which we want to run one by one + * @return {boolean} tell the user if the queue run finished + */ +function runStoppableQueue(queue) { + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + var step = function step(index) { + if (index >= queue.length) { + return true; + } + var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; + if (result === false) return false; + return step(++index); + }; + return step(0); +} + +// requestAnimationFrame +var raf = inBrowser && (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame) || function (cb) { + return setTimeout(cb, 17); +}; + +// cancelAnimationFrame +var caf = inBrowser && (window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame) || function (id) { + clearTimeout(id); +}; + +// 根据要求的位数,将9格式化为 09\009\0009... +function strRepeat(num, bit) { + var pBit = bit; + num = '' + (num || ''); + var numLen = num.length; + bit = (bit || numLen) - numLen; + var paddingStr = bit > 0 ? num.repeat ? '0'.repeat(bit) : new Array(bit + 1).join('0') : ''; + return (paddingStr + num).slice(0, pBit); +} + +// video 时间格式化 +function formatTime(time) { + var hh = Math.floor(time / 3600); + time = Math.floor(time % 3600); + var mm = strRepeat(Math.floor(time / 60), 2); + time = Math.floor(time % 60); + var ss = strRepeat(time, 2); + return hh >= 1 ? hh + ':' + mm + ':' + ss : mm + ':' + ss; +} + +/** + * 格式化日期对象为:年-月-日 时:分:秒.毫秒 + * @param {Date} date Date日期对象 + * @param {String} pattern 要输出的日期格式,默认:`yyyy-MM-dd hh:mm:ss.i` + * @return {String} + */ +function formatDate() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'yyyy-MM-dd hh:mm:ss.i'; + + var year = date.getFullYear().toString(); + var fields = { + M: date.getMonth() + 1, + d: date.getDate(), + h: date.getHours(), + m: date.getMinutes(), + s: date.getSeconds(), + i: date.getMilliseconds() + }; + pattern = pattern.replace(/(y+)/ig, function (_, yearPattern) { + return year.substr(4 - Math.min(4, yearPattern.length)); + }); + + var _loop = function _loop(i) { + pattern = pattern.replace(new RegExp('(' + i + '+)', 'g'), function (_, pattStr) { + return (fields[i] < 10 && pattStr.length > 1 ? '0' : '') + fields[i]; + }); + }; + + for (var i in fields) { + _loop(i); + } + return pattern; +} + +/** + * 读取本地存储的值(不支持localStorage则降级到cookie) + * @param {String} key 目标数据key + * @return {String} + */ +function getLocalStorage(key) { + try { + return window.localStorage.getItem(key); + } catch (e) { + try { + var regRt = document.cookie.match(new RegExp('(^| )' + key + '=([^;]*)(;|$)')); + return isArray(regRt) ? unescape(regRt[2]) : ''; + } catch (e) { + return ''; + } + } +} +/** + * 将指定key对应值写入本地存储(不支持localStorage则降级到cookie) + * @param {String} key + * @param {String} val + * @return {String} + */ +function setLocalStorage(key, val) { + try { + window.localStorage.setItem(key, val); + } catch (e) { + var expires = new Date(); + // 默认存储300天 + expires.setTime(expires.getTime() + 24 * 3600 * 1000 * 300); + try { + document.cookie = key + '=' + escape(val) + ';expires=' + expires.toUTCString() + ';path=/;'; + } catch (e) { + console.error(e); + } + } +} + +// 19.1.2.1 Object.assign(target, source, ...) + + + + + +var $assign = Object.assign; + +// should work with symbols and should have deterministic property order (V8 bug) +var _objectAssign = !$assign || _fails(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = _toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = _objectGops.f; + var isEnum = _objectPie.f; + while (aLen > index) { + var S = _iobject(arguments[index++]); + var keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; +} : $assign; + +// 19.1.3.1 Object.assign(target, source) + + +_export(_export.S + _export.F, 'Object', { assign: _objectAssign }); + +var assign = _core.Object.assign; + +var assign$1 = createCommonjsModule(function (module) { +module.exports = { "default": assign, __esModule: true }; +}); + +var _Object$assign = unwrapExports(assign$1); + +/** +* @module event +* @author huzunjie +* @description 自定义事件基础类 +*/ + +/* 缓存事件监听方法及包装,内部数据格式: + * targetIndex_: [ [ + * function(){ ... handler ... }, + * function(){ ... handlerWrap ... handler.apply(target, arguments) ... }, + * isOnce + * ]] + */ +var _evtListenerCache = _Object$create(null); +_evtListenerCache.count = 0; + +/** + * 得到某对象的某事件类型对应的监听队列数组 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型(这里的时间类型不只是名称,还是缓存标识,可以通过添加后缀来区分) + * @return {Array} + */ +function getEvtTypeCache(target, type) { + + var evtId = target.__evt_id; + if (!evtId) { + + /* 设置__evt_id不可枚举 */ + Object.defineProperty(target, '__evt_id', { + writable: true, + enumerable: false, + configurable: true + }); + + /* 空对象初始化绑定索引 */ + evtId = target.__evt_id = ++_evtListenerCache.count; + } + + var typeCacheKey = evtId + '_' + type; + var evtTypeCache = _evtListenerCache[typeCacheKey]; + if (!evtTypeCache) { + evtTypeCache = _evtListenerCache[typeCacheKey] = []; + } + + return evtTypeCache; +} + +/** + * 触发事件监听方法 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Object} eventObj 触发事件时要传回的event对象 + * @return {undefined} + */ +function emitEventCache(target, type, eventObj) { + var evt = _Object$create(null); + evt.type = type; + evt.target = target; + if (eventObj) { + _Object$assign(evt, isObject(eventObj) ? eventObj : { data: eventObj }); + } + getEvtTypeCache(target, type).forEach(function (item) { + (item[1] || item[0]).apply(target, [evt]); + }); +} + +/** + * 添加事件监听到缓存 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 是否单次执行 + * @param {Function} handlerWrap + * @return {undefined} + */ +function addEventCache(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var handlerWrap = arguments[4]; + + if (isFunction(isOnce) && !handlerWrap) { + handlerWrap = isOnce; + isOnce = undefined; + } + var handlers = [handler, undefined, isOnce]; + if (isOnce && !handlerWrap) { + handlerWrap = function handlerWrap() { + removeEventCache(target, type, handler, isOnce); + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + handler.apply(target, args); + }; + } + if (handlerWrap) { + handlers[1] = handlerWrap; + } + getEvtTypeCache(target, type).push(handlers); +} + +/** + * 移除事件监听 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {undefined} + */ +function removeEventCache(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var typeCache = getEvtTypeCache(target, type); + + if (handler || isOnce) { + /* 有指定 handler 则清除对应监听 */ + var handlerId = -1; + var handlerWrap = void 0; + typeCache.find(function (item, i) { + if ((!handler || item[0] === handler) && (!isOnce || item[2])) { + handlerId = i; + handlerWrap = item[1]; + return true; + } + }); + if (handlerId !== -1) { + typeCache.splice(handlerId, 1); + } + return handlerWrap; + } else { + /* 未指定 handler 则清除type对应的所有监听 */ + typeCache.length = 0; + } +} + +/** + * @class CustEvent + * @description + * Event 自定义事件类 + * 1. 可以使用不传参得到的实例作为eventBus使用 + * 2. 可以通过指定target,用多个实例操作同一target对象的事件管理 + * 3. 当设定target时,可以通过设置assign为true,来给target实现"on\once\off\emit"方法 + * @param {Object} target 发生事件的对象(空则默认为event实例) + * @param {Boolean} assign 是否将"on\once\off\emit"方法实现到target对象上 + * @return {event} + */ +var CustEvent = function () { + function CustEvent(target, assign) { + var _this = this; + + _classCallCheck(this, CustEvent); + + /* 设置__target不可枚举 */ + Object.defineProperty(this, '__target', { + writable: true, + enumerable: false, + configurable: true + }); + this.__target = this; + + if (target) { + + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') { + throw new Error('CusEvent target are not object'); + } + this.__target = target; + + /* 为target实现on\once\off\emit */ + if (assign) { + ['on', 'once', 'off', 'emit'].forEach(function (mth) { + target[mth] = _this[mth]; + }); + } + } + } + + /** + * 添加事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + + _createClass(CustEvent, [{ + key: 'on', + value: function on(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + addEventCache(this.__target, type, handler, isOnce); + return this; + } + + /** + * 添加事件监听,并且只执行一次 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {event} + */ + + }, { + key: 'once', + value: function once(type, handler) { + return this.on(type, handler, true); + } + + /** + * 移除事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数(不指定handler则清除type对应的所有事件监听) + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + }, { + key: 'off', + value: function off(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + removeEventCache(this.__target, type, handler, isOnce); + return this; + } + + /** + * 触发事件监听函数 + * @param {String} type 事件类型 + * @return {event} + */ + + }, { + key: 'emit', + value: function emit(type, data) { + emitEventCache(this.__target, type, { data: data }); + return this; + } + }]); + + return CustEvent; +}(); + +/** + * @module dom + * @author huzunjie + * @description 一些常用的DOM判断及操作方法,可以使用dom.$('*')包装DOM,实现类jQuery的链式操作;当然这里的静态方法也可以直接使用。 + */ + +var _divEl = inBrowser ? document.createElement('div') : {}; +var _textAttrName = 'innerText'; +'textContent' in _divEl && (_textAttrName = 'textContent'); +var _arrPrototype = Array.prototype; + +/** + * 读取HTML元素属性值 + * @param {HTMLElement} el 目标元素 + * @param {String} attrName 目标属性名称 + * @return {String} + */ +function getAttr(el, attrName) { + return el.getAttribute(attrName); +} + +/** + * 设置HTML元素属性值 + * @param {HTMLElement} el 目标元素 + * @param {String} attrName 目标属性名称 + * @param {String} attrVal 目标属性值 + */ +function setAttr(el, attrName, attrVal) { + if (attrVal === undefined) { + el.removeAttribute(attrName); + } else { + el.setAttribute(attrName, attrVal); + } +} + +/** + * 为HTML元素添加className + * @param {HTMLElement} el 目标元素 + * @param {String} cls 要添加的className(多个以空格分割) + */ +function addClassName(el, cls) { + if (!cls || !(cls = cls.trim())) { + return; + } + var clsArr = cls.split(/\s+/); + if (el.classList) { + clsArr.forEach(function (c) { + return el.classList.add(c); + }); + } else { + var curCls = ' ' + (el.className || '') + ' '; + clsArr.forEach(function (c) { + curCls.indexOf(' ' + c + ' ') === -1 && (curCls += ' ' + c); + }); + el.className = curCls.trim(); + } +} + +/** + * 为HTML元素移除className + * @param {HTMLElement} el 目标元素 + * @param {String} cls 要移除的className(多个以空格分割) + */ +function removeClassName(el, cls) { + if (!cls || !(cls = cls.trim())) { + return; + } + + var clsArr = cls.split(/\s+/); + if (el.classList) { + clsArr.forEach(function (c) { + return el.classList.remove(c); + }); + } else { + var curCls = ' ' + el.className + ' '; + clsArr.forEach(function (c) { + var tar = ' ' + c + ' '; + while (curCls.indexOf(tar) !== -1) { + curCls = curCls.replace(tar, ' '); + } + }); + el.className = curCls.trim(); + } +} + +/** + * 检查HTML元素是否已设置className + * @param {HTMLElement} el 目标元素 + * @param {String} className 要检查的className + * @return {Boolean} + */ +function hasClassName(el, className) { + return new RegExp('(?:^|\\s)' + className + '(?=\\s|$)').test(el.className); +} + +/** + * addEventListener 是否已支持 passive + * @return {Boolean} + */ +var supportsPassive = false; +try { + var opts = Object.defineProperty({}, 'passive', { + get: function get() { + supportsPassive = true; + } + }); + if (inBrowser) window.addEventListener('test', null, opts); +} catch (e) { + console.error(e); +} + +/** + * 为HTML元素移除事件监听 + * @param {HTMLElement} el 目标元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段的监听 + */ +function removeEvent(el, type, handler) { + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + if (capture !== undefined && !isBoolean(capture) && supportsPassive) { + capture = { passive: true }; + } + if (once) { + /* 尝试从缓存中读取包装后的方法 */ + var handlerWrap = removeEventCache(el, type + '_once', handler); + if (handlerWrap) { + handler = handlerWrap; + } + } + el.removeEventListener(type, handler, capture); +} + +/** + * 为HTML元素添加事件监听 + * @param {HTMLElement} el 目标元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean|Object} capture 是否在捕获阶段监听,这里也可以传入 { passive: true } 表示被动模式 + */ +function addEvent(el, type, handler) { + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + if (capture !== undefined && !isBoolean(capture) && supportsPassive) { + capture = { passive: true }; + } + if (once) { + var oldHandler = handler; + handler = function () { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + oldHandler.apply(this, args); + removeEvent(el, type, handler, once, capture); + }; + }(); + /* 将包装后的方法记录到缓存中 */ + addEventCache(el, type + '_once', oldHandler, handler); + } + + el.addEventListener(type, handler, capture); +} + +/** + * 为HTML元素添加事件代理 + * @param {HTMLElement} el 目标元素 + * @param {String} selector 要被代理的元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + */ +function addDelegate(el, selector, type, handler) { + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + if (capture !== undefined && !isBoolean(capture) && supportsPassive) { + capture = { passive: true }; + } + var handlerWrap = function handlerWrap(e) { + var targetElsArr = findParents(e.target || e.srcElement, el, true); + var targetElArr = query(selector, el, true); + var retEl = void 0; + if (targetElArr.find) { + retEl = targetElArr.find(function (seEl) { + return targetElsArr.find(function (tgEl) { + return seEl === tgEl; + }); + }); + } else { + // Fixed IE11 Array.find not defined bug + targetElArr.forEach(function (seEl) { + return !retEl && targetElsArr.forEach(function (tgEl) { + if (!retEl && seEl === tgEl) { + retEl = tgEl; + } + }); + }); + } + retEl && handler.apply(retEl, arguments); + }; + /* 将包装后的方法记录到缓存中 */ + addEventCache(el, type + '_delegate_' + selector, handler, handlerWrap); + el.addEventListener(type, handlerWrap, capture); +} + +/** + * 为HTML元素移除事件代理 + * @param {HTMLElement} el 目标元素 + * @param {String} selector 要被代理的元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + */ +function removeDelegate(el, selector, type, handler) { + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + if (capture !== undefined && !isBoolean(capture) && supportsPassive) { + capture = { passive: true }; + } + /* 尝试从缓存中读取包装后的方法 */ + var handlerWrap = removeEventCache(el, type + '_delegate_' + selector, handler); + handlerWrap && el.removeEventListener(type, handlerWrap, capture); +} + +/** + * 读取HTML元素样式值 + * @param {HTMLElement} el 目标元素 + * @param {String} key 样式key + * @return {String} + */ +function getStyle(el, key) { + return (el.currentStyle || document.defaultView.getComputedStyle(el, null))[key] || el.style[key]; +} + +/** + * 设置HTML元素样式值 + * @param {HTMLElement} el 目标元素 + * @param {String} key 样式key + * @param {String} val 样式值 + */ +function setStyle(el, key, val) { + if (isObject(key)) { + for (var k in key) { + setStyle(el, k, key[k]); + } + } else { + el.style[key] = val; + } +} + +/** + * 根据选择器查询目标元素 + * @param {String} selector 选择器,用于 querySelectorAll + * @param {HTMLElement} container 父容器 + * @param {Boolean} toArray 强制输出为数组 + * @return {NodeList|Array} + */ +function query(selector) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; + var toArray = arguments[2]; + + var retNodeList = container.querySelectorAll(selector); + return toArray ? _Array$from(retNodeList) : retNodeList; +} + +/** + * 从DOM树中移除el + * @param {HTMLElement} el 目标元素 + */ +function removeEl(el) { + el.parentNode.removeChild(el); +} + +/** + * 查找元素的父节点们 + * @param {HTMLElement} el 目标元素 + * @param {HTMLElement} endEl 最大父容器(不指定则找到html) + * @param {Boolean} haveEl 包含当前元素 + * @param {Boolean} haveEndEl 包含设定的最大父容器 + */ +function findParents(el) { + var endEl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var haveEl = arguments[2]; + var haveEndEl = arguments[3]; + + var retEls = []; + if (haveEl) { + retEls.push(el); + } + while (el && el.parentNode !== endEl) { + el = el.parentNode; + el && retEls.push(el); + } + if (haveEndEl) { + retEls.push(endEl); + } + return retEls; +} + +/** + * @class NodeWrap + * @description + * NodeWrap DOM包装器,用以实现基本的链式操作 + * new dom.NodeWrap('*') 相当于 dom.$('*') + * 这里面用于DOM操作的属性方法都是基于上面静态方法实现,有需要可以随时修改补充 + * @param {String} selector 选择器(兼容 String||HTMLString||NodeList||NodeArray||HTMLElement) + * @param {HTMLElement} container 父容器(默认为document) + */ + +var NodeWrap = function () { + function NodeWrap(selector) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; + + _classCallCheck(this, NodeWrap); + + var _this = this; + _this.selector = selector; + + /* String||NodeList||HTMLElement 识别处理 */ + var elsArr = void 0; + if (selector && selector.constructor === NodeList) { + /* 支持直接传入NodeList来构建包装器 */ + elsArr = makeArray(selector); + } else if (isArray(selector)) { + /* 支持直接传入Node数组来构建包装器 */ + elsArr = selector; + } else if (isString(selector)) { + if (selector.indexOf('<') === 0) { + /* 支持直接传入HTML字符串来新建DOM并构建包装器 */ + _divEl.innerHTML = selector; + elsArr = query('*', _divEl, true); + } else { + /* 支持直接传入字符串选择器来查找DOM并构建包装器 */ + elsArr = query(selector, container, true); + } + } else { + /* 其他任意对象直接构建包装器 */ + elsArr = [selector]; + } + _Object$assign(_this, elsArr); + + /* NodeWrap本意可以 extends Array省略构造方法中下面这部分代码,但目前编译不支持 */ + _this.length = elsArr.length; + } + + /** + * 循环遍历DOM集合 + * @param {Function} fn 遍历函数 fn(item, i) + * @return {Object} + */ + + + _createClass(NodeWrap, [{ + key: 'each', + value: function each() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + _arrPrototype.forEach.apply(this, args); + return this; + } + + /** + * 添加元素到DOM集合 + * @param {HTMLElement} el 要加入的元素 + * @return {this} + */ + + }, { + key: 'push', + value: function push() { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + _arrPrototype.push.apply(this, args); + return this; + } + + /** + * 截取DOM集合片段,并得到新的包装器splice + * @param {Nubmer} start + * @param {Nubmer} count + * @return {NodeWrap} 新的DOM集合包装器 + */ + + }, { + key: 'splice', + value: function splice() { + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + return $(_arrPrototype.splice.apply(this, args)); + } + + /** + * 查找子元素 + * @param {String} selector 选择器 + * @return {NodeWrap} 新的DOM集合包装器 + */ + + }, { + key: 'find', + value: function find(selector) { + var childs = []; + this.each(function (el) { + childs = childs.concat(query(selector, el, true)); + }); + var childsWrap = $(childs); + childsWrap.parent = this; + childsWrap.selector = selector; + return childsWrap; + } + + /** + * 添加子元素 + * @param {HTMLElement} childEls 要添加的HTML元素 + * @return {this} + */ + + }, { + key: 'append', + value: function append(childEls) { + var childsWrap = $(childEls); + var firstEl = this[0]; + childsWrap.each(function (newEl) { + return firstEl.appendChild(newEl); + }); + return this; + } + + /** + * 将元素集合添加到指定容器 + * @param {HTMLElement} parentEl 要添加到父容器 + * @return {this} + */ + + }, { + key: 'appendTo', + value: function appendTo(parentEl) { + $(parentEl).append(this); + return this; + } + + /** + * DOM集合text内容读写操作 + * @param {String} val 文本内容(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'text', + value: function text(val) { + if (arguments.length === 0) { + return this[0][_textAttrName]; + } + return this.each(function (el) { + el[_textAttrName] = val; + }); + } + + /** + * DOM集合HTML内容读写操作 + * @param {String} html html内容(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'html', + value: function html(_html) { + if (arguments.length === 0) { + return this[0].innerHTML; + } + return this.each(function (el) { + el.innerHTML = _html; + }); + } + + /** + * DOM集合属性读写操作 + * @param {String} name 属性名称 + * @param {String} val 属性值(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'attr', + value: function attr(name, val) { + if (arguments.length === 1) { + return getAttr(this[0], name); + } + return this.each(function (el) { + return setAttr(el, name, val); + }); + } + + /** + * DOM集合dataset读写操作 + * @param {String} key 键名 + * @param {Any} val 键值(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'data', + value: function data(key, val) { + if (arguments.length === 0) { + return this[0].dataset || {}; + } + if (arguments.length === 1) { + return (this[0].dataset || {})[key]; + } + return this.each(function (el) { + (el.dataset || (el.dataset = {}))[key] = val; + }); + } + + /** + * DOM集合样式读写操作 + * @param {String} key 样式key + * @param {String} val 样式值(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'css', + value: function css(key, val) { + if (arguments.length === 1 && !isObject(key)) { + return getStyle(this[0], key); + } + return this.each(function (el) { + return setStyle(el, key, val); + }); + } + + /** + * 为DOM集合增加className + * @param {String} cls 要增加的className + * @return {this} + */ + + }, { + key: 'addClass', + value: function addClass(cls) { + return this.each(function (el) { + return addClassName(el, cls); + }); + } + + /** + * 移除当前DOM集合的className + * @param {String} cls 要移除的className + * @return {this} + */ + + }, { + key: 'removeClass', + value: function removeClass(cls) { + return this.each(function (el) { + return removeClassName(el, cls); + }); + } + + /** + * 检查索引0的DOM是否有className + * @param {String} cls 要检查的className + * @return {this} + */ + + }, { + key: 'hasClass', + value: function hasClass(cls) { + return hasClassName(this[0], cls); + } + + /** + * 为DOM集合添加事件监听 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'on', + value: function on(type, handler) { + var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + return this.each(function (el) { + return addEvent(el, type, handler, once, capture); + }); + } + + /** + * 为DOM集合解除事件监听 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'off', + value: function off(type, handler) { + var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + return this.each(function (el) { + return removeEvent(el, type, handler, once, capture); + }); + } + + /** + * 为DOM集合绑定事件代理 + * @param {String} selector 目标子元素选择器 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'delegate', + value: function delegate(selector, type, handler) { + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + return this.each(function (el) { + return addDelegate(el, selector, type, handler, capture); + }); + } + + /** + * 为DOM集合解绑事件代理 + * @param {String} selector 目标子元素选择器 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'undelegate', + value: function undelegate(selector, type, handler) { + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + return this.each(function (el) { + return removeDelegate(el, selector, type, handler, capture); + }); + } + + /** + * 从DOM树中移除 + * @return {this} + */ + + }, { + key: 'remove', + value: function remove() { + return this.each(function (el) { + return removeEl(el); + }); + } + }]); + + return NodeWrap; +}(); + +function $(selector, container) { + return selector.constructor === NodeWrap ? selector : new NodeWrap(selector, container); +} + +// all object keys, includes non-enumerable and symbols + + + +var Reflect = _global.Reflect; +var _ownKeys = Reflect && Reflect.ownKeys || function ownKeys(it) { + var keys = _objectGopn.f(_anObject(it)); + var getSymbols = _objectGops.f; + return getSymbols ? keys.concat(getSymbols(it)) : keys; +}; + +// https://github.com/tc39/proposal-object-getownpropertydescriptors + + + + + + +_export(_export.S, 'Object', { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { + var O = _toIobject(object); + var getDesc = _objectGopd.f; + var keys = _ownKeys(O); + var result = {}; + var i = 0; + var key, desc; + while (keys.length > i) { + desc = getDesc(O, key = keys[i++]); + if (desc !== undefined) _createProperty(result, key, desc); + } + return result; + } +}); + +var getOwnPropertyDescriptors = _core.Object.getOwnPropertyDescriptors; + +var getOwnPropertyDescriptors$1 = createCommonjsModule(function (module) { +module.exports = { "default": getOwnPropertyDescriptors, __esModule: true }; +}); + +var _Object$getOwnPropertyDescriptors = unwrapExports(getOwnPropertyDescriptors$1); + +var getOwnPropertySymbols = _core.Object.getOwnPropertySymbols; + +var getOwnPropertySymbols$1 = createCommonjsModule(function (module) { +module.exports = { "default": getOwnPropertySymbols, __esModule: true }; +}); + +var _Object$getOwnPropertySymbols = unwrapExports(getOwnPropertySymbols$1); + +// 19.1.2.7 Object.getOwnPropertyNames(O) +_objectSap('getOwnPropertyNames', function () { + return _objectGopnExt.f; +}); + +var $Object$3 = _core.Object; +var getOwnPropertyNames = function getOwnPropertyNames(it) { + return $Object$3.getOwnPropertyNames(it); +}; + +var getOwnPropertyNames$1 = createCommonjsModule(function (module) { +module.exports = { "default": getOwnPropertyNames, __esModule: true }; +}); + +var _Object$getOwnPropertyNames = unwrapExports(getOwnPropertyNames$1); + +/** + * bind the function with some context. we have some fallback strategy here + * @param {function} fn the function which we need to bind the context on + * @param {any} context the context object + */ +function bind$1(fn, context) { + if (fn.bind) { + return fn.bind(context); + } else if (fn.apply) { + return function __autobind__() { + for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { + args[_key3] = arguments[_key3]; + } + + return fn.apply(context, args); + }; + } else { + return function __autobind__() { + for (var _len3 = arguments.length, args = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { + args[_key4] = arguments[_key4]; + } + + return fn.call.apply(fn, [context].concat(_toConsumableArray(args))); + }; + } +} + +/** + * get an deep property + */ +function getDeepProperty$1(obj, keys) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$throwError = _ref.throwError, + throwError = _ref$throwError === undefined ? false : _ref$throwError, + backup = _ref.backup; + + if (isString(keys)) { + keys = keys.split('.'); + } + if (!isArray(keys)) { + throw new TypeError('keys of getDeepProperty must be string or Array'); + } + var read = []; + var target = obj; + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + if (isVoid(target)) { + if (throwError) { + throw new Error('obj' + (read.length > 0 ? '.' + read.join('.') : ' itself') + ' is ' + target); + } else { + return backup; + } + } + target = target[key]; + read.push(key); + } + return target; +} + +var ITERATOR$4 = _wks('iterator'); + +var core_isIterable = _core.isIterable = function (it) { + var O = Object(it); + return O[ITERATOR$4] !== undefined + || '@@iterator' in O + // eslint-disable-next-line no-prototype-builtins + || _iterators.hasOwnProperty(_classof(O)); +}; + +var isIterable = core_isIterable; + +var isIterable$1 = createCommonjsModule(function (module) { +module.exports = { "default": isIterable, __esModule: true }; +}); + +unwrapExports(isIterable$1); + +var core_getIterator = _core.getIterator = function (it) { + var iterFn = core_getIteratorMethod(it); + if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); + return _anObject(iterFn.call(it)); +}; + +var getIterator = core_getIterator; + +var getIterator$1 = createCommonjsModule(function (module) { +module.exports = { "default": getIterator, __esModule: true }; +}); + +unwrapExports(getIterator$1); + +var slicedToArray = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _isIterable3 = _interopRequireDefault(isIterable$1); + + + +var _getIterator3 = _interopRequireDefault(getIterator$1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if ((0, _isIterable3.default)(Object(arr))) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); +}); + +var _slicedToArray = unwrapExports(slicedToArray); + +var getWeak = _meta.getWeak; + + + + + + + +var arrayFind = _arrayMethods(5); +var arrayFindIndex = _arrayMethods(6); +var id$1 = 0; + +// fallback for uncaught frozen keys +var uncaughtFrozenStore = function (that) { + return that._l || (that._l = new UncaughtFrozenStore()); +}; +var UncaughtFrozenStore = function () { + this.a = []; +}; +var findUncaughtFrozen = function (store, key) { + return arrayFind(store.a, function (it) { + return it[0] === key; + }); +}; +UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.a.push([key, value]); + }, + 'delete': function (key) { + var index = arrayFindIndex(this.a, function (it) { + return it[0] === key; + }); + if (~index) this.a.splice(index, 1); + return !!~index; + } +}; + +var _collectionWeak = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + _anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = id$1++; // collection id + that._l = undefined; // leak store for uncaught frozen objects + if (iterable != undefined) _forOf(iterable, IS_MAP, that[ADDER], that); + }); + _redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + if (!_isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(_validateCollection(this, NAME))['delete'](key); + return data && _has(data, this._i) && delete data[this._i]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + if (!_isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(_validateCollection(this, NAME)).has(key); + return data && _has(data, this._i); + } + }); + return C; + }, + def: function (that, key, value) { + var data = getWeak(_anObject(key), true); + if (data === true) uncaughtFrozenStore(that).set(key, value); + else data[that._i] = value; + return that; + }, + ufstore: uncaughtFrozenStore +}; + +var es6_weakMap = createCommonjsModule(function (module) { +var each = _arrayMethods(0); + + + + + + + +var WEAK_MAP = 'WeakMap'; +var getWeak = _meta.getWeak; +var isExtensible = Object.isExtensible; +var uncaughtFrozenStore = _collectionWeak.ufstore; +var tmp = {}; +var InternalMap; + +var wrapper = function (get) { + return function WeakMap() { + return get(this, arguments.length > 0 ? arguments[0] : undefined); + }; +}; + +var methods = { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + if (_isObject(key)) { + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(_validateCollection(this, WEAK_MAP)).get(key); + return data ? data[this._i] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return _collectionWeak.def(_validateCollection(this, WEAK_MAP), key, value); + } +}; + +// 23.3 WeakMap Objects +var $WeakMap = module.exports = _collection(WEAK_MAP, wrapper, methods, _collectionWeak, true, true); + +// IE11 WeakMap frozen keys fix +if (_fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { + InternalMap = _collectionWeak.getConstructor(wrapper, WEAK_MAP); + _objectAssign(InternalMap.prototype, methods); + _meta.NEED = true; + each(['delete', 'has', 'get', 'set'], function (key) { + var proto = $WeakMap.prototype; + var method = proto[key]; + _redefine(proto, key, function (a, b) { + // store frozen objects on internal weakmap shim + if (_isObject(a) && !isExtensible(a)) { + if (!this._f) this._f = new InternalMap(); + var result = this._f[key](a, b); + return key == 'set' ? this : result; + // store all the rest on native weakmap + } return method.call(this, a, b); + }); + }); +} +}); + +// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of +_setCollectionOf('WeakMap'); + +// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from +_setCollectionFrom('WeakMap'); + +var weakMap = _core.WeakMap; + +var weakMap$1 = createCommonjsModule(function (module) { +module.exports = { "default": weakMap, __esModule: true }; +}); + +var _WeakMap = unwrapExports(weakMap$1); + +var defineProperty$3 = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty$2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (obj, key, value) { + if (key in obj) { + (0, _defineProperty2.default)(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +}; +}); + +var _defineProperty = unwrapExports(defineProperty$3); + +// 19.1.2.15 Object.preventExtensions(O) + +var meta = _meta.onFreeze; + +_objectSap('preventExtensions', function ($preventExtensions) { + return function preventExtensions(it) { + return $preventExtensions && _isObject(it) ? $preventExtensions(meta(it)) : it; + }; +}); + +var preventExtensions = _core.Object.preventExtensions; + +var preventExtensions$1 = createCommonjsModule(function (module) { +module.exports = { "default": preventExtensions, __esModule: true }; +}); + +unwrapExports(preventExtensions$1); + +var getOwnPropertyDescriptor$2 = _Object$getOwnPropertyDescriptor; +// ********************** 对象操作 ************************ +/** + * sort Object attributes by function + * and transfer them into array + * @param {Object} obj Object form from numric + * @param {Function} fn sort function + * @return {Array} the sorted attirbutes array + */ + + +/** + * to check if an descriptor + * @param {anything} desc + */ +function isDescriptor(desc) { + if (!desc || !desc.hasOwnProperty) { + return false; + } + + var keys = ['value', 'initializer', 'get', 'set']; + + for (var i = 0, l = keys.length; i < l; i++) { + if (desc.hasOwnProperty(keys[i])) { + return true; + } + } + return false; +} +/** + * to check if the descirptor is an accessor descriptor + * @param {descriptor} desc it should be a descriptor better + */ +function isAccessorDescriptor(desc) { + return !!desc && (isFunction(desc.get) || isFunction(desc.set)) && isBoolean(desc.configurable) && isBoolean(desc.enumerable) && desc.writable === undefined; +} +/** + * to check if the descirptor is an data descriptor + * @param {descriptor} desc it should be a descriptor better + */ +function isDataDescriptor(desc) { + return !!desc && desc.hasOwnProperty('value') && isBoolean(desc.configurable) && isBoolean(desc.enumerable) && isBoolean(desc.writable); +} +/** + * to check if the descirptor is an initiallizer descriptor + * @param {descriptor} desc it should be a descriptor better + */ +function isInitializerDescriptor(desc) { + return !!desc && isFunction(desc.initializer) && isBoolean(desc.configurable) && isBoolean(desc.enumerable) && isBoolean(desc.writable); +} +/** + * set one value on the object + * @param {string} key + */ +function createDefaultSetter(key) { + return function set(newValue) { + _Object$defineProperty(this, key, { + configurable: true, + writable: true, + // IS enumerable when reassigned by the outside word + enumerable: true, + value: newValue + }); + return newValue; + }; +} + +/** + * Compress many function into one function, but this function only accept one arguments; + * @param {Array} fns the array of function we need to compress into one function + * @param {string} errmsg When we check that there is something is not function, we will throw an error, you can set your own error message + */ +function compressOneArgFnArray(fns) { + var errmsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'You must pass me an array of function'; + + if (!isArray(fns) || fns.length < 1) { + throw new TypeError(errmsg); + } + if (fns.length === 1) { + if (!isFunction(fns[0])) { + throw new TypeError(errmsg); + } + return fns[0]; + } + return fns.reduce(function (prev, curr) { + if (!isFunction(curr) || !isFunction(prev)) throw new TypeError(errmsg); + return function (value) { + return bind$1(curr, this)(bind$1(prev, this)(value)); + }; + }); +} + +function getOwnKeysFn() { + var getOwnPropertyNames = _Object$getOwnPropertyNames, + getOwnPropertySymbols = _Object$getOwnPropertySymbols; + + return isFunction(getOwnPropertySymbols) ? function (obj) { + // $FlowFixMe: do not support symwbol yet + return _Array$from(getOwnPropertyNames(obj).concat(getOwnPropertySymbols(obj))); + } : getOwnPropertyNames; +} + +var getOwnKeys = getOwnKeysFn(); + +function getOwnPropertyDescriptorsFn() { + // $FlowFixMe: In some environment, Object.getOwnPropertyDescriptors has been implemented; + return isFunction(_Object$getOwnPropertyDescriptors) ? _Object$getOwnPropertyDescriptors : function (obj) { + return getOwnKeys(obj).reduce(function (descs, key) { + descs[key] = getOwnPropertyDescriptor$2(obj, key); + return descs; + }, {}); + }; +} + +var getOwnPropertyDescriptors$2 = getOwnPropertyDescriptorsFn(); + +function compressMultipleDecorators() { + for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) { + fns[_key] = arguments[_key]; + } + + if (!fns.length) throw new TypeError('You must pass in decorators in compressMultipleDecorators'); + fns.forEach(function (fn) { + if (!isFunction(fn)) throw new TypeError('Decorators must be a function, but not "' + fn + '" in ' + (typeof fn === 'undefined' ? 'undefined' : _typeof(fn))); + }); + if (fns.length === 1) return fns[0]; + return function (obj, prop, descirptor) { + // $FlowFixMe: the reduce will return a descriptor + return fns.reduce(function (descirptor, fn) { + return fn(obj, prop, descirptor); + }, descirptor); + }; +} + +function accessor() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + get = _ref.get, + set = _ref.set; + + var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref2$preGet = _ref2.preGet, + preGet = _ref2$preGet === undefined ? false : _ref2$preGet, + _ref2$preSet = _ref2.preSet, + preSet = _ref2$preSet === undefined ? true : _ref2$preSet; + + if (!isFunction(get) && !isFunction(set) && !(isArray(get) && get.length > 0) && !(isArray(set) && set.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 errmsg = '@accessor only accept function or array of function as getter/setter'; + get = isArray(get) ? compressOneArgFnArray(get, errmsg) : get; + set = isArray(set) ? compressOneArgFnArray(set, errmsg) : set; + return function (obj, prop, descriptor) { + var _ref3 = descriptor || {}, + _ref3$configurable = _ref3.configurable, + configurable = _ref3$configurable === undefined ? true : _ref3$configurable, + _ref3$enumerable = _ref3.enumerable, + enumerable = _ref3$enumerable === undefined ? true : _ref3$enumerable; + + var hasGet = isFunction(get); + var hasSet = isFunction(set); + var handleGet = function handleGet(value) { + // $FlowFixMe: it's really function here + return hasGet ? bind$1(get, this)(value) : value; + }; + var handleSet = function handleSet(value) { + // $FlowFixMe: it's really function here + return hasSet ? bind$1(set, this)(value) : value; + }; + if (isAccessorDescriptor(descriptor)) { + var originGet = descriptor.get, + originSet = descriptor.set; + + var hasOriginGet = isFunction(originGet); + var hasOriginSet = isFunction(originSet); + var getter = hasOriginGet || hasGet ? function () { + var _this = this; + + var boundGetter = bind$1(handleGet, this); + var originBoundGetter = function originBoundGetter() { + return hasOriginGet + // $FlowFixMe: we have do a check here + ? bind$1(originGet, _this)() : undefined; + }; + var order = preGet ? [boundGetter, originBoundGetter] : [originBoundGetter, boundGetter]; + // $FlowFixMe: it's all function here + return order.reduce(function (value, fn) { + return fn(value); + }, undefined); + } : undefined; + var setter = hasOriginSet || hasSet ? function (val) { + var _this2 = this; + + var boundSetter = bind$1(handleSet, this); + var originBoundSetter = function originBoundSetter(value) { + return hasOriginSet + // $FlowFixMe: flow act like a retarded child on optional property + ? bind$1(originSet, _this2)(value) : value; + }; + var order = preSet ? [boundSetter, originBoundSetter] : [originBoundSetter, boundSetter]; + return order.reduce(function (value, fn) { + return fn(value); + }, val); + } : undefined; + return { + get: getter, + set: setter, + configurable: configurable, + enumerable: enumerable + }; + } else if (isInitializerDescriptor(descriptor)) { + // $FlowFixMe: disjoint union is horrible, descriptor is initializerDescriptor now + var initializer = descriptor.initializer; + + var value = void 0; + var inited = false; + return { + get: function get() { + var boundFn = bind$1(handleGet, this); + if (inited) return boundFn(value); + value = bind$1(initializer, this)(); + inited = true; + return boundFn(value); + }, + set: function set(val) { + var boundFn = bind$1(handleSet, this); + value = preSet ? boundFn(val) : val; + inited = true; + if (!preSet) { + boundFn(value); + } + return value; + }, + + configurable: configurable, + enumerable: enumerable + }; + } else { + // $FlowFixMe: disjoint union is horrible, descriptor is DataDescriptor now + var _ref4 = descriptor || {}, + _value = _ref4.value; + + return { + get: function get() { + return bind$1(handleGet, this)(_value); + }, + set: function set(val) { + var boundFn = bind$1(handleSet, this); + _value = preSet ? boundFn(val) : val; + if (!preSet) { + boundFn(_value); + } + return _value; + }, + + configurable: configurable, + enumerable: enumerable + }; + } + }; +} + +function before() { + for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) { + fns[_key] = arguments[_key]; + } + + if (fns.length === 0) 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 (fns.length > 2 && isDescriptor(fns[2])) { + throw new Error('You may use @before straightly, @before return decorators, you should call it before you set it as decorator.'); + } + for (var i = fns.length - 1; i > -1; i--) { + if (!isFunction(fns[i])) throw new TypeError('@before only accept function parameter'); + } + return function (obj, prop, descriptor) { + var _ref = descriptor || {}, + fn = _ref.value, + configurable = _ref.configurable, + enumerable = _ref.enumerable, + writable = _ref.writable; + + if (!isFunction(fn)) throw new TypeError('@before can only be used on function, please check the property "' + prop + '" is a method or not.'); + var handler = function handler() { + var _this = this; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + var paras = fns.reduce(function (paras, fn) { + var result = bind$1(fn, _this).apply(undefined, _toConsumableArray(paras)); + return result === undefined ? paras : isArray(result) ? result + // $FlowFixMe: what the hell, it can be anything + : [result]; + }, args); + return bind$1(fn, this).apply(undefined, _toConsumableArray(paras)); + }; + return { + value: handler, + configurable: configurable, + enumerable: enumerable, + writable: writable + }; + }; +} + +function after() { + for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) { + fns[_key] = arguments[_key]; + } + + if (fns.length === 0) throw new Error("@after accept at least one parameter. If you don't need to preprocess after your function, do not add @after decorators"); + if (fns.length > 2 && isDescriptor(fns[2])) { + throw new Error('You may have used @after straightly. @after return decorators. You should call it before you use it as decorators'); + } + var fn = compressOneArgFnArray(fns, '@after only accept function parameter'); + return function (obj, prop, descriptor) { + var _ref = descriptor || {}, + value = _ref.value, + configurable = _ref.configurable, + enumerable = _ref.enumerable, + writable = _ref.writable; + + if (!isFunction(value)) throw new TypeError('@after can only be used on function, please checkout your property "' + prop + '" is a method or not.'); + var handler = function handler() { + var ret = bind$1(value, this).apply(undefined, arguments); + return bind$1(fn, this)(ret); + }; + return { + value: handler, + configurable: configurable, + enumerable: enumerable, + writable: writable + }; + }; +} + +function initialize() { + for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) { + fns[_key] = arguments[_key]; + } + + if (fns.length === 0) throw new Error("@initialize accept at least one parameter. If you don't need to initialize your value, do not add @initialize."); + if (fns.length > 2 && isDescriptor(fns[2])) { + throw new Error('You may use @initialize straightly, @initialize return decorators, you need to call it'); + } + var fn = compressOneArgFnArray(fns, '@initialize only accept function parameter'); + return function (obj, prop, descriptor) { + if (descriptor === undefined) { + return { + value: bind$1(fn, obj)(), + configurable: true, + writable: true, + enumerable: true + }; + } + if (isAccessorDescriptor(descriptor)) { + var hasBeenReset = false; + var originSet = descriptor.set; + + return accessor({ + get: function get(value) { + if (hasBeenReset) return value; + return bind$1(fn, this)(value); + }, + + set: originSet ? function (value) { + hasBeenReset = true; + return value; + } : undefined + })(obj, prop, descriptor); + } + /** + * when we set decorator on propery + * we will get a descriptor with initializer + * as they will be attach on the instance later + * so, we need to substitute the initializer function + */ + if (isInitializerDescriptor(descriptor)) { + // $FlowFixMe: useless disjoint union + var initializer = descriptor.initializer; + + var handler = function handler() { + return bind$1(fn, this)(bind$1(initializer, this)()); + }; + return { + initializer: handler, + configurable: descriptor.configurable, + // $FlowFixMe: useless disjoint union + writable: descriptor.writable, + enumerable: descriptor.enumerable + }; + } + // $FlowFixMe: useless disjoint union + var value = bind$1(fn, this)(descriptor.value); + return { + value: value, + // $FlowFixMe: useless disjoint union + writable: descriptor.writable, + configurable: descriptor.configurable, + enumerable: descriptor.enumerable + }; + }; +} + +var getOwnPropertyDescriptor$1$1 = _Object$getOwnPropertyDescriptor; +var defineProperty$4 = _Object$defineProperty; + +function setAlias(root, prop, _ref, obj, key, _ref2) { + var configurable = _ref.configurable, + enumerable = _ref.enumerable; + var force = _ref2.force, + omit = _ref2.omit; + + var originDesc = getOwnPropertyDescriptor$1$1(obj, key); + if (originDesc !== undefined) { + if (omit) return; + // TODO: we should add an github link here + if (!force) throw new Error('"' + prop + '" is an existing property, if you want to override it, please set "force" true in @alias option.'); + if (!originDesc.configurable) { + throw new Error('property "' + prop + '" is unconfigurable.'); + } + } + defineProperty$4(obj, key, { + get: function get() { + return root[prop]; + }, + set: function set(value) { + root[prop] = value; + return prop; + }, + + configurable: configurable, + enumerable: enumerable + }); +} +function alias(other, key, option) { + // set argument into right position + if (arguments.length === 2) { + if (isString(other)) { + // $FlowFixMe: i will check this later + option = key; + key = other; + other = undefined; + } + } else if (arguments.length === 1) { + // $FlowFixMe: i will check this later + key = other; + other = undefined; + } + // argument validate + if (!isString(key)) throw new TypeError('@alias need a string as a key to find the porperty to set alias on'); + var illegalObjErrorMsg = 'If you want to use @alias to set alias on other instance, you must pass in a legal instance'; + if (other !== undefined && isPrimitive(other)) throw new TypeError(illegalObjErrorMsg); + + var _ref3 = isObject(option) ? option : { force: false, omit: false }, + force = _ref3.force, + omit = _ref3.omit; + + return function (obj, prop, descriptor) { + descriptor = descriptor || { + value: undefined, + configurable: true, + writable: true, + enumerable: true + }; + function getTargetAndName(other, obj, key) { + var target = isPrimitive(other) ? obj : other; + var keys = key.split('.'); + + var _keys$slice = keys.slice(-1), + _keys$slice2 = _slicedToArray(_keys$slice, 1), + name = _keys$slice2[0]; + + target = getDeepProperty$1(target, keys.slice(0, -1), { throwError: true }); + if (isPrimitive(target)) { + throw new TypeError(illegalObjErrorMsg); + } + return { + target: target, + name: name + }; + } + if (isInitializerDescriptor(descriptor)) { + return initialize(function (value) { + var _getTargetAndName = getTargetAndName(other, this, key), + target = _getTargetAndName.target, + name = _getTargetAndName.name; + + setAlias(this, prop, descriptor, target, name, { force: force, omit: omit }); + return value; + })(obj, prop, descriptor); + } + if (isAccessorDescriptor(descriptor)) { + var inited = void 0; + var handler = function handler(value) { + if (inited) return value; + + var _getTargetAndName2 = getTargetAndName(other, this, key), + target = _getTargetAndName2.target, + name = _getTargetAndName2.name; + + setAlias(this, prop, descriptor, target, name, { force: force, omit: omit }); + inited = true; + return value; + }; + return accessor({ get: handler, set: handler })(obj, prop, descriptor); + } + + var _getTargetAndName3 = getTargetAndName(other, obj, key), + target = _getTargetAndName3.target, + name = _getTargetAndName3.name; + + setAlias(obj, prop, descriptor, target, name, { force: force, omit: omit }); + return descriptor; + }; +} + +var defineProperty$1$1 = _Object$defineProperty; + +function classify(decorator) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + requirement = _ref.requirement, + _ref$customArgs = _ref.customArgs, + customArgs = _ref$customArgs === undefined ? false : _ref$customArgs; + + return function () { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref2$exclude = _ref2.exclude, + exclude = _ref2$exclude === undefined ? [] : _ref2$exclude, + _ref2$include = _ref2.include, + include = _ref2$include === undefined ? [] : _ref2$include, + _ref2$construct = _ref2.construct, + construct = _ref2$construct === undefined ? false : _ref2$construct, + _ref2$self = _ref2.self, + self = _ref2$self === undefined ? false : _ref2$self; + + if (!isArray(exclude)) throw new TypeError('options.exclude must be an array'); + if (!isArray(include)) throw new TypeError('options.include must be an array'); + return function (Klass) { + var isClass = isFunction(Klass); + if (!self && !isClass) throw new TypeError('@' + decorator.name + 'Class can only be used on class'); + if (self && isPrimitive(Klass)) throw new TypeError('@' + decorator.name + 'Class must be used on non-primitive type value in \'self\' mode'); + var prototype = self ? Klass : Klass.prototype; + if (isVoid(prototype)) throw new Error('The prototype of the ' + Klass.name + ' is empty, please check it'); + var descs = getOwnPropertyDescriptors$2(prototype); + getOwnKeys(prototype).concat(include).forEach(function (key) { + var desc = descs[key]; + if (key === 'constructor' && !construct || self && isClass && ['name', 'length', 'prototype'].indexOf(key) > -1 || exclude.indexOf(key) > -1 || isFunction(requirement) && requirement(prototype, key, desc, { self: self }) === false) return; + defineProperty$1$1(prototype, key, (customArgs ? decorator.apply(undefined, _toConsumableArray(args)) : decorator)(prototype, key, desc)); + }); + }; + }; +} + +var autobindClass = classify(autobind, { + requirement: function requirement(obj, prop, desc) { + // $FlowFixMe: it's data descriptor now + return isDataDescriptor(desc) && isFunction(desc.value); + } +}); + +var mapStore = void 0; +// save bound function for super +function getBoundSuper(obj, fn) { + if (typeof _WeakMap === 'undefined') { + throw new Error('Using @autobind on ' + fn.name + '() requires WeakMap support due to its use of super.' + fn.name + '()'); + } + + if (!mapStore) { + mapStore = new _WeakMap(); + } + + if (mapStore.has(obj) === false) { + mapStore.set(obj, new _WeakMap()); + } + + var superStore = mapStore.get(obj); + // $FlowFixMe: already insure superStore is not undefined + if (superStore.has(fn) === false) { + // $FlowFixMe: already insure superStore is not undefined + superStore.set(fn, bind$1(fn, obj)); + } + // $FlowFixMe: already insure superStore is not undefined + return superStore.get(fn); +} +/** + * auto bind the function on the class, just support function + * @param {Object} obj Target Object + * @param {string} prop prop strong + * @param {Object} descriptor + */ +function autobind(obj, prop, descriptor) { + if (arguments.length === 1) return autobindClass()(obj); + + var _ref = descriptor || {}, + fn = _ref.value, + configurable = _ref.configurable; + + if (!isFunction(fn)) { + throw new TypeError('@autobind can only be used on functions, not "' + fn + '" in ' + (typeof fn === 'undefined' ? 'undefined' : _typeof(fn)) + ' on property "' + prop + '"'); + } + var constructor = obj.constructor; + + return { + configurable: configurable, + enumerable: false, + get: function get() { + var _this = this; + + var boundFn = function boundFn() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return fn.call.apply(fn, [_this].concat(_toConsumableArray(args))); + }; + // Someone accesses the property directly on the prototype on which it is + // actually defined on, i.e. Class.prototype.hasOwnProperty(key) + if (this === obj) { + return fn; + } + // Someone accesses the property directly on a prototype, + // but it was found up the chain, not defined directly on it + // i.e. Class.prototype.hasOwnProperty(key) == false && key in Class.prototype + if (this.constructor !== constructor && _Object$getPrototypeOf(this).constructor === constructor) { + return fn; + } + + // Autobound method calling super.sameMethod() which is also autobound and so on. + if (this.constructor !== constructor && prop in this.constructor.prototype) { + return getBoundSuper(this, fn); + } + _Object$defineProperty(this, prop, { + configurable: true, + writable: true, + // NOT enumerable when it's a bound method + enumerable: false, + value: boundFn + }); + + return boundFn; + }, + + set: createDefaultSetter(prop) + }; +} + +var defineProperty$2$1 = _Object$defineProperty; +/** + * make one attr only can be read, but could not be rewrited/ deleted + * @param {Object} obj + * @param {string} prop + * @param {Object} descriptor + * @return {descriptor} + */ + +function frozen(obj, prop, descriptor) { + if (descriptor === undefined) { + return { + value: undefined, + writable: false, + enumerable: false, + configurable: false + }; + } + descriptor.enumerable = false; + descriptor.configurable = false; + if (isAccessorDescriptor(descriptor)) { + var _get = descriptor.get; + + descriptor.set = undefined; + if (!isFunction(_get)) { + return; + } + return { + get: function get() { + var value = bind$1(_get, this)(); + defineProperty$2$1(this, prop, { + value: value, + writable: false, + configurable: false, + enumerable: false + }); + return value; + }, + + set: undefined, + configurable: false, + enumerable: false + }; + } + // $FlowFixMe: comeon, can disjoint union be reliable? + descriptor.writable = false; + return descriptor; +} + +var getOwnPropertyDescriptor$2$1 = _Object$getOwnPropertyDescriptor; +var defineProperty$3$1 = _Object$defineProperty; + +function waituntil(key) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + other = _ref.other; + + if (!isFunction(key) && !isPromise(key) && !isString(key)) throw new TypeError('@waitUntil only accept Function, Promise or String'); + return function (obj, prop, descriptor) { + var _ref2 = descriptor || {}, + _value = _ref2.value, + configurable = _ref2.configurable; + + if (!isFunction(_value)) throw new TypeError('@waituntil can only be used on function, but not ' + _value + ' on property "' + prop + '"'); + var binded = false; + var waitingQueue = []; + var canIRun = isPromise(key) ? function () { + return key; + } : isFunction(key) ? key : function () { + // $FlowFixMe: We have use isPromise to exclude + var keys = key.split('.'); + var prop = keys.slice(-1); + var originTarget = isPrimitive(other) ? this : other; + if (!binded) { + var target = getDeepProperty$1(originTarget, keys.slice(0, -1)); + if (isVoid(target)) return target; + var _descriptor = getOwnPropertyDescriptor$2$1(target, prop); + /** + * create a setter hook here + * when it get ture, it will run all function in waiting queue immediately + */ + var set = function set(value) { + if (value === true) { + while (waitingQueue.length > 0) { + waitingQueue[0](); + waitingQueue.shift(); + } + } + return value; + }; + var desc = isDescriptor(_descriptor) ? accessor({ set: set })(target, prop, _descriptor) : accessor({ set: set })(target, prop, { + value: undefined, + configurable: true, + enumerable: true, + writable: true + }); + defineProperty$3$1(target, prop, desc); + binded = true; + } + return getDeepProperty$1(originTarget, keys); + }; + return { + value: function value() { + var _this = this; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var boundFn = bind$1(_value, this); + var runnable = bind$1(canIRun, this).apply(undefined, args); + if (isPromise(runnable)) { + return _Promise.resolve(runnable).then(function () { + return bind$1(_value, _this).apply(undefined, args); + }); + } else if (runnable === true) { + return bind$1(_value, this).apply(undefined, args); + } else { + return new _Promise(function (resolve) { + var cb = function cb() { + boundFn.apply(undefined, args); + resolve(); + }; + waitingQueue.push(cb); + }); + } + }, + + // function should not be enmuerable + enumerable: false, + configurable: configurable, + // as we have delay this function + // it's not a good idea to change it + writable: false + }; + }; +} + +function nonenumerable(obj, prop, descriptor) { + if (descriptor === undefined) { + return { + value: undefined, + enumerable: false, + configurable: true, + writable: true + }; + } + descriptor.enumerable = false; + return descriptor; +} + +var defineProperty$6 = _Object$defineProperty; +var getOwnPropertyDescriptor$3 = _Object$getOwnPropertyDescriptor; + + +function applyDecorators(Class, props) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$self = _ref.self, + self = _ref$self === undefined ? false : _ref$self, + _ref$omit = _ref.omit, + omit = _ref$omit === undefined ? false : _ref$omit; + + var isPropsFunction = isFunction(props); + if (isPropsFunction || isArray(props)) { + // apply decorators on class + if (!isFunction(Class)) throw new TypeError('If you want to decorator class, you must pass it a legal class'); + // $FlowFixMe: Terrible union, it's function now + if (isPropsFunction) props(Class);else { + // $FlowFixMe: Terrible union, it's array now + for (var i = 0, len = props.length; i < len; i++) { + // $FlowFixMe: Terrible union, it's array now + var fn = props[i]; + if (!isFunction(fn)) throw new TypeError('If you want to decorate an class, you must pass it function or array of function'); + fn(Class); + } + } + return Class; + } + if (!self && !isFunction(Class)) throw new TypeError('applyDecorators only accept class as first arguments. If you want to modify instance, you should set options.self true.'); + if (self && isPrimitive(Class)) throw new TypeError("We can't apply docorators on a primitive value, even in self mode"); + if (!isObject(props)) throw new TypeError('applyDecorators only accept object as second arguments'); + var prototype = self ? Class : Class.prototype; + if (isVoid(prototype)) throw new Error('The class muse have a prototype, please take a check'); + for (var key in props) { + var value = props[key]; + var decorators = isArray(value) ? value : [value]; + var handler = void 0; + try { + handler = compressMultipleDecorators.apply(undefined, _toConsumableArray(decorators)); + } catch (err) { + throw new Error('The decorators set on props must be Function or Array of Function'); + } + var descriptor = getOwnPropertyDescriptor$3(prototype, key); + if (descriptor && !descriptor.configurable) { + if (!omit) throw new Error(key + ' of ' + prototype + ' is unconfigurable'); + continue; + } + defineProperty$6(prototype, key, handler(prototype, key, descriptor)); + } + return Class; +} + +var arrayChangeMethod = ['push', 'pop', 'unshift', 'shift', 'splice', 'sort', 'reverse']; + +function deepProxy(value, hook, _ref) { + var _operateProps; + + var diff = _ref.diff, + operationPrefix = _ref.operationPrefix; + + var mapStore = {}; + var arrayChanging = false; + var proxyValue = new Proxy(value, { + get: function get(target, property, receiver) { + var value = target[property]; + if (isArray(target) && arrayChangeMethod.indexOf(property) > -1) { + return function () { + arrayChanging = true; + bind$1(value, receiver).apply(undefined, arguments); + arrayChanging = false; + hook(); + }; + } + if (mapStore[property] === true) return value; + if (isObject(value) || isArray(value)) { + var _proxyValue = mapStore[property] || deepProxy(value, hook, { diff: diff, operationPrefix: operationPrefix }); + mapStore[property] = _proxyValue; + return _proxyValue; + } + mapStore[property] = true; + return value; + }, + set: function set(target, property, value) { + var oldVal = target[property]; + var newVal = isObject(value) || isArray(value) ? deepProxy(value, hook, { diff: diff, operationPrefix: operationPrefix }) : value; + target[property] = newVal; + mapStore[property] = true; + if (arrayChanging || diff && oldVal === newVal) return true; + hook(); + return true; + }, + deleteProperty: function deleteProperty(target, property) { + delete target[property]; + delete mapStore[property]; + if (arrayChanging) return true; + hook(); + return true; + } + }); + var operateProps = (_operateProps = {}, _defineProperty(_operateProps, operationPrefix + 'set', [initialize(function (method) { + return function (property, val) { + // $FlowFixMe: we have check the computed value + proxyValue[property] = val; + }; + }), nonenumerable]), _defineProperty(_operateProps, operationPrefix + 'del', [initialize(function (method) { + return function (property) { + // $FlowFixMe: we have check the computed value + delete proxyValue[property]; + }; + }), nonenumerable]), _operateProps); + applyDecorators(proxyValue, operateProps, { self: true }); + return proxyValue; +} + +function deepObserve(value, hook, _ref2) { + var _this = this, + _operateProps2; + + var operationPrefix = _ref2.operationPrefix, + diff = _ref2.diff; + + var mapStore = {}; + var arrayChanging = false; + function getPropertyDecorators(keys) { + var oldVal = void 0; + return keys.reduce(function (props, key) { + props[key] = [accessor({ + set: function set(value) { + oldVal = this[key]; + return value; + } + }), accessor({ + get: function get(val) { + if (mapStore[key]) return val; + if (isObject(val) || isArray(val)) { + deepObserve(val, hook, { operationPrefix: operationPrefix, diff: diff }); + } + mapStore[key] = true; + return val; + }, + set: function set(val) { + if (isObject(val) || isArray(val)) deepObserve(val, hook, { operationPrefix: operationPrefix, diff: diff }); + mapStore[key] = true; + if (!arrayChanging && (!diff || oldVal !== val)) hook(); + return val; + } + }, { preSet: false })]; + return props; + }, {}); + } + var props = getPropertyDecorators(getOwnKeys(value)); + applyDecorators(value, props, { self: true, omit: true }); + if (isArray(value)) { + var methodProps = arrayChangeMethod.reduce(function (props, key) { + props[key] = [initialize(function (method) { + method = isFunction(method) ? method + // $FlowFixMe: we have check the key + : Array.prototype[key]; + return function () { + var originLength = value.length; + arrayChanging = true; + bind$1(method, value).apply(undefined, arguments); + arrayChanging = false; + if (originLength < value.length) { + var keys = new Array(value.length - originLength).fill(1).map(function (value, index) { + return (index + originLength).toString(); + }); + var _props = getPropertyDecorators(keys); + applyDecorators(value, _props, { self: true, omit: true }); + } + hook(); + }; + }), nonenumerable]; + return props; + }, {}); + applyDecorators(value, methodProps, { self: true }); + } + var operateProps = (_operateProps2 = {}, _defineProperty(_operateProps2, operationPrefix + 'set', [initialize(function (method) { + return function (property, val) { + var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + disable = _ref3.disable, + isNewVal = _ref3.isNewVal; + + isNewVal = isNewVal || getOwnKeys(value).indexOf(property) === -1; + if (isFunction(method)) { + bind$1(method, _this)(property, val, { disable: true, isNewVal: isNewVal }); + } + if (isNewVal) { + var _props2 = getPropertyDecorators([property]); + applyDecorators(value, _props2, { self: true, omit: true }); + } + if (!disable) { + value[property] = val; + } + }; + }), nonenumerable]), _defineProperty(_operateProps2, operationPrefix + 'del', [initialize(function (method) { + return function (property) { + if (isFunction(method)) { + bind$1(method, _this)(property); + } else { + delete value[property]; + } + hook(); + }; + }), nonenumerable]), _operateProps2); + applyDecorators(value, operateProps, { self: true }); + return value; +} + +function watch() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var option = isObject(args[args.length - 1]) ? args[args.length - 1] : {}; + // $FlowFixMe: we have check if it's an object + var deep = option.deep, + omit = option.omit, + other = option.other, + _option$operationPref = option.operationPrefix, + operationPrefix = _option$operationPref === undefined ? '__' : _option$operationPref, + _option$diff = option.diff, + diff = _option$diff === undefined ? true : _option$diff; + // $FlowFixMe: we have check if it's an object + + var proxy = option.proxy; + + if (typeof Proxy !== 'function') { + proxy = false; + } + if (!args.length) throw new TypeError('You must pass a function or a string to find the hanlder function.'); + if (other !== undefined && isPrimitive(other)) throw new TypeError('If you want us to trigger function on the other instance, you must pass in a legal instance'); + if (!isString(operationPrefix)) throw new TypeError('operationPrefix must be an string'); + return function (obj, prop, descriptor) { + var fns = args.reduce(function (fns, keyOrFn, index) { + if (!isString(keyOrFn) && !isFunction(keyOrFn)) { + if (!index || index !== args.length - 1) throw new TypeError('You can only pass function or string as handler'); + return fns; + } + fns.push(isString(keyOrFn) ? function (newVal, oldVal) { + var target = other || obj; + // $FlowFixMe: we have ensure it must be a string + var fn = getDeepProperty$1(target, keyOrFn); + if (!isFunction(fn)) { + if (!omit) 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'); + return; + } + return bind$1(fn, this)(newVal, oldVal); + } : keyOrFn); + return fns; + }, []); + var handler = function handler(newVal, oldVal) { + var _this2 = this; + + fns.forEach(function (fn) { + return bind$1(fn, _this2)(newVal, oldVal); + }); + }; + var inited = false; + var oldVal = void 0; + var newVal = void 0; + var proxyValue = void 0; + return compressMultipleDecorators(accessor({ + set: function set(value) { + var _this3 = this; + + oldVal = this[prop]; + proxyValue = undefined; + var hook = function hook() { + return bind$1(handler, _this3)(newVal, oldVal); + }; + return deep && (isObject(value) || isArray(value)) ? proxy ? deepProxy(value, hook, { diff: diff, operationPrefix: operationPrefix }) : deepObserve(value, hook, { operationPrefix: operationPrefix, diff: diff }) : value; + }, + get: function get(value) { + var _this4 = this; + + if (proxyValue) return proxyValue; + if (!inited) { + inited = true; + var hook = function hook() { + return bind$1(handler, _this4)(newVal, oldVal); + }; + if (deep && (isObject(value) || isArray(value))) { + if (proxy) { + proxyValue = deepProxy(value, hook, { diff: diff, operationPrefix: operationPrefix }); + oldVal = proxyValue; + newVal = proxyValue; + return proxyValue; + } + deepObserve(value, hook, { operationPrefix: operationPrefix, diff: diff }); + } + oldVal = value; + newVal = value; + } + return value; + } + }, { preSet: true }), accessor({ + set: function set(value) { + newVal = value; + if (!diff || oldVal !== value) bind$1(handler, this)(newVal, oldVal); + oldVal = value; + return value; + } + }, { preSet: false }))(obj, prop, descriptor); + }; +} + +function runnable(key) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + other = _ref.other, + backup = _ref.backup; + + if (!isFunction(key) && !isString(key)) throw new TypeError('@runnable only accept Function or String'); + return function (obj, prop, descriptor) { + var _ref2 = descriptor || {}, + _value = _ref2.value, + configurable = _ref2.configurable; + + if (!isFunction(_value)) throw new TypeError('@runnable can only be used on method, but not ' + _value + ' on property "' + prop + '".'); + var canIRun = isFunction(key) ? key : function () { + var keys = key.split('.'); + var originTarget = isPrimitive(other) ? this : other; + return getDeepProperty$1(originTarget, keys); + }; + backup = isFunction(backup) ? backup : function () {}; + return { + value: function value() { + if (bind$1(canIRun, this).apply(undefined, arguments) === true) { + return bind$1(_value, this).apply(undefined, arguments); + } else { + // $FlowFixMe: I have reassign it when it's not a function + return bind$1(backup, this).apply(undefined, arguments); + } + }, + + // function should not be enmuerable + enumerable: false, + configurable: configurable, + // as we have delay this function + // it's not a good idea to change it + writable: false + }; + }; +} + +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 before$1 = classify(before, { + requirement: function requirement(obj, prop, desc) { + // $FlowFixMe: it's data descriptor now + return isDataDescriptor(desc) && isFunction(desc.value); + }, + + customArgs: true +}); + +var after$1 = classify(after, { + requirement: function requirement(obj, prop, desc) { + // $FlowFixMe: it's data descriptor now + return isDataDescriptor(desc) && isFunction(desc.value); + }, + + customArgs: true +}); + +var runnable$1 = classify(runnable, { + requirement: function requirement(obj, prop, desc) { + // $FlowFixMe: it's data descriptor now + return isDataDescriptor(desc) && isFunction(desc.value); + }, + + customArgs: true +}); + +var waituntil$1 = classify(waituntil, { + requirement: function requirement(obj, prop, desc) { + // $FlowFixMe: it's data descriptor now + return isDataDescriptor(desc) && isFunction(desc.value); + }, + + customArgs: true +}); + +// 20.1.2.4 Number.isNaN(number) + + +_export(_export.S, 'Number', { + isNaN: function isNaN(number) { + // eslint-disable-next-line no-self-compare + return number != number; + } +}); + +var isNan = _core.Number.isNaN; + +var isNan$1 = createCommonjsModule(function (module) { +module.exports = { "default": isNan, __esModule: true }; +}); + +var _Number$isNaN = unwrapExports(isNan$1); + +var $JSON$1 = _core.JSON || (_core.JSON = { stringify: JSON.stringify }); +var stringify = function stringify(it) { // eslint-disable-line no-unused-vars + return $JSON$1.stringify.apply($JSON$1, arguments); +}; + +var stringify$1 = createCommonjsModule(function (module) { +module.exports = { "default": stringify, __esModule: true }; +}); + +var _JSON$stringify = unwrapExports(stringify$1); + +var get = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; + + + +var _getPrototypeOf2 = _interopRequireDefault(getPrototypeOf$1); + + + +var _getOwnPropertyDescriptor2 = _interopRequireDefault(getOwnPropertyDescriptor$1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function get(object, property, receiver) { + if (object === null) object = Function.prototype; + var desc = (0, _getOwnPropertyDescriptor2.default)(object, property); + + if (desc === undefined) { + var parent = (0, _getPrototypeOf2.default)(object); + + if (parent === null) { + return undefined; + } else { + return get(parent, property, receiver); + } + } else if ("value" in desc) { + return desc.value; + } else { + var getter = desc.get; + + if (getter === undefined) { + return undefined; + } + + return getter.call(receiver); + } +}; +}); + +var _get = unwrapExports(get); + +var VENDOR_PREFIXES = ['', 'o', 'ms', 'moz', 'webkit', 'webkitCurrent']; + +var SYNONYMS = [['', ''], // empty +['exit', 'cancel'], // firefox & old webkits expect cancelFullScreen instead of exitFullscreen +['screen', 'Screen']]; + +var DESKTOP_FULLSCREEN_STYLE = { + position: 'fixed', + zIndex: '2147483647', + left: 0, + top: 0, + right: 0, + bottom: 0, + overflow: 'hidden', + width: '100%', + height: '100%' +}; + +var FULLSCREEN_CHANGE = ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange']; + +var FULLSCREEN_ERROR = ['fullscreenerror', 'webkitfullscreenerror', 'mozfullscreenerror', 'MSFullscreenError']; + +var supportDocument = typeof document !== 'undefined'; + +function setStyle$1(el, key, val) { + if (isObject(key)) { + for (var k in key) { + setStyle$1(el, k, key[k]); + } + } else { + // $FlowFixMe: we found it + el.style[key] = val; + } +} + +function native(target, name) { + var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (isObject(name)) { + option = name; + } + if (isString(target)) { + name = target; + } + var _option = option, + _option$keyOnly = _option.keyOnly, + keyOnly = _option$keyOnly === undefined ? false : _option$keyOnly; + /* istanbul ignore if */ + + if (!supportDocument) { + return keyOnly ? '' : undefined; + } + if (!isElement(target)) { + target = document; + } + if (!isString(name)) throw new Error('You must pass in a string as name, but not ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name)) + '.'); + for (var i = 0; i < SYNONYMS.length; i++) { + name = name.replace(SYNONYMS[i][0], SYNONYMS[i][1]); + for (var j = 0; j < VENDOR_PREFIXES.length; j++) { + var prefixed = j === 0 ? name : VENDOR_PREFIXES[j] + name.charAt(0).toUpperCase() + name.substr(1); + // $FlowFixMe: we support document computed property here + if (target[prefixed] !== undefined) return keyOnly ? prefixed : target[prefixed]; + } + } + return keyOnly ? '' : undefined; +} + +function dispatchEvent(element, name) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$bubbles = _ref.bubbles, + bubbles = _ref$bubbles === undefined ? true : _ref$bubbles, + _ref$cancelable = _ref.cancelable, + cancelable = _ref$cancelable === undefined ? true : _ref$cancelable; + + var event = void 0; + /* istanbul ignore else */ + if (isFunction(Event)) { + event = new Event(name, { + bubbles: bubbles, + cancelable: cancelable + }); + } else if (supportDocument && document.createEvent) { + event = document.createEvent('HTMLEvents'); + event.initEvent(name, true, true); + } else if (supportDocument && document.createEventObject) { + // $FlowFixMe: IE < 9 + event = document.createEventObject(); + event.eventType = name; + event.eventName = name; + } + /* istanbul ignore next */ + if (!isObject(event) && !isEvent(event)) throw new Error("We can't create an object on this browser, please report to author"); + /* istanbul ignore else */ + if (element.dispatchEvent) { + element.dispatchEvent(event); + // $FlowFixMe: IE < 9 + } else if (element.fireEvent) { + // $FlowFixMe: IE < 9 + element.fireEvent('on' + event.eventType, event); // can trigger only real event (e.g. 'click') + // $FlowFixMe: support computed key + } else if (element[name]) { + // $FlowFixMe: support computed key + element[name](); + // $FlowFixMe: support computed key + } else if (element['on' + name]) { + // $FlowFixMe: support computed key + element['on' + name](); + } +} + +var _dec, _dec2, _dec3, _dec4, _dec5, _class, _class2; + +function _applyDecoratedDescriptor(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; +} +var fullscreenEnabled = native('fullscreenEnabled'); +var useStyleFirst = false; + +var ESFullScreen = (_dec = autobindClass(), _dec2 = alias('requestFullscreen'), _dec3 = alias('exitFullscreen'), _dec4 = alias('addEventListener'), _dec5 = alias('removeEventListener'), _dec(_class = (_class2 = function () { + function ESFullScreen() { + _classCallCheck(this, ESFullScreen); + + this._fullscreenElement = null; + this.isNativelySupport = defined(native('fullscreenElement')) && (!defined(fullscreenEnabled) || fullscreenEnabled === true); + this._openKey = supportDocument ? native(document.body || document.documentElement, 'requestFullscreen', { keyOnly: true }) : ''; + this._exitKey = native('exitFullscreen', { keyOnly: true }); + this._useStyleFirst = false; + this.hasUsedStyle = false; + } + + _createClass(ESFullScreen, [{ + key: 'open', + value: function open(element) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$force = _ref.force, + force = _ref$force === undefined ? false : _ref$force; + var originElement = this.fullscreenElement; + if (originElement && originElement !== element) { + if (!force) { + dispatchEvent(document, 'fullscreenerror'); + return false; + } + this.exit(); + } + + if (!this.useStyleFirst) { + if (this.isNativelySupport) { + // $FlowFixMe: support computed key on HTMLElment here + isFunction(element[this._openKey]) && element[this._openKey](); + return true; + } + + // add wekitEnterFullscreen support as required in https://github.com/toxic-johann/es-fullscreen/issues/4 + /* istanbul ignore if */ + if (element instanceof HTMLVideoElement && element.webkitSupportsFullscreen && + // $FlowFixMe: support webkitEnterFullscreen on some werid safari + isFunction(element.webkitEnterFullscreen)) { + element.webkitEnterFullscreen(); + this._fullscreenElement = element; + return true; + } + } + + this._savedStyles = _Object$keys(DESKTOP_FULLSCREEN_STYLE).reduce(function (styles, key) { + // $FlowFixMe: support string here + styles[key] = element.style[key]; + return styles; + }, {}); + setStyle$1(element, DESKTOP_FULLSCREEN_STYLE); + + /* istanbul ignore else */ + if (document.body) { + this._bodyOverflow = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + } + /* istanbul ignore else */ + if (document.documentElement) { + this._htmlOverflow = document.documentElement.style.overflow; + document.documentElement.style.overflow = 'hidden'; + } + this._fullscreenElement = element; + this.hasUsedStyle = true; + dispatchEvent(element, 'fullscreenchange'); + return true; + } + }, { + key: 'exit', + value: function exit() { + if (!this.isFullscreen) return false; + if (this.isNativelySupport && !this.useStyleFirst && !this.hasUsedStyle) { + // $FlowFixMe: support document computed key here + document[this._exitKey](); + return true; + } + // $FlowFixMe: element is an Elment here + var element = this._fullscreenElement; + setStyle$1(element, this._savedStyles); + /* istanbul ignore else */ + if (document.body) document.body.style.overflow = this._bodyOverflow; + /* istanbul ignore else */ + if (document.documentElement) document.documentElement.style.overflow = this._htmlOverflow; + + this._fullscreenElement = null; + this._savedStyles = {}; + dispatchEvent(element, 'fullscreenchange'); + return true; + } + }, { + key: 'on', + value: function on(name, fn) { + var element = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document; + + this._handleEvent(element, 'addEventListener', name, fn); + } + }, { + key: 'off', + value: function off(name, fn) { + var element = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document; + + this._handleEvent(element, 'removeEventListener', name, fn); + } + }, { + key: '_handleEvent', + value: function _handleEvent(element, behavior, name, fn) { + var names = name === 'fullscreenchange' ? FULLSCREEN_CHANGE : name === 'fullscreenerror' ? FULLSCREEN_ERROR : [name]; + names.forEach(function (name) { + // $FlowFixMe: support computed attribute here + element[behavior](name, fn); + }); + } + }, { + key: 'useStyleFirst', + get: function get() { + return useStyleFirst; + }, + set: function set(value) { + value = !!value; + if (value === useStyleFirst) return value; + useStyleFirst = value; + dispatchEvent(document, 'esfullscreenmethodchange'); + return value; + } + }, { + key: 'fullscreenElement', + get: function get() { + var element = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullScreenElement', 'msFullscreenElement'].reduce(function (element, key) { + // $FlowFixMe: support computed element on document + return element || document[key]; + }, null); + return element || this._fullscreenElement; + } + }, { + key: 'isFullscreen', + get: function get() { + return isElement(this.fullscreenElement); + } + }]); + + return ESFullScreen; +}(), _applyDecoratedDescriptor(_class2.prototype, 'open', [_dec2], _Object$getOwnPropertyDescriptor(_class2.prototype, 'open'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'exit', [_dec3], _Object$getOwnPropertyDescriptor(_class2.prototype, 'exit'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'on', [_dec4], _Object$getOwnPropertyDescriptor(_class2.prototype, 'on'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'off', [_dec5], _Object$getOwnPropertyDescriptor(_class2.prototype, 'off'), _class2.prototype), _class2)) || _class); + +var index = new ESFullScreen(); + +var isEnum$1 = _objectPie.f; +var _objectToArray = function (isEntries) { + return function (it) { + var O = _toIobject(it); + var keys = _objectKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) if (isEnum$1.call(O, key = keys[i++])) { + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; +}; + +// https://github.com/tc39/proposal-object-values-entries + +var $entries = _objectToArray(true); + +_export(_export.S, 'Object', { + entries: function entries(it) { + return $entries(it); + } +}); + +var entries = _core.Object.entries; + +var entries$1 = createCommonjsModule(function (module) { +module.exports = { "default": entries, __esModule: true }; +}); + +var _Object$entries = unwrapExports(entries$1); + +var tempCurrentTime = 0; + +var NativeVideoKernel = function (_CustEvent) { + _inherits(NativeVideoKernel, _CustEvent); + + _createClass(NativeVideoKernel, null, [{ + key: 'isSupport', + + /* istanbul ignore next */ + value: function isSupport() { + return true; + } + }]); + + function NativeVideoKernel(videoElement, config, customConfig) { + _classCallCheck(this, NativeVideoKernel); + + var _this = _possibleConstructorReturn(this, (NativeVideoKernel.__proto__ || _Object$getPrototypeOf(NativeVideoKernel)).call(this)); + + if (!isElement(videoElement)) throw new Error('You must pass in an legal video element but not ' + (typeof videoElement === 'undefined' ? 'undefined' : _typeof(videoElement))); + _this.video = videoElement; + _this.config = config; + _this.customConfig = customConfig; + return _this; + } + + _createClass(NativeVideoKernel, [{ + key: 'load', + value: function load(src) { + this.video.setAttribute('src', src); + this.video.src = src; + } + }, { + key: 'startLoad', + value: function startLoad(src) { + /* istanbul ignore next */ + var currentTime = this.video.currentTime || tempCurrentTime; + this.load(src); + this.seek(currentTime); + } + + // https://developer.mozilla.org/de/docs/Web/HTML/Using_HTML5_audio_and_video#Stopping_the_download_of_media + + }, { + key: 'stopLoad', + value: function stopLoad() { + tempCurrentTime = this.video.currentTime; + this.video.src = ''; + this.video.removeAttribute('src'); + } + }, { + key: 'destroy', + value: function destroy() { + /* istanbul ignore next */ + if (isElement(this.video)) this.stopLoad(); + } + }, { + key: 'play', + value: function play() { + return this.video.play(); + } + }, { + key: 'pause', + value: function pause() { + return this.video.pause(); + } + }, { + key: 'refresh', + value: function refresh() { + this.video.src = this.config.src; + } + }, { + key: 'attachMedia', + value: function attachMedia() {} + }, { + key: 'seek', + value: function seek(seconds) { + this.video.currentTime = seconds; + } + }]); + + return NativeVideoKernel; +}(CustEvent); + +var defaultConfig = { + isLive: false, // vod or live + box: '', // box type : native mp4 hls flv + preset: {}, + presetConfig: {} +}; + +var LOG_TAG = 'chimee-kernel'; +var kernelEvents = ['mediaInfo', 'heartbeat', 'error']; +var boxSuffixMap = { + flv: '.flv', + hls: '.m3u8', + mp4: '.mp4' +}; + +var ChimeeKernel = function (_CustEvent) { + _inherits(ChimeeKernel, _CustEvent); + + /** + * kernelWrapper + * @param {any} wrap videoElement + * @param {any} option + * @class kernel + */ + function ChimeeKernel(videoElement, config) { + _classCallCheck(this, ChimeeKernel); + + var _this = _possibleConstructorReturn(this, (ChimeeKernel.__proto__ || _Object$getPrototypeOf(ChimeeKernel)).call(this)); + + _this.VERSION = '1.4.0'; + + if (!isElement(videoElement)) throw new Error('You must pass in an video element to the chimee-kernel'); + // copy and maintain only one config for chimee-kernel + // actually kernel is disposable in most situation nowaday + _this.config = deepAssign({}, defaultConfig, config); + _this.videoElement = videoElement; + _this.initVideoKernel(); + _this.bindEvents(_this.videoKernel); + return _this; + } + + _createClass(ChimeeKernel, [{ + key: 'destroy', + value: function destroy() { + this.bindEvents(this.videoKernel, true); + this.videoKernel.destroy(); + } + }, { + key: 'initVideoKernel', + value: function initVideoKernel() { + var config = this.config; + var box = this.chooseBox(config); + this.box = box; + var VideoKernel = this.chooseVideoKernel(this.box, config.preset); + + if (!isFunction(VideoKernel)) throw new Error('We can\'t find video kernel for ' + box + '. Please check your config and make sure it\'s installed or provided'); + + var customConfig = config.presetConfig[this.box] || {}; + + // TODO: nowaday, kernels all get config from one config + // it's not a good way, because custom config may override kernel config + // so we may remove this code later + deepAssign(config, customConfig); + + this.videoKernel = new VideoKernel(this.videoElement, config, customConfig); + } + + // return the config box + // or choose the right one according to the src + + }, { + key: 'chooseBox', + value: function chooseBox(_ref) { + var src = _ref.src, + box = _ref.box; + + if (isString(box) && box) return box; + src = src.toLowerCase(); + for (var key in boxSuffixMap) { + var suffix = boxSuffixMap[key]; + if (src.indexOf(suffix) > -1) return key; + } + return 'native'; + } + + // choose the right video kernel according to the box setting + + }, { + key: 'chooseVideoKernel', + value: function chooseVideoKernel(box, preset) { + switch (box) { + case 'native': + // $FlowFixMe: it's the same as videoKernel + return NativeVideoKernel; + case 'mp4': + return this.getMp4Kernel(preset.mp4); + case 'flv': + case 'hls': + return preset[box]; + default: + throw new Error('We currently do not support box ' + box + ', please contact us through https://github.com/Chimeejs/chimee/issues.'); + } + } + + // fetch the legal mp4 kernel + // if it's not exist or not support + // we will fall back to the native video kernel + + }, { + key: 'getMp4Kernel', + value: function getMp4Kernel(mp4Kernel) { + var hasLegalMp4Kernel = mp4Kernel && isFunction(mp4Kernel.isSupport); + // $FlowFixMe: we have make sure it's an kernel now + var supportMp4Kernel = hasLegalMp4Kernel && mp4Kernel.isSupport(); + // $FlowFixMe: we have make sure it's an kernel now + if (supportMp4Kernel) return mp4Kernel; + if (hasLegalMp4Kernel) this.warnLog('mp4 decode is not support in this browser, we will switch to the native video kernel'); + this.box = 'native'; + // $FlowFixMe: it's the same as videoKernel + return NativeVideoKernel; + } + }, { + key: 'errorLog', + value: function errorLog() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + this.emit('error', new Error(args[0])); + return Log$1.error.apply(Log$1, [LOG_TAG].concat(args)); + } + }, { + key: 'warnLog', + value: function warnLog() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return Log$1.warn.apply(Log$1, [LOG_TAG].concat(args)); + } + }, { + key: 'bindEvents', + value: function bindEvents(videoKernel) { + var _this2 = this; + + var remove = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + kernelEvents.forEach(function (eventName) { + /* istanbul ignore next */ + // $FlowFixMe: we have make sure it's legal now + videoKernel[remove ? 'off' : 'on'](eventName, function () { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + data = _ref2.data; + + _this2.emit(eventName, data); + }); + }); + } + }, { + key: 'attachMedia', + value: function attachMedia() { + this.videoKernel.attachMedia(); + } + }, { + key: 'load', + value: function load() { + var src = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.config.src; + + this.config.src = src; + this.videoKernel.load(src); + } + }, { + key: 'startLoad', + value: function startLoad() { + /* istanbul ignore if */ + if (!isFunction(this.videoKernel.startLoad)) throw new Error('This video kernel do not support startLoad, please contact us on https://github.com/Chimeejs/chimee/issues'); + this.videoKernel.startLoad(this.config.src); + } + }, { + key: 'stopLoad', + value: function stopLoad() { + /* istanbul ignore else */ + if (isFunction(this.videoKernel.stopLoad)) this.videoKernel.stopLoad(); + } + }, { + key: 'play', + value: function play() { + this.videoKernel.play(); + } + }, { + key: 'pause', + value: function pause() { + this.videoKernel.pause(); + } + }, { + key: 'seek', + value: function seek(seconds) { + if (!isNumber(seconds)) { + this.errorLog('When you try to seek, you must offer us a number, but not ' + (typeof seconds === 'undefined' ? 'undefined' : _typeof(seconds))); + return; + } + this.videoKernel.seek(seconds); + } + }, { + key: 'refresh', + value: function refresh() { + this.videoKernel.refresh(); + } + }, { + key: 'currentTime', + get: function get() { + return this.videoElement.currentTime || 0; + } + }]); + + return ChimeeKernel; +}(CustEvent); + +var _global$1 = createCommonjsModule(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef +}); + +var _core$1 = createCommonjsModule(function (module) { +var core = module.exports = { version: '2.5.3' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef +}); +var _core_1$1 = _core$1.version; + +var _isObject$1 = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject$1 = function (it) { + if (!_isObject$1(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails$1 = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors$1 = !_fails$1(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +var document$3 = _global$1.document; +// typeof document.createElement is 'object' in old IE +var is$1 = _isObject$1(document$3) && _isObject$1(document$3.createElement); +var _domCreate$1 = function (it) { + return is$1 ? document$3.createElement(it) : {}; +}; + +var _ie8DomDefine$1 = !_descriptors$1 && !_fails$1(function () { + return Object.defineProperty(_domCreate$1('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive$1 = function (it, S) { + if (!_isObject$1(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject$1(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !_isObject$1(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !_isObject$1(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP$4 = Object.defineProperty; + +var f$8 = _descriptors$1 ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject$1(O); + P = _toPrimitive$1(P, true); + _anObject$1(Attributes); + if (_ie8DomDefine$1) try { + return dP$4(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +var _objectDp$1 = { + f: f$8 +}; + +var _propertyDesc$1 = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +var _hide$1 = _descriptors$1 ? function (object, key, value) { + return _objectDp$1.f(object, key, _propertyDesc$1(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +var hasOwnProperty$1 = {}.hasOwnProperty; +var _has$1 = function (it, key) { + return hasOwnProperty$1.call(it, key); +}; + +var id$2 = 0; +var px$1 = Math.random(); +var _uid$1 = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id$2 + px$1).toString(36)); +}; + +var _redefine$1 = createCommonjsModule(function (module) { +var SRC = _uid$1('src'); +var TO_STRING = 'toString'; +var $toString = Function[TO_STRING]; +var TPL = ('' + $toString).split(TO_STRING); + +_core$1.inspectSource = function (it) { + return $toString.call(it); +}; + +(module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) _has$1(val, 'name') || _hide$1(val, 'name', key); + if (O[key] === val) return; + if (isFunction) _has$1(val, SRC) || _hide$1(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if (O === _global$1) { + O[key] = val; + } else if (!safe) { + delete O[key]; + _hide$1(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + _hide$1(O, key, val); + } +// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative +})(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || $toString.call(this); +}); +}); + +var _aFunction$1 = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx$1 = function (fn, that, length) { + _aFunction$1(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +var PROTOTYPE$3 = 'prototype'; + +var $export$1 = function (type, name, source) { + var IS_FORCED = type & $export$1.F; + var IS_GLOBAL = type & $export$1.G; + var IS_STATIC = type & $export$1.S; + var IS_PROTO = type & $export$1.P; + var IS_BIND = type & $export$1.B; + var target = IS_GLOBAL ? _global$1 : IS_STATIC ? _global$1[name] || (_global$1[name] = {}) : (_global$1[name] || {})[PROTOTYPE$3]; + var exports = IS_GLOBAL ? _core$1 : _core$1[name] || (_core$1[name] = {}); + var expProto = exports[PROTOTYPE$3] || (exports[PROTOTYPE$3] = {}); + var key, own, out, exp; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? _ctx$1(out, _global$1) : IS_PROTO && typeof out == 'function' ? _ctx$1(Function.call, out) : out; + // extend global + if (target) _redefine$1(target, key, out, type & $export$1.U); + // export + if (exports[key] != out) _hide$1(exports, key, exp); + if (IS_PROTO && expProto[key] != out) expProto[key] = out; + } +}; +_global$1.core = _core$1; +// type bitmap +$export$1.F = 1; // forced +$export$1.G = 2; // global +$export$1.S = 4; // static +$export$1.P = 8; // proto +$export$1.B = 16; // bind +$export$1.W = 32; // wrap +$export$1.U = 64; // safe +$export$1.R = 128; // real proto method for `library` +var _export$1 = $export$1; + +// https://github.com/tc39/proposal-global + + +_export$1(_export$1.G, { global: _global$1 }); + +var global$1 = _core$1.global; + +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', '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', 'mousewheel', 'fullscreenchange', 'contextmenu', 'touchstart', 'touchmove', 'touchend']; +var passiveEvents = ['wheel', 'mousewheel', 'touchstart', 'touchmove']; +var selfProcessorEvents = ['silentLoad', 'fullscreen']; +var kernelMethods = ['play', 'pause', 'seek', 'startLoad', 'stopLoad']; +var dispatcherMethods = ['load']; +var kernelEvents$1 = ['mediaInfo', 'heartbeat', 'error']; +var domMethods = ['focus', 'fullscreen', 'requestFullscreen', 'exitFullscreen']; +var videoMethods = ['canPlayType', 'captureStream', 'setSinkId']; + +var _dec$1, _dec2$1, _dec3$1, _dec4$1, _class$1; + +function _applyDecoratedDescriptor$1(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; +} +var secondaryReg = /^(before|after|_)/; +function secondaryChecker(key) { + if (key.match(secondaryReg)) { + return false; + } + return true; +} +/** + *
+ * event Bus class. Bus take charge of commuication between plugins and user.
+ * Some of the event may trigger the kernel to do some task.
+ * An event will run in four lifecycle
+ * before -> processor -> main -> after -> side effect(_)
+ * -------------------- emit period ----------------
+ * before: once an event emit, it will run through plugins in bubble to know is it possible to run.
+ * processor: if sth need to be done on kernel. It will tell kernel. If kernel will trigger event later, it will break down here. Else will run into trigger period
+ * -------------------- trigger period -----------------
+ * main: this procedure will trigger the main event in bubble, which means it can be stop in one plugin.
+ * after: once event run through all events. It will trigger after event. This event will be trigger in broadcast way.
+ * side effect(_): This events will always trigger once we bump into trigger period. So that you can know if the events been blocked. But it's not advice to listen on this effect.
+ * 
+ */ +var Bus = (_dec$1 = runnable(secondaryChecker), _dec2$1 = runnable(secondaryChecker, { + backup: function backup() { + return false; + } +}), _dec3$1 = runnable(secondaryChecker), _dec4$1 = runnable(secondaryChecker, { + backup: function backup() { + return false; + } +}), _class$1 = function () { + /** + * @param {Dispatcheer} dispatcher bus rely on dispatcher, so you mush pass dispatcher at first when you generate Bus. + * @return {Bus} + */ + + /** + * the handler set of all events + * @type {Object} + * @member events + */ + function Bus(dispatcher) { + _classCallCheck(this, Bus); + + this.events = {}; + this.onceMap = {}; + + /** + * the referrence to dispatcher + * @type {Dispatcher} + */ + this.__dispatcher = dispatcher; + } + /** + * [Can only be called in dispatcher]bind event on bus. + * @param {string} id plugin's id + * @param {string} key event's name + * @param {fn} handler function + */ + + + _createClass(Bus, [{ + key: 'on', + value: function on(id, key, fn) { + var _getEventStage2 = this._getEventStage(key), + stage = _getEventStage2.stage, + eventName = _getEventStage2.key; + + this._addEvent([eventName, stage, id], fn); + } + /** + * [Can only be called in dispatcher]remove event off bus. Only suggest one by one. + * @param {string} id plugin's id + * @param {string} key event's name + * @param {fn} handler function + */ + + }, { + key: 'off', + value: function off(id, key, fn) { + var _getEventStage3 = this._getEventStage(key), + stage = _getEventStage3.stage, + eventName = _getEventStage3.key; + + var keys = [eventName, stage, id]; + var deleted = this._removeEvent(keys, fn); + if (deleted) return; + var handler = this._getHandlerFromOnceMap(keys, fn); + if (isFunction(handler)) { + this._removeEvent(keys, handler) && this._removeFromOnceMap(keys, fn, handler); + } + } + /** + * [Can only be called in dispatcher]bind event on bus and remove it once event is triggered. + * @param {string} id plugin's id + * @param {string} key event's name + * @param {Function} fn handler function + */ + + }, { + key: 'once', + value: function once(id, key, fn) { + var _getEventStage4 = this._getEventStage(key), + stage = _getEventStage4.stage, + eventName = _getEventStage4.key; + + var bus = this; + var keys = [eventName, stage, id]; + var handler = function handler() { + // keep the this so that it can run + bind(fn, this).apply(undefined, arguments); + bus._removeEvent(keys, handler); + bus._removeFromOnceMap(keys, fn, handler); + }; + this._addEvent(keys, handler); + this._addToOnceMap(keys, fn, handler); + } + /** + * [Can only be called in dispatcher]emit an event, which will run before -> processor period. + * It may stop in before period. + * @param {string} key event's name + * @param {anything} args other argument will be passed into handler + * @return {Promise} this promise maybe useful if the event would not trigger kernel event. In that will you can know if it runs successful. But you can know if the event been stopped by the promise. + */ + + }, { + key: 'emit', + value: function emit(key) { + var _this = this; + + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var event = this.events[key]; + if (isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return _Promise.resolve(); + // $FlowFixMe: conditional return here + 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); + return _Promise.reject(error); + }); + } + /** + * [Can only be called in dispatcher]emit an event, which will run before -> processor period synchronize. + * It may stop in before period. + * @param {string} key event's name + * @param {anything} args other argument will be passed into handler + * @return {Promise} this promise maybe useful if the event would not trigger kernel event. In that will you can know if it runs successful. But you can know if the event been stopped by the promise. + */ + + }, { + key: 'emitSync', + value: function emitSync(key) { + var event = this.events[key]; + + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + if (isEmpty(event)) { + if (selfProcessorEvents.indexOf(key) > -1) return true; + // $FlowFixMe: conditional return here + 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))) && (selfProcessorEvents.indexOf(key) > -1 || + // $FlowFixMe: conditional return here + 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 + * @param {string} key event's name + * @param {anything} args + * @return {Promise|undefined} you can know if event trigger finished~ However, if it's unlegal + */ + + }, { + key: 'trigger', + value: function trigger(key) { + var _this2 = this; + + for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + + var event = this.events[key]; + if (isEmpty(event)) { + return _Promise.resolve(true); + } + var mainQueue = this._getEventQueue(event.main, this.__dispatcher.order); + return runRejectableQueue.apply(undefined, [mainQueue].concat(_toConsumableArray(args))).then(function () { + var afterQueue = _this2._getEventQueue(event.after, _this2.__dispatcher.order); + return runRejectableQueue.apply(undefined, [afterQueue].concat(_toConsumableArray(args))); + }).then(function () { + return _this2._runSideEffectEvent.apply(_this2, [key, _this2.__dispatcher.order].concat(_toConsumableArray(args))); + }).catch(function (error) { + if (isError(error)) _this2.__dispatcher.throwError(error); + return _this2._runSideEffectEvent.apply(_this2, [key, _this2.__dispatcher.order].concat(_toConsumableArray(args))); + }); + } + /** + * [Can only be called in dispatcher]trigger an event, which will run main -> after -> side effect period in synchronize + * @param {string} key event's name + * @param {anything} args + * @return {boolean} you can know if event trigger finished~ However, if it's unlegal + */ + + }, { + key: 'triggerSync', + value: function triggerSync(key) { + var event = this.events[key]; + if (isEmpty(event)) { + return true; + } + var mainQueue = this._getEventQueue(event.main, this.__dispatcher.order); + var afterQueue = this._getEventQueue(event.after, this.__dispatcher.order); + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + var result = runStoppableQueue.apply(undefined, [mainQueue].concat(_toConsumableArray(args))) && runStoppableQueue.apply(undefined, [afterQueue].concat(_toConsumableArray(args))); + this._runSideEffectEvent.apply(this, [key, this.__dispatcher.order].concat(_toConsumableArray(args))); + return result; + } + /** + * destroy hook which will be called when object destroy + */ + + }, { + key: 'destroy', + value: function destroy() { + delete this.events; + delete this.__dispatcher; + } + /** + * add event into bus + * @private + * @param {Array} keys keys map pointing to position to put event handler + * @param {function} fn handler to put + */ + + }, { + key: '_addEvent', + value: function _addEvent(keys, fn) { + keys = deepClone(keys); + var id = keys.pop(); + var target = keys.reduce(function (target, key) { + target[key] = target[key] || {}; + return target[key]; + }, this.events); + // events will store like {play: {main: {plugin: []}}} + target[id] = target[id] || []; + target[id].push(fn); + } + /** + * remove event from bus + * @private + * @param {Array} keys keys map pointing to position to get event handler + * @param {function} fn handler to put + */ + + }, { + key: '_removeEvent', + value: function _removeEvent(keys, fn) { + keys = deepClone(keys); + var id = keys.pop(); + var target = this.events; + for (var i = 0, len = keys.length; i < len; i++) { + var son = target[keys[i]]; + // if we can't find the event binder, just return + if (isEmpty(son)) return; + target = son; + } + var queue = target[id] || []; + var index$$1 = queue.indexOf(fn); + var hasFn = index$$1 > -1; + // if we found handler remove it + if (hasFn) { + queue.splice(index$$1, 1); + } + // if this plugin has no event binding, we remove this event session, which make us perform faster in emit & trigger period. + if (queue.length < 1) { + delete target[id]; + } + return hasFn; + } + }, { + key: '_addToOnceMap', + value: function _addToOnceMap(keys, fn, handler) { + var key = keys.join('-'); + var map = this.onceMap[key] = this.onceMap[key] || new _Map(); + if (!map.has(fn)) map.set(fn, []); + var handlers = map.get(fn); + // $FlowFixMe: flow do not understand map yet + handlers.push(handler); + } + }, { + key: '_removeFromOnceMap', + value: function _removeFromOnceMap(keys, fn, handler) { + var key = keys.join('-'); + var map = this.onceMap[key]; + // do not need to check now + // if(isVoid(map) || !map.has(fn)) return; + var handlers = map.get(fn); + var index$$1 = handlers.indexOf(handler); + handlers.splice(index$$1, 1); + if (isEmpty(handlers)) map.delete(fn); + } + }, { + key: '_getHandlerFromOnceMap', + value: function _getHandlerFromOnceMap(keys, fn) { + var key = keys.join('-'); + var map = this.onceMap[key]; + if (isVoid(map) || !map.has(fn)) return; + var handlers = map.get(fn); + return handlers[0]; + } + /** + * get event stage by evnet key name + * @private + * @param {key} key event's name + * @return {stage} event stage + */ + + }, { + key: '_getEventStage', + value: function _getEventStage(key) { + var secondaryCheck = key.match(secondaryReg); + var stage = secondaryCheck && secondaryCheck[0] || 'main'; + if (secondaryCheck) { + key = camelize(key.replace(secondaryReg, '')); + } + return { stage: stage, key: key }; + } + /** + * get event handlers queue to run + * @private + * @param {Object} handlerSet the object include all handler + * @param {Array} Array form of plugin id + * @return {Array} event handler in queue to run + */ + + }, { + key: '_getEventQueue', + value: function _getEventQueue(handlerSet, order) { + var _this3 = this; + + order = isArray(order) ? order.concat(['_vm']) : ['_vm']; + return isEmpty(handlerSet) ? [] : order.reduce(function (queue, id) { + if (isEmpty(handlerSet[id]) || !isArray(handlerSet[id]) || + // in case plugins is missed + // _vm indicate the user. This is the function for user + !_this3.__dispatcher.plugins[id] && id !== '_vm') { + return queue; + } + return queue.concat(handlerSet[id].map(function (fn) { + // bind context for plugin instance + return bind(fn, _this3.__dispatcher.plugins[id] || _this3.__dispatcher.vm); + })); + }, []); + } + /** + * event processor period. If event needs call kernel function. + * I will called here. + * If kernel will reponse. I will stop here. + * Else I will trigger next period. + * @param {string} key event's name + * @param {boolean} options.sync we will take triggerSync if true, otherwise we will run trigger. default is false + * @param {anything} args + * @return {Promise|undefined} + */ + + }, { + key: '_eventProcessor', + value: function _eventProcessor(key, _ref) { + var sync = _ref.sync; + + 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 || isDispatcherMethod) { + if (isDispatcherMethod) { + var _dispatcher; + + (_dispatcher = this.__dispatcher)[key].apply(_dispatcher, _toConsumableArray(args)); + } else { + var _dispatcher2; + + (_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 + return this[sync ? 'triggerSync' : 'trigger'].apply(this, [key].concat(_toConsumableArray(args))); + } + /** + * run side effect period + * @param {string} key event's name + * @param {args} args + */ + + }, { + key: '_runSideEffectEvent', + value: function _runSideEffectEvent(key, order) { + for (var _len6 = arguments.length, args = Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) { + args[_key6 - 2] = arguments[_key6]; + } + + var event = this.events[key]; + if (isEmpty(event)) { + return false; + } + var queue = this._getEventQueue(event._, order); + queue.forEach(function (run) { + return run.apply(undefined, _toConsumableArray(args)); + }); + return true; + } + }]); + + return Bus; +}(), _applyDecoratedDescriptor$1(_class$1.prototype, 'emit', [_dec$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'emit'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1.prototype, 'emitSync', [_dec2$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'emitSync'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1.prototype, 'trigger', [_dec3$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'trigger'), _class$1.prototype), _applyDecoratedDescriptor$1(_class$1.prototype, 'triggerSync', [_dec4$1], _Object$getOwnPropertyDescriptor(_class$1.prototype, 'triggerSync'), _class$1.prototype), _class$1); + +/** + * 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); +} + +var _dec$1$1, _dec2$1$1, _class$1$1, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7; + +function _initDefineProp(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$1$1(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$$1(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$$1(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 + /* istanbul ignore next */ + : value === null ? undefined : value; + this.dom.setAttr('video', _set, val); + return value; + } + }, { + preSet: false + }); +} + +function accessorCustomAttribute(attribute, isBoolean$$1) { + return accessor({ + get: function get$$1(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 === null ? undefined : value; + this.dom.setAttr('video', attribute, val); + return value; + } + }); +} + +function accessorWidthAndHeight(property) { + return accessor({ + get: function get$$1(value) { + if (!this.dispatcher.videoConfigReady || !this.inited) 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: [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: function set(value) { + var options = ['none', 'auto', 'metadata', '']; + return options.indexOf(value) > -1 ? value : 'none'; + } + }, { + preSet: true + }), accessorVideoAttribute('preload')], + poster: [ + // 因为如果在 video 上随便加一个字符串,他会将其拼接到地址上,所以这里要避免 + // 单元测试无法检测 + string$1(), accessor({ + get: function get$$1(value) { + return this.dispatcher.videoConfigReady && this.inited ? this.dom.videoElement.poster : value; + }, + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + if (value.length) this.dom.setAttr('video', 'poster', value); + return value; + } + })], + playsInline: [accessor({ + get: function get$$1(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-playsinline', val); + return value; + } + }), boolean$1()], + x5VideoPlayerFullscreen: [accessor({ + set: function set(value) { + return !!value; + }, + get: function get$$1(value) { + return !!value; + } + }), accessorCustomAttribute('x5-video-player-fullscreen', true)], + x5VideoOrientation: [accessor({ set: stringOrVoid }), accessorCustomAttribute('x5-video-orientation')], + x5VideoPlayerType: [accessor({ + set: function set(value) { + if (!this.dispatcher.videoConfigReady) return value; + var val = value === 'h5' ? 'h5' : undefined; + this.dom.setAttr('video', 'x5-video-player-type', val); + return value; + }, + get: function get$$1() { + return this.dom.getAttr('video', 'x5-video-player-type') ? 'h5' : undefined; + } + })], + xWebkitAirplay: [accessor({ + set: function set(value) { + return !!value; + }, + get: function get$$1(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$1$1 = boolean(), _dec2$1$1 = string(function (str) { + return str.toLocaleLowerCase(); +}), _class$1$1 = function () { + + // 转为供 kernel 使用的内部参数 + function VideoConfig(dispatcher, config) { + _classCallCheck(this, VideoConfig); + + _initDefineProp(this, 'needToLoadSrc', _descriptor, this); + + _initDefineProp(this, 'changeWatchable', _descriptor2, this); + + _initDefineProp(this, 'inited', _descriptor3, this); + + this.src = ''; + + _initDefineProp(this, 'isLive', _descriptor4, this); + + _initDefineProp(this, 'box', _descriptor5, this); + + this.preset = {}; + this.presetConfig = {}; + this.autoload = true; + this.autoplay = false; + this.controls = false; + this.width = '100%'; + this.height = '100%'; + 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.x5VideoPlayerType = undefined; + this.xWebkitAirplay = false; + this.playbackRate = 1; + this.defaultPlaybackRate = 1; + this.disableRemotePlayback = false; + this.volume = 1; + + _initDefineProp(this, '_kernelProperty', _descriptor6, this); + + _initDefineProp(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); + } + + // 此处 box 只能置空,因为 kernel 会自动根据你的安装 kernel 和相关地址作智能判断。 + // 曾经 bug 详见 https://github.com/Chimeejs/chimee-kernel/issues/1 + + // kernels 不在 videoConfig 上设置默认值,防止判断出错 + + + _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 = _applyDecoratedDescriptor$1$1(_class$1$1.prototype, 'needToLoadSrc', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor2 = _applyDecoratedDescriptor$1$1(_class$1$1.prototype, 'changeWatchable', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return true; + } +}), _descriptor3 = _applyDecoratedDescriptor$1$1(_class$1$1.prototype, 'inited', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor4 = _applyDecoratedDescriptor$1$1(_class$1$1.prototype, 'isLive', [_dec$1$1, nonconfigurable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _descriptor5 = _applyDecoratedDescriptor$1$1(_class$1$1.prototype, 'box', [_dec2$1$1, nonconfigurable], { + enumerable: true, + initializer: function initializer() { + return ''; + } +}), _descriptor6 = _applyDecoratedDescriptor$1$1(_class$1$1.prototype, '_kernelProperty', [frozen], { + enumerable: true, + initializer: function initializer() { + return ['isLive', 'box', 'preset', 'kernels', 'presetConfig']; + } +}), _descriptor7 = _applyDecoratedDescriptor$1$1(_class$1$1.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', 'x5VideoPlayerType']; + } +}), _class$1$1); + +var _dec$2, _dec2$2, _dec3$1$1, _dec4$1$1, _dec5$1, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _dec19, _class$2, _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; +} +var VideoWrapper = (_dec$2 = autobindClass(), _dec2$2 = alias('silentLoad'), _dec3$1$1 = alias('fullScreen'), _dec4$1$1 = alias('$fullScreen'), _dec5$1 = alias('fullscreen'), _dec6 = alias('emit'), _dec7 = alias('emitSync'), _dec8 = alias('on'), _dec9 = alias('addEventListener'), _dec10 = before(eventBinderCheck), _dec11 = alias('off'), _dec12 = alias('removeEventListener'), _dec13 = before(eventBinderCheck), _dec14 = alias('once'), _dec15 = before(eventBinderCheck), _dec16 = alias('css'), _dec17 = before(attrAndStyleCheck), _dec18 = alias('attr'), _dec19 = before(attrAndStyleCheck), _dec$2(_class$2 = (_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$$1() { + 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$$1() { + 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$$1() { + // $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) { + 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 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$$1 = _this3.__unwatchHandlers.indexOf(unwatcher); + if (index$$1 > -1) _this3.__unwatchHandlers.splice(index$$1, 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)) { + // $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)) { + // $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) { + 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'); + + 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) { + 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$$1 = this.__events[key].indexOf(fn); + if (index$$1 < 0) return; + this.__events[key].splice(index$$1, 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$$1() { + return this.__dispatcher.kernel.currentTime; + }, + set: function set(second) { + this.__dispatcher.bus.emitSync('seek', second); + } + }, { + key: '$plugins', + get: function get$$1() { + return this.__dispatcher.plugins; + } + }, { + key: '$pluginOrder', + get: function get$$1() { + return this.__dispatcher.order; + } + }, { + key: '$wrapper', + get: function get$$1() { + return this.__dispatcher.dom.wrapper; + } + }, { + key: '$container', + get: function get$$1() { + return this.__dispatcher.dom.container; + } + }, { + key: '$video', + get: function get$$1() { + return this.__dispatcher.dom.videoElement; + } + }, { + key: 'isFullscreen', + get: function get$$1() { + return this.__dispatcher.dom.isFullscreen; + } + }, { + key: 'fullscreenElement', + get: function get$$1() { + return this.__dispatcher.dom.fullscreenElement; + } + }, { + key: 'container', + get: function get$$1() { + return this.__dispatcher.containerConfig; + }, + set: function set(config) { + if (!isObject(config)) { + throw new Error('The config of container must be Object, but not ' + (typeof config === 'undefined' ? 'undefined' : _typeof(config)) + '.'); + } + deepAssign(this.__dispatcher.containerConfig, config); + return this.__dispatcher.container; + } + }]); + + return VideoWrapper; +}(), _applyDecoratedDescriptor$2(_class2$1.prototype, '$silentLoad', [_dec2$2], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$silentLoad'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$fullscreen', [_dec3$1$1, _dec4$1$1, _dec5$1], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$fullscreen'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emit', [_dec6], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emit'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$emitSync', [_dec7], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$emitSync'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$on', [_dec8, _dec9, _dec10], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$on'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$off', [_dec11, _dec12, _dec13], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$off'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$once', [_dec14, _dec15], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$once'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$css', [_dec16, _dec17], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$css'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$attr', [_dec18, _dec19], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$attr'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$plugins', [nonenumerable], _Object$getOwnPropertyDescriptor(_class2$1.prototype, '$plugins'), _class2$1.prototype), _applyDecoratedDescriptor$2(_class2$1.prototype, '$pluginOrder', [nonenumerable], _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$2); + +var _dec$3, _class$3; + +/** + *
+ * 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
+ * 
+ */ +var Plugin = (_dec$3 = autobindClass(), _dec$3(_class$3 = function (_VideoWrapper) { + _inherits(Plugin, _VideoWrapper); + + /** + *
+   * 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()
+   * 
+ * @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} 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; + + var dispatcher = arguments[1]; + var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { name: name }; + + _classCallCheck(this, Plugin); + + var _this = _possibleConstructorReturn(this, (Plugin.__proto__ || _Object$getPrototypeOf(Plugin)).call(this)); + + _this.destroyed = false; + _this.VERSION = '0.9.3'; + _this.__operable = true; + _this.__level = 0; + + if (isEmpty(dispatcher)) { + throw new TypeError('lack of dispatcher'); + } + if (!isString(id)) { + throw new TypeError('id of PluginConfig must be string'); + } + _this.__id = id; + _this.__dispatcher = dispatcher; + _this.$videoConfig = _this.__dispatcher.videoConfig; + _this.__wrapAsVideo(_this.$videoConfig); + _this.beforeCreate = _this.beforeCreate || beforeCreate; + try { + isFunction(_this.beforeCreate) && _this.beforeCreate({ + events: events, + data: data, + computed: computed, + methods: methods + }, option); + } catch (error) { + _this.$throwError(error); + } + // bind plugin methods into instance + if (!isEmpty(methods) && isObject(methods)) { + _Object$keys(methods).forEach(function (key) { + var fn = methods[key]; + if (!isFunction(fn)) throw new TypeError('plugins methods must be Function'); + _Object$defineProperty(_this, key, { + value: bind(fn, _this), + writable: true, + enumerable: false, + configurable: true + }); + }); + } + // hook plugin events on bus + if (!isEmpty(events) && isObject(events)) { + _Object$keys(events).forEach(function (key) { + if (!isFunction(events[key])) throw new TypeError('plugins events hook must bind with Function'); + _this.$on(key, events[key]); + }); + } + // bind data into plugin instance + if (!isEmpty(data) && isObject(data)) { + deepAssign(_this, data); + } + // set the computed member by getter and setter + if (!isEmpty(computed) && isObject(computed)) { + var props = _Object$keys(computed).reduce(function (props, key) { + var val = computed[key]; + if (isFunction(val)) { + props[key] = accessor({ get: val }); + return props; + } + if (isObject(val) && (isFunction(val.get) || isFunction(val.set))) { + props[key] = accessor(val); + return props; + } + return props; + }, {}); + applyDecorators(_this, props, { self: true }); + } + /** + * the create Function of plugin + * @type {Function} + */ + _this.create = _this.create || create; + /** + * this init Function of plugin + * which will be called when we start to create the video player + * the plugin can handle some config here + * @type {Function} + */ + _this.init = _this.init || init; + /** + * this inited Function of plugin + * which will be called when we have created the video player + * @type {Function} + */ + _this.inited = _this.inited || inited; + /** + * the destroy Function of plugin + * @type {Function} + */ + _this.destroy = _this.destroy || destroy; + /** + * the dom node of whole plugin + * @type {HTMLElement} + */ + _this.$dom = _this.__dispatcher.dom.insertPlugin(_this.__id, el, { penetrate: penetrate, inner: inner, autoFocus: autoFocus, className: className }); + // now we can frozen inner, autoFocus and penetrate + _this.$inner = inner; + _this.$autoFocus = autoFocus; + _this.$penetrate = penetrate; + applyDecorators(_this, { + $inner: frozen, + $autoFocus: frozen, + $penetrate: frozen + }, { self: true }); + /** + * to tell us if the plugin can be operable, can be dynamic change + * @type {boolean} + */ + _this.$operable = isBoolean(option.operable) ? option.operable : operable; + _this.__level = isInteger$2(option.level) ? option.level : level; + /** + * pluginOption, so it's easy for plugin developer to check the config + * @type {Object} + */ + _this.$config = option; + try { + isFunction(_this.create) && _this.create(); + } catch (error) { + _this.$throwError(error); + } + return _this; + } + /** + * call for init lifecycle hook, which mainly handle the original config of video and kernel. + * @param {VideoConfig} videoConfig the original config of the videoElement or Kernel + */ + + + _createClass(Plugin, [{ + key: '__init', + value: function __init(videoConfig) { + try { + isFunction(this.init) && this.init(videoConfig); + } catch (error) { + this.$throwError(error); + } + } + /** + * call for inited lifecycle hook, which just to tell the plugin we have inited. + */ + + }, { + key: '__inited', + value: function __inited() { + var _this2 = this; + + var result = void 0; + try { + result = isFunction(this.inited) && this.inited(); + } catch (error) { + this.$throwError(error); + } + this.readySync = !isPromise(result); + this.ready = this.readySync ? _Promise.resolve() + // $FlowFixMe: it's promise now + : result.then(function (ret) { + _this2.readySync = true; + return ret; + }).catch(function (error) { + if (isError(error)) return _this2.$throwError(error); + return _Promise.reject(error); + }); + return this.readySync || this.ready; + } + + /** + * set the plugin to be the top of all plugins + */ + + }, { + key: '$bumpToTop', + value: function $bumpToTop() { + var topLevel = this.__dispatcher._getTopLevel(this.$inner); + this.$level = topLevel + 1; + } + }, { + key: '$throwError', + value: function $throwError(error) { + this.__dispatcher.throwError(error); + } + /** + * officail destroy function for plugin + * we will call user destory function in this method + */ + + }, { + key: '$destroy', + value: function $destroy() { + isFunction(this.destroy) && this.destroy(); + _get(Plugin.prototype.__proto__ || _Object$getPrototypeOf(Plugin.prototype), '__destroy', this).call(this); + this.__dispatcher.dom.removePlugin(this.__id); + delete this.__dispatcher; + delete this.$dom; + this.destroyed = true; + } + /** + * to tell us if the plugin can be operable, can be dynamic change + * @type {boolean} + */ + + }, { + key: '$operable', + set: function set(val) { + if (!isBoolean(val)) return; + this.$dom.style.pointerEvents = val ? 'auto' : 'none'; + this.__operable = val; + }, + get: function get$$1() { + return this.__operable; + } + /** + * the z-index level, higher when you set higher + * @type {boolean} + */ + + }, { + key: '$level', + set: function set(val) { + if (!isInteger$2(val)) return; + this.__level = val; + this.__dispatcher._sortZIndex(); + }, + get: function get$$1() { + return this.__level; + } + }]); + + return Plugin; +}(VideoWrapper)) || _class$3); + +var _dec$4, _dec2$3, _dec3$2, _dec4$2, _dec5$1$1, _dec6$1, _class$4; + +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 targetCheck(target) { + if (target === 'video') target = 'videoElement'; + if (!isElement(this[target])) throw new TypeError('Your target "' + target + '" is not a legal HTMLElement'); + + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + return [target].concat(args); +} +function attrOperationCheck(target, attr, val) { + if (!isString(attr)) throw new TypeError('to handle dom\'s attribute or style, your attr parameter must be string, but not ' + attr + ' in ' + (typeof attr === 'undefined' ? 'undefined' : _typeof(attr))); + if (!isString(target)) throw new TypeError('to handle dom\'s attribute or style, your target parameter must be string, , but not ' + target + ' in ' + (typeof target === 'undefined' ? 'undefined' : _typeof(target))); + return [target, attr, val]; +} +/** + *
+ * Dom work for Dispatcher.
+ * It take charge of dom management of Dispatcher.
+ * 
+ */ +var Dom = (_dec$4 = waituntil('__dispatcher.videoConfigReady'), _dec2$3 = before(attrOperationCheck, targetCheck), _dec3$2 = before(attrOperationCheck, targetCheck), _dec4$2 = before(attrOperationCheck, targetCheck), _dec5$1$1 = before(attrOperationCheck, targetCheck), _dec6$1 = before(targetCheck), _class$4 = function () { + /** + * to mark is the mouse in the video area + */ + + /** + * Array to store all video dom event handler + */ + + /** + * Array to store all video dom event handler + */ + + /** + * the html to restore when we are destroyed + */ + function Dom(wrapper, dispatcher) { + var _this = this; + + _classCallCheck(this, Dom); + + this.plugins = {}; + this.originHTML = ''; + this.videoEventHandlerList = []; + this.videoDomEventHandlerList = []; + this.containerDomEventHandlerList = []; + this.wrapperDomEventHandlerList = []; + this.__domEventHandlerList = {}; + this.__mouseInVideo = false; + this.__videoExtendedNodes = []; + this.isFullscreen = false; + this.fullscreenElement = undefined; + + this.__dispatcher = dispatcher; + if (!isElement(wrapper) && !isString(wrapper)) throw new TypeError('Wrapper can only be string or HTMLElement, but not ' + (typeof wrapper === 'undefined' ? 'undefined' : _typeof(wrapper))); + var $wrapper = $(wrapper); + if ($wrapper.length === 0) { + throw new TypeError('Can not get dom node accroding wrapper. Please check your wrapper'); + } + /** + * the referrence of the dom wrapper of whole Chimee + */ + // $FlowFixMe: support computed key on nodewrap + this.wrapper = $wrapper[0]; + this.originHTML = this.wrapper.innerHTML; + // if we find video element inside wrapper + // we use it + // or we create a video element by ourself. + // $FlowFixMe: support computed key on nodewrap + var videoElement = $wrapper.find('video')[0]; + if (!videoElement) { + videoElement = document.createElement('video'); + } + /** + * referrence of video's dom element + */ + this.installVideo(videoElement); + this._addDomEvents(this.container, this.containerDomEventHandlerList, function (key) { + return function () { + 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).triggerSync.apply(_dispatcher$bus, ['c_' + key].concat(_toConsumableArray(args))); + }; + }); + this._addDomEvents(this.wrapper, this.wrapperDomEventHandlerList, function (key) { + return function () { + 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, ['w_' + key].concat(_toConsumableArray(args))); + }; + }); + this._fullscreenMonitor(); + index.on('fullscreenchange', this._fullscreenMonitor); + } + /** + * collection of video extension nodes + * some nodes can be regarded as part of video (such as penetrate element) + * so we store them here + */ + + /** + * Object to store different plugin's dom event handlers + */ + + /** + * Array to store all container dom event handler + */ + + /** + * Array to store all video event handler + */ + + /** + * all plugin's dom element set + */ + + + _createClass(Dom, [{ + key: 'installVideo', + value: function installVideo(videoElement) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$bindEvent = _ref.bindEvent, + bindEvent = _ref$bindEvent === undefined ? true : _ref$bindEvent; + + 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); + } + if (bindEvent) this.bindVideoEvents(videoElement); + this.videoElement = videoElement; + return videoElement; + } + }, { + key: 'bindVideoEvents', + value: function bindVideoEvents(videoElement) { + var _this2 = this; + + videoEvents.forEach(function (key) { + var fn = function fn() { + var _dispatcher$bus3; + + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + return (_dispatcher$bus3 = _this2.__dispatcher.bus).trigger.apply(_dispatcher$bus3, [key].concat(_toConsumableArray(args))); + }; + _this2.videoEventHandlerList.push(fn); + addEvent(videoElement, key, fn); + }); + this._addDomEvents(videoElement, this.videoDomEventHandlerList, function (key) { + return _this2._getEventHandler(key, { penetrate: true }); + }); + } + }, { + key: 'removeVideo', + value: function removeVideo() { + var _this3 = this; + + var videoElement = this.videoElement; + this._autoFocusToVideo(this.videoElement, false); + videoEvents.forEach(function (key, index$$1) { + removeEvent(_this3.videoElement, key, _this3.videoEventHandlerList[index$$1]); + }); + this.videoEventHandlerList = []; + domEvents.forEach(function (key, index$$1) { + removeEvent(_this3.videoElement, key, _this3.videoDomEventHandlerList[index$$1]); + }); + this.videoDomEventHandlerList = []; + $(videoElement).remove(); + delete this.videoElement; + return videoElement; + } + + /** + * 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 + */ + + }, { + key: 'insertPlugin', + value: function insertPlugin(id, el) { + var _this4 = this; + + var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!isString(id)) throw new TypeError('insertPlugin id parameter must be string'); + if (isElement(this.plugins[id])) { + this.removePlugin(id); + } + if (isString(el)) { + if (isHTMLString(el)) { + var outer = document.createElement('div'); + outer.innerHTML = el; + el = outer.children[0]; + } else { + el = document.createElement(hypenate(el)); + } + } else if (isObject(el)) { + // $FlowFixMe: we have check el's type here and make sure it's an object + option = el; + } + var _option = option, + inner = _option.inner, + penetrate = _option.penetrate, + autoFocus = _option.autoFocus; + var _option2 = option, + className = _option2.className; + + var node = el && isElement(el) ? el : document.createElement('div'); + if (isArray(className)) { + className = className.join(' '); + } + if (isString(className)) { + addClassName(node, className); + } + this.plugins[id] = node; + var outerElement = inner ? this.container : this.wrapper; + var originElement = inner ? this.videoElement : this.container; + if (isBoolean(autoFocus) ? autoFocus : inner) this._autoFocusToVideo(node); + // auto forward the event if this plugin can be penetrate + if (penetrate) { + this.__domEventHandlerList[id] = this.__domEventHandlerList[id] || []; + this._addDomEvents(node, this.__domEventHandlerList[id], function (key) { + return _this4._getEventHandler(key, { penetrate: penetrate }); + }); + this.__videoExtendedNodes.push(node); + } + if (outerElement.lastChild === originElement) { + outerElement.appendChild(node); + return node; + } + outerElement.insertBefore(node, originElement.nextSibling); + return node; + } + + /** + * remove plugin's dom + */ + + }, { + key: 'removePlugin', + value: function removePlugin(id) { + var _this5 = this; + + if (!isString(id)) return; + var dom = this.plugins[id]; + if (isElement(dom)) { + dom.parentNode && dom.parentNode.removeChild(dom); + this._autoFocusToVideo(dom, true); + } + if (!isEmpty(this.__domEventHandlerList[id])) { + domEvents.forEach(function (key, index$$1) { + removeEvent(_this5.plugins[id], key, _this5.__domEventHandlerList[id][index$$1]); + }); + delete this.__domEventHandlerList[id]; + } + delete this.plugins[id]; + } + + /** + * Set zIndex for a plugins list + */ + + }, { + key: 'setPluginsZIndex', + value: function setPluginsZIndex(plugins) { + var _this6 = this; + + // $FlowFixMe: there are videoElment and container here + plugins.forEach(function (key, index$$1) { + return setStyle(key.match(/^(videoElement|container)$/) ? _this6[key] : _this6.plugins[key], 'z-index', ++index$$1); + }); + } + + /** + * set attribute on our dom + * @param {string} attr attribute's name + * @param {anything} val attribute's value + * @param {string} target the HTMLElemnt string name, only support video/wrapper/container now + */ + + }, { + key: 'setAttr', + value: function setAttr$$1(target, attr, val) { + // $FlowFixMe: flow do not support computed property/element on class, which is silly here. + setAttr(this[target], attr, val); + } + }, { + key: 'getAttr', + value: function getAttr$$1(target, attr) { + // $FlowFixMe: flow do not support computed property/element on class, which is silly here. + return getAttr(this[target], attr); + } + }, { + key: 'setStyle', + value: function setStyle$$1(target, attr, val) { + // $FlowFixMe: flow do not support computed property/element on class, which is silly here. + setStyle(this[target], attr, val); + } + }, { + key: 'getStyle', + value: function getStyle$$1(target, attr) { + // $FlowFixMe: flow do not support computed property/element on class, which is silly here. + return getStyle(this[target], attr); + } + }, { + key: 'requestFullscreen', + value: function requestFullscreen(target) { + // $FlowFixMe: flow do not support computed property/element on document, which is silly here. + return index.open(this[target]); + } + }, { + key: 'exitFullscreen', + value: function exitFullscreen() { + return index.exit(); + } + }, { + key: 'fullscreen', + value: function fullscreen() { + 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]; + } + + return request ? this.requestFullscreen.apply(this, [target].concat(_toConsumableArray(args))) : this.exitFullscreen.apply(this, _toConsumableArray(args)); + } + }, { + key: 'focus', + value: function focus() { + this.videoElement.focus(); + } + + /** + * function called when we distory + */ + + }, { + key: 'destroy', + value: function destroy() { + var _this7 = this; + + this.removeVideo(); + domEvents.forEach(function (key, index$$1) { + removeEvent(_this7.container, key, _this7.containerDomEventHandlerList[index$$1]); + removeEvent(_this7.wrapper, key, _this7.wrapperDomEventHandlerList[index$$1]); + }); + index.off('fullscreenchange', this._fullscreenMonitor); + this.wrapper.innerHTML = this.originHTML; + delete this.wrapper; + delete this.plugins; + } + + /** + * bind all dom events on one element + * we will use passive mode if it support + */ + + }, { + key: '_addDomEvents', + value: function _addDomEvents(element, handlerList, handlerGenerate) { + domEvents.forEach(function (key) { + var fn = handlerGenerate(key); + handlerList.push(fn); + if (passiveEvents.indexOf(key) > -1) { + addEvent(element, key, fn, false, { passive: true }); + return; + } + addEvent(element, key, fn); + }); + } + }, { + key: '_autoFocusToVideo', + value: function _autoFocusToVideo(element) { + var remove = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (!isElement(element)) return; + (remove ? removeEvent : addEvent)(element, 'mouseup', this._focusToVideo, false, true); + (remove ? removeEvent : addEvent)(element, 'touchend', this._focusToVideo, false, true); + } + }, { + key: '_focusToVideo', + value: function _focusToVideo() { + var x = window.scrollX; + var y = window.scrollY; + isFunction(this.videoElement.focus) && this.videoElement.focus(); + window.scrollTo(x, y); + } + }, { + key: '_fullscreenMonitor', + value: function _fullscreenMonitor(evt) { + var element = index.fullscreenElement; + var original = this.isFullscreen; + if (!element || !isPosterityNode(this.wrapper, element) && element !== this.wrapper) { + this.isFullscreen = false; + this.fullscreenElement = undefined; + } else { + this.isFullscreen = true; + this.fullscreenElement = this.wrapper === element ? 'wrapper' : this.container === element ? 'container' : this.videoElement === element ? 'video' : element; + } + if (isEvent(evt) && original !== this.isFullscreen) { + this.__dispatcher.bus.triggerSync('fullscreenchange', evt); + } + } + + /** + * get the event handler for dom to bind + */ + + }, { + key: '_getEventHandler', + value: function _getEventHandler(key, _ref2) { + var _this8 = this; + + var penetrate = _ref2.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 = _this8.__dispatcher.bus).triggerSync.apply(_dispatcher$bus4, [key].concat(args)); + }; + } + var insideVideo = function insideVideo(node) { + return _this8.__videoExtendedNodes.indexOf(node) > -1 || _this8.__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 (_this8.__mouseInVideo && type === 'mouseleave' && !insideVideo(to)) { + var _dispatcher$bus5; + + _this8.__mouseInVideo = false; + return (_dispatcher$bus5 = _this8.__dispatcher.bus).triggerSync.apply(_dispatcher$bus5, ['mouseleave'].concat(args)); + } + if (!_this8.__mouseInVideo && type === 'mouseenter' && insideVideo(currentTarget)) { + var _dispatcher$bus6; + + _this8.__mouseInVideo = true; + return (_dispatcher$bus6 = _this8.__dispatcher.bus).triggerSync.apply(_dispatcher$bus6, ['mouseenter'].concat(args)); + } + }; + } + }]); + + return Dom; +}(), _applyDecoratedDescriptor$3(_class$4.prototype, 'setAttr', [_dec$4, _dec2$3], _Object$getOwnPropertyDescriptor(_class$4.prototype, 'setAttr'), _class$4.prototype), _applyDecoratedDescriptor$3(_class$4.prototype, 'getAttr', [_dec3$2], _Object$getOwnPropertyDescriptor(_class$4.prototype, 'getAttr'), _class$4.prototype), _applyDecoratedDescriptor$3(_class$4.prototype, 'setStyle', [_dec4$2], _Object$getOwnPropertyDescriptor(_class$4.prototype, 'setStyle'), _class$4.prototype), _applyDecoratedDescriptor$3(_class$4.prototype, 'getStyle', [_dec5$1$1], _Object$getOwnPropertyDescriptor(_class$4.prototype, 'getStyle'), _class$4.prototype), _applyDecoratedDescriptor$3(_class$4.prototype, 'requestFullscreen', [_dec6$1], _Object$getOwnPropertyDescriptor(_class$4.prototype, 'requestFullscreen'), _class$4.prototype), _applyDecoratedDescriptor$3(_class$4.prototype, '_focusToVideo', [autobind], _Object$getOwnPropertyDescriptor(_class$4.prototype, '_focusToVideo'), _class$4.prototype), _applyDecoratedDescriptor$3(_class$4.prototype, '_fullscreenMonitor', [autobind], _Object$getOwnPropertyDescriptor(_class$4.prototype, '_fullscreenMonitor'), _class$4.prototype), _class$4); + +var defaultContainerConfig = { + width: '100%', + height: '100%', + position: 'relative', + display: 'block' +}; + +// base css controller for container and wrapper + +var Vessel = function Vessel(dispatcher, target, config) { + var _this = this; + + _classCallCheck(this, Vessel); + + this.__dispatcher = dispatcher; + this.__target = target; + ['width', 'height', 'position', 'display'].forEach(function (key) { + _Object$defineProperty(_this, key, { + get: function get$$1() { + return this.__dispatcher.dom.getStyle(this.__target, key); + }, + set: function set(value) { + if (isNumber(value)) { + value = value + 'px'; + } + if (!isString(value)) { + throw new Error('The value of ' + key + ' in ' + this.__target + 'Config must be string, but not ' + (typeof value === 'undefined' ? 'undefined' : _typeof(value)) + '.'); + } + this.__dispatcher.dom.setStyle(this.__target, key, value); + return value; + }, + + configurable: true, + enumerable: true + }); + }); + deepAssign(this, config); +}; + +var _dec$5, _dec2$4, _dec3$3, _dec4$3, _dec5$2, _class$5; + +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; +} +var pluginConfigSet = {}; +var kernelsSet = {}; +function convertNameIntoId(name) { + if (!isString(name)) throw new Error('Plugin\'s name must be a string, but not "' + name + '" in ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name))); + return camelize(name); +} +function checkPluginConfig(config) { + if (isFunction(config)) { + if (!(config.prototype instanceof Plugin)) { + throw new TypeError('Your are trying to install plugin ' + config.name + ', but it\'s not extends from Chimee.plugin.'); + } + return; + } + if (!isObject(config) || isEmpty(config)) throw new TypeError('plugin\'s config must be an Object, but not "' + config + '" in ' + (typeof config === 'undefined' ? 'undefined' : _typeof(config))); + var name = config.name; + + if (!isString(name) || name.length < 1) throw new TypeError('plugin must have a legal namea, but not "' + name + '" in ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name))); +} +/** + *
+ * Dispatcher is the hub of plugins, user, and video kernel.
+ * It take charge of plugins install, use and remove
+ * It also offer a bridge to let user handle video kernel.
+ * 
+ */ +var Dispatcher = (_dec$5 = before(convertNameIntoId), _dec2$4 = before(checkPluginConfig), _dec3$3 = before(convertNameIntoId), _dec4$3 = before(convertNameIntoId), _dec5$2 = before(convertNameIntoId), _class$5 = function () { + /** + * @param {UserConfig} config UserConfig for whole Chimee player + * @param {Chimee} vm referrence of outer class + * @return {Dispatcher} + */ + + /** + * the synchronous ready flag + * @type {boolean} + * @member readySync + */ + + /** + * all plugins instance set + * @type {Object} + * @member plugins + */ + function Dispatcher(config, vm) { + var _this = this; + + _classCallCheck(this, Dispatcher); + + this.plugins = {}; + this.order = []; + this.readySync = false; + this.zIndexMap = { + inner: [], + outer: [] + }; + this.changeWatchable = true; + this.kernelEventHandlerList = []; + + if (!isObject(config)) throw new TypeError('UserConfig must be an Object, but not "' + config + '" in ' + (typeof config === 'undefined' ? 'undefined' : _typeof(config))); + /** + * dom Manager + * @type {Dom} + */ + this.dom = new Dom(config.wrapper, this); + /** + * eventBus + * @type {Bus} + */ + this.bus = new Bus(this); + /** + * Chimee's referrence + * @type {[type]} + */ + this.vm = vm; + /** + * tell user have Chimee installed finished + * @type {Promises} + */ + this.videoConfigReady = false; + // create the videoconfig + this.videoConfig = new VideoConfig(this, config); + // support both plugin and plugins here as people often cofuse both + // $FlowFixMe: we support plugins here, which should be illegal + if (isArray(config.plugins) && !isArray(config.plugin)) { + config.plugin = config.plugins; + delete config.plugins; + } + // use the plugin user want to use + this._initUserPlugin(config.plugin); + // add default config for container + var containerConfig = deepAssign({}, defaultContainerConfig, config.container || {}); + // trigger the init life hook of plugin + this.order.forEach(function (key) { + return _this.plugins[key].__init(_this.videoConfig, containerConfig); + }); + this.videoConfigReady = true; + this.videoConfig.init(); + this.containerConfig = new Vessel(this, 'container', containerConfig); + /** + * video kernel + * @type {Kernel} + */ + this.kernel = this._createKernel(this.dom.videoElement, this.videoConfig); + this._bindKernelEvents(this.kernel); + // trigger auto load event + var asyncInitedTasks = []; + this.order.forEach(function (key) { + var ready = _this.plugins[key].__inited(); + if (isPromise(ready)) { + asyncInitedTasks.push(ready); + } + }); + this.readySync = asyncInitedTasks.length === 0; + // tell them we have inited the whold player + this.ready = this.readySync ? _Promise.resolve() : _Promise.all(asyncInitedTasks).then(function () { + _this.readySync = true; + _this.bus.trigger('ready'); + _this._autoloadVideoSrcAtFirst(); + }); + if (this.readySync) this._autoloadVideoSrcAtFirst(); + } + /** + * use a plugin, which means we will new a plugin instance and include int this Chimee instance + * @param {Object|string} option you can just set a plugin name or plugin config + * @return {Promise} + */ + + // to save the kernel event handler, so that we can remove it when we destroy the kernel + + /** + * the z-index map of the dom, it contain some important infomation + * @type {Object} + * @member zIndexMap + */ + + /** + * plugin's order + * @type {Array} + * @member order + */ + + + _createClass(Dispatcher, [{ + key: 'use', + value: function use(option) { + if (isString(option)) option = { name: option, alias: undefined }; + if (!isObject(option) || isObject(option) && !isString(option.name)) { + throw new TypeError('pluginConfig do not match requirement'); + } + if (!isString(option.alias)) option.alias = undefined; + var _option = option, + name = _option.name, + alias$$1 = _option.alias; + + option.name = alias$$1 || name; + delete option.alias; + var key = camelize(name); + var id = camelize(alias$$1 || name); + var pluginOption = option; + var pluginConfig = Dispatcher.getPluginConfig(key); + if (isEmpty(pluginConfig)) throw new TypeError('You have not installed plugin ' + key); + if (isObject(pluginConfig)) { + pluginConfig.id = id; + } + var plugin = isFunction(pluginConfig) ? new pluginConfig({ id: id }, this, pluginOption) // eslint-disable-line + : new Plugin(pluginConfig, this, pluginOption); + this.plugins[id] = plugin; + _Object$defineProperty(this.vm, id, { + value: plugin, + configurable: true, + enumerable: false, + writable: false + }); + this.order.push(id); + this._sortZIndex(); + if (this.videoConfigReady) plugin.__inited(); + return plugin.ready; + } + /** + * unuse an plugin, we will destroy the plugin instance and exlude it + * @param {string} name plugin's name + */ + + }, { + key: 'unuse', + value: function unuse(id) { + var plugin = this.plugins[id]; + if (!isObject(plugin) || !isFunction(plugin.$destroy)) { + delete this.plugins[id]; + return; + } + plugin.$destroy(); + var orderIndex = this.order.indexOf(id); + if (orderIndex > -1) { + this.order.splice(orderIndex, 1); + } + delete this.plugins[id]; + delete this.vm[id]; + } + }, { + key: 'throwError', + 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$kernels = option.kernels, + kernels = _option$kernels === undefined ? this.videoConfig.kernels : _option$kernels, + _option$preset = option.preset, + preset = _option$preset === undefined ? this.videoConfig.preset : _option$preset; + // all live stream seem as immediate mode + // it's impossible to seek on live stream + + var immediate = option.immediate || isLive; + // form the base config for kernel + // it should be the same as the config now + var config = { isLive: isLive, box: box, src: src, kernels: kernels, preset: preset }; + // build tasks accroding repeat times + var tasks = new Array(repeatTimes + 1).fill(1).map(function (value, index$$1) { + 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$$1; + video.muted = true; + var newVideoReady = false; + var kernel = void 0; + var _videoError = void 0; + var videoCanplay = void 0; + var videoLoadedmetadata = void 0; + // bind time update on old video + // when we bump into the switch point and ready + // we switch + var oldVideoTimeupdate = function oldVideoTimeupdate() { + 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); + removeEvent(video, 'error', _videoError, true); + if (!newVideoReady) { + removeEvent(video, 'canplay', videoCanplay, true); + removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + kernel.destroy(); + return resolve(); + } + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + videoCanplay = function videoCanplay() { + newVideoReady = true; + // you can set it immediately run by yourself + if (immediate) { + removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + removeEvent(video, 'error', _videoError, true); + return reject({ + error: false, + video: video, + kernel: kernel + }); + } + }; + videoLoadedmetadata = function videoLoadedmetadata() { + if (!isLive) kernel.seek(idealTime); + }; + _videoError = function videoError(evt) { + removeEvent(video, 'canplay', videoCanplay, true); + removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + kernel.off('error', _videoError); + var error = void 0; + if (evt.target === kernel) { + var message = evt.data.errmsg; + + Log$1.error("chimee's silentload bump into a kernel error", message); + error = new Error(message); + } else { + error = !isEmpty(video.error) ? new Error(video.error.message) : new Error('unknow video error'); + Log$1.error("chimee's silentload", error.message); + } + kernel.destroy(); + _this2._silentLoadTempKernel = undefined; + return index$$1 === repeatTimes ? reject(error) : resolve(error); + }; + addEvent(video, 'canplay', videoCanplay, true); + addEvent(video, 'loadedmetadata', videoLoadedmetadata, true); + addEvent(video, 'error', _videoError, true); + kernel = _this2._createKernel(video, config); + _this2._silentLoadTempKernel = kernel; + kernel.on('error', _videoError); + addEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); + kernel.load(); + }); + }; + }); + return runRejectableQueue(tasks).then(function () { + var message = 'The silentLoad for ' + src + ' timed out. Please set a longer duration or check your network'; + return _Promise.reject(new Error(message)); + }).catch(function (data) { + if (isError(data)) { + return _Promise.reject(data); + } + if (data.error) { + 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; + if (paused) { + _this2.switchKernel({ video: video, kernel: kernel, config: config }); + return _Promise.resolve(); + } + return new _Promise(function (resolve) { + addEvent(video, 'play', function () { + _this2.switchKernel({ video: video, kernel: kernel, config: config }); + resolve(); + }, true); + video.play(); + }); + }); + } + }, { + key: 'load', + value: function load(srcOrOption) { + var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var src = isString(srcOrOption) ? srcOrOption : isObject(srcOrOption) && isString(srcOrOption.src) ? srcOrOption.src : ''; + if (isObject(srcOrOption)) { + delete srcOrOption.src; + option = srcOrOption; + } + var oldBox = this.kernel.box; + var videoConfig = this.videoConfig; + var _option2 = option, + _option2$isLive = _option2.isLive, + isLive = _option2$isLive === undefined ? videoConfig.isLive : _option2$isLive, + _option2$box = _option2.box, + box = _option2$box === undefined ? videoConfig.box : _option2$box, + _option2$preset = _option2.preset, + preset = _option2$preset === undefined ? videoConfig.preset : _option2$preset, + _option2$kernels = _option2.kernels, + kernels = _option2$kernels === undefined ? videoConfig.kernels : _option2$kernels; + + if (box !== 'native' || box !== oldBox || !isEmpty(option)) { + var video = document.createElement('video'); + var config = { isLive: isLive, box: box, preset: preset, src: src, kernels: kernels }; + var kernel = this._createKernel(video, config); + this.switchKernel({ video: video, kernel: kernel, config: config }); + } + var originAutoLoad = this.videoConfig.autoload; + this._changeUnwatchable(this.videoConfig, 'autoload', false); + this.videoConfig.src = src || this.videoConfig.src; + this.kernel.load(this.videoConfig.src); + this._changeUnwatchable(this.videoConfig, 'autoload', originAutoLoad); + } + }, { + key: 'switchKernel', + value: function switchKernel(_ref) { + var _this3 = this; + + var video = _ref.video, + kernel = _ref.kernel, + config = _ref.config; + + var oldKernel = this.kernel; + var originVideoConfig = deepClone(this.videoConfig); + this.dom.removeVideo(); + this.dom.installVideo(video, { bindEvent: false }); + // as we will reset the currentVideoConfig on the new video + // it will trigger the watch function as they maybe differnet + // because video config will return the real situation + // 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; + this._bindKernelEvents(oldKernel, true); + this._bindKernelEvents(kernel); + this.kernel = kernel; + this._silentLoadTempKernel = undefined; + var isLive = config.isLive, + box = config.box, + preset = config.preset, + kernels = config.kernels; + + _Object$assign(this.videoConfig, { isLive: isLive, box: box, preset: preset, kernels: kernels }); + // const config = {} + oldKernel.destroy(); + // delay video event binding + // so that people can't feel the default value change + setTimeout(function () { + return _this3.dom.bindVideoEvents(video); + }); + } + /** + * destroy function called when dispatcher destroyed + */ + + }, { + key: 'destroy', + value: function destroy() { + for (var _key in this.plugins) { + this.unuse(_key); + } + this.bus.destroy(); + delete this.bus; + this.dom.destroy(); + delete this.dom; + this._bindKernelEvents(this.kernel, true); + this.kernel.destroy(); + delete this.kernel; + delete this.vm; + delete this.plugins; + delete this.order; + } + /** + * use a set of plugin + * @param {Array} configs a set of plugin config + * @return {Array} a set of Promise indicate the plugin install stage + */ + + }, { + key: '_initUserPlugin', + value: function _initUserPlugin() { + var _this4 = this; + + var configs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if (!isArray(configs)) { + configs = []; + } + return configs.map(function (config) { + return _this4.use(config); + }); + } + /** + * sort zIndex of plugins to make plugin display in order + */ + + }, { + key: '_sortZIndex', + value: function _sortZIndex() { + var _this5 = this; + + var _order$reduce = this.order.reduce(function (levelSet, key) { + var plugin = _this5.plugins[key]; + if (isEmpty(plugin)) return levelSet; + var set = levelSet[plugin.$inner ? 'inner' : 'outer']; + var level = plugin.$level; + set[level] = set[level] || []; + set[level].push(key); + return levelSet; + }, { inner: {}, outer: {} }), + inner = _order$reduce.inner, + outer = _order$reduce.outer; + + inner[0] = inner[0] || []; + inner[0].unshift('videoElement'); + outer[0] = outer[0] || []; + outer[0].unshift('container'); + var innerOrderArr = transObjectAttrIntoArray(inner); + var outerOrderArr = transObjectAttrIntoArray(outer); + this.dom.setPluginsZIndex(innerOrderArr); + this.dom.setPluginsZIndex(outerOrderArr); + this.zIndexMap.inner = innerOrderArr; + this.zIndexMap.outer = outerOrderArr; + } + /** + * get the top element's level + * @param {boolean} inner get the inner array or the outer array + */ + + }, { + key: '_getTopLevel', + value: function _getTopLevel(inner) { + var arr = this.zIndexMap[inner ? 'inner' : 'outer']; + var plugin = this.plugins[arr[arr.length - 1]]; + return isEmpty(plugin) ? 0 : plugin.$level; + } + }, { + key: '_autoloadVideoSrcAtFirst', + value: function _autoloadVideoSrcAtFirst() { + if (this.videoConfig.autoload) { + if ("production" !== 'prodution' && !this.videoConfig.src) { + Log$1.warn('You have not set the src, so you better set autoload to be false. Accroding to https://github.com/Chimeejs/chimee/blob/master/doc/zh-cn/chimee-api.md#src.'); + return; + } + this.bus.emit('load', this.videoConfig.src); + } + } + }, { + key: '_changeUnwatchable', + value: function _changeUnwatchable(object, property, value) { + this.changeWatchable = false; + object[property] = value; + this.changeWatchable = true; + } + }, { + key: '_createKernel', + value: function _createKernel(video, config) { + var kernels = config.kernels, + preset = config.preset; + var presetConfig = {}; + var newPreset = {}; + if (isArray(kernels)) { + // SKC means SingleKernelConfig + newPreset = kernels.reduce(function (kernels, keyOrSKC) { + // if it is a string key, it means the kernel has been pre installed. + if (isString(keyOrSKC)) { + var kernelFn = kernelsSet[keyOrSKC]; + if (!isFunction(kernelFn)) { + Log$1.warn('You have not installed kernel for ' + keyOrSKC + '.'); + return kernels; + } + kernels[keyOrSKC] = kernelFn; + return kernels; + } + // if it is a SingleKernelConfig, it means user may pass in some config here + // so we need to extract the handler + // get the name of the handler + // and collect the config for the handler + if (isObject(keyOrSKC)) { + var name = keyOrSKC.name, + handler = keyOrSKC.handler; + // if the handler is a pure string, it means the kernel has been pre installed + + if (isString(handler)) { + var _kernelFn = kernelsSet[handler]; + if (!isFunction(_kernelFn)) { + Log$1.warn('You have not installed kernel for ' + handler + '.'); + return kernels; + } + kernels[handler] = _kernelFn; + presetConfig[handler] = keyOrSKC; + return kernels; + } + // if the handler is a function, it means that the user pass in the kernel directly + // if the provide name, we use it as kernel name + // if they do not provide name, we just use the function's name + if (isFunction(handler)) { + var kernelName = name || handler.name; + kernels[kernelName] = handler; + presetConfig[kernelName] = keyOrSKC; + return kernels; + } + Log$1.warn('When you pass in an SingleKernelConfig in Array, you must clarify it\'s handler, we only support handler in string or function but not ' + (typeof handler === 'undefined' ? 'undefined' : _typeof(handler))); + return kernels; + } + Log$1.warn('If you pass in kernels as array, you must pass in kernels in string or function, but not ' + (typeof keyOrSKC === 'undefined' ? 'undefined' : _typeof(keyOrSKC))); + return kernels; + }, {}); + } + + if (isObject(kernels)) { + // SKC means SingleKernelConfig + _Object$entries(kernels).forEach(function (_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), + key = _ref3[0], + fnOrSKC = _ref3[1]; + + // if it's a function, means we need to do nothing + if (isFunction(fnOrSKC)) { + newPreset[key] = fnOrSKC; + return; + } + if (isObject(fnOrSKC)) { + var handler = fnOrSKC.handler; + // if handler is an string, it means user has pre install it + + if (isString(handler)) { + var kernelFn = kernelsSet[handler]; + if (!isFunction(kernelFn)) { + Log$1.warn('You have not installed kernel for ' + handler + '.'); + return; + } + newPreset[key] = kernelFn; + presetConfig[key] = fnOrSKC; + return; + } + if (isFunction(handler)) { + newPreset[key] = handler; + presetConfig[key] = fnOrSKC; + return; + } + Log$1.warn('When you pass in an SingleKernelConfig in Object, you must clarify it\'s handler, we only support handler in string or function but not ' + (typeof handler === 'undefined' ? 'undefined' : _typeof(handler))); + return; + } + Log$1.warn('If you pass in kernels as object, you must pass in kernels in string or function, but not ' + (typeof fnOrSKC === 'undefined' ? 'undefined' : _typeof(fnOrSKC))); + return kernels; + }); + } + config.preset = _Object$assign(newPreset, preset); + config.presetConfig = presetConfig; + var kernel = new ChimeeKernel(video, config); + return kernel; + } + }, { + key: '_bindKernelEvents', + value: function _bindKernelEvents(kernel) { + var _this6 = this; + + var remove = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + kernelEvents$1.forEach(function (key, index$$1) { + if (!remove) { + var _fn = function _fn() { + var _bus; + + for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { + args[_key2] = arguments[_key2]; + } + + return (_bus = _this6.bus).triggerSync.apply(_bus, [key].concat(_toConsumableArray(args))); + }; + kernel.on(key, _fn); + _this6.kernelEventHandlerList.push(_fn); + return; + } + var fn = _this6.kernelEventHandlerList[index$$1]; + kernel.off(key, fn); + }); + if (remove) { + this.kernelEventHandlerList = []; + kernel.off('error', this.throwError); + } else { + kernel.on('error', this.throwError); + } + } + /** + * static method to install plugin + * we will store the plugin config + * @type {string} plugin's id + */ + + }], [{ + key: 'install', + value: function install(config) { + var name = config.name; + + var id = camelize(name); + if (!isEmpty(pluginConfigSet[id])) { + } + var pluginConfig = isFunction(config) ? config : deepAssign({ id: id }, config); + pluginConfigSet[id] = pluginConfig; + return id; + } + }, { + key: 'hasInstalled', + value: function hasInstalled(id) { + return !isEmpty(pluginConfigSet[id]); + } + }, { + key: 'uninstall', + value: function uninstall(id) { + delete pluginConfigSet[id]; + } + /** + * get Plugin config based on plugin's id + * @type {[type]} + */ + + }, { + key: 'getPluginConfig', + value: function getPluginConfig(id) { + return pluginConfigSet[id]; + } + }, { + key: 'installKernel', + value: function installKernel(key, value) { + var tasks = isObject(key) ? _Object$entries(key) : [[key, value]]; + tasks.forEach(function (_ref4) { + var _ref5 = _slicedToArray(_ref4, 2), + key = _ref5[0], + value = _ref5[1]; + + if (!isFunction(value)) throw new Error('The kernel you install on ' + key + ' must be a Function, but not ' + (typeof value === 'undefined' ? 'undefined' : _typeof(value))); + if (isFunction(kernelsSet[key])) Log$1.warn('You have alrady install a kernel on ' + key + ', and now we will replace it'); + kernelsSet[key] = value; + }); + } + + // only use for debug in internal + + }, { + key: 'uninstallKernel', + value: function uninstallKernel(key) { + delete kernelsSet[key]; + } + }, { + key: 'hasInstalledKernel', + value: function hasInstalledKernel(key) { + return isFunction(kernelsSet[key]); + } + }]); + + return Dispatcher; +}(), _applyDecoratedDescriptor$4(_class$5.prototype, 'unuse', [_dec$5], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'unuse'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5.prototype, 'throwError', [autobind], _Object$getOwnPropertyDescriptor(_class$5.prototype, 'throwError'), _class$5.prototype), _applyDecoratedDescriptor$4(_class$5, 'install', [_dec2$4], _Object$getOwnPropertyDescriptor(_class$5, 'install'), _class$5), _applyDecoratedDescriptor$4(_class$5, 'hasInstalled', [_dec3$3], _Object$getOwnPropertyDescriptor(_class$5, 'hasInstalled'), _class$5), _applyDecoratedDescriptor$4(_class$5, 'uninstall', [_dec4$3], _Object$getOwnPropertyDescriptor(_class$5, 'uninstall'), _class$5), _applyDecoratedDescriptor$4(_class$5, 'getPluginConfig', [_dec5$2], _Object$getOwnPropertyDescriptor(_class$5, 'getPluginConfig'), _class$5), _class$5); + +var _class$6, _descriptor$1; + +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$5(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; +} +var GlobalConfig = (_class$6 = function () { + _createClass(GlobalConfig, [{ + key: 'silent', + get: function get$$1() { + return this._silent; + }, + set: function set(val) { + var _this = this; + + val = !!val; + this._silent = val; + _Object$keys(this.log).forEach(function (key) { + _this.log[key] = !val; + }); + } + }]); + + function GlobalConfig() { + _classCallCheck(this, GlobalConfig); + + this.log = { + error: true, + info: true, + warn: true, + debug: true, + verbose: true + }; + + _initDefineProp$1(this, '_silent', _descriptor$1, this); + + this.errorHandler = undefined; + + var props = _Object$keys(this.log).reduce(function (props, key) { + props[key] = accessor({ + get: function get$$1() { + // $FlowFixMe: we have check the keys + return Log$1['ENABLE_' + key.toUpperCase()]; + }, + set: function set(val) { + // $FlowFixMe: we have check the keys + Log$1['ENABLE_' + key.toUpperCase()] = val; + if (val === true) this.silent = false; + return val; + } + }); + return props; + }, {}); + applyDecorators(this.log, props, { self: true }); + } + + return GlobalConfig; +}(), _descriptor$1 = _applyDecoratedDescriptor$5(_class$6.prototype, '_silent', [nonenumerable], { + enumerable: true, + initializer: function initializer() { + return false; + } +}), _class$6); + +var _dec$6, _class$7, _class2$1$1, _descriptor$2, _descriptor2$1, _descriptor3$1, _init, _init2, _init3, _init4, _init5, _init6, _init7, _init8, _init9, _class3, _temp; + +function _initDefineProp$2(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$6(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; +} + +var Chimee = (_dec$6 = autobindClass(), _dec$6(_class$7 = (_class2$1$1 = (_temp = _class3 = function (_VideoWrapper) { + _inherits(Chimee, _VideoWrapper); + + function Chimee(config) { + _classCallCheck(this, Chimee); + + /* istanbul ignore if */ + var _this = _possibleConstructorReturn(this, (Chimee.__proto__ || _Object$getPrototypeOf(Chimee)).call(this)); + + _this.destroyed = false; + + _initDefineProp$2(_this, '__id', _descriptor$2, _this); + + _initDefineProp$2(_this, 'version', _descriptor2$1, _this); + + _initDefineProp$2(_this, 'config', _descriptor3$1, _this); + if (isString(config) || isElement(config)) { + config = { + wrapper: config, + controls: true + }; + } else if (isObject(config)) { + if (!config.wrapper) throw new Error('You must pass in an legal object'); + } else { + throw new Error('You must pass in an Object containing wrapper or string or element to new a Chimee'); + } + // $FlowFixMe: we have check wrapper here + _this.__dispatcher = new Dispatcher(config, _this); + _this.ready = _this.__dispatcher.ready; + _this.readySync = _this.__dispatcher.readySync; + _this.__wrapAsVideo(_this.__dispatcher.videoConfig); + return _this; + } + + _createClass(Chimee, [{ + key: 'destroy', + value: function destroy() { + _get(Chimee.prototype.__proto__ || _Object$getPrototypeOf(Chimee.prototype), '__destroy', this).call(this); + this.__dispatcher.destroy(); + // $FlowFixMe: normal obejct define + Object.defineProperty(this, '__dispatcher', { + get: function get$$1() { + throw new Error('This instance has been destroyed.'); + }, + + enumerable: true, + configurable: true + }); + this.destroyed = true; + } + }, { + key: 'use', + value: function use(option) { + this.__dispatcher.use(option); + } + }, { + key: 'unuse', + value: function unuse(name) { + this.__dispatcher.unuse(name); + } + }, { + key: '__throwError', + value: function __throwError(error) { + if (isString(error)) error = new Error(error); + var errorHandler = this.config.errorHandler || Chimee.config.errorHandler; + if (isFunction(errorHandler)) return errorHandler(error); + if (Chimee.config.silent) return; + throw error; + } + }]); + + return Chimee; +}(VideoWrapper), _class3.plugin = Plugin, _class3.config = new GlobalConfig(), _class3.install = Dispatcher.install, _class3.uninstall = Dispatcher.uninstall, _class3.hasInstalled = Dispatcher.hasInstalled, _class3.installKernel = Dispatcher.installKernel, _class3.uninstallKernel = Dispatcher.uninstallKernel, _class3.hasInstalledKernel = Dispatcher.hasInstalledKernel, _class3.getPluginConfig = Dispatcher.getPluginConfig, _temp), _descriptor$2 = _applyDecoratedDescriptor$6(_class2$1$1.prototype, '__id', [frozen], { + enumerable: true, + initializer: function initializer() { + return '_vm'; + } +}), _descriptor2$1 = _applyDecoratedDescriptor$6(_class2$1$1.prototype, 'version', [frozen], { + enumerable: true, + initializer: function initializer() { + return '0.9.3'; + } +}), _descriptor3$1 = _applyDecoratedDescriptor$6(_class2$1$1.prototype, 'config', [frozen], { + enumerable: true, + initializer: function initializer() { + return { + errorHandler: undefined + }; + } +}), _applyDecoratedDescriptor$6(_class2$1$1, 'plugin', [frozen], (_init = _Object$getOwnPropertyDescriptor(_class2$1$1, 'plugin'), _init = _init ? _init.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'config', [frozen], (_init2 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'config'), _init2 = _init2 ? _init2.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init2; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'install', [frozen], (_init3 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'install'), _init3 = _init3 ? _init3.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init3; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'uninstall', [frozen], (_init4 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'uninstall'), _init4 = _init4 ? _init4.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init4; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'hasInstalled', [frozen], (_init5 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'hasInstalled'), _init5 = _init5 ? _init5.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init5; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'installKernel', [frozen], (_init6 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'installKernel'), _init6 = _init6 ? _init6.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init6; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'uninstallKernel', [frozen], (_init7 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'uninstallKernel'), _init7 = _init7 ? _init7.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init7; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'hasInstalledKernel', [frozen], (_init8 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'hasInstalledKernel'), _init8 = _init8 ? _init8.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init8; + } +}), _class2$1$1), _applyDecoratedDescriptor$6(_class2$1$1, 'getPluginConfig', [frozen], (_init9 = _Object$getOwnPropertyDescriptor(_class2$1$1, 'getPluginConfig'), _init9 = _init9 ? _init9.value : undefined, { + enumerable: true, + configurable: true, + writable: true, + initializer: function initializer() { + return _init9; + } +}), _class2$1$1), _class2$1$1)) || _class$7); + +/** + * chimee-plugin-controlbar v0.3.9 + * (c) 2017 yandeqiang + * Released under ISC + */ + +function __$styleInject(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject("container{position:relative}container,video{display:block;width:100%;height:100%;background:#000;outline:none}video:focus{outline:none}.chimee-flex-component svg:hover g,.chimee-flex-component svg g{fill:#fff;stroke:#fff}chimee-clarity-list,chimee-control-state-pause,chimee-control-state-play,chimee-progressbar-tip,chimee-screen-full,chimee-screen-small,chimee-volume-state-high,chimee-volume-state-low,chimee-volume-state-mute{display:none}chimee-control.full chimee-screen-full,chimee-control.pause chimee-control-state-pause,chimee-control.play chimee-control-state-play,chimee-control.small chimee-screen-small,chimee-volume.high chimee-volume-state-high,chimee-volume.low chimee-volume-state-low,chimee-volume.mute chimee-volume-state-mute{display:inline-block;width:1.4em;height:100%}chimee-control{display:block;height:100%;line-height:2em;font-size:14px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden;font-family:Roboto,Arial,Helvetica,sans-serif;-webkit-transition:visibility .5s ease;transition:visibility .5s ease}chimee-control,chimee-control-wrap{position:absolute;bottom:0;left:0;width:100%}chimee-control-wrap{height:2.2em;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start;background:rgba(0,0,0,.5);-webkit-transition:bottom .5s ease;transition:bottom .5s ease;pointer-events:auto}.chimee-flex-component{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1;-webkit-box-flex:0;-ms-flex-positive:0;flex-grow:0;height:2em;cursor:pointer}.chimee-flex-component svg{vertical-align:middle;width:2em;height:1.5em}chimee-control-state.chimee-flex-component{-ms-flex-preferred-size:3em;flex-basis:3em;text-align:right;margin-right:1em}chimee-control-state .left,chimee-control-state .right{-webkit-transition:d .2s ease-in-out;transition:d .2s ease-in-out}chimee-progresstime.chimee-flex-component{color:#fff;font-weight:400;text-align:center;white-space:nowrap}chimee-progresstime-pass,chimee-progresstime-total{display:inline}chimee-progressbar.chimee-flex-component{position:relative;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1}chimee-progressbar-wrap{display:inline-block;height:100%;position:absolute;left:1em;right:1em;top:0}chimee-progressbar.progressbar-layout-top{position:static}chimee-progressbar.progressbar-layout-top chimee-progressbar-wrap{top:-1.6em;height:1.6em;left:0;right:0}chimee-progressbar.progressbar-layout-top .chimee-progressbar-line{left:0;top:.8em}.chimee-progressbar-line{position:absolute;top:.9em;left:0;display:inline-block;height:3px}chimee-progressbar-bg{width:100%;background:#4c4c4c}chimee-progressbar-buffer{width:0;background:#6f6f6f}chimee-progressbar-all{background:#de698c}chimee-progressbar-ball{content:\"\";position:absolute;right:-.8em;top:-.3em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-progressbar-tip{position:absolute;bottom:.5em;top:-1.5em;left:0;z-index:1;padding:0 .5em;height:1.5em;background:#fff;line-height:1.5em;border-radius:4px;color:#000;text-align:center}chimee-volume.chimee-flex-component{cursor:pointer;padding:0;-ms-flex-preferred-size:7em;flex-basis:7em;white-space:nowrap;margin-right:1em;position:relative}chimee-volume.chimee-flex-component.vertical{padding-right:1em;-ms-flex-preferred-size:2em;flex-basis:2em}chimee-volume-state{display:inline-block;width:2em;vertical-align:top}chimee-volume .line,chimee-volume .ring1,chimee-volume .ring2{stroke-dasharray:150;stroke-dashoffset:150;-webkit-transition:stroke-dashoffset .7s ease-in-out;transition:stroke-dashoffset .7s ease-in-out}chimee-volume.high .ring1,chimee-volume.high .ring2,chimee-volume.low .ring2,chimee-volume.mute .line,chimee-volume.mute .ring1,chimee-volume.mute .ring2{stroke-dashoffset:0}chimee-volume.vertical:hover chimee-volume-bar{display:inline-block}chimee-volume.vertical chimee-volume-bar{position:absolute;top:-7em;left:-.2em;width:2em;height:4em;padding-bottom:3em;display:none;vertical-align:middle}chimee-volume.vertical chimee-volume-bar:before{content:\"\";position:absolute;left:0;right:0;top:0;bottom:1em;background:#212121;border-radius:4px}chimee-volume.vertical chimee-volume-bar-wrap{display:inline-block;position:absolute;bottom:1em;left:0;top:1em;right:0;height:4em}chimee-volume.vertical chimee-volume-bar-all,chimee-volume.vertical chimee-volume-bar-bg{position:absolute;bottom:0;left:1em;display:inline-block;width:2px;border-radius:4px}chimee-volume.vertical chimee-volume-bar-bg{height:4em;background:#4c4c4c;opacity:.5}chimee-volume.vertical chimee-volume-bar-all{background:#de698c}chimee-volume.vertical chimee-volume-bar-all:after{content:\"\";position:absolute;right:-.34em;top:-.4em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-volume.horizonal chimee-volume-bar{position:relative;height:1.2em;width:4em;display:inline-block;vertical-align:middle}chimee-volume.horizonal chimee-volume-bar-all,chimee-volume.horizonal chimee-volume-bar-bg{position:absolute;top:.4em;left:0;display:inline-block;height:2px}chimee-volume.horizonal chimee-volume-bar-bg{width:4em;background:#4c4c4c;opacity:.5}chimee-volume.horizonal chimee-volume-bar-all{background:#de698c}chimee-volume.horizonal chimee-volume-bar-all:after{content:\"\";position:absolute;right:-.4em;top:-.3em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-screen.chimee-flex-component{-ms-flex-preferred-size:3em;flex-basis:3em;text-align:left}chimee-clarity.chimee-flex-component{position:relative;color:#fff;width:6em;height:1.75em;padding:0;padding-right:1em;padding-left:1em;text-align:center;vertical-align:middle;font-size:16px}chimee-clarity.chimee-flex-component:hover chimee-clarity-list{display:inline-block}chimee-clarity.chimee-flex-component svg{width:auto;height:auto}chimee-clarity-list{position:absolute;left:0;bottom:1em;width:100%;padding-bottom:1.5em;opacity:.8;-webkit-box-sizing:content-box;box-sizing:content-box;line-height:0}chimee-clarity-list ul{margin:0;padding:.5em 0;background:#292929;line-height:2em}chimee-clarity-list li{list-style-type:none}chimee-clarity-list li.active,chimee-clarity-list li:hover{color:#de698c}chimee-clarity-list-arrow{position:absolute;bottom:1.5em;width:100%}", undefined); + +function unwrapExports$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule$1(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +// 7.2.1 RequireObjectCoercible(argument) +var _defined$1 = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +// 7.1.13 ToObject(argument) + +var _toObject$1 = function (it) { + return Object(_defined$1(it)); +}; + +var hasOwnProperty$2 = {}.hasOwnProperty; +var _has$2 = function (it, key) { + return hasOwnProperty$2.call(it, key); +}; + +var toString$2 = {}.toString; + +var _cof$1 = function (it) { + return toString$2.call(it).slice(8, -1); +}; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings + +// eslint-disable-next-line no-prototype-builtins +var _iobject$1 = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return _cof$1(it) == 'String' ? it.split('') : Object(it); +}; + +// to indexed object, toObject with fallback for non-array-like ES3 strings + + +var _toIobject$1 = function (it) { + return _iobject$1(_defined$1(it)); +}; + +// 7.1.4 ToInteger +var ceil$1 = Math.ceil; +var floor$2 = Math.floor; +var _toInteger$1 = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor$2 : ceil$1)(it); +}; + +// 7.1.15 ToLength + +var min$2 = Math.min; +var _toLength$1 = function (it) { + return it > 0 ? min$2(_toInteger$1(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +var max$1 = Math.max; +var min$1$1 = Math.min; +var _toAbsoluteIndex$1 = function (index, length) { + index = _toInteger$1(index); + return index < 0 ? max$1(index + length, 0) : min$1$1(index, length); +}; + +// false -> Array#indexOf +// true -> Array#includes + + + +var _arrayIncludes$1 = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = _toIobject$1($this); + var length = _toLength$1(O.length); + var index = _toAbsoluteIndex$1(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +var _global$2 = createCommonjsModule$1(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef +}); + +var SHARED$1 = '__core-js_shared__'; +var store$1 = _global$2[SHARED$1] || (_global$2[SHARED$1] = {}); +var _shared$1 = function (key) { + return store$1[key] || (store$1[key] = {}); +}; + +var id$3 = 0; +var px$2 = Math.random(); +var _uid$2 = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id$3 + px$2).toString(36)); +}; + +var shared$1 = _shared$1('keys'); + +var _sharedKey$1 = function (key) { + return shared$1[key] || (shared$1[key] = _uid$2(key)); +}; + +var arrayIndexOf$1 = _arrayIncludes$1(false); +var IE_PROTO$3 = _sharedKey$1('IE_PROTO'); + +var _objectKeysInternal$1 = function (object, names) { + var O = _toIobject$1(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO$3) _has$2(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (_has$2(O, key = names[i++])) { + ~arrayIndexOf$1(result, key) || result.push(key); + } + return result; +}; + +// IE 8- don't enum bug keys +var _enumBugKeys$1 = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) + + + +var _objectKeys$1 = Object.keys || function keys(O) { + return _objectKeysInternal$1(O, _enumBugKeys$1); +}; + +var _core$2 = createCommonjsModule$1(function (module) { +var core = module.exports = { version: '2.5.1' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef +}); + +var _aFunction$2 = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx$2 = function (fn, that, length) { + _aFunction$2(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +var _isObject$2 = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject$2 = function (it) { + if (!_isObject$2(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails$2 = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors$2 = !_fails$2(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +var document$1$1 = _global$2.document; +// typeof document.createElement is 'object' in old IE +var is$2 = _isObject$2(document$1$1) && _isObject$2(document$1$1.createElement); +var _domCreate$2 = function (it) { + return is$2 ? document$1$1.createElement(it) : {}; +}; + +var _ie8DomDefine$2 = !_descriptors$2 && !_fails$2(function () { + return Object.defineProperty(_domCreate$2('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive$2 = function (it, S) { + if (!_isObject$2(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject$2(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !_isObject$2(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !_isObject$2(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP$5 = Object.defineProperty; + +var f$9 = _descriptors$2 ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject$2(O); + P = _toPrimitive$2(P, true); + _anObject$2(Attributes); + if (_ie8DomDefine$2) try { + return dP$5(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +var _objectDp$2 = { + f: f$9 +}; + +var _propertyDesc$2 = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +var _hide$2 = _descriptors$2 ? function (object, key, value) { + return _objectDp$2.f(object, key, _propertyDesc$2(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +var PROTOTYPE$4 = 'prototype'; + +var $export$2 = function (type, name, source) { + var IS_FORCED = type & $export$2.F; + var IS_GLOBAL = type & $export$2.G; + var IS_STATIC = type & $export$2.S; + var IS_PROTO = type & $export$2.P; + var IS_BIND = type & $export$2.B; + var IS_WRAP = type & $export$2.W; + var exports = IS_GLOBAL ? _core$2 : _core$2[name] || (_core$2[name] = {}); + var expProto = exports[PROTOTYPE$4]; + var target = IS_GLOBAL ? _global$2 : IS_STATIC ? _global$2[name] : (_global$2[name] || {})[PROTOTYPE$4]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? _ctx$2(out, _global$2) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE$4] = C[PROTOTYPE$4]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? _ctx$2(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export$2.R && expProto && !expProto[key]) _hide$2(expProto, key, out); + } + } +}; +// type bitmap +$export$2.F = 1; // forced +$export$2.G = 2; // global +$export$2.S = 4; // static +$export$2.P = 8; // proto +$export$2.B = 16; // bind +$export$2.W = 32; // wrap +$export$2.U = 64; // safe +$export$2.R = 128; // real proto method for `library` +var _export$2 = $export$2; + +// most Object methods by ES6 should accept primitives + + + +var _objectSap$1 = function (KEY, exec) { + var fn = (_core$2.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + _export$2(_export$2.S + _export$2.F * _fails$2(function () { fn(1); }), 'Object', exp); +}; + +// 19.1.2.14 Object.keys(O) + + + +_objectSap$1('keys', function () { + return function keys(it) { + return _objectKeys$1(_toObject$1(it)); + }; +}); + +var keys$1$1 = _core$2.Object.keys; + +var keys$2 = createCommonjsModule$1(function (module) { +module.exports = { "default": keys$1$1, __esModule: true }; +}); + +var _Object$keys$1 = unwrapExports$1(keys$2); + +// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + + +var IE_PROTO$1$1 = _sharedKey$1('IE_PROTO'); +var ObjectProto$2 = Object.prototype; + +var _objectGpo$1 = Object.getPrototypeOf || function (O) { + O = _toObject$1(O); + if (_has$2(O, IE_PROTO$1$1)) return O[IE_PROTO$1$1]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto$2 : null; +}; + +// 19.1.2.9 Object.getPrototypeOf(O) + + + +_objectSap$1('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return _objectGpo$1(_toObject$1(it)); + }; +}); + +var getPrototypeOf$1$1 = _core$2.Object.getPrototypeOf; + +var getPrototypeOf$2 = createCommonjsModule$1(function (module) { +module.exports = { "default": getPrototypeOf$1$1, __esModule: true }; +}); + +var _Object$getPrototypeOf$1 = unwrapExports$1(getPrototypeOf$2); + +var classCallCheck$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; +}); + +var _classCallCheck$1 = unwrapExports$1(classCallCheck$1); + +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +_export$2(_export$2.S + _export$2.F * !_descriptors$2, 'Object', { defineProperty: _objectDp$2.f }); + +var $Object$4 = _core$2.Object; +var defineProperty$2$2 = function defineProperty(it, key, desc) { + return $Object$4.defineProperty(it, key, desc); +}; + +var defineProperty$7 = createCommonjsModule$1(function (module) { +module.exports = { "default": defineProperty$2$2, __esModule: true }; +}); + +unwrapExports$1(defineProperty$7); + +var createClass$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty$7); + +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$1 = unwrapExports$1(createClass$1); + +// true -> String#at +// false -> String#codePointAt +var _stringAt$1 = function (TO_STRING) { + return function (that, pos) { + var s = String(_defined$1(that)); + var i = _toInteger$1(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +var _library$1 = true; + +var _redefine$2 = _hide$2; + +var _iterators$1 = {}; + +var _objectDps$1 = _descriptors$2 ? Object.defineProperties : function defineProperties(O, Properties) { + _anObject$2(O); + var keys = _objectKeys$1(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) _objectDp$2.f(O, P = keys[i++], Properties[P]); + return O; +}; + +var document$2$1 = _global$2.document; +var _html$1 = document$2$1 && document$2$1.documentElement; + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + + + +var IE_PROTO$2$1 = _sharedKey$1('IE_PROTO'); +var Empty$1 = function () { /* empty */ }; +var PROTOTYPE$1$1 = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict$1 = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = _domCreate$2('iframe'); + var i = _enumBugKeys$1.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + _html$1.appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict$1 = iframeDocument.F; + while (i--) delete createDict$1[PROTOTYPE$1$1][_enumBugKeys$1[i]]; + return createDict$1(); +}; + +var _objectCreate$1 = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty$1[PROTOTYPE$1$1] = _anObject$2(O); + result = new Empty$1(); + Empty$1[PROTOTYPE$1$1] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO$2$1] = O; + } else result = createDict$1(); + return Properties === undefined ? result : _objectDps$1(result, Properties); +}; + +var _wks$1 = createCommonjsModule$1(function (module) { +var store = _shared$1('wks'); + +var Symbol = _global$2.Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid$2)('Symbol.' + name)); +}; + +$exports.store = store; +}); + +var def$1 = _objectDp$2.f; + +var TAG$2 = _wks$1('toStringTag'); + +var _setToStringTag$1 = function (it, tag, stat) { + if (it && !_has$2(it = stat ? it : it.prototype, TAG$2)) def$1(it, TAG$2, { configurable: true, value: tag }); +}; + + + +var IteratorPrototype$1 = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_hide$2(IteratorPrototype$1, _wks$1('iterator'), function () { return this; }); + +var _iterCreate$1 = function (Constructor, NAME, next) { + Constructor.prototype = _objectCreate$1(IteratorPrototype$1, { next: _propertyDesc$2(1, next) }); + _setToStringTag$1(Constructor, NAME + ' Iterator'); +}; + + + + + + + + + +var ITERATOR$5 = _wks$1('iterator'); +var BUGGY$1 = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR$1 = '@@iterator'; +var KEYS$1 = 'keys'; +var VALUES$1 = 'values'; + +var returnThis$1 = function () { return this; }; + +var _iterDefine$1 = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + _iterCreate$1(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY$1 && kind in proto) return proto[kind]; + switch (kind) { + case KEYS$1: return function keys() { return new Constructor(this, kind); }; + case VALUES$1: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES$1; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR$5] || proto[FF_ITERATOR$1] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = _objectGpo$1($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + _setToStringTag$1(IteratorPrototype, TAG, true); + // fix for some old engines + if (!_library$1 && !_has$2(IteratorPrototype, ITERATOR$5)) _hide$2(IteratorPrototype, ITERATOR$5, returnThis$1); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES$1) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!_library$1 || FORCED) && (BUGGY$1 || VALUES_BUG || !proto[ITERATOR$5])) { + _hide$2(proto, ITERATOR$5, $default); + } + // Plug for library + _iterators$1[NAME] = $default; + _iterators$1[TAG] = returnThis$1; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES$1), + keys: IS_SET ? $default : getMethod(KEYS$1), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) _redefine$2(proto, key, methods[key]); + } else _export$2(_export$2.P + _export$2.F * (BUGGY$1 || VALUES_BUG), NAME, methods); + } + return methods; +}; +var $at$1 = _stringAt$1(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_iterDefine$1(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at$1(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +var _iterStep$1 = 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$1 = _iterDefine$1(Array, 'Array', function (iterated, kind) { + this._t = _toIobject$1(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return _iterStep$1(1); + } + if (kind == 'keys') return _iterStep$1(0, index); + if (kind == 'values') return _iterStep$1(0, O[index]); + return _iterStep$1(0, [index, O[index]]); +}, 'values'); + +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +_iterators$1.Arguments = _iterators$1.Array; + +var TO_STRING_TAG$1 = _wks$1('toStringTag'); + +var DOMIterables$1 = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i$1 = 0; i$1 < DOMIterables$1.length; i$1++) { + var NAME$1 = DOMIterables$1[i$1]; + var Collection$1 = _global$2[NAME$1]; + var proto$1 = Collection$1 && Collection$1.prototype; + if (proto$1 && !proto$1[TO_STRING_TAG$1]) _hide$2(proto$1, TO_STRING_TAG$1, NAME$1); + _iterators$1[NAME$1] = _iterators$1.Array; +} + +var f$1$1 = _wks$1; + +var _wksExt$1 = { + f: f$1$1 +}; + +var iterator$2$1 = _wksExt$1.f('iterator'); + +var iterator$3 = createCommonjsModule$1(function (module) { +module.exports = { "default": iterator$2$1, __esModule: true }; +}); + +unwrapExports$1(iterator$3); + +var _meta$1 = createCommonjsModule$1(function (module) { +var META = _uid$2('meta'); + + +var setDesc = _objectDp$2.f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !_fails$2(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!_isObject$2(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!_has$2(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!_has$2(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !_has$2(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; +}); + +var defineProperty$4$2 = _objectDp$2.f; +var _wksDefine$1 = function (name) { + var $Symbol = _core$2.Symbol || (_core$2.Symbol = _library$1 ? {} : _global$2.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty$4$2($Symbol, name, { value: _wksExt$1.f(name) }); +}; + +var f$2$1 = Object.getOwnPropertySymbols; + +var _objectGops$1 = { + f: f$2$1 +}; + +var f$3$1 = {}.propertyIsEnumerable; + +var _objectPie$1 = { + f: f$3$1 +}; + +// all enumerable object keys, includes symbols + + + +var _enumKeys$1 = function (it) { + var result = _objectKeys$1(it); + var getSymbols = _objectGops$1.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = _objectPie$1.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +// 7.2.2 IsArray(argument) + +var _isArray$1 = Array.isArray || function isArray$$1(arg) { + return _cof$1(arg) == 'Array'; +}; + +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + +var hiddenKeys$1 = _enumBugKeys$1.concat('length', 'prototype'); + +var f$5$1 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return _objectKeysInternal$1(O, hiddenKeys$1); +}; + +var _objectGopn$1 = { + f: f$5$1 +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + +var gOPN$1$1 = _objectGopn$1.f; +var toString$1$1 = {}.toString; + +var windowNames$1 = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames$1 = function (it) { + try { + return gOPN$1$1(it); + } catch (e) { + return windowNames$1.slice(); + } +}; + +var f$4$1 = function getOwnPropertyNames(it) { + return windowNames$1 && toString$1$1.call(it) == '[object Window]' ? getWindowNames$1(it) : gOPN$1$1(_toIobject$1(it)); +}; + +var _objectGopnExt$1 = { + f: f$4$1 +}; + +var gOPD$1$1 = Object.getOwnPropertyDescriptor; + +var f$6$1 = _descriptors$2 ? gOPD$1$1 : function getOwnPropertyDescriptor(O, P) { + O = _toIobject$1(O); + P = _toPrimitive$2(P, true); + if (_ie8DomDefine$2) try { + return gOPD$1$1(O, P); + } catch (e) { /* empty */ } + if (_has$2(O, P)) return _propertyDesc$2(!_objectPie$1.f.call(O, P), O[P]); +}; + +var _objectGopd$1 = { + f: f$6$1 +}; +// ECMAScript 6 symbols shim + + + + + +var META$1 = _meta$1.KEY; + + + + + + + + + + + + + + + + + + +var gOPD$2 = _objectGopd$1.f; +var dP$1$1 = _objectDp$2.f; +var gOPN$2 = _objectGopnExt$1.f; +var $Symbol$1 = _global$2.Symbol; +var $JSON$2 = _global$2.JSON; +var _stringify$1 = $JSON$2 && $JSON$2.stringify; +var PROTOTYPE$2$1 = 'prototype'; +var HIDDEN$1 = _wks$1('_hidden'); +var TO_PRIMITIVE$1 = _wks$1('toPrimitive'); +var isEnum$2 = {}.propertyIsEnumerable; +var SymbolRegistry$1 = _shared$1('symbol-registry'); +var AllSymbols$1 = _shared$1('symbols'); +var OPSymbols$1 = _shared$1('op-symbols'); +var ObjectProto$1$1 = Object[PROTOTYPE$2$1]; +var USE_NATIVE$2 = typeof $Symbol$1 == 'function'; +var QObject$1 = _global$2.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter$1 = !QObject$1 || !QObject$1[PROTOTYPE$2$1] || !QObject$1[PROTOTYPE$2$1].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc$1 = _descriptors$2 && _fails$2(function () { + return _objectCreate$1(dP$1$1({}, 'a', { + get: function () { return dP$1$1(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD$2(ObjectProto$1$1, key); + if (protoDesc) delete ObjectProto$1$1[key]; + dP$1$1(it, key, D); + if (protoDesc && it !== ObjectProto$1$1) dP$1$1(ObjectProto$1$1, key, protoDesc); +} : dP$1$1; + +var wrap$1 = function (tag) { + var sym = AllSymbols$1[tag] = _objectCreate$1($Symbol$1[PROTOTYPE$2$1]); + sym._k = tag; + return sym; +}; + +var isSymbol$1 = USE_NATIVE$2 && typeof $Symbol$1.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol$1; +}; + +var $defineProperty$1 = function defineProperty(it, key, D) { + if (it === ObjectProto$1$1) $defineProperty$1(OPSymbols$1, key, D); + _anObject$2(it); + key = _toPrimitive$2(key, true); + _anObject$2(D); + if (_has$2(AllSymbols$1, key)) { + if (!D.enumerable) { + if (!_has$2(it, HIDDEN$1)) dP$1$1(it, HIDDEN$1, _propertyDesc$2(1, {})); + it[HIDDEN$1][key] = true; + } else { + if (_has$2(it, HIDDEN$1) && it[HIDDEN$1][key]) it[HIDDEN$1][key] = false; + D = _objectCreate$1(D, { enumerable: _propertyDesc$2(0, false) }); + } return setSymbolDesc$1(it, key, D); + } return dP$1$1(it, key, D); +}; +var $defineProperties$1 = function defineProperties(it, P) { + _anObject$2(it); + var keys = _enumKeys$1(P = _toIobject$1(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty$1(it, key = keys[i++], P[key]); + return it; +}; +var $create$1 = function create(it, P) { + return P === undefined ? _objectCreate$1(it) : $defineProperties$1(_objectCreate$1(it), P); +}; +var $propertyIsEnumerable$1 = function propertyIsEnumerable(key) { + var E = isEnum$2.call(this, key = _toPrimitive$2(key, true)); + if (this === ObjectProto$1$1 && _has$2(AllSymbols$1, key) && !_has$2(OPSymbols$1, key)) return false; + return E || !_has$2(this, key) || !_has$2(AllSymbols$1, key) || _has$2(this, HIDDEN$1) && this[HIDDEN$1][key] ? E : true; +}; +var $getOwnPropertyDescriptor$2 = function getOwnPropertyDescriptor(it, key) { + it = _toIobject$1(it); + key = _toPrimitive$2(key, true); + if (it === ObjectProto$1$1 && _has$2(AllSymbols$1, key) && !_has$2(OPSymbols$1, key)) return; + var D = gOPD$2(it, key); + if (D && _has$2(AllSymbols$1, key) && !(_has$2(it, HIDDEN$1) && it[HIDDEN$1][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames$1 = function getOwnPropertyNames(it) { + var names = gOPN$2(_toIobject$1(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!_has$2(AllSymbols$1, key = names[i++]) && key != HIDDEN$1 && key != META$1) result.push(key); + } return result; +}; +var $getOwnPropertySymbols$1 = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto$1$1; + var names = gOPN$2(IS_OP ? OPSymbols$1 : _toIobject$1(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (_has$2(AllSymbols$1, key = names[i++]) && (IS_OP ? _has$2(ObjectProto$1$1, key) : true)) result.push(AllSymbols$1[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE$2) { + $Symbol$1 = function Symbol() { + if (this instanceof $Symbol$1) throw TypeError('Symbol is not a constructor!'); + var tag = _uid$2(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto$1$1) $set.call(OPSymbols$1, value); + if (_has$2(this, HIDDEN$1) && _has$2(this[HIDDEN$1], tag)) this[HIDDEN$1][tag] = false; + setSymbolDesc$1(this, tag, _propertyDesc$2(1, value)); + }; + if (_descriptors$2 && setter$1) setSymbolDesc$1(ObjectProto$1$1, tag, { configurable: true, set: $set }); + return wrap$1(tag); + }; + _redefine$2($Symbol$1[PROTOTYPE$2$1], 'toString', function toString() { + return this._k; + }); + + _objectGopd$1.f = $getOwnPropertyDescriptor$2; + _objectDp$2.f = $defineProperty$1; + _objectGopn$1.f = _objectGopnExt$1.f = $getOwnPropertyNames$1; + _objectPie$1.f = $propertyIsEnumerable$1; + _objectGops$1.f = $getOwnPropertySymbols$1; + + if (_descriptors$2 && !_library$1) { + _redefine$2(ObjectProto$1$1, 'propertyIsEnumerable', $propertyIsEnumerable$1, true); + } + + _wksExt$1.f = function (name) { + return wrap$1(_wks$1(name)); + }; +} + +_export$2(_export$2.G + _export$2.W + _export$2.F * !USE_NATIVE$2, { Symbol: $Symbol$1 }); + +for (var es6Symbols$1 = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j$1 = 0; es6Symbols$1.length > j$1;)_wks$1(es6Symbols$1[j$1++]); + +for (var wellKnownSymbols$1 = _objectKeys$1(_wks$1.store), k$1 = 0; wellKnownSymbols$1.length > k$1;) _wksDefine$1(wellKnownSymbols$1[k$1++]); + +_export$2(_export$2.S + _export$2.F * !USE_NATIVE$2, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return _has$2(SymbolRegistry$1, key += '') + ? SymbolRegistry$1[key] + : SymbolRegistry$1[key] = $Symbol$1(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol$1(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry$1) if (SymbolRegistry$1[key] === sym) return key; + }, + useSetter: function () { setter$1 = true; }, + useSimple: function () { setter$1 = false; } +}); + +_export$2(_export$2.S + _export$2.F * !USE_NATIVE$2, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create$1, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty$1, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties$1, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor$2, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames$1, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols$1 +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON$2 && _export$2(_export$2.S + _export$2.F * (!USE_NATIVE$2 || _fails$2(function () { + var S = $Symbol$1(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify$1([S]) != '[null]' || _stringify$1({ a: S }) != '{}' || _stringify$1(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + if (it === undefined || isSymbol$1(it)) return; // IE8 returns string on undefined + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + replacer = args[1]; + if (typeof replacer == 'function') $replacer = replacer; + if ($replacer || !_isArray$1(replacer)) replacer = function (key, value) { + if ($replacer) value = $replacer.call(this, key, value); + if (!isSymbol$1(value)) return value; + }; + args[1] = replacer; + return _stringify$1.apply($JSON$2, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol$1[PROTOTYPE$2$1][TO_PRIMITIVE$1] || _hide$2($Symbol$1[PROTOTYPE$2$1], TO_PRIMITIVE$1, $Symbol$1[PROTOTYPE$2$1].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +_setToStringTag$1($Symbol$1, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +_setToStringTag$1(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +_setToStringTag$1(_global$2.JSON, 'JSON', true); + +_wksDefine$1('asyncIterator'); + +_wksDefine$1('observable'); + +var symbol$2$1 = _core$2.Symbol; + +var symbol$3 = createCommonjsModule$1(function (module) { +module.exports = { "default": symbol$2$1, __esModule: true }; +}); + +unwrapExports$1(symbol$3); + +var _typeof_1$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + + + +var _iterator2 = _interopRequireDefault(iterator$3); + + + +var _symbol2 = _interopRequireDefault(symbol$3); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +}); + +unwrapExports$1(_typeof_1$1); + +var possibleConstructorReturn$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + + + +var _typeof3 = _interopRequireDefault(_typeof_1$1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +}); + +var _possibleConstructorReturn$1 = unwrapExports$1(possibleConstructorReturn$1); + +// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + +var $getOwnPropertyDescriptor$1$1 = _objectGopd$1.f; + +_objectSap$1('getOwnPropertyDescriptor', function () { + return function getOwnPropertyDescriptor(it, key) { + return $getOwnPropertyDescriptor$1$1(_toIobject$1(it), key); + }; +}); + +var $Object$1$1 = _core$2.Object; +var getOwnPropertyDescriptor$1$2 = function getOwnPropertyDescriptor(it, key) { + return $Object$1$1.getOwnPropertyDescriptor(it, key); +}; + +var getOwnPropertyDescriptor$4 = createCommonjsModule$1(function (module) { +module.exports = { "default": getOwnPropertyDescriptor$1$2, __esModule: true }; +}); + +var _Object$getOwnPropertyDescriptor$1 = unwrapExports$1(getOwnPropertyDescriptor$4); + +var get$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + + + +var _getPrototypeOf2 = _interopRequireDefault(getPrototypeOf$2); + + + +var _getOwnPropertyDescriptor2 = _interopRequireDefault(getOwnPropertyDescriptor$4); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function get(object, property, receiver) { + if (object === null) object = Function.prototype; + var desc = (0, _getOwnPropertyDescriptor2.default)(object, property); + + if (desc === undefined) { + var parent = (0, _getPrototypeOf2.default)(object); + + if (parent === null) { + return undefined; + } else { + return get(parent, property, receiver); + } + } else if ("value" in desc) { + return desc.value; + } else { + var getter = desc.get; + + if (getter === undefined) { + return undefined; + } + + return getter.call(receiver); + } +}; +}); + +var _get$1 = unwrapExports$1(get$1); + +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ + + +var check$1 = function (O, proto) { + _anObject$2(O); + if (!_isObject$2(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); +}; +var _setProto$1 = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = _ctx$2(Function.call, _objectGopd$1.f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check$1(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check$1 +}; + +// 19.1.3.19 Object.setPrototypeOf(O, proto) + +_export$2(_export$2.S, 'Object', { setPrototypeOf: _setProto$1.set }); + +var setPrototypeOf$2$1 = _core$2.Object.setPrototypeOf; + +var setPrototypeOf$3 = createCommonjsModule$1(function (module) { +module.exports = { "default": setPrototypeOf$2$1, __esModule: true }; +}); + +unwrapExports$1(setPrototypeOf$3); + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +_export$2(_export$2.S, 'Object', { create: _objectCreate$1 }); + +var $Object$2$1 = _core$2.Object; +var create$2 = function create(P, D) { + return $Object$2$1.create(P, D); +}; + +var create$3 = createCommonjsModule$1(function (module) { +module.exports = { "default": create$2, __esModule: true }; +}); + +unwrapExports$1(create$3); + +var inherits$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + + + +var _setPrototypeOf2 = _interopRequireDefault(setPrototypeOf$3); + + + +var _create2 = _interopRequireDefault(create$3); + + + +var _typeof3 = _interopRequireDefault(_typeof_1$1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } + + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +}); + +var _inherits$1 = unwrapExports$1(inherits$1); + +// call something on iterator step with safe closing on error + +var _iterCall$1 = function (iterator, fn, value, entries) { + try { + return entries ? fn(_anObject$2(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) _anObject$2(ret.call(iterator)); + throw e; + } +}; + +// check on default Array iterator + +var ITERATOR$1$1 = _wks$1('iterator'); +var ArrayProto$1 = Array.prototype; + +var _isArrayIter$1 = function (it) { + return it !== undefined && (_iterators$1.Array === it || ArrayProto$1[ITERATOR$1$1] === it); +}; + + + +var _createProperty$1 = function (object, index, value) { + if (index in object) _objectDp$2.f(object, index, _propertyDesc$2(0, value)); + else object[index] = value; +}; + +// getting tag from 19.1.3.6 Object.prototype.toString() + +var TAG$1$1 = _wks$1('toStringTag'); +// ES3 wrong here +var ARG$1 = _cof$1(function () { return arguments; }()) == 'Arguments'; + +// fallback for IE11 Script Access Denied error +var tryGet$1 = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } +}; + +var _classof$1 = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet$1(O = Object(it), TAG$1$1)) == 'string' ? T + // builtinTag case + : ARG$1 ? _cof$1(O) + // ES3 arguments fallback + : (B = _cof$1(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; +}; + +var ITERATOR$2$1 = _wks$1('iterator'); + +var core_getIteratorMethod$1 = _core$2.getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR$2$1] + || it['@@iterator'] + || _iterators$1[_classof$1(it)]; +}; + +var ITERATOR$3$1 = _wks$1('iterator'); +var SAFE_CLOSING$1 = false; + +try { + var riter$1 = [7][ITERATOR$3$1](); + riter$1['return'] = function () { SAFE_CLOSING$1 = true; }; + // eslint-disable-next-line no-throw-literal + +} catch (e) { /* empty */ } + +var _iterDetect$1 = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING$1) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR$3$1](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR$3$1] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; +}; + + + + + + + + + +_export$2(_export$2.S + _export$2.F * !_iterDetect$1(function (iter) { }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = _toObject$1(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = core_getIteratorMethod$1(O); + var length, result, step, iterator; + if (mapping) mapfn = _ctx$2(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$1(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + _createProperty$1(result, index, mapping ? _iterCall$1(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = _toLength$1(O.length); + for (result = new C(length); length > index; index++) { + _createProperty$1(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } +}); + +var from$1$1 = _core$2.Array.from; + +var from$2 = createCommonjsModule$1(function (module) { +module.exports = { "default": from$1$1, __esModule: true }; +}); + +var _Array$from$1 = unwrapExports$1(from$2); + +var toConsumableArray$1 = createCommonjsModule$1(function (module, exports) { + +exports.__esModule = true; + + + +var _from2 = _interopRequireDefault(from$2); + +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$1 = unwrapExports$1(toConsumableArray$1); + +// 20.1.2.3 Number.isInteger(number) + +var floor$1$1 = Math.floor; +var _isInteger$1 = function isInteger(it) { + return !_isObject$2(it) && isFinite(it) && floor$1$1(it) === it; +}; + +// 20.1.2.3 Number.isInteger(number) + + +_export$2(_export$2.S, 'Number', { isInteger: _isInteger$1 }); + +var isInteger$2$1 = _core$2.Number.isInteger; + +var isInteger$1$1 = createCommonjsModule$1(function (module) { +module.exports = { "default": isInteger$2$1, __esModule: true }; +}); + +unwrapExports$1(isInteger$1$1); + +var _stringWs$1 = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +var space$1 = '[' + _stringWs$1 + ']'; +var non$1 = '\u200b\u0085'; +var ltrim$1 = RegExp('^' + space$1 + space$1 + '*'); +var rtrim$1 = RegExp(space$1 + space$1 + '*$'); + +var exporter$1 = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = _fails$2(function () { + return !!_stringWs$1[KEY]() || non$1[KEY]() != non$1; + }); + var fn = exp[KEY] = FORCE ? exec(trim$1) : _stringWs$1[KEY]; + if (ALIAS) exp[ALIAS] = fn; + _export$2(_export$2.P + _export$2.F * FORCE, 'String', exp); +}; + +// 1 -> String#trimLeft +// 2 -> String#trimRight +// 3 -> String#trim +var trim$1 = exporter$1.trim = function (string$$1, TYPE) { + string$$1 = String(_defined$1(string$$1)); + if (TYPE & 1) string$$1 = string$$1.replace(ltrim$1, ''); + if (TYPE & 2) string$$1 = string$$1.replace(rtrim$1, ''); + return string$$1; +}; + +var _stringTrim$1 = exporter$1; + +var $parseFloat$1 = _global$2.parseFloat; +var $trim$1 = _stringTrim$1.trim; + +var _parseFloat$3 = 1 / $parseFloat$1(_stringWs$1 + '-0') !== -Infinity ? function parseFloat(str) { + var string$$1 = $trim$1(String(str), 3); + var result = $parseFloat$1(string$$1); + return result === 0 && string$$1.charAt(0) == '-' ? -0 : result; +} : $parseFloat$1; + +// 20.1.2.12 Number.parseFloat(string) +_export$2(_export$2.S + _export$2.F * (Number.parseFloat != _parseFloat$3), 'Number', { parseFloat: _parseFloat$3 }); + +var _parseFloat$1$1 = parseFloat; + +var _parseFloat$4 = createCommonjsModule$1(function (module) { +module.exports = { "default": _parseFloat$1$1, __esModule: true }; +}); + +unwrapExports$1(_parseFloat$4); + +/** + * toxic-predicate-functions v0.1.5 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** + * toxic-utils v0.1.6 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** + * bind the function with some context. we have some fallback strategy here + * @param {function} fn the function which we need to bind the context on + * @param {any} context the context object + */ +function bind$2(fn, context) { + if (fn.bind) { + return fn.bind(context); + } else if (fn.apply) { + return function __autobind__() { + for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { + args[_key3] = arguments[_key3]; + } + + return fn.apply(context, args); + }; + } else { + return function __autobind__() { + for (var _len3 = arguments.length, args = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { + args[_key4] = arguments[_key4]; + } + + return fn.call.apply(fn, [context].concat(_toConsumableArray$1(args))); + }; + } +} + +var Base = function () { + function Base(parent) { + _classCallCheck$1(this, Base); + + this.parent = parent; + } + + _createClass$1(Base, [{ + key: 'create', + value: function create() { + this.createEl(); + this.addAllEvent(); + } + }, { + key: 'destroy', + value: function destroy() { + this.removeAllEvent(); + } + }, { + key: 'createEl', + value: function createEl() { + this.$dom = document.createElement(this.option.tag); + this.$dom.innerHTML = this.option.html; + this.parent.$wrap.appendChild(this.$dom); + } + }, { + key: 'addAllEvent', + value: function addAllEvent() { + var _this = this; + + this.option.defaultEvent && _Object$keys$1(this.option.defaultEvent).forEach(function (item) { + var key = _this.option.defaultEvent[item]; + _this[key] = bind$2(_this[key], _this); + addEvent(_this.$dom, item, _this[key], false, false); + }); + this.option.event && _Object$keys$1(this.option.event).forEach(function (item) { + var key = '__' + item; + _this[key] = bind$2(_this.option.event[item], _this); + addEvent(_this.$dom, item, _this[key], false, false); + }); + } + }, { + key: 'removeAllEvent', + value: function removeAllEvent() { + var _this2 = this; + + this.option.defaultEvent && _Object$keys$1(this.option.defaultEvent).forEach(function (item) { + var key = _this2.option.defaultEvent[item]; + _this2[key] = bind$2(_this2[key], _this2); + removeEvent(_this2.$dom, item, _this2[key], false, false); + }); + this.option.event && _Object$keys$1(this.option.event).forEach(function (item) { + var key = '__' + item; + _this2[key] = bind$2(_this2.option.event[item], _this2); + removeEvent(_this2.$dom, item, _this2[key], false, false); + }); + } + }]); + + return Base; +}(); + +/** + * 自定义组件配置 + */ + +var Component = function (_Base) { + _inherits$1(Component, _Base); + + function Component(parent, option) { + _classCallCheck$1(this, Component); + + var _this = _possibleConstructorReturn$1(this, (Component.__proto__ || _Object$getPrototypeOf$1(Component)).call(this, parent)); + + _this.option = option; + _this.init(); + return _this; + } + + _createClass$1(Component, [{ + key: 'init', + value: function init() { + _get$1(Component.prototype.__proto__ || _Object$getPrototypeOf$1(Component.prototype), 'create', this).call(this); + addClassName(this.$dom, 'chimee-flex-component'); + } + }]); + + return Component; +}(Base); + +/** + * play 配置 + */ + +var defaultOption = { + tag: 'chimee-control-state', + html: '\n \n \n ', + animate: { + icon: '\n \n \n \n \n \n \n ', + path: { + play: { + left: 'M0.921875,0.265625L0.921875,197.074852L95.7890625,149L96.2929688,49Z', + right: 'M90.3142151,45.9315226L90.3142151,151.774115L201.600944,99.9938782L201.600944,98.0237571Z' + }, + pause: { + left: 'M0.921875,1.265625L0.921875,198.074852L79.3611677,198.074852L79.3611677,0.258923126Z', + right: 'M126.921875,1.265625L126.921875,198.074852L205.361168,198.074852L205.361168,0.258923126Z' + } + } + }, + defaultEvent: { + click: 'click' + } +}; + +var Play = function (_Base) { + _inherits$1(Play, _Base); + + function Play(parent, option) { + _classCallCheck$1(this, Play); + + var _this = _possibleConstructorReturn$1(this, (Play.__proto__ || _Object$getPrototypeOf$1(Play)).call(this, parent)); + + _this.option = deepAssign(defaultOption, isObject(option) ? option : {}); + _this.animate = false; + _this.init(); + return _this; + } + + _createClass$1(Play, [{ + key: 'init', + value: function init() { + // 创建 html / 绑定事件 + _get$1(Play.prototype.__proto__ || _Object$getPrototypeOf$1(Play.prototype), 'create', this).call(this); + this.$dom = $(this.$dom); + this.$dom.addClass('chimee-flex-component'); + + // 判断是否是默认或者用户提供 icon + if (this.option.icon && this.option.icon.play && this.option.icon.pause) { + this.$play = this.$dom.find('chimee-control-state-play'); + this.$pause = this.$dom.find('chimee-control-state-pause'); + this.$play.html(this.option.icon.play); + this.$pause.html(this.option.icon.pause); + } else if (!this.option.bitmap) { + this.animate = true; + this.option.animate.path = this.option.path ? this.option.path : this.option.animate.path; + this.$dom.html(this.option.animate.icon); + this.$left = this.$dom.find('.left'); + this.$right = this.$dom.find('.right'); + } + this.changeState('pause'); + } + }, { + key: 'changeState', + value: function changeState(state) { + var nextState = state === 'play' ? 'pause' : 'play'; + this.state = state; + addClassName(this.parent.$dom, nextState); + removeClassName(this.parent.$dom, state); + this.animate && this.setPath(nextState); + } + }, { + key: 'setPath', + value: function setPath(state) { + var path = this.option.animate.path; + if (state === 'play') { + this.$left.attr('d', path.play.left); + this.$right.attr('d', path.play.right); + } else { + this.$left.attr('d', path.pause.left); + this.$right.attr('d', path.pause.right); + } + } + }, { + key: 'click', + value: function click(e) { + var nextState = this.state === 'play' ? 'pause' : 'play'; + this.changeState(nextState); + this.parent.$emit(nextState); + } + }]); + + return Play; +}(Base); + +var _class$8; + +function _applyDecoratedDescriptor$7(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; +} + +/** + * Volume 配置 + */ + +var defaultOption$1 = { + tag: 'chimee-volume', + html: '\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ', + animate: { + icon: '\n \n \n \n \n \n \n \n \n ' + }, + defaultEvent: { + mousedown: 'mousedown' + } +}; + +var getElementPath = function getElementPath(elem) { + var path = []; + if (elem === null) return path; + path.push(elem); + while (elem.parentNode !== null) { + elem = elem.parentNode; + path.push(elem); + } + return path; +}; + +var Volume = (_class$8 = function (_Base) { + _inherits$1(Volume, _Base); + + function Volume(parent, option) { + _classCallCheck$1(this, Volume); + + var _this = _possibleConstructorReturn$1(this, (Volume.__proto__ || _Object$getPrototypeOf$1(Volume)).call(this, parent)); + + _this.parent.preVolume = 0; + _this.option = deepAssign(defaultOption$1, isObject(option) ? option : {}); + _this.init(); + return _this; + } + + _createClass$1(Volume, [{ + key: 'init', + value: function init() { + var _this2 = this; + + _get$1(Volume.prototype.__proto__ || _Object$getPrototypeOf$1(Volume.prototype), 'create', this).call(this); + this.$dom = $(this.$dom); + this.$state = this.$dom.find('chimee-volume-state'); + this.$bar = this.$dom.find('chimee-volume-bar'); + this.$all = this.$dom.find('chimee-volume-bar-all'); + this.$bg = this.$dom.find('chimee-volume-bar-bg'); + this.layout = this.option.layout === 'vertical' ? 'vertical' : 'horizonal'; + + // 判断是否是默认或者用户提供 icon + if (this.option.icon && this.option.icon.mute && this.option.icon.low) { + this.option.icon.high = this.option.icon.high || this.option.icon.low; + this.$mute = this.$dom.find('chimee-volume-state-mute'); + this.$low = this.$dom.find('chimee-volume-state-low'); + this.$high = this.$dom.find('chimee-volume-state-high'); + this.$mute.html(this.option.icon.mute); + this.$low.html(this.option.icon.low); + this.$high.html(this.option.icon.high); + } else if (!this.option.bitmap) { + this.animate = true; + this.$state.html(this.option.animate.icon); + } + + this.$dom.addClass('chimee-flex-component ' + this.layout); + this.changeState(); + + this.watch_muted = this.parent.$watch('muted', function (val) { + _this2.update(); + }); + } + }, { + key: 'inited', + value: function inited() { + this.update(); + } + }, { + key: 'destroy', + value: function destroy() { + this.watch_muted(); + _get$1(Volume.prototype.__proto__ || _Object$getPrototypeOf$1(Volume.prototype), 'destroy', this).call(this); + } + }, { + key: 'changeState', + value: function changeState() { + if (this.parent.muted || this.parent.volume === 0) { + this.state = 'mute'; + } else if (this.parent.volume > 0 && this.parent.volume <= 0.5) { + this.state = 'low'; + } else if (this.parent.volume > 0.5 && this.parent.volume <= 1) { + this.state = 'high'; + } + this.$dom.removeClass('mute low high'); + this.$dom.addClass(this.state); + } + }, { + key: 'click', + value: function click(e) { + var path = e.path || getElementPath(e.target); + if (path.indexOf(this.$state[0]) !== -1) { + this.stateClick(e); + return 'state'; + } else if (path.indexOf(this.$bar[0]) !== -1) { + this.barClick(e); + return 'bar'; + } + return 'padding'; + } + }, { + key: 'stateClick', + value: function stateClick() { + if (this.parent.muted) { + this.parent.muted = false; + return; + } + var currentVolume = this.parent.volume; + this.parent.volume = currentVolume === 0 ? this.parent.preVolume : 0; + this.parent.preVolume = currentVolume; + this.changeState(); + } + }, { + key: 'barClick', + value: function barClick(e) { + var volume = this.layout === 'vertical' ? 1 - e.offsetY / this.$bg[0].offsetHeight : e.offsetX / this.$bg[0].offsetWidth; + this.parent.volume = volume < 0 ? 0 : volume > 1 ? 1 : volume; + this.update(); + } + }, { + key: 'mousedown', + value: function mousedown(e) { + if (this.click(e) !== 'bar') return; + this.startX = this.layout === 'vertical' ? e.clientY : e.clientX; + this.startVolume = this.parent.volume; + addEvent(window, 'mousemove', this.draging); + addEvent(window, 'mouseup', this.dragEnd); + addEvent(window, 'contextmenu', this.dragEnd); + } + + /** + * 更新声音条 + */ + + }, { + key: 'update', + value: function update() { + this.changeState(); + var volume = this.parent.muted ? 0 : this.parent.volume; + this.layout === 'vertical' ? this.$all.css('height', volume * 100 + '%') : this.$all.css('width', volume * 100 + '%'); + } + + /** + * 开始拖拽 + * @param {EventObject} e 鼠标事件 + */ + + }, { + key: 'draging', + value: function draging(e) { + this.endX = this.layout === 'vertical' ? e.clientY : e.clientX; + var dragVolume = this.layout === 'vertical' ? (this.startX - this.endX) / this.$bg[0].offsetHeight : (this.endX - this.startX) / this.$bg[0].offsetWidth; + var dragAfterVolume = +(this.startVolume + dragVolume).toFixed(2); + this.parent.volume = dragAfterVolume < 0 ? 0 : dragAfterVolume > 1 ? 1 : dragAfterVolume; + this.parent.muted = false; + } + + /** + * 结束拖拽 + */ + + }, { + key: 'dragEnd', + value: function dragEnd() { + this.startX = 0; + this.startVolume = 0; + removeEvent(window, 'mousemove', this.draging); + removeEvent(window, 'mouseup', this.dragEnd); + removeEvent(window, 'contextmenu', this.dragEnd); + } + }]); + + return Volume; +}(Base), _applyDecoratedDescriptor$7(_class$8.prototype, 'draging', [autobind], _Object$getOwnPropertyDescriptor$1(_class$8.prototype, 'draging'), _class$8.prototype), _applyDecoratedDescriptor$7(_class$8.prototype, 'dragEnd', [autobind], _Object$getOwnPropertyDescriptor$1(_class$8.prototype, 'dragEnd'), _class$8.prototype), _class$8); + +var _class$1$2; + +function _applyDecoratedDescriptor$1$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; +} + +var defaultOption$2 = { + tag: 'chimee-progressbar', + html: '\n \n \n \n \n \n \n \n \n ' +}; + +var ProgressBar = (_class$1$2 = function (_Base) { + _inherits$1(ProgressBar, _Base); + + function ProgressBar(parent, option) { + _classCallCheck$1(this, ProgressBar); + + var _this = _possibleConstructorReturn$1(this, (ProgressBar.__proto__ || _Object$getPrototypeOf$1(ProgressBar)).call(this, parent)); + + _this.option = deepAssign(defaultOption$2, isObject(option) ? option : {}); + _this.visiable = option !== false; + _this.init(); + return _this; + } + + _createClass$1(ProgressBar, [{ + key: 'init', + value: function init() { + _get$1(ProgressBar.prototype.__proto__ || _Object$getPrototypeOf$1(ProgressBar.prototype), 'create', this).call(this); + this.$dom = $(this.$dom); + this.$wrap = this.$dom.find('chimee-progressbar-wrap'); + this.$buffer = this.$dom.find('chimee-progressbar-buffer'); + this.$all = this.$dom.find('chimee-progressbar-all'); + this.$tip = this.$dom.find('chimee-progressbar-tip'); + this.$track = this.$dom.find('chimee-progressbar-track'); + this.$line = this.$dom.find('.chimee-progressbar-line'); + this.$ball = this.$dom.find('chimee-progressbar-ball'); + this.$dom.addClass('chimee-flex-component'); + + // css 配置 + !this.visiable && this.$dom.css('visibility', 'hidden'); + // this.$line.css({ + // top: this.$wrap. + // }); + // 进度条居中布局,还是在上方 + if (this.option.layout === 'top') { + this.$dom.addClass('progressbar-layout-top'); + this.$wrap.css({ + // left: -this.$dom[0].offsetLeft + 'px', + top: -this.$ball[0].offsetHeight + 'px' + // height: this.$ball[0].offsetHeight * 2 + 'px' + }); + // this.$line.css({ + // top: this.$ball[0].offsetHeight + 'px' + // }) + setStyle(this.parent.$wrap, 'paddingTop', this.$ball[0].offsetHeight + 'px'); + } + this.addWrapEvent(); + } + }, { + key: 'destroy', + value: function destroy() { + this.removeWrapEvent(); + // 解绑全屏监听事件 + this.watch_screen && this.watch_screen(); + _get$1(ProgressBar.prototype.__proto__ || _Object$getPrototypeOf$1(ProgressBar.prototype), 'destroy', this).call(this); + } + }, { + key: 'addWrapEvent', + value: function addWrapEvent() { + this.$wrap.on('mousedown', this.mousedown); + this.$wrap.on('mousemove', this.tipShow); + this.$wrap.on('mouseleave', this.tipEnd); + } + }, { + key: 'removeWrapEvent', + value: function removeWrapEvent() { + this.$wrap.off('mousedown', this.mousedown); + this.$wrap.off('mousemove', this.tipShow); + this.$wrap.off('mouseleave', this.tipEnd); + } + + /** + * 缓存进度条更新 progress 事件 + */ + + }, { + key: 'progress', + value: function progress() { + var buffer = 0; + try { + buffer = this.parent.buffered.end(0); + } catch (e) {} + var bufferWidth = buffer / this.parent.duration * 100 + '%'; + this.$buffer.css('width', bufferWidth); + } + + /** + * requestAnimationFrame 来更新进度条, timeupdate 事件 + */ + + }, { + key: 'update', + value: function update() { + // const allWidth = this.$wrap[0].offsetWidth - this.$ball[0].offsetWidth; + var time = this._currentTime !== undefined ? this._currentTime : this.parent.currentTime; + var timePer = time ? time / this.parent.duration : 0; + // const timeWidth = timePer * allWidth; + this.$all.css('width', 'calc(' + timePer * 100 + '% - ' + this.$ball[0].offsetWidth / 2 + 'px'); + } + }, { + key: 'mousedown', + value: function mousedown(e) { + // const ballRect = this.$ball[0].getClientRects()[0]; + // const ballLeft = ballRect.left; + // const ballRight = ballRect.left + ballRect.width; + // this.inBall = e.clientX <= ballRight && e.clientX >= ballLeft; + if (e.target === this.$tip[0]) return; + this._currentTime = e.offsetX / this.$wrap[0].offsetWidth * this.parent.duration; + // if(!this.inBall) this.update(); + this.startX = e.clientX; + this.startTime = this._currentTime; + addEvent(window, 'mousemove', this.draging); + addEvent(window, 'mouseup', this.dragEnd); + addEvent(window, 'contextmenu', this.dragEnd); + } + + /** + * 开始拖拽 + * @param {EventObject} e 鼠标事件 + */ + + }, { + key: 'draging', + value: function draging(e) { + this.endX = e.clientX; + var dragTime = (this.endX - this.startX) / this.$wrap[0].offsetWidth * this.parent.duration; + var dragAfterTime = +(this.startTime + dragTime).toFixed(2); + this._currentTime = dragAfterTime < 0 ? 0 : dragAfterTime > this.parent.duration ? this.parent.duration : dragAfterTime; + this.update(); + } + + /** + * 结束拖拽 + */ + + }, { + key: 'dragEnd', + value: function dragEnd() { + this.update(); + this.startX = 0; + this.startTime = 0; + // if(!this.inBall) { + this.parent.currentTime = this._currentTime; + // this.inBall = false; + // } + this._currentTime = undefined; + removeEvent(window, 'mousemove', this.draging); + removeEvent(window, 'mouseup', this.dragEnd); + removeEvent(window, 'contextmenu', this.dragEnd); + } + }, { + key: 'tipShow', + value: function tipShow(e) { + if (e.target === this.$tip[0] || e.target === this.$ball[0]) { + this.$tip.css('display', 'none'); + return; + } + var time = e.offsetX / this.$wrap[0].offsetWidth * this.parent.duration; + time = time < 0 ? 0 : time > this.parent.duration ? this.parent.duration : time; + var tipContent = formatTime(time); + var left = e.offsetX - this.$tip[0].offsetWidth / 2; + var leftBound = this.$wrap[0].offsetWidth - this.$tip[0].offsetWidth; + left = left < 0 ? 0 : left > leftBound ? leftBound : left; + this.$tip.text(tipContent); + this.$tip.css('display', 'inline-block'); + this.$tip.css('left', left + 'px'); + } + }, { + key: 'tipEnd', + value: function tipEnd() { + this.$tip.css('display', 'none'); + } + }]); + + return ProgressBar; +}(Base), _applyDecoratedDescriptor$1$2(_class$1$2.prototype, 'mousedown', [autobind], _Object$getOwnPropertyDescriptor$1(_class$1$2.prototype, 'mousedown'), _class$1$2.prototype), _applyDecoratedDescriptor$1$2(_class$1$2.prototype, 'draging', [autobind], _Object$getOwnPropertyDescriptor$1(_class$1$2.prototype, 'draging'), _class$1$2.prototype), _applyDecoratedDescriptor$1$2(_class$1$2.prototype, 'dragEnd', [autobind], _Object$getOwnPropertyDescriptor$1(_class$1$2.prototype, 'dragEnd'), _class$1$2.prototype), _applyDecoratedDescriptor$1$2(_class$1$2.prototype, 'tipShow', [autobind], _Object$getOwnPropertyDescriptor$1(_class$1$2.prototype, 'tipShow'), _class$1$2.prototype), _applyDecoratedDescriptor$1$2(_class$1$2.prototype, 'tipEnd', [autobind], _Object$getOwnPropertyDescriptor$1(_class$1$2.prototype, 'tipEnd'), _class$1$2.prototype), _class$1$2); + +/** + * progressTime 配置 + */ + +var defaultOption$3 = { + tag: 'chimee-progresstime', + html: '\n 00:00/00:00\n \n ' +}; + +var ProgressTime = function (_Base) { + _inherits$1(ProgressTime, _Base); + + function ProgressTime(parent, option) { + _classCallCheck$1(this, ProgressTime); + + var _this = _possibleConstructorReturn$1(this, (ProgressTime.__proto__ || _Object$getPrototypeOf$1(ProgressTime)).call(this, parent)); + + _this.option = deepAssign(defaultOption$3, isObject(option) ? option : {}); + _this.init(); + return _this; + } + + _createClass$1(ProgressTime, [{ + key: 'init', + value: function init() { + _get$1(ProgressTime.prototype.__proto__ || _Object$getPrototypeOf$1(ProgressTime.prototype), 'create', this).call(this); + this.$dom = $(this.$dom); + this.$total = this.$dom.find('chimee-progresstime-total-value'); + this.$pass = this.$dom.find('chimee-progresstime-pass'); + this.$dom.addClass('chimee-flex-component'); + } + }, { + key: 'updatePass', + value: function updatePass() { + this.$pass.text(formatTime(this.parent.currentTime)); + } + }, { + key: 'updateTotal', + value: function updateTotal() { + this.$total.text(formatTime(this.parent.duration)); + } + }]); + + return ProgressTime; +}(Base); + +var _class$2$1; + +function _applyDecoratedDescriptor$2$1(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; +} + +/** + * Screen 配置 + */ + +var defaultOption$4 = { + tag: 'chimee-screen', + html: '\n \n \n \n Created with Sketch.\n \n \n \n \n \n \n \n \n \n \n \n \n Created with Sketch.\n \n \n \n \n \n \n \n \n \n ', + defaultEvent: { + click: 'click' + } +}; + +var Screen = (_class$2$1 = function (_Base) { + _inherits$1(Screen, _Base); + + function Screen(parent, option) { + _classCallCheck$1(this, Screen); + + var _this = _possibleConstructorReturn$1(this, (Screen.__proto__ || _Object$getPrototypeOf$1(Screen)).call(this, parent)); + + _this.state = 'small'; + _this.option = deepAssign(defaultOption$4, isObject(option) ? option : {}); + _this.init(); + return _this; + } + + _createClass$1(Screen, [{ + key: 'init', + value: function init() { + _get$1(Screen.prototype.__proto__ || _Object$getPrototypeOf$1(Screen.prototype), 'create', this).call(this); + this.$dom = $(this.$dom); + this.changeState(this.state); + // addClassName(this.$dom, 'flex-item'); + this.$dom.addClass('chimee-flex-component'); + + this.$full = this.$dom.find('chimee-screen-full'); + this.$small = this.$dom.find('chimee-screen-small'); + // 判断是否是默认或者用户提供 icon + if (this.option.icon && this.option.icon.full && this.option.icon.small) { + // if((!this.option.icon.play && this.option.icon.puase) || (this.option.icon.play && !this.option.icon.puase)) { + // console.warn(`Please provide a play and pause icon!If you can't, we will use default icon!`); + // } + this.$full.html(this.option.icon.full); + this.$small.html(this.option.icon.small); + } else if (this.option.bitmap) { + this.$full.html(''); + this.$small.html(''); + } + } + }, { + key: 'changeState', + value: function changeState(state) { + var removeState = state === 'small' ? 'full' : 'small'; + addClassName(this.parent.$dom, state); + removeClassName(this.parent.$dom, removeState); + } + }, { + key: 'click', + value: function click() { + var full = false; + if (this.state === 'small') { + this.state = 'full'; + full = true; + } else { + this.state = 'small'; + full = false; + } + this.changeState(this.state); + this.parent.$fullscreen(full, 'container'); + if (full) { + this.watch_screen = this.parent.$watch('isFullscreen', this.screenChange); + } else { + this.watch_screen(); + } + } + }, { + key: 'screenChange', + value: function screenChange() { + if (!this.parent.fullscreenElement) return; + this.state = 'small'; + this.changeState('small'); + this.parent.$fullscreen(false, 'container'); + } + }]); + + return Screen; +}(Base), _applyDecoratedDescriptor$2$1(_class$2$1.prototype, 'screenChange', [autobind], _Object$getOwnPropertyDescriptor$1(_class$2$1.prototype, 'screenChange'), _class$2$1.prototype), _class$2$1); + +/** + * play 配置 + */ + +var defaultOption$5 = { + tag: 'chimee-clarity', + width: '2em', + html: '\n \n \n
    \n
    \n \n \n \n \n \n
    \n
    \n ', + defaultEvent: { + click: 'click' + }, + duration: 10, + increment: 1 +}; + +var Clarity = function (_Base) { + _inherits$1(Clarity, _Base); + + function Clarity(parent, option) { + _classCallCheck$1(this, Clarity); + + var _this = _possibleConstructorReturn$1(this, (Clarity.__proto__ || _Object$getPrototypeOf$1(Clarity)).call(this, parent)); + + _this.option = deepAssign(defaultOption$5, isObject(option) ? option : {}); + _this.init(); + return _this; + } + + _createClass$1(Clarity, [{ + key: 'init', + value: function init() { + _get$1(Clarity.prototype.__proto__ || _Object$getPrototypeOf$1(Clarity.prototype), 'create', this).call(this); + addClassName(this.$dom, 'chimee-flex-component'); + + this.$text = $(this.$dom).find('chimee-clarity-text'); + this.$list = $(this.$dom).find('chimee-clarity-list'); + this.$listUl = this.$list.find('ul'); + + // 用户自定义配置 + this.option.width && setStyle(this.$dom, 'width', this.option.width); + + this.initTextList(); + } + }, { + key: 'initTextList', + value: function initTextList() { + var _this2 = this; + + this.option.list.forEach(function (item) { + var li = $(document.createElement('li')); + li.attr('data-url', item.src); + li.text(item.name); + if (item.src === _this2.parent.$videoConfig.src) { + _this2.$text.text(item.name); + li.addClass('active'); + } + _this2.$listUl.append(li); + }); + } + }, { + key: 'click', + value: function click(e) { + var _this3 = this; + + var elem = e.target; + if (elem.tagName === 'LI') { + var url = elem.getAttribute('data-url') || ''; + this.switchClarity(url).then(function () { + _this3.loadOption = undefined; + _Array$from$1(elem.parentElement.children).map(function (item) { + removeClassName(item, 'active'); + }); + addClassName(e.target, 'active'); + _this3.$text.text(e.target.textContent); + }).catch(function (e) { + console.warn(e); + }); + } + } + }, { + key: 'switchClarity', + value: function switchClarity(url) { + if (this.loadOption) { + this.loadOption.abort = true; + } + this.loadOption = { + duration: this.option.duration, + repeatTimes: 3, + immediate: true, + increment: this.option.increment + }; + return this.parent.$silentLoad(url, this.loadOption); + } + }]); + + return Clarity; +}(Base); + +function hundleChildren(plugin) { + var childConfig = {}; + if (!plugin.$config.children) { + childConfig = plugin.isLive ? { + play: true, // 底部播放暂停按钮 + progressTime: false, // 播放时间 + progressBar: false, // 播放进度控制条 + volume: true, // 声音控制 + screen: true // 全屏控制 + } : { + play: true, // 底部播放暂停按钮 + progressTime: true, // 播放时间 + progressBar: true, // 播放进度控制条 + volume: true, // 声音控制 + screen: true // 全屏控制 + }; + } else { + childConfig = plugin.$config.children; + } + + return childConfig; +} + +/** + * 1. 将所有的 ui component 输出到 html 结构中 + * 2. 为这些 component 绑定响应的事件 + * @param {*} dom 所有 ui 节点的子容器 + * @param {*} config 关于 ui 的一些列设置 + * @return {Array} 所有子节点 + */ + +function createChild(plugin) { + var childConfig = plugin.config.children = hundleChildren(plugin); + var children = {}; + if (!childConfig) { + children.play = new Play(plugin); + children.progressTime = new ProgressTime(plugin); + children.progressBar = new ProgressBar(plugin); + children.volume = new Volume(plugin); + children.screen = new Screen(plugin); + } else { + _Object$keys$1(childConfig).forEach(function (item) { + switch (item) { + case 'play': + if (childConfig.play) { + children.play = new Play(plugin, childConfig.play); + } + break; + case 'progressTime': + if (childConfig.progressTime) { + children.progressTime = new ProgressTime(plugin, childConfig.progressTime); + } + break; + case 'progressBar': + children.progressBar = new ProgressBar(plugin, childConfig.progressBar); + break; + case 'volume': + if (childConfig.volume) { + children.volume = new Volume(plugin, childConfig.volume); + } + break; + case 'screen': + if (childConfig.screen) { + children.screen = new Screen(plugin, childConfig.screen); + } + break; + case 'clarity': + if (childConfig.clarity && Array.isArray(childConfig.clarity.list)) { + children.clarity = new Clarity(plugin, childConfig.clarity); + } + break; + default: + children[item] = new Component(plugin, childConfig[item]); + break; + } + }); + } + + return children; +} + +var majorColorStyle = '\n .chimee-flex-component svg *{\n fill: majorColor;\n stroke: majorColor;\n }\n chimee-progressbar-all{\n background: majorColor;\n }\n chimee-volume.chimee-flex-component chimee-volume-bar-all{\n background: majorColor; \n }\n chimee-clarity-list li:hover,\n chimee-clarity-list li.active {\n color: majorColor;\n }\n'; + +var hoverColorStyle = '\n .chimee-flex-component svg:hover *{\n fill: hoverColor;\n stroke: hoverColor;\n }\n'; + +/** + * 插件默认配置 + */ + +var defaultConfig$1 = { + hideBarTime: 2000, // hidebar 延迟时间, barShowByMouse 为 move 时有效,enter 时为0, 用户设置无效 + barShowByMouse: 'move' // 控制条显示由, move 还是 enter/leave 来控制显示/隐藏 +}; + +var chimeeControl = { + name: 'chimeeControl', + el: 'chimee-control', + data: { + children: {}, + show: false, + disabled: true + }, + level: 99, + operable: false, + penetrate: false, + create: function create() {}, + init: function init(videoConfig) { + if (videoConfig.controls) { + this.show = true; + videoConfig.controls = false; + } + var _this = this; + applyDecorators(videoConfig, { + controls: accessor({ + get: function get() { + return _this.show; + }, + set: function set(value) { + _this.show = Boolean(value); + _this._display(); + return false; + } + }, { preSet: true }) + }, { self: true }); + this.config = isObject(this.$config) ? deepAssign(defaultConfig$1, this.$config) : defaultConfig$1; + + this.config.hideBarTime = this.config.barShowByMouse === 'move' ? this.config.hideBarTime : 0; + this.$dom.innerHTML = ''; + this.$wrap = this.$dom.querySelector('chimee-control-wrap'); + this.children = createChild(this); + this._setStyle(); + }, + destroy: function destroy() { + window.clearTimeout(this.timeId); + }, + inited: function inited() { + for (var i in this.children) { + this.children[i].inited && this.children[i].inited(); + } + }, + + events: { + loadstart: function loadstart() { + this._disable(true); + }, + canplay: function canplay() { + this._disable(false); + }, + play: function play() { + this.children.play && this.children.play.changeState('play'); + this.config.barShowByMouse === 'move' && this._hideItself(); + }, + pause: function pause() { + this.children.play && this.children.play.changeState('pause'); + this._showItself(); + }, + c_mouseenter: function c_mouseenter() { + if (this.config.barShowByMouse === 'move') return; + this._showItself(); + }, + c_mousemove: function c_mousemove() { + this._mousemove(); + }, + c_mouseleave: function c_mouseleave() { + if (this.config.barShowByMouse === 'move') return; + this._hideItself(); + }, + durationchange: function durationchange() { + this.children.progressTime && this.children.progressTime.updateTotal(); + }, + timeupdate: function timeupdate() { + this._progressUpdate(); + }, + progress: function progress() { + this.children.progressBar && this.children.progressBar.progress(); + }, + volumechange: function volumechange() { + this.children.volume && this.children.volume.update(); + }, + keydown: function keydown(e) { + if (this.disabled) return; + e.stopPropagation(); + switch (e.keyCode) { + case 32: + { + e.preventDefault(); + this.children.play && this.children.play.click(e); + break; + } + case 37: + { + e.preventDefault(); + var reduceTime = this.currentTime - 10; + this.currentTime = reduceTime < 0 ? 0 : reduceTime; + this._mousemove(); + break; + } + case 39: + { + e.preventDefault(); + var raiseTime = this.currentTime + 10; + this.currentTime = raiseTime > this.duration ? this.duration : raiseTime; + this._mousemove(); + break; + } + case 38: + { + e.preventDefault(); + var raiseVolume = this.volume + 0.1; + this.volume = raiseVolume > 1 ? 1 : raiseVolume; + this._mousemove(); + break; + } + case 40: + { + e.preventDefault(); + var reduceVolume = this.volume - 0.1; + this.volume = reduceVolume < 0 ? 0 : reduceVolume; + this._mousemove(); + break; + } + } + }, + click: function click(e) { + var _this2 = this; + + var time = new Date(); + var preTime = this.clickTime; + this.clickTime = time; + if (time - preTime < 300) { + clearTimeout(this.clickTimeId); + return; + } + this.clickTimeId = setTimeout(function () { + !_this2.disabled && _this2.children.play && _this2.children.play.click(e); + }, 300); + }, + dblclick: function dblclick(e) { + // this.dblclick = true; + !this.disabled && this.children.screen && this.children.screen.click(); + } + }, + methods: { + _progressUpdate: function _progressUpdate() { + this.children.progressBar && this.children.progressBar.update(); + this.children.progressTime && this.children.progressTime.updatePass(); + }, + _hideItself: function _hideItself() { + var _this3 = this; + + window.clearTimeout(this.timeId); + this.timeId = setTimeout(function () { + var bottom = _this3.$wrap.offsetHeight; + bottom = _this3.children.progressBar ? _this3.children.progressBar.$wrap[0].offsetTop - bottom : -bottom; + setStyle(_this3.$wrap, { + bottom: bottom + 'px' + }); + setStyle(_this3.$dom, { + visibility: 'hidden' + }); + }, this.config.hideBarTime); + }, + _showItself: function _showItself() { + window.clearTimeout(this.timeId); + setStyle(this.$wrap, { + bottom: '0' + }); + setStyle(this.$dom, { + visibility: 'visible' + }); + }, + _display: function _display() { + var display = this.show ? 'block' : 'none'; + setStyle(this.$dom, { + display: display + }); + }, + _mousemove: function _mousemove(e) { + if (this.paused || this.config.barShowByMouse === 'enter') return; + this._showItself(); + this._hideItself(); + }, + + // controlbar 不可以点 + // 键盘/鼠标事件不监听 + _disable: function _disable(disabled) { + if (!this.show) return; + this.disabled = disabled; + setStyle(this.$wrap, 'pointerEvents', disabled ? 'none' : 'auto'); + }, + _setStyle: function _setStyle() { + var css = ''; + css += this.config.majorColor ? majorColorStyle.replace(/majorColor/g, this.config.majorColor) : ''; + css += this.config.hoverColor ? hoverColorStyle.replace(/hoverColor/g, this.config.hoverColor) : ''; + var style = document.createElement('style'); + style.setAttribute('type', 'text/css'); + style.innerHTML = css; + document.head.appendChild(style); + } + } +}; + +/** + * chimee-plugin-popup v0.0.7 + * (c) 2017 huzunjie + * Released under MIT + */ + +function __$styleInject$1(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject$1("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}", undefined); + +/** + * 这里提供一个工厂方法,用于生产一个popup插件配置,或基于popup特性实现自己的插件 + * @param {Object} optons 针对popup扩展了定制化参数,另外也用来重写部分PluginConfig配置 + * @param {String} optons.name 插件名 + * @param {String} optons.tagName Popup DOM容器的tagName + * @param {String} optons.className Popup DOM容器的className + * @param {String} optons.title Popup 标题,当设置值为 false 则不渲染title对应DOM + * @param {String} optons.body Popup 内容,当设置值为 false 则不渲染body对应DOM + * @param {String} optons.html html 用于构架popup的模板,重写后上面的title、body无效 + * @param {String} optons.offset 设定相对播放器要展示的坐标位置,空格分割的坐标值:'X:left Y:top'||'top right bottom left', 具体的像素百分比值或者auto;实例化后可重写 popupplugin.offset('0 0 0 0') + * @param {String} optons.offsetAttr offset对应的CSS属性key,默认'left top'、'top right bottom left'-当offset空格分割的参数值多余2个时,便于只设定个别或特定方向边距 + * @param {String} optons.translate 在offset基础上的偏移量,格式如:"leftVal topVal",当offset为50%这里没设定值,则默认偏移-50%;实例化后可重写 popupplugin.translate('0 0') + * @param {String} optons.width 宽度值(需要带单位);实例化后可重写 popupplugin.width('100px') + * @param {String} optons.height 高度值(需要带单位);实例化后可重写 popupplugin.height('100px') + * @param {Boolean} optons.hide 初始状态是否设置为关闭,默认值 false + * @param {Function} optons.opened 开启时执行 + * @param {Function} optons.closed 关闭时执行 + * @param {Boolean} optons.penetrate 是否将交互事件同步到video元素(点击当前popup同样实现video的暂停播放),默认值 false + * @param {Boolean} optons.operable 是否启用事件交互(false则设置CSS事件穿透),默认值 true + * @return {PluginConfig} + */ +function popupFactory() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$tagName = _ref.tagName, + tagName = _ref$tagName === undefined ? 'chimee-popup' : _ref$tagName, + className = _ref.className, + _ref$name = _ref.name, + name = _ref$name === undefined ? 'popup' : _ref$name, + html = _ref.html, + _ref$title = _ref.title, + title = _ref$title === undefined ? '这是一个信息框' : _ref$title, + _ref$body = _ref.body, + body = _ref$body === undefined ? '这里是信息内容' : _ref$body, + _ref$offsetAttr = _ref.offsetAttr, + offsetAttr = _ref$offsetAttr === undefined ? 'left top' : _ref$offsetAttr, + _ref$offset = _ref.offset, + offset = _ref$offset === undefined ? '50% 50%' : _ref$offset, + _ref$translate = _ref.translate, + translate = _ref$translate === undefined ? '' : _ref$translate, + width = _ref.width, + height = _ref.height, + level = _ref.level, + init = _ref.init, + inited = _ref.inited, + data = _ref.data, + _create = _ref.create, + _beforeCreate = _ref.beforeCreate, + _destroy = _ref.destroy, + events = _ref.events, + computed = _ref.computed, + _ref$methods = _ref.methods, + methods = _ref$methods === undefined ? {} : _ref$methods, + _ref$penetrate = _ref.penetrate, + penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, + _ref$operable = _ref.operable, + operable = _ref$operable === undefined ? true : _ref$operable, + _ref$hide = _ref.hide, + hide = _ref$hide === undefined ? false : _ref$hide, + opened = _ref.opened, + closed = _ref.closed, + autoFocus = _ref.autoFocus; + + var defaultConfig = { + html: html || '\n \xD7\n ' + (title !== false ? '' + title + '' : '') + '\n ' + (body !== false ? '' + body + '' : '') + '\n ', + closeSelector: '._close' + }; + + return { + name: name, + el: tagName, + className: className, + beforeCreate: function beforeCreate() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + events = _ref2.events, + methods = _ref2.methods; + + var option = arguments[1]; + + if (isObject(option)) { + isObject(option.events) && deepAssign(events, option.events); + isObject(option.methods) && deepAssign(methods, option.methods); + } + _beforeCreate && _beforeCreate.apply(this, arguments); + }, + create: function create() { + + var config = isObject(this.$config) ? deepAssign(defaultConfig, this.$config) : defaultConfig; + var $dom = this.$domWrap = $(this.$dom).css('display', 'none'); + + $dom.html(config.html).delegate('cm-pp-close, ' + config.closeSelector, 'click', this.close); + + this.width(width).height(height).offset(offset).translate(translate); + + this._hide = hide; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _create && _create.apply(this, args); + !this._hide && this.open(); + }, + destroy: function destroy() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + _destroy && _destroy.apply(this, args); + this.$domWrap.undelegate(this.$config.closeSelector, 'click', this.close).remove(); + }, + + level: level, + init: init, + inited: inited, + data: data, + events: events, + computed: computed, + penetrate: penetrate, + operable: operable, + autoFocus: autoFocus, + methods: deepAssign({ + open: function open() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'block'); + this._hide = false; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this.$emit('popupOpen', args, this); + isFunction(opened) && opened.apply(this, args); + return this; + }, + close: function close() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'none'); + this._hide = true; + + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + this.$emit('popupClose', args, this); + isFunction(closed) && closed.apply(this, args); + return this; + }, + width: function width(_width) { + _width && this.$domWrap.css('width', _width); + return this; + }, + height: function height(_height) { + _height && this.$domWrap.css('height', _height); + return this; + }, + offset: function offset(vals) { + var trblArr = ('' + (vals || '')).split(' '); + var cssObj = {}; + if (trblArr.length > 2) { + ['top', 'right', 'bottom', 'left'].forEach(function (dir, i) { + if (trblArr[i]) { + cssObj[dir] = trblArr[i]; + } + }); + this.$domWrap.css(cssObj); + return this; + } + + var _trblArr = _slicedToArray(trblArr, 2), + left = _trblArr[0], + _top = _trblArr[1]; + + if (left === '') { + return this; + } + var top = _top || left; + var xyAttr = offsetAttr.split(' '); + cssObj[xyAttr[0]] = left; + cssObj[xyAttr[1]] = top; + this.$domWrap.css(cssObj); + + var translateXY = []; + if (left === '50%') { + translateXY.push('-50%'); + } + if (top === '50%') { + translateXY.push('-50%'); + } + translateXY.length > 0 && this.translate(translateXY.join(' ')); + return this; + }, + translate: function translate(xy) { + var _$split = ('' + (xy || '')).split(' '), + _$split2 = _slicedToArray(_$split, 2), + x = _$split2[0], + y = _$split2[1]; + + if (x !== '') { + this.$domWrap.css('transform', 'translate(' + x + ', ' + (y || x) + ')'); + if (!('transform' in document.createElement('a').style) && window.console && window.console.warn) { + console.warn('[chimee-plugin-popup] 当前环境不支持CSS3的transform特性,Dom元素无法正常使用translate。'); + } + } + return this; + } + }, methods) + }; +} + +/** + * chimee-plugin-popup v0.0.5 + * (c) 2017 huzunjie + * Released under MIT + */ + +function __$styleInject$2(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject$2("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}", undefined); + +/** + * 这里提供一个工厂方法,用于生产一个popup插件配置,或基于popup特性实现自己的插件 + * @param {Object} optons 针对popup扩展了定制化参数,另外也用来重写部分PluginConfig配置 + * @param {String} optons.name 插件名 + * @param {String} optons.tagName Popup DOM容器的tagName + * @param {String} optons.className Popup DOM容器的className + * @param {String} optons.title Popup 标题,当设置值为 false 则不渲染title对应DOM + * @param {String} optons.body Popup 内容,当设置值为 false 则不渲染body对应DOM + * @param {String} optons.html html 用于构架popup的模板,重写后上面的title、body无效 + * @param {String} optons.offset 设定相对播放器要展示的坐标位置,空格分割的坐标值:'X:left Y:top'||'top right bottom left', 具体的像素百分比值或者auto;实例化后可重写 popupplugin.offset('0 0 0 0') + * @param {String} optons.offsetAttr offset对应的CSS属性key,默认'left top'、'top right bottom left'-当offset空格分割的参数值多余2个时,便于只设定个别或特定方向边距 + * @param {String} optons.translate 在offset基础上的偏移量,格式如:"leftVal topVal",当offset为50%这里没设定值,则默认偏移-50%;实例化后可重写 popupplugin.translate('0 0') + * @param {String} optons.width 宽度值(需要带单位);实例化后可重写 popupplugin.width('100px') + * @param {String} optons.height 高度值(需要带单位);实例化后可重写 popupplugin.height('100px') + * @param {Boolean} optons.hide 初始状态是否设置为关闭,默认值 false + * @param {Function} optons.opened 开启时执行 + * @param {Function} optons.closed 关闭时执行 + * @param {Boolean} optons.penetrate 是否将交互事件同步到video元素(点击当前popup同样实现video的暂停播放),默认值 false + * @param {Boolean} optons.operable 是否启用事件交互(false则设置CSS事件穿透),默认值 true + * @return {PluginConfig} + */ +function popupFactory$1() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$tagName = _ref.tagName, + tagName = _ref$tagName === undefined ? 'chimee-popup' : _ref$tagName, + className = _ref.className, + _ref$name = _ref.name, + name = _ref$name === undefined ? 'popup' : _ref$name, + html = _ref.html, + _ref$title = _ref.title, + title = _ref$title === undefined ? '这是一个信息框' : _ref$title, + _ref$body = _ref.body, + body = _ref$body === undefined ? '这里是信息内容' : _ref$body, + _ref$offsetAttr = _ref.offsetAttr, + offsetAttr = _ref$offsetAttr === undefined ? 'left top' : _ref$offsetAttr, + _ref$offset = _ref.offset, + offset = _ref$offset === undefined ? '50% 50%' : _ref$offset, + _ref$translate = _ref.translate, + translate = _ref$translate === undefined ? '' : _ref$translate, + width = _ref.width, + height = _ref.height, + level = _ref.level, + init = _ref.init, + inited = _ref.inited, + data = _ref.data, + _create = _ref.create, + _beforeCreate = _ref.beforeCreate, + _destroy = _ref.destroy, + events = _ref.events, + computed = _ref.computed, + _ref$methods = _ref.methods, + methods = _ref$methods === undefined ? {} : _ref$methods, + _ref$penetrate = _ref.penetrate, + penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, + _ref$operable = _ref.operable, + operable = _ref$operable === undefined ? true : _ref$operable, + _ref$hide = _ref.hide, + hide = _ref$hide === undefined ? false : _ref$hide, + opened = _ref.opened, + closed = _ref.closed, + autoFocus = _ref.autoFocus; + + var defaultConfig = { + html: html || '\n \xD7\n ' + (title !== false ? '' + title + '' : '') + '\n ' + (body !== false ? '' + body + '' : '') + '\n ', + closeSelector: '._close' + }; + + return { + name: name, + el: tagName, + className: className, + beforeCreate: function beforeCreate() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + events = _ref2.events, + methods = _ref2.methods; + + var option = arguments[1]; + + if (isObject(option)) { + isObject(option.events) && deepAssign(events, option.events); + isObject(option.methods) && deepAssign(methods, option.methods); + } + _beforeCreate && _beforeCreate.apply(this, arguments); + }, + create: function create() { + + var config = isObject(this.$config) ? deepAssign(defaultConfig, this.$config) : defaultConfig; + var $dom = this.$domWrap = $(this.$dom).css('display', 'none'); + + $dom.html(config.html).delegate('cm-pp-close, ' + config.closeSelector, 'click', this.close); + + this.width(width).height(height).offset(offset).translate(translate); + + this._hide = hide; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _create && _create.apply(this, args); + !this._hide && this.open(); + }, + destroy: function destroy() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + _destroy && _destroy.apply(this, args); + this.$domWrap.undelegate(this.$config.closeSelector, 'click', this.close).remove(); + }, + + level: level, + init: init, + inited: inited, + data: data, + events: events, + computed: computed, + penetrate: penetrate, + operable: operable, + autoFocus: autoFocus, + methods: deepAssign({ + open: function open() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'block'); + this._hide = false; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this.$emit('popupOpen', args, this); + isFunction(opened) && opened.apply(this, args); + return this; + }, + close: function close() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'none'); + this._hide = true; + + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + this.$emit('popupClose', args, this); + isFunction(closed) && closed.apply(this, args); + return this; + }, + width: function width(_width) { + _width && this.$domWrap.css('width', _width); + return this; + }, + height: function height(_height) { + _height && this.$domWrap.css('height', _height); + return this; + }, + offset: function offset(vals) { + var trblArr = ('' + (vals || '')).split(' '); + var cssObj = {}; + if (trblArr.length > 2) { + ['top', 'right', 'bottom', 'left'].forEach(function (dir, i) { + if (trblArr[i] && trblArr[i] !== 'auto') { + cssObj[dir] = trblArr[i]; + } + }); + this.$domWrap.css(cssObj); + return this; + } + + var _trblArr = _slicedToArray(trblArr, 2), + left = _trblArr[0], + _top = _trblArr[1]; + + if (left === '') { + return this; + } + var top = _top || left; + var xyAttr = offsetAttr.split(' '); + cssObj[xyAttr[0]] = left; + cssObj[xyAttr[1]] = top; + this.$domWrap.css(cssObj); + + var translateXY = []; + if (left === '50%') { + translateXY.push('-50%'); + } + if (top === '50%') { + translateXY.push('-50%'); + } + translateXY.length > 0 && this.translate(translateXY.join(' ')); + return this; + }, + translate: function translate(xy) { + var _$split = ('' + (xy || '')).split(' '), + _$split2 = _slicedToArray(_$split, 2), + x = _$split2[0], + y = _$split2[1]; + + x && this.$domWrap.css('transform', 'translate(' + x + ', ' + (y || x) + ')'); + return this; + } + }, methods) + }; +} + +/** chimeePluginContextmenu + * chimee-plugin-contextmenu v0.1.2 + * (c) 2017 huzunjie + * Released under ISC + */ + +function __$styleInject$3(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject$3("chimee-menu{position:absolute;color:#fff;background-color:rgba(37,37,37,.7);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);border-radius:2px;padding:2px;box-shadow:0 1px 4px rgba(0,0,0,.6)}chimee-menu ul{margin:0;padding:0;font-size:12px}chimee-menu li{cursor:pointer;padding:0 4px;line-height:24px;list-style:none;white-space:nowrap;margin:0;border:0;font-size:12px;font-weight:400}chimee-menu li:hover{background-color:hsla(0,0%,100%,.1)}chimee-menu li[disable]{opacity:.5;cursor:default}chimee-menu li a{color:#fff;text-decoration:none}chimee-menu li a:hover{color:#fff}", undefined); + +var logPopupOpenEvt = 'openLogPopup'; +/* 右键菜单插件 + * 接收参数:baseMenus, menus + * 也可通过方法 updatemenu 更新自定义菜单项 + */ +var contextmenuConf = popupFactory$1({ + tagName: 'chimee-menu', + name: 'chimeeContextmenu', + html: '
      ', + offset: '0', + hide: true, + data: { + // 默认菜单项 + baseMenus: [{ + text: '查看日志', + action: logPopupOpenEvt, + hide: true + }, { + text: 'Chimee {VERSION} © 360', + url: 'http://chimee.org', + disable: true /* , + { + text: '关闭', + className: '_close' + }*/ + }] + }, + create: function create() { + var _this = this; + + var _$config = this.$config, + baseMenus = _$config.baseMenus, + menus = _$config.menus; + + if (isArray(baseMenus)) { + this.baseMenus = baseMenus; + } + this.updatemenu(menus); + this.$domWrap.on('click', this.clickHandler); + // 如果已装载日志插件,则显示相应菜单项 + if (this.$plugins.chimeeLog) { + this.switchLogMenu(false); + } + // 点击播放器之外的文档区域关闭右键菜单 + this._doc = new this.$domWrap.constructor(document); + this._doc_click = function (e) { + return _this.close(); + }; + this._doc.on('click', this._doc_click); + }, + destroy: function destroy() { + this._doc.off('click', this._doc_click); + }, + opened: function opened() { + // 盖住所有插件 + this.$bumpToTop(); + }, + + events: { + contextmenu: function contextmenu(e) { + var left = e.offsetX; + var top = e.offsetY; + var containerEl = this.$dom.parentElement; + if (isFunction(containerEl.getBoundingClientRect)) { + var rect = containerEl.getBoundingClientRect(); + left = e.pageX - rect.left - (document.documentElement.scrollLeft || document.body.scrollLeft || 0); + top = e.pageY - rect.top - (document.documentElement.scrollTop || document.body.scrollTop || 0); + } + this.offset(left + 'px ' + top + 'px').open(e); + e.preventDefault(); + }, + + // 当日志插件卸载时隐藏“查看日志”菜单项 + logPluginDestroy: function logPluginDestroy() { + this.switchLogMenu(true); + }, + + // 当日志插件状态完毕显示“查看日志”菜单项 + logPluginCreate: function logPluginCreate() { + this.switchLogMenu(false); + } + }, + methods: { + switchLogMenu: function switchLogMenu(hide) { + var logMenuConf = this.baseMenus.find(function (item) { + return item.action === logPopupOpenEvt; + }); + if (logMenuConf) { + logMenuConf.hide = hide; + this.$domWrap.find('[data-action="' + logPopupOpenEvt + '"]').css('display', hide ? 'none' : ''); + } + }, + updatemenu: function updatemenu(menusConfig) { + var _this2 = this; + + var menus = []; + if (isArray(menusConfig)) { + menus = menus.concat(menusConfig); + } + // 菜单模板编译 + var meunsHTML = menus.concat(this.baseMenus).map(function (_ref) { + var hide = _ref.hide, + disable = _ref.disable, + action = _ref.action, + className = _ref.className, + text = _ref.text, + url = _ref.url; + + var attrDis = disable ? 'disable' : ''; + var dataAct = action ? 'data-action="' + action + '"' : ''; + var clsAttr = className ? 'class="' + className + '"' : ''; + var hideSty = hide ? 'style="display:none"' : ''; + // 文本替换,使之支持 {VERSION} 的变量写法 + var innText = text.replace(/\{([^)]*)\}/g, function (_, matchStr) { + return _this2[matchStr]; + }); + if (url) { + innText = '' + innText + ''; + } + return '
    • ' + innText + '
    • '; + }).join(''); + + // 输出菜单DOM + this.$domWrap.find('ul').html(meunsHTML); + }, + clickHandler: function clickHandler(e) { + var el = e.target; + if (!el.disable) { + var act = el.dataset.action; + if (act) { + // 抛出右键项点击对应事件给全局 + this.$emit(act); + isFunction(this[act]) && this[act](e); + } + this.close(); + } + e.stopPropagation(); + } + } +}); + +/** + * chimee-plugin-popup v0.0.5 + * (c) 2017 huzunjie + * Released under MIT + */ + +function __$styleInject$4(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject$4("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}", undefined); + +/** + * 这里提供一个工厂方法,用于生产一个popup插件配置,或基于popup特性实现自己的插件 + * @param {Object} optons 针对popup扩展了定制化参数,另外也用来重写部分PluginConfig配置 + * @param {String} optons.name 插件名 + * @param {String} optons.tagName Popup DOM容器的tagName + * @param {String} optons.className Popup DOM容器的className + * @param {String} optons.title Popup 标题,当设置值为 false 则不渲染title对应DOM + * @param {String} optons.body Popup 内容,当设置值为 false 则不渲染body对应DOM + * @param {String} optons.html html 用于构架popup的模板,重写后上面的title、body无效 + * @param {String} optons.offset 设定相对播放器要展示的坐标位置,空格分割的坐标值:'X:left Y:top'||'top right bottom left', 具体的像素百分比值或者auto;实例化后可重写 popupplugin.offset('0 0 0 0') + * @param {String} optons.offsetAttr offset对应的CSS属性key,默认'left top'、'top right bottom left'-当offset空格分割的参数值多余2个时,便于只设定个别或特定方向边距 + * @param {String} optons.translate 在offset基础上的偏移量,格式如:"leftVal topVal",当offset为50%这里没设定值,则默认偏移-50%;实例化后可重写 popupplugin.translate('0 0') + * @param {String} optons.width 宽度值(需要带单位);实例化后可重写 popupplugin.width('100px') + * @param {String} optons.height 高度值(需要带单位);实例化后可重写 popupplugin.height('100px') + * @param {Boolean} optons.hide 初始状态是否设置为关闭,默认值 false + * @param {Function} optons.opened 开启时执行 + * @param {Function} optons.closed 关闭时执行 + * @param {Boolean} optons.penetrate 是否将交互事件同步到video元素(点击当前popup同样实现video的暂停播放),默认值 false + * @param {Boolean} optons.operable 是否启用事件交互(false则设置CSS事件穿透),默认值 true + * @return {PluginConfig} + */ +function popupFactory$2() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$tagName = _ref.tagName, + tagName = _ref$tagName === undefined ? 'chimee-popup' : _ref$tagName, + className = _ref.className, + _ref$name = _ref.name, + name = _ref$name === undefined ? 'popup' : _ref$name, + html = _ref.html, + _ref$title = _ref.title, + title = _ref$title === undefined ? '这是一个信息框' : _ref$title, + _ref$body = _ref.body, + body = _ref$body === undefined ? '这里是信息内容' : _ref$body, + _ref$offsetAttr = _ref.offsetAttr, + offsetAttr = _ref$offsetAttr === undefined ? 'left top' : _ref$offsetAttr, + _ref$offset = _ref.offset, + offset = _ref$offset === undefined ? '50% 50%' : _ref$offset, + _ref$translate = _ref.translate, + translate = _ref$translate === undefined ? '' : _ref$translate, + width = _ref.width, + height = _ref.height, + level = _ref.level, + init = _ref.init, + inited = _ref.inited, + data = _ref.data, + _create = _ref.create, + _beforeCreate = _ref.beforeCreate, + _destroy = _ref.destroy, + events = _ref.events, + computed = _ref.computed, + _ref$methods = _ref.methods, + methods = _ref$methods === undefined ? {} : _ref$methods, + _ref$penetrate = _ref.penetrate, + penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, + _ref$operable = _ref.operable, + operable = _ref$operable === undefined ? true : _ref$operable, + _ref$hide = _ref.hide, + hide = _ref$hide === undefined ? false : _ref$hide, + opened = _ref.opened, + closed = _ref.closed, + autoFocus = _ref.autoFocus; + + var defaultConfig = { + html: html || '\n \xD7\n ' + (title !== false ? '' + title + '' : '') + '\n ' + (body !== false ? '' + body + '' : '') + '\n ', + closeSelector: '._close' + }; + + return { + name: name, + el: tagName, + className: className, + beforeCreate: function beforeCreate() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + events = _ref2.events, + methods = _ref2.methods; + + var option = arguments[1]; + + if (isObject(option)) { + isObject(option.events) && deepAssign(events, option.events); + isObject(option.methods) && deepAssign(methods, option.methods); + } + _beforeCreate && _beforeCreate.apply(this, arguments); + }, + create: function create() { + + var config = isObject(this.$config) ? deepAssign(defaultConfig, this.$config) : defaultConfig; + var $dom = this.$domWrap = $(this.$dom).css('display', 'none'); + + $dom.html(config.html).delegate('cm-pp-close, ' + config.closeSelector, 'click', this.close); + + this.width(width).height(height).offset(offset).translate(translate); + + this._hide = hide; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _create && _create.apply(this, args); + !this._hide && this.open(); + }, + destroy: function destroy() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + _destroy && _destroy.apply(this, args); + this.$domWrap.undelegate(this.$config.closeSelector, 'click', this.close).remove(); + }, + + level: level, + init: init, + inited: inited, + data: data, + events: events, + computed: computed, + penetrate: penetrate, + operable: operable, + autoFocus: autoFocus, + methods: deepAssign({ + open: function open() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'block'); + this._hide = false; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this.$emit('popupOpen', args, this); + isFunction(opened) && opened.apply(this, args); + return this; + }, + close: function close() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'none'); + this._hide = true; + + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + this.$emit('popupClose', args, this); + isFunction(closed) && closed.apply(this, args); + return this; + }, + width: function width(_width) { + _width && this.$domWrap.css('width', _width); + return this; + }, + height: function height(_height) { + _height && this.$domWrap.css('height', _height); + return this; + }, + offset: function offset(vals) { + var trblArr = ('' + (vals || '')).split(' '); + var cssObj = {}; + if (trblArr.length > 2) { + ['top', 'right', 'bottom', 'left'].forEach(function (dir, i) { + if (trblArr[i] && trblArr[i] !== 'auto') { + cssObj[dir] = trblArr[i]; + } + }); + this.$domWrap.css(cssObj); + return this; + } + + var _trblArr = _slicedToArray(trblArr, 2), + left = _trblArr[0], + _top = _trblArr[1]; + + if (left === '') { + return this; + } + var top = _top || left; + var xyAttr = offsetAttr.split(' '); + cssObj[xyAttr[0]] = left; + cssObj[xyAttr[1]] = top; + this.$domWrap.css(cssObj); + + var translateXY = []; + if (left === '50%') { + translateXY.push('-50%'); + } + if (top === '50%') { + translateXY.push('-50%'); + } + translateXY.length > 0 && this.translate(translateXY.join(' ')); + return this; + }, + translate: function translate(xy) { + var _$split = ('' + (xy || '')).split(' '), + _$split2 = _slicedToArray(_$split, 2), + x = _$split2[0], + y = _$split2[1]; + + x && this.$domWrap.css('transform', 'translate(' + x + ', ' + (y || x) + ')'); + return this; + } + }, methods) + }; +} + +/** + * chimee-plugin-log v0.0.4 + * (c) 2017 huzunjie + * Released under MIT + */ + +function __$styleInject$5(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject$5(".chimee-log{padding:2px;box-shadow:0 1px 4px rgba(0,0,0,.6)}.chimee-log label{margin-left:10px;font-weight:100;font-size:12px}.chimee-log label input{vertical-align:middle;display:inline;width:auto;padding:0;margin:0}.chimee-log vs-pp-body{padding:3px}.chimee-log textarea{display:block;width:100%;height:200px;margin:-3px;border:1px solid hsla(0,0%,100%,.5);background-color:hsla(0,0%,100%,.9)}", undefined); + +/** 日志插件(可以在实例化播放器时,通过重置部分参数,达成相应业务需求) + * @param {String} logPostUrl 打点上报地址,默认为 undefined ,如果传入则将日志上报到该地址 + * @param {Object} events 可以重置事件绑定,自定义日志时机,也可以通过 methods 的 write_eventName_log或send_eventName_log 来进行输出或上报日志数据加工 +*/ + +// 存储页面开启时间,测试本地存储兼容性 +var pageLoadedTimestamp = new Date().getTime().toString(); +setLocalStorage('_chimee_t', pageLoadedTimestamp); +var supportLS = getLocalStorage('_chimee_t') === pageLoadedTimestamp; + +// 为日志相关事件实现基本的日志输出绑定 +var defaultEvents = function () { + for (var _len = arguments.length, evs = Array(_len), _key = 0; _key < _len; _key++) { + evs[_key] = arguments[_key]; + } + + var rets = {}; + evs.forEach(function (evType) { + rets[evType] = function (e) { + var _this = this; + + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + this.writeLog(e); + // 打点 + var box = this.box, + type = this.type, + src = this.src; + var waitingNum = this._waiting_num, + currentTime = this.currentTime, + _is_seek = this._is_seek, + isSeek = _is_seek === undefined ? false : _is_seek, + _is_play = this._is_play, + isPlay = _is_play === undefined ? false : _is_play, + playingTimestamp = this.playingTimestamp, + loadstartTimestamp = this.loadstartTimestamp, + waitingTimestamp = this.waitingTimestamp; + + switch (evType) { + case 'loadstart': + this.sendLog(evType, { box: box, type: type, src: src }); + // 30秒后没加载完毕则认为超时 + this._ls_timeout = setTimeout(function () { + _this.sendLog('timeout', { src: src }); + }, this.timeoutDelay); + this._total_waiting_time = 0; + break; + case 'seeking': + this._is_seek = true; + break; + case 'play': + this._is_play = true; + break; + case 'pause': + this.sendLog(evType, { src: src, currentTime: currentTime }); + break; + case 'canplay': + clearTimeout(this._ls_timeout); + var canplayTime = this.canplayTimestamp; + this.sendLog(evType, { src: src, currentTime: currentTime, waitingNum: waitingNum, waitingTime: canplayTime - (loadstartTimestamp || waitingTimestamp || canplayTime) }); + break; + case 'playing': + clearTimeout(this._ls_timeout); + var waitingTime = playingTimestamp - (loadstartTimestamp || waitingTimestamp || playingTimestamp); + this._total_waiting_time += waitingTime; + this.sendLog(evType, { + src: src, + // 等待次数,0 为首次加载 + waitingNum: waitingNum, + // 通过 currentTime 位置 + currentTime: currentTime, + // 是否seek导致的缓冲 + isSeek: isSeek, + isPlay: isPlay, + // 等待时长 + waitingTime: waitingTime + }); + this.loadstartTimestamp = 0; + this.waitingTimestamp = 0; + this._is_seek = false; + this._is_play = false; + break; + case 'ended': + this.sendLog(evType, { src: src, waitingNum: waitingNum, totalWaitingTime: this._total_waiting_time }); + break; + case 'waiting': + this._waiting_num++; + this.sendLog(evType, { + src: src, + waitingNum: waitingNum, + currentTime: currentTime, + // 是否seek导致的缓冲 + isSeek: isSeek, + isPlay: isPlay + }); + break; + case 'error': + this.sendLog(evType, { src: src, args: args }); + break; + } + }; + }); + return rets; +}('loadstart', // 客户端开始请求数据 +'abort', // 用户主动终止下载 +'durationchange', // 视频时长变化(video通过metadata拿到长度值 this.duration) +'loadedmetadata', // 播放器获取到metadata +'loadeddata', // 首帧加载完毕 +'progress', // 正在下载数据 +'canplay', // 可播放的,缓冲未必充分 +'canplaythrough', // 缓冲足够,可以播放了 +'pause', // 暂停 +'play', // 播放 +'playing', // 已切换到播放状态 +'emptied', // 媒体列表为空 +'ended', // 媒体列表播放完毕 +'seeking', // 播放位置跳转,寻找关键帧中 +'seeked', // 关键帧寻找完毕 +'stalled', // 浏览器尝试获取媒体数据,但数据不可用 +'suspend', // 当浏览器刻意不获取媒体数据时(比如播放中video被销毁) +'timeupdate', // 播放的进度变化 this.currentTime +'waiting', // 等待下一帧缓冲 +'error' // 异常 +); + +// 生产log组件对应的 PluginConfig +var index$1 = popupFactory$2({ + name: 'chimeeLog', + className: 'chimee-log', + title: '日志信息' + (supportLS ? '' : ''), + body: '', + offset: '0', + width: '400px', + hide: true, + autoFocus: false, + logPostUrl: undefined, // 日志上报地址,不填写则不上报 + beforeCreate: function beforeCreate(_, option) { + if (isUrl(option.logPostUrl)) { + this.logPostUrl = option.logPostUrl; + } + if (option.timeoutDelay) { + this.timeoutDelay = option.timeoutDelay; + } + }, + create: function create() { + this.logBase.ver = this.VERSION; + var $wrap = this.$domWrap; + this.$txtEl = $wrap.find('textarea'); + // 如果当前环境支持本地存储,则给予用户记住打开状态的复选框 + if (supportLS) { + var lsKey = 'auto_on'; + // 下次自动打开日志展示窗口 + var autoOn = getLocalStorage(lsKey) === '1'; + $wrap.find('input[type="checkbox"]').on('change', function (e) { + setLocalStorage(lsKey, +this.checked); + })[0].checked = autoOn; + // 告诉父组件是否create后开启 + this._hide = !autoOn; + } + this.writeLog({ type: 'ready' }); + this.$emitSync('logPluginCreate'); + }, + destroy: function destroy() { + clearTimeout(this._ls_timeout); + this.$emitSync('logPluginDestroy'); + this.sendLog('destroy'); + }, + + // 播放器初始化完毕 + inited: function inited() { + // this.writeLog({type: 'inited'}); + // this.sendLog('inited'); + }, + closed: function closed() { + this.$txtEl.text(''); + }, + opened: function opened() { + this.$bumpToTop(); + }, + + methods: { + writeLog: function writeLog(event) { + var logName = event.type; + // 记录事件发生的时间戳 + this[logName + 'Timestamp'] = +new Date(); + + // 模态窗为隐藏状态则停止输出 + if (this._hide) return; + + var logData = void 0; + var logWriteFunName = 'write_' + logName + '_log'; + if (this[logWriteFunName]) { + for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + + logData = this[logWriteFunName](logName, args); + } + var logText = this.$txtEl.text() + '\n[' + formatDate(new Date(this[logName + 'Timestamp']), 'yyyy-MM-dd hh:mm:ss.i') + '] ' + logName + ' ' + (logData !== undefined ? _JSON$stringify(logData) : ''); + var txtEl = this.$txtEl.text(logText)[0]; + txtEl.scrollTop = txtEl.scrollHeight; + }, + + // 定义loadstart要打印出的日志信息 + write_loadstart_log: function write_loadstart_log(logName) { + var box = this.box, + type = this.type, + src = this.src; + + return { box: box, type: type, src: src }; + }, + + // 定义loadstart要打印出的日志信息 + write_durationchange_log: function write_durationchange_log() { + var duration = this.duration; + return { duration: duration }; + }, + + // 定义loadstart要打印出的日志信息 + write_timeupdate_log: function write_timeupdate_log() { + var currentTime = this.currentTime; + return { currentTime: currentTime }; + }, + + + // 得到 inited 时要上报的日志 + send_inited_log: function send_inited_log() { + /* chimee 构建: + pro - protocol + box - box + type - type + src - src + uid - cookie + ver - chimee 版本 + _t - 时间戳 + _r - 随机数 + */ + var box = this.box, + type = this.type, + src = this.src, + ctrs = this.controls, + loop = this.loop; + + return { pro: location.protocol, box: box, type: type, src: src, ctrs: ctrs, loop: loop }; + }, + + + // 发送日志到服务端 + sendLog: function sendLog(logType, data) { + var logPostUrl = this.logPostUrl; + // 未设置上报地址则什么也不干 + if (!logPostUrl) return; + var logData = deepAssign(data || {}, this.logBase); + + var logParseFunName = 'send_' + logType + '_log'; + if (this[logParseFunName]) { + deepAssign(logData, this[logParseFunName](logType, logData)); + } + deepAssign(logData, { + evt: logType, + _t: +new Date(), + _r: Math.random() + }); + // console.log(logType, ' logData:', logData); + var logQuerys = []; + _Object$keys(logData).forEach(function (key) { + return logQuerys.push(encodeURIComponent(key) + '=' + encodeURIComponent(logData[key])); + }); + + // 上报打点 + var img = new Image(); + img.onload = img.onerror = function (e) { + img = null; + }; + img.src = logPostUrl + '?' + logQuerys.join('&'); + } + }, + events: deepAssign(defaultEvents, { + openLogPopup: function openLogPopup() { + this.open(); + } + }), + // 以下为日志上报处理相关逻辑 + data: { + timeoutDelay: 3e4, + pageLoadedTimestamp: pageLoadedTimestamp, + // 缓冲次数 + _waiting_num: 0, + _total_waiting_time: 0, + logBase: { + uid: function (uid) { + if (!uid) { + uid = uuid(); + setLocalStorage('_chimee_uid', uid); + } + return uid; + }(getLocalStorage('_chimee_uid')), + ref: location.href + } + }, + computed: { + type: function type() { + return this.$videoConfig.isLive ? 'live' : 'vod'; + } + } +}); + +/** + * the handler to generate an deep traversal handler + * @param {Function} fn the function you wanna run when you reach in the deep property + * @return {Function} the handler + */ +function genTraversalHandler$2(fn) { + function recursiveFn(source, target, key) { + if (isArray(source) || isObject(source)) { + target = isPrimitive(target) ? isObject(source) ? {} : [] : target; + for (var _key in source) { + // $FlowFixMe: support computed key here + target[_key] = recursiveFn(source[_key], target[_key], _key); + } + return target; + } + return fn(source, target, key); + } + return recursiveFn; +} +var _deepAssign$2 = genTraversalHandler$2(function (val) { + return val; +}); +/** + * deeply clone an object + * @param {Array|Object} source if you pass in other type, it will throw an error + * @return {clone-target} the new Object + */ +function deepClone$2(source) { + if (isPrimitive(source)) { + throw new TypeError('deepClone only accept non primitive type'); + } + return _deepAssign$2(source); +} +/** + * merge multiple objects + * @param {...Object} args [description] + * @return {merge-object} [description] + */ +function deepAssign$2() { + for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { + args[_key2] = arguments[_key2]; + } + + if (args.length < 2) { + throw new Error('deepAssign accept two and more argument'); + } + for (var i = args.length - 1; i > -1; i--) { + if (isPrimitive(args[i])) { + throw new TypeError('deepAssign only accept non primitive type'); + } + } + var target = args.shift(); + args.forEach(function (source) { + return _deepAssign$2(source, target); + }); + return target; +} + +/** + * camelize any string, e.g hello world -> helloWorld + * @param {string} str only accept string! + * @return {string} camelize string + */ +function camelize$2(str, isBig) { + return str.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g, function (match, spilt, initials, index) { + return !isBig && index === 0 ? initials.toLowerCase() : initials.toUpperCase(); + }); +} +/** + * hypenate any string e.g hello world -> hello-world + * @param {string} str only accept string + * @return {string} + */ +function hypenate$2(str) { + return camelize$2(str).replace(/([A-Z])/g, function (match) { + return '-' + match.toLowerCase(); + }); +} + +/** + * bind the function with some context. we have some fallback strategy here + * @param {function} fn the function which we need to bind the context on + * @param {any} context the context object + */ +function bind$3(fn, context) { + if (fn.bind) { + return fn.bind(context); + } else if (fn.apply) { + return function __autobind__() { + for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { + args[_key3] = arguments[_key3]; + } + + return fn.apply(context, args); + }; + } else { + return function __autobind__() { + for (var _len3 = arguments.length, args = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { + args[_key4] = arguments[_key4]; + } + + return fn.call.apply(fn, [context].concat(_toConsumableArray(args))); + }; + } +} + +/** + * generate an uuid + */ +function uuid$2() { + return S4$2() + S4$2() + '-' + S4$2() + '-' + S4$2() + '-' + S4$2() + '-' + S4$2() + S4$2() + S4$2(); +} +/** + * generate an random number which length is 4 + */ +function S4$2() { + return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1); +} + +/** + * generate an random number with specific length + */ +function rand$2(length) { + var str = ''; + while (str.length < length) { + str += S4$2(); + } + return str.slice(0, length); +} + +/** + * get an deep property + */ +function getDeepProperty$2(obj, keys) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$throwError = _ref.throwError, + throwError = _ref$throwError === undefined ? false : _ref$throwError, + backup = _ref.backup; + + if (isString(keys)) { + keys = keys.split('.'); + } + if (!isArray(keys)) { + throw new TypeError('keys of getDeepProperty must be string or Array'); + } + var read = []; + var target = obj; + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + if (isVoid(target)) { + if (throwError) { + throw new Error('obj' + (read.length > 0 ? '.' + read.join('.') : ' itself') + ' is ' + target); + } else { + return backup; + } + } + target = target[key]; + read.push(key); + } + return target; +} + +// ********************** judgement ************************ +/** + * check if the code running in browser environment (not include worker env) + * @returns {Boolean} + */ +var inBrowser$1 = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; + +// ********************** 对象操作 ************************ +/** + * 转变一个类数组对象为数组 + */ +function makeArray$1(obj) { + return _Array$from(obj); +} + +/** + * sort Object attributes by function + * and transfer them into array + * @param {Object} obj Object form from numric + * @param {Function} fn sort function + * @return {Array} the sorted attirbutes array + */ +function transObjectAttrIntoArray$1(obj) { + var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) { + return +a - +b; + }; + + return _Object$keys(obj).sort(fn).reduce(function (order, key) { + return order.concat(obj[key]); + }, []); +} +/** + * run a queue one by one.If include function reject or return false it will stop + * @param {Array} queue the queue which we want to run one by one + * @return {Promise} tell us whether a queue run finished + */ +function runRejectableQueue$1(queue) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + return new _Promise(function (resolve, reject) { + var step = function step(index) { + if (index >= queue.length) { + resolve(); + return; + } + var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; + if (result === false) return reject('stop'); + return _Promise.resolve(result).then(function () { + return step(index + 1); + }).catch(function (err) { + return reject(err || 'stop'); + }); + }; + step(0); + }); +} +/** + * run a queue one by one.If include function return false it will stop + * @param {Array} queue the queue which we want to run one by one + * @return {boolean} tell the user if the queue run finished + */ +function runStoppableQueue$1(queue) { + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + var step = function step(index) { + if (index >= queue.length) { + return true; + } + var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; + if (result === false) return false; + return step(++index); + }; + return step(0); +} +/** + * set an attribute to an object which is frozen. + * Means you can't remove it, iterate it or rewrite it. + * @param {!primitive} obj + * @param {string} key + * @param {Anything} value + */ +function setFrozenAttr(obj, key, value) { + if (isPrimitive(obj)) throw TypeError('setFrozenAttr obj parameter can not be primitive type'); + if (!isString(key)) throw TypeError('setFrozenAttr key parameter must be String'); + _Object$defineProperty(obj, key, { + value: value, + configurable: false, + enumerable: false, + writable: false + }); +} +/** + * set attr on an Object. We will bind getter and setter on it if you provide to us + * @param {!primitive} obj + * @param {string} key + * @param {Function} get + * @param {Function} set + * @param {String} prefix the origin data's prefix. We do not plan to save it by closure. + */ +function setAttrGetterAndSetter(obj, key) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + get = _ref.get, + set = _ref.set; + + var prefix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '__'; + + if (isPrimitive(obj)) throw TypeError('setFrozenAttr obj parameter can not be primitive type'); + if (!isString(key)) throw TypeError('setAttrGetterAndSetter key parameter must be String'); + var originalData = obj[key]; + if (!isFunction(get)) { + _Object$defineProperty(obj, prefix + key, { + value: originalData, + configurable: true, + writable: true, + enumerable: false + }); + get = function get() { + return this[prefix + key]; + }; + if (set && isFunction(set)) { + var originSetter = set; + set = function set() { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this[prefix + key] = originSetter.call.apply(originSetter, [this].concat(args)); + }; + } + } + _Object$defineProperty(obj, key, { get: get, set: set }); +} + +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; + } +} + +// decodeUTF8 +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 debounce$1(func, wait, immediate) { + // immediate默认为false + var timeout = void 0, + args = void 0, + context = void 0, + timestamp = void 0, + result = void 0; + + var later = function later() { + // 当wait指定的时间间隔期间多次调用_.debounce返回的函数,则会不断更新timestamp的值,导致last < wait && last >= 0一直为true,从而不断启动新的计时器延时执行func + var last = new Date() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function () { + context = this; + args = arguments; + timestamp = new Date(); + // 第一次调用该方法时,且immediate为true,则调用func函数 + var callNow = immediate && !timeout; + // 在wait指定的时间间隔内首次调用该方法,则启动计时器定时调用func函数 + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; +} + +/** + * 函数节流(控制函数执行频率) + * @param {Function} func 要节流控制的函数,必填 + * @return {Number} wait 等待时长 + * @return {Object} options { + * leading<是否首次调用立即执行,否:则按wait设定等待到期后调用才执行>:false, + * trailing<是否在调用并未到期时启用定时器,以保证一定执行>:true + * } + * @return {Object} cxt 上下文对象 + * @return {Function} + */ +function throttle$1(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; + }; +} + +// requestAnimationFrame +var raf$1 = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (cb) { + return setTimeout(cb, 17); +}; + +// cancelAnimationFrame +var caf$1 = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame || function (id) { + clearTimeout(id); +}; + +// 根据要求的位数,将9格式化为 09\009\0009... +function strRepeat$1(num, bit) { + var pBit = bit; + num = '' + (num || ''); + var numLen = num.length; + bit = (bit || numLen) - numLen; + var paddingStr = bit > 0 ? num.repeat ? '0'.repeat(bit) : new Array(bit + 1).join('0') : ''; + return (paddingStr + num).slice(0, pBit); +} + +// video 时间格式化 +function formatTime$1(time) { + var hh = Math.floor(time / 3600); + time = Math.floor(time % 3600); + var mm = strRepeat$1(Math.floor(time / 60), 2); + time = Math.floor(time % 60); + var ss = strRepeat$1(time, 2); + return hh >= 1 ? hh + ':' + mm + ':' + ss : mm + ':' + ss; +} + +/** + * 给obj对象扩展上trans方法,用以实现methodName对应的属性方法包装为静态函数且保持上下文的功能 + * @param {Object} obj 目标对象 + */ +function addTransMethod(obj) { + setFrozenAttr(obj, 'trans', function (methodName) { + if (!obj.__fns) { + setFrozenAttr(obj, '__fns', {}); + } + if (!obj.__fns[methodName]) { + obj.__fns[methodName] = function () { + if (!isFunction(obj[methodName])) throw TypeError('obj.trans(methodName) parameter must be Function'); + return obj[methodName].apply(obj, arguments); + }; + } + return obj.__fns[methodName]; + }); +} + +/** + * 追加样式代码到head的style标签,不存在则创建 + * @param {String} cssText 样式文本 + * @return {HTMLElement} + */ +function appendCSS$1(cssText) { + var doc = document; + var styleEl = doc.querySelector('style'); + if (!styleEl) { + styleEl = doc.createElement('style'); + var header = doc.querySelector('head'); + header && header.appendChild(styleEl); + } + styleEl.appendChild(doc.createTextNode(cssText)); + return styleEl; +} + +/** + * 格式化日期对象为:年-月-日 时:分:秒.毫秒 + * @param {Date} date Date日期对象 + * @param {String} pattern 要输出的日期格式,默认:`yyyy-MM-dd hh:mm:ss.i` + * @return {String} + */ +function formatDate$1() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'yyyy-MM-dd hh:mm:ss.i'; + + var year = date.getFullYear().toString(); + var fields = { + M: date.getMonth() + 1, + d: date.getDate(), + h: date.getHours(), + m: date.getMinutes(), + s: date.getSeconds(), + i: date.getMilliseconds() + }; + pattern = pattern.replace(/(y+)/ig, function (_, yearPattern) { + return year.substr(4 - Math.min(4, yearPattern.length)); + }); + + var _loop = function _loop(i) { + pattern = pattern.replace(new RegExp('(' + i + '+)', 'g'), function (_, pattStr) { + return (fields[i] < 10 && pattStr.length > 1 ? '0' : '') + fields[i]; + }); + }; + + for (var i in fields) { + _loop(i); + } + return pattern; +} + +/** + * 读取本地存储的值(不支持localStorage则降级到cookie) + * @param {String} key 目标数据key + * @return {String} + */ +function getLocalStorage$1(key) { + try { + return window.localStorage.getItem(key); + } catch (e) { + try { + var regRt = document.cookie.match(new RegExp('(^| )' + key + '=([^;]*)(;|$)')); + return isArray(regRt) ? unescape(regRt[2]) : ''; + } catch (e) { + return ''; + } + } +} +/** + * 将指定key对应值写入本地存储(不支持localStorage则降级到cookie) + * @param {String} key + * @param {String} val + * @return {String} + */ +function setLocalStorage$1(key, val) { + try { + window.localStorage.setItem(key, val); + } catch (e) { + var expires = new Date(); + // 默认存储300天 + expires.setTime(expires.getTime() + 24 * 3600 * 1000 * 300); + try { + document.cookie = key + '=' + escape(val) + ';expires=' + expires.toUTCString() + ';path=/;'; + } catch (e) {} + } +} + + + +var lib = Object.freeze({ + Log: Log$1, + genTraversalHandler: genTraversalHandler$2, + deepClone: deepClone$2, + deepAssign: deepAssign$2, + camelize: camelize$2, + hypenate: hypenate$2, + bind: bind$3, + uuid: uuid$2, + S4: S4$2, + rand: rand$2, + getDeepProperty: getDeepProperty$2, + defined: defined, + isVoid: isVoid, + isArray: isArray, + isFunction: isFunction, + isObject: isObject, + isNumber: isNumber, + isNumeric: isNumeric, + isInteger: isInteger$2, + isEmpty: isEmpty, + isEvent: isEvent, + isBlob: isBlob, + isFile: isFile, + isDate: isDate, + isString: isString, + isBoolean: isBoolean, + isPromise: isPromise, + isPrimitive: isPrimitive, + isUrl: isUrl, + isNode: isNode$2, + isElement: isElement, + isChildNode: isChildNode, + isPosterityNode: isPosterityNode, + isHTMLString: isHTMLString, + isError: isError, + isRegExp: isRegExp, + inBrowser: inBrowser$1, + makeArray: makeArray$1, + transObjectAttrIntoArray: transObjectAttrIntoArray$1, + runRejectableQueue: runRejectableQueue$1, + runStoppableQueue: runStoppableQueue$1, + setFrozenAttr: setFrozenAttr, + setAttrGetterAndSetter: setAttrGetterAndSetter, + decodeUTF8: decodeUTF8$1, + debounce: debounce$1, + throttle: throttle$1, + raf: raf$1, + caf: caf$1, + strRepeat: strRepeat$1, + formatTime: formatTime$1, + addTransMethod: addTransMethod, + appendCSS: appendCSS$1, + formatDate: formatDate$1, + getLocalStorage: getLocalStorage$1, + setLocalStorage: setLocalStorage$1, + emitEventCache: emitEventCache, + addEventCache: addEventCache, + removeEventCache: removeEventCache, + CustEvent: CustEvent, + getAttr: getAttr, + setAttr: setAttr, + addClassName: addClassName, + removeClassName: removeClassName, + hasClassName: hasClassName, + get supportsPassive () { return supportsPassive; }, + removeEvent: removeEvent, + addEvent: addEvent, + addDelegate: addDelegate, + removeDelegate: removeDelegate, + getStyle: getStyle, + setStyle: setStyle, + query: query, + removeEl: removeEl, + findParents: findParents, + NodeWrap: NodeWrap, + $: $ +}); + +var chimeeHelper = ( lib && undefined ) || lib; + +function __$styleInject$6(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + head.appendChild(style); + return returnValue; +} + +function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var _slicedToArray$1 = _interopDefault$1(slicedToArray); + + +__$styleInject$6("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;opacity:.8;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}", undefined); + +/** + * 生产一个popup插件配置 + * @param {Object} optons 针对popup扩展了定制化参数,另外也用来重写部分PluginConfig配置 + * @param {String} optons.name 插件名 + * @param {String} optons.tagName Popup DOM容器的tagName + * @param {String} optons.className Popup DOM容器的className + * @param {String} optons.title Popup 标题,当设置值为 false 则不渲染title对应DOM + * @param {String} optons.body Popup 内容,当设置值为 false 则不渲染body对应DOM + * @param {String} optons.html html 用于构架popup的模板,重写后上面的title、body无效 + * @param {String} optons.offset 设定相对播放器要展示的坐标位置,空格分割的坐标值:'X:left Y:top'||'top right bottom left', 具体的像素百分比值或者auto;实例化后可重写 popupplugin.offset('0 0 0 0') + * @param {String} optons.offsetAttr offset对应的CSS属性key,默认'left top'、'top right bottom left'-当offset空格分割的参数值多余2个时,便于只设定个别或特定方向边距 + * @param {String} optons.translate 在offset基础上的偏移量,格式如:"leftVal topVal",当offset为50%这里没设定值,则默认偏移-50%;实例化后可重写 popupplugin.translate('0 0') + * @param {String} optons.width 宽度值(需要带单位);实例化后可重写 popupplugin.width('100px') + * @param {String} optons.height 高度值(需要带单位);实例化后可重写 popupplugin.height('100px') + * @param {Boolean} optons.hide 初始状态是否设置为关闭,默认值 false + * @param {Function} optons.opened 开启时执行 + * @param {Function} optons.closed 关闭时执行 + * @param {Boolean} optons.penetrate 是否将交互事件同步到video元素(点击当前popup同样实现video的暂停播放),默认值 false + * @param {Boolean} optons.operable 是否启用事件交互(false则设置CSS事件穿透),默认值 true + * @return {PluginConfig} + */ +function popupFactory$3() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$tagName = _ref.tagName, + tagName = _ref$tagName === undefined ? 'chimee-popup' : _ref$tagName, + className = _ref.className, + _ref$name = _ref.name, + name = _ref$name === undefined ? 'popup' : _ref$name, + html = _ref.html, + _ref$title = _ref.title, + title = _ref$title === undefined ? '这是一个信息框' : _ref$title, + _ref$body = _ref.body, + body = _ref$body === undefined ? '这里是信息内容' : _ref$body, + _ref$offsetAttr = _ref.offsetAttr, + offsetAttr = _ref$offsetAttr === undefined ? 'left top' : _ref$offsetAttr, + _ref$offset = _ref.offset, + offset = _ref$offset === undefined ? '50% 50%' : _ref$offset, + _ref$translate = _ref.translate, + translate = _ref$translate === undefined ? '' : _ref$translate, + width = _ref.width, + height = _ref.height, + level = _ref.level, + init = _ref.init, + inited = _ref.inited, + data = _ref.data, + _create = _ref.create, + _beforeCreate = _ref.beforeCreate, + _destroy = _ref.destroy, + events = _ref.events, + computed = _ref.computed, + _ref$methods = _ref.methods, + methods = _ref$methods === undefined ? {} : _ref$methods, + _ref$penetrate = _ref.penetrate, + penetrate = _ref$penetrate === undefined ? false : _ref$penetrate, + _ref$operable = _ref.operable, + operable = _ref$operable === undefined ? true : _ref$operable, + _ref$hide = _ref.hide, + hide = _ref$hide === undefined ? false : _ref$hide, + opened = _ref.opened, + closed = _ref.closed, + autoFocus = _ref.autoFocus; + + var defaultConfig = { + html: html || '\n \xD7\n ' + (title !== false ? '' + title + '' : '') + '\n ' + (body !== false ? '' + body + '' : '') + '\n ', + closeSelector: '._close' + }; + + return { + name: name, + el: tagName, + className: className, + beforeCreate: function beforeCreate() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + events = _ref2.events, + methods = _ref2.methods; + + var option = arguments[1]; + + if (chimeeHelper.isObject(option)) { + chimeeHelper.isObject(option.events) && chimeeHelper.deepAssign(events, option.events); + chimeeHelper.isObject(option.methods) && chimeeHelper.deepAssign(methods, option.methods); + } + _beforeCreate && _beforeCreate.apply(this, arguments); + }, + create: function create() { + + var config = chimeeHelper.isObject(this.$config) ? chimeeHelper.deepAssign(defaultConfig, this.$config) : defaultConfig; + var $dom = this.$domWrap = chimeeHelper.$(this.$dom).css('display', 'none'); + + $dom.html(config.html).delegate('cm-pp-close, ' + config.closeSelector, 'click', this.close); + + this.width(width).height(height).offset(offset).translate(translate); + + this._hide = hide; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _create && _create.apply(this, args); + !this._hide && this.open(); + }, + destroy: function destroy() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + _destroy && _destroy.apply(this, args); + this.$domWrap.undelegate(this.$config.closeSelector, 'click', this.close).remove(); + }, + + level: level, + init: init, + inited: inited, + data: data, + events: events, + computed: computed, + penetrate: penetrate, + operable: operable, + autoFocus: autoFocus, + methods: chimeeHelper.deepAssign({ + open: function open() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'block'); + this._hide = false; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this.$emit('popupOpen', args, this); + chimeeHelper.isFunction(opened) && opened.apply(this, args); + return this; + }, + close: function close() { + if (this.destroyed) return this; + this.$domWrap.css('display', 'none'); + this._hide = true; + + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + this.$emit('popupClose', args, this); + chimeeHelper.isFunction(closed) && closed.apply(this, args); + return this; + }, + width: function width(_width) { + _width && this.$domWrap.css('width', _width); + return this; + }, + height: function height(_height) { + _height && this.$domWrap.css('height', _height); + return this; + }, + offset: function offset(vals) { + var trblArr = ('' + (vals || '')).split(' '); + var cssObj = {}; + if (trblArr.length > 2) { + ['top', 'right', 'bottom', 'left'].forEach(function (dir, i) { + if (trblArr[i] && trblArr[i] !== 'auto') { + cssObj[dir] = trblArr[i]; + } + }); + this.$domWrap.css(cssObj); + return this; + } + + var _trblArr = _slicedToArray$1(trblArr, 2), + left = _trblArr[0], + _top = _trblArr[1]; + + if (left === '') { + return this; + } + var top = _top || left; + var xyAttr = offsetAttr.split(' '); + cssObj[xyAttr[0]] = left; + cssObj[xyAttr[1]] = top; + this.$domWrap.css(cssObj); + + var translateXY = []; + if (left === '50%') { + translateXY.push('-50%'); + } + if (top === '50%') { + translateXY.push('-50%'); + } + translateXY.length > 0 && this.translate(translateXY.join(' ')); + return this; + }, + translate: function translate(xy) { + var _$split = ('' + (xy || '')).split(' '), + _$split2 = _slicedToArray$1(_$split, 2), + x = _$split2[0], + y = _$split2[1]; + + x && this.$domWrap.css('transform', 'translate(' + x + ', ' + (y || x) + ')'); + return this; + } + }, methods) + }; +} + +var lib$1 = popupFactory$3; + +/** + * chimee-plugin-center-state v0.0.10 + * (c) 2017 yandeqiang + * Released under ISC + */ + +function __$styleInject$7(css, returnValue) { + if (typeof document === 'undefined') { + return returnValue; + } + css = css || ''; + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + head.appendChild(style); + + if (style.styleSheet){ + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } + return returnValue; +} + +__$styleInject$7("chimee-center-state{position:absolute}@keyframes a{0%{opacity:1}to{transform:scale(2);opacity:0}}@keyframes b{0%{transform:rotate(0)}to{transform:rotate(1turn)}}chimee-center-state-correct,chimee-center-state-error,chimee-center-state-loading,chimee-center-state-tip{display:none}chimee-center-state.correct chimee-center-state-correct,chimee-center-state.error chimee-center-state-error,chimee-center-state.loading chimee-center-state-loading,chimee-center-state.tip chimee-center-state-tip{display:inline-block}chimee-center-state-correct{width:104px;height:104px}chimee-center-state-tip{position:absolute;left:26px;bottom:26px;width:52px;height:52px;border-radius:26px;background:rgba(0,0,0,.5);animation:a .5s linear 1 normal forwards}chimee-center-state.play span{background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjQycHgiIGhlaWdodD0iNTFweCIgdmlld0JveD0iMCAwIDQyIDUxIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0My4xICgzOTAxMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxwb2x5Z29uIGlkPSJUcmlhbmdsZSIgZmlsbD0iI0ZGRkZGRiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjEuMDAwMDAwLCAyNS41MDAwMDApIHJvdGF0ZSg5MC4wMDAwMDApIHRyYW5zbGF0ZSgtMjEuMDAwMDAwLCAtMjUuNTAwMDAwKSAiIHBvaW50cz0iMjEgNSA0NiA0NiAtNCA0NiI+PC9wb2x5Z29uPgogICAgPC9nPgo8L3N2Zz4=\")}chimee-center-state.pause span{background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjUwcHgiIGhlaWdodD0iNTBweCIgdmlld0JveD0iMCAwIDUwIDUwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0My4xICgzOTAxMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjAiIHdpZHRoPSIyMCIgaGVpZ2h0PSI1MCI+PC9yZWN0PgogICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUiIGZpbGw9IiNGRkZGRkYiIHg9IjMwIiB5PSIwIiB3aWR0aD0iMjAiIGhlaWdodD0iNTAiPjwvcmVjdD4KICAgIDwvZz4KPC9zdmc+\")}chimee-center-state.back span{background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjczMXB4IiBoZWlnaHQ9Ijg4NHB4IiB2aWV3Qm94PSIwIDAgNzMxIDg4NCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iNzcxLeWNlee6v++8jOWIt+aWsCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzY1LjUwMDAwMCwgNDQyLjAwMDAwMCkgc2NhbGUoLTEsIDEpIHRyYW5zbGF0ZSgtMzY1LjUwMDAwMCwgLTQ0Mi4wMDAwMDApICIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjZmZmZmZmIj4KICAgICAgICAgICAgPHBhdGggZD0iTTcwNS4xMTg1NTgsNDkyLjQxNDIwMyBDNjkwLjk4OTc2OSw0OTIuNDE0MjAzIDY3OS41MzU5MDMsNTAzLjg2ODA2OSA2NzkuNTM1OTAzLDUxNy45OTY4NTggQzY3OS41MzU5MDMsNjkxLjA2MDQ0OSA1MzguNzM3MTU3LDgzMS44NTkxOTUgMzY1LjY3MzU2Niw4MzEuODU5MTk1IEMxOTIuNjA4OTUyLDgzMS44NTkxOTUgNTEuODEyMjUyLDY5MS4wNjA0NDkgNTEuODEyMjUyLDUxNy45OTY4NTggQzUxLjgxMjI1MiwzNTUuMDM4NDE2IDE3Ni42NTI1MzgsMjIwLjcwNjk2NSAzMzUuNzE0MjMsMjA1LjU3MzI4OSBMMjIzLjYwMDgwMywzMTcuNjg2NzE2IEMyMTMuNjEwMjY1LDMyNy42NzcyNTQgMjEzLjYxMDI2NSwzNDMuODc1MTY4IDIyMy42MDA4MDMsMzUzLjg2NTcwNyBDMjI4LjU5NjU4NCwzNTguODYwNDY1IDIzNS4xNDM2OTcsMzYxLjM1ODM1NSAyNDEuNjkwODEsMzYxLjM1ODM1NSBDMjQ4LjIzNzkyMywzNjEuMzU4MzU1IDI1NC43ODUwMzYsMzU4Ljg2MDQ2NSAyNTkuNzgwODE3LDM1My44NjU3MDcgTDQxNC43MzcwMDUsMTk4LjkwOTUxOSBDNDI0LjcyNzU0MywxODguOTE4OTgxIDQyNC43Mjc1NDMsMTcyLjcyMTA2NyA0MTQuNzM3MDA1LDE2Mi43MzA1MjggTDI1OS43Nzk3OTMsNy43NzQzNDEgQzI0OS43ODgyMzEsLTIuMjE2MTk3IDIzMy41OTEzNDEsLTIuMjE2MTk3IDIyMy42MDA4MDIsNy43NzQzNDEgQzIxMy42MTAyNjQsMTcuNzY0ODc5IDIxMy42MTAyNjQsMzMuOTYyNzkzIDIyMy42MDA4MDIsNDMuOTUzMzMyIEwzMzMuOTkwOTgxLDE1NC4zNDM1MTEgQzI5NS45MDE0NzgsMTU3LjYwMjc0MSAyNTguODgyMzUzLDE2Ni43MzM3MDIgMjIzLjU4MTM1OSwxODEuNjY0NzYzIEMxODAuMTExMzEyLDIwMC4wNTE1MjkgMTQxLjA3NjI3MywyMjYuMzY3ODk0IDEwNy41NjA5NDksMjU5Ljg4MzIxOSBDNzQuMDQ1NjI1LDI5My4zOTg1NDQgNDcuNzI5MjU5LDMzMi40MzI1NTkgMjkuMzQyNDkzLDM3NS45MDM2MjkgQzEwLjMwMTgzNSw0MjAuOTIxOTM5IDAuNjQ2OTQxLDQ2OC43Mjk3ODEgMC42NDY5NDEsNTE3Ljk5NTgzNCBDMC42NDY5NDEsNTY3LjI2MzkzNCAxMC4zMDE4MzUsNjE1LjA2OTczIDI5LjM0MjQ5Myw2NjAuMDg5MDYzIEM0Ny43MjkyNTksNzAzLjU1ODA4NyA3NC4wNDU2MjQsNzQyLjU5NDE0OSAxMDcuNTYwOTQ5LDc3Ni4xMDk0NzMgQzE0MS4wNzYyNzQsODA5LjYyNDc5NyAxODAuMTEwMjg5LDgzNS45NDExNjMgMjIzLjU4MTM1OSw4NTQuMzI2OTA2IEMyNjguNTk5NjY5LDg3My4zNjg1ODggMzE2LjQwNjQ4OCw4ODMuMDIzNDgyIDM2NS42NzM1NjQsODgzLjAyMzQ4MiBDNDE0Ljk0MTY2NCw4ODMuMDIzNDgyIDQ2Mi43NDc0Niw4NzMuMzY4NTg4IDUwNy43NjY3OTMsODU0LjMyNjkwNiBDNTUxLjIzNTgxNyw4MzUuOTQxMTY0IDU5MC4yNzE4NzksODA5LjYyNDc5OCA2MjMuNzg3MjAzLDc3Ni4xMDk0NzMgQzY1Ny4zMDI1MjcsNzQyLjU5NDE0OCA2ODMuNjE4ODkzLDcwMy41NTkxMSA3MDIuMDA0NjM2LDY2MC4wODkwNjMgQzcyMS4wNDYzMTgsNjE1LjA2OTczIDczMC43MDEyMTIsNTY3LjI2MjkxMSA3MzAuNzAxMjEyLDUxNy45OTU4MzQgQzczMC43MDEyMTMsNTAzLjg2ODA2OSA3MTkuMjQ4MzcsNDkyLjQxNDIwMyA3MDUuMTE4NTU4LDQ5Mi40MTQyMDMgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgPC9nPgogICAgICAgIDx0ZXh0IGlkPSIxMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgZm9udC1zaXplPSIyODgiIGZvbnQtd2VpZ2h0PSJub3JtYWwiIGZpbGw9IiNmZmZmZmYiPgogICAgICAgICAgICA8dHNwYW4geD0iMjExIiB5PSI2MzQiPjEwPC90c3Bhbj4KICAgICAgICA8L3RleHQ+CiAgICA8L2c+Cjwvc3ZnPg==\")}chimee-center-state.forward span{background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjczMXB4IiBoZWlnaHQ9Ijg4NHB4IiB2aWV3Qm94PSIwIDAgNzMxIDg4NCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iNzcxLeWNlee6v++8jOWIt+aWsCIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjZmZmZmZmIj4KICAgICAgICAgICAgPHBhdGggZD0iTTcwNS4xMTg1NTgsNDkyLjQxNDIwMyBDNjkwLjk4OTc2OSw0OTIuNDE0MjAzIDY3OS41MzU5MDMsNTAzLjg2ODA2OSA2NzkuNTM1OTAzLDUxNy45OTY4NTggQzY3OS41MzU5MDMsNjkxLjA2MDQ0OSA1MzguNzM3MTU3LDgzMS44NTkxOTUgMzY1LjY3MzU2Niw4MzEuODU5MTk1IEMxOTIuNjA4OTUyLDgzMS44NTkxOTUgNTEuODEyMjUyLDY5MS4wNjA0NDkgNTEuODEyMjUyLDUxNy45OTY4NTggQzUxLjgxMjI1MiwzNTUuMDM4NDE2IDE3Ni42NTI1MzgsMjIwLjcwNjk2NSAzMzUuNzE0MjMsMjA1LjU3MzI4OSBMMjIzLjYwMDgwMywzMTcuNjg2NzE2IEMyMTMuNjEwMjY1LDMyNy42NzcyNTQgMjEzLjYxMDI2NSwzNDMuODc1MTY4IDIyMy42MDA4MDMsMzUzLjg2NTcwNyBDMjI4LjU5NjU4NCwzNTguODYwNDY1IDIzNS4xNDM2OTcsMzYxLjM1ODM1NSAyNDEuNjkwODEsMzYxLjM1ODM1NSBDMjQ4LjIzNzkyMywzNjEuMzU4MzU1IDI1NC43ODUwMzYsMzU4Ljg2MDQ2NSAyNTkuNzgwODE3LDM1My44NjU3MDcgTDQxNC43MzcwMDUsMTk4LjkwOTUxOSBDNDI0LjcyNzU0MywxODguOTE4OTgxIDQyNC43Mjc1NDMsMTcyLjcyMTA2NyA0MTQuNzM3MDA1LDE2Mi43MzA1MjggTDI1OS43Nzk3OTMsNy43NzQzNDEgQzI0OS43ODgyMzEsLTIuMjE2MTk3IDIzMy41OTEzNDEsLTIuMjE2MTk3IDIyMy42MDA4MDIsNy43NzQzNDEgQzIxMy42MTAyNjQsMTcuNzY0ODc5IDIxMy42MTAyNjQsMzMuOTYyNzkzIDIyMy42MDA4MDIsNDMuOTUzMzMyIEwzMzMuOTkwOTgxLDE1NC4zNDM1MTEgQzI5NS45MDE0NzgsMTU3LjYwMjc0MSAyNTguODgyMzUzLDE2Ni43MzM3MDIgMjIzLjU4MTM1OSwxODEuNjY0NzYzIEMxODAuMTExMzEyLDIwMC4wNTE1MjkgMTQxLjA3NjI3MywyMjYuMzY3ODk0IDEwNy41NjA5NDksMjU5Ljg4MzIxOSBDNzQuMDQ1NjI1LDI5My4zOTg1NDQgNDcuNzI5MjU5LDMzMi40MzI1NTkgMjkuMzQyNDkzLDM3NS45MDM2MjkgQzEwLjMwMTgzNSw0MjAuOTIxOTM5IDAuNjQ2OTQxLDQ2OC43Mjk3ODEgMC42NDY5NDEsNTE3Ljk5NTgzNCBDMC42NDY5NDEsNTY3LjI2MzkzNCAxMC4zMDE4MzUsNjE1LjA2OTczIDI5LjM0MjQ5Myw2NjAuMDg5MDYzIEM0Ny43MjkyNTksNzAzLjU1ODA4NyA3NC4wNDU2MjQsNzQyLjU5NDE0OSAxMDcuNTYwOTQ5LDc3Ni4xMDk0NzMgQzE0MS4wNzYyNzQsODA5LjYyNDc5NyAxODAuMTEwMjg5LDgzNS45NDExNjMgMjIzLjU4MTM1OSw4NTQuMzI2OTA2IEMyNjguNTk5NjY5LDg3My4zNjg1ODggMzE2LjQwNjQ4OCw4ODMuMDIzNDgyIDM2NS42NzM1NjQsODgzLjAyMzQ4MiBDNDE0Ljk0MTY2NCw4ODMuMDIzNDgyIDQ2Mi43NDc0Niw4NzMuMzY4NTg4IDUwNy43NjY3OTMsODU0LjMyNjkwNiBDNTUxLjIzNTgxNyw4MzUuOTQxMTY0IDU5MC4yNzE4NzksODA5LjYyNDc5OCA2MjMuNzg3MjAzLDc3Ni4xMDk0NzMgQzY1Ny4zMDI1MjcsNzQyLjU5NDE0OCA2ODMuNjE4ODkzLDcwMy41NTkxMSA3MDIuMDA0NjM2LDY2MC4wODkwNjMgQzcyMS4wNDYzMTgsNjE1LjA2OTczIDczMC43MDEyMTIsNTY3LjI2MjkxMSA3MzAuNzAxMjEyLDUxNy45OTU4MzQgQzczMC43MDEyMTMsNTAzLjg2ODA2OSA3MTkuMjQ4MzcsNDkyLjQxNDIwMyA3MDUuMTE4NTU4LDQ5Mi40MTQyMDMgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgPC9nPgogICAgICAgIDx0ZXh0IGlkPSIxMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgZm9udC1zaXplPSIyODgiIGZvbnQtd2VpZ2h0PSJub3JtYWwiIGZpbGw9IiNmZmZmZmYiPgogICAgICAgICAgICA8dHNwYW4geD0iMjExIiB5PSI2MzQiPjEwPC90c3Bhbj4KICAgICAgICA8L3RleHQ+CiAgICA8L2c+Cjwvc3ZnPg==\")}chimee-center-state.volume-high span{background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEwN3B4IiBoZWlnaHQ9IjEwMXB4IiB2aWV3Qm94PSIwIDAgMTA3IDEwMSIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEuMDAwMDAwLCAwLjAwMDAwMCkiIHN0cm9rZT0iI0ZGRkZGRiI+CiAgICAgICAgPHBvbHlnb24gaWQ9IlBhdGgiIGZpbGw9IiNmZmZmZmYiIHBvaW50cz0iMC40MDczMTY0NDYgMzAgMjcuNjUwMDc3OSAzMCA1Ny4zNzM3MjkzIDIuODQyMTcwOTRlLTE0IDU4LjQ3NjI1MzIgMTAwIDI3LjY1MDA3NzkgNzAgMC40MDczMTY0NDYgNzAiPjwvcG9seWdvbj4KICAgICAgICA8cGF0aCBkPSJNNjMuNjExNjUwNSw1LjAwOTc1MjM5IEM2OS43MDc5Mjc1LDQuNzg2MTIwNTcgNzYuNjU0OTI1MSw4LjQwODU2MTQ2IDg0LjQ1MjY0MzEsMTUuODc3MDc1IEM5Ni4xNDkyMjAxLDI3LjA3OTg0NTQgMTAwLjk3MDg3NCwzNC43OTc1MTI1IDEwMC45NzA4NzQsNTAuOTYwODU1OCBDMTAwLjk3MDg3NCw2Ny4xMjQxOTkxIDk2LjI4ODcyMjUsNzMuNzkwNzQ4MiA4NC40NTI2NDMxLDgzLjgzMDY3MjQgQzc2LjU2MTkyMzQsOTAuNTIzOTU1MiA2OS42MTQ5MjU5LDk0LjAzMjA2NDQgNjMuNjExNjUwNSw5NC4zNTUiIGlkPSLlpJbnjq8iIHN0cm9rZS13aWR0aD0iMTAiPjwvcGF0aD4KICAgICAgICA8cGF0aCBkPSJNNjUuODUwNTY5OSwyOS40OTI5MTk1IEM2OC41MzY5NDM0LDI5LjM5MzExNjkgNzEuNTk4MTkzOCwzMS4wMDk3NDE2IDc1LjAzNDMyMSwzNC4zNDI3OTM0IEM4MC4xODg1MTE4LDM5LjM0MjM3MTIgODIuMzEzMjEyMyw0Mi43ODY2MTU0IDgyLjMxMzIxMjMsNTAgQzgyLjMxMzIxMjMsNTcuMjEzMzg0NiA4MC4yNDk5ODQ3LDYwLjE4ODUzNTQgNzUuMDM0MzIxLDY0LjY2OTE1NzYgQzcxLjU1NzIxMTksNjcuNjU2MjM5IDY4LjQ5NTk2MTUsNjkuMjIxODM5NyA2NS44NTA1Njk5LDY5LjM2NTk1OTUiIGlkPSLlhoXnjq8iIHN0cm9rZS13aWR0aD0iMTAiPjwvcGF0aD4KICAgIDwvZz4KPC9zdmc+\")}chimee-center-state.volume-low span{background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9Ijg5cHgiIGhlaWdodD0iMTAxcHgiIHZpZXdCb3g9IjAgMCA4OSAxMDEiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDQ0LjEgKDQxNDU1KSAtIGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCAtLT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9Ikdyb3VwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxLjAwMDAwMCwgMC4wMDAwMDApIiBzdHJva2U9IiNGRkZGRkYiPgogICAgICAgIDxwb2x5Z29uIGlkPSJQYXRoIiBmaWxsPSIjZmZmZmZmIiBwb2ludHM9IjAuNDA3MzE2NDQ2IDMwIDI3LjY1MDA3NzkgMzAgNTcuMzczNzI5MyAyLjg0MjE3MDk0ZS0xNCA1OC40NzYyNTMyIDEwMCAyNy42NTAwNzc5IDcwIDAuNDA3MzE2NDQ2IDcwIj48L3BvbHlnb24+CiAgICAgICAgPHBhdGggZD0iTTY1Ljg1MDU2OTksMjkuNDkyOTE5NSBDNjguNTM2OTQzNCwyOS4zOTMxMTY5IDcxLjU5ODE5MzgsMzEuMDA5NzQxNiA3NS4wMzQzMjEsMzQuMzQyNzkzNCBDODAuMTg4NTExOCwzOS4zNDIzNzEyIDgyLjMxMzIxMjMsNDIuNzg2NjE1NCA4Mi4zMTMyMTIzLDUwIEM4Mi4zMTMyMTIzLDU3LjIxMzM4NDYgODAuMjQ5OTg0Nyw2MC4xODg1MzU0IDc1LjAzNDMyMSw2NC42NjkxNTc2IEM3MS41NTcyMTE5LDY3LjY1NjIzOSA2OC40OTU5NjE1LDY5LjIyMTgzOTcgNjUuODUwNTY5OSw2OS4zNjU5NTk1IiBpZD0i5YaF546vIiBzdHJva2Utd2lkdGg9IjEwIj48L3BhdGg+CiAgICA8L2c+Cjwvc3ZnPg==\")}chimee-center-state-tip span{display:inline-block;width:24px;height:24px;margin:14px;background-origin:content-box;background-size:auto 100%;background-repeat:no-repeat;background-position:50%;box-sizing:initial}chimee-center-state.play span{background-position:110% 50%}chimee-center-state-loading{width:52px;height:52px;padding:26px;background-image:url(\"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjgwcHgiIGhlaWdodD0iODBweCIgdmlld0JveD0iMCAwIDgwIDgwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0Ny4xICg0NTQyMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJsb2FkaW5nIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTAuMDAwMDAwLCAtMTAuMDAwMDAwKSIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjRkZGRkZGIj4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjEiIHg9IjQ3IiB5PSIxMCIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDY1LjAwMDAwMCwgMjQuMDE5MjM4KSByb3RhdGUoMzAuMDAwMDAwKSB0cmFuc2xhdGUoLTY1LjAwMDAwMCwgLTI0LjAxOTIzOCkgIiB4PSI2MiIgeT0iMTQuMDE5MjM3OSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjgiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDc1Ljk4MDc2MiwgMzUuMDAwMDAwKSByb3RhdGUoNjAuMDAwMDAwKSB0cmFuc2xhdGUoLTc1Ljk4MDc2MiwgLTM1LjAwMDAwMCkgIiB4PSI3Mi45ODA3NjIxIiB5PSIyNSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjciIHRyYW5zZm9ybT0idHJhbnNsYXRlKDgwLjAwMDAwMCwgNTAuMDAwMDAwKSByb3RhdGUoOTAuMDAwMDAwKSB0cmFuc2xhdGUoLTgwLjAwMDAwMCwgLTUwLjAwMDAwMCkgIiB4PSI3NyIgeT0iNDAiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGwtb3BhY2l0eT0iMC42IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg3NS45ODA3NjIsIDY1LjAwMDAwMCkgcm90YXRlKDEyMC4wMDAwMDApIHRyYW5zbGF0ZSgtNzUuOTgwNzYyLCAtNjUuMDAwMDAwKSAiIHg9IjcyLjk4MDc2MjEiIHk9IjU1IiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuNSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNjUuMDAwMDAwLCA3NS45ODA3NjIpIHJvdGF0ZSgxNTAuMDAwMDAwKSB0cmFuc2xhdGUoLTY1LjAwMDAwMCwgLTc1Ljk4MDc2MikgIiB4PSI2MiIgeT0iNjUuOTgwNzYyMSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDUwLjAwMDAwMCwgODAuMDAwMDAwKSByb3RhdGUoMTgwLjAwMDAwMCkgdHJhbnNsYXRlKC01MC4wMDAwMDAsIC04MC4wMDAwMDApICIgeD0iNDciIHk9IjcwIiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuMyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzUuMDAwMDAwLCA3NS45ODA3NjIpIHJvdGF0ZSgtMTUwLjAwMDAwMCkgdHJhbnNsYXRlKC0zNS4wMDAwMDAsIC03NS45ODA3NjIpICIgeD0iMzIiIHk9IjY1Ljk4MDc2MjEiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGwtb3BhY2l0eT0iMC4yIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNC4wMTkyMzgsIDY1LjAwMDAwMCkgcm90YXRlKC0xMjAuMDAwMDAwKSB0cmFuc2xhdGUoLTI0LjAxOTIzOCwgLTY1LjAwMDAwMCkgIiB4PSIyMS4wMTkyMzc5IiB5PSI1NSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjMiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDIwLjAwMDAwMCwgNTAuMDAwMDAwKSByb3RhdGUoLTkwLjAwMDAwMCkgdHJhbnNsYXRlKC0yMC4wMDAwMDAsIC01MC4wMDAwMDApICIgeD0iMTciIHk9IjQwIiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuNCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjQuMDE5MjM4LCAzNS4wMDAwMDApIHJvdGF0ZSgtNjAuMDAwMDAwKSB0cmFuc2xhdGUoLTI0LjAxOTIzOCwgLTM1LjAwMDAwMCkgIiB4PSIyMS4wMTkyMzc5IiB5PSIyNSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDM1LjAwMDAwMCwgMjQuMDE5MjM4KSByb3RhdGUoLTMwLjAwMDAwMCkgdHJhbnNsYXRlKC0zNS4wMDAwMDAsIC0yNC4wMTkyMzgpICIgeD0iMzIiIHk9IjE0LjAxOTIzNzkiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+\");background-origin:content-box;background-size:auto 100%;background-repeat:no-repeat;background-position:50%;animation:b 1.2s linear infinite}chimee-center-state-error{display:none;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:180px;font-size:16px;z-index:1;color:#ffcf00;text-shadow:0 0 3px red;font-weight:100;text-align:center}", undefined); + +var clss = 'correct tip play pause back forward volume-high volume-low'; + +var defaultConfig$2 = { + errorTips: '加载失败,请刷新重试' +}; + +var chimeeCenterState = lib$1({ + name: 'chimeeCenterState', + tagName: 'chimee-center-state', + html: '\n \n \n \n \n \n \n \n ', + offset: '50%', + hide: false, + create: function create() {}, + inited: function inited() { + this.config = isObject(this.$config) ? deepAssign$2(defaultConfig$2, this.$config) : defaultConfig$2; + this.$dom.querySelector('chimee-center-state-error').innerText = this.config.errorTips; + this.src && this.showLoading(true); + }, + + penetrate: true, + operable: false, + destroy: function destroy() { + this.clearTimeout(); + }, + + events: { + pause: function pause() { + this.showTip('pause'); + this.showLoading(false); + }, + play: function play() { + this.showTip('play'); + }, + canplay: function canplay() { + this.playing(); + }, + playing: function playing() { + this.playing(); + }, + loadstart: function loadstart() { + this.waiting('loadstart'); + }, + waiting: function waiting() { + this.waiting(); + }, + + // 卡顿(FLV|HLS加载异常待内部特供事件) + // stalled () { + // this.showLoading(); + // }, + timeupdate: function timeupdate() { + this.showLoading(false); + this.clearTimeout(); + }, + keydown: function keydown(e) { + + // controlbar 存在,才会有键盘事件,因此如果 controlbar 组件没有加载时,return + var hasControlbar = this.$videoConfig.plugin.some(function (item) { + var name = item.name || item; + return name === 'chimeeControl'; + }); + if (!hasControlbar) return; + + e.stopPropagation(); + switch (e.keyCode) { + case 37: + { + e.preventDefault(); + !this.live && this.showTip('back'); + break; + } + case 39: + { + e.preventDefault(); + !this.live && this.showTip('forward'); + break; + } + case 38: + { + e.preventDefault(); + this.showTip('volume-high'); + break; + } + case 40: + { + e.preventDefault(); + this.showTip('volume-low'); + break; + } + } + } + }, + methods: { + playing: function playing() { + this.clearTimeout(); + this.showLoading(false); + this.showError(false); + }, + waiting: function waiting(status) { + var _this = this; + + this.clearTimeout(); + // 加载超过20秒则超时显示异常 + this._timeout = setTimeout(function () { + return _this.showError(); + }, 3e4); + (status === 'loadstart' || !this.paused) && this.showLoading(true); + }, + clearTimeout: function (_clearTimeout) { + function clearTimeout() { + return _clearTimeout.apply(this, arguments); + } + + clearTimeout.toString = function () { + return _clearTimeout.toString(); + }; + + return clearTimeout; + }(function () { + if (this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + } + }), + showTip: function showTip(cls) { + var _this2 = this; + + this.$domWrap.removeClass(clss).addClass('correct tip ' + cls); + // this.tip = cls; + setTimeout(function () { + _this2.$domWrap.removeClass('tip ' + cls); + // this.tip = undefined; + }, 500); + }, + showLoading: function showLoading(status) { + if (status === false) { + this.$domWrap.removeClass('loading'); + } else { + this.$domWrap.addClass('correct loading'); + } + }, + showError: function showError(status) { + if (status === false) { + this.$domWrap.removeClass('error'); + } else { + this.$domWrap[0].className = ''; + this.$domWrap.addClass('error'); + } + } + } +}); + +var hls = createCommonjsModule(function (module, exports) { +(function webpackUniversalModuleDefinition(root, factory) { + module.exports = factory(); +})(commonjsGlobal, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/dist/"; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 8); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return enableLogs; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logger; }); +var _typeof = 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 = function enableLogs(debugConfig) { + if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(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 = exportedLogger; + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony default export */ __webpack_exports__["a"] = ({ + // 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, payload : fragment payload, 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' +}); + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ErrorTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ErrorDetails; }); +var 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 = { + // 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' +}; + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return utf8ArrayToStr; }); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * ID3 parser + */ +var ID3 = function () { + function ID3() { + _classCallCheck(this, ID3); + } + + /** + * 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 + */ + ID3.isHeader = 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 + */ + + + ID3.isFooter = 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 + */ + + + ID3.getID3Data = 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; + }; + + ID3._readSize = 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 + */ + + + ID3.getTimeStamp = 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 + */ + + + ID3.isTimeStampFrame = function isTimeStampFrame(frame) { + return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp'; + }; + + ID3._getFrameData = 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 + */ + + + ID3.getID3Frames = 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; + }; + + ID3._decodeFrame = 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; + }; + + ID3._readTimeStamp = 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; + }; + + ID3._decodePrivFrame = function _decodePrivFrame(frame) { + /* + Format: \0 + */ + if (frame.size < 2) { + return undefined; + } + + var owner = ID3._utf8ArrayToStr(frame.data, true); + var privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); + + return { key: frame.type, info: owner, data: privateData.buffer }; + }; + + ID3._decodeTextFrame = 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 }; + } + }; + + ID3._decodeURLFrame = 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. + */ + + + ID3._utf8ArrayToStr = function _utf8ArrayToStr(array) { + var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + + var len = array.length; + var c = void 0; + var char2 = void 0; + var char3 = void 0; + var out = ''; + var i = 0; + while (i < len) { + c = array[i++]; + if (c === 0x00 && exitOnNull) { + return out; + } else if (c === 0x00 || c === 0x03) { + // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it + continue; + } + switch (c >> 4) { + case 0: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; + default: + } + } + return out; + }; + + return ID3; +}(); + +var utf8ArrayToStr = ID3._utf8ArrayToStr; + +/* harmony default export */ __webpack_exports__["a"] = (ID3); + + + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +// CONCATENATED MODULE: ./src/crypt/aes-crypto.js +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var AESCrypto = function () { + function AESCrypto(subtle, iv) { + _classCallCheck(this, AESCrypto); + + this.subtle = subtle; + this.aesIV = iv; + } + + AESCrypto.prototype.decrypt = function decrypt(data, key) { + return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data); + }; + + return AESCrypto; +}(); + +/* harmony default export */ var aes_crypto = (AESCrypto); +// CONCATENATED MODULE: ./src/crypt/fast-aes-key.js +function fast_aes_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var FastAESKey = function () { + function FastAESKey(subtle, key) { + fast_aes_key__classCallCheck(this, FastAESKey); + + this.subtle = subtle; + this.key = key; + } + + FastAESKey.prototype.expandKey = function expandKey() { + return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']); + }; + + return FastAESKey; +}(); + +/* harmony default export */ var fast_aes_key = (FastAESKey); +// CONCATENATED MODULE: ./src/crypt/aes-decryptor.js +function aes_decryptor__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var AESDecryptor = function () { + function AESDecryptor() { + aes_decryptor__classCallCheck(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. + + + AESDecryptor.prototype.uint8ArrayToUint32Array_ = 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; + }; + + AESDecryptor.prototype.initTable = 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]]; + } + } + }; + + AESDecryptor.prototype.expandKey = 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. + + + AESDecryptor.prototype.networkToHostOrderSwap = function networkToHostOrderSwap(word) { + return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24; + }; + + AESDecryptor.prototype.decrypt = 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; + }; + + AESDecryptor.prototype.destroy = 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; +}(); + +/* harmony default export */ var aes_decryptor = (AESDecryptor); +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/crypt/decrypter.js +function decrypter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + + + +/*globals self: false */ + +var decrypter_Decrypter = function () { + function Decrypter(observer, config) { + decrypter__classCallCheck(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; + } + + Decrypter.prototype.isSync = function isSync() { + return this.disableWebCrypto && this.config.enableSoftwareAES; + }; + + Decrypter.prototype.decrypt = function decrypt(data, key, iv, callback) { + var _this = this; + + if (this.disableWebCrypto && this.config.enableSoftwareAES) { + if (this.logEnabled) { + logger["b" /* logger */].log('JS AES decrypt'); + this.logEnabled = false; + } + var decryptor = this.decryptor; + if (!decryptor) { + this.decryptor = decryptor = new aes_decryptor(); + } + decryptor.expandKey(key); + callback(decryptor.decrypt(data, 0, iv)); + } else { + if (this.logEnabled) { + logger["b" /* logger */].log('WebCrypto AES decrypt'); + this.logEnabled = false; + } + var subtle = this.subtle; + if (this.key !== key) { + this.key = key; + this.fastAesKey = new fast_aes_key(subtle, key); + } + + this.fastAesKey.expandKey().then(function (aesKey) { + // decrypt using web crypto + var crypto = new aes_crypto(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); + }); + } + }; + + Decrypter.prototype.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) { + if (this.config.enableSoftwareAES) { + logger["b" /* logger */].log('WebCrypto Error, disable WebCrypto API'); + this.disableWebCrypto = true; + this.logEnabled = true; + this.decrypt(data, key, iv, callback); + } else { + logger["b" /* logger */].error('decrypting error : ' + err.message); + this.observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_DECRYPT_ERROR, fatal: true, reason: err.message }); + } + }; + + Decrypter.prototype.destroy = function destroy() { + var decryptor = this.decryptor; + if (decryptor) { + decryptor.destroy(); + this.decryptor = undefined; + } + }; + + return Decrypter; +}(); + +/* harmony default export */ var decrypter = __webpack_exports__["a"] = (decrypter_Decrypter); + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 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(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(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(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(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(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(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +// 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 */ + module.exports = URLToolkit; +})(this); +/* jshint ignore:end */ + + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules +var crypt_decrypter = __webpack_require__(4); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/demux/adts.js +/** + * ADTS parser helper + */ + + + +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["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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["b" /* 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 || /vivaldi/i.test(userAgent)) || !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 }; +} + +function isHeaderPattern(data, offset) { + return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0; +} + +function getHeaderLength(data, offset) { + return !!(data[offset + 1] & 0x01) ? 7 : 9; +} + +function getFullFrameLength(data, offset) { + return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5; +} + +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 && isHeaderPattern(data, offset)) { + return true; + } + return false; +} + +function adts_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 && isHeaderPattern(data, offset)) { + // ADTS header Length + var headerLength = getHeaderLength(data, offset); + // ADTS frame Length + var frameLength = headerLength; + if (offset + 5 < data.length) { + frameLength = getFullFrameLength(data, offset); + } + var newOffset = offset + frameLength; + if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) { + return true; + } + } + return false; +} + +function initTrackConfig(track, observer, data, offset, audioCodec) { + if (!track.samplerate) { + var config = 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["b" /* logger */].log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount); + } +} + +function getFrameDuration(samplerate) { + return 1024 * 90000 / samplerate; +} + +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 = getHeaderLength(data, offset); + // retrieve frame size + frameLength = 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; +} + +function appendFrame(track, data, offset, pts, frameIndex) { + var frameDuration = getFrameDuration(track.samplerate); + var header = 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; +} +// EXTERNAL MODULE: ./src/demux/id3.js +var id3 = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/demux/aacdemuxer.js +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * AAC demuxer + */ + + + + +var aacdemuxer_AACDemuxer = function () { + function AACDemuxer(observer, remuxer, config) { + _classCallCheck(this, AACDemuxer); + + this.observer = observer; + this.config = config; + this.remuxer = remuxer; + } + + AACDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 }; + }; + + AACDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + AACDemuxer.probe = function probe(data) { + if (!data) { + return false; + } + // Check for the ADTS sync word + // 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 + var id3Data = id3["a" /* default */].getID3Data(data, 0) || []; + var offset = id3Data.length; + + for (var length = data.length; offset < length; offset++) { + if (adts_probe(data, offset)) { + logger["b" /* logger */].log('ADTS sync word found !'); + return true; + } + } + return false; + }; + + // feed incoming data to the front of the parsing pipeline + + + AACDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) { + var track = this._audioTrack; + var id3Data = id3["a" /* default */].getID3Data(data, 0) || []; + var timestamp = id3["a" /* default */].getTimeStamp(id3Data); + var pts = timestamp ? 90 * timestamp : timeOffset * 90000; + var frameIndex = 0; + var stamp = pts; + var length = data.length; + var offset = id3Data.length; + + var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }]; + + while (offset < length - 1) { + if (isHeader(data, offset) && offset + 5 < length) { + initTrackConfig(track, this.observer, data, offset, track.manifestCodec); + var frame = appendFrame(track, data, offset, pts, frameIndex); + if (frame) { + offset += frame.length; + stamp = frame.sample.pts; + frameIndex++; + } else { + logger["b" /* logger */].log('Unable to parse AAC frame'); + break; + } + } else if (id3["a" /* default */].isHeader(data, offset)) { + id3Data = id3["a" /* 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); + }; + + AACDemuxer.prototype.destroy = function destroy() {}; + + return AACDemuxer; +}(); + +/* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer); +// CONCATENATED MODULE: ./src/demux/mp4demuxer.js +function mp4demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * MP4 demuxer + */ + + + +var UINT32_MAX = Math.pow(2, 32) - 1; + +var mp4demuxer_MP4Demuxer = function () { + function MP4Demuxer(observer, remuxer) { + mp4demuxer__classCallCheck(this, MP4Demuxer); + + this.observer = observer; + this.remuxer = remuxer; + } + + MP4Demuxer.prototype.resetTimeStamp = function resetTimeStamp(initPTS) { + this.initPTS = initPTS; + }; + + MP4Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + //jshint unused:false + if (initSegment && initSegment.byteLength) { + var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment); + + // default audio codec if nothing specified + // TODO : extract that from initsegment + if (audioCodec == null) { + audioCodec = 'mp4a.40.5'; + } + if (videoCodec == null) { + videoCodec = 'avc1.42e01e'; + } + var tracks = {}; + if (initData.audio && initData.video) { + tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null }; + } else { + 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(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, { tracks: tracks }); + } else { + if (audioCodec) { + this.audioCodec = audioCodec; + } + if (videoCodec) { + this.videoCodec = videoCodec; + } + } + }; + + MP4Demuxer.probe = function probe(data) { + // ensure we find a moof box in the first 16 kB + return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0; + }; + + MP4Demuxer.bin2str = function bin2str(buffer) { + return String.fromCharCode.apply(null, buffer); + }; + + MP4Demuxer.readUint32 = 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; + }; + + MP4Demuxer.writeUint32 = 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 + + + MP4Demuxer.findBox = 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. + */ + + + MP4Demuxer.parseInitSegment = 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) { + // extract codec info. TODO : parse codec details to be able to build MIME type + var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']); + if (codecBox.length) { + codecBox = codecBox[0]; + var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16)); + logger["b" /* logger */].log('MP4Demuxer:' + type + ':' + codecType + ' found'); + } + 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 + */ + + + MP4Demuxer.getStartDTS = 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]; + // convert base time to seconds + return baseTime / scale; + }); + })); + + // return the minimum + result = Math.min.apply(null, baseTimes); + return isFinite(result) ? result : 0; + }; + + MP4Demuxer.offsetStartDTS = 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; + baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0); + 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); + } + }); + }); + }); + }; + + // feed incoming data to the front of the parsing pipeline + + + MP4Demuxer.prototype.append = 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(events["a" /* 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); + }; + + MP4Demuxer.prototype.destroy = function destroy() {}; + + return MP4Demuxer; +}(); + +/* harmony default export */ var mp4demuxer = (mp4demuxer_MP4Demuxer); +// CONCATENATED MODULE: ./src/demux/mpegaudio.js +/** + * 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], + + SamplesCoefficients: [ + // MPEG 2.5 + [0, // Reserved + 72, // Layer3 + 144, // Layer2 + 12 // Layer1 + ], + // Reserved + [0, // Reserved + 0, // Layer3 + 0, // Layer2 + 0 // Layer1 + ], + // MPEG 2 + [0, // Reserved + 72, // Layer3 + 144, // Layer2 + 12 // Layer1 + ], + // MPEG 1 + [0, // Reserved + 144, // Layer3 + 144, // Layer2 + 12 // Layer1 + ]], + + BytesInSlot: [0, // Reserved + 1, // Layer3 + 1, // Layer2 + 4 // Layer1 + ], + + 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 = header.samplesPerFrame * 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] >> 1 & 1; + 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 channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) + var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC]; + var bytesInSlot = MpegAudio.BytesInSlot[headerC]; + var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot; + var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot; + + return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame }; + } + + 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; + } +}; + +/* harmony default export */ var mpegaudio = (MpegAudio); +// CONCATENATED MODULE: ./src/demux/exp-golomb.js +function exp_golomb__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264. +*/ + + + +var exp_golomb_ExpGolomb = function () { + function ExpGolomb(data) { + exp_golomb__classCallCheck(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 + + + ExpGolomb.prototype.loadWord = 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 + + + ExpGolomb.prototype.skipBits = 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 + + + ExpGolomb.prototype.readBits = function readBits(size) { + var bits = Math.min(this.bitsAvailable, size), + // :uint + valu = this.word >>> 32 - bits; // :uint + if (size > 32) { + logger["b" /* 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 + + + ExpGolomb.prototype.skipLZ = 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 + + + ExpGolomb.prototype.skipUEG = function skipUEG() { + this.skipBits(1 + this.skipLZ()); + }; + + // ():void + + + ExpGolomb.prototype.skipEG = function skipEG() { + this.skipBits(1 + this.skipLZ()); + }; + + // ():uint + + + ExpGolomb.prototype.readUEG = function readUEG() { + var clz = this.skipLZ(); // :uint + return this.readBits(clz + 1) - 1; + }; + + // ():int + + + ExpGolomb.prototype.readEG = 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 + + + ExpGolomb.prototype.readBoolean = function readBoolean() { + return 1 === this.readBits(1); + }; + + // ():int + + + ExpGolomb.prototype.readUByte = function readUByte() { + return this.readBits(8); + }; + + // ():int + + + ExpGolomb.prototype.readUShort = function readUShort() { + return this.readBits(16); + }; + // ():int + + + ExpGolomb.prototype.readUInt = 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 + */ + + + ExpGolomb.prototype.skipScalingList = 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. + */ + + + ExpGolomb.prototype.readSPS = 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 + }; + }; + + ExpGolomb.prototype.readSliceType = function readSliceType() { + // skip NALu type + this.readUByte(); + // discard first_mb_in_slice + this.readUEG(); + // return slice_type + return this.readUEG(); + }; + + return ExpGolomb; +}(); + +/* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb); +// CONCATENATED MODULE: ./src/demux/sample-aes.js +function sample_aes__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * SAMPLE-AES decrypter +*/ + + + +var sample_aes_SampleAesDecrypter = function () { + function SampleAesDecrypter(observer, config, decryptdata, discardEPB) { + sample_aes__classCallCheck(this, SampleAesDecrypter); + + this.decryptdata = decryptdata; + this.discardEPB = discardEPB; + this.decrypter = new crypt_decrypter["a" /* default */](observer, config); + } + + SampleAesDecrypter.prototype.decryptBuffer = 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 + + + SampleAesDecrypter.prototype.decryptAacSample = 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); + } + }); + }; + + SampleAesDecrypter.prototype.decryptAacSamples = 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 + + + SampleAesDecrypter.prototype.getAvcEncryptedData = 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; + }; + + SampleAesDecrypter.prototype.getAvcDecryptedUnit = 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; + }; + + SampleAesDecrypter.prototype.decryptAvcSample = 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); + } + }); + }; + + SampleAesDecrypter.prototype.decryptAvcSamples = 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; +}(); + +/* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter); +// CONCATENATED MODULE: ./src/demux/tsdemuxer.js +function tsdemuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 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'; + + + +// We are using fixed track IDs for driving the MP4 remuxer +// instead of following the TS PIDs. +// There is no reason not to do this and some browsers/SourceBuffer-demuxers +// may not like if there are TrackID "switches" +// See https://github.com/video-dev/hls.js/issues/1331 +// Here we are mapping our internal track types to constant MP4 track IDs +// With MSE currently one can only have one track of each, and we are muxing +// whatever video/audio rendition in them. +var RemuxerTrackIdConfig = { + video: 0, + audio: 1, + id3: 2, + text: 3 +}; + +var tsdemuxer_TSDemuxer = function () { + function TSDemuxer(observer, remuxer, config, typeSupported) { + tsdemuxer__classCallCheck(this, TSDemuxer); + + this.observer = observer; + this.config = config; + this.typeSupported = typeSupported; + this.remuxer = remuxer; + this.sampleAes = null; + } + + TSDemuxer.prototype.setDecryptData = function setDecryptData(decryptdata) { + if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') { + this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB); + } else { + this.sampleAes = null; + } + }; + + TSDemuxer.probe = function probe(data) { + var syncOffset = TSDemuxer._syncOffset(data); + if (syncOffset < 0) { + return false; + } else { + if (syncOffset) { + logger["b" /* logger */].warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?'); + } + return true; + } + }; + + TSDemuxer._syncOffset = function _syncOffset(data) { + // scan 1000 first bytes + var scanwindow = Math.min(1000, data.length - 3 * 188); + var i = 0; + while (i < scanwindow) { + // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47 + if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) { + return i; + } else { + i++; + } + } + return -1; + }; + + /** + * Creates a track model internal to demuxer used to drive remuxing input + * + * @param {string} type 'audio' | 'video' | 'id3' | 'text' + * @param {number} duration + * @return {object} TSDemuxer's internal track model + */ + + + TSDemuxer.createTrack = function createTrack(type, duration) { + return { + container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined, + type: type, + id: RemuxerTrackIdConfig[type], + pid: -1, + inputTimeScale: 90000, + sequenceNumber: 0, + samples: [], + len: 0, + dropped: type === 'video' ? 0 : undefined, + isAAC: type === 'audio' ? true : undefined, + duration: type === 'audio' ? duration : undefined + }; + }; + + /** + * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start) + * Resets all internal track instances of the demuxer. + * + * @override Implements generic demuxing/remuxing interface (see DemuxerInline) + * @param {object} initSegment + * @param {string} audioCodec + * @param {string} videoCodec + * @param {number} duration (in TS timescale = 90kHz) + */ + + + TSDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + this.pmtParsed = false; + this._pmtId = -1; + + this._avcTrack = TSDemuxer.createTrack('video', duration); + this._audioTrack = TSDemuxer.createTrack('audio', duration); + this._id3Track = TSDemuxer.createTrack('id3', duration); + this._txtTrack = TSDemuxer.createTrack('text', duration); + + // flush any partial content + this.aacOverFlow = null; + this.aacLastPTS = null; + this.avcSample = null; + this.audioCodec = audioCodec; + this.videoCodec = videoCodec; + this._duration = duration; + }; + + /** + * + * @override + */ + + + TSDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + // feed incoming data to the front of the parsing pipeline + + + TSDemuxer.prototype.append = 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.pid, + audioId = audioTrack.pid, + id3Id = id3Track.pid, + 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); + + var syncOffset = TSDemuxer._syncOffset(data); + + // don't parse last TS packet if incomplete + len -= (len + syncOffset) % 188; + + // loop through TS packets + for (start = syncOffset; 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 + // NOTE this is only the PID of the track as found in TS, + // but we are not using this for MP4 track IDs. + avcId = parsedPIDs.avc; + if (avcId > 0) { + avcTrack.pid = avcId; + } + audioId = parsedPIDs.audio; + if (audioId > 0) { + audioTrack.pid = audioId; + audioTrack.isAAC = parsedPIDs.isAAC; + } + id3Id = parsedPIDs.id3; + if (id3Id > 0) { + id3Track.pid = id3Id; + } + if (unknownPIDs && !pmtParsed) { + logger["b" /* logger */].log('reparse from beginning'); + unknownPIDs = false; + // we set it to -188, the += 188 in the for loop will reset start to 0 + start = syncOffset - 188; + } + pmtParsed = this.pmtParsed = true; + break; + case 17: + case 0x1fff: + break; + default: + unknownPIDs = true; + break; + } + } else { + this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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["b" /* 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); + } + }; + + TSDemuxer.prototype.decryptAndRemux = 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); + } + }; + + TSDemuxer.prototype.decryptAndRemuxAvc = 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); + } + }; + + TSDemuxer.prototype.destroy = function destroy() { + this._initPTS = this._initDTS = undefined; + this._duration = 0; + }; + + TSDemuxer.prototype._parsePAT = 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); + }; + + TSDemuxer.prototype._parsePMT = 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["b" /* 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["b" /* 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["b" /* 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["b" /* logger */].warn('HEVC stream type found, not supported for now'); + break; + + default: + logger["b" /* 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; + }; + + TSDemuxer.prototype._parsePES = 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["b" /* 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; + } + }; + + TSDemuxer.prototype.pushAccesUnit = 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["b" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug); + } + }; + + TSDemuxer.prototype._parseAVCPES = 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, + pushAccesUnit = this.pushAccesUnit.bind(this), + createAVCSample = function createAVCSample(key, pts, dts, debug) { + return { key: key, pts: pts, dts: dts, units: [], debug: debug }; + }; + //free pes.data to save up some memory + pes.data = null; + + // if new NAL units found and last sample still there, let's push ... + // this helps parsing streams with missing AUD (only do this if AUD never found) + if (avcSample && units.length && !track.audFound) { + pushAccesUnit(avcSample, track); + avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, ''); + } + + units.forEach(function (unit) { + switch (unit.type) { + //NDR + case 1: + push = true; + if (!avcSample) { + avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); + } + if (debug) { + 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 exp_golomb(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 = 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 exp_golomb(_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 exp_golomb(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; + track.audFound = true; + if (avcSample) { + pushAccesUnit(avcSample, track); + } + avcSample = _this.avcSample = 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) { + pushAccesUnit(avcSample, track); + this.avcSample = null; + } + }; + + TSDemuxer.prototype._insertSampleInOrder = 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); + } + }; + + TSDemuxer.prototype._getLastNalUnit = 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; + }; + + TSDemuxer.prototype._parseAVCNALu = 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 + */ + + + TSDemuxer.prototype.discardEPB = 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; + }; + + TSDemuxer.prototype._parseAACPES = 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 (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["b" /* logger */].warn('parsing error:' + reason); + this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: fatal, reason: reason }); + if (fatal) { + return; + } + } + + initTrackConfig(track, this.observer, data, offset, this.audioCodec); + frameIndex = 0; + frameDuration = 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["b" /* logger */].log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90)); + pts = newPTS; + } + } + + //scan for aac samples + while (offset < len) { + if (isHeader(data, offset) && offset + 5 < len) { + var frame = 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; + }; + + TSDemuxer.prototype._parseMPEGPES = 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 (mpegaudio.isHeader(data, offset)) { + var frame = mpegaudio.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++; + } + } + }; + + TSDemuxer.prototype._parseID3PES = function _parseID3PES(pes) { + this._id3Track.samples.push(pes); + }; + + return TSDemuxer; +}(); + +/* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer); +// CONCATENATED MODULE: ./src/demux/mp3demuxer.js +function mp3demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * MP3 demuxer + */ + + + + +var mp3demuxer_MP3Demuxer = function () { + function MP3Demuxer(observer, remuxer, config) { + mp3demuxer__classCallCheck(this, MP3Demuxer); + + this.observer = observer; + this.config = config; + this.remuxer = remuxer; + } + + MP3Demuxer.prototype.resetInitSegment = 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 }; + }; + + MP3Demuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + MP3Demuxer.probe = function probe(data) { + // check if data contains ID3 timestamp and MPEG sync word + var offset, length; + var id3Data = id3["a" /* default */].getID3Data(data, 0); + if (id3Data && id3["a" /* 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 (mpegaudio.probe(data, offset)) { + logger["b" /* logger */].log('MPEG Audio sync word found !'); + return true; + } + } + } + return false; + }; + + // feed incoming data to the front of the parsing pipeline + + + MP3Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) { + var id3Data = id3["a" /* default */].getID3Data(data, 0); + var timestamp = id3["a" /* default */].getTimeStamp(id3Data); + var pts = timestamp ? 90 * timestamp : timeOffset * 90000; + 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 (mpegaudio.isHeader(data, offset)) { + var frame = mpegaudio.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 (id3["a" /* default */].isHeader(data, offset)) { + id3Data = id3["a" /* 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); + }; + + MP3Demuxer.prototype.destroy = function destroy() {}; + + return MP3Demuxer; +}(); + +/* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer); +// CONCATENATED MODULE: ./src/helper/aac.js +function aac__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * AAC helper + */ + +var AAC = function () { + function AAC() { + aac__classCallCheck(this, AAC); + } + + AAC.getSilentFrame = 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; +}(); + +/* harmony default export */ var aac = (AAC); +// CONCATENATED MODULE: ./src/remux/mp4-generator.js +function mp4_generator__classCallCheck(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 mp4_generator_UINT32_MAX = Math.pow(2, 32) - 1; + +var MP4 = function () { + function MP4() { + mp4_generator__classCallCheck(this, MP4); + } + + MP4.init = 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)); + }; + + MP4.box = 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; + }; + + MP4.hdlr = function hdlr(type) { + return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]); + }; + + MP4.mdat = function mdat(data) { + return MP4.box(MP4.types.mdat, data); + }; + + MP4.mdhd = function mdhd(timescale, duration) { + duration *= timescale; + var upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (mp4_generator_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])); + }; + + MP4.mdia = function mdia(track) { + return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track)); + }; + + MP4.mfhd = 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]) // sequence_number + ); + }; + + MP4.minf = 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)); + } + }; + + MP4.moof = 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 + */ + + + MP4.moov = 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))); + }; + + MP4.mvex = 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)); + }; + + MP4.mvhd = function mvhd(timescale, duration) { + duration *= timescale; + var upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (mp4_generator_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); + }; + + MP4.sdtp = 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); + }; + + MP4.stbl = 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)); + }; + + MP4.avc1 = 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]))); + }; + + MP4.esds = 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 + }; + + MP4.mp4a = 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))); + }; + + MP4.mp3 = 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])); + }; + + MP4.stsd = 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)); + } + }; + + MP4.tkhd = function tkhd(track) { + var id = track.id, + duration = track.duration * track.timescale, + width = track.width, + height = track.height, + upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)), + lowerWordDuration = Math.floor(duration % (mp4_generator_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 + ])); + }; + + MP4.traf = function traf(track, baseMediaDecodeTime) { + var sampleDependencyTable = MP4.sdtp(track), + id = track.id, + upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (mp4_generator_UINT32_MAX + 1)), + lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (mp4_generator_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]) // track_ID + ), 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 + */ + + + MP4.trak = function trak(track) { + track.duration = track.duration || 0xffffffff; + return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track)); + }; + + MP4.trex = 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 + ])); + }; + + MP4.trun = 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); + }; + + MP4.initSegment = 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; +}(); + +/* harmony default export */ var mp4_generator = (MP4); +// CONCATENATED MODULE: ./src/remux/mp4-remuxer.js +function mp4_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** +* fMP4 remuxer +*/ + + + + + + + +// 10 seconds +var MAX_SILENT_FRAME_DURATION = 10 * 1000; + +var mp4_remuxer_MP4Remuxer = function () { + function MP4Remuxer(observer, config, typeSupported, vendor) { + mp4_remuxer__classCallCheck(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; + } + + MP4Remuxer.prototype.destroy = function destroy() {}; + + MP4Remuxer.prototype.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) { + this._initPTS = this._initDTS = defaultTimeStamp; + }; + + MP4Remuxer.prototype.resetInitSegment = function resetInitSegment() { + this.ISGenerated = false; + }; + + MP4Remuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { + // generate Init Segment if needed + if (!this.ISGenerated) { + this.generateIS(audioTrack, videoTrack, timeOffset); + } + + if (this.ISGenerated) { + var nbAudioSamples = audioTrack.samples.length; + var nbVideoSamples = videoTrack.samples.length; + var audioTimeOffset = timeOffset; + var videoTimeOffset = timeOffset; + if (nbAudioSamples && nbVideoSamples) { + // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS) + // if first audio DTS is not aligned with first video DTS then we need to take that into account + // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small + // drift between audio and video streams + var audiovideoDeltaDts = (audioTrack.samples[0].dts - videoTrack.samples[0].dts) / videoTrack.inputTimeScale; + audioTimeOffset += Math.max(0, audiovideoDeltaDts); + videoTimeOffset += Math.max(0, -audiovideoDeltaDts); + } + // 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 (nbAudioSamples) { + // if initSegment was generated without video samples, regenerate it again + if (!audioTrack.timescale) { + logger["b" /* logger */].warn('regenerate InitSegment as audio detected'); + this.generateIS(audioTrack, videoTrack, timeOffset); + } + var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset); + //logger.log('nb AVC samples:' + videoTrack.samples.length); + if (nbVideoSamples) { + 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["b" /* logger */].warn('regenerate InitSegment as video detected'); + this.generateIS(audioTrack, videoTrack, timeOffset); + } + this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset); + } + } else { + var videoData = void 0; + //logger.log('nb AVC samples:' + videoTrack.samples.length); + if (nbVideoSamples) { + videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, accurateTimeOffset); + } + if (videoData && audioTrack.codec) { + this.remuxEmptyAudio(audioTrack, audioTimeOffset, 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(events["a" /* default */].FRAG_PARSED); + }; + + MP4Remuxer.prototype.generateIS = 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["b" /* 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() : mp4_generator.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: mp4_generator.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(events["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS }); + } + } + + if (Object.keys(tracks).length) { + observer.trigger(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, data); + this.ISGenerated = true; + if (computePTSDTS) { + this._initPTS = initPTS; + this._initDTS = initDTS; + } + } else { + observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' }); + } + }; + + MP4Remuxer.prototype.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) { + var offset = 8, + timeScale = track.timescale, + mp4SampleDuration, + mdat, + moof, + firstPTS, + firstDTS, + 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["b" /* 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["b" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it'); + } else if (delta < -1) { + logger["b" /* 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["b" /* logger */].log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms'); + } + } + + // 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* 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(mp4_generator.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["b" /* 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 = mp4_generator.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(events["a" /* default */].FRAG_PARSING_DATA, data); + return data; + }; + + MP4Remuxer.prototype.remuxAudio = 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); + + // compute normalized PTS + inputSamples.forEach(function (sample) { + sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale); + }); + + // filter out sample with negative PTS that are not playable anyway + // if we don't remove these negative samples, they will shift all audio samples forward. + // leading to audio overlap between current / next fragment + inputSamples = inputSamples.filter(function (sample) { + return sample.pts >= 0; + }); + + // in case all samples have negative PTS, and have been filtered out, return now + if (inputSamples.length === 0) { + return; + } + + if (!contiguous) { + if (!accurateTimeOffset) { + // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS + nextAudioPts = inputSamples[0].pts; + } else { + // if timeOffset is accurate, let's use it as predicted next audio PTS + nextAudioPts = timeOffset * inputTimeScale; + } + } + + // 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. + + if (track.isAAC) { + var maxAudioFramesDrift = this.config.maxAudioFramesDrift; + 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; + + //console.log(Math.round(pts) + '/' + Math.round(nextPts) + '/' + Math.round(delta)); + var duration = Math.abs(1000 * delta / inputTimeScale); + + // If we're overlapping by more than a duration, drop this sample + if (delta <= -maxAudioFramesDrift * inputSampleDuration) { + logger["b" /* logger */].warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(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 maxAudioFramesDrift frame away + // 2: Not more than MAX_SILENT_FRAME_DURATION away + // 3: currentTime (aka nextPtsNorm) is not 0 + else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) { + var missing = Math.round(delta / inputSampleDuration); + logger["b" /* 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 = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + if (!fillFrame) { + logger["b" /* 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 { + 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["b" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it'); + if (numMissingFrames > 0) { + fillFrame = aac.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["b" /* 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 + firstPTS = _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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* 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(mp4_generator.types.mdat, 4); + } + } else { + // no audio samples + return; + } + for (var _i3 = 0; _i3 < numMissingFrames; _i3++) { + fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + if (!fillFrame) { + logger["b" /* 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 = mp4_generator.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(events["a" /* default */].FRAG_PARSING_DATA, audioData); + return audioData; + } + return null; + }; + + MP4Remuxer.prototype.remuxEmptyAudio = 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 = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + + logger["b" /* logger */].warn('remux empty Audio'); + // Can't remux if we can't generate a silent frame... + if (!silentFrame) { + logger["b" /* 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); + }; + + MP4Remuxer.prototype.remuxID3 = 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(events["a" /* default */].FRAG_PARSING_METADATA, { + samples: track.samples + }); + } + + track.samples = []; + timeOffset = timeOffset; + }; + + MP4Remuxer.prototype.remuxText = 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(events["a" /* default */].FRAG_PARSING_USERDATA, { + samples: track.samples + }); + } + + track.samples = []; + timeOffset = timeOffset; + }; + + MP4Remuxer.prototype._PTSNormalize = 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; +}(); + +/* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer); +// CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js +function passthrough_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * passthrough remuxer +*/ + + +var passthrough_remuxer_PassThroughRemuxer = function () { + function PassThroughRemuxer(observer) { + passthrough_remuxer__classCallCheck(this, PassThroughRemuxer); + + this.observer = observer; + } + + PassThroughRemuxer.prototype.destroy = function destroy() {}; + + PassThroughRemuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + PassThroughRemuxer.prototype.resetInitSegment = function resetInitSegment() {}; + + PassThroughRemuxer.prototype.remux = 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(events["a" /* default */].FRAG_PARSING_DATA, { + data1: rawData, + startPTS: timeOffset, + startDTS: timeOffset, + type: streamType, + nb: 1, + dropped: 0 + }); + //notify end of parsing + observer.trigger(events["a" /* default */].FRAG_PARSED); + }; + + return PassThroughRemuxer; +}(); + +/* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer); +// CONCATENATED MODULE: ./src/demux/demuxer-inline.js +function demuxer_inline__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* inline demuxer. + * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...) + */ + + + + + + + + + + + +var demuxer_inline_DemuxerInline = function () { + function DemuxerInline(observer, typeSupported, config, vendor) { + demuxer_inline__classCallCheck(this, DemuxerInline); + + this.observer = observer; + this.typeSupported = typeSupported; + this.config = config; + this.vendor = vendor; + } + + DemuxerInline.prototype.destroy = function destroy() { + var demuxer = this.demuxer; + if (demuxer) { + demuxer.destroy(); + } + }; + + DemuxerInline.prototype.push = 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 crypt_decrypter["a" /* 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(events["a" /* 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); + } + }; + + DemuxerInline.prototype.pushDecrypted = 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 TS/AAC/MP3/MP4 + var muxConfig = [{ demux: tsdemuxer, remux: mp4_remuxer }, { demux: mp4demuxer, remux: passthrough_remuxer }, { demux: aacdemuxer, remux: mp4_remuxer }, { demux: mp3demuxer, remux: mp4_remuxer }]; + + // 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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; +}(); + +/* harmony default export */ var demuxer_inline = __webpack_exports__["a"] = (demuxer_inline_DemuxerInline); + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +var cues_namespaceObject = {}; +__webpack_require__.d(cues_namespaceObject, "newCue", function() { return newCue; }); + +// EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js +var url_toolkit = __webpack_require__(6); +var url_toolkit_default = /*#__PURE__*/__webpack_require__.n(url_toolkit); + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/event-handler.js +var _typeof = 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* +* +* All objects in the event handling chain should inherit from this class +* +*/ + + + + + +var event_handler_EventHandler = function () { + function EventHandler(hls) { + _classCallCheck(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(); + } + + EventHandler.prototype.destroy = function destroy() { + this.unregisterListeners(); + }; + + EventHandler.prototype.isEventHandler = function isEventHandler() { + return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function'; + }; + + EventHandler.prototype.registerListeners = 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); + } + }; + + EventHandler.prototype.unregisterListeners = function unregisterListeners() { + if (this.isEventHandler()) { + this.handledEvents.forEach(function (event) { + this.hls.off(event, this.onEvent); + }, this); + } + }; + + /** + * arguments: event (string), data (any) + */ + + + EventHandler.prototype.onEvent = function onEvent(event, data) { + this.onEventGeneric(event, data); + }; + + EventHandler.prototype.onEventGeneric = 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["b" /* logger */].error('internal error happened while processing ' + event + ':' + err.message); + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: false, event: event, err: err }); + } + }; + + return EventHandler; +}(); + +/* harmony default export */ var event_handler = (event_handler_EventHandler); +// CONCATENATED MODULE: ./src/utils/attr-list.js +function attr_list__classCallCheck(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) { + attr_list__classCallCheck(this, AttrList); + + if (typeof attrs === 'string') { + attrs = AttrList.parseAttrList(attrs); + } + for (var attr in attrs) { + if (attrs.hasOwnProperty(attr)) { + this[attr] = attrs[attr]; + } + } + } + + AttrList.prototype.decimalInteger = function decimalInteger(attrName) { + var intValue = parseInt(this[attrName], 10); + if (intValue > Number.MAX_SAFE_INTEGER) { + return Infinity; + } + return intValue; + }; + + AttrList.prototype.hexadecimalInteger = 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; + } + }; + + AttrList.prototype.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) { + var intValue = parseInt(this[attrName], 16); + if (intValue > Number.MAX_SAFE_INTEGER) { + return Infinity; + } + return intValue; + }; + + AttrList.prototype.decimalFloatingPoint = function decimalFloatingPoint(attrName) { + return parseFloat(this[attrName]); + }; + + AttrList.prototype.enumeratedString = function enumeratedString(attrName) { + return this[attrName]; + }; + + AttrList.prototype.decimalResolution = 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) + }; + }; + + AttrList.parseAttrList = 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; +}(); + +/* harmony default export */ var attr_list = (AttrList); +// CONCATENATED MODULE: ./src/utils/codecs.js +// from http://mp4ra.org/codecs.html +var sampleEntryCodesISO = { + audio: { + 'a3ds': true, + 'ac-3': true, + 'ac-4': true, + 'alac': true, + 'alaw': true, + 'dra1': true, + 'dts+': true, + 'dts-': true, + 'dtsc': true, + 'dtse': true, + 'dtsh': true, + 'ec-3': true, + 'enca': true, + 'g719': true, + 'g726': true, + 'm4ae': true, + 'mha1': true, + 'mha2': true, + 'mhm1': true, + 'mhm2': true, + 'mlpa': true, + 'mp4a': true, + 'raw ': true, + 'Opus': true, + 'samr': true, + 'sawb': true, + 'sawp': true, + 'sevc': true, + 'sqcp': true, + 'ssmv': true, + 'twos': true, + 'ulaw': true + }, + video: { + 'avc1': true, + 'avc2': true, + 'avc3': true, + 'avc4': true, + 'avcp': true, + 'drac': true, + 'dvav': true, + 'dvhe': true, + 'encv': true, + 'hev1': true, + 'hvc1': true, + 'mjp2': true, + 'mp4v': true, + 'mvc1': true, + 'mvc2': true, + 'mvc3': true, + 'mvc4': true, + 'resv': true, + 'rv60': true, + 's263': true, + 'svc1': true, + 'svc2': true, + 'vc-1': true, + 'vp08': true, + 'vp09': true + } +}; + +function isCodecType(codec, type) { + var typeCodes = sampleEntryCodesISO[type]; + return !!typeCodes && typeCodes[codec.slice(0, 4)] === true; +} + +function isCodecSupportedInMp4(codec, type) { + return MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"'); +} + + +// CONCATENATED MODULE: ./src/loader/playlist-loader.js +var _createClass = 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 _possibleConstructorReturn(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(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 playlist_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Playlist Loader +*/ + + + + + + + + + +// 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:\s*(\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 playlist_loader_LevelKey = function () { + function LevelKey() { + playlist_loader__classCallCheck(this, LevelKey); + + this.method = null; + this.key = null; + this.iv = null; + this._uri = null; + } + + _createClass(LevelKey, [{ + key: 'uri', + get: function get() { + if (!this._uri && this.reluri) { + this._uri = url_toolkit_default.a.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true }); + } + return this._uri; + } + }]); + + return LevelKey; +}(); + +var playlist_loader_Fragment = function () { + function Fragment() { + playlist_loader__classCallCheck(this, Fragment); + + this._url = null; + this._byteRange = null; + this._decryptdata = null; + this.tagList = []; + } + + /** + * Utility method for parseLevelPlaylist to create an initialization vector for a given segment + * @returns {Uint8Array} + */ + Fragment.prototype.createInitializationVector = 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 + */ + + + Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) { + var decryptdata = levelkey; + + if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) { + decryptdata = new playlist_loader_LevelKey(); + decryptdata.method = levelkey.method; + decryptdata.baseuri = levelkey.baseuri; + decryptdata.reluri = levelkey.reluri; + decryptdata.iv = this.createInitializationVector(segmentNumber); + } + + return decryptdata; + }; + + Fragment.prototype.cloneObj = function cloneObj(obj) { + return JSON.parse(JSON.stringify(obj)); + }; + + _createClass(Fragment, [{ + key: 'url', + get: function get() { + if (!this._url && this.relurl) { + this._url = url_toolkit_default.a.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; +}(); + +function findGroup(groups, mediaGroupId) { + if (!groups) { + return null; + } + + var matchingGroup = null; + + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + if (group.id === mediaGroupId) { + matchingGroup = group; + } + } + + return matchingGroup; +} + +var playlist_loader_PlaylistLoader = function (_EventHandler) { + _inherits(PlaylistLoader, _EventHandler); + + function PlaylistLoader(hls) { + playlist_loader__classCallCheck(this, PlaylistLoader); + + var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].LEVEL_LOADING, events["a" /* default */].AUDIO_TRACK_LOADING, events["a" /* default */].SUBTITLE_TRACK_LOADING)); + + _this.loaders = {}; + return _this; + } + + PlaylistLoader.prototype.destroy = function destroy() { + for (var loaderName in this.loaders) { + var loader = this.loaders[loaderName]; + if (loader) { + loader.destroy(); + } + } + this.loaders = {}; + event_handler.prototype.destroy.call(this); + }; + + PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) { + this.load(data.url, { type: 'manifest' }); + }; + + PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) { + this.load(data.url, { type: 'level', level: data.level, id: data.id }); + }; + + PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) { + this.load(data.url, { type: 'audioTrack', id: data.id }); + }; + + PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) { + this.load(data.url, { type: 'subtitleTrack', id: data.id }); + }; + + PlaylistLoader.prototype.load = function load(url, context) { + var loader = this.loaders[context.type]; + if (loader !== undefined) { + var loaderContext = loader.context; + if (loaderContext && loaderContext.url === url) { + logger["b" /* logger */].trace('playlist request ongoing'); + return; + } else { + logger["b" /* logger */].warn('abort previous loader for type:' + context.type); + loader.abort(); + } + } + var config = this.hls.config, + maxRetry = void 0, + timeout = void 0, + retryDelay = void 0, + maxRetryDelay = void 0; + if (context.type === 'manifest') { + maxRetry = config.manifestLoadingMaxRetry; + timeout = config.manifestLoadingTimeOut; + retryDelay = config.manifestLoadingRetryDelay; + maxRetryDelay = config.manifestLoadingMaxRetryTimeout; + } else if (context.type === 'level') { + // Disable internal loader retry logic, since we are managing retries in Level Controller + maxRetry = 0; + timeout = config.levelLoadingTimeOut; + } else { + // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config + maxRetry = config.levelLoadingMaxRetry; + timeout = config.levelLoadingTimeOut; + retryDelay = config.levelLoadingRetryDelay; + maxRetryDelay = config.levelLoadingMaxRetryTimeout; + logger["b" /* 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: maxRetry, 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); + }; + + PlaylistLoader.prototype.resolve = function resolve(url, baseUrl) { + return url_toolkit_default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true }); + }; + + PlaylistLoader.prototype.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) { + var levels = [], + result = void 0; + MASTER_PLAYLIST_REGEX.lastIndex = 0; + + function setCodecs(codecs, level) { + ['video', 'audio'].forEach(function (type) { + var filtered = codecs.filter(function (codec) { + return isCodecType(codec, type); + }); + if (filtered.length) { + var preferred = filtered.filter(function (codec) { + return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0; + }); + level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0]; + + // remove from list + codecs = codecs.filter(function (codec) { + return filtered.indexOf(codec) === -1; + }); + } + }); + + level.unknownCodecs = codecs; + } + + while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) { + var level = {}; + + var attrs = level.attrs = new attr_list(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; + + setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level); + + if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) { + level.videoCodec = this.avc1toavcoti(level.videoCodec); + } + + levels.push(level); + } + return levels; + }; + + PlaylistLoader.prototype.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type) { + var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + + var result = void 0; + var medias = []; + var id = 0; + MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0; + while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) { + var media = {}; + var attrs = new attr_list(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 (audioGroups.length) { + var groupCodec = findGroup(audioGroups, media.groupId); + media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec; + } + media.id = id++; + medias.push(media); + } + } + return medias; + }; + + PlaylistLoader.prototype.avc1toavcoti = 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; + }; + + PlaylistLoader.prototype.parseLevelPlaylist = 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 playlist_loader_LevelKey(), + cc = 0, + prevFrag = null, + frag = new playlist_loader_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 playlist_loader_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]); + if (level.programDateTime === undefined) { + level.programDateTime = new Date(new Date(Date.parse(result[5])) - 1000 * totalduration); + } + } 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 attr_list(decryptparams); + var decryptmethod = keyAttrs.enumeratedString('METHOD'), + decrypturi = keyAttrs.URI, + decryptiv = keyAttrs.hexadecimalInteger('IV'); + if (decryptmethod) { + levelkey = new playlist_loader_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 attr_list(startParams); + var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); + //TIME-OFFSET can be 0 + if (!isNaN(startTimeOffset)) { + level.startTimeOffset = startTimeOffset; + } + break; + case 'MAP': + var mapAttrs = new attr_list(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 playlist_loader_Fragment(); + break; + default: + logger["b" /* 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; + level.startCC = level.fragments[0] ? level.fragments[0].cc : 0; + level.endCC = cc; + return level; + }; + + PlaylistLoader.prototype.loadsuccess = 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(events["a" /* 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(events["a" /* default */].LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails }); + } else { + if (type === 'audioTrack') { + hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails }); + } else if (type === 'subtitleTrack') { + hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails }); + } + } + } else { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* 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 audioGroups = levels.map(function (l) { + return { id: l.attrs.AUDIO, codec: l.audioCodec }; + }); + var audioTracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups); + 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["b" /* logger */].log('audio codec signaled in quality level, but no embedded audio track signaled, create one'); + audioTracks.unshift({ type: 'main', name: 'main' }); + } + } + hls.trigger(events["a" /* default */].MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, url: url, stats: stats, networkDetails: networkDetails }); + } else { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest', networkDetails: networkDetails }); + } + } + } else { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter', networkDetails: networkDetails }); + } + }; + + PlaylistLoader.prototype.loaderror = 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["a" /* ErrorDetails */].MANIFEST_LOAD_ERROR; + fatal = true; + break; + case 'level': + details = errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR; + fatal = false; + break; + case 'audioTrack': + details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR; + fatal = false; + break; + } + if (loader) { + loader.abort(); + this.loaders[context.type] = undefined; + } + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context: context, networkDetails: networkDetails }); + }; + + PlaylistLoader.prototype.loadtimeout = 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["a" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT; + fatal = true; + break; + case 'level': + details = errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT; + fatal = false; + break; + case 'audioTrack': + details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT; + fatal = false; + break; + } + if (loader) { + loader.abort(); + this.loaders[context.type] = undefined; + } + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context: context, networkDetails: networkDetails }); + }; + + return PlaylistLoader; +}(event_handler); + +/* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader); +// CONCATENATED MODULE: ./src/loader/fragment-loader.js +function fragment_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fragment_loader__possibleConstructorReturn(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 fragment_loader__inherits(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 fragment_loader_FragmentLoader = function (_EventHandler) { + fragment_loader__inherits(FragmentLoader, _EventHandler); + + function FragmentLoader(hls) { + fragment_loader__classCallCheck(this, FragmentLoader); + + var _this = fragment_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING)); + + _this.loaders = {}; + return _this; + } + + FragmentLoader.prototype.destroy = function destroy() { + var loaders = this.loaders; + for (var loaderName in loaders) { + var loader = loaders[loaderName]; + if (loader) { + loader.destroy(); + } + } + this.loaders = {}; + event_handler.prototype.destroy.call(this); + }; + + FragmentLoader.prototype.onFragLoading = function onFragLoading(data) { + var frag = data.frag, + type = frag.type, + loader = this.loaders[type], + config = this.hls.config; + + frag.loaded = 0; + if (loader) { + logger["b" /* 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); + }; + + FragmentLoader.prototype.loadsuccess = 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(events["a" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails }); + }; + + FragmentLoader.prototype.loaderror = 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails }); + }; + + FragmentLoader.prototype.loadtimeout = 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails }); + }; + + // data will be used for progressive parsing + + + FragmentLoader.prototype.loadprogress = 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(events["a" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails }); + }; + + return FragmentLoader; +}(event_handler); + +/* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader); +// CONCATENATED MODULE: ./src/loader/key-loader.js +function key_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function key_loader__possibleConstructorReturn(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 key_loader__inherits(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 key_loader_KeyLoader = function (_EventHandler) { + key_loader__inherits(KeyLoader, _EventHandler); + + function KeyLoader(hls) { + key_loader__classCallCheck(this, KeyLoader); + + var _this = key_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].KEY_LOADING)); + + _this.loaders = {}; + _this.decryptkey = null; + _this.decrypturl = null; + return _this; + } + + KeyLoader.prototype.destroy = function destroy() { + for (var loaderName in this.loaders) { + var loader = this.loaders[loaderName]; + if (loader) { + loader.destroy(); + } + } + this.loaders = {}; + event_handler.prototype.destroy.call(this); + }; + + KeyLoader.prototype.onKeyLoading = 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["b" /* 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(events["a" /* default */].KEY_LOADED, { frag: frag }); + } + }; + + KeyLoader.prototype.loadsuccess = 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(events["a" /* default */].KEY_LOADED, { frag: frag }); + }; + + KeyLoader.prototype.loaderror = function loaderror(response, context) { + var frag = context.frag, + loader = frag.loader; + if (loader) { + loader.abort(); + } + this.loaders[context.type] = undefined; + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response }); + }; + + KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) { + var frag = context.frag, + loader = frag.loader; + if (loader) { + loader.abort(); + } + this.loaders[context.type] = undefined; + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag }); + }; + + return KeyLoader; +}(event_handler); + +/* harmony default export */ var key_loader = (key_loader_KeyLoader); +// CONCATENATED MODULE: ./src/utils/binary-search.js +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; + } +}; + +/* harmony default export */ var binary_search = (BinarySearch); +// CONCATENATED MODULE: ./src/helper/buffer-helper.js +/** + * Buffer Helper utils, providing methods dealing buffer length retrieval +*/ + +var BufferHelper = { + isBuffered: function isBuffered(media, position) { + try { + 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; + } + } + } + } catch (error) { + // this is to catch + // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': + // This SourceBuffer has been removed from the parent media source + } + return false; + }, + + bufferInfo: function bufferInfo(media, pos, maxHoleDuration) { + try { + 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); + } + } catch (error) { + // this is to catch + // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': + // This SourceBuffer has been removed from the parent media source + } + 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 }; + } +}; + +/* harmony default export */ var buffer_helper = (BufferHelper); +// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 12 modules +var demuxer_inline = __webpack_require__(7); + +// EXTERNAL MODULE: ./node_modules/events/events.js +var events_events = __webpack_require__(5); +var events_default = /*#__PURE__*/__webpack_require__.n(events_events); + +// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js +var webworkify_webpack = __webpack_require__(9); +var webworkify_webpack_default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack); + +// CONCATENATED MODULE: ./src/helper/mediasource-helper.js +/** + * MediaSource helper + */ + +function getMediaSource() { + if (typeof window !== 'undefined') { + return window.MediaSource || window.WebKitMediaSource; + } +} +// CONCATENATED MODULE: ./src/demux/demuxer.js +function demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + + + + +var demuxer_MediaSource = getMediaSource(); + +var demuxer_Demuxer = function () { + function Demuxer(hls, id) { + demuxer__classCallCheck(this, Demuxer); + + this.hls = hls; + this.id = id; + // observer setup + var observer = this.observer = new events_default.a(); + 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(events["a" /* default */].FRAG_DECRYPTED, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_DATA, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSED, forwardMessage); + observer.on(events["a" /* default */].ERROR, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_METADATA, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage); + observer.on(events["a" /* default */].INIT_PTS_FOUND, forwardMessage); + + var typeSupported = { + mp4: demuxer_MediaSource.isTypeSupported('video/mp4'), + mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'), + mp3: demuxer_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["b" /* logger */].log('demuxing in webworker'); + var w = void 0; + try { + w = this.w = webworkify_webpack_default()(/*require.resolve*/(10)); + this.onwmsg = this.onWorkerMessage.bind(this); + w.addEventListener('message', this.onwmsg); + w.onerror = function (event) { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* 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["b" /* 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 demuxer_inline["a" /* default */](observer, typeSupported, config, vendor); + this.w = undefined; + } + } else { + this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor); + } + } + + Demuxer.prototype.destroy = 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; + } + }; + + Demuxer.prototype.push = 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["b" /* logger */].log(this.id + ':discontinuity detected'); + } + if (trackSwitch) { + logger["b" /* logger */].log(this.id + ':switch detected'); + } + this.frag = frag; + if (w) { + // post fragment payload as transferable objects for ArrayBuffer (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 instanceof ArrayBuffer ? [data] : []); + } else { + var demuxer = this.demuxer; + if (demuxer) { + demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); + } + } + }; + + Demuxer.prototype.onWorkerMessage = 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 events["a" /* 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; +}(); + +/* harmony default export */ var demux_demuxer = (demuxer_Demuxer); +// CONCATENATED MODULE: ./src/helper/level-helper.js +/** + * Level Helper class, providing methods dealing with playlist sliding and drift +*/ + + + +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["b" /* 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["b" /* 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); + } + } +} + +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; + // update frag reference in fragments array + // rationale is that fragments array might not contain this frag object. + // this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS() + // if we don't update frag, we won't be able to propagate PTS info on the playlist + // resulting in invalid sliding computation + fragments[fragIdx] = frag; + // adjust fragment PTS/duration from seqnum-1 to frag 0 + for (i = fragIdx; i > 0; i--) { + updatePTS(fragments, i, i - 1); + } + + // adjust fragment PTS/duration from seqnum to last frag + for (i = fragIdx; i < fragments.length - 1; i++) { + updatePTS(fragments, i, i + 1); + } + details.PTSKnown = true; + //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`); + + return drift; +} + +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["b" /* 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) { + 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; +} +// CONCATENATED MODULE: ./src/utils/timeRanges.js +/** + * 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; + } +}; + +/* harmony default export */ var timeRanges = (TimeRanges); +// CONCATENATED MODULE: ./src/utils/discontinuities.js + + + +function findFirstFragWithCC(fragments, cc) { + var firstFrag = null; + + for (var i = 0; i < fragments.length; i += 1) { + var currentFrag = fragments[i]; + if (currentFrag && currentFrag.cc === cc) { + firstFrag = currentFrag; + break; + } + } + + return firstFrag; +} + +function findFragWithCC(fragments, CC) { + return binary_search.search(fragments, function (candidate) { + if (candidate.cc < CC) { + return 1; + } else if (candidate.cc > CC) { + return -1; + } else { + return 0; + } + }); +} + +function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) { + var shouldAlign = false; + if (lastLevel && lastLevel.details && details) { + if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) { + shouldAlign = true; + } + } + return shouldAlign; +} + +// Find the first frag in the previous level which matches the CC of the first frag of the new level +function findDiscontinuousReferenceFrag(prevDetails, curDetails) { + var prevFrags = prevDetails.fragments; + var curFrags = curDetails.fragments; + + if (!curFrags.length || !prevFrags.length) { + logger["b" /* logger */].log('No fragments to align'); + return; + } + + var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc); + + if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) { + logger["b" /* logger */].log('No frag in previous level to align on'); + return; + } + + return prevStartFrag; +} + +function adjustPts(sliding, details) { + details.fragments.forEach(function (frag) { + if (frag) { + var start = frag.start + sliding; + frag.start = frag.startPTS = start; + frag.endPTS = start + frag.duration; + } + }); + details.PTSKnown = true; +} + +// If a change in CC is detected, the PTS can no longer be relied upon +// Attempt to align the level by using the last level - find the last frag matching the current CC and use it's PTS +// as a reference +function alignDiscontinuities(lastFrag, lastLevel, details) { + if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) { + var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details); + if (referenceFrag) { + logger["b" /* logger */].log('Adjusting PTS using last level due to CC increase within current level'); + adjustPts(referenceFrag.start, details); + } + } + // try to align using programDateTime attribute (if available) + if (details.PTSKnown === false && lastLevel && lastLevel.details) { + // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM + // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM + // then we can deduce that playlist B sliding is 1000+8 = 1008s + var lastPDT = lastLevel.details.programDateTime; + var newPDT = details.programDateTime; + // date diff is in ms. frag.start is in seconds + var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start; + if (!isNaN(sliding)) { + logger["b" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3)); + adjustPts(sliding, details); + } + } +} +// CONCATENATED MODULE: ./src/controller/stream-controller.js +var stream_controller__createClass = 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 stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function stream_controller__possibleConstructorReturn(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 stream_controller__inherits(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 stream_controller_StreamController = function (_EventHandler) { + stream_controller__inherits(StreamController, _EventHandler); + + function StreamController(hls) { + stream_controller__classCallCheck(this, StreamController); + + var _this = stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_SWITCHED, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* 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; + } + + StreamController.prototype.destroy = function destroy() { + this.stopLoad(); + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + event_handler.prototype.destroy.call(this); + this.state = State.STOPPED; + }; + + StreamController.prototype.startLoad = 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["b" /* 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; + } + }; + + StreamController.prototype.stopLoad = 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; + }; + + StreamController.prototype.tick = function tick() { + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(this.tick, 1); + } + this.ticks = 0; + } + }; + + StreamController.prototype.doTick = 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["b" /* 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? + + + StreamController.prototype._doTickIdle = function _doTickIdle() { + var hls = this.hls, + config = hls.config, + media = this.media; + + // if start level not parsed yet OR + // if video not attached AND start fragment already requested OR start frag prefetch disable + // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment + 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 = buffer_helper.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["b" /* 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 (levelDetails === undefined || levelDetails.live === true && this.levelLastLoaded !== level) { + this.state = State.WAITING_LEVEL; + return; + } + + // we just got done loading the final fragment and there is no other buffered range after ... + // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between + // so we should not switch to ENDED in that case, to be able to buffer them + // dont switch to ENDED if we need to backtrack last fragment + var fragPrevious = this.fragPrevious; + if (!levelDetails.live && fragPrevious && !fragPrevious.backtracked && fragPrevious.sn === levelDetails.endSN && !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(events["a" /* 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); + }; + + StreamController.prototype._fetchPayloadOrEos = 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["b" /* 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; + }; + + StreamController.prototype._ensureFragmentAtLivePoint = 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["b" /* 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) { + var fragNext = fragments[targetSN - levelDetails.startSN]; + if (fragPrevious.cc === fragNext.cc) { + frag = fragNext; + logger["b" /* logger */].log('live playlist, switching playlist, load frag with next SN: ' + frag.sn); + } + } + // next frag SN not available (or not with same continuity counter) + // look for a frag sharing the same CC + if (!frag) { + frag = binary_search.search(fragments, function (frag) { + return fragPrevious.cc - frag.cc; + }); + if (frag) { + logger["b" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + 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["b" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn); + } + } + return frag; + }; + + StreamController.prototype._findFragment = 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 + (candidate.deltaPTS ? candidate.deltaPTS : 0)); + 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 = binary_search.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["b" /* 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["b" /* 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["b" /* 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["b" /* 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; + }; + + StreamController.prototype._loadFragmentOrKey = 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["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level); + this.state = State.KEY_LOADING; + hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + } else { + logger["b" /* 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag }); + return; + } + } else { + frag.loadCounter = 1; + } + frag.loadIdx = this.fragLoadIdx; + frag.autoLevel = hls.autoLevelEnabled; + frag.bitrateTest = this.bitrateTest; + + this.fragCurrent = frag; + this.startFragRequested = true; + // Don't update nextLoadPosition for fragments which are not buffered + if (!isNaN(frag.sn) && !frag.bitrateTest) { + this.nextLoadPosition = frag.start + frag.duration; + } + hls.trigger(events["a" /* 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 demux_demuxer(hls, 'main'); + } + this.state = State.FRAG_LOADING; + return; + } + }; + + StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) { + return binary_search.search(this._bufferedFrags, function (frag) { + if (position < frag.startPTS) { + return -1; + } else if (position > frag.endPTS) { + return 1; + } + return 0; + }); + }; + + StreamController.prototype.followingBufferedFrag = 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; + }; + + StreamController.prototype._checkFragmentChanged = 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 (buffer_helper.isBuffered(video, currentTime)) { + fragPlayingCurrent = this.getBufferedFrag(currentTime); + } else if (buffer_helper.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(events["a" /* default */].FRAG_CHANGED, { frag: fragPlaying }); + var fragPlayingLevel = fragPlaying.level; + if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) { + this.hls.trigger(events["a" /* 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 + */ + + + StreamController.prototype.immediateLevelSwitch = function immediateLevelSwitch() { + logger["b" /* 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 + if (this.fragLoadIdx !== undefined) { + 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 + */ + + + StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() { + var media = this.media; + if (media && media.buffered.length) { + this.immediateSwitch = false; + if (buffer_helper.isBuffered(media, media.currentTime)) { + // only nudge if currentTime is buffered + media.currentTime -= 0.0001; + } + if (!this.previouslyPaused) { + media.play(); + } + } + }; + + StreamController.prototype.nextLevelSwitch = 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; + if (this.fragLoadIdx !== undefined) { + // 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); + } + } + } + }; + + StreamController.prototype.flushMainBuffer = 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(events["a" /* default */].BUFFER_FLUSHING, flushScope); + }; + + StreamController.prototype.onMediaAttached = 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); + } + }; + + StreamController.prototype.onMediaDetaching = function onMediaDetaching() { + var media = this.media; + if (media && media.ended) { + logger["b" /* 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(); + }; + + StreamController.prototype.onMediaSeeking = function onMediaSeeking() { + var media = this.media, + currentTime = media ? media.currentTime : undefined, + config = this.config; + if (!isNaN(currentTime)) { + logger["b" /* logger */].log('media seeking to ' + currentTime.toFixed(3)); + } + var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media; + var bufferInfo = buffer_helper.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["b" /* 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["b" /* 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(); + }; + + StreamController.prototype.onMediaSeeked = function onMediaSeeked() { + var media = this.media, + currentTime = media ? media.currentTime : undefined; + if (!isNaN(currentTime)) { + logger["b" /* logger */].log('media seeked to ' + currentTime.toFixed(3)); + } + // tick to speed up FRAGMENT_PLAYING triggering + this.tick(); + }; + + StreamController.prototype.onMediaEnded = function onMediaEnded() { + logger["b" /* logger */].log('media ended'); + // reset startPosition and lastCurrentTime to restart playback @ stream beginning + this.startPosition = this.lastCurrentTime = 0; + }; + + StreamController.prototype.onManifestLoading = function onManifestLoading() { + // reset buffer on manifest loading + logger["b" /* logger */].log('trigger BUFFER_RESET'); + this.hls.trigger(events["a" /* default */].BUFFER_RESET); + this._bufferedFrags = []; + this.stalled = false; + this.startPosition = this.lastCurrentTime = 0; + }; + + StreamController.prototype.onManifestParsed = 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["b" /* logger */].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'); + } + this.levels = data.levels; + this.startFragRequested = false; + var config = this.config; + if (config.autoStartLoad || this.forceStartLoad) { + this.hls.startLoad(config.startPosition); + } + }; + + StreamController.prototype.onLevelLoaded = function onLevelLoaded(data) { + var newDetails = data.details; + var newLevelId = data.level; + var lastLevel = this.levels[this.levelLastLoaded]; + var curLevel = this.levels[newLevelId]; + var duration = newDetails.totalduration; + var sliding = 0; + + logger["b" /* logger */].log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration); + + if (newDetails.live) { + var curDetails = curLevel.details; + if (curDetails && newDetails.fragments.length > 0) { + // we already have details for that level, merge them + mergeDetails(curDetails, newDetails); + sliding = newDetails.fragments[0].start; + this.liveSyncPosition = this.computeLivePosition(sliding, curDetails); + if (newDetails.PTSKnown && !isNaN(sliding)) { + logger["b" /* logger */].log('live playlist sliding:' + sliding.toFixed(3)); + } else { + logger["b" /* logger */].log('live playlist - outdated PTS, unknown sliding'); + alignDiscontinuities(this.fragPrevious, lastLevel, newDetails); + } + } else { + logger["b" /* logger */].log('live playlist - first load, unknown sliding'); + newDetails.PTSKnown = false; + alignDiscontinuities(this.fragPrevious, lastLevel, newDetails); + } + } else { + newDetails.PTSKnown = false; + } + // override level info + curLevel.details = newDetails; + this.levelLastLoaded = newLevelId; + this.hls.trigger(events["a" /* 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["b" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment'); + startTimeOffset = sliding + duration + startTimeOffset; + } + logger["b" /* 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["b" /* 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(); + }; + + StreamController.prototype.onKeyLoaded = function onKeyLoaded() { + if (this.state === State.KEY_LOADING) { + this.state = State.IDLE; + this.tick(); + } + }; + + StreamController.prototype.onFragLoaded = 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["b" /* 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(events["a" /* 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(events["a" /* 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["b" /* 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["b" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc); + var demuxer = this.demuxer; + if (!demuxer) { + demuxer = this.demuxer = new demux_demuxer(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; + }; + + StreamController.prototype.onFragParsingInitSegment = 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["b" /* 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["b" /* 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(events["a" /* default */].BUFFER_CODECS, tracks); + // loop through tracks that are going to be provided to bufferController + for (trackName in tracks) { + track = tracks[trackName]; + logger["b" /* 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(events["a" /* default */].BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' }); + } + } + //trigger handler right now + this.tick(); + } + }; + + StreamController.prototype.onFragParsingData = 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["b" /* 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) { + var levelDetails = level.details; + if (levelDetails && frag.sn === levelDetails.startSN) { + logger["b" /* logger */].warn('missing video frame(s) on first frag, appending with gap'); + } else { + logger["b" /* 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["b" /* 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 = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS), + hls = this.hls; + hls.trigger(events["a" /* 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(events["a" /* default */].BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' }); + } + }); + //trigger handler right now + this.tick(); + } + }; + + StreamController.prototype.onFragParsed = 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(); + } + }; + + StreamController.prototype.onAudioTrackSwitching = 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["b" /* 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["b" /* 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(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId }); + this.altAudio = false; + } + }; + + StreamController.prototype.onAudioTrackSwitched = 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["b" /* logger */].log('switching on alternate audio, use video.buffered to schedule main fragment loading'); + this.mediaBuffer = videoBuffer; + } + } + this.altAudio = altAudio; + this.tick(); + }; + + StreamController.prototype.onBufferCreated = 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["b" /* logger */].log('alternate track found, use ' + name + '.buffered to schedule main fragment loading'); + this.mediaBuffer = mediaTrack.buffer; + } else { + this.mediaBuffer = this.media; + } + }; + + StreamController.prototype.onBufferAppended = 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(); + } + } + }; + + StreamController.prototype._checkAppendedParsed = 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["b" /* logger */].log('main buffered : ' + timeRanges.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 buffer_helper.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(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' }); + this.state = State.IDLE; + } + this.tick(); + } + }; + + StreamController.prototype.onError = 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; + } + // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end + var mediaBuffered = !!this.media && buffer_helper.isBuffered(this.media, this.media.currentTime) && buffer_helper.isBuffered(this.media, this.media.currentTime + 0.5); + + switch (data.details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT: + if (!data.fatal) { + // keep retrying until the limit will be reached + if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) { + // exponential backoff capped to config.fragLoadingMaxRetryTimeout + var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout); + // reset load counter to avoid frag loop loading error + frag.loadCounter = 0; + logger["b" /* 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.fragLoadError++; + this.state = State.FRAG_LOADING_WAITING_RETRY; + } else { + logger["b" /* 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["a" /* 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["a" /* ErrorDetails */].LEVEL_LOAD_ERROR: + case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT: + if (this.state !== State.ERROR) { + if (data.fatal) { + // if fatal error, stop processing + this.state = State.ERROR; + logger["b" /* 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["a" /* 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["b" /* 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; + } + }; + + StreamController.prototype._reduceMaxBufferLength = 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["b" /* logger */].warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's'); + if (this.fragLoadIdx !== undefined) { + // increase fragment load Index to avoid frag loop loading error after buffer flush + this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold; + } + } + }; + + StreamController.prototype._checkBuffer = 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 = buffer_helper.isBuffered(mediaBuffer, startPosition), + firstbufferedPosition = buffered.start(0), + startNotBufferedButClose = !startPositionBuffered && Math.abs(startPosition - firstbufferedPosition) < config.maxSeekHole; + // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered + if (currentTime !== startPosition || startNotBufferedButClose) { + logger["b" /* logger */].log('target start position:' + startPosition); + // if startPosition not buffered, let's seek to buffered.start(0) + if (startNotBufferedButClose) { + startPosition = firstbufferedPosition; + logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition); + } + logger["b" /* logger */].log('adjust currentTime from ' + currentTime + ' to ' + startPosition); + media.currentTime = startPosition; + } + } else if (this.immediateSwitch) { + this.immediateLevelSwitchEnd(); + } else { + var bufferInfo = buffer_helper.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["b" /* 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["b" /* logger */].warn('playback stalling in low buffer @' + currentTime); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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["b" /* 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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["b" /* logger */].warn('playback stalling in high buffer @' + currentTime); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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["b" /* 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_NUDGE_ON_STALL, fatal: false }); + } else { + logger["b" /* logger */].error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error'); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: true }); + } + } + } + } + } + } + } + }; + + StreamController.prototype.onFragLoadEmergencyAborted = 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(); + }; + + StreamController.prototype.onBufferFlushed = 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 buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2); + }); + + if (this.fragLoadIdx !== undefined) { + // 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; + }; + + StreamController.prototype.swapAudioCodec = function swapAudioCodec() { + this.audioCodecSwap = !this.audioCodecSwap; + }; + + StreamController.prototype.computeLivePosition = 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); + }; + + stream_controller__createClass(StreamController, [{ + key: 'state', + set: function set(nextState) { + if (this.state !== nextState) { + var previousState = this.state; + this._state = nextState; + logger["b" /* logger */].log('main stream:' + previousState + '->' + nextState); + this.hls.trigger(events["a" /* 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; +}(event_handler); + +/* harmony default export */ var stream_controller = (stream_controller_StreamController); +// CONCATENATED MODULE: ./src/controller/level-controller.js +var level_controller__createClass = 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 level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function level_controller__possibleConstructorReturn(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 level_controller__inherits(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 level_controller_LevelController = function (_EventHandler) { + level_controller__inherits(LevelController, _EventHandler); + + function LevelController(hls) { + level_controller__classCallCheck(this, LevelController); + + var _this = level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].ERROR)); + + _this.canload = false; + _this.currentLevelIndex = null; + _this.manualLevelIndex = -1; + _this.timer = null; + return _this; + } + + LevelController.prototype.destroy = function destroy() { + this.cleanTimer(); + this.manualLevelIndex = -1; + }; + + LevelController.prototype.cleanTimer = function cleanTimer() { + if (this.timer !== null) { + clearTimeout(this.timer); + this.timer = null; + } + }; + + LevelController.prototype.startLoad = function startLoad() { + var levels = this._levels; + + this.canload = true; + this.levelRetryCount = 0; + + // 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 !== null) { + this.loadLevel(); + } + }; + + LevelController.prototype.stopLoad = function stopLoad() { + this.canload = false; + }; + + LevelController.prototype.onManifestLoaded = function onManifestLoaded(data) { + var levels = []; + var bitrateStart = void 0; + var levelSet = {}; + var levelFromSet = null; + var videoCodecFound = false; + var audioCodecFound = false; + var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase()); + var audioTracks = []; + + // regroup redundant levels together + data.levels.forEach(function (level) { + level.loadError = 0; + level.fragmentError = false; + + videoCodecFound = videoCodecFound || !!level.videoCodec; + audioCodecFound = audioCodecFound || !!level.audioCodec || !!(level.attrs && level.attrs.AUDIO); + + // erase audio codec info if browser does not support mp4a.40.34. + // demuxer will autodetect codec and fallback to mpeg/audio + if (chromeOrFirefox === true && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) { + level.audioCodec = undefined; + } + + levelFromSet = levelSet[level.bitrate]; + + if (levelFromSet === undefined) { + level.url = [level.url]; + level.urlId = 0; + levelSet[level.bitrate] = level; + levels.push(level); + } else { + levelFromSet.url.push(level.url); + } + }); + + // remove audio-only level if we also have levels with audio+video codecs signalled + if (videoCodecFound === true && audioCodecFound === true) { + levels = levels.filter(function (_ref) { + var videoCodec = _ref.videoCodec; + return !!videoCodec; + }); + } + + // only keep levels with supported audio/video codecs + levels = levels.filter(function (_ref2) { + var audioCodec = _ref2.audioCodec, + videoCodec = _ref2.videoCodec; + + return (!audioCodec || isCodecSupportedInMp4(audioCodec)) && (!videoCodec || isCodecSupportedInMp4(videoCodec)); + }); + + if (data.audioTracks) { + audioTracks = data.audioTracks.filter(function (track) { + return !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'); + }); + } + + if (levels.length > 0) { + // 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["b" /* logger */].log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart); + break; + } + } + this.hls.trigger(events["a" /* default */].MANIFEST_PARSED, { + levels: levels, + audioTracks: audioTracks, + firstLevel: this._firstLevel, + stats: data.stats, + audio: audioCodecFound, + video: videoCodecFound, + altAudio: audioTracks.length > 0 + }); + } else { + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].MANIFEST_INCOMPATIBLE_CODECS_ERROR, + fatal: true, + url: this.hls.url, + reason: 'no level with compatible codecs found in manifest' + }); + } + }; + + LevelController.prototype.setLevelInternal = 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 + this.cleanTimer(); + if (this.currentLevelIndex !== newLevel) { + logger["b" /* logger */].log('switching to level ' + newLevel); + this.currentLevelIndex = newLevel; + var levelProperties = levels[newLevel]; + levelProperties.level = newLevel; + // LEVEL_SWITCH to be deprecated in next major release + hls.trigger(events["a" /* default */].LEVEL_SWITCH, levelProperties); + hls.trigger(events["a" /* 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(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId }); + } + } else { + // invalid level id given, trigger error + hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].OTHER_ERROR, + details: errors["a" /* ErrorDetails */].LEVEL_SWITCH_ERROR, + level: newLevel, + fatal: false, + reason: 'invalid level idx' + }); + } + }; + + LevelController.prototype.onError = function onError(data) { + if (data.fatal === true) { + if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) { + this.cleanTimer(); + } + return; + } + + var levelError = false, + fragmentError = false; + var levelIndex = void 0; + + // try to recover not fatal errors + switch (data.details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT: + levelIndex = data.frag.level; + fragmentError = true; + break; + case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR: + case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT: + levelIndex = data.context.level; + levelError = true; + break; + case errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR: + levelIndex = data.level; + levelError = true; + break; + } + + if (levelIndex !== undefined) { + this.recoverLevel(data, levelIndex, levelError, fragmentError); + } + }; + + /** + * Switch to a redundant stream if any available. + * If redundant stream is not available, emergency switch down if ABR mode is enabled. + * + * @param {Object} errorEvent + * @param {Number} levelIndex current level index + * @param {Boolean} levelError + * @param {Boolean} fragmentError + */ + // FIXME Find a better abstraction where fragment/level retry management is well decoupled + + + LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) { + var _this2 = this; + + var config = this.hls.config; + var errorDetails = errorEvent.details; + + var level = this._levels[levelIndex]; + var redundantLevels = void 0, + delay = void 0, + nextLevel = void 0; + + level.loadError++; + level.fragmentError = fragmentError; + + if (levelError === true) { + if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) { + // exponential backoff capped to max retry timeout + delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); + // Schedule level reload + this.timer = setTimeout(function () { + return _this2.loadLevel(); + }, delay); + // boolean used to inform stream controller not to switch back to IDLE on non fatal error + errorEvent.levelRetry = true; + this.levelRetryCount++; + logger["b" /* logger */].warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount); + } else { + logger["b" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error'); + this.currentLevelIndex = null; + // stopping live reloading timer if any + this.cleanTimer(); + // switch error to fatal + errorEvent.fatal = true; + return; + } + } + + // Try any redundant streams if available for both errors: level and fragment + // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down + if (levelError === true || fragmentError === true) { + redundantLevels = level.url.length; + + if (redundantLevels > 1 && level.loadError < redundantLevels) { + logger["b" /* logger */].warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant stream id ' + level.urlId); + level.urlId = (level.urlId + 1) % redundantLevels; + level.details = undefined; + } else { + // Search for available level + if (this.manualLevelIndex === -1) { + // When lowest level has been reached, let's start hunt from the top + nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1; + logger["b" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel); + this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel; + } else if (fragmentError === true) { + // Allow fragment retry as long as configuration allows. + // reset this._level so that another call to set level() will trigger again a frag load + logger["b" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment'); + this.currentLevelIndex = null; + } + } + } + }; + + // reset errors on the successful load of a fragment + + + LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) { + var frag = _ref3.frag; + + if (frag !== undefined && frag.type === 'main') { + var level = this._levels[frag.level]; + if (level !== undefined) { + level.fragmentError = false; + level.loadError = 0; + this.levelRetryCount = 0; + } + } + }; + + LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) { + var _this3 = this; + + var levelId = data.level; + // only process level loaded events matching with expected level + if (levelId === this.currentLevelIndex) { + var curLevel = this._levels[levelId]; + // reset level load error counter on successful level loaded only if there is no issues with fragments + if (curLevel.fragmentError === false) { + curLevel.loadError = 0; + this.levelRetryCount = 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["b" /* 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["b" /* logger */].log('live playlist, reload in ' + reloadInterval + ' ms'); + this.timer = setTimeout(function () { + return _this3.loadLevel(); + }, reloadInterval); + } else { + this.cleanTimer(); + } + } + }; + + LevelController.prototype.loadLevel = function loadLevel() { + var level = void 0, + urlIndex = void 0; + + if (this.currentLevelIndex !== null && this.canload === true) { + level = this._levels[this.currentLevelIndex]; + if (level !== undefined && level.url.length > 0) { + urlIndex = level.urlId; + this.hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlIndex], level: this.currentLevelIndex, id: urlIndex }); + } + } + }; + + level_controller__createClass(LevelController, [{ + key: 'levels', + get: function get() { + return this._levels; + } + }, { + key: 'level', + get: function get() { + return this.currentLevelIndex; + }, + set: function set(newLevel) { + var levels = this._levels; + if (levels) { + newLevel = Math.min(newLevel, levels.length - 1); + if (this.currentLevelIndex !== newLevel || levels[newLevel].details === undefined) { + this.setLevelInternal(newLevel); + } + } + } + }, { + key: 'manualLevel', + get: function get() { + return this.manualLevelIndex; + }, + set: function set(newLevel) { + this.manualLevelIndex = 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.manualLevelIndex !== -1) { + return this.manualLevelIndex; + } else { + return this.hls.nextAutoLevel; + } + }, + set: function set(nextLevel) { + this.level = nextLevel; + if (this.manualLevelIndex === -1) { + this.hls.nextAutoLevel = nextLevel; + } + } + }]); + + return LevelController; +}(event_handler); + +/* harmony default export */ var level_controller = (level_controller_LevelController); +// EXTERNAL MODULE: ./src/demux/id3.js +var id3 = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/controller/id3-track-controller.js +function id3_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function id3_track_controller__possibleConstructorReturn(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 id3_track_controller__inherits(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 id3_track_controller_ID3TrackController = function (_EventHandler) { + id3_track_controller__inherits(ID3TrackController, _EventHandler); + + function ID3TrackController(hls) { + id3_track_controller__classCallCheck(this, ID3TrackController); + + var _this = id3_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_METADATA)); + + _this.id3Track = undefined; + _this.media = undefined; + return _this; + } + + ID3TrackController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + // Add ID3 metatadata text track. + + + ID3TrackController.prototype.onMediaAttached = function onMediaAttached(data) { + this.media = data.media; + if (!this.media) { + return; + } + }; + + ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() { + this.media = undefined; + }; + + ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) { + var fragment = data.frag; + var samples = data.samples; + + // create track dynamically + if (!this.id3Track) { + this.id3Track = this.media.addTextTrack('metadata', 'id3'); + this.id3Track.mode = 'hidden'; + } + + // 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 = id3["a" /* 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 (!id3["a" /* default */].isTimeStampFrame(frame)) { + var cue = new Cue(startTime, endTime, ''); + cue.value = frame; + this.id3Track.addCue(cue); + } + } + } + } + }; + + return ID3TrackController; +}(event_handler); + +/* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController); +// CONCATENATED MODULE: ./src/helper/is-supported.js + + +function is_supported_isSupported() { + var mediaSource = getMediaSource(); + var 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; +} +// CONCATENATED MODULE: ./src/utils/ewma.js +function ewma__classCallCheck(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) { + ewma__classCallCheck(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; + } + + EWMA.prototype.sample = function sample(weight, value) { + var adjAlpha = Math.pow(this.alpha_, weight); + this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_; + this.totalWeight_ += weight; + }; + + EWMA.prototype.getTotalWeight = function getTotalWeight() { + return this.totalWeight_; + }; + + EWMA.prototype.getEstimate = function getEstimate() { + if (this.alpha_) { + var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); + return this.estimate_ / zeroFactor; + } else { + return this.estimate_; + } + }; + + return EWMA; +}(); + +/* harmony default export */ var ewma = (EWMA); +// CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.js +function ewma_bandwidth_estimator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* + * 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_bandwidth_estimator_EwmaBandWidthEstimator = function () { + function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) { + ewma_bandwidth_estimator__classCallCheck(this, EwmaBandWidthEstimator); + + this.hls = hls; + this.defaultEstimate_ = defaultEstimate; + this.minWeight_ = 0.001; + this.minDelayMs_ = 50; + this.slow_ = new ewma(slow); + this.fast_ = new ewma(fast); + } + + EwmaBandWidthEstimator.prototype.sample = 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); + }; + + EwmaBandWidthEstimator.prototype.canEstimate = function canEstimate() { + var fast = this.fast_; + return fast && fast.getTotalWeight() >= this.minWeight_; + }; + + EwmaBandWidthEstimator.prototype.getEstimate = 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_; + } + }; + + EwmaBandWidthEstimator.prototype.destroy = function destroy() {}; + + return EwmaBandWidthEstimator; +}(); + +/* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator); +// CONCATENATED MODULE: ./src/controller/abr-controller.js +var abr_controller__createClass = 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 abr_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function abr_controller__possibleConstructorReturn(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 abr_controller__inherits(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 abr_controller_AbrController = function (_EventHandler) { + abr_controller__inherits(AbrController, _EventHandler); + + function AbrController(hls) { + abr_controller__classCallCheck(this, AbrController); + + var _this = abr_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_BUFFERED, events["a" /* 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; + } + + AbrController.prototype.destroy = function destroy() { + this.clearTimer(); + event_handler.prototype.destroy.call(this); + }; + + AbrController.prototype.onFragLoading = 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 ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate); + } + this.fragCurrent = frag; + } + }; + + AbrController.prototype._abandonRulesCheck = 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["b" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules'); + this.clearTimer(); + // reset forced auto level value so that next level will be selected + this._nextAutoLevel = -1; + 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 && stats && (!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 = (buffer_helper.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["b" /* logger */].warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel + ':fragLoadedDelay[' + nextLoadLevel + ']<fragLoadedDelay[' + (frag.level - 1) + '];bufferStarvationDelay:' + fragLevelNextLoadedDelay.toFixed(1) + '<' + fragLoadedDelay.toFixed(1) + ':' + bufferStarvationDelay.toFixed(1)); + // force next load level in auto mode + hls.nextLoadLevel = nextLoadLevel; + // update bw estimate for this fragment before cancelling load (this will help reducing the bw) + this._bwEstimator.sample(requestDelay, stats.loaded); + //abort fragment loading + loader.abort(); + // stop abandon rules timer + this.clearTimer(); + hls.trigger(events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats }); + } + } + } + } + }; + + AbrController.prototype.onFragLoaded = function onFragLoaded(data) { + var frag = data.frag; + if (frag.type === 'main' && !isNaN(frag.sn)) { + // stop monitoring bw once frag loaded + this.clearTimer(); + // store level id after successful fragment load + this.lastLoadedFragLevel = frag.level; + // reset forced auto level value so that next level will be selected + this._nextAutoLevel = -1; + + // compute level average bitrate + if (this.hls.config.abrMaxWithRealBitrate) { + var level = this.hls.levels[frag.level]; + var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded; + var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration; + level.loaded = { bytes: loadedBytes, duration: loadedDuration }; + level.realBitrate = Math.round(8 * loadedBytes / loadedDuration); + } + // if fragment has been loaded to perform a bitrate test, + if (data.frag.bitrateTest) { + var stats = data.stats; + stats.tparsed = stats.tbuffered = stats.tload; + this.onFragBuffered(data); + } + } + }; + + AbrController.prototype.onFragBuffered = function onFragBuffered(data) { + var stats = data.stats, + frag = data.frag; + // only update stats on first frag buffering + // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly + // and leading to wrong bw estimation + // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED) + if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && !isNaN(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) { + // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached + // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached + // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation + var fragLoadingProcessingMs = stats.tparsed - stats.trequest; + logger["b" /* logger */].log('latency/loading/parsing/append/kbps:' + Math.round(stats.tfirst - stats.trequest) + '/' + Math.round(stats.tload - stats.tfirst) + '/' + Math.round(stats.tparsed - stats.tload) + '/' + Math.round(stats.tbuffered - stats.tparsed) + '/' + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest))); + this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded); + stats.bwEstimate = this._bwEstimator.getEstimate(); + // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration + if (frag.bitrateTest) { + this.bitrateTestDelay = fragLoadingProcessingMs / 1000; + } else { + this.bitrateTestDelay = 0; + } + } + }; + + AbrController.prototype.onError = function onError(data) { + // stop timer in case of frag loading error + switch (data.details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + this.clearTimer(); + break; + default: + break; + } + }; + + AbrController.prototype.clearTimer = function clearTimer() { + clearInterval(this.timer); + this.timer = null; + }; + + // return next auto level + + + AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) { + for (var i = maxAutoLevel; i >= 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["b" /* 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; + }; + + abr_controller__createClass(AbrController, [{ + 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 = (buffer_helper.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["b" /* 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["b" /* 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; +}(event_handler); + +/* harmony default export */ var abr_controller = (abr_controller_AbrController); +// CONCATENATED MODULE: ./src/controller/buffer-controller.js +function buffer_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function buffer_controller__possibleConstructorReturn(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 buffer_controller__inherits(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 buffer_controller_MediaSource = getMediaSource(); + +var buffer_controller_BufferController = function (_EventHandler) { + buffer_controller__inherits(BufferController, _EventHandler); + + function BufferController(hls) { + buffer_controller__classCallCheck(this, BufferController); + + // the value that we have set mediasource.duration to + // (the actual duration may be tweaked slighly by the browser) + var _this = buffer_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].BUFFER_RESET, events["a" /* default */].BUFFER_APPENDING, events["a" /* default */].BUFFER_CODECS, events["a" /* default */].BUFFER_EOS, events["a" /* default */].BUFFER_FLUSHING, events["a" /* default */].LEVEL_PTS_UPDATED, events["a" /* default */].LEVEL_UPDATED)); + + _this._msDuration = null; + // the value that we want to set mediaSource.duration to + _this._levelDuration = null; + // current stream state: true - for live broadcast, false - for VoD content + _this._live = null; + // cache the self generated object url to detect hijack of video tag + _this._objectUrl = null; + + // Source Buffer listeners + _this.onsbue = _this.onSBUpdateEnd.bind(_this); + _this.onsbe = _this.onSBUpdateError.bind(_this); + _this.pendingTracks = {}; + _this.tracks = {}; + return _this; + } + + BufferController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + BufferController.prototype.onLevelPtsUpdated = 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["b" /* logger */].warn('can not abort audio buffer: ' + err); + } + + if (!updating) { + logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start); + audioBuffer.timestampOffset = data.start; + } else { + this.audioTimestampOffset = data.start; + } + } + } + }; + + BufferController.prototype.onManifestParsed = function onManifestParsed(data) { + var audioExpected = data.audio, + videoExpected = data.video || data.levels.length && data.audio, + 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["b" /* logger */].log(sourceBufferNb + ' sourceBuffer(s) expected'); + } + this.sourceBufferNb = sourceBufferNb; + }; + + BufferController.prototype.onMediaAttaching = function onMediaAttaching(data) { + var media = this.media = data.media; + if (media) { + // setup the media source + var ms = this.mediaSource = new buffer_controller_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); + // cache the locally generated object url + this._objectUrl = media.src; + } + }; + + BufferController.prototype.onMediaDetaching = function onMediaDetaching() { + logger["b" /* 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["b" /* 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._objectUrl); + + // clean up video tag src only if it's our own url. some external libraries might + // hijack the video tag and change its 'src' without destroying the Hls instance first + if (this.media.src === this._objectUrl) { + this.media.removeAttribute('src'); + this.media.load(); + } else { + logger["b" /* logger */].warn('media.src was changed by a third party - skip cleanup'); + } + } + + this.mediaSource = null; + this.media = null; + this._objectUrl = null; + this.pendingTracks = {}; + this.tracks = {}; + this.sourceBuffer = {}; + this.flushRange = []; + this.segments = []; + this.appended = 0; + } + this.onmso = this.onmse = this.onmsc = null; + this.hls.trigger(events["a" /* default */].MEDIA_DETACHED); + }; + + BufferController.prototype.onMediaSourceOpen = function onMediaSourceOpen() { + logger["b" /* logger */].log('media source opened'); + this.hls.trigger(events["a" /* 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(); + }; + + BufferController.prototype.checkPendingTracks = 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(); + } + }; + + BufferController.prototype.onMediaSourceClose = function onMediaSourceClose() { + logger["b" /* logger */].log('media source closed'); + }; + + BufferController.prototype.onMediaSourceEnded = function onMediaSourceEnded() { + logger["b" /* logger */].log('media source ended'); + }; + + BufferController.prototype.onSBUpdateEnd = function onSBUpdateEnd() { + // update timestampOffset + if (this.audioTimestampOffset) { + var audioBuffer = this.sourceBuffer.audio; + logger["b" /* 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(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending }); + + // don't append in flushing mode + if (!this._needsFlush) { + this.doAppending(); + } + + this.updateMediaElementDuration(); + }; + + BufferController.prototype.onSBUpdateError = function onSBUpdateError(event) { + logger["b" /* 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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 + }; + + BufferController.prototype.onBufferReset = 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; + }; + + BufferController.prototype.onBufferCodecs = 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(); + } + } + }; + + BufferController.prototype.createSourceBuffers = 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["b" /* 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["b" /* logger */].error('error while trying to add sourceBuffer:' + err.message); + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType }); + } + } + } + this.hls.trigger(events["a" /* default */].BUFFER_CREATED, { tracks: tracks }); + }; + + BufferController.prototype.onBufferAppending = function onBufferAppending(data) { + if (!this._needsFlush) { + if (!this.segments) { + this.segments = [data]; + } else { + this.segments.push(data); + } + this.doAppending(); + } + }; + + BufferController.prototype.onBufferAppendFail = function onBufferAppendFail(data) { + logger["b" /* 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false }); + }; + + // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos() + + + BufferController.prototype.onBufferEos = 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["b" /* logger */].log(type + ' sourceBuffer now EOS'); + } + } + } + this.checkEos(); + }; + + // if all source buffers are marked as ended, signal endOfStream() to MediaSource. + + + BufferController.prototype.checkEos = 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["b" /* 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["b" /* logger */].warn('exception while calling mediaSource.endOfStream()'); + } + this._needsEos = false; + }; + + BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) { + this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type }); + // attempt flush immediately + this.flushBufferCounter = 0; + this.doFlush(); + }; + + BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) { + var details = _ref.details; + + if (details.fragments.length > 0) { + this._levelDuration = details.totalduration + details.fragments[0].start; + this._live = details.live; + this.updateMediaElementDuration(); + } + }; + + /** + * Update Media Source duration to current level duration or override to Infinity if configuration parameter + * 'liveDurationInfinity` is set to `true` + * More details: https://github.com/video-dev/hls.js/issues/355 + */ + + + BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() { + var config = this.hls.config; + + var duration = void 0; + + if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') { + return; + } + + for (var type in this.sourceBuffer) { + if (this.sourceBuffer[type].updating === true) { + // can't set duration whilst a buffer is updating + return; + } + } + + duration = this.media.duration; + // initialise to the value that the media source is reporting + if (this._msDuration === null) { + this._msDuration = this.mediaSource.duration; + } + + if (this._live === true && config.liveDurationInfinity === true) { + // Override duration to Infinity + logger["b" /* logger */].log('Media Source duration is set to Infinity'); + this._msDuration = this.mediaSource.duration = Infinity; + } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || duration === Infinity || isNaN(duration)) { + // levelDuration was the last value we set. + // not using mediaSource.duration as the browser may tweak this value + // only update Media Source duration if its value increase, this is to avoid + // flushing already buffered portion when switching between quality level + logger["b" /* logger */].log('Updating Media Source duration to ' + this._levelDuration.toFixed(3)); + this._msDuration = this.mediaSource.duration = this._levelDuration; + } + }; + + BufferController.prototype.doFlush = 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["b" /* logger */].error('error while accessing sourceBuffer.buffered'); + } + this.appended = appended; + this.hls.trigger(events["a" /* default */].BUFFER_FLUSHED); + } + }; + + BufferController.prototype.doAppending = function doAppending() { + var hls = this.hls, + sourceBuffer = this.sourceBuffer, + segments = this.segments; + if (Object.keys(sourceBuffer).length) { + if (this.media.error) { + this.segments = []; + logger["b" /* 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["b" /* logger */].error('error while trying to append buffer:' + err.message); + segments.unshift(segment); + var event = { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, parent: segment.parent }; + if (err.code !== 22) { + if (this.appendError) { + this.appendError++; + } else { + this.appendError = 1; + } + event.details = errors["a" /* 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["b" /* logger */].log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer'); + segments = []; + event.fatal = true; + hls.trigger(events["a" /* default */].ERROR, event); + return; + } else { + event.fatal = false; + hls.trigger(events["a" /* 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["a" /* ErrorDetails */].BUFFER_FULL_ERROR; + event.fatal = false; + hls.trigger(events["a" /* 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 + */ + + + BufferController.prototype.flushBuffer = function flushBuffer(startOffset, endOffset, typeIn) { + var sb, + i, + bufStart, + bufEnd, + flushStart, + flushEnd, + sourceBuffer = this.sourceBuffer; + if (Object.keys(sourceBuffer).length) { + logger["b" /* 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["b" /* logger */].log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime); + sb.remove(flushStart, flushEnd); + return false; + } + } + } catch (e) { + logger["b" /* 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["b" /* logger */].warn('cannot flush, sb updating in progress'); + return false; + } + } + } else { + logger["b" /* logger */].warn('abort flushing too many retries'); + } + logger["b" /* logger */].log('buffer flushed'); + } + // everything flushed ! + return true; + }; + + return BufferController; +}(event_handler); + +/* harmony default export */ var buffer_controller = (buffer_controller_BufferController); +// CONCATENATED MODULE: ./src/controller/cap-level-controller.js +var cap_level_controller__createClass = 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 cap_level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function cap_level_controller__possibleConstructorReturn(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 cap_level_controller__inherits(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 cap_level_controller_CapLevelController = function (_EventHandler) { + cap_level_controller__inherits(CapLevelController, _EventHandler); + + function CapLevelController(hls) { + cap_level_controller__classCallCheck(this, CapLevelController); + + return cap_level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FPS_DROP_LEVEL_CAPPING, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MANIFEST_PARSED)); + } + + CapLevelController.prototype.destroy = 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); + } + } + }; + + CapLevelController.prototype.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) { + // Don't add a restricted level more than once + if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) { + this.restrictedLevels.push(data.droppedLevel); + } + }; + + CapLevelController.prototype.onMediaAttaching = function onMediaAttaching(data) { + this.media = data.media instanceof HTMLVideoElement ? data.media : null; + }; + + CapLevelController.prototype.onManifestParsed = 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(); + } + }; + + CapLevelController.prototype.detectPlayerSize = 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) + */ + + + CapLevelController.prototype.getMaxLevel = 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); + }; + + CapLevelController.isLevelAllowed = function isLevelAllowed(level) { + var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + return restrictedLevels.indexOf(level) === -1; + }; + + CapLevelController.getMaxLevelByMediaSize = 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; + }; + + cap_level_controller__createClass(CapLevelController, [{ + 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: 'contentScaleFactor', + get: function get() { + var pixelRatio = 1; + try { + pixelRatio = window.devicePixelRatio; + } catch (e) {} + return pixelRatio; + } + }]); + + return CapLevelController; +}(event_handler); + +/* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController); +// CONCATENATED MODULE: ./src/controller/fps-controller.js +function fps_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fps_controller__possibleConstructorReturn(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 fps_controller__inherits(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 fps_controller_FPSController = function (_EventHandler) { + fps_controller__inherits(FPSController, _EventHandler); + + function FPSController(hls) { + fps_controller__classCallCheck(this, FPSController); + + return fps_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING)); + } + + FPSController.prototype.destroy = function destroy() { + if (this.timer) { + clearInterval(this.timer); + } + this.isVideoPlaybackQualityAvailable = false; + }; + + FPSController.prototype.onMediaAttaching = 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); + } + }; + + FPSController.prototype.checkFPS = 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(events["a" /* 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["b" /* 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(events["a" /* 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; + } + }; + + FPSController.prototype.checkFPSInterval = 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; +}(event_handler); + +/* harmony default export */ var fps_controller = (fps_controller_FPSController); +// CONCATENATED MODULE: ./src/utils/xhr-loader.js +function xhr_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * XHR based logger +*/ + + + +var xhr_loader_XhrLoader = function () { + function XhrLoader(config) { + xhr_loader__classCallCheck(this, XhrLoader); + + if (config && config.xhrSetup) { + this.xhrSetup = config.xhrSetup; + } + } + + XhrLoader.prototype.destroy = function destroy() { + this.abort(); + this.loader = null; + }; + + XhrLoader.prototype.abort = 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; + }; + + XhrLoader.prototype.load = 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(); + }; + + XhrLoader.prototype.loadInternal = function loadInternal() { + var xhr, + context = this.context; + 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(); + }; + + XhrLoader.prototype.readystatechange = 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["b" /* logger */].error(status + ' while loading ' + context.url); + this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr); + } else { + // retry + logger["b" /* 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); + } + } + }; + + XhrLoader.prototype.loadtimeout = function loadtimeout() { + logger["b" /* logger */].warn('timeout while loading ' + this.context.url); + this.callbacks.onTimeout(this.stats, this.context, null); + }; + + XhrLoader.prototype.loadprogress = 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; +}(); + +/* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader); +// CONCATENATED MODULE: ./src/controller/audio-track-controller.js +var audio_track_controller__createClass = 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 audio_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function audio_track_controller__possibleConstructorReturn(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 audio_track_controller__inherits(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 audio_track_controller_AudioTrackController = function (_EventHandler) { + audio_track_controller__inherits(AudioTrackController, _EventHandler); + + function AudioTrackController(hls) { + audio_track_controller__classCallCheck(this, AudioTrackController); + + var _this = audio_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].ERROR)); + + _this.ticks = 0; + _this.ontick = _this.tick.bind(_this); + return _this; + } + + AudioTrackController.prototype.destroy = function destroy() { + this.cleanTimer(); + event_handler.prototype.destroy.call(this); + }; + + AudioTrackController.prototype.cleanTimer = function cleanTimer() { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + }; + + AudioTrackController.prototype.tick = function tick() { + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(this.tick, 1); + } + this.ticks = 0; + } + }; + + AudioTrackController.prototype.doTick = function doTick() { + this.updateTrack(this.trackId); + }; + + AudioTrackController.prototype.onError = function onError(data) { + if (data.fatal && data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) { + this.cleanTimer(); + } + }; + + AudioTrackController.prototype.onManifestLoading = function onManifestLoading() { + // reset audio tracks on manifest loading + this.tracks = []; + this.trackId = -1; + }; + + AudioTrackController.prototype.onManifestParsed = function onManifestParsed(data) { + var _this2 = this; + + var tracks = data.audioTracks || []; + var defaultFound = false; + this.tracks = tracks; + this.hls.trigger(events["a" /* 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 && !defaultFound) { + _this2.audioTrack = id; + defaultFound = true; + return; + } + id++; + }); + if (defaultFound === false && tracks.length) { + logger["b" /* logger */].log('no default audio track defined, use first audio track as default'); + this.audioTrack = 0; + } + }; + + AudioTrackController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) { + if (data.id < this.tracks.length) { + logger["b" /* 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 + this.cleanTimer(); + } + } + }; + + /** get alternate audio tracks list from playlist **/ + + + AudioTrackController.prototype.setAudioTrackInternal = function setAudioTrackInternal(newId) { + // check if level idx is valid + if (newId >= 0 && newId < this.tracks.length) { + // stopping live reloading timer if any + this.cleanTimer(); + this.trackId = newId; + logger["b" /* 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(events["a" /* default */].AUDIO_TRACK_SWITCH, eventObj); + hls.trigger(events["a" /* 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["b" /* logger */].log('(re)loading playlist for audioTrack ' + newId); + hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: newId }); + } + } + }; + + AudioTrackController.prototype.updateTrack = function updateTrack(newId) { + // check if level idx is valid + if (newId >= 0 && newId < this.tracks.length) { + // stopping live reloading timer if any + this.cleanTimer(); + this.trackId = newId; + logger["b" /* 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["b" /* logger */].log('(re)loading playlist for audioTrack ' + newId); + this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: newId }); + } + } + }; + + audio_track_controller__createClass(AudioTrackController, [{ + 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; +}(event_handler); + +/* harmony default export */ var audio_track_controller = (audio_track_controller_AudioTrackController); +// CONCATENATED MODULE: ./src/controller/audio-stream-controller.js +var audio_stream_controller__createClass = 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 audio_stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function audio_stream_controller__possibleConstructorReturn(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 audio_stream_controller__inherits(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 audio_stream_controller_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 audio_stream_controller_AudioStreamController = function (_EventHandler) { + audio_stream_controller__inherits(AudioStreamController, _EventHandler); + + function AudioStreamController(hls) { + audio_stream_controller__classCallCheck(this, AudioStreamController); + + var _this = audio_stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].AUDIO_TRACKS_UPDATED, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].BUFFER_RESET, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED, events["a" /* default */].INIT_PTS_FOUND)); + + _this.config = hls.config; + _this.audioCodecSwap = false; + _this.ticks = 0; + _this._state = audio_stream_controller_State.STOPPED; + _this.ontick = _this.tick.bind(_this); + _this.initPTS = []; + _this.waitingFragment = null; + _this.videoTrackCC = null; + return _this; + } + + AudioStreamController.prototype.destroy = function destroy() { + this.stopLoad(); + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + event_handler.prototype.destroy.call(this); + this.state = audio_stream_controller_State.STOPPED; + }; + + //Signal that video PTS was found + + + AudioStreamController.prototype.onInitPtsFound = 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["b" /* 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 === audio_stream_controller_State.WAITING_INIT_PTS) { + this.tick(); + } + } + }; + + AudioStreamController.prototype.startLoad = 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["b" /* logger */].log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3)); + this.state = audio_stream_controller_State.IDLE; + } else { + this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition; + this.state = audio_stream_controller_State.STARTING; + } + this.nextLoadPosition = this.startPosition = this.lastCurrentTime; + this.tick(); + } else { + this.startPosition = startPosition; + this.state = audio_stream_controller_State.STOPPED; + } + }; + + AudioStreamController.prototype.stopLoad = 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 = audio_stream_controller_State.STOPPED; + }; + + AudioStreamController.prototype.tick = function tick() { + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(this.tick, 1); + } + this.ticks = 0; + } + }; + + AudioStreamController.prototype.doTick = function doTick() { + var pos, + track, + trackDetails, + hls = this.hls, + config = hls.config; + //logger.log('audioStream:' + this.state); + switch (this.state) { + case audio_stream_controller_State.ERROR: + //don't do anything in error state to avoid breaking further ... + case audio_stream_controller_State.PAUSED: + //don't do anything in paused state either ... + case audio_stream_controller_State.BUFFER_FLUSHING: + break; + case audio_stream_controller_State.STARTING: + this.state = audio_stream_controller_State.WAITING_TRACK; + this.loadedmetadata = false; + break; + case audio_stream_controller_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, + videoBuffer = this.videoBuffer ? this.videoBuffer : this.media, + bufferInfo = buffer_helper.bufferInfo(media, pos, config.maxBufferHole), + mainBufferInfo = buffer_helper.bufferInfo(videoBuffer, pos, config.maxBufferHole), + bufferLen = bufferInfo.len, + bufferEnd = bufferInfo.end, + fragPrevious = this.fragPrevious, + + // ensure we buffer at least config.maxBufferLength (default 30s) + // once we reach that threshold, don't buffer more than video (mainBufferInfo.len) + maxBufLen = Math.max(config.maxBufferLength, mainBufferInfo.len), + 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 = audio_stream_controller_State.WAITING_TRACK; + break; + } + + // check if we need to finalize media stream + // we just got done loading the final fragment and there is no other buffered range after ... + // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between + // so we should not switch to ENDED in that case, to be able to buffer them + if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) { + // 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(events["a" /* default */].BUFFER_EOS, { type: 'audio' }); + this.state = audio_stream_controller_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["b" /* 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["b" /* 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 = 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["b" /* 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 = binary_search.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["b" /* 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["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId); + this.state = audio_stream_controller_State.KEY_LOADING; + hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + } else { + logger["b" /* 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(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* 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(events["a" /* default */].FRAG_LOADING, { frag: frag }); + this.state = audio_stream_controller_State.FRAG_LOADING; + } + } + } + break; + case audio_stream_controller_State.WAITING_TRACK: + track = this.tracks[this.trackId]; + // check if playlist is already loaded + if (track && track.details) { + this.state = audio_stream_controller_State.IDLE; + } + break; + case audio_stream_controller_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["b" /* logger */].log('audioStreamController: retryDate reached, switch back to IDLE state'); + this.state = audio_stream_controller_State.IDLE; + } + break; + case audio_stream_controller_State.WAITING_INIT_PTS: + var videoTrackCC = this.videoTrackCC; + if (this.initPTS[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 (videoTrackCC !== waitingFragCC) { + track = this.tracks[this.trackId]; + if (track.details && track.details.live) { + logger["b" /* logger */].warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')'); + this.waitingFragment = null; + this.state = audio_stream_controller_State.IDLE; + } + } else { + this.state = audio_stream_controller_State.FRAG_LOADING; + this.onFragLoaded(this.waitingFragment); + this.waitingFragment = null; + } + } else { + this.state = audio_stream_controller_State.IDLE; + } + + break; + case audio_stream_controller_State.STOPPED: + case audio_stream_controller_State.FRAG_LOADING: + case audio_stream_controller_State.PARSING: + case audio_stream_controller_State.PARSED: + case audio_stream_controller_State.ENDED: + break; + default: + break; + } + }; + + AudioStreamController.prototype.onMediaAttached = 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); + } + }; + + AudioStreamController.prototype.onMediaDetaching = function onMediaDetaching() { + var media = this.media; + if (media && media.ended) { + logger["b" /* 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 = this.videoBuffer = null; + this.loadedmetadata = false; + this.stopLoad(); + }; + + AudioStreamController.prototype.onMediaSeeking = function onMediaSeeking() { + if (this.state === audio_stream_controller_State.ENDED) { + // switch to IDLE state to check for potential new fragment + this.state = audio_stream_controller_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(); + }; + + AudioStreamController.prototype.onMediaEnded = function onMediaEnded() { + // reset startPosition and lastCurrentTime to restart playback @ stream beginning + this.startPosition = this.lastCurrentTime = 0; + }; + + AudioStreamController.prototype.onAudioTracksUpdated = function onAudioTracksUpdated(data) { + logger["b" /* logger */].log('audio tracks updated'); + this.tracks = data.audioTracks; + }; + + AudioStreamController.prototype.onAudioTrackSwitching = 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 = audio_stream_controller_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 = audio_stream_controller_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(); + }; + + AudioStreamController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) { + var newDetails = data.details, + trackId = data.id, + track = this.tracks[trackId], + duration = newDetails.totalduration, + sliding = 0; + + logger["b" /* 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 + mergeDetails(curDetails, newDetails); + sliding = newDetails.fragments[0].start; + // TODO + //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails); + if (newDetails.PTSKnown) { + logger["b" /* logger */].log('live audio playlist sliding:' + sliding.toFixed(3)); + } else { + logger["b" /* logger */].log('live audio playlist - outdated PTS, unknown sliding'); + } + } else { + newDetails.PTSKnown = false; + logger["b" /* 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["b" /* 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 === audio_stream_controller_State.WAITING_TRACK) { + this.state = audio_stream_controller_State.IDLE; + } + //trigger handler right now + this.tick(); + }; + + AudioStreamController.prototype.onKeyLoaded = function onKeyLoaded() { + if (this.state === audio_stream_controller_State.KEY_LOADING) { + this.state = audio_stream_controller_State.IDLE; + this.tick(); + } + }; + + AudioStreamController.prototype.onFragLoaded = function onFragLoaded(data) { + var fragCurrent = this.fragCurrent, + fragLoaded = data.frag; + if (this.state === audio_stream_controller_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 = audio_stream_controller_State.IDLE; + + stats.tparsed = stats.tbuffered = performance.now(); + details.initSegment.data = data.payload; + this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' }); + this.tick(); + } else { + this.state = audio_stream_controller_State.PARSING; + // transmux the MPEG-TS data to ISO-BMFF segments + this.appended = false; + if (!this.demuxer) { + this.demuxer = new demux_demuxer(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["b" /* 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["b" /* 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 = audio_stream_controller_State.WAITING_INIT_PTS; + } + } + } + this.fragLoadError = 0; + }; + + AudioStreamController.prototype.onFragParsingInitSegment = 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 === audio_stream_controller_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(events["a" /* default */].BUFFER_CODECS, tracks); + logger["b" /* 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(events["a" /* default */].BUFFER_APPENDING, appendObj); + } + } + //trigger handler right now + this.tick(); + } + } + }; + + AudioStreamController.prototype.onFragParsingData = 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 === audio_stream_controller_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["b" /* 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); + 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["b" /* logger */].log('switching audio track : currentTime:' + currentTime); + if (currentTime >= data.startPTS) { + logger["b" /* logger */].log('switching audio track : flushing all audio'); + this.state = audio_stream_controller_State.BUFFER_FLUSHING; + hls.trigger(events["a" /* 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(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId }); + } + } else { + //Lets announce that the initial audio track switch flush occur + this.audioSwitch = false; + hls.trigger(events["a" /* 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 === audio_stream_controller_State.PARSING) { + // arm pending Buffering flag before appending a segment + _this2.pendingBuffering = true; + _this2.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj); + } + }); + this.pendingData = []; + this.appended = true; + } + } + //trigger handler right now + this.tick(); + } + }; + + AudioStreamController.prototype.onFragParsed = 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 === audio_stream_controller_State.PARSING) { + this.stats.tparsed = performance.now(); + this.state = audio_stream_controller_State.PARSED; + this._checkAppendedParsed(); + } + }; + + AudioStreamController.prototype.onBufferReset = function onBufferReset() { + // reset reference to sourcebuffers + this.mediaBuffer = this.videoBuffer = null; + this.loadedmetadata = false; + }; + + AudioStreamController.prototype.onBufferCreated = function onBufferCreated(data) { + var audioTrack = data.tracks.audio; + if (audioTrack) { + this.mediaBuffer = audioTrack.buffer; + this.loadedmetadata = true; + } + if (data.tracks.video) { + this.videoBuffer = data.tracks.video.buffer; + } + }; + + AudioStreamController.prototype.onBufferAppended = function onBufferAppended(data) { + if (data.parent === 'audio') { + var state = this.state; + if (state === audio_stream_controller_State.PARSING || state === audio_stream_controller_State.PARSED) { + // check if all buffers have been appended + this.pendingBuffering = data.pending > 0; + this._checkAppendedParsed(); + } + } + }; + + AudioStreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() { + //trigger handler right now + if (this.state === audio_stream_controller_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(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' }); + var media = this.mediaBuffer ? this.mediaBuffer : this.media; + logger["b" /* logger */].log('audio buffered : ' + timeRanges.toString(media.buffered)); + if (this.audioSwitch && this.appended) { + this.audioSwitch = false; + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: this.trackId }); + } + this.state = audio_stream_controller_State.IDLE; + } + this.tick(); + } + }; + + AudioStreamController.prototype.onError = 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["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* 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["b" /* logger */].warn('audioStreamController: frag loading failed, retry in ' + delay + ' ms'); + this.retryDate = performance.now() + delay; + // retry loading state + this.state = audio_stream_controller_State.FRAG_LOADING_WAITING_RETRY; + } else { + logger["b" /* logger */].error('audioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...'); + // switch error to fatal + data.fatal = true; + this.state = audio_stream_controller_State.ERROR; + } + } + break; + case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR: + case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR: + case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT: + case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR: + case errors["a" /* 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 !== audio_stream_controller_State.ERROR) { + // if fatal error, stop processing, otherwise move to IDLE to retry loading + this.state = data.fatal ? audio_stream_controller_State.ERROR : audio_stream_controller_State.IDLE; + logger["b" /* logger */].warn('audioStreamController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...'); + } + break; + case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR: + // if in appending state + if (data.parent === 'audio' && (this.state === audio_stream_controller_State.PARSING || this.state === audio_stream_controller_State.PARSED)) { + var media = this.mediaBuffer, + currentTime = this.media.currentTime, + mediaBuffered = media && buffer_helper.isBuffered(media, currentTime) && buffer_helper.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["b" /* 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 = audio_stream_controller_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["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush audio buffer'); + this.fragCurrent = null; + // flush everything + this.state = audio_stream_controller_State.BUFFER_FLUSHING; + this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); + } + } + break; + default: + break; + } + }; + + AudioStreamController.prototype.onBufferFlushed = function onBufferFlushed() { + var _this3 = this; + + var pendingData = this.pendingData; + if (pendingData && pendingData.length) { + logger["b" /* logger */].log('appending pending audio data on Buffer Flushed'); + pendingData.forEach(function (appendObj) { + _this3.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj); + }); + this.appended = true; + this.pendingData = []; + this.state = audio_stream_controller_State.PARSED; + } else { + // move to IDLE once flush complete. this should trigger new fragment loading + this.state = audio_stream_controller_State.IDLE; + // reset reference to frag + this.fragPrevious = null; + this.tick(); + } + }; + + audio_stream_controller__createClass(AudioStreamController, [{ + key: 'state', + set: function set(nextState) { + if (this.state !== nextState) { + var previousState = this.state; + this._state = nextState; + logger["b" /* logger */].log('audio stream:' + previousState + '->' + nextState); + } + }, + get: function get() { + return this._state; + } + }]); + + return AudioStreamController; +}(event_handler); + +/* harmony default export */ var audio_stream_controller = (audio_stream_controller_AudioStreamController); +// CONCATENATED MODULE: ./src/utils/vttcue.js +/** + * 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. + */ + +/* harmony default export */ var vttcue = ((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; +})()); +// CONCATENATED MODULE: ./src/utils/vttparser.js +/* + * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716 + */ + + + +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)); + } + }; +}; + +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 vttcue(0, 0, 0); +// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244 +// Safari doesn't yet support this change, but FF and Chrome do. +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(); + // strip of UTF-8 BOM if any + // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8 + 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 vttcue(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; + } +}; + + + +/* harmony default export */ var vttparser = (VTTParser); +// CONCATENATED MODULE: ./src/utils/cues.js + + +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, 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); + } + } +} +// CONCATENATED MODULE: ./src/utils/cea-608-parser.js +function cea_608_parser__classCallCheck(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 cea_608_parser_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) { + cea_608_parser__classCallCheck(this, PenState); + + this.foreground = foreground || 'white'; + this.underline = underline || false; + this.italics = italics || false; + this.background = background || 'black'; + this.flash = flash || false; + } + + PenState.prototype.reset = function reset() { + this.foreground = 'white'; + this.underline = false; + this.italics = false; + this.background = 'black'; + this.flash = false; + }; + + PenState.prototype.setStyles = 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]; + } + } + }; + + PenState.prototype.isDefault = function isDefault() { + return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash; + }; + + PenState.prototype.equals = function equals(other) { + return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash; + }; + + PenState.prototype.copy = function copy(newPenState) { + this.foreground = newPenState.foreground; + this.underline = newPenState.underline; + this.italics = newPenState.italics; + this.background = newPenState.background; + this.flash = newPenState.flash; + }; + + PenState.prototype.toString = 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) { + cea_608_parser__classCallCheck(this, StyledUnicodeChar); + + this.uchar = uchar || ' '; // unicode character + this.penState = new PenState(foreground, underline, italics, background, flash); + } + + StyledUnicodeChar.prototype.reset = function reset() { + this.uchar = ' '; + this.penState.reset(); + }; + + StyledUnicodeChar.prototype.setChar = function setChar(uchar, newPenState) { + this.uchar = uchar; + this.penState.copy(newPenState); + }; + + StyledUnicodeChar.prototype.setPenState = function setPenState(newPenState) { + this.penState.copy(newPenState); + }; + + StyledUnicodeChar.prototype.equals = function equals(other) { + return this.uchar === other.uchar && this.penState.equals(other.penState); + }; + + StyledUnicodeChar.prototype.copy = function copy(newChar) { + this.uchar = newChar.uchar; + this.penState.copy(newChar.penState); + }; + + StyledUnicodeChar.prototype.isEmpty = function isEmpty() { + return this.uchar === ' ' && this.penState.isDefault(); + }; + + return StyledUnicodeChar; +}(); + +/** + * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar. + * @constructor + */ + + +var Row = function () { + function Row() { + cea_608_parser__classCallCheck(this, Row); + + this.chars = []; + for (var i = 0; i < NR_COLS; i++) { + this.chars.push(new StyledUnicodeChar()); + } + this.pos = 0; + this.currPenState = new PenState(); + } + + Row.prototype.equals = 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; + }; + + Row.prototype.copy = function copy(other) { + for (var i = 0; i < NR_COLS; i++) { + this.chars[i].copy(other.chars[i]); + } + }; + + Row.prototype.isEmpty = function isEmpty() { + 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. + */ + + + Row.prototype.setCursor = function setCursor(absPos) { + if (this.pos !== absPos) { + this.pos = absPos; + } + if (this.pos < 0) { + cea_608_parser_logger.log('ERROR', 'Negative cursor position ' + this.pos); + this.pos = 0; + } else if (this.pos > NR_COLS) { + cea_608_parser_logger.log('ERROR', 'Too large cursor position ' + this.pos); + this.pos = NR_COLS; + } + }; + + /** + * Move the cursor relative to current position. + */ + + + Row.prototype.moveCursor = 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. + */ + + + Row.prototype.backSpace = function backSpace() { + this.moveCursor(-1); + this.chars[this.pos].setChar(' ', this.currPenState); + }; + + Row.prototype.insertChar = function insertChar(byte) { + if (byte >= 0x90) { + //Extended char + this.backSpace(); + } + var char = getCharForByte(byte); + if (this.pos >= NR_COLS) { + cea_608_parser_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); + }; + + Row.prototype.clearFromPos = function clearFromPos(startPos) { + var i; + for (i = startPos; i < NR_COLS; i++) { + this.chars[i].reset(); + } + }; + + Row.prototype.clear = function clear() { + this.clearFromPos(0); + this.pos = 0; + this.currPenState.reset(); + }; + + Row.prototype.clearToEndOfRow = function clearToEndOfRow() { + this.clearFromPos(this.pos); + }; + + Row.prototype.getTextString = 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(''); + } + }; + + Row.prototype.setPenStyles = 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() { + cea_608_parser__classCallCheck(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(); + } + + CaptionScreen.prototype.reset = function reset() { + for (var i = 0; i < NR_ROWS; i++) { + this.rows[i].clear(); + } + this.currRow = NR_ROWS - 1; + }; + + CaptionScreen.prototype.equals = 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; + }; + + CaptionScreen.prototype.copy = function copy(other) { + for (var i = 0; i < NR_ROWS; i++) { + this.rows[i].copy(other.rows[i]); + } + }; + + CaptionScreen.prototype.isEmpty = function isEmpty() { + var empty = true; + for (var i = 0; i < NR_ROWS; i++) { + if (!this.rows[i].isEmpty()) { + empty = false; + break; + } + } + return empty; + }; + + CaptionScreen.prototype.backSpace = function backSpace() { + var row = this.rows[this.currRow]; + row.backSpace(); + }; + + CaptionScreen.prototype.clearToEndOfRow = function clearToEndOfRow() { + var row = this.rows[this.currRow]; + row.clearToEndOfRow(); + }; + + /** + * Insert a character (without styling) in the current row. + */ + + + CaptionScreen.prototype.insertChar = function insertChar(char) { + var row = this.rows[this.currRow]; + row.insertChar(char); + }; + + CaptionScreen.prototype.setPen = function setPen(styles) { + var row = this.rows[this.currRow]; + row.setPenStyles(styles); + }; + + CaptionScreen.prototype.moveCursor = function moveCursor(relPos) { + var row = this.rows[this.currRow]; + row.moveCursor(relPos); + }; + + CaptionScreen.prototype.setCursor = function setCursor(absPos) { + cea_608_parser_logger.log('INFO', 'setCursor: ' + absPos); + var row = this.rows[this.currRow]; + row.setCursor(absPos); + }; + + CaptionScreen.prototype.setPAC = function setPAC(pacData) { + cea_608_parser_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 < cea_608_parser_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). + */ + + + CaptionScreen.prototype.setBkgData = function setBkgData(bkgData) { + + cea_608_parser_logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData)); + this.backSpace(); + this.setPen(bkgData); + this.insertChar(0x20); //Space + }; + + CaptionScreen.prototype.setRollUpRows = function setRollUpRows(nrRows) { + this.nrRollUpRows = nrRows; + }; + + CaptionScreen.prototype.rollUp = function rollUp() { + if (this.nrRollUpRows === null) { + cea_608_parser_logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet'); + return; //Not properly setup + } + cea_608_parser_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); + cea_608_parser_logger.log('INFO', 'Rolling up'); + //logger.log('TEXT', this.get_display_text()) + }; + + /** + * Get all non-empty rows with as unicode text. + */ + + + CaptionScreen.prototype.getDisplayText = 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; + }; + + CaptionScreen.prototype.getTextAndFormat = 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) { + cea_608_parser__classCallCheck(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. + } + + Cea608Channel.prototype.reset = 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; + }; + + Cea608Channel.prototype.getHandler = function getHandler() { + return this.outputFilter; + }; + + Cea608Channel.prototype.setHandler = function setHandler(newHandler) { + this.outputFilter = newHandler; + }; + + Cea608Channel.prototype.setPAC = function setPAC(pacData) { + this.writeScreen.setPAC(pacData); + }; + + Cea608Channel.prototype.setBkgData = function setBkgData(bkgData) { + this.writeScreen.setBkgData(bkgData); + }; + + Cea608Channel.prototype.setMode = function setMode(newMode) { + if (newMode === this.mode) { + return; + } + this.mode = newMode; + cea_608_parser_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; + }; + + Cea608Channel.prototype.insertChars = 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'; + cea_608_parser_logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true)); + if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') { + cea_608_parser_logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)); + this.outputDataUpdate(); + } + }; + + Cea608Channel.prototype.ccRCL = function ccRCL() { + // Resume Caption Loading (switch mode to Pop On) + cea_608_parser_logger.log('INFO', 'RCL - Resume Caption Loading'); + this.setMode('MODE_POP-ON'); + }; + + Cea608Channel.prototype.ccBS = function ccBS() { + // BackSpace + cea_608_parser_logger.log('INFO', 'BS - BackSpace'); + if (this.mode === 'MODE_TEXT') { + return; + } + this.writeScreen.backSpace(); + if (this.writeScreen === this.displayedMemory) { + this.outputDataUpdate(); + } + }; + + Cea608Channel.prototype.ccAOF = function ccAOF() { + // Reserved (formerly Alarm Off) + return; + }; + + Cea608Channel.prototype.ccAON = function ccAON() { + // Reserved (formerly Alarm On) + return; + }; + + Cea608Channel.prototype.ccDER = function ccDER() { + // Delete to End of Row + cea_608_parser_logger.log('INFO', 'DER- Delete to End of Row'); + this.writeScreen.clearToEndOfRow(); + this.outputDataUpdate(); + }; + + Cea608Channel.prototype.ccRU = function ccRU(nrRows) { + //Roll-Up Captions-2,3,or 4 Rows + cea_608_parser_logger.log('INFO', 'RU(' + nrRows + ') - Roll Up'); + this.writeScreen = this.displayedMemory; + this.setMode('MODE_ROLL-UP'); + this.writeScreen.setRollUpRows(nrRows); + }; + + Cea608Channel.prototype.ccFON = function ccFON() { + //Flash On + cea_608_parser_logger.log('INFO', 'FON - Flash On'); + this.writeScreen.setPen({ flash: true }); + }; + + Cea608Channel.prototype.ccRDC = function ccRDC() { + // Resume Direct Captioning (switch mode to PaintOn) + cea_608_parser_logger.log('INFO', 'RDC - Resume Direct Captioning'); + this.setMode('MODE_PAINT-ON'); + }; + + Cea608Channel.prototype.ccTR = function ccTR() { + // Text Restart in text mode (not supported, however) + cea_608_parser_logger.log('INFO', 'TR'); + this.setMode('MODE_TEXT'); + }; + + Cea608Channel.prototype.ccRTD = function ccRTD() { + // Resume Text Display in Text mode (not supported, however) + cea_608_parser_logger.log('INFO', 'RTD'); + this.setMode('MODE_TEXT'); + }; + + Cea608Channel.prototype.ccEDM = function ccEDM() { + // Erase Displayed Memory + cea_608_parser_logger.log('INFO', 'EDM - Erase Displayed Memory'); + this.displayedMemory.reset(); + this.outputDataUpdate(true); + }; + + Cea608Channel.prototype.ccCR = function ccCR() { + // Carriage Return + cea_608_parser_logger.log('CR - Carriage Return'); + this.writeScreen.rollUp(); + this.outputDataUpdate(true); + }; + + Cea608Channel.prototype.ccENM = function ccENM() { + //Erase Non-Displayed Memory + cea_608_parser_logger.log('INFO', 'ENM - Erase Non-displayed Memory'); + this.nonDisplayedMemory.reset(); + }; + + Cea608Channel.prototype.ccEOC = function ccEOC() { + //End of Caption (Flip Memories) + cea_608_parser_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; + cea_608_parser_logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText()); + } + this.outputDataUpdate(true); + }; + + Cea608Channel.prototype.ccTO = function ccTO(nrCols) { + // Tab Offset 1,2, or 3 columns + cea_608_parser_logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset'); + this.writeScreen.moveCursor(nrCols); + }; + + Cea608Channel.prototype.ccMIDROW = 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'; + } + cea_608_parser_logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles)); + this.writeScreen.setPen(styles); + }; + + Cea608Channel.prototype.outputDataUpdate = function outputDataUpdate() { + var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var t = cea_608_parser_logger.time; + if (t === null) { + return; + } + if (this.outputFilter) { + 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); + if (dispatch === true && this.outputFilter.dispatchCue) { + this.outputFilter.dispatchCue(); + } + } + this.cueStartTime = this.displayedMemory.isEmpty() ? null : t; + } + } + this.lastOutputScreen.copy(this.displayedMemory); + } + }; + + Cea608Channel.prototype.cueSplitAtTime = 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) { + cea_608_parser__classCallCheck(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 }; + } + + Cea608Parser.prototype.getHandler = function getHandler(index) { + return this.channels[index].getHandler(); + }; + + Cea608Parser.prototype.setHandler = 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. + */ + + + Cea608Parser.prototype.addData = function addData(t, byteList) { + var cmdFound, + a, + b, + charsFound = false; + + this.lastTime = t; + cea_608_parser_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 { + cea_608_parser_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 { + cea_608_parser_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; + cea_608_parser_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 + */ + + + Cea608Parser.prototype.parseCmd = 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) + cea_608_parser_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} + */ + + + Cea608Parser.prototype.parseMidrow = 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) { + cea_608_parser_logger.log('ERROR', 'Mismatch channel in midrow parsing'); + return false; + } + var channel = this.channels[chNr - 1]; + channel.ccMIDROW(b); + cea_608_parser_logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')'); + return true; + } + return false; + }; + /** + * Parse Preable Access Codes (Table 53). + * @returns {Boolean} Tells if PAC found + */ + + + Cea608Parser.prototype.parsePAC = 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. + */ + + + Cea608Parser.prototype.interpretPAC = 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. + */ + + + Cea608Parser.prototype.parseChars = 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; + } + cea_608_parser_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); + cea_608_parser_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 + */ + + + Cea608Parser.prototype.parseBackgroundAttributes = 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. + */ + + + Cea608Parser.prototype.reset = 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. + */ + + + Cea608Parser.prototype.cueSplitAtTime = function cueSplitAtTime(t) { + for (var i = 0; i < this.channels.length; i++) { + if (this.channels[i]) { + this.channels[i].cueSplitAtTime(t); + } + } + }; + + return Cea608Parser; +}(); + +/* harmony default export */ var cea_608_parser = (Cea608Parser); +// CONCATENATED MODULE: ./src/utils/output-filter.js +function output_filter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var OutputFilter = function () { + function OutputFilter(timelineController, track) { + output_filter__classCallCheck(this, OutputFilter); + + this.timelineController = timelineController; + this.track = track; + this.startTime = null; + this.endTime = null; + this.screen = null; + } + + OutputFilter.prototype.dispatchCue = function dispatchCue() { + if (this.startTime === null) { + return; + } + this.timelineController.addCues('textTrack' + this.track, this.startTime, this.endTime, this.screen); + this.startTime = null; + }; + + OutputFilter.prototype.newCue = function newCue(startTime, endTime, screen) { + if (this.startTime === null || this.startTime > startTime) { + this.startTime = startTime; + } + this.endTime = endTime; + this.screen = screen; + this.timelineController.createCaptionsTrack(this.track); + }; + + return OutputFilter; +}(); + +/* harmony default export */ var output_filter = (OutputFilter); +// CONCATENATED MODULE: ./src/utils/webvtt-parser.js + + + +// 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; + // Uint8Array.prototype.reduce is not implemented in IE11 + var vttLines = Object(id3["b" /* utf8ArrayToStr */])(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 vttparser(); + + 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.toString()) + hash(cue.endTime.toString()) + hash(cue.text); + + // Fix encoding of special characters. TODO: Test with all sorts of weird characters. + cue.text = decodeURIComponent(encodeURIComponent(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(); + } +}; + +/* harmony default export */ var webvtt_parser = (WebVTTParser); +// CONCATENATED MODULE: ./src/controller/timeline-controller.js +function timeline_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function timeline_controller__possibleConstructorReturn(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 timeline_controller__inherits(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 timeline_controller_TimelineController = function (_EventHandler) { + timeline_controller__inherits(TimelineController, _EventHandler); + + function TimelineController(hls) { + timeline_controller__classCallCheck(this, TimelineController); + + var _this = timeline_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_USERDATA, events["a" /* default */].FRAG_DECRYPTED, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].LEVEL_SWITCHING, events["a" /* 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 channel1 = new output_filter(_this, 1); + var channel2 = new output_filter(_this, 2); + + _this.cea608Parser = new cea_608_parser(0, channel1, channel2); + } + return _this; + } + + TimelineController.prototype.addCues = 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. + + + TimelineController.prototype.onInitPtsFound = 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 = []; + } + }; + + TimelineController.prototype.getExistingTrack = 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; + }; + + TimelineController.prototype.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); + }; + + TimelineController.prototype.createCaptionsTrack = function createCaptionsTrack(track) { + var trackVar = 'textTrack' + track; + if (!this[trackVar]) { + //Enable reuse of existing text track. + var existingTrack = this.getExistingTrack(track); + if (!existingTrack) { + var textTrack = this.createTextTrack('captions', this.config['captionsTextTrack' + track + 'Label'], this.config.captionsTextTrack1LanguageCode); + if (textTrack) { + textTrack[trackVar] = true; + this[trackVar] = textTrack; + } + } else { + this[trackVar] = existingTrack; + clearCurrentCues(this[trackVar]); + + this.sendAddTrackEvent(this[trackVar], this.media); + } + } + }; + + TimelineController.prototype.createTextTrack = function createTextTrack(kind, label, lang) { + var media = this.media; + if (media) { + return media.addTextTrack(kind, label, lang); + } + }; + + TimelineController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + TimelineController.prototype.onMediaAttaching = function onMediaAttaching(data) { + this.media = data.media; + this._cleanTracks(); + }; + + TimelineController.prototype.onMediaDetaching = function onMediaDetaching() { + clearCurrentCues(this.textTrack1); + clearCurrentCues(this.textTrack2); + }; + + TimelineController.prototype.onManifestLoading = function onManifestLoading() { + this.lastSn = -1; // Detect discontiguity in fragment parsing + this.prevCC = -1; + this.vttCCs = { ccOffset: 0, presentationOffset: 0 }; // Detect discontinuity in subtitle manifests + this._cleanTracks(); + }; + + TimelineController.prototype._cleanTracks = function _cleanTracks() { + // 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]); + } + } + } + }; + + TimelineController.prototype.onManifestLoaded = 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); + }); + } + }; + + TimelineController.prototype.onLevelSwitching = function onLevelSwitching() { + this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE'; + }; + + TimelineController.prototype.onFragLoaded = 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 decryptData = frag.decryptdata; + // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait. + if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') { + this._parseVTTs(frag, payload); + } + } else { + // In case there is no payload, finish unsuccessfully. + this.hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); + } + } + }; + + TimelineController.prototype._parseVTTs = function _parseVTTs(frag, payload) { + 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. + webvtt_parser.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)) { + try { + currentTrack.addCue(cue); + } catch (err) { + var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text); + textTrackCue.id = cue.id; + currentTrack.addCue(textTrackCue); + } + } + }); + hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag }); + }, function (e) { + // Something went wrong while parsing. Trigger event with success false. + logger["b" /* logger */].log('Failed to parse VTT cue: ' + e); + hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); + }); + }; + + TimelineController.prototype.onFragDecrypted = function onFragDecrypted(data) { + var decryptedData = data.payload, + frag = data.frag; + + if (frag.type === 'subtitle') { + if (typeof this.initPTS === 'undefined') { + this.unparsedVttFrags.push(data); + return; + } + + this._parseVTTs(frag, decryptedData); + } + }; + + TimelineController.prototype.onFragParsingUserdata = 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); + } + } + }; + + TimelineController.prototype.extractCea608Data = 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; +}(event_handler); + +/* harmony default export */ var timeline_controller = (timeline_controller_TimelineController); +// CONCATENATED MODULE: ./src/controller/subtitle-track-controller.js +var subtitle_track_controller__createClass = 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 subtitle_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function subtitle_track_controller__possibleConstructorReturn(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 subtitle_track_controller__inherits(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 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 subtitle_track_controller_SubtitleTrackController = function (_EventHandler) { + subtitle_track_controller__inherits(SubtitleTrackController, _EventHandler); + + function SubtitleTrackController(hls) { + subtitle_track_controller__classCallCheck(this, SubtitleTrackController); + + var _this = subtitle_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].SUBTITLE_TRACK_LOADED)); + + _this.tracks = []; + _this.trackId = -1; + _this.media = undefined; + _this.subtitleDisplay = false; + return _this; + } + + SubtitleTrackController.prototype._onTextTracksChanged = 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; + }; + + SubtitleTrackController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + // Listen for subtitle track change, then extract the current track ID. + + + SubtitleTrackController.prototype.onMediaAttached = function onMediaAttached(data) { + var _this2 = this; + + this.media = data.media; + if (!this.media) { + return; + } + + if (this.queuedDefaultTrack !== undefined) { + this.subtitleTrack = this.queuedDefaultTrack; + delete this.queuedDefaultTrack; + } + + this.trackChangeListener = this._onTextTracksChanged.bind(this); + + this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks); + if (this.useTextTrackPolling) { + this.subtitlePollingInterval = setInterval(function () { + _this2.trackChangeListener(); + }, 500); + } else { + this.media.textTracks.addEventListener('change', this.trackChangeListener); + } + }; + + SubtitleTrackController.prototype.onMediaDetaching = function onMediaDetaching() { + if (!this.media) { + return; + } + if (this.useTextTrackPolling) { + clearInterval(this.subtitlePollingInterval); + } else { + this.media.textTracks.removeEventListener('change', this.trackChangeListener); + } + + this.media = undefined; + }; + + // Reset subtitle tracks on manifest loading + + + SubtitleTrackController.prototype.onManifestLoading = function onManifestLoading() { + this.tracks = []; + this.trackId = -1; + }; + + // Fired whenever a new manifest is loaded. + + + SubtitleTrackController.prototype.onManifestLoaded = function onManifestLoaded(data) { + var _this3 = this; + + var tracks = data.subtitles || []; + this.tracks = tracks; + this.trackId = -1; + this.hls.trigger(events["a" /* 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) { + // setting this.subtitleTrack will trigger internal logic + // if media has not been attached yet, it will fail + // we keep a reference to the default track id + // and we'll set subtitleTrack when onMediaAttached is triggered + if (_this3.media) { + _this3.subtitleTrack = track.id; + } else { + _this3.queuedDefaultTrack = track.id; + } + } + }); + }; + + // Trigger subtitle track playlist reload. + + + SubtitleTrackController.prototype.onTick = 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["b" /* logger */].log('(re)loading playlist for subtitle track ' + trackId); + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: trackId }); + } + }; + + SubtitleTrackController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) { + var _this4 = this; + + if (data.id < this.tracks.length) { + logger["b" /* 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 () { + _this4.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 **/ + + + SubtitleTrackController.prototype.setSubtitleTrackInternal = function setSubtitleTrackInternal(newId) { + // check if level idx is valid + if (newId < -1 || newId >= this.tracks.length) { + return; + } + + // stopping live reloading timer if any + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + + var textTracks = filterSubtitleTracks(this.media.textTracks); + + // hide currently enabled subtitle track + if (this.trackId !== -1 && this.subtitleDisplay) { + textTracks[this.trackId].mode = 'hidden'; + } + + this.trackId = newId; + logger["b" /* logger */].log('switching to subtitle track ' + newId); + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_SWITCH, { id: newId }); + + if (newId === -1) { + return; + } + + var subtitleTrack = this.tracks[newId]; + if (this.subtitleDisplay) { + textTracks[newId].mode = 'showing'; + } + + // 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["b" /* logger */].log('(re)loading playlist for subtitle track ' + newId); + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId }); + } + }; + + subtitle_track_controller__createClass(SubtitleTrackController, [{ + 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; +}(event_handler); + +/* harmony default export */ var subtitle_track_controller = (subtitle_track_controller_SubtitleTrackController); +// EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules +var decrypter = __webpack_require__(4); + +// CONCATENATED MODULE: ./src/controller/subtitle-stream-controller.js +function subtitle_stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function subtitle_stream_controller__possibleConstructorReturn(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 subtitle_stream_controller__inherits(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 subtitle_stream_controller_State = { + STOPPED: 'STOPPED', + IDLE: 'IDLE', + KEY_LOADING: 'KEY_LOADING', + FRAG_LOADING: 'FRAG_LOADING' +}; + +var subtitle_stream_controller_SubtitleStreamController = function (_EventHandler) { + subtitle_stream_controller__inherits(SubtitleStreamController, _EventHandler); + + function SubtitleStreamController(hls) { + subtitle_stream_controller__classCallCheck(this, SubtitleStreamController); + + var _this = subtitle_stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].ERROR, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].SUBTITLE_TRACKS_UPDATED, events["a" /* default */].SUBTITLE_TRACK_SWITCH, events["a" /* default */].SUBTITLE_TRACK_LOADED, events["a" /* default */].SUBTITLE_FRAG_PROCESSED)); + + _this.config = hls.config; + _this.vttFragSNsProcessed = {}; + _this.vttFragQueues = undefined; + _this.currentlyProcessing = null; + _this.state = subtitle_stream_controller_State.STOPPED; + _this.currentTrackId = -1; + _this.ticks = 0; + _this.decrypter = new decrypter["a" /* default */](hls.observer, hls.config); + return _this; + } + + SubtitleStreamController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + this.state = subtitle_stream_controller_State.STOPPED; + }; + + // Remove all queued items and create a new, empty queue for each track. + + + SubtitleStreamController.prototype.clearVttFragQueues = 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. + + + SubtitleStreamController.prototype.nextFrag = function nextFrag() { + if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) { + var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift(); + this.fragCurrent = frag; + this.hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag }); + this.state = subtitle_stream_controller_State.FRAG_LOADING; + } + }; + + // When fragment has finished processing, add sn to list of completed if successful. + + + SubtitleStreamController.prototype.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) { + if (data.success) { + this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn); + } + this.currentlyProcessing = null; + this.state = subtitle_stream_controller_State.IDLE; + this.nextFrag(); + }; + + SubtitleStreamController.prototype.onMediaAttached = function onMediaAttached() { + this.state = subtitle_stream_controller_State.IDLE; + }; + + // If something goes wrong, procede to next frag, if we were processing one. + + + SubtitleStreamController.prototype.onError = 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(); + } + }; + + SubtitleStreamController.prototype.tick = function tick() { + var _this3 = this; + + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(function () { + _this3.tick(); + }, 1); + } + this.ticks = 0; + } + }; + + SubtitleStreamController.prototype.doTick = function doTick() { + var _this4 = this; + + switch (this.state) { + case subtitle_stream_controller_State.IDLE: + var tracks = this.tracks; + var trackId = this.currentTrackId; + + var processedFragSNs = this.vttFragSNsProcessed[trackId], + fragQueue = this.vttFragQueues[trackId], + 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; + }); + }; + + // exit if tracks don't exist + if (!tracks) { + break; + } + var trackDetails; + + if (trackId < tracks.length) { + trackDetails = tracks[trackId].details; + } + + if (typeof trackDetails === 'undefined') { + break; + } + + // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue. + trackDetails.fragments.forEach(function (frag) { + if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) { + // Load key if subtitles are encrypted + if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) { + logger["b" /* logger */].log('Loading key for ' + frag.sn); + _this4.state = subtitle_stream_controller_State.KEY_LOADING; + _this4.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + } else { + // Frags don't know their subtitle track ID, so let's just add that... + frag.trackId = trackId; + fragQueue.push(frag); + _this4.nextFrag(); + } + } + }); + } + }; + + // Got all new subtitle tracks. + + + SubtitleStreamController.prototype.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) { + var _this5 = this; + + logger["b" /* logger */].log('subtitle tracks updated'); + this.tracks = data.subtitleTracks; + this.clearVttFragQueues(); + this.vttFragSNsProcessed = {}; + this.tracks.forEach(function (track) { + _this5.vttFragSNsProcessed[track.id] = []; + }); + }; + + SubtitleStreamController.prototype.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) { + this.currentTrackId = data.id; + this.clearVttFragQueues(); + }; + + // Got a new set of subtitle fragments. + + + SubtitleStreamController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded() { + this.tick(); + }; + + SubtitleStreamController.prototype.onKeyLoaded = function onKeyLoaded() { + if (this.state === subtitle_stream_controller_State.KEY_LOADING) { + this.state = subtitle_stream_controller_State.IDLE; + this.tick(); + } + }; + + SubtitleStreamController.prototype.onFragLoaded = function onFragLoaded(data) { + var fragCurrent = this.fragCurrent, + decryptData = data.frag.decryptdata; + var fragLoaded = data.frag, + hls = this.hls; + if (this.state === subtitle_stream_controller_State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) { + // check to see if the payload needs to be decrypted + if (data.payload.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.method === 'AES-128') { + var startTime; + try { + startTime = performance.now(); + } catch (error) { + startTime = Date.now(); + } + // decrypt the subtitles + this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) { + var endTime; + try { + endTime = performance.now(); + } catch (error) { + endTime = Date.now(); + } + hls.trigger(events["a" /* default */].FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); + }); + } + } + }; + + return SubtitleStreamController; +}(event_handler); + +/* harmony default export */ var subtitle_stream_controller = (subtitle_stream_controller_SubtitleStreamController); +// CONCATENATED MODULE: ./src/config.js +/** + * HLS config + */ + + + + + + +//import FetchLoader from './utils/fetch-loader'; + + + + + + + + + +var 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 + liveDurationInfinity: false, // used by buffer-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: xhr_loader, + //loader: FetchLoader, + fLoader: undefined, + pLoader: undefined, + xhrSetup: undefined, + fetchSetup: undefined, + abrController: abr_controller, + bufferController: buffer_controller, + capLevelController: cap_level_controller, + fpsController: fps_controller, + stretchShortVideoTrack: false, // used by mp4-remuxer + maxAudioFramesDrift: 1, // 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 +}; + +{ + hlsDefaultConfig.subtitleStreamController = subtitle_stream_controller; + hlsDefaultConfig.subtitleTrackController = subtitle_track_controller; + hlsDefaultConfig.timelineController = timeline_controller; + hlsDefaultConfig.cueHandler = cues_namespaceObject; + hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller + hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller +} + +{ + hlsDefaultConfig.audioStreamController = audio_stream_controller; + hlsDefaultConfig.audioTrackController = audio_track_controller; +} +// CONCATENATED MODULE: ./src/hls.js +var hls__createClass = 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 hls__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * HLS interface + */ + + + + + + + + + + + + + + + + +var hls_Hls = function () { + Hls.isSupported = function isSupported() { + return is_supported_isSupported(); + }; + + hls__createClass(Hls, null, [{ + key: 'version', + get: function get() { + return "0.8.9"; + } + }, { + key: 'Events', + get: function get() { + return events["a" /* default */]; + } + }, { + key: 'ErrorTypes', + get: function get() { + return errors["b" /* ErrorTypes */]; + } + }, { + key: 'ErrorDetails', + get: function get() { + return errors["a" /* ErrorDetails */]; + } + }, { + key: 'DefaultConfig', + get: function get() { + if (!Hls.defaultConfig) { + return 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] : {}; + + hls__classCallCheck(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"'); + } + + Object(logger["a" /* enableLogs */])(config.debug); + this.config = config; + this._autoLevelCapping = -1; + // observer setup + var observer = this.observer = new events_default.a(); + 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 playlist_loader(this); + var fragmentLoader = new fragment_loader(this); + var keyLoader = new key_loader(this); + var id3TrackController = new id3_track_controller(this); + + // network controllers + var levelController = this.levelController = new level_controller(this); + var streamController = this.streamController = new stream_controller(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; + } + + Hls.prototype.destroy = function destroy() { + logger["b" /* logger */].log('destroy'); + this.trigger(events["a" /* default */].DESTROYING); + this.detachMedia(); + this.coreComponents.concat(this.networkControllers).forEach(function (component) { + component.destroy(); + }); + this.url = null; + this.observer.removeAllListeners(); + this._autoLevelCapping = -1; + }; + + Hls.prototype.attachMedia = function attachMedia(media) { + logger["b" /* logger */].log('attachMedia'); + this.media = media; + this.trigger(events["a" /* default */].MEDIA_ATTACHING, { media: media }); + }; + + Hls.prototype.detachMedia = function detachMedia() { + logger["b" /* logger */].log('detachMedia'); + this.trigger(events["a" /* default */].MEDIA_DETACHING); + this.media = null; + }; + + Hls.prototype.loadSource = function loadSource(url) { + url = url_toolkit_default.a.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true }); + logger["b" /* logger */].log('loadSource:' + url); + this.url = url; + // when attaching to a source URL, trigger a playlist load + this.trigger(events["a" /* default */].MANIFEST_LOADING, { url: url }); + }; + + Hls.prototype.startLoad = function startLoad() { + var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1; + + logger["b" /* logger */].log('startLoad(' + startPosition + ')'); + this.networkControllers.forEach(function (controller) { + controller.startLoad(startPosition); + }); + }; + + Hls.prototype.stopLoad = function stopLoad() { + logger["b" /* logger */].log('stopLoad'); + this.networkControllers.forEach(function (controller) { + controller.stopLoad(); + }); + }; + + Hls.prototype.swapAudioCodec = function swapAudioCodec() { + logger["b" /* logger */].log('swapAudioCodec'); + this.streamController.swapAudioCodec(); + }; + + Hls.prototype.recoverMediaError = function recoverMediaError() { + logger["b" /* logger */].log('recoverMediaError'); + var media = this.media; + this.detachMedia(); + this.attachMedia(media); + }; + + /** Return all quality levels **/ + + + hls__createClass(Hls, [{ + 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["b" /* 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["b" /* 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["b" /* 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["b" /* 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["b" /* 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["b" /* 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; + } + } + }, { + key: 'subtitleDisplay', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; + }, + set: function set(value) { + var subtitleTrackController = this.subtitleTrackController; + if (subtitleTrackController) { + subtitleTrackController.subtitleDisplay = value; + } + } + }]); + + return Hls; +}(); + +/* harmony default export */ var src_hls = __webpack_exports__["default"] = (hls_Hls); + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +function webpackBootstrapFunc (modules) { +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.l = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; + +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; + +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; + +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // on error function for async loading +/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; + + var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE); + return f.default || f // try to call default if defined to also support babel esmodule exports +} + +// http://stackoverflow.com/a/2593661/130442 +function quoteRegExp (str) { + return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') +} + +function getModuleDependencies (module) { + var retval = []; + var fnString = module.toString(); + var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/); + if (!wrapperSignature) return retval + + var webpackRequireName = wrapperSignature[1]; + var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + '\\((\/\\*.*?\\*\/)?\s?.*?([\\.|\\-|\\w|\/|@]+).*?\\)', 'g'); // additional chars when output.pathinfo is true + var match; + while ((match = re.exec(fnString))) { + retval.push(match[3]); + } + return retval +} + +function getRequiredModules (sources, moduleId) { + var modulesQueue = [moduleId]; + var requiredModules = []; + var seenModules = {}; + + while (modulesQueue.length) { + var moduleToCheck = modulesQueue.pop(); + if (seenModules[moduleToCheck] || !sources[moduleToCheck]) continue + seenModules[moduleToCheck] = true; + requiredModules.push(moduleToCheck); + var newModules = getModuleDependencies(sources[moduleToCheck]); + modulesQueue = modulesQueue.concat(newModules); + } + + return requiredModules +} + +module.exports = function (moduleId, options) { + options = options || {}; + var sources = __webpack_require__.m; + + var requiredModules = options.all ? Object.keys(sources) : getRequiredModules(sources, moduleId); + var src = '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[id].toString() }).join(',') + '})(self);'; + + var blob = new window.Blob([src], { type: 'text/javascript' }); + if (options.bare) { return blob } + + var URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + var workerUrl = URL.createObjectURL(blob); + var worker = new window.Worker(workerUrl); + worker.objectURL = workerUrl; + + return worker +}; + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_events__); +/* 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 __WEBPACK_IMPORTED_MODULE_3_events___default.a(); + 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 __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__["a" /* default */](observer, data.typeSupported, config, data.vendor); + try { + Object(__WEBPACK_IMPORTED_MODULE_2__utils_logger__["a" /* 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(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_DECRYPTED, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSED, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].ERROR, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_METADATA, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].INIT_PTS_FOUND, forwardMessage); + + // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy) + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* 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); + }); +}; + +/* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker); + +/***/ }) +/******/ ])["default"]; +}); + +}); + +var HlsCore = unwrapExports(hls); + +var defaultCustomConfig = { + debug: false, + enableWorker: true +}; + +var _class$9; + +function _applyDecoratedDescriptor$8(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; +} + +var LOG_TAG$1 = 'chimee-kernel-hls'; + +var Hls = (_class$9 = function (_CustEvent) { + _inherits(Hls, _CustEvent); + + _createClass(Hls, null, [{ + key: 'isSupport', + value: function isSupport() { + return HlsCore.isSupported(); + } + }]); + + function Hls(videoElement, config) { + var customConfig = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, Hls); + + var _this = _possibleConstructorReturn(this, (Hls.__proto__ || _Object$getPrototypeOf(Hls)).call(this)); + + _this.version = '1.2.0'; + + if (!isElement(videoElement)) throw new Error('video element passed in ' + LOG_TAG$1 + ' must be a HTMLVideoElement, but not ' + (typeof videoElement === 'undefined' ? 'undefined' : _typeof(videoElement))); + if (!isObject(config)) throw new Error('config of ' + LOG_TAG$1 + ' must be an Object but not ' + (typeof config === 'undefined' ? 'undefined' : _typeof(config))); + _this.video = videoElement; + _this.config = config; + _this.customConfig = deepAssign({}, defaultCustomConfig, customConfig); + _this.hlsKernel = new HlsCore(_this.customConfig); + _this.bindEvents(); + _this.attachMedia(); + return _this; + } + + _createClass(Hls, [{ + key: 'bindEvents', + value: function bindEvents() { + var remove = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var hlsKernel = this.hlsKernel; + /* istanbul ignore else */ + if (hlsKernel) { + hlsKernel[remove ? 'off' : 'on'](HlsCore.Events.ERROR, this.hlsErrorHandler); + } + } + }, { + key: 'load', + value: function load() { + return this.hlsKernel.loadSource(this.config.src); + } + }, { + key: 'startLoad', + value: function startLoad() { + return this.hlsKernel.startLoad(); + } + }, { + key: 'stopLoad', + value: function stopLoad() { + return this.hlsKernel.stopLoad(); + } + }, { + key: 'attachMedia', + value: function attachMedia() { + return this.hlsKernel.attachMedia(this.video); + } + }, { + key: 'play', + value: function play() { + return this.video.play(); + } + }, { + key: 'destroy', + value: function destroy() { + this.bindEvents(true); + return this.hlsKernel.destroy(); + } + }, { + key: 'seek', + value: function seek(seconds) { + this.video.currentTime = seconds; + } + }, { + key: 'pause', + value: function pause() { + return this.video.pause(); + } + }, { + key: 'refresh', + value: function refresh() { + this.hlsKernel.stopLoad(); + return this.hlsKernel.loadSource(this.config.src); + } + }, { + key: 'hlsErrorHandler', + value: function hlsErrorHandler(event, data) { + this.emit('error', data); + this.emit(event, data); + /* istanbul ignore next */ + Log$1.error(LOG_TAG$1 + (event ? ' ' + event : ''), data.details); + } + }]); + + return Hls; +}(CustEvent), _applyDecoratedDescriptor$8(_class$9.prototype, 'hlsErrorHandler', [autobind], _Object$getOwnPropertyDescriptor(_class$9.prototype, 'hlsErrorHandler'), _class$9.prototype), _class$9); + +var lib$2 = createCommonjsModule(function (module, exports) { +(function webpackUniversalModuleDefinition(root, factory) { + module.exports = factory(); +})(commonjsGlobal, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 6); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * chimee-helper-events v0.1.0 + * (c) 2017 toxic-johann + * Released under MIT + */ + +(function (global, factory) { + factory(exports); +}(this, (function (exports) { +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; +} + +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +var _toInteger = function(it){ + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +// 7.2.1 RequireObjectCoercible(argument) +var _defined = function(it){ + if(it == undefined)throw TypeError("Can't call method on " + it); + return it; +}; + +// true -> String#at +// false -> String#codePointAt +var _stringAt = function(TO_STRING){ + return function(that, pos){ + var s = String(_defined(that)) + , i = _toInteger(pos) + , l = s.length + , a, b; + if(i < 0 || i >= l)return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +var _library = true; + +var _global = createCommonjsModule$$1(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); +if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef +}); + +var _core = createCommonjsModule$$1(function (module) { +var core = module.exports = {version: '2.4.0'}; +if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef +}); + +var _aFunction = function(it){ + if(typeof it != 'function')throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx = function(fn, that, length){ + _aFunction(fn); + if(that === undefined)return fn; + switch(length){ + case 1: return function(a){ + return fn.call(that, a); + }; + case 2: return function(a, b){ + return fn.call(that, a, b); + }; + case 3: return function(a, b, c){ + return fn.call(that, a, b, c); + }; + } + return function(/* ...args */){ + return fn.apply(that, arguments); + }; +}; + +var _isObject = function(it){ + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject = function(it){ + if(!_isObject(it))throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails = function(exec){ + try { + return !!exec(); + } catch(e){ + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors = !_fails(function(){ + return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; +}); + +var document$1 = _global.document; +var is = _isObject(document$1) && _isObject(document$1.createElement); +var _domCreate = function(it){ + return is ? document$1.createElement(it) : {}; +}; + +var _ie8DomDefine = !_descriptors && !_fails(function(){ + return Object.defineProperty(_domCreate('div'), 'a', {get: function(){ return 7; }}).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive = function(it, S){ + if(!_isObject(it))return it; + var fn, val; + if(S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it)))return val; + if(typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it)))return val; + if(!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it)))return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP = Object.defineProperty; + +var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes){ + _anObject(O); + P = _toPrimitive(P, true); + _anObject(Attributes); + if(_ie8DomDefine)try { + return dP(O, P, Attributes); + } catch(e){ /* empty */ } + if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); + if('value' in Attributes)O[P] = Attributes.value; + return O; +}; + +var _objectDp = { + f: f +}; + +var _propertyDesc = function(bitmap, value){ + return { + enumerable : !(bitmap & 1), + configurable: !(bitmap & 2), + writable : !(bitmap & 4), + value : value + }; +}; + +var _hide = _descriptors ? function(object, key, value){ + return _objectDp.f(object, key, _propertyDesc(1, value)); +} : function(object, key, value){ + object[key] = value; + return object; +}; + +var PROTOTYPE = 'prototype'; + +var $export = function(type, name, source){ + var IS_FORCED = type & $export.F + , IS_GLOBAL = type & $export.G + , IS_STATIC = type & $export.S + , IS_PROTO = type & $export.P + , IS_BIND = type & $export.B + , IS_WRAP = type & $export.W + , exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}) + , expProto = exports[PROTOTYPE] + , target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE] + , key, own, out; + if(IS_GLOBAL)source = name; + for(key in source){ + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if(own && key in exports)continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? _ctx(out, _global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function(C){ + var F = function(a, b, c){ + if(this instanceof C){ + switch(arguments.length){ + case 0: return new C; + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if(IS_PROTO){ + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if(type & $export.R && expProto && !expProto[key])_hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +var _export = $export; + +var _redefine = _hide; + +var hasOwnProperty = {}.hasOwnProperty; +var _has = function(it, key){ + return hasOwnProperty.call(it, key); +}; + +var toString = {}.toString; + +var _cof = function(it){ + return toString.call(it).slice(8, -1); +}; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings + +var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function(it){ + return _cof(it) == 'String' ? it.split('') : Object(it); +}; + +// to indexed object, toObject with fallback for non-array-like ES3 strings + +var _toIobject = function(it){ + return _iobject(_defined(it)); +}; + +// 7.1.15 ToLength +var min = Math.min; +var _toLength = function(it){ + return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +var max = Math.max; +var min$1 = Math.min; +var _toIndex = function(index, length){ + index = _toInteger(index); + return index < 0 ? max(index + length, 0) : min$1(index, length); +}; + +// false -> Array#indexOf +// true -> Array#includes + +var _arrayIncludes = function(IS_INCLUDES){ + return function($this, el, fromIndex){ + var O = _toIobject($this) + , length = _toLength(O.length) + , index = _toIndex(fromIndex, length) + , value; + // Array#includes uses SameValueZero equality algorithm + if(IS_INCLUDES && el != el)while(length > index){ + value = O[index++]; + if(value != value)return true; + // Array#toIndex ignores holes, Array#includes - not + } else for(;length > index; index++)if(IS_INCLUDES || index in O){ + if(O[index] === el)return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +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 _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); + // Don't enum bug & hidden keys + while(names.length > i)if(_has(O, key = names[i++])){ + ~arrayIndexOf(result, key) || result.push(key); + } + return result; +}; + +// IE 8- don't enum bug keys +var _enumBugKeys = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) + + +var _objectKeys = Object.keys || function keys(O){ + return _objectKeysInternal(O, _enumBugKeys); +}; + +var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties){ + _anObject(O); + var keys = _objectKeys(Properties) + , length = keys.length + , i = 0 + , P; + while(length > i)_objectDp.f(O, P = keys[i++], Properties[P]); + return O; +}; + +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 Empty = function(){ /* empty */ }; +var PROTOTYPE$1 = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function(){ + // Thrash, waste and sodomy: IE GC bug + var iframe = _domCreate('iframe') + , i = _enumBugKeys.length + , lt = '<' + , gt = '>' + , iframeDocument; + iframe.style.display = 'none'; + _html.appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while(i--)delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; + return createDict(); +}; + +var _objectCreate = Object.create || function create(O, Properties){ + var result; + if(O !== null){ + Empty[PROTOTYPE$1] = _anObject(O); + result = new Empty; + Empty[PROTOTYPE$1] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : _objectDps(result, Properties); +}; + +var _wks = createCommonjsModule$$1(function (module) { +var store = _shared('wks') + , Symbol = _global.Symbol + , USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function(name){ + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); +}; + +$exports.store = store; +}); + +var def = _objectDp.f; +var TAG = _wks('toStringTag'); + +var _setToStringTag = function(it, tag, stat){ + if(it && !_has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); +}; + +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_hide(IteratorPrototype, _wks('iterator'), function(){ return this; }); + +var _iterCreate = function(Constructor, NAME, next){ + Constructor.prototype = _objectCreate(IteratorPrototype, {next: _propertyDesc(1, 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'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function(){ return this; }; + +var _iterDefine = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ + _iterCreate(Constructor, NAME, next); + var getMethod = function(kind){ + if(!BUGGY && kind in proto)return proto[kind]; + switch(kind){ + case KEYS: return function keys(){ return new Constructor(this, kind); }; + case VALUES: return function values(){ return new Constructor(this, kind); }; + } return function entries(){ return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator' + , DEF_VALUES = DEFAULT == VALUES + , VALUES_BUG = false + , proto = Base.prototype + , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] + , $default = $native || getMethod(DEFAULT) + , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined + , $anyNative = NAME == 'Array' ? proto.entries || $native : $native + , methods, key, IteratorPrototype; + // Fix native + if($anyNative){ + IteratorPrototype = _objectGpo($anyNative.call(new Base)); + if(IteratorPrototype !== Object.prototype){ + // Set @@toStringTag to native iterators + _setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if(!_library && !_has(IteratorPrototype, ITERATOR))_hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if(DEF_VALUES && $native && $native.name !== VALUES){ + VALUES_BUG = true; + $default = function values(){ return $native.call(this); }; + } + // Define iterator + if((!_library || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ + _hide(proto, ITERATOR, $default); + } + if(DEFAULT){ + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if(FORCED)for(key in methods){ + if(!(key in proto))_redefine(proto, key, methods[key]); + } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; + +var $at = _stringAt(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_iterDefine(String, 'String', function(iterated){ + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function(){ + var O = this._t + , index = this._i + , point; + if(index >= O.length)return {value: undefined, done: true}; + point = $at(O, index); + this._i += point.length; + return {value: point, done: false}; +}); + +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'); + +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); +} + +var f$1 = _wks; + +var _wksExt = { + f: f$1 +}; + +var iterator$2 = _wksExt.f('iterator'); + +var iterator = createCommonjsModule$$1(function (module) { +module.exports = { "default": iterator$2, __esModule: true }; +}); + +var _meta = createCommonjsModule$$1(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({})); +}); +var setMeta = function(it){ + setDesc(it, META, {value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + }}); +}; +var fastKey = function(it, create){ + // return primitive with prefix + if(!_isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if(!_has(it, META)){ + // can't set metadata to uncaught frozen object + if(!isExtensible(it))return 'F'; + // not necessary to add metadata + if(!create)return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function(it, create){ + if(!_has(it, META)){ + // can't set metadata to uncaught frozen object + if(!isExtensible(it))return true; + // not necessary to add metadata + if(!create)return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function(it){ + if(FREEZE && meta.NEED && isExtensible(it) && !_has(it, META))setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; +}); + +var defineProperty = _objectDp.f; +var _wksDefine = function(name){ + var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global.Symbol || {}); + if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: _wksExt.f(name)}); +}; + +var _keyof = function(object, el){ + var O = _toIobject(object) + , keys = _objectKeys(O) + , length = keys.length + , index = 0 + , key; + while(length > index)if(O[key = keys[index++]] === el)return key; +}; + +var f$2 = Object.getOwnPropertySymbols; + +var _objectGops = { + f: f$2 +}; + +var f$3 = {}.propertyIsEnumerable; + +var _objectPie = { + f: f$3 +}; + +// all enumerable object keys, includes symbols + +var _enumKeys = function(it){ + var result = _objectKeys(it) + , getSymbols = _objectGops.f; + if(getSymbols){ + var symbols = getSymbols(it) + , isEnum = _objectPie.f + , i = 0 + , key; + while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); + } return result; +}; + +// 7.2.2 IsArray(argument) + +var _isArray = Array.isArray || function isArray(arg){ + return _cof(arg) == 'Array'; +}; + +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) +var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); + +var f$5 = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ + return _objectKeysInternal(O, hiddenKeys); +}; + +var _objectGopn = { + f: f$5 +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window +var gOPN$1 = _objectGopn.f; +var toString$1 = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function(it){ + try { + return gOPN$1(it); + } catch(e){ + return windowNames.slice(); + } +}; + +var f$4 = function getOwnPropertyNames(it){ + return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN$1(_toIobject(it)); +}; + +var _objectGopnExt = { + f: f$4 +}; + +var gOPD$1 = Object.getOwnPropertyDescriptor; + +var f$6 = _descriptors ? gOPD$1 : function getOwnPropertyDescriptor(O, P){ + O = _toIobject(O); + P = _toPrimitive(P, true); + if(_ie8DomDefine)try { + return gOPD$1(O, P); + } catch(e){ /* empty */ } + if(_has(O, P))return _propertyDesc(!_objectPie.f.call(O, P), O[P]); +}; + +var _objectGopd = { + f: f$6 +}; + +// ECMAScript 6 symbols shim +var META = _meta.KEY; +var gOPD = _objectGopd.f; +var dP$1 = _objectDp.f; +var gOPN = _objectGopnExt.f; +var $Symbol = _global.Symbol; +var $JSON = _global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE$2 = 'prototype'; +var HIDDEN = _wks('_hidden'); +var TO_PRIMITIVE = _wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = _shared('symbol-registry'); +var AllSymbols = _shared('symbols'); +var OPSymbols = _shared('op-symbols'); +var ObjectProto$1 = Object[PROTOTYPE$2]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = _global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = _descriptors && _fails(function(){ + return _objectCreate(dP$1({}, 'a', { + get: function(){ return dP$1(this, 'a', {value: 7}).a; } + })).a != 7; +}) ? function(it, key, D){ + var protoDesc = gOPD(ObjectProto$1, key); + if(protoDesc)delete ObjectProto$1[key]; + dP$1(it, key, D); + if(protoDesc && it !== ObjectProto$1)dP$1(ObjectProto$1, key, protoDesc); +} : dP$1; + +var wrap = function(tag){ + var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ + return typeof it == 'symbol'; +} : function(it){ + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D){ + if(it === ObjectProto$1)$defineProperty(OPSymbols, key, D); + _anObject(it); + key = _toPrimitive(key, true); + _anObject(D); + if(_has(AllSymbols, key)){ + if(!D.enumerable){ + if(!_has(it, HIDDEN))dP$1(it, HIDDEN, _propertyDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if(_has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; + D = _objectCreate(D, {enumerable: _propertyDesc(0, false)}); + } return setSymbolDesc(it, key, D); + } return dP$1(it, key, D); +}; +var $defineProperties = function defineProperties(it, P){ + _anObject(it); + var keys = _enumKeys(P = _toIobject(P)) + , i = 0 + , l = keys.length + , key; + while(l > i)$defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P){ + return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key){ + var E = isEnum.call(this, key = _toPrimitive(key, true)); + if(this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key))return false; + return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ + it = _toIobject(it); + key = _toPrimitive(key, true); + if(it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key))return; + var D = gOPD(it, key); + if(D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it){ + var names = gOPN(_toIobject(it)) + , result = [] + , i = 0 + , key; + while(names.length > i){ + if(!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ + var IS_OP = it === ObjectProto$1 + , names = gOPN(IS_OP ? OPSymbols : _toIobject(it)) + , result = [] + , i = 0 + , key; + while(names.length > i){ + if(_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true))result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if(!USE_NATIVE){ + $Symbol = function Symbol(){ + if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); + var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function(value){ + if(this === ObjectProto$1)$set.call(OPSymbols, value); + if(_has(this, HIDDEN) && _has(this[HIDDEN], tag))this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, _propertyDesc(1, value)); + }; + if(_descriptors && setter)setSymbolDesc(ObjectProto$1, tag, {configurable: true, set: $set}); + return wrap(tag); + }; + _redefine($Symbol[PROTOTYPE$2], 'toString', function toString(){ + return this._k; + }); + + _objectGopd.f = $getOwnPropertyDescriptor; + _objectDp.f = $defineProperty; + _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; + _objectPie.f = $propertyIsEnumerable; + _objectGops.f = $getOwnPropertySymbols; + + if(_descriptors && !_library){ + _redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + _wksExt.f = function(name){ + return wrap(_wks(name)); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE, {Symbol: $Symbol}); + +for(var symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), i$1 = 0; symbols.length > i$1; )_wks(symbols[i$1++]); + +for(var symbols = _objectKeys(_wks.store), i$1 = 0; symbols.length > i$1; )_wksDefine(symbols[i$1++]); + +_export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function(key){ + return _has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(key){ + if(isSymbol(key))return _keyof(SymbolRegistry, key); + throw TypeError(key + ' is not a symbol!'); + }, + useSetter: function(){ setter = true; }, + useSimple: function(){ setter = false; } +}); + +_export(_export.S + _export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function(){ + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it){ + if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined + var args = [it] + , i = 1 + , replacer, $replacer; + while(arguments.length > i)args.push(arguments[i++]); + replacer = args[1]; + if(typeof replacer == 'function')$replacer = replacer; + if($replacer || !_isArray(replacer))replacer = function(key, value){ + if($replacer)value = $replacer.call(this, key, value); + if(!isSymbol(value))return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +_setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +_setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +_setToStringTag(_global.JSON, 'JSON', true); + +_wksDefine('asyncIterator'); + +_wksDefine('observable'); + +var index = _core.Symbol; + +var symbol = createCommonjsModule$$1(function (module) { +module.exports = { "default": index, __esModule: true }; +}); + +var _typeof_1 = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _iterator2 = _interopRequireDefault(iterator); + + + +var _symbol2 = _interopRequireDefault(symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +}); + +var _typeof = unwrapExports$$1(_typeof_1); + +var classCallCheck = createCommonjsModule$$1(function (module, exports) { + +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$$1(classCallCheck); + +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +_export(_export.S + _export.F * !_descriptors, 'Object', {defineProperty: _objectDp.f}); + +var $Object = _core.Object; +var defineProperty$3 = function defineProperty(it, key, desc){ + return $Object.defineProperty(it, key, desc); +}; + +var defineProperty$1 = createCommonjsModule$$1(function (module) { +module.exports = { "default": defineProperty$3, __esModule: true }; +}); + +var createClass = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty$1); + +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$$1(createClass); + +// 19.1.2.1 Object.assign(target, source, ...) +var $assign = Object.assign; + +// should work with symbols and should have deterministic property order (V8 bug) +var _objectAssign = !$assign || _fails(function(){ + var A = {} + , B = {} + , S = Symbol() + , K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function(k){ B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source){ // eslint-disable-line no-unused-vars + var T = _toObject(target) + , aLen = arguments.length + , index = 1 + , getSymbols = _objectGops.f + , isEnum = _objectPie.f; + while(aLen > index){ + var S = _iobject(arguments[index++]) + , keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S) + , length = keys.length + , j = 0 + , key; + while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; + } return T; +} : $assign; + +// 19.1.3.1 Object.assign(target, source) + + +_export(_export.S + _export.F, 'Object', {assign: _objectAssign}); + +var assign$1 = _core.Object.assign; + +var assign = createCommonjsModule$$1(function (module) { +module.exports = { "default": assign$1, __esModule: true }; +}); + +var _Object$assign = unwrapExports$$1(assign); + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +_export(_export.S, 'Object', {create: _objectCreate}); + +var $Object$1 = _core.Object; +var create$1 = function create(P, D){ + return $Object$1.create(P, D); +}; + +var create = createCommonjsModule$$1(function (module) { +module.exports = { "default": create$1, __esModule: true }; +}); + +var _Object$create = unwrapExports$$1(create); + +// most Object methods by ES6 should accept primitives + +var _objectSap = function(KEY, exec){ + var fn = (_core.Object || {})[KEY] || Object[KEY] + , exp = {}; + exp[KEY] = exec(fn); + _export(_export.S + _export.F * _fails(function(){ fn(1); }), 'Object', exp); +}; + +// 19.1.2.14 Object.keys(O) + + +_objectSap('keys', function(){ + return function keys(it){ + return _objectKeys(_toObject(it)); + }; +}); + +var keys$1 = _core.Object.keys; + +var keys = createCommonjsModule$$1(function (module) { +module.exports = { "default": keys$1, __esModule: true }; +}); + +// 20.1.2.3 Number.isInteger(number) +var floor$1 = Math.floor; +var _isInteger = function isInteger(it){ + return !_isObject(it) && isFinite(it) && floor$1(it) === it; +}; + +// 20.1.2.3 Number.isInteger(number) + + +_export(_export.S, 'Number', {isInteger: _isInteger}); + +var isInteger$2 = _core.Number.isInteger; + +var isInteger$1 = createCommonjsModule$$1(function (module) { +module.exports = { "default": isInteger$2, __esModule: true }; +}); + +var _stringWs = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +var space = '[' + _stringWs + ']'; +var non = '\u200b\u0085'; +var ltrim = RegExp('^' + space + space + '*'); +var rtrim = RegExp(space + space + '*$'); + +var exporter = function(KEY, exec, ALIAS){ + var exp = {}; + var FORCE = _fails(function(){ + return !!_stringWs[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : _stringWs[KEY]; + if(ALIAS)exp[ALIAS] = fn; + _export(_export.P + _export.F * FORCE, 'String', exp); +}; + +// 1 -> String#trimLeft +// 2 -> String#trimRight +// 3 -> String#trim +var trim = exporter.trim = function(string, TYPE){ + string = String(_defined(string)); + if(TYPE & 1)string = string.replace(ltrim, ''); + if(TYPE & 2)string = string.replace(rtrim, ''); + return string; +}; + +var _stringTrim = exporter; + +var $parseFloat = _global.parseFloat; +var $trim = _stringTrim.trim; + +var _parseFloat$3 = 1 / $parseFloat(_stringWs + '-0') !== -Infinity ? function parseFloat(str){ + var string = $trim(String(str), 3) + , result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; +} : $parseFloat; + +// 20.1.2.12 Number.parseFloat(string) +_export(_export.S + _export.F * (Number.parseFloat != _parseFloat$3), 'Number', {parseFloat: _parseFloat$3}); + +var _parseFloat$1 = parseFloat; + +var _parseFloat = createCommonjsModule$$1(function (module) { +module.exports = { "default": _parseFloat$1, __esModule: true }; +}); + +/** + * toxic-predicate-functions v0.1.2 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** + * to check whether a variable is array + * @param {Anything} arr + * @return {Boolean} true when it is a boolean + */ +function isArray$1(arr) { + return Array.isArray(arr); +} + +/** + * 判断是否为function + * @param {Anything} obj [description] + * @return {Boolean} [description] + */ +function isFunction(obj) { + return typeof obj === 'function'; +} + +/** + * 判断是否是对象 + * @param {Anything} obj 传入对象 + * @return {Boolean} [description] + */ +function isObject$1(obj) { + // incase of arrow function and array + return Object(obj) === obj && String(obj) === '[object Object]' && !isFunction(obj) && !isArray$1(obj); +} + +/** +* @module event +* @author huzunjie +* @description 自定义事件基础类 +*/ + +/* 缓存事件监听方法及包装,内部数据格式: + * targetIndex_<type:'click|mouseup|done'>: [ [ + * function(){ ... handler ... }, + * function(){ ... handlerWrap ... handler.apply(target, arguments) ... }, + * isOnce + * ]] + */ +var _evtListenerCache = _Object$create(null); +_evtListenerCache.count = 0; + +/** + * 得到某对象的某事件类型对应的监听队列数组 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型(这里的时间类型不只是名称,还是缓存标识,可以通过添加后缀来区分) + * @return {Array} + */ +function getEvtTypeCache(target, type) { + + var evtId = target.__evt_id; + if (!evtId) { + + /* 设置__evt_id不可枚举 */ + Object.defineProperty(target, '__evt_id', { + writable: true, + enumerable: false, + configurable: true + }); + + /* 空对象初始化绑定索引 */ + evtId = target.__evt_id = ++_evtListenerCache.count; + } + + var typeCacheKey = evtId + '_' + type; + var evtTypeCache = _evtListenerCache[typeCacheKey]; + if (!evtTypeCache) { + evtTypeCache = _evtListenerCache[typeCacheKey] = []; + } + + return evtTypeCache; +} + +/** + * 触发事件监听方法 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Object} eventObj 触发事件时要传回的event对象 + * @return {undefined} + */ +function emitEventCache(target, type, eventObj) { + var evt = _Object$create(null); + evt.type = type; + evt.target = target; + if (eventObj) { + _Object$assign(evt, isObject$1(eventObj) ? eventObj : { data: eventObj }); + } + getEvtTypeCache(target, type).forEach(function (item) { + (item[1] || item[0]).apply(target, [evt]); + }); +} + +/** + * 添加事件监听到缓存 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 是否单次执行 + * @param {Function} handlerWrap + * @return {undefined} + */ +function addEventCache(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var handlerWrap = arguments[4]; + + if (isFunction(isOnce) && !handlerWrap) { + handlerWrap = isOnce; + isOnce = undefined; + } + var handlers = [handler, undefined, isOnce]; + if (isOnce && !handlerWrap) { + handlerWrap = function handlerWrap() { + removeEventCache(target, type, handler, isOnce); + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + handler.apply(target, args); + }; + } + if (handlerWrap) { + handlers[1] = handlerWrap; + } + getEvtTypeCache(target, type).push(handlers); +} + +/** + * 移除事件监听 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {undefined} + */ +function removeEventCache(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var typeCache = getEvtTypeCache(target, type); + + if (handler || isOnce) { + /* 有指定 handler 则清除对应监听 */ + var handlerId = -1; + var handlerWrap = void 0; + typeCache.find(function (item, i) { + if ((!handler || item[0] === handler) && (!isOnce || item[2])) { + handlerId = i; + handlerWrap = item[1]; + return true; + } + }); + if (handlerId !== -1) { + typeCache.splice(handlerId, 1); + } + return handlerWrap; + } else { + /* 未指定 handler 则清除type对应的所有监听 */ + typeCache.length = 0; + } +} + +/** + * @class CustEvent + * @description + * Event 自定义事件类 + * 1. 可以使用不传参得到的实例作为eventBus使用 + * 2. 可以通过指定target,用多个实例操作同一target对象的事件管理 + * 3. 当设定target时,可以通过设置assign为true,来给target实现"on\once\off\emit"方法 + * @param {Object} target 发生事件的对象(空则默认为event实例) + * @param {Boolean} assign 是否将"on\once\off\emit"方法实现到target对象上 + * @return {event} + */ +var CustEvent = function () { + function CustEvent(target, assign$$1) { + var _this = this; + + _classCallCheck(this, CustEvent); + + /* 设置__target不可枚举 */ + Object.defineProperty(this, '__target', { + writable: true, + enumerable: false, + configurable: true + }); + this.__target = this; + + if (target) { + + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') { + throw new Error('CusEvent target are not object'); + } + this.__target = target; + + /* 为target实现on\once\off\emit */ + if (assign$$1) { + ['on', 'once', 'off', 'emit'].forEach(function (mth) { + target[mth] = _this[mth]; + }); + } + } + } + + /** + * 添加事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + + _createClass(CustEvent, [{ + key: 'on', + value: function on(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + addEventCache(this.__target, type, handler, isOnce); + return this; + } + + /** + * 添加事件监听,并且只执行一次 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {event} + */ + + }, { + key: 'once', + value: function once(type, handler) { + return this.on(type, handler, true); + } + + /** + * 移除事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数(不指定handler则清除type对应的所有事件监听) + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + }, { + key: 'off', + value: function off(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + removeEventCache(this.__target, type, handler, isOnce); + return this; + } + + /** + * 触发事件监听函数 + * @param {String} type 事件类型 + * @return {event} + */ + + }, { + key: 'emit', + value: function emit(type, data) { + emitEventCache(this.__target, type, { data: data }); + return this; + } + }]); + + return CustEvent; +}(); + +exports.emitEventCache = emitEventCache; +exports.addEventCache = addEventCache; +exports.removeEventCache = removeEventCache; +exports.CustEvent = CustEvent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var ERRORNO = exports.ERRORNO = { + NET_ERROR: 100, + CODEC_ERROR: 101, + CANNOT_SEEK: 102, + ENDOFSTREAM_ERROR: 103, + MEDIASOURCE_ERROR: 104, + SOURCEBUFFER_ERROR: 105, + SBABORT_ERROR: 106, + APPENDBUFFER_ERROR: 107 +}; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * chimee-helper-log v0.1.2 + * (c) 2017 toxic-johann + * Released under MIT + */ + +(function (global, factory) { + module.exports = factory(); +}(this, (function () { +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 classCallCheck = createCommonjsModule$$1(function (module, exports) { + +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$$1(classCallCheck); + +var _global = createCommonjsModule$$1(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef +}); + +var _core = createCommonjsModule$$1(function (module) { +var core = module.exports = { version: '2.5.0' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef +}); + +var _aFunction = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx = function (fn, that, length) { + _aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +var _isObject = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject = function (it) { + if (!_isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors = !_fails(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +var document = _global.document; +// typeof document.createElement is 'object' in old IE +var is = _isObject(document) && _isObject(document.createElement); +var _domCreate = function (it) { + return is ? document.createElement(it) : {}; +}; + +var _ie8DomDefine = !_descriptors && !_fails(function () { + return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive = function (it, S) { + if (!_isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP = Object.defineProperty; + +var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject(O); + P = _toPrimitive(P, true); + _anObject(Attributes); + if (_ie8DomDefine) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +var _objectDp = { + f: f +}; + +var _propertyDesc = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +var _hide = _descriptors ? function (object, key, value) { + return _objectDp.f(object, key, _propertyDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? _ctx(out, _global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) _hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +var _export = $export; + +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +_export(_export.S + _export.F * !_descriptors, 'Object', { defineProperty: _objectDp.f }); + +var $Object = _core.Object; +var defineProperty$2 = function defineProperty(it, key, desc) { + return $Object.defineProperty(it, key, desc); +}; + +var defineProperty = createCommonjsModule$$1(function (module) { +module.exports = { "default": defineProperty$2, __esModule: true }; +}); + +var createClass = createCommonjsModule$$1(function (module, exports) { + +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$$1(createClass); + +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +var _toInteger = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +// 7.2.1 RequireObjectCoercible(argument) +var _defined = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +// true -> String#at +// false -> String#codePointAt +var _stringAt = function (TO_STRING) { + return function (that, pos) { + var s = String(_defined(that)); + var i = _toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +var _library = true; + +var _redefine = _hide; + +var hasOwnProperty = {}.hasOwnProperty; +var _has = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +var toString = {}.toString; + +var _cof = function (it) { + return toString.call(it).slice(8, -1); +}; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings + +// eslint-disable-next-line no-prototype-builtins +var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return _cof(it) == 'String' ? it.split('') : Object(it); +}; + +// to indexed object, toObject with fallback for non-array-like ES3 strings + + +var _toIobject = function (it) { + return _iobject(_defined(it)); +}; + +// 7.1.15 ToLength + +var min = Math.min; +var _toLength = function (it) { + return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +var max = Math.max; +var min$1 = Math.min; +var _toAbsoluteIndex = function (index, length) { + index = _toInteger(index); + return index < 0 ? max(index + length, 0) : min$1(index, length); +}; + +// false -> Array#indexOf +// true -> Array#includes + + + +var _arrayIncludes = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = _toIobject($this); + var length = _toLength(O.length); + var index = _toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +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 _objectKeysInternal = function (object, names) { + var O = _toIobject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO$1) _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); + } + return result; +}; + +// IE 8- don't enum bug keys +var _enumBugKeys = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) + + + +var _objectKeys = Object.keys || function keys(O) { + return _objectKeysInternal(O, _enumBugKeys); +}; + +var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties) { + _anObject(O); + var keys = _objectKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) _objectDp.f(O, P = keys[i++], Properties[P]); + return O; +}; + +var document$1 = _global.document; +var _html = document$1 && document$1.documentElement; + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + + + +var IE_PROTO = _sharedKey('IE_PROTO'); +var Empty = function () { /* empty */ }; +var PROTOTYPE$1 = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = _domCreate('iframe'); + var i = _enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + _html.appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; + return createDict(); +}; + +var _objectCreate = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE$1] = _anObject(O); + result = new Empty(); + Empty[PROTOTYPE$1] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : _objectDps(result, Properties); +}; + +var _wks = createCommonjsModule$$1(function (module) { +var store = _shared('wks'); + +var Symbol = _global.Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); +}; + +$exports.store = store; +}); + +var def = _objectDp.f; + +var TAG = _wks('toStringTag'); + +var _setToStringTag = function (it, tag, stat) { + if (it && !_has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); +}; + +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_hide(IteratorPrototype, _wks('iterator'), function () { return this; }); + +var _iterCreate = function (Constructor, NAME, next) { + Constructor.prototype = _objectCreate(IteratorPrototype, { next: _propertyDesc(1, 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()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR = '@@iterator'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function () { return this; }; + +var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + _iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = _objectGpo($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + _setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!_library && !_has(IteratorPrototype, ITERATOR)) _hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!_library || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + _hide(proto, ITERATOR, $default); + } + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) _redefine(proto, key, methods[key]); + } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; + +var $at = _stringAt(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_iterDefine(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +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; + var kind = this._k; + var 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 TO_STRING_TAG = _wks('toStringTag'); + +var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i = 0; i < DOMIterables.length; i++) { + var NAME = DOMIterables[i]; + var Collection = _global[NAME]; + var proto = Collection && Collection.prototype; + if (proto && !proto[TO_STRING_TAG]) _hide(proto, TO_STRING_TAG, NAME); +} + +var f$1 = _wks; + +var _wksExt = { + f: f$1 +}; + +var iterator$2 = _wksExt.f('iterator'); + +var iterator = createCommonjsModule$$1(function (module) { +module.exports = { "default": iterator$2, __esModule: true }; +}); + +var _meta = createCommonjsModule$$1(function (module) { +var META = _uid('meta'); + + +var setDesc = _objectDp.f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !_fails(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!_isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; +}); + +var defineProperty$4 = _objectDp.f; +var _wksDefine = function (name) { + var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty$4($Symbol, name, { value: _wksExt.f(name) }); +}; + +var _keyof = function (object, el) { + var O = _toIobject(object); + var keys = _objectKeys(O); + var length = keys.length; + var index = 0; + var key; + while (length > index) if (O[key = keys[index++]] === el) return key; +}; + +var f$2 = Object.getOwnPropertySymbols; + +var _objectGops = { + f: f$2 +}; + +var f$3 = {}.propertyIsEnumerable; + +var _objectPie = { + f: f$3 +}; + +// all enumerable object keys, includes symbols + + + +var _enumKeys = function (it) { + var result = _objectKeys(it); + var getSymbols = _objectGops.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = _objectPie.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +// 7.2.2 IsArray(argument) + +var _isArray = Array.isArray || function isArray(arg) { + return _cof(arg) == 'Array'; +}; + +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + +var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); + +var f$5 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return _objectKeysInternal(O, hiddenKeys); +}; + +var _objectGopn = { + f: f$5 +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + +var gOPN$1 = _objectGopn.f; +var toString$1 = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return gOPN$1(it); + } catch (e) { + return windowNames.slice(); + } +}; + +var f$4 = function getOwnPropertyNames(it) { + return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN$1(_toIobject(it)); +}; + +var _objectGopnExt = { + f: f$4 +}; + +var gOPD$1 = Object.getOwnPropertyDescriptor; + +var f$6 = _descriptors ? gOPD$1 : function getOwnPropertyDescriptor(O, P) { + O = _toIobject(O); + P = _toPrimitive(P, true); + if (_ie8DomDefine) try { + return gOPD$1(O, P); + } catch (e) { /* empty */ } + if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]); +}; + +var _objectGopd = { + f: f$6 +}; + +// ECMAScript 6 symbols shim + + + + + +var META = _meta.KEY; + + + + + + + + + + + + + + + + + + + +var gOPD = _objectGopd.f; +var dP$1 = _objectDp.f; +var gOPN = _objectGopnExt.f; +var $Symbol = _global.Symbol; +var $JSON = _global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE$2 = 'prototype'; +var HIDDEN = _wks('_hidden'); +var TO_PRIMITIVE = _wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = _shared('symbol-registry'); +var AllSymbols = _shared('symbols'); +var OPSymbols = _shared('op-symbols'); +var ObjectProto$1 = Object[PROTOTYPE$2]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = _global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = _descriptors && _fails(function () { + return _objectCreate(dP$1({}, 'a', { + get: function () { return dP$1(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto$1, key); + if (protoDesc) delete ObjectProto$1[key]; + dP$1(it, key, D); + if (protoDesc && it !== ObjectProto$1) dP$1(ObjectProto$1, key, protoDesc); +} : dP$1; + +var wrap = function (tag) { + var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto$1) $defineProperty(OPSymbols, key, D); + _anObject(it); + key = _toPrimitive(key, true); + _anObject(D); + if (_has(AllSymbols, key)) { + if (!D.enumerable) { + if (!_has(it, HIDDEN)) dP$1(it, HIDDEN, _propertyDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (_has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _objectCreate(D, { enumerable: _propertyDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP$1(it, key, D); +}; +var $defineProperties = function defineProperties(it, P) { + _anObject(it); + var keys = _enumKeys(P = _toIobject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P) { + return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = _toPrimitive(key, true)); + if (this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return false; + return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = _toIobject(it); + key = _toPrimitive(key, true); + if (it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(_toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto$1; + var names = gOPN(IS_OP ? OPSymbols : _toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true)) result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto$1) $set.call(OPSymbols, value); + if (_has(this, HIDDEN) && _has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, _propertyDesc(1, value)); + }; + if (_descriptors && setter) setSymbolDesc(ObjectProto$1, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + _redefine($Symbol[PROTOTYPE$2], 'toString', function toString() { + return this._k; + }); + + _objectGopd.f = $getOwnPropertyDescriptor; + _objectDp.f = $defineProperty; + _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; + _objectPie.f = $propertyIsEnumerable; + _objectGops.f = $getOwnPropertySymbols; + + if (_descriptors && !_library) { + _redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + _wksExt.f = function (name) { + return wrap(_wks(name)); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE, { Symbol: $Symbol }); + +for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j = 0; es6Symbols.length > j;)_wks(es6Symbols[j++]); + +for (var wellKnownSymbols = _objectKeys(_wks.store), k = 0; wellKnownSymbols.length > k;) _wksDefine(wellKnownSymbols[k++]); + +_export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return _has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(key) { + if (isSymbol(key)) return _keyof(SymbolRegistry, key); + throw TypeError(key + ' is not a symbol!'); + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } +}); + +_export(_export.S + _export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + if (it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + replacer = args[1]; + if (typeof replacer == 'function') $replacer = replacer; + if ($replacer || !_isArray(replacer)) replacer = function (key, value) { + if ($replacer) value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +_setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +_setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +_setToStringTag(_global.JSON, 'JSON', true); + +_wksDefine('asyncIterator'); + +_wksDefine('observable'); + +var index = _core.Symbol; + +var symbol = createCommonjsModule$$1(function (module) { +module.exports = { "default": index, __esModule: true }; +}); + +var _typeof_1 = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _iterator2 = _interopRequireDefault(iterator); + + + +var _symbol2 = _interopRequireDefault(symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +}); + +var _typeof = unwrapExports$$1(_typeof_1); + +// most Object methods by ES6 should accept primitives + + + +var _objectSap = function (KEY, exec) { + var fn = (_core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp); +}; + +// 19.1.2.14 Object.keys(O) + + + +_objectSap('keys', function () { + return function keys(it) { + return _objectKeys(_toObject(it)); + }; +}); + +var keys$1 = _core.Object.keys; + +var keys = createCommonjsModule$$1(function (module) { +module.exports = { "default": keys$1, __esModule: true }; +}); + +// 20.1.2.3 Number.isInteger(number) + +var floor$1 = Math.floor; +var _isInteger = function isInteger(it) { + return !_isObject(it) && isFinite(it) && floor$1(it) === it; +}; + +// 20.1.2.3 Number.isInteger(number) + + +_export(_export.S, 'Number', { isInteger: _isInteger }); + +var isInteger$2 = _core.Number.isInteger; + +var isInteger$1 = createCommonjsModule$$1(function (module) { +module.exports = { "default": isInteger$2, __esModule: true }; +}); + +var _stringWs = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +var space = '[' + _stringWs + ']'; +var non = '\u200b\u0085'; +var ltrim = RegExp('^' + space + space + '*'); +var rtrim = RegExp(space + space + '*$'); + +var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = _fails(function () { + return !!_stringWs[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : _stringWs[KEY]; + if (ALIAS) exp[ALIAS] = fn; + _export(_export.P + _export.F * FORCE, 'String', exp); +}; + +// 1 -> String#trimLeft +// 2 -> String#trimRight +// 3 -> String#trim +var trim = exporter.trim = function (string, TYPE) { + string = String(_defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; +}; + +var _stringTrim = exporter; + +var $parseFloat = _global.parseFloat; +var $trim = _stringTrim.trim; + +var _parseFloat$3 = 1 / $parseFloat(_stringWs + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; +} : $parseFloat; + +// 20.1.2.12 Number.parseFloat(string) +_export(_export.S + _export.F * (Number.parseFloat != _parseFloat$3), 'Number', { parseFloat: _parseFloat$3 }); + +var _parseFloat$1 = parseFloat; + +var _parseFloat = createCommonjsModule$$1(function (module) { +module.exports = { "default": _parseFloat$1, __esModule: true }; +}); + +/** + * toxic-predicate-functions v0.1.2 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** + * 判断是否是string + * @param {Anything} str [description] + * @return {Boolean} [description] + */ +function isString(str) { + return typeof str === 'string' || str instanceof String; +} + +function formatter(tag, msg) { + if (!isString(tag)) throw new TypeError('Log\'s method only acccept string as argument, but not ' + tag + ' in ' + (typeof tag === 'undefined' ? 'undefined' : _typeof(tag))); + if (!isString(msg)) return '[' + Log.GLOBAL_TAG + '] > ' + tag; + tag = Log.FORCE_GLOBAL_TAG ? Log.GLOBAL_TAG : tag || Log.GLOBAL_TAG; + return '[' + tag + '] > ' + msg; +} +/** + * Log Object + */ + +var Log = function () { + function Log() { + _classCallCheck(this, Log); + } + + _createClass(Log, null, [{ + key: 'error', + + /** + * equal to console.error, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + value: function error(tag, msg) { + if (!Log.ENABLE_ERROR) { + return; + } + + (console.error || console.warn || console.log)(formatter(tag, msg)); + } + /** + * equal to console.info, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {string} + */ + + }, { + key: 'info', + value: function info(tag, msg) { + if (!Log.ENABLE_INFO) { + return; + } + (console.info || console.log)(formatter(tag, msg)); + } + /** + * equal to console.warn, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'warn', + value: function warn(tag, msg) { + if (!Log.ENABLE_WARN) { + return; + } + (console.warn || console.log)(formatter(tag, msg)); + } + /** + * equal to console.debug, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'debug', + value: function debug(tag, msg) { + if (!Log.ENABLE_DEBUG) { + return; + } + (console.debug || console.log)(formatter(tag, msg)); + } + /** + * equal to console.verbose, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'verbose', + value: function verbose(tag, msg) { + if (!Log.ENABLE_VERBOSE) { + return; + } + console.log(formatter(tag, msg)); + } + }]); + + return Log; +}(); + +Log.GLOBAL_TAG = 'chimee'; +Log.FORCE_GLOBAL_TAG = false; +Log.ENABLE_ERROR = true; +Log.ENABLE_INFO = true; +Log.ENABLE_WARN = true; +Log.ENABLE_DEBUG = true; +Log.ENABLE_VERBOSE = true; + +return Log; + +}))); + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _fetch = __webpack_require__(10); + +var _fetch2 = _interopRequireDefault(_fetch); + +var _xhrRange = __webpack_require__(12); + +var _xhrRange2 = _interopRequireDefault(_xhrRange); + +var _websocket = __webpack_require__(13); + +var _websocket2 = _interopRequireDefault(_websocket); + +var _xhrMozChunk = __webpack_require__(14); + +var _xhrMozChunk2 = _interopRequireDefault(_xhrMozChunk); + +var _chimeeHelperEvents = __webpack_require__(0); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } /** + * 处理range的静态函数 + * author songguangyu + * email 522963130@qq.com + */ + +/** + * Ioloader 处理io的调用器 缓存多余数据 + * @class Ioloader + * @param {object} video config + */ +var Ioloader = function (_CustEvent) { + _inherits(Ioloader, _CustEvent); + + function Ioloader(config) { + _classCallCheck(this, Ioloader); + + var _this = _possibleConstructorReturn(this, (Ioloader.__proto__ || Object.getPrototypeOf(Ioloader)).call(this)); + + _this.loader = null; + _this.config = {}; + _this.config = config || {}; + _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 = _this.config.stashSize || 1024 * 384; + _this.resumeFrom = 0; + _this.currentRange = {}; + _this.totalReceive = 0; + _this.seekPonit = undefined; + _this.timer = null; + _this.heartBeatInterval = null; + _this.preTotalReceive = 0; + _this.seekLock = false; + _this.webSocketURLReg = /wss?:\/\/(.+?)/; + _this.selectLoader(); + _this.bindEvent(); + return _this; + } + + /** + * 自动选择io处理器 + */ + + + _createClass(Ioloader, [{ + key: 'selectLoader', + value: function selectLoader() { + var config = this.config; + var url = this.config.src; + if (this.webSocketURLReg.test(url)) { + this.loader = new _websocket2.default(url, config, this.queryHandle); + } else if (_fetch2.default.isSupport()) { + this.loader = new _fetch2.default(url, config, this.queryHandle); + } else if (_xhrMozChunk2.default.isSupport()) { + this.loader = new _xhrMozChunk2.default(url, config, this.queryHandle); + } else if (_xhrRange2.default.isSupport()) { + this.loader = new _xhrRange2.default(url, config, this.queryHandle); + } + this.loader.arrivalDataCallback = this.onLoaderChunkArrival.bind(this); + } + /** + * 绑定事件 + */ + + }, { + key: 'bindEvent', + value: function bindEvent() { + var _this2 = this; + + this.loader.on('end', function () { + var buffer = _this2.cacheBuffer.slice(0, _this2.cacheRemain); + _this2.arrivalDataCallback(buffer, _this2.stashByteStart); + _this2.emit('end'); + }); + this.loader.on('error', function (handle) { + _this2.emit('error', handle.data); + }); + } + /** + * 数据接收器 + * @param {arrayBuffer} chunk data + * @param {number} chunk byte postion + */ + + }, { + key: 'onLoaderChunkArrival', + value: function onLoaderChunkArrival(chunk, byteStart, keyframePoint) { + if (this.seekLock && keyframePoint === undefined) { + return; + } + if (keyframePoint !== undefined) { + this.seekPonit = keyframePoint; + this.seekLock = false; + } + 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) { + var buffer = this.cacheBuffer.slice(0, this.cacheRemain); + var consumed = 0; + if (this.seekPonit !== undefined) { + consumed = this.arrivalDataCallback(buffer, this.stashByteStart, this.seekPonit); + this.seekPonit = undefined; + } else { + consumed = this.arrivalDataCallback(buffer, this.stashByteStart); + } + + 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 { + var _consumed = 0; + if (this.seekPonit !== undefined) { + _consumed = this.arrivalDataCallback(chunk, byteStart, this.seekPonit); + this.seekPonit = undefined; + } 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; + } + } + } + } + } + /** + * 清空缓存buffer + */ + + }, { + key: 'initCacheBuffer', + value: function initCacheBuffer() { + this.cacheRemain = 0; + this.totalReceive = 0; + this.cacheBuffer = new ArrayBuffer(this.bufferSize); + } + + /** + * 动态扩展buffer存储器大小 + * @param {number} chunk byte size + */ + + }, { + key: 'expandBuffer', + value: function expandBuffer(expectedBytes) { + var bufferNewSize = this.bufferSize; + // while (bufferNewSize < expectedBytes) { + // bufferNewSize *= 2; + // } + if (bufferNewSize < expectedBytes) { + bufferNewSize = expectedBytes; + } + this.cacheBuffer = new ArrayBuffer(bufferNewSize); + this.bufferSize = bufferNewSize; + } + + /** + * 暂停 + */ + + }, { + key: 'pause', + value: function pause() { + this.loader.pause(); + } + + /** + * 打开连接 + */ + + }, { + key: 'open', + value: function open(startBytes, keyframePoint) { + this.loader.open({ from: startBytes || 0, to: -1 }, keyframePoint); + this.heartbeat(); + } + + /** + * 心跳 + */ + + }, { + key: 'heartbeat', + value: function heartbeat() { + var _this3 = this; + + window.clearInterval(this.heartBeatInterval); + this.heartBeatInterval = setInterval(function () { + _this3.emit('heartbeat', { + speed: _this3.totalReceive - _this3.preTotalReceive, + totalReceive: _this3.totalReceive + }); + _this3.preTotalReceive = _this3.totalReceive; + }, 1000); + } + + /** + * 重新播放 + */ + + }, { + key: 'resume', + value: function resume() { + this.paused = false; + var bytes = this.totalReceive; + this.open(bytes); + } + + /** + * seek + */ + + }, { + key: 'seek', + value: function seek(bytes, dropCache, keyframePoint) { + this.seekLock = true; + this.totalReceive = bytes; + this.preTotalReceive = bytes; + this.initCacheBuffer(); + this.cacheRemain = 0; + this.stashByteStart = 0; + this.open(bytes, keyframePoint); + } + + /** + * destory + */ + + }, { + key: 'destroy', + value: function destroy() { + this.pause(); + this.initCacheBuffer(); + window.clearInterval(this.heartBeatInterval); + this.heartBeatInterval = null; + } + }]); + + return Ioloader; +}(_chimeeHelperEvents.CustEvent); + +exports.default = Ioloader; + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (range) { + var headers = {}; + var param = void 0; + + if (range.to !== -1) { + param = 'bytes=' + range.from.toString() + '-' + range.to.toString(); + } else { + param = 'bytes=' + range.from.toString() + '-'; + } + headers['Range'] = param; + + return { + headers: headers + }; +}; + +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_chimee_helper_events__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_chimee_helper_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_chimee_helper_events__); + +/** + * chimee-flv2fmp4 v0.3.5 + * (c) 2017 gaolingxiao@360.cn,332065255@qq.com + * Released under ISC + */ + + + +function unwrapExports$$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule$$1(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +// 7.2.1 RequireObjectCoercible(argument) +var _defined = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +// 7.1.13 ToObject(argument) + +var _toObject = function (it) { + return Object(_defined(it)); +}; + +var hasOwnProperty = {}.hasOwnProperty; +var _has = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +var _global = createCommonjsModule$$1(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef +}); + +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; +}; + +var _core = createCommonjsModule$$1(function (module) { +var core = module.exports = { version: '2.5.1' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef +}); + +var _aFunction = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx = function (fn, that, length) { + _aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +var _isObject = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject = function (it) { + if (!_isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors = !_fails(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +var document = _global.document; +// typeof document.createElement is 'object' in old IE +var is = _isObject(document) && _isObject(document.createElement); +var _domCreate = function (it) { + return is ? document.createElement(it) : {}; +}; + +var _ie8DomDefine = !_descriptors && !_fails(function () { + return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive = function (it, S) { + if (!_isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP = Object.defineProperty; + +var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject(O); + P = _toPrimitive(P, true); + _anObject(Attributes); + if (_ie8DomDefine) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +var _objectDp = { + f: f +}; + +var _propertyDesc = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +var _hide = _descriptors ? function (object, key, value) { + return _objectDp.f(object, key, _propertyDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? _ctx(out, _global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) _hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +var _export = $export; + +// most Object methods by ES6 should accept primitives + + + +var _objectSap = function (KEY, exec) { + var fn = (_core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp); +}; + +// 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$$1(function (module) { +module.exports = { "default": getPrototypeOf$1, __esModule: true }; +}); + +var _Object$getPrototypeOf = unwrapExports$$1(getPrototypeOf); + +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +var _toInteger = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +// true -> String#at +// false -> String#codePointAt +var _stringAt = function (TO_STRING) { + return function (that, pos) { + var s = String(_defined(that)); + var i = _toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +var _library = true; + +var _redefine = _hide; + +var toString = {}.toString; + +var _cof = function (it) { + return toString.call(it).slice(8, -1); +}; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings + +// eslint-disable-next-line no-prototype-builtins +var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return _cof(it) == 'String' ? it.split('') : Object(it); +}; + +// to indexed object, toObject with fallback for non-array-like ES3 strings + + +var _toIobject = function (it) { + return _iobject(_defined(it)); +}; + +// 7.1.15 ToLength + +var min = Math.min; +var _toLength = function (it) { + return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +var max = Math.max; +var min$1 = Math.min; +var _toAbsoluteIndex = function (index, length) { + index = _toInteger(index); + return index < 0 ? max(index + length, 0) : min$1(index, length); +}; + +// false -> Array#indexOf +// true -> Array#includes + + + +var _arrayIncludes = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = _toIobject($this); + var length = _toLength(O.length); + var index = _toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +var arrayIndexOf = _arrayIncludes(false); +var IE_PROTO$2 = _sharedKey('IE_PROTO'); + +var _objectKeysInternal = function (object, names) { + var O = _toIobject(object); + var i = 0; + var result = []; + var 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); + } + return result; +}; + +// IE 8- don't enum bug keys +var _enumBugKeys = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) + + + +var _objectKeys = Object.keys || function keys(O) { + return _objectKeysInternal(O, _enumBugKeys); +}; + +var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties) { + _anObject(O); + var keys = _objectKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) _objectDp.f(O, P = keys[i++], Properties[P]); + return O; +}; + +var document$1 = _global.document; +var _html = document$1 && document$1.documentElement; + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + + + +var IE_PROTO$1 = _sharedKey('IE_PROTO'); +var Empty = function () { /* empty */ }; +var PROTOTYPE$1 = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = _domCreate('iframe'); + var i = _enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + _html.appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; + return createDict(); +}; + +var _objectCreate = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE$1] = _anObject(O); + result = new Empty(); + Empty[PROTOTYPE$1] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO$1] = O; + } else result = createDict(); + return Properties === undefined ? result : _objectDps(result, Properties); +}; + +var _wks = createCommonjsModule$$1(function (module) { +var store = _shared('wks'); + +var Symbol = _global.Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); +}; + +$exports.store = store; +}); + +var def = _objectDp.f; + +var TAG = _wks('toStringTag'); + +var _setToStringTag = function (it, tag, stat) { + if (it && !_has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); +}; + + + +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_hide(IteratorPrototype, _wks('iterator'), function () { return this; }); + +var _iterCreate = function (Constructor, NAME, next) { + Constructor.prototype = _objectCreate(IteratorPrototype, { next: _propertyDesc(1, next) }); + _setToStringTag(Constructor, NAME + ' Iterator'); +}; + + + + + + + + + +var ITERATOR = _wks('iterator'); +var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR = '@@iterator'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function () { return this; }; + +var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + _iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = _objectGpo($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + _setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!_library && !_has(IteratorPrototype, ITERATOR)) _hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!_library || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + _hide(proto, ITERATOR, $default); + } + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) _redefine(proto, key, methods[key]); + } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; +var $at = _stringAt(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_iterDefine(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +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; + var kind = this._k; + var 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 TO_STRING_TAG = _wks('toStringTag'); + +var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i = 0; i < DOMIterables.length; i++) { + var NAME = DOMIterables[i]; + var Collection = _global[NAME]; + var proto = Collection && Collection.prototype; + if (proto && !proto[TO_STRING_TAG]) _hide(proto, TO_STRING_TAG, NAME); +} + +var f$1 = _wks; + +var _wksExt = { + f: f$1 +}; + +var iterator$2 = _wksExt.f('iterator'); + +var iterator = createCommonjsModule$$1(function (module) { +module.exports = { "default": iterator$2, __esModule: true }; +}); + +unwrapExports$$1(iterator); + +var _meta = createCommonjsModule$$1(function (module) { +var META = _uid('meta'); + + +var setDesc = _objectDp.f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !_fails(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!_isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; +}); + +var defineProperty = _objectDp.f; +var _wksDefine = function (name) { + var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: _wksExt.f(name) }); +}; + +var f$2 = Object.getOwnPropertySymbols; + +var _objectGops = { + f: f$2 +}; + +var f$3 = {}.propertyIsEnumerable; + +var _objectPie = { + f: f$3 +}; + +// all enumerable object keys, includes symbols + + + +var _enumKeys = function (it) { + var result = _objectKeys(it); + var getSymbols = _objectGops.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = _objectPie.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +// 7.2.2 IsArray(argument) + +var _isArray = Array.isArray || function isArray(arg) { + return _cof(arg) == 'Array'; +}; + +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + +var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); + +var f$5 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return _objectKeysInternal(O, hiddenKeys); +}; + +var _objectGopn = { + f: f$5 +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + +var gOPN$1 = _objectGopn.f; +var toString$1 = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return gOPN$1(it); + } catch (e) { + return windowNames.slice(); + } +}; + +var f$4 = function getOwnPropertyNames(it) { + return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN$1(_toIobject(it)); +}; + +var _objectGopnExt = { + f: f$4 +}; + +var gOPD$1 = Object.getOwnPropertyDescriptor; + +var f$6 = _descriptors ? gOPD$1 : function getOwnPropertyDescriptor(O, P) { + O = _toIobject(O); + P = _toPrimitive(P, true); + if (_ie8DomDefine) try { + return gOPD$1(O, P); + } catch (e) { /* empty */ } + if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]); +}; + +var _objectGopd = { + f: f$6 +}; +// ECMAScript 6 symbols shim + + + + + +var META = _meta.KEY; + + + + + + + + + + + + + + + + + + +var gOPD = _objectGopd.f; +var dP$1 = _objectDp.f; +var gOPN = _objectGopnExt.f; +var $Symbol = _global.Symbol; +var $JSON = _global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE$2 = 'prototype'; +var HIDDEN = _wks('_hidden'); +var TO_PRIMITIVE = _wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = _shared('symbol-registry'); +var AllSymbols = _shared('symbols'); +var OPSymbols = _shared('op-symbols'); +var ObjectProto$1 = Object[PROTOTYPE$2]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = _global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = _descriptors && _fails(function () { + return _objectCreate(dP$1({}, 'a', { + get: function () { return dP$1(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto$1, key); + if (protoDesc) delete ObjectProto$1[key]; + dP$1(it, key, D); + if (protoDesc && it !== ObjectProto$1) dP$1(ObjectProto$1, key, protoDesc); +} : dP$1; + +var wrap = function (tag) { + var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto$1) $defineProperty(OPSymbols, key, D); + _anObject(it); + key = _toPrimitive(key, true); + _anObject(D); + if (_has(AllSymbols, key)) { + if (!D.enumerable) { + if (!_has(it, HIDDEN)) dP$1(it, HIDDEN, _propertyDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (_has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _objectCreate(D, { enumerable: _propertyDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP$1(it, key, D); +}; +var $defineProperties = function defineProperties(it, P) { + _anObject(it); + var keys = _enumKeys(P = _toIobject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P) { + return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = _toPrimitive(key, true)); + if (this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return false; + return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = _toIobject(it); + key = _toPrimitive(key, true); + if (it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(_toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto$1; + var names = gOPN(IS_OP ? OPSymbols : _toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true)) result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto$1) $set.call(OPSymbols, value); + if (_has(this, HIDDEN) && _has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, _propertyDesc(1, value)); + }; + if (_descriptors && setter) setSymbolDesc(ObjectProto$1, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + _redefine($Symbol[PROTOTYPE$2], 'toString', function toString() { + return this._k; + }); + + _objectGopd.f = $getOwnPropertyDescriptor; + _objectDp.f = $defineProperty; + _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; + _objectPie.f = $propertyIsEnumerable; + _objectGops.f = $getOwnPropertySymbols; + + if (_descriptors && !_library) { + _redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + _wksExt.f = function (name) { + return wrap(_wks(name)); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE, { Symbol: $Symbol }); + +for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j = 0; es6Symbols.length > j;)_wks(es6Symbols[j++]); + +for (var wellKnownSymbols = _objectKeys(_wks.store), k = 0; wellKnownSymbols.length > k;) _wksDefine(wellKnownSymbols[k++]); + +_export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return _has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } +}); + +_export(_export.S + _export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + if (it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + replacer = args[1]; + if (typeof replacer == 'function') $replacer = replacer; + if ($replacer || !_isArray(replacer)) replacer = function (key, value) { + if ($replacer) value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +_setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +_setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +_setToStringTag(_global.JSON, 'JSON', true); + +_wksDefine('asyncIterator'); + +_wksDefine('observable'); + +var symbol$2 = _core.Symbol; + +var symbol = createCommonjsModule$$1(function (module) { +module.exports = { "default": symbol$2, __esModule: true }; +}); + +unwrapExports$$1(symbol); + +var _typeof_1 = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _iterator2 = _interopRequireDefault(iterator); + + + +var _symbol2 = _interopRequireDefault(symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +}); + +var _typeof = unwrapExports$$1(_typeof_1); + +var possibleConstructorReturn = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _typeof3 = _interopRequireDefault(_typeof_1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +}); + +var _possibleConstructorReturn = unwrapExports$$1(possibleConstructorReturn); + +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ + + +var check = function (O, proto) { + _anObject(O); + if (!_isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); +}; +var _setProto = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = _ctx(Function.call, _objectGopd.f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check +}; + +// 19.1.3.19 Object.setPrototypeOf(O, proto) + +_export(_export.S, 'Object', { setPrototypeOf: _setProto.set }); + +var setPrototypeOf$2 = _core.Object.setPrototypeOf; + +var setPrototypeOf = createCommonjsModule$$1(function (module) { +module.exports = { "default": setPrototypeOf$2, __esModule: true }; +}); + +unwrapExports$$1(setPrototypeOf); + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +_export(_export.S, 'Object', { create: _objectCreate }); + +var $Object = _core.Object; +var create$2 = function create(P, D) { + return $Object.create(P, D); +}; + +var create = createCommonjsModule$$1(function (module) { +module.exports = { "default": create$2, __esModule: true }; +}); + +unwrapExports$$1(create); + +var inherits = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _setPrototypeOf2 = _interopRequireDefault(setPrototypeOf); + + + +var _create2 = _interopRequireDefault(create); + + + +var _typeof3 = _interopRequireDefault(_typeof_1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } + + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +}); + +var _inherits = unwrapExports$$1(inherits); +// 19.1.2.1 Object.assign(target, source, ...) + + + + + +var $assign = Object.assign; + +// should work with symbols and should have deterministic property order (V8 bug) +var _objectAssign = !$assign || _fails(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = _toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = _objectGops.f; + var isEnum = _objectPie.f; + while (aLen > index) { + var S = _iobject(arguments[index++]); + var keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; +} : $assign; + +// 19.1.3.1 Object.assign(target, source) + + +_export(_export.S + _export.F, 'Object', { assign: _objectAssign }); + +var assign$1 = _core.Object.assign; + +var assign = createCommonjsModule$$1(function (module) { +module.exports = { "default": assign$1, __esModule: true }; +}); + +var _Object$assign = unwrapExports$$1(assign); + +var classCallCheck = createCommonjsModule$$1(function (module, exports) { + +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$$1(classCallCheck); + +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +_export(_export.S + _export.F * !_descriptors, 'Object', { defineProperty: _objectDp.f }); + +var $Object$1 = _core.Object; +var defineProperty$3 = function defineProperty(it, key, desc) { + return $Object$1.defineProperty(it, key, desc); +}; + +var defineProperty$1 = createCommonjsModule$$1(function (module) { +module.exports = { "default": defineProperty$3, __esModule: true }; +}); + +unwrapExports$$1(defineProperty$1); + +var createClass = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty$1); + +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$$1(createClass); + +/* 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 = []; + this.size = -1; + } + + _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(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(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(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(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(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 <xqq@xqq.im> + * + * 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 <xqq@xqq.im> + * + * 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 = null; + +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(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(new Uint8Array(arrayBuffer, dataOffset + 2, length)); + } else { + str = ''; + } + return { + data: str, + size: 2 + length + }; + } + + /** + * 解析metadata + */ + + }, { + key: 'parseMetadata', + value: function parseMetadata(arr) { + 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 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 uint8 = new Uint8Array(arr); + var buffer = uint8.buffer; + var dv = new DataView(buffer, 0, dataSize); + var value = null; + 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) + if ((dv.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) { + + } + 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; + + 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 <xqq@xqq.im> + * + * 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$1 = 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$1(); + 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: 0, 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); + // console.log(this._mediaInfo, this._mediaInfo.isComplete()); + } + }, { + key: '_parseScriptData', + value: function _parseScriptData(obj) { + var scriptData = obj; + + if (scriptData.hasOwnProperty('onMetaData')) { + 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) { + if (this._onError) this._onError('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 { + this._onError('Flv: Invalid video packet type ' + packetType); + return; + } + } + + /** + * 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.config = config; + 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; + mi.meta = meta; + 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 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 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; + + 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 + '"'; + } + this._onTrackMetadata('audio', meta); + 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 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 + + } + + // 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; + } + } + }, { + key: 'hasAudio', + set: function set(s) { + this._mediaInfo.hasAudio = this._hasAudio = s; + } + }, { + key: 'hasVideo', + set: function set(s) { + this._mediaInfo.hasVideo = this._hasVideo = s; + } + }]); + + return 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; + this._dispose = false; + this.busy = false; + this.busyArr = []; + } + + /** + * 接受 外部的flv二进制数据 + */ + + + _createClass(FlvParse, [{ + key: 'setFlv', + value: function setFlv(uint8) { + // this.stop = true; + this.busy = true; + this._dispose = false; + 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; + this.busy = false; + return this.offset; + } else if (!this.frist) { + this.parse(); + return this.offset; + } 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: 'dispose', + value: function dispose() {} + /** + * 开始解析 + */ + + }, { + 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) { + if (this.arrTag.length == 0) this.arrTag.push(t);else { + // console.log('这是截获的自定义数据',t); + } + } + t.size = 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; +}(); + +/** + * 代码借鉴了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; +}(); + +/* + * 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 <xqq@xqq.im> + * + * 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 <xqq@xqq.im> + * + * 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]; + } + } + Browser = browser; + // Object.assign(Browser, browser); +} + +detect(); + +var Browser$1 = Browser; + +/* + * Copyright (C) 2016 Bilibili. All Rights Reserved. + * + * @author zheng qian <xqq@xqq.im> + * + * 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() { + 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 <xqq@xqq.im> + * + * 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. + */ + +// import Log from '../utils/logger.js'; +// Fragmented mp4 remuxer + +var MP4Remuxer$1 = function () { + function MP4Remuxer(config) { + _classCallCheck(this, MP4Remuxer); + + this.TAG = 'MP4Remuxer'; + + this._config = config; + this._isLive = config.isLive === true ? true : false; + + 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$1.chrome && (Browser$1.version.major < 50 || Browser$1.version.major === 50 && Browser$1.version.build < 2661) ? true : false; + + // 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$1.msedge || Browser$1.msie; + + // While only FireFox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ... + this._mp3UseMpegAudio = !Browser$1.firefox; + } + + _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 IllegalStateException('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; + + var container = 'mp4'; + var codec = metadata.codec; + + if (type === 'audio') { + this._audioMeta = metadata; + if (metadata.codec === 'mp3' && this._mp3UseMpegAudio) { + // 'audio/mpeg' for MP3 audio track + container = 'mpeg'; + codec = ''; + metabox = new Uint8Array(); + } else { + // 'audio/mp4, codecs="codec"' + metabox = MP4.generateInitSegment(metadata); + } + } else if (type === 'video') { + this._videoMeta = metadata; + metabox = MP4.generateInitSegment(metadata); + } else { + return; + } + + // dispatch metabox (Initialization Segment) + if (!this._onInitSegment) { + throw new IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!'); + } + this._onInitSegment(type, { + type: type, + data: metabox.buffer, + codec: codec, + container: type + '/' + container, + mediaDuration: metadata.duration // in timescale 1000 (milliseconds) + }); + } + }, { + 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) { + if (this._audioMeta == null) { + return; + } + + var track = audioTrack; + var samples = track.samples; + var dtsCorrection = undefined; + var firstDts = -1, + lastDts = -1; + var refSampleDuration = this._audioMeta.refSampleDuration; + + var mpegRawTrack = this._audioMeta.codec === 'mp3' && this._mp3UseMpegAudio; + var firstSegmentAfterSeek = this._dtsBaseInited && this._audioNextDts === undefined; + + var insertPrefixSilentFrame = false; + + if (!samples || samples.length <= 1) { + return; + } + + var offset = 0; + var mdatbox = null; + var mdatBytes = 0; + + // calculate initial mdat size + if (mpegRawTrack) { + // for raw mpeg buffer + offset = 0; + mdatBytes = track.length; + } else { + // for fmp4 mdat box + offset = 8; // size + type + mdatBytes = 8 + track.length; + } + + var firstSampleOriginalDts = samples[0].dts - this._dtsBase; + + // calculate dtsCorrection + if (this._audioNextDts) { + dtsCorrection = firstSampleOriginalDts - this._audioNextDts; + } else { + // this._audioNextDts == undefined + if (this._audioSegmentInfoList.isEmpty()) { + dtsCorrection = 0; + if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) { + if (this._audioMeta.originalCodec !== 'mp3') { + insertPrefixSilentFrame = true; + } + } + } else { + var lastSample = this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts); + if (lastSample != null) { + var distance = firstSampleOriginalDts - (lastSample.originalDts + lastSample.duration); + if (distance <= 3) { + distance = 0; + } + var expectedDts = lastSample.dts + lastSample.duration + distance; + dtsCorrection = firstSampleOriginalDts - expectedDts; + } else { + // lastSample == null, cannot found + dtsCorrection = 0; + } + } + } + + if (insertPrefixSilentFrame) { + // align audio segment beginDts to match with current video segment's beginDts + var firstSampleDts = firstSampleOriginalDts - dtsCorrection; + var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts); + if (videoSegment != null && videoSegment.beginDts < firstSampleDts) { + var silentUnit = AAC.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount); + if (silentUnit) { + var dts = videoSegment.beginDts; + var silentFrameDuration = firstSampleDts - videoSegment.beginDts; + Log.v(this.TAG, 'InsertPrefixSilentAudio: dts: ' + dts + ', duration: ' + silentFrameDuration); + samples.unshift({ unit: silentUnit, dts: dts, pts: dts }); + mdatBytes += silentUnit.byteLength; + } // silentUnit == null: Cannot generate, skip + } else { + insertPrefixSilentFrame = false; + } + } + + var mp4Samples = []; + dtsCorrection = 0; + + // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples + for (var i = 0; i + 1 < samples.length; i++) { + var sample = samples[i]; + var originalDts = sample.dts - this._dtsBase; + var _dts = originalDts - dtsCorrection; + + if (firstDts === -1) { + firstDts = _dts; + } + + var sampleDuration = 0; + + if (i !== samples.length - 1) { + var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection; + sampleDuration = nextDts - _dts; + } else { + // the last sample + 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 = Math.floor(refSampleDuration); + } + } + + var needFillSilentFrames = false; + var silentFrames = null; + + // // Silent frame generation, if large timestamp gap detected + // if (sampleDuration > refSampleDuration * 1.5 && this._audioMeta.codec !== 'mp3') { + // // We need to insert silent frames to fill timestamp gap + // needFillSilentFrames = true; + // let delta = Math.abs(sampleDuration - refSampleDuration); + // let frameCount = Math.ceil(delta / refSampleDuration); + // let currentDts = dts + refSampleDuration; // Notice: in float + + // // console.log(this.TAG, 'Large audio timestamp gap detected, may cause AV sync to drift. ' + + // // 'Silent frames will be generated to avoid unsync.\n' + + // // `dts: ${dts + sampleDuration} ms, expected: ${dts + Math.round(refSampleDuration)} ms, ` + + // // `delta: ${Math.round(delta)} ms, generate: ${frameCount} frames`); + + // let silentUnit = AAC.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount); + // if (silentUnit == null) { + // // console.log(this.TAG, 'Unable to generate silent frame for ' + + // // `${this._audioMeta.originalCodec} with ${this._audioMeta.channelCount} channels, repeat last frame`); + // // Repeat last frame + // silentUnit = unit; + // } + // silentFrames = []; + + // for (let j = 0; j < frameCount; j++) { + // let intDts = Math.round(currentDts); // round to integer + // if (silentFrames.length > 0) { + // // Set previous frame sample duration + // let previousFrame = silentFrames[silentFrames.length - 1]; + // previousFrame.duration = intDts - previousFrame.dts; + // } + // let frame = { + // dts: intDts, + // pts: intDts, + // cts: 0, + // unit: silentUnit, + // size: silentUnit.byteLength, + // duration: 0, // wait for next sample + // originalDts: originalDts, + // flags: { + // isLeading: 0, + // dependsOn: 1, + // isDependedOn: 0, + // hasRedundancy: 0 + // } + // }; + // silentFrames.push(frame); + // mdatBytes += unit.byteLength; + // currentDts += refSampleDuration; + // } + + // // last frame: align end time to next frame dts + // let lastFrame = silentFrames[silentFrames.length - 1]; + // lastFrame.duration = dts + sampleDuration - lastFrame.dts; + + // // silentFrames.forEach((frame) => { + // // Log.w(this.TAG, `SilentAudio: dts: ${frame.dts}, duration: ${frame.duration}`); + // // }); + + // // Set correct sample duration for current frame + // sampleDuration = Math.round(refSampleDuration); + // } + + mp4Samples.push({ + dts: _dts, + pts: _dts, + cts: 0, + unit: sample.unit, + size: sample.unit.byteLength, + duration: sampleDuration, + originalDts: originalDts, + flags: { + isLeading: 0, + dependsOn: 1, + isDependedOn: 0, + hasRedundancy: 0 + } + }); + + if (needFillSilentFrames) { + // Silent frames should be inserted after wrong-duration frame + mp4Samples.push.apply(mp4Samples, silentFrames); + } + } + + // allocate mdatbox + if (mpegRawTrack) { + // allocate for raw mpeg buffer + mdatbox = new Uint8Array(mdatBytes); + } else { + // allocate for fmp4 mdat box + var _mdatBytes = 8; // + videoTrack.length; + for (var _i = 0; _i < mp4Samples.length; ++_i) { + _mdatBytes += mp4Samples[_i].size; + } + + mdatbox = new Uint8Array(_mdatBytes); + // size field + mdatbox[0] = _mdatBytes >>> 24 & 0xFF; + mdatbox[1] = _mdatBytes >>> 16 & 0xFF; + mdatbox[2] = _mdatBytes >>> 8 & 0xFF; + mdatbox[3] = _mdatBytes & 0xFF; + // type field (fourCC) + mdatbox.set(MP4.types.mdat, 4); + } + + // Write samples into mdatbox + for (var _i2 = 0; _i2 < mp4Samples.length; _i2++) { + var _unit = mp4Samples[_i2].unit; + mdatbox.set(_unit, offset); + offset += _unit.byteLength; + } + + var latest = mp4Samples[mp4Samples.length - 1]; + lastDts = latest.dts + latest.duration; + // console.log(latest.dts,latest.originalDts); + // lastDts = latest.originalDts + latest.duration; + this._audioNextDts = lastDts; + // console.log('dtsCorrection',dtsCorrection,'firstSampleOriginalDts',firstSampleOriginalDts,'_dtsBase',this._dtsBase,'this._audioNextDts',this._audioNextDts,'latest.dts',latest.dts,latest.originalDts) + + // 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.sequenceNumber += track.addcoefficient; + var moofbox = null; + + if (mpegRawTrack) { + // Generate empty buffer, because useless for raw mpeg + moofbox = new Uint8Array(); + } else { + // Generate moof for fmp4 segment + moofbox = MP4.moof(track, firstDts); + } + + track.samples = [samples[samples.length - 1]]; + track.length = 0; + + var segment = { + type: 'audio', + data: this._mergeBoxes(moofbox, mdatbox).buffer, + sampleCount: mp4Samples.length, + info: info + }; + + if (mpegRawTrack && firstSegmentAfterSeek) { + // For MPEG audio stream in MSE, if seeking occurred, before appending new buffer + // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer. + segment.timestampOffset = firstDts; + } + + this._onMediaSegment('audio', segment); + } + }, { + key: '_remuxVideo', + value: function _remuxVideo(videoTrack) { + if (this._videoMeta == null) { + return; + } + + var track = videoTrack; + var samples = track.samples; + var dtsCorrection = undefined; + var firstDts = -1, + lastDts = -1; + var firstPts = -1, + lastPts = -1; + + if (!samples || samples.length <= 1) { + return; + } + + var firstSampleOriginalDts = samples[0].dts - this._dtsBase; + + // calculate dtsCorrection + if (this._videoNextDts) { + dtsCorrection = Math.max(firstSampleOriginalDts - this._videoNextDts, 0); + } else { + // this._videoNextDts == undefined + if (this._videoSegmentInfoList.isEmpty()) { + dtsCorrection = 0; + } else { + var lastSample = this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts); + if (lastSample != null) { + var distance = firstSampleOriginalDts - (lastSample.originalDts + lastSample.duration); + if (distance <= 3) { + distance = 0; + } + var expectedDts = lastSample.dts + lastSample.duration + distance; + dtsCorrection = firstSampleOriginalDts - expectedDts; + } else { + // lastSample == null, cannot found + dtsCorrection = 0; + } + } + } + + var info = new MediaSegmentInfo(); + var mp4Samples = []; + var firstFrameDtsCorrection = dtsCorrection; + dtsCorrection = 0; + + // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples + for (var i = 0; i + 1 < samples.length; i++) { + var sample = samples[i]; + var originalDts = sample.dts - this._dtsBase - (i == 0 ? firstFrameDtsCorrection : 0); + var isKeyframe = sample.isKeyframe; + var dts = originalDts - dtsCorrection; + var cts = sample.cts; + var pts = dts + cts; + + if (firstDts === -1) { + firstDts = dts; + firstPts = pts; + } + + var sampleDuration = 0; + + if (i !== samples.length - 1) { + var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection; + sampleDuration = nextDts - dts; + } else { + // the last sample + 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 = Math.floor(this._videoMeta.refSampleDuration); + } + } + + if (isKeyframe) { + var syncPoint = new SampleInfo(dts, pts, sampleDuration, sample.dts, true); + syncPoint.fileposition = sample.fileposition; + info.appendSyncPoint(syncPoint); + } + + mp4Samples.push({ + dts: dts, + pts: pts, + cts: cts, + units: sample.units, + size: sample.length, + isKeyframe: isKeyframe, + duration: sampleDuration, + originalDts: originalDts, + flags: { + isLeading: 0, + dependsOn: isKeyframe ? 2 : 1, + isDependedOn: isKeyframe ? 1 : 0, + hasRedundancy: 0, + isNonSync: isKeyframe ? 0 : 1 + } + }); + } + + var offset = 8; + var mdatBytes = 8; // + videoTrack.length; + for (var _i3 = 0; _i3 < mp4Samples.length; ++_i3) { + mdatBytes += mp4Samples[_i3].size; + } + var mdatbox = new Uint8Array(mdatBytes); + mdatbox[0] = mdatBytes >>> 24 & 0xFF; + mdatbox[1] = mdatBytes >>> 16 & 0xFF; + mdatbox[2] = mdatBytes >>> 8 & 0xFF; + mdatbox[3] = mdatBytes & 0xFF; + mdatbox.set(MP4.types.mdat, 4); + // Write samples into mdatbox + for (var _i4 = 0; _i4 < mp4Samples.length; _i4++) { + var units = mp4Samples[_i4].units; + while (units.length) { + var unit = units.shift(); + var data = unit.data; + mdatbox.set(data, offset); + offset += data.byteLength; + } + } + + var latest = mp4Samples[mp4Samples.length - 1]; + lastDts = latest.dts + latest.duration; + // lastDts = latest.originalDts + 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.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 = [samples[samples.length - 1]]; + 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); + + MP4.init(); + this._config = { _isLive: false }; + _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._tagdemux = new tagDemux(); + this._flvparse = new FlvParse(); + this.ftyp_moov_v = null; //双路视频 + this.ftyp_moov_a = 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; + + this._tagdemux._onTrackMetadata = this.Metadata.bind(this); + this._tagdemux._onMediaInfo = this.metaSucc.bind(this); + this._tagdemux._onDataAvailable = this.onDataAvailable.bind(this); + this._tagdemux._onError = this.error.bind(this); + this.m4mof = new MP4Remuxer$1(this._config); + this.m4mof.onMediaSegment = this.onMdiaSegment.bind(this); + } + + _createClass(flv2fmp4, [{ + key: 'seek', + value: function seek(baseTime) { + this._flvparse.dispose(); + this.setflvBase = this.setflvBasefrist; + if (baseTime == undefined || baseTime == 0) { + baseTime = 0; + this._pendingResolveSeekPoint = -1; + } + if (this._tempBaseTime != baseTime) { + this._tempBaseTime = baseTime; + this._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 = this._flvparse.setFlv(new Uint8Array(arraybuff)); + } catch (error) { + this.error(error); + } + if (this._flvparse.arrTag.length == 0) return offset; + // if(this._flvparse.arrTag[0].tagType!=18){ + // if(this.error)this.error(new Error('without metadata tag')); + // } + if (this._flvparse.arrTag.length > 0) { + this._tagdemux.hasAudio = this.hasAudio = this._flvparse._hasAudio; + this._tagdemux.hasVideo = this.hasVideo = this._flvparse._hasVideo; + + if (this._tempBaseTime != 0 && this._tempBaseTime == this._flvparse.arrTag[0].getTime()) { + this._tagdemux._timestampBase = 0; + } + try { + this._tagdemux.moofTag(this._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 = this._flvparse.setFlv(new Uint8Array(arraybuff)); + } catch (error) { + this.error(error); + } + if (this._flvparse.arrTag.length > 0) { + try { + this._tagdemux.moofTag(this._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(track, 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(['video', meta]); + this.m4mof._videoMeta = meta; + if (this.hasVideo && !this.hasAudio) { + this.metaSucc(); + return; + } + break; + case 'audio': + this.metas.push(['audio', meta]); + this.m4mof._audioMeta = meta; + if (!this.hasVideo && this.hasAudio) { + this.metaSucc(); + return; + } + break; + } + if (this.hasVideo && this.hasAudio && this.m4mof._videoMeta && this.m4mof._audioMeta) { + this.metaSucc(); + } + } + + /** + * metadata解读成功后触发及第一个视频tag和第一个音频tag + * + * @param {any} mi + * @returns + * + * @memberof flv2fmp4 + */ + + }, { + key: 'metaSucc', + value: function metaSucc(mi) { + var _this = this; + + if (this.onMediaInfo && mi) { + + this.onMediaInfo(mi || this._tagdemux._mediaInfo, { hasAudio: this.hasAudio, hasVideo: this.hasVideo }); + } + // 获取ftyp和moov + if (this.metas.length == 0) { + this.metaSuccRun = true; + return; + } + if (mi) return; + if (this.metas.length > 1) { + // this.ftyp_moov_v= + this.metas.map(function (item) { + if (item[0] == 'video') { + _this.ftyp_moov_v = MP4.generateInitSegment([item[1]]); + } else { + _this.ftyp_moov_a = MP4.generateInitSegment([item[1]]); + } + }); + } else { + this.ftyp_moov = MP4.generateInitSegment([this.metas[0][1]]); + } + + if (this.onInitSegment && this.loadmetadata == false) { + + if (this.ftyp_moov) { + this.onInitSegment(this.ftyp_moov); + } else { + this.onInitSegment(this.ftyp_moov_v, this.ftyp_moov_a); + } + this.loadmetadata = true; + } + } + }, { + key: 'onDataAvailable', + value: function onDataAvailable(audiotrack, videotrack) { + // this.m4mof.remux(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 _this2 = _possibleConstructorReturn(this, (foreign.__proto__ || _Object$getPrototypeOf(foreign)).call(this)); + + _this2.f2m = new flv2fmp4(config); + _this2.f2m._error = _this2.error.bind(_this2); + // 外部方法赋值 + _this2._onInitSegment = null; + _this2._onMediaSegment = null; + _this2._onMediaInfo = null; + _this2._seekCallBack = null; + return _this2; + } + + _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; +}(__WEBPACK_IMPORTED_MODULE_0_chimee_helper_events__["CustEvent"]); + +/* harmony default export */ __webpack_exports__["default"] = (foreign); + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = __webpack_require__(7); + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _mseController = __webpack_require__(8); + +var _mseController2 = _interopRequireDefault(_mseController); + +var _transmuxer = __webpack_require__(9); + +var _transmuxer2 = _interopRequireDefault(_transmuxer); + +var _config = __webpack_require__(17); + +var _config2 = _interopRequireDefault(_config); + +var _chimeeHelper = __webpack_require__(18); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } + +/** + * flv controller + * @export + * @class Flv + */ +var Flv = function (_CustEvent) { + _inherits(Flv, _CustEvent); + + _createClass(Flv, null, [{ + key: 'isSupport', + value: function isSupport() { + var parser = new _chimeeHelper.UAParser(); + var info = parser.getBrowser(); + if (info.name === 'Safari' && parseInt(info.major) < 10) { + return false; + } + if (window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640020,mp4a.40.2"')) { + return true; + } else { + return false; + } + } + }, { + key: 'version', + get: function get() { + return "1.4.9"; + } + + /** + * flv Wrapper + * @param {any} wrap videoElement + * @param {any} option + * @class Flv + */ + + }]); + + 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.timer = null; + _this2.seekTimer = null; + _this2.config = (0, _chimeeHelper.deepAssign)({}, _config2.default, config); + _this2.requestSetTime = false; + _this2.throttle = null; + _this2.bindEvents(); + _this2.attachMedia(); + return _this2; + } + /** + * internal set currentTime + * @memberof Flv + */ + + + _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); + } + } + }); + } + + /** + * bind events + * @memberof Flv + */ + + }, { + key: 'bindEvents', + value: function bindEvents() { + var _this3 = this; + + if (this.video) { + this.video.addEventListener('canplay', function () { + if (_this3.config.isLive) { + _this3.video.play(); + } + if (_this3.config.lockInternalProperty) { + _this3.internalPropertyHandle(); + } + }); + } + } + + /** + * new mediaSource + * @memberof Flv + */ + + }, { + key: 'attachMedia', + value: function attachMedia() { + var _this4 = this; + + this.mediaSource = new _mseController2.default(this.video, this.config); + + this.mediaSource.on('error', function (errorMessage) { + _this4.emit('error', errorMessage.data); + if (_this4.transmuxer) { + _this4.transmuxer.pause(); + } + }); + this.mediaSource.on('bufferFull', function () { + _this4.pauseTransmuxer(); + }); + this.mediaSource.on('updateend', function () { + _this4.onmseUpdateEnd(); + }); + } + + /** + * load + * @param {string} video url + * @memberof Flv + */ + + }, { + key: 'load', + value: function load(src) { + if (src) { + this.config.src = src; + } + this.transmuxer = new _transmuxer2.default(this.mediaSource, this.config, this.globalEvent); + this.transmuxerEvent(this.transmuxer); + this.transmuxer.loadSource(); + } + }, { + key: 'transmuxerEvent', + value: function transmuxerEvent(transmuxer) { + var _this5 = this; + + var mediaSource = this.mediaSource; + transmuxer.on('mediaSegment', function (handle) { + mediaSource.emit('mediaSegment', handle.data); + }); + + transmuxer.on('mediaSegmentInit', function (handle) { + mediaSource.emit('mediaSegmentInit', handle.data); + }); + + transmuxer.on('error', function (errorMessage) { + _this5.emit('error', errorMessage.data); + transmuxer.pause(); + mediaSource.pause(); + }); + + transmuxer.on('end', function (handle) { + mediaSource.endOfStream(); + }); + + transmuxer.on('heartbeat', function (handle) { + _this5.emit('heartbeat', handle.data); + }); + + transmuxer.on('mediaInfo', function (mediaInfo) { + if (!_this5.mediaInfo) { + _this5.mediaInfo = mediaInfo; + _this5.emit('mediaInfo', mediaInfo.data); + mediaSource.init(mediaInfo.data); + _this5.video.src = URL.createObjectURL(mediaSource.mediaSource); + _this5.video.addEventListener('seeking', _this5._throttle.call(_this5)); + } + }); + } + }, { + key: '_throttle', + value: function _throttle() { + this.throttle = (0, _chimeeHelper.throttle)(this._seek.bind(this), 200, { leading: false }); + return this.throttle; + } + + /** + * seek in buffered + * @param {number} seek time + * @memberof Flv + */ + + }, { + 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; + } + + /** + * get current buffer end + * @memberof Flv + */ + + }, { + 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; + } + } + } + /** + * _seek + * @param {number} seek time + * @memberof Flv + */ + + }, { + key: '_seek', + value: function _seek(seconds) { + var _this6 = this; + + this.currentTimeLock = true; + var currentTime = (0, _chimeeHelper.isNumber)(seconds) && !isNaN(seconds) ? seconds : this.video.currentTime; + if (this.requestSetTime) { + this.requestSetTime = false; + this.currentTimeLock = false; + return; + } + if (this.isTimeinBuffered(currentTime)) { + if (this.config.alwaysSeekKeyframe) { + var nearlestkeyframe = this.transmuxer.getNearestKeyframe(Math.floor(currentTime * 1000)); + if (nearlestkeyframe) { + this.requestSetTime = true; + this.video.currentTime = nearlestkeyframe.keyframetime / 1000; + } + } + } else { + _chimeeHelper.Log.verbose(this.tag, 'do seek'); + this.transmuxer.pause(); + var _nearlestkeyframe = this.transmuxer.getNearestKeyframe(Math.floor(currentTime * 1000)); + currentTime = _nearlestkeyframe.keyframetime / 1000; + this.seekTimer = setTimeout(function () { + _this6.mediaSource.seek(currentTime); + _this6.transmuxer.seek(_nearlestkeyframe); + }, 100); + this.requestSetTime = true; + this.video.currentTime = currentTime; + window.clearInterval(this.timer); + this.timer = null; + } + this.currentTimeLock = false; + return currentTime; + } + + /** + * mediaSource updateend + * @memberof Flv + */ + + }, { + 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) { + _chimeeHelper.Log.verbose(this.tag, 'Maximum buffering duration exceeded, suspend transmuxing task'); + this.pauseTransmuxer(); + } + } + /** + * heartbeat + * @memberof Flv + */ + + }, { + 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; + _chimeeHelper.Log.verbose(this.tag, 'Continue loading from paused position'); + this.transmuxer.resume(); + this.mediaSource.resume(); + } + } + + /** + * pause transmuxer + * @memberof Flv + */ + + }, { + key: 'pauseTransmuxer', + value: function pauseTransmuxer() { + this.transmuxer.pause(); + this.mediaSource.pause(); + if (!this.timer) { + this.timer = setInterval(this.heartbeat.bind(this), 1000); + } + } + }, { + key: 'resume', + value: function resume() { + this._seek(0); + } + + /** + * destroy + * @memberof Flv + */ + + }, { + key: 'destroy', + value: function destroy() { + window.clearInterval(this.timer); + window.clearInterval(this.seekTimer); + this.video.removeEventListener('seeking', this.throttle); + if (this.video) { + URL.revokeObjectURL(this.video.src); + this.video.src = ''; + this.video.removeAttribute('src'); + if (this.transmuxer) { + this.transmuxer.pause(); + this.transmuxer.destroy(); + this.transmuxer = null; + } + if (this.mediaSource) { + this.mediaSource.destroy(); + this.mediaSource = null; + } + } + } + }, { + key: 'seek', + value: function seek(seconds) { + return this._seek(seconds); + } + }, { + key: 'play', + value: function play() { + return this.video.play(); + } + }, { + key: 'pause', + value: function pause() { + return this.video.pause(); + } + }, { + key: 'refresh', + value: function refresh() { + if (this.transmuxer && this.mediaSource) { + this._seek(0); + } else { + _chimeeHelper.Log.verbose(this.tag, 'transmuxer & mediaSource not ready'); + } + } + + /** + * stop stream load + * @memberof Flv + */ + + }, { + key: 'stopLoad', + value: function stopLoad() { + this.transmuxer && this.transmuxer.pause(); + this.mediaSource && this.mediaSource.pause(); + } + }]); + + return Flv; +}(_chimeeHelper.CustEvent); + +exports.default = Flv; + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _chimeeHelperEvents = __webpack_require__(0); + +var _chimeeHelperLog = __webpack_require__(2); + +var _chimeeHelperLog2 = _interopRequireDefault(_chimeeHelperLog); + +var _$const = __webpack_require__(1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } + +var MSEController = function (_CustEvent) { + _inherits(MSEController, _CustEvent); + + /** + * Mediasource 控制层 + * @class Mediasource + * @param {Element} videoElement + * @param {object} config + */ + 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.hasVideo = true; + _this.hasAudio = true; + _this.removeRangesList = { + video: [], + audio: [] + }; + _this.removeBucketing = false; + _this.timer = { + video: null, + audio: null + }; + _this.queue = { + video: [], + audio: [] + }; + _this.sourceBuffer = { + video: null, + audio: null + }; + _this.mimeCodec = { + video: null, + audio: null + }; + _this.sourceBufferEvent(); + _this.complete = false; + return _this; + } + + /** + * mediaSource init + * @param {Object} mediaInfo + */ + + + _createClass(MSEController, [{ + key: 'init', + value: function init(mediaInfo) { + if (this.mediaSource) { + _chimeeHelperLog2.default.Error(this.tag, 'MediaSource has been attached to an HTMLMediaElement!'); + this.emit('error', { errno: _$const.ERRORNO.MEDIASOURCE_ERROR, errmsg: 'MediaSource has been attached to an HTMLMediaElement!' }); + return; + } + + if (mediaInfo.hasAudio) { + this.mimeCodec['audio'] = 'audio/mp4; codecs="' + mediaInfo.audioCodec + '"'; + } else { + this.hasAudio = false; + } + if (mediaInfo.hasVideo) { + this.mimeCodec['video'] = 'video/mp4; codecs="' + mediaInfo.videoCodec + '"'; + } else { + this.hasVideo = false; + } + 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); + } + + /** + * mediaSource open + */ + + }, { + key: 'onSourceOpen', + value: function onSourceOpen() { + _chimeeHelperLog2.default.verbose(this.tag, 'MediaSource onSourceOpen'); + this.mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen); + if (this.hasAudio) { + this.addSourceBuffer('audio'); + } + if (this.hasVideo) { + this.addSourceBuffer('video'); + } + if (this.hasQueueList()) { + this.doUpdate(); + } + this.emit('source_open'); + } + + /** + * addSourceBuffer + * @param {String} tag type + */ + + }, { + key: 'addSourceBuffer', + value: function addSourceBuffer(type) { + var _this2 = this; + + this.sourceBuffer[type] = this.mediaSource.addSourceBuffer(this.mimeCodec[type]); + _chimeeHelperLog2.default.verbose(this.tag, 'add sourcebuffer ' + type); + var sb = this.sourceBuffer[type]; + sb.addEventListener('error', this.e.onSourceBufferError); + sb.addEventListener('abort', function () { + return _chimeeHelperLog2.default.verbose(_this2.tag, 'sourceBuffer: abort'); + }); + sb.addEventListener('updateend', function () { + if (!_this2.sourceBuffer) { + return; + } + if (_this2.hasRemoveList()) { + if (_this2.removeRangesList.video.length) { + _this2.cleanRangesList('video'); + } + if (_this2.removeRangesList.audio.length) { + _this2.cleanRangesList('audio'); + } + } else if (_this2.hasQueueList()) { + _this2.doUpdate(); + } else if (_this2.complete && !_this2.sourceBuffer[type].updating) { + _this2.endOfStream(); + } + _this2.emit('updateend'); + }); + } + }, { + key: 'hasRemoveList', + value: function hasRemoveList() { + return this.removeRangesList.video.length || this.removeRangesList.audio.length; + } + }, { + key: 'hasQueueList', + value: function hasQueueList() { + return this.queue.video.length || this.queue.audio.length; + } + + /** + * addSourceBuffer + */ + + }, { + key: 'doUpdate', + value: function doUpdate() { + for (var type in this.queue) { + if (this.queue[type].length > 0 && !this.sourceBuffer[type].updating) { + var data = this.queue[type].shift(); + this.appendBuffer(data, type); + } + } + } + + /** + * sourceBuffer event + */ + + }, { + key: 'sourceBufferEvent', + value: function sourceBufferEvent() { + var _this3 = this; + + this.on('mediaSegment', function (handler) { + var data = handler.data; + var type = data.type; + if (_this3.needCleanupSourceBuffer(type)) { + _this3.doCleanupSourceBuffer(type); + } + // if(!this.sourceBuffer[type] || (this.sourceBuffer[type].updating || this.queue[type].length > 0)) { + // this.queue[type].push(data.data); + // } else { + // this.appendBuffer(data.data, type); + // } + _this3.queue[type].push(data.data); + if (_this3.sourceBuffer[type] && !_this3.hasRemoveList()) { + _this3.doUpdate(); + } + }); + + this.on('mediaSegmentInit', function (handler) { + var data = handler.data; + var type = data.type; + // if (!this.sourceBuffer[type] || (this.sourceBuffer[type].updating || this.queue[type].length > 0)) { + // this.queue[type].push(data.data); + // } else { + // this.appendBuffer(data.data, type); + // } + _this3.queue[type].push(data.data); + }); + } + + /** + * need clean sourcebuffer + * @param {String} tag type + */ + + }, { + key: 'needCleanupSourceBuffer', + value: function needCleanupSourceBuffer(type) { + var currentTime = this.video.currentTime; + + // const sb = this.sourceBuffer[type]; + // const buffered = sb.buffered; + var buffered = this.video.buffered; + if (buffered.length >= 1) { + if (currentTime - buffered.start(0) >= this.config.autoCleanupMaxBackwardDuration) { + return true; + } + } + return false; + } + + /** + * clean buffer + * @param {String} tag type + */ + + }, { + key: 'doCleanupSourceBuffer', + value: function doCleanupSourceBuffer(type) { + var currentTime = this.video.currentTime; + var sb = this.sourceBuffer[type]; + 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[type].push({ start: start, end: removeEnd }); + } + } + } + if (doRemove && !this.sourceBuffer[type].updating) { + this.cleanRangesList(type); + } + } + + /** + * clean bufferlist + * @param {String} tag type + */ + + }, { + key: 'cleanRangesList', + value: function cleanRangesList(type) { + if (this.sourceBuffer[type].updating) { + return; + } + var sb = this.sourceBuffer[type]; + while (this.removeRangesList[type].length && !sb.updating) { + var ranges = this.removeRangesList[type].shift(); + sb.remove(ranges.start, ranges.end); + } + } + + /** + * appendBuffer + * @param {Object} data + * @param {String} tag type + */ + + }, { + key: 'appendBuffer', + value: function appendBuffer(data, type) { + if (!this.sourceBuffer[type]) { + return; + } + try { + this.sourceBuffer[type].appendBuffer(data.buffer); + } catch (e) { + this.queue[type].unshift(data); + if (e.code === 22) { + // chrome can cache about 350M + _chimeeHelperLog2.default.verbose(this.tag, 'MediaSource bufferFull'); + this.emit('bufferFull'); + } else { + // this.emit('error', {errno: ERRORNO.APPENDBUFFER_ERROR, errmsg: e}); + } + } + } + + /** + * sourcebuffer end + */ + + }, { + key: 'onSourceEnded', + value: function onSourceEnded() { + _chimeeHelperLog2.default.verbose(this.tag, 'MediaSource onSourceEnded'); + } + + /** + * sourcebuffer close + */ + + }, { + key: 'onSourceClose', + value: function onSourceClose() { + _chimeeHelperLog2.default.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); + } + } + + /** + * sourcebuffer error + * @param {Object} evnet + */ + + }, { + key: 'onSourceBufferError', + value: function onSourceBufferError(e) { + this.emit('error', { errnono: _$const.ERRORNO.SOURCEBUFFER_ERROR, errmsg: e }); + _chimeeHelperLog2.default.error(this.tag, 'SourceBuffer Error: ' + e); + } + + /** + * seek + */ + + }, { + key: 'seek', + value: function seek() { + for (var type in this.sourceBuffer) { + var sb = this.sourceBuffer[type]; + if (!sb) { + continue; + } + if (this.mediaSource.readyState === 'open') { + try { + sb.abort(); + } catch (e) { + this.emit('error', { errno: _$const.ERRORNO.SBABORT_ERROR, errmsg: e }); + _chimeeHelperLog2.default.error(this.tag, e.message); + } + } + this.queue[type] = []; + for (var i = 0; i < sb.buffered.length; i++) { + var start = sb.buffered.start(i); + var end = sb.buffered.end(i); + this.removeRangesList[type].push({ start: start, end: end }); + } + if (!sb.updating) { + this.cleanRangesList(type); + } + } + } + + /** + * resume + */ + + }, { + key: 'resume', + value: function resume() { + this.doUpdate(); + } + + /** + * pause + */ + + }, { + key: 'pause', + value: function pause() { + // this.endOfStream(); + } + }, { + key: 'endOfStream', + value: function endOfStream() { + if (this.mediaSource) { + var ms = this.mediaSource; + this.complete = true; + var sb = this.sourceBuffer; + if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) { + return; + } else { + if (ms.readyState === 'open') { + try { + ms.endOfStream(); + this.complete = false; + } catch (error) { + _chimeeHelperLog2.default.verbose(this.tag, error); + this.emit('error', { errno: _$const.ERRORNO.ENDOFSTREAM_ERROR, errmsg: error }); + } + } + } + } + } + + /** + * destroy + */ + + }, { + key: 'destroy', + value: function destroy() { + if (this.mediaSource) { + var ms = this.mediaSource; + // pending segments should be discard + this.queue = { + video: [], + audio: [] + }; + this.sourceBuffer = { + video: null, + audio: null + }; + this.mimeCodec = { + video: null, + audio: null + }; + // remove all sourcebuffers + var sb = this.sourceBuffer; + this.complete = false; + this.endOfStream(); + if (sb) { + if (ms.readyState !== 'closed') { + ms.removeSourceBuffer(sb); + sb.removeEventListener('error', this.e.onSourceBufferError); + sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd); + } + this.sourceBuffer = null; + } + ms.removeEventListener('sourceopen', this.e.onSourceOpen); + ms.removeEventListener('sourceended', this.e.onSourceEnded); + ms.removeEventListener('sourceclose', this.e.onSourceClose); + this.mediaSource = null; + } + } + }]); + + return MSEController; +}(_chimeeHelperEvents.CustEvent); + +exports.default = MSEController; + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _ioLoader = __webpack_require__(3); + +var _ioLoader2 = _interopRequireDefault(_ioLoader); + +var _chimeeHelperEvents = __webpack_require__(0); + +var _webworkifyWebpack = __webpack_require__(15); + +var _webworkifyWebpack2 = _interopRequireDefault(_webworkifyWebpack); + +var _chimeeFlv2fmp = __webpack_require__(5); + +var _chimeeFlv2fmp2 = _interopRequireDefault(_chimeeFlv2fmp); + +var _$const = __webpack_require__(1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } + +/** + * Transmuxer controller + * @class Transmuxer + * @param {mediaSource} mediaSource + * @param {object} config + */ +var Transmuxer = function (_CustEvent) { + _inherits(Transmuxer, _CustEvent); + + function Transmuxer(mediaSource, config, globalEvent) { + _classCallCheck(this, Transmuxer); + + var _this = _possibleConstructorReturn(this, (Transmuxer.__proto__ || Object.getPrototypeOf(Transmuxer)).call(this)); + + _this.config = config || {}; + _this.tag = 'transmuxer'; + _this.loader = null; + _this.CPU = null; + _this.keyframePoint = false; + _this.w = null; + if (_this.config.webWorker) { + _this.w = (0, _webworkifyWebpack2.default)(/*require.resolve*/(16)); + _this.w.addEventListener('message', function (e) { + _this.parseCallback.call(_this, e.data); + }); + _this.w.postMessage({ cmd: 'init', data: config }); + } + _this.lock = 0; + return _this; + } + /** + * instance ioloader + */ + + + _createClass(Transmuxer, [{ + key: 'loadSource', + value: function loadSource() { + if (this.config.webWorker) { + this.w.postMessage({ cmd: 'loadSource' }); + } else { + this.loader = new _ioLoader2.default(this.config); + this.loader.arrivalDataCallback = this.arrivalDataCallback.bind(this); + this.loader.open(); + this.loaderBindEvent(this.loader); + } + } + /** + * bindEvent + */ + + }, { + key: 'loaderBindEvent', + value: function loaderBindEvent(loader) { + var _this2 = this; + + loader.on('end', function () { + _this2.emit('end'); + }); + loader.on('error', function (handle) { + _this2.emit('error', handle.data); + }); + loader.on('heartbeat', function (handle) { + _this2.emit('heartbeat', handle.data); + }); + } + /** + * loader data callback + * @param {arraybuffer} data + * @param {number} bytestart + * @param {keyframePoint} keyframe + */ + + }, { + key: 'arrivalDataCallback', + value: function arrivalDataCallback(data, byteStart, keyframePoint) { + var _this3 = this; + + if (!this.CPU) { + this.config.isLive ? this.config._isLive = true : this.config._isLive = false; + this.CPU = new _chimeeFlv2fmp2.default(this.config); + this.CPU.onInitSegment = this.onRemuxerInitSegmentArrival.bind(this); + this.CPU.onMediaSegment = this.onRemuxerMediaSegmentArrival.bind(this); + this.CPU.onMediaInfo = this.onMediaInfo.bind(this); + this.CPU.on('error', function (handle) { + _this3.emit('error', { errno: _$const.ERRORNO.CODEC_ERROR, errmsg: handle.data }); + }); + } + if (keyframePoint !== undefined) { + this.CPU.seek(keyframePoint); + } + var consumed = this.CPU.setflv(data); + return consumed; + } + + /** + * loader data callback + * @param {arraybuffer} data + */ + + }, { + key: 'parseCallback', + value: function parseCallback(data) { + switch (data.cmd) { + case 'mediaSegmentInit': + this.emit('mediaSegmentInit', data.source); + break; + case 'mediaSegment': + this.emit('mediaSegment', data.source); + break; + case 'mediainfo': + this.mediaInfo = data.source; + this.emit('mediaInfo', data.source); + break; + case 'error': + this.emit('error', data.source); + break; + } + } + + /** + * Demux mediaInfo + * @param {object} video message info + */ + + }, { + key: 'onMediaInfo', + value: function onMediaInfo(mediaInfo) { + this.mediaInfo = mediaInfo; + this.emit('mediaInfo', mediaInfo); + } + + /** + * remuxer init segment arrival + * @param {arraybuffer} video data + */ + + }, { + key: 'onRemuxerInitSegmentArrival', + value: function onRemuxerInitSegmentArrival(video, audio) { + this.emit('mediaSegmentInit', { + type: 'video', + data: video + }); + if (audio) { + this.emit('mediaSegmentInit', { + type: 'audio', + data: audio + }); + } + } + + /** + * remuxer segment arrival + * @param {String} tag type + * @param {arraybuffer} video data + */ + + }, { + key: 'onRemuxerMediaSegmentArrival', + value: function onRemuxerMediaSegmentArrival(type, data) { + this.emit('mediaSegment', { type: type, data: data }); + } + + /** + * get video mediaInfo + */ + + }, { + key: 'getMediaInfo', + value: function getMediaInfo() { + return this.mediaInfo; + } + + /** + * stop loader + */ + + }, { + key: 'pause', + value: function pause() { + if (this.config.webWorker) { + this.w.postMessage({ cmd: 'pause' }); + } else { + this.loader.pause(); + } + } + + /** + * resume loader + */ + + }, { + key: 'resume', + value: function resume() { + if (this.config.webWorker) { + this.w.postMessage({ cmd: 'resume' }); + } else { + this.loader.resume(); + } + } + /** + * flv can seek + */ + + }, { + key: 'isSeekable', + value: function isSeekable() { + return this.mediaInfo.hasKeyframesIndex; + } + /** + * video seek + * @param {object} 关键帧集合 + */ + + }, { + key: 'seek', + value: function seek(keyframe) { + if (!this.isSeekable()) { + this.emit('error', { errno: _$const.ERRORNO.CANNOT_SEEK, errmsg: '这个flv视频不支持seek' }); + return false; + } + if (this.config.webWorker) { + this.w.postMessage({ cmd: 'seek', keyframe: keyframe }); + } else { + this.loader.seek(keyframe.keyframePoint, false, keyframe.keyframetime); + } + } + + /** + * destroy + */ + + }, { + key: 'destroy', + value: function destroy() { + if (this.config.webWorker) { + this.w.postMessage({ cmd: 'destroy' }); + } else { + this.loader.destroy(); + this.loader = null; + this.CPU = null; + } + } + + /** + * get nearlest keyframe binary search + * @param {Number} video time + */ + + }, { + key: 'getNearestKeyframe', + value: function getNearestKeyframe(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; +}(_chimeeHelperEvents.CustEvent); + +exports.default = Transmuxer; + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _handleQuery = __webpack_require__(11); + +var _handleQuery2 = _interopRequireDefault(_handleQuery); + +var _chimeeHelperEvents = __webpack_require__(0); + +var _chimeeHelperLog = __webpack_require__(2); + +var _chimeeHelperLog2 = _interopRequireDefault(_chimeeHelperLog); + +var _$const = __webpack_require__(1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } /** + * fetch firfox 直播 点播 + * author songguangyu + * email 522963130@qq.com + */ + + +/** + * FetchLoader + * @class FetchLoader + * @param {string} video url + * @param {object} range.from range.to + */ +var FetchLoader = function (_CustEvent) { + _inherits(FetchLoader, _CustEvent); + + _createClass(FetchLoader, null, [{ + key: 'isSupport', + + + /** + * broswer is support moz-chunk + */ + value: function isSupport() { + if (self.fetch && self.ReadableStream) { + return true; + } else { + return false; + } + } + }]); + + function FetchLoader(src, config) { + _classCallCheck(this, FetchLoader); + + var _this = _possibleConstructorReturn(this, (FetchLoader.__proto__ || Object.getPrototypeOf(FetchLoader)).call(this)); + + _this.tag = 'fetch'; + _this.fetching = false; + _this.config = config; + _this.range = { + from: 0, + to: 524288 + }; + _this.src = src; + _this.totalRange = null; + _this.block = 524288; + _this.reader = null; + _this.requestAbort = false; + _this.arrivalDataCallback = null; + _this.bytesStart = 0; + _this.heartbeat = null; + return _this; + } + /** + * if don't need range don't set + * @param {object} range.from range.to + */ + + + _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 }; + if (!this.config.isLive) { + this.range.from = r.from; + this.range.to = r.to; + var queryResult = (0, _handleQuery2.default)(r, this.config); + if (typeof queryResult === 'string') { + this.src = this.config.src + queryResult; + } else { + for (var i in queryResult) { + reqHeaders.append(i, queryResult[i]); + } + } + } + if (keyframePoint) { + this.bytesStart = 0; + } + this.bytesStart = range.from; + var params = { + method: 'GET', + headers: reqHeaders, + mode: 'cors', + cache: 'default', + referrerPolicy: 'no-referrer-when-downgrade' + }; + fetch(this.src, params).then(function (res) { + if (res.ok) { + var reader = res.body.getReader(); + return _this2.pump(reader, keyframePoint); + } + }).catch(function (e) { + _this2.emit('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: e }); + }); + } + + /** + * pause video + */ + + }, { + key: 'pause', + value: function pause() { + this.requestAbort = true; + } + + /** + * pump data + */ + + }, { + key: 'pump', + value: function pump(reader, keyframePoint) { + var _this3 = this; + + // ReadableStreamReader + return reader.read().then(function (result) { + if (result.done) { + _this3.emit('end'); + _chimeeHelperLog2.default.verbose(_this3.tag, 'load end'); + } else { + if (_this3.requestAbort === true) { + _this3.requestAbort = false; + 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); + } + }).catch(function (e) { + _this3.emit('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: e.message }); + }); + } + }]); + + return FetchLoader; +}(_chimeeHelperEvents.CustEvent); + +exports.default = FetchLoader; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (range, config) { + if (config.seekType === 'range') { + var headers = {}; + var param = void 0; + if (range.to !== -1) { + param = 'bytes=' + range.from.toString() + '-' + range.to.toString(); + } else { + param = 'bytes=' + range.from.toString() + '-'; + } + headers['Range'] = param; + return headers; + } else { + var _param = void 0; + if (range.to !== -1) { + _param = '?start=' + range.from.toString() + '&end=' + range.to.toString(); + } else { + _param = '?start=' + range.from.toString(); + } + return _param; + } +}; + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _handleRange = __webpack_require__(4); + +var _handleRange2 = _interopRequireDefault(_handleRange); + +var _chimeeHelperEvents = __webpack_require__(0); + +var _$const = __webpack_require__(1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } /** + * XHR 点播 + * author songguangyu + * email 522963130@qq.com + */ +// import Log from 'helper/log'; + + +/** + * MozChunkLoader + * @class MozChunkLoader + * @param {string} video url + * @param {object} range.from range.to + */ +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; + } + } + }]); + + 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 = 524288; + _this.range = {}; + _this.bytesStart = 0; + _this.needSeek = false; + _this.keyframePoint = null; + return _this; + } + /** + * if don't need range don't set + * @param {object} range.from range.to + */ + + + _createClass(RangeLoader, [{ + key: 'open', + value: function open(range, keyframePoint) { + 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; + if (r.to === -1) { + r.to = r.from + this.chunkSizeKB; + } + if (keyframePoint) { + this.bytesStart = range.from; + this.needSeek = true; + this.keyframePoint = keyframePoint; + } + this.range.to = r.to; + var headers = (0, _handleRange2.default)(r).headers; + for (var i in headers) { + xhr.setRequestHeader(i, headers[i]); + } + xhr.send(); + } + + /** + * pause + */ + + }, { + key: 'pause', + value: function pause() { + this.abort(); + } + /** + * abort request + */ + + }, { + key: 'abort', + value: function abort() { + if (this.xhr) { + 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('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: info }); + } + } + } + + /** + * xhr onProgress + */ + + }, { + key: 'onProgress', + value: function onProgress(e) { + if (!this.totalLength) { + this.totalLength = e.total; + this.abort(); + this.open(); + } + } + + /** + * xhr onLoad + */ + + }, { + key: 'onLoad', + value: function onLoad(e) { + if (!this.totalLength) { + return; + } + + if (this.arrivalDataCallback) { + var chunk = e.target.response; + if (this.needSeek) { + this.needSeek = false; + this.arrivalDataCallback(chunk, this.bytesStart, this.keyframePoint); + } else { + this.arrivalDataCallback(chunk, this.bytesStart); + } + this.bytesStart += chunk.byteLength; + this.open({ from: this.bytesStart, to: -1 }); + } + } + + /** + * 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('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: info }); + } + }]); + + return RangeLoader; +}(_chimeeHelperEvents.CustEvent); + +exports.default = RangeLoader; + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _chimeeHelperEvents = __webpack_require__(0); + +var _$const = __webpack_require__(1); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } + +var WebSocketLoader = function (_CustEvent) { + _inherits(WebSocketLoader, _CustEvent); + + _createClass(WebSocketLoader, null, [{ + key: 'isSupported', + value: function isSupported() { + try { + return typeof window.WebSocket !== 'undefined'; + } catch (e) { + return false; + } + } + }]); + + function WebSocketLoader(src, config) { + _classCallCheck(this, WebSocketLoader); + + var _this = _possibleConstructorReturn(this, (WebSocketLoader.__proto__ || Object.getPrototypeOf(WebSocketLoader)).call(this)); + + _this.tag = 'WebSocket'; + _this.src = src; + _this._ws = null; + _this._requestAbort = false; + _this._receivedLength = 0; + return _this; + } + + _createClass(WebSocketLoader, [{ + key: 'destroy', + value: function destroy() { + if (this._ws) { + this.abort(); + } + } + }, { + key: 'open', + value: function open(range, keyframePoint) { + try { + var ws = this._ws = new self.WebSocket(this.src); + ws.binaryType = 'arraybuffer'; + ws.onopen = this.onWebSocketOpen.bind(this); + ws.onclose = this.onWebSocketClose.bind(this); + ws.onmessage = this.onWebSocketMessage.bind(this); + ws.onerror = this.onWebSocketError.bind(this); + } catch (e) { + var info = { + code: e.code, + msg: e.message + }; + this.emit('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: info }); + } + } + }, { + key: 'abort', + value: function abort() { + var ws = this._ws; + if (ws && (ws.readyState === 0 || ws.readyState === 1)) { + this._requestAbort = true; + ws.close(); + } + + this._ws = null; + } + }, { + key: 'onWebSocketClose', + value: function onWebSocketClose(e) { + if (this._requestAbort === true) { + this._requestAbort = false; + return; + } + this.emit('end'); + } + }, { + key: 'onWebSocketOpen', + value: function onWebSocketOpen() {} + }, { + key: 'onWebSocketMessage', + value: function onWebSocketMessage(e) { + var _this2 = this; + + if (e.data instanceof ArrayBuffer) { + this.dispatchArrayBuffer(e.data); + } else if (e.data instanceof Blob) { + var reader = new FileReader(); + reader.onload = function () { + _this2.dispatchArrayBuffer(reader.result); + }; + reader.readAsArrayBuffer(e.data); + } else { + var info = { code: -1, msg: 'Unsupported WebSocket message type: ' + e.data.constructor.name }; + this.emit('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: info }); + } + } + }, { + key: 'dispatchArrayBuffer', + value: function dispatchArrayBuffer(arraybuffer) { + var chunk = arraybuffer; + var byteStart = this.receivedLength; + this.receivedLength += chunk.byteLength; + + if (this.arrivalDataCallback) { + this.arrivalDataCallback(chunk, byteStart); + } + } + }, { + key: 'onWebSocketError', + value: function onWebSocketError(e) { + var info = { + code: e.code, + msg: e.message + }; + this.emit('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: info }); + } + }]); + + return WebSocketLoader; +}(_chimeeHelperEvents.CustEvent); + +exports.default = WebSocketLoader; + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = 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 _handleRange = __webpack_require__(4); + +var _handleRange2 = _interopRequireDefault(_handleRange); + +var _chimeeHelperEvents = __webpack_require__(0); + +var _$const = __webpack_require__(1); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(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(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; } /** + * XHR firfox 直播 点播 + * author songguangyu + * email 522963130@qq.com + */ +// import Log from 'helper/log'; + + +/** + * MozChunkLoader + * @class MozChunkLoader + * @param {string} video url + * @param {object} range.from range.to + */ +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; + } + } + }]); + + 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; + _this.keyframePoint = null; + return _this; + } + /** + * if don't need range don't set + * @param {object} range.from range.to + */ + + + _createClass(MozChunkLoader, [{ + key: 'open', + value: function open(range, keyframePoint) { + 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.isLive) { + var r = range || { from: 0, to: -1 }; + this.range.from = r.from; + this.range.to = r.to; + if (keyframePoint) { + this.needSeek = true; + this.keyframePoint = keyframePoint; + } + var headers = (0, _handleRange2.default)(r).headers; + for (var i in headers) { + xhr.setRequestHeader(i, headers[i]); + } + } + xhr.send(); + } + + /** + * pause + */ + + }, { + key: 'pause', + value: function pause() { + this.abort(); + } + /** + * abort request + */ + + }, { + key: 'abort', + value: function abort() { + if (this.xhr) { + 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('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: 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; + if (this.needSeek) { + this.needSeek = false; + this.arrivalDataCallback(chunk, this.bytesStart, this.keyframePoint); + } else { + 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('error', { errno: _$const.ERRORNO.NET_ERROR, errmsg: info }); + } + }]); + + return MozChunkLoader; +}(_chimeeHelperEvents.CustEvent); + +exports.default = MozChunkLoader; + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +function webpackBootstrapFunc (modules) { +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.l = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; + +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; + +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; + +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // on error function for async loading +/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; + + var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE); + return f.default || f // try to call default if defined to also support babel esmodule exports +} + +var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'; +var dependencyRegExp = '\\((\/\\*.*?\\*\/)?\s?.*?(' + moduleNameReqExp + ').*?\\)'; // additional chars when output.pathinfo is true + +// http://stackoverflow.com/a/2593661/130442 +function quoteRegExp (str) { + return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') +} + +function getModuleDependencies (sources, module, queueName) { + var retval = {}; + retval[queueName] = []; + + var fnString = module.toString(); + var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/); + if (!wrapperSignature) return retval + var webpackRequireName = wrapperSignature[1]; + + // main bundle deps + var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g'); + var match; + while ((match = re.exec(fnString))) { + if (match[3] === 'dll-reference') continue + retval[queueName].push(match[3]); + } + + // dll deps + re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g'); + while ((match = re.exec(fnString))) { + if (!sources[match[2]]) { + retval[queueName].push(match[1]); + sources[match[2]] = __webpack_require__(match[1]).m; + } + retval[match[2]] = retval[match[2]] || []; + retval[match[2]].push(match[4]); + } + + return retval +} + +function hasValuesInQueues (queues) { + var keys = Object.keys(queues); + return keys.reduce(function (hasValues, key) { + return hasValues || queues[key].length > 0 + }, false) +} + +function getRequiredModules (sources, moduleId) { + var modulesQueue = { + main: [moduleId] + }; + var requiredModules = { + main: [] + }; + var seenModules = { + main: {} + }; + + while (hasValuesInQueues(modulesQueue)) { + var queues = Object.keys(modulesQueue); + for (var i = 0; i < queues.length; i++) { + var queueName = queues[i]; + var queue = modulesQueue[queueName]; + var moduleToCheck = queue.pop(); + seenModules[queueName] = seenModules[queueName] || {}; + if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue + seenModules[queueName][moduleToCheck] = true; + requiredModules[queueName] = requiredModules[queueName] || []; + requiredModules[queueName].push(moduleToCheck); + var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName); + var newModulesKeys = Object.keys(newModules); + for (var j = 0; j < newModulesKeys.length; j++) { + modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []; + modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]); + } + } + } + + return requiredModules +} + +module.exports = function (moduleId, options) { + options = options || {}; + var sources = { + main: __webpack_require__.m + }; + + var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId); + + var src = ''; + + Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) { + var entryModule = 0; + while (requiredModules[module][entryModule]) { + entryModule++; + } + requiredModules[module].push(entryModule); + sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'; + src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'; + }); + + src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '})(self);'; + + var blob = new window.Blob([src], { type: 'text/javascript' }); + if (options.bare) { return blob } + + var URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + var workerUrl = URL.createObjectURL(blob); + var worker = new window.Worker(workerUrl); + worker.objectURL = workerUrl; + + return worker +}; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (ctx) { + var CPU = null; + var loader = null; + var config = {}; + ctx.addEventListener('message', function (e) { + switch (e.data.cmd) { + case 'init': + config = e.data.data; + break; + case 'loadSource': + loader = new _ioLoader2.default(config); + loader.arrivalDataCallback = arrivalDataCallbackWorker; + loader.open(); + break; + case 'pause': + loader.pause(); + break; + case 'seek': + seek(e.data.keyframe); + break; + case 'resume': + loader.resume(); + break; + case 'destroy': + destroy(); + break; + } }); + + function init() { + CPU = new _chimeeFlv2fmp2.default(); + CPU.onInitSegment = onRemuxerInitSegmentArrival; + CPU.onMediaSegment = onRemuxerMediaSegmentArrival; + CPU.onError = onCPUError; + CPU.onMediaInfo = onMediaInfo; + CPU.on('error', function (handle) { + self.postMessage({ cmd: 'error', source: handle.data }); + }); + } + + function onRemuxerInitSegmentArrival(video, audio) { + self.postMessage({ + cmd: 'mediaSegmentInit', + source: { + type: 'video', + data: video + } + }); + if (audio) { + self.postMessage({ + cmd: 'mediaSegmentInit', + source: { + type: 'audio', + data: audio + } + }); + } + } + + function onRemuxerMediaSegmentArrival(type, data) { + self.postMessage({ cmd: 'mediaSegment', source: { type: type, data: data } }); + } + + function onCPUError(error) { + self.postMessage({ cmd: 'error', source: error }); + } + + function onMediaInfo(mediainfo) { + self.postMessage({ cmd: 'mediainfo', source: mediainfo }); + } + + function seek(keyframe) { + loader.pause(); + loader = new _ioLoader2.default(config); + loader.arrivalDataCallback = arrivalDataCallbackWorker; + loader.seek(keyframe.keyframePoint, false, keyframe.keyframetime); + } + + function destroy() { + loader.destroy(); + loader = null; + CPU = null; + } + + function arrivalDataCallbackWorker(data, byteStart, keyframePoint) { + if (!CPU) { + init(); + } + if (keyframePoint) { + CPU.seek(keyframePoint); + } + var consumed = CPU.setflv(data); + return consumed; + } +}; + +var _chimeeFlv2fmp = __webpack_require__(5); + +var _chimeeFlv2fmp2 = _interopRequireDefault(_chimeeFlv2fmp); + +var _ioLoader = __webpack_require__(3); + +var _ioLoader2 = _interopRequireDefault(_ioLoader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = { + isLive: false, // 是否是直播 + box: 'flv', // 容器 + seekInKeyframe: true, // 总是seek 到关键帧 + alwaysSeekKeyframe: true, // 总是seek 到关键帧 + lazyLoadMaxDuration: 2 * 60, // 懒加载 最大播放长度 + lazyLoadRecoverDuration: 30, // 懒加载还有多少长度 重启加载功能 + lockInternalProperty: false, // 锁定原生的选项 + debug: true, // 是否开启debug模式 + webWorker: false, // 是否开启webworker + autoCleanupSourceBuffer: true, // 是否自动清除 sourcebuffer + autoCleanupMaxBackwardDuration: 30, // 清除sourcebuffer最大时间 + autoCleanupMinBackwardDuration: 30, // 清除sourcebuffer最小时间 + stashSize: 1024 * 384, // io缓存大小 直播下建议设置成 1024 * 128 + seekType: 'range' // seek请求的方式 是range 还是 query +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) { +/** + * chimee-helper v0.2.8 + * (c) 2017 toxic-johann + * Released under MIT + */ + +(function (global, factory) { + factory(exports); +}(this, (function (exports) { +var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + + +function unwrapExports$$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule$$1(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +var _toInteger = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +// 7.2.1 RequireObjectCoercible(argument) +var _defined = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +// true -> String#at +// false -> String#codePointAt +var _stringAt = function (TO_STRING) { + return function (that, pos) { + var s = String(_defined(that)); + var i = _toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +var _library = true; + +var _global = createCommonjsModule$$1(function (module) { +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef +}); + +var _core = createCommonjsModule$$1(function (module) { +var core = module.exports = { version: '2.5.1' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef +}); + +var _aFunction = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +// optional / simple context binding + +var _ctx = function (fn, that, length) { + _aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +var _isObject = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +var _anObject = function (it) { + if (!_isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +var _fails = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +// Thank's IE8 for his funny defineProperty +var _descriptors = !_fails(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +var document$1 = _global.document; +// typeof document.createElement is 'object' in old IE +var is = _isObject(document$1) && _isObject(document$1.createElement); +var _domCreate = function (it) { + return is ? document$1.createElement(it) : {}; +}; + +var _ie8DomDefine = !_descriptors && !_fails(function () { + return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +// 7.1.1 ToPrimitive(input [, PreferredType]) + +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +var _toPrimitive = function (it, S) { + if (!_isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +var dP = Object.defineProperty; + +var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject(O); + P = _toPrimitive(P, true); + _anObject(Attributes); + if (_ie8DomDefine) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +var _objectDp = { + f: f +}; + +var _propertyDesc = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +var _hide = _descriptors ? function (object, key, value) { + return _objectDp.f(object, key, _propertyDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? _ctx(out, _global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) _hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +var _export = $export; + +var _redefine = _hide; + +var hasOwnProperty = {}.hasOwnProperty; +var _has = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +var _iterators = {}; + +var toString = {}.toString; + +var _cof = function (it) { + return toString.call(it).slice(8, -1); +}; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings + +// eslint-disable-next-line no-prototype-builtins +var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return _cof(it) == 'String' ? it.split('') : Object(it); +}; + +// to indexed object, toObject with fallback for non-array-like ES3 strings + + +var _toIobject = function (it) { + return _iobject(_defined(it)); +}; + +// 7.1.15 ToLength + +var min = Math.min; +var _toLength = function (it) { + return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +var max = Math.max; +var min$1 = Math.min; +var _toAbsoluteIndex = function (index, length) { + index = _toInteger(index); + return index < 0 ? max(index + length, 0) : min$1(index, length); +}; + +// false -> Array#indexOf +// true -> Array#includes + + + +var _arrayIncludes = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = _toIobject($this); + var length = _toLength(O.length); + var index = _toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +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 _objectKeysInternal = function (object, names) { + var O = _toIobject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO$1) _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); + } + return result; +}; + +// IE 8- don't enum bug keys +var _enumBugKeys = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) + + + +var _objectKeys = Object.keys || function keys(O) { + return _objectKeysInternal(O, _enumBugKeys); +}; + +var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties) { + _anObject(O); + var keys = _objectKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) _objectDp.f(O, P = keys[i++], Properties[P]); + return O; +}; + +var document$2 = _global.document; +var _html = document$2 && document$2.documentElement; + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + + + +var IE_PROTO = _sharedKey('IE_PROTO'); +var Empty = function () { /* empty */ }; +var PROTOTYPE$1 = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = _domCreate('iframe'); + var i = _enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + _html.appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; + return createDict(); +}; + +var _objectCreate = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE$1] = _anObject(O); + result = new Empty(); + Empty[PROTOTYPE$1] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : _objectDps(result, Properties); +}; + +var _wks = createCommonjsModule$$1(function (module) { +var store = _shared('wks'); + +var Symbol = _global.Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); +}; + +$exports.store = store; +}); + +var def = _objectDp.f; + +var TAG = _wks('toStringTag'); + +var _setToStringTag = function (it, tag, stat) { + if (it && !_has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); +}; + + + +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_hide(IteratorPrototype, _wks('iterator'), function () { return this; }); + +var _iterCreate = function (Constructor, NAME, next) { + Constructor.prototype = _objectCreate(IteratorPrototype, { next: _propertyDesc(1, 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()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR = '@@iterator'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function () { return this; }; + +var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + _iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = _objectGpo($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + _setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!_library && !_has(IteratorPrototype, ITERATOR)) _hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!_library || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + _hide(proto, ITERATOR, $default); + } + // Plug for library + _iterators[NAME] = $default; + _iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) _redefine(proto, key, methods[key]); + } else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; +var $at = _stringAt(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_iterDefine(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +// 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 _createProperty = function (object, index, value) { + if (index in object) _objectDp.f(object, index, _propertyDesc(0, value)); + else object[index] = value; +}; + +// getting tag from 19.1.3.6 Object.prototype.toString() + +var TAG$1 = _wks('toStringTag'); +// ES3 wrong here +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 ITERATOR$2 = _wks('iterator'); + +var core_getIteratorMethod = _core.getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR$2] + || it['@@iterator'] + || _iterators[_classof(it)]; +}; + +var ITERATOR$3 = _wks('iterator'); +var SAFE_CLOSING = false; + +try { + var riter = [7][ITERATOR$3](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + +} catch (e) { /* empty */ } + +var _iterDetect = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var 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', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = _toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = core_getIteratorMethod(O); + var 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$$1(function (module) { +module.exports = { "default": from$1, __esModule: true }; +}); + +var _Array$from = unwrapExports$$1(from); + +var toConsumableArray = createCommonjsModule$$1(function (module, exports) { + +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$$1(toConsumableArray); + +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; + var kind = this._k; + var 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; + +var TO_STRING_TAG = _wks('toStringTag'); + +var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i = 0; i < DOMIterables.length; i++) { + var NAME = DOMIterables[i]; + var Collection = _global[NAME]; + var proto = Collection && Collection.prototype; + if (proto && !proto[TO_STRING_TAG]) _hide(proto, TO_STRING_TAG, NAME); + _iterators[NAME] = _iterators.Array; +} + +var f$1 = _wks; + +var _wksExt = { + f: f$1 +}; + +var iterator$2 = _wksExt.f('iterator'); + +var iterator = createCommonjsModule$$1(function (module) { +module.exports = { "default": iterator$2, __esModule: true }; +}); + +unwrapExports$$1(iterator); + +var _meta = createCommonjsModule$$1(function (module) { +var META = _uid('meta'); + + +var setDesc = _objectDp.f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !_fails(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!_isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!_has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; +}); + +var defineProperty = _objectDp.f; +var _wksDefine = function (name) { + var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: _wksExt.f(name) }); +}; + +var f$2 = Object.getOwnPropertySymbols; + +var _objectGops = { + f: f$2 +}; + +var f$3 = {}.propertyIsEnumerable; + +var _objectPie = { + f: f$3 +}; + +// all enumerable object keys, includes symbols + + + +var _enumKeys = function (it) { + var result = _objectKeys(it); + var getSymbols = _objectGops.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = _objectPie.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +// 7.2.2 IsArray(argument) + +var _isArray = Array.isArray || function isArray(arg) { + return _cof(arg) == 'Array'; +}; + +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + +var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); + +var f$5 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return _objectKeysInternal(O, hiddenKeys); +}; + +var _objectGopn = { + f: f$5 +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + +var gOPN$1 = _objectGopn.f; +var toString$1 = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return gOPN$1(it); + } catch (e) { + return windowNames.slice(); + } +}; + +var f$4 = function getOwnPropertyNames(it) { + return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN$1(_toIobject(it)); +}; + +var _objectGopnExt = { + f: f$4 +}; + +var gOPD$1 = Object.getOwnPropertyDescriptor; + +var f$6 = _descriptors ? gOPD$1 : function getOwnPropertyDescriptor(O, P) { + O = _toIobject(O); + P = _toPrimitive(P, true); + if (_ie8DomDefine) try { + return gOPD$1(O, P); + } catch (e) { /* empty */ } + if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]); +}; + +var _objectGopd = { + f: f$6 +}; +// ECMAScript 6 symbols shim + + + + + +var META = _meta.KEY; + + + + + + + + + + + + + + + + + + +var gOPD = _objectGopd.f; +var dP$1 = _objectDp.f; +var gOPN = _objectGopnExt.f; +var $Symbol = _global.Symbol; +var $JSON = _global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE$2 = 'prototype'; +var HIDDEN = _wks('_hidden'); +var TO_PRIMITIVE = _wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = _shared('symbol-registry'); +var AllSymbols = _shared('symbols'); +var OPSymbols = _shared('op-symbols'); +var ObjectProto$1 = Object[PROTOTYPE$2]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = _global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = _descriptors && _fails(function () { + return _objectCreate(dP$1({}, 'a', { + get: function () { return dP$1(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto$1, key); + if (protoDesc) delete ObjectProto$1[key]; + dP$1(it, key, D); + if (protoDesc && it !== ObjectProto$1) dP$1(ObjectProto$1, key, protoDesc); +} : dP$1; + +var wrap = function (tag) { + var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto$1) $defineProperty(OPSymbols, key, D); + _anObject(it); + key = _toPrimitive(key, true); + _anObject(D); + if (_has(AllSymbols, key)) { + if (!D.enumerable) { + if (!_has(it, HIDDEN)) dP$1(it, HIDDEN, _propertyDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (_has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _objectCreate(D, { enumerable: _propertyDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP$1(it, key, D); +}; +var $defineProperties = function defineProperties(it, P) { + _anObject(it); + var keys = _enumKeys(P = _toIobject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P) { + return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = _toPrimitive(key, true)); + if (this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return false; + return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = _toIobject(it); + key = _toPrimitive(key, true); + if (it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(_toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto$1; + var names = gOPN(IS_OP ? OPSymbols : _toIobject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true)) result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto$1) $set.call(OPSymbols, value); + if (_has(this, HIDDEN) && _has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, _propertyDesc(1, value)); + }; + if (_descriptors && setter) setSymbolDesc(ObjectProto$1, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + _redefine($Symbol[PROTOTYPE$2], 'toString', function toString() { + return this._k; + }); + + _objectGopd.f = $getOwnPropertyDescriptor; + _objectDp.f = $defineProperty; + _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; + _objectPie.f = $propertyIsEnumerable; + _objectGops.f = $getOwnPropertySymbols; + + if (_descriptors && !_library) { + _redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + _wksExt.f = function (name) { + return wrap(_wks(name)); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE, { Symbol: $Symbol }); + +for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j = 0; es6Symbols.length > j;)_wks(es6Symbols[j++]); + +for (var wellKnownSymbols = _objectKeys(_wks.store), k = 0; wellKnownSymbols.length > k;) _wksDefine(wellKnownSymbols[k++]); + +_export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return _has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } +}); + +_export(_export.S + _export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + if (it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + replacer = args[1]; + if (typeof replacer == 'function') $replacer = replacer; + if ($replacer || !_isArray(replacer)) replacer = function (key, value) { + if ($replacer) value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +_setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +_setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +_setToStringTag(_global.JSON, 'JSON', true); + +_wksDefine('asyncIterator'); + +_wksDefine('observable'); + +var symbol$2 = _core.Symbol; + +var symbol = createCommonjsModule$$1(function (module) { +module.exports = { "default": symbol$2, __esModule: true }; +}); + +unwrapExports$$1(symbol); + +var _typeof_1 = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _iterator2 = _interopRequireDefault(iterator); + + + +var _symbol2 = _interopRequireDefault(symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +}); + +var _typeof = unwrapExports$$1(_typeof_1); + +// most Object methods by ES6 should accept primitives + + + +var _objectSap = function (KEY, exec) { + var fn = (_core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp); +}; + +// 19.1.2.14 Object.keys(O) + + + +_objectSap('keys', function () { + return function keys(it) { + return _objectKeys(_toObject(it)); + }; +}); + +var keys$1 = _core.Object.keys; + +var keys = createCommonjsModule$$1(function (module) { +module.exports = { "default": keys$1, __esModule: true }; +}); + +var _Object$keys = unwrapExports$$1(keys); + +// 20.1.2.3 Number.isInteger(number) + +var floor$1 = Math.floor; +var _isInteger = function isInteger(it) { + return !_isObject(it) && isFinite(it) && floor$1(it) === it; +}; + +// 20.1.2.3 Number.isInteger(number) + + +_export(_export.S, 'Number', { isInteger: _isInteger }); + +var isInteger$2 = _core.Number.isInteger; + +var isInteger$1 = createCommonjsModule$$1(function (module) { +module.exports = { "default": isInteger$2, __esModule: true }; +}); + +var _Number$isInteger = unwrapExports$$1(isInteger$1); + +var _stringWs = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +var space = '[' + _stringWs + ']'; +var non = '\u200b\u0085'; +var ltrim = RegExp('^' + space + space + '*'); +var rtrim = RegExp(space + space + '*$'); + +var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = _fails(function () { + return !!_stringWs[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : _stringWs[KEY]; + if (ALIAS) exp[ALIAS] = fn; + _export(_export.P + _export.F * FORCE, 'String', exp); +}; + +// 1 -> String#trimLeft +// 2 -> String#trimRight +// 3 -> String#trim +var trim = exporter.trim = function (string, TYPE) { + string = String(_defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; +}; + +var _stringTrim = exporter; + +var $parseFloat = _global.parseFloat; +var $trim = _stringTrim.trim; + +var _parseFloat$3 = 1 / $parseFloat(_stringWs + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; +} : $parseFloat; + +// 20.1.2.12 Number.parseFloat(string) +_export(_export.S + _export.F * (Number.parseFloat != _parseFloat$3), 'Number', { parseFloat: _parseFloat$3 }); + +var _parseFloat$1 = parseFloat; + +var _parseFloat = createCommonjsModule$$1(function (module) { +module.exports = { "default": _parseFloat$1, __esModule: true }; +}); + +var _Number$parseFloat = unwrapExports$$1(_parseFloat); + +/** + * toxic-predicate-functions v0.1.5 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** + * to check whether the object is defined or not + */ +function defined$1(obj) { + return typeof obj !== 'undefined'; +} +/** + * is void element or not ? Means it will return true when val is undefined or null + */ +function isVoid(obj) { + return obj === undefined || obj === null; +} +/** + * to check whether a variable is array + */ +function isArray(arr) { + return Array.isArray(arr); +} + +/** + * is it a function or not + */ +function isFunction(obj) { + return typeof obj === 'function'; +} + +/** + * is it an object or not + */ +function isObject$1(obj) { + // incase of arrow function and array + return Object(obj) === obj && String(obj) === '[object Object]' && !isFunction(obj) && !isArray(obj); +} +/** + * to tell you if it's a real number + */ +function isNumber(obj) { + return typeof obj === 'number'; +} +/** + * to tell you if the val can be transfer into number + */ +function isNumeric(obj) { + return !isArray(obj) && obj - _Number$parseFloat(obj) + 1 >= 0; +} +/** + * is it an interget or not + */ +function isInteger(num) { + return _Number$isInteger(num); +} + +/** + * return true when the value is "", {}, [], 0, null, undefined, false. + */ +function isEmpty(obj) { + if (isArray(obj)) { + return obj.length === 0; + } else if (isObject$1(obj)) { + return _Object$keys(obj).length === 0; + } else { + return !obj; + } +} +/** + * is it an event or not + */ +function isEvent(obj) { + return obj instanceof Event || (obj && obj.originalEvent) instanceof Event; +} +/** + * is it a blob + */ +function isBlob(obj) { + return obj instanceof Blob; +} +/** + * is it a file uploaded by user through file inpue + */ +function isFile(obj) { + return isBlob(obj) && isString(obj.name); +} +/** + * is it a date + */ +function isDate(obj) { + return Object.prototype.toString.call(obj) === '[object Date]'; +} +/** + * is it a string + */ +function isString(str) { + return typeof str === 'string' || str instanceof String; +} +/** + * is Boolean or not + */ +function isBoolean(bool) { + return typeof bool === 'boolean'; +} +/** + * is a promise or not + */ +function isPromise(obj) { + return !!obj && ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +} +/** + * is Primitive type or not, whick means it will return true when data is number/string/boolean/undefined/null + */ +function isPrimitive(val) { + return isVoid(val) || isBoolean(val) || isString(val) || isNumber(val); +} +/** + * is it an url, but this test require the url to have an protocol + */ +function isUrl(str) { + return isString(str) && !!str.match(/^((https?|ftp|rtsp|mms):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6}|localhost)(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i); +} +/** + * to test if a HTML node + */ +function isNode(obj) { + return !!((typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? obj instanceof Node : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'); +} +/** + * to test if a HTML element + */ +function isElement(obj) { + return !!((typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === 'object' ? obj instanceof HTMLElement : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string'); +} +/** + * check if node A is node B's parent or not + */ +function isChildNode(parent, child) { + if (!isNode(parent) || !isNode(child)) { + return false; + } + return child.parentNode === parent; +} +/** + * check if node B is node A's posterrity or not + */ +function isPosterityNode(parent, child) { + if (!isNode(parent) || !isNode(child)) { + return false; + } + while (child.parentNode) { + child = child.parentNode; + if (child === parent) { + return true; + } + } + return false; +} +/** + * check if the string is an HTMLString + */ +function isHTMLString(str) { + return (/<[^>]+?>/.test(str) + ); +} +/** + * check if is an error + */ +function isError(val) { + return val instanceof Error; +} +/** + * check if is an RegExp + */ +function isRegExp(val) { + return val instanceof RegExp; +} + +/** + * toxic-utils v0.1.6 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** + * the handler to generate an deep traversal handler + * @param {Function} fn the function you wanna run when you reach in the deep property + * @return {Function} the handler + */ +function genTraversalHandler(fn) { + function recursiveFn(source, target, key) { + if (isArray(source) || isObject$1(source)) { + target = isPrimitive(target) ? isObject$1(source) ? {} : [] : target; + for (var _key in source) { + // $FlowFixMe: support computed key here + target[_key] = recursiveFn(source[_key], target[_key], _key); + } + return target; + } + return fn(source, target, key); + } + return recursiveFn; +} +var _deepAssign = genTraversalHandler(function (val) { + return val; +}); +/** + * deeply clone an object + * @param {Array|Object} source if you pass in other type, it will throw an error + * @return {clone-target} the new Object + */ +function deepClone(source) { + if (isPrimitive(source)) { + throw new TypeError('deepClone only accept non primitive type'); + } + return _deepAssign(source); +} +/** + * merge multiple objects + * @param {...Object} args [description] + * @return {merge-object} [description] + */ +function deepAssign() { + for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { + args[_key2] = arguments[_key2]; + } + + if (args.length < 2) { + throw new Error('deepAssign accept two and more argument'); + } + for (var i = args.length - 1; i > -1; i--) { + if (isPrimitive(args[i])) { + throw new TypeError('deepAssign only accept non primitive type'); + } + } + var target = args.shift(); + args.forEach(function (source) { + return _deepAssign(source, target); + }); + return target; +} + +/** + * camelize any string, e.g hello world -> helloWorld + * @param {string} str only accept string! + * @return {string} camelize string + */ +function camelize(str, isBig) { + return str.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g, function (match, spilt, initials, index) { + return !isBig && index === 0 ? initials.toLowerCase() : initials.toUpperCase(); + }); +} +/** + * hypenate any string e.g hello world -> hello-world + * @param {string} str only accept string + * @return {string} + */ +function hypenate(str) { + return camelize(str).replace(/([A-Z])/g, function (match) { + return '-' + match.toLowerCase(); + }); +} + +/** + * bind the function with some context. we have some fallback strategy here + * @param {function} fn the function which we need to bind the context on + * @param {any} context the context object + */ +function bind(fn, context) { + if (fn.bind) { + return fn.bind(context); + } else if (fn.apply) { + return function __autobind__() { + for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { + args[_key3] = arguments[_key3]; + } + + return fn.apply(context, args); + }; + } else { + return function __autobind__() { + for (var _len3 = arguments.length, args = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { + args[_key4] = arguments[_key4]; + } + + return fn.call.apply(fn, [context].concat(_toConsumableArray(args))); + }; + } +} + +/** + * generate an uuid + */ +function uuid() { + return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); +} +/** + * generate an random number which length is 4 + */ +function S4() { + return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1); +} + +/** + * generate an random number with specific length + */ +function rand(length) { + var str = ''; + while (str.length < length) { + str += S4(); + } + return str.slice(0, length); +} + +/** + * get an deep property + */ +function getDeepProperty(obj, keys) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$throwError = _ref.throwError, + throwError = _ref$throwError === undefined ? false : _ref$throwError, + backup = _ref.backup; + + if (isString(keys)) { + keys = keys.split('.'); + } + if (!isArray(keys)) { + throw new TypeError('keys of getDeepProperty must be string or Array<string>'); + } + var read = []; + var target = obj; + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + if (isVoid(target)) { + if (throwError) { + throw new Error('obj' + (read.length > 0 ? '.' + read.join('.') : ' itself') + ' is ' + target); + } else { + return backup; + } + } + target = target[key]; + read.push(key); + } + return target; +} + +var _anInstance = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; +}; + +var _forOf = createCommonjsModule$$1(function (module) { +var BREAK = {}; +var RETURN = {}; +var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : core_getIteratorMethod(iterable); + var f = _ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (_isArrayIter(iterFn)) for (length = _toLength(iterable.length); length > index; index++) { + result = entries ? f(_anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = _iterCall(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } +}; +exports.BREAK = BREAK; +exports.RETURN = RETURN; +}); + +// 7.3.20 SpeciesConstructor(O, defaultConstructor) + + +var SPECIES = _wks('species'); +var _speciesConstructor = function (O, D) { + var C = _anObject(O).constructor; + var S; + return C === undefined || (S = _anObject(C)[SPECIES]) == undefined ? D : _aFunction(S); +}; + +// fast apply, http://jsperf.lnkit.com/fast-apply/5 +var _invoke = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); +}; + +var process$1 = _global.process; +var setTask = _global.setImmediate; +var clearTask = _global.clearImmediate; +var MessageChannel = _global.MessageChannel; +var Dispatch = _global.Dispatch; +var counter = 0; +var queue = {}; +var ONREADYSTATECHANGE = 'onreadystatechange'; +var defer; +var channel; +var port; +var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } +}; +var listener = function (event) { + run.call(event.data); +}; +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + _invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (_cof(process$1) == 'process') { + defer = function (id) { + process$1.nextTick(_ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(_ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = _ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (_global.addEventListener && typeof postMessage == 'function' && !_global.importScripts) { + defer = function (id) { + _global.postMessage(id + '', '*'); + }; + _global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in _domCreate('script')) { + defer = function (id) { + _html.appendChild(_domCreate('script'))[ONREADYSTATECHANGE] = function () { + _html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(_ctx(run, id, 1), 0); + }; + } +} +var _task = { + set: setTask, + clear: clearTask +}; + +var macrotask = _task.set; +var Observer = _global.MutationObserver || _global.WebKitMutationObserver; +var process$2 = _global.process; +var Promise = _global.Promise; +var isNode$2 = _cof(process$2) == 'process'; + +var _microtask = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode$2 && (parent = process$2.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode$2) { + notify = function () { + process$2.nextTick(flush); + }; + // browsers with MutationObserver + } else if (Observer) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + var promise = Promise.resolve(); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(_global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; +}; +// 25.4.1.5 NewPromiseCapability(C) + + +function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = _aFunction(resolve); + this.reject = _aFunction(reject); +} + +var f$7 = function (C) { + return new PromiseCapability(C); +}; + +var _newPromiseCapability = { + f: f$7 +}; + +var _perform = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } +}; + +var _promiseResolve = function (C, x) { + _anObject(C); + if (_isObject(x) && x.constructor === C) return x; + var promiseCapability = _newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; +}; + +var _redefineAll = function (target, src, safe) { + for (var key in src) { + if (safe && target[key]) target[key] = src[key]; + else _hide(target, key, src[key]); + } return target; +}; + + + + +var SPECIES$1 = _wks('species'); + +var _setSpecies = function (KEY) { + var C = typeof _core[KEY] == 'function' ? _core[KEY] : _global[KEY]; + if (_descriptors && C && !C[SPECIES$1]) _objectDp.f(C, SPECIES$1, { + configurable: true, + get: function () { return this; } + }); +}; + + + + + + + + + + +var task = _task.set; +var microtask = _microtask(); + + + +var PROMISE = 'Promise'; +var TypeError$1 = _global.TypeError; +var process = _global.process; +var $Promise = _global[PROMISE]; +var isNode$1 = _classof(process) == 'process'; +var empty = function () { /* empty */ }; +var Internal; +var newGenericPromiseCapability; +var OwnPromiseCapability; +var Wrapper; +var newPromiseCapability = newGenericPromiseCapability = _newPromiseCapability.f; + +var USE_NATIVE$1 = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[_wks('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode$1 || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; + } catch (e) { /* empty */ } +}(); + +// helpers +var isThenable = function (it) { + var then; + return _isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; +var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); + if (domain) domain.exit(); + } + if (result === reaction.promise) { + reject(TypeError$1('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); +}; +var onUnhandled = function (promise) { + task.call(_global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = _perform(function () { + if (isNode$1) { + process.emit('unhandledRejection', value, promise); + } else if (handler = _global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = _global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode$1 || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); +}; +var isUnhandled = function (promise) { + if (promise._h == 1) return false; + var chain = promise._a || promise._c; + var i = 0; + var reaction; + while (chain.length > i) { + reaction = chain[i++]; + if (reaction.fail || !isUnhandled(reaction.promise)) return false; + } return true; +}; +var onHandleUnhandled = function (promise) { + task.call(_global, function () { + var handler; + if (isNode$1) { + process.emit('rejectionHandled', promise); + } else if (handler = _global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); +}; +var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); +}; +var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError$1("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, _ctx($resolve, wrapper, 1), _ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } +}; + +// constructor polyfill +if (!USE_NATIVE$1) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + _anInstance(this, $Promise, PROMISE, '_h'); + _aFunction(executor); + Internal.call(this); + try { + executor(_ctx($resolve, this, 1), _ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = _redefineAll($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(_speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode$1 ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = _ctx($resolve, promise, 1); + this.reject = _ctx($reject, promise, 1); + }; + _newPromiseCapability.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; +} + +_export(_export.G + _export.W + _export.F * !USE_NATIVE$1, { Promise: $Promise }); +_setToStringTag($Promise, PROMISE); +_setSpecies(PROMISE); +Wrapper = _core[PROMISE]; + +// statics +_export(_export.S + _export.F * !USE_NATIVE$1, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } +}); +_export(_export.S + _export.F * (_library || !USE_NATIVE$1), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return _promiseResolve(_library && this === Wrapper ? $Promise : this, x); + } +}); +_export(_export.S + _export.F * !(USE_NATIVE$1 && _iterDetect(function (iter) { + $Promise.all(iter)['catch'](empty); +})), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = _perform(function () { + var values = []; + var index = 0; + var remaining = 1; + _forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = _perform(function () { + _forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } +}); + + + + + + +_export(_export.P + _export.R, 'Promise', { 'finally': function (onFinally) { + var C = _speciesConstructor(this, _core.Promise || _global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return _promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return _promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); +} }); +// https://github.com/tc39/proposal-promise-try + + + + +_export(_export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = _newPromiseCapability.f(this); + var result = _perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; +} }); + +var promise$1 = _core.Promise; + +var promise = createCommonjsModule$$1(function (module) { +module.exports = { "default": promise$1, __esModule: true }; +}); + +var _Promise = unwrapExports$$1(promise); + +/** + * chimee-helper-utils v0.2.0 + * (c) 2017 toxic-johann + * Released under MIT + */ + +// ********************** judgement ************************ +/** + * check if the code running in browser environment (not include worker env) + * @returns {Boolean} + */ +var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; + +// ********************** 对象操作 ************************ +/** + * 转变一个类数组对象为数组 + */ +function makeArray(obj) { + return _Array$from(obj); +} + +/** + * sort Object attributes by function + * and transfer them into array + * @param {Object} obj Object form from numric + * @param {Function} fn sort function + * @return {Array} the sorted attirbutes array + */ +function transObjectAttrIntoArray(obj) { + var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) { + return +a - +b; + }; + + return _Object$keys(obj).sort(fn).reduce(function (order, key) { + return order.concat(obj[key]); + }, []); +} +/** + * run a queue one by one.If include function reject or return false it will stop + * @param {Array} queue the queue which we want to run one by one + * @return {Promise} tell us whether a queue run finished + */ +function runRejectableQueue(queue) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + return new _Promise(function (resolve, reject) { + var step = function step(index) { + if (index >= queue.length) { + resolve(); + return; + } + var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; + if (result === false) return reject('stop'); + return _Promise.resolve(result).then(function () { + return step(index + 1); + }).catch(function (err) { + return reject(err || 'stop'); + }); + }; + step(0); + }); +} +/** + * run a queue one by one.If include function return false it will stop + * @param {Array} queue the queue which we want to run one by one + * @return {boolean} tell the user if the queue run finished + */ +function runStoppableQueue(queue) { + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + var step = function step(index) { + if (index >= queue.length) { + return true; + } + var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; + if (result === false) return false; + return step(++index); + }; + return step(0); +} + +function checkContinuation(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; + } +} + +// decodeUTF8 +function decodeUTF8(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(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(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(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 debounce(func, wait, immediate) { + // immediate默认为false + var timeout = void 0, + args = void 0, + context = void 0, + timestamp = void 0, + result = void 0; + + var later = function later() { + // 当wait指定的时间间隔期间多次调用_.debounce返回的函数,则会不断更新timestamp的值,导致last < wait && last >= 0一直为true,从而不断启动新的计时器延时执行func + var last = new Date() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function () { + context = this; + args = arguments; + timestamp = new Date(); + // 第一次调用该方法时,且immediate为true,则调用func函数 + var callNow = immediate && !timeout; + // 在wait指定的时间间隔内首次调用该方法,则启动计时器定时调用func函数 + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; +} + +/** + * 函数节流(控制函数执行频率) + * @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; + }; +} + +// requestAnimationFrame +var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (cb) { + return setTimeout(cb, 17); +}; + +// cancelAnimationFrame +var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame || function (id) { + clearTimeout(id); +}; + +// 根据要求的位数,将9格式化为 09\009\0009... +function strRepeat(num, bit) { + var pBit = bit; + num = '' + (num || ''); + var numLen = num.length; + bit = (bit || numLen) - numLen; + var paddingStr = bit > 0 ? num.repeat ? '0'.repeat(bit) : new Array(bit + 1).join('0') : ''; + return (paddingStr + num).slice(0, pBit); +} + +// video 时间格式化 +function formatTime(time) { + var hh = Math.floor(time / 3600); + time = Math.floor(time % 3600); + var mm = strRepeat(Math.floor(time / 60), 2); + time = Math.floor(time % 60); + var ss = strRepeat(time, 2); + return hh >= 1 ? hh + ':' + mm + ':' + ss : mm + ':' + ss; +} + +/** + * 追加样式代码到head的style标签,不存在则创建 + * @param {String} cssText 样式文本 + * @return {HTMLElement} + */ +function appendCSS(cssText) { + var doc = document; + var styleEl = doc.querySelector('style'); + if (!styleEl) { + styleEl = doc.createElement('style'); + var header = doc.querySelector('head'); + header && header.appendChild(styleEl); + } + styleEl.appendChild(doc.createTextNode(cssText)); + return styleEl; +} + +/** + * 格式化日期对象为:年-月-日 时:分:秒.毫秒 + * @param {Date} date Date日期对象 + * @param {String} pattern 要输出的日期格式,默认:`yyyy-MM-dd hh:mm:ss.i` + * @return {String} + */ +function formatDate() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'yyyy-MM-dd hh:mm:ss.i'; + + var year = date.getFullYear().toString(); + var fields = { + M: date.getMonth() + 1, + d: date.getDate(), + h: date.getHours(), + m: date.getMinutes(), + s: date.getSeconds(), + i: date.getMilliseconds() + }; + pattern = pattern.replace(/(y+)/ig, function (_, yearPattern) { + return year.substr(4 - Math.min(4, yearPattern.length)); + }); + + var _loop = function _loop(i) { + pattern = pattern.replace(new RegExp('(' + i + '+)', 'g'), function (_, pattStr) { + return (fields[i] < 10 && pattStr.length > 1 ? '0' : '') + fields[i]; + }); + }; + + for (var i in fields) { + _loop(i); + } + return pattern; +} + +/** + * 读取本地存储的值(不支持localStorage则降级到cookie) + * @param {String} key 目标数据key + * @return {String} + */ +function getLocalStorage(key) { + try { + return window.localStorage.getItem(key); + } catch (e) { + try { + var regRt = document.cookie.match(new RegExp('(^| )' + key + '=([^;]*)(;|$)')); + return isArray(regRt) ? unescape(regRt[2]) : ''; + } catch (e) { + return ''; + } + } +} +/** + * 将指定key对应值写入本地存储(不支持localStorage则降级到cookie) + * @param {String} key + * @param {String} val + * @return {String} + */ +function setLocalStorage(key, val) { + try { + window.localStorage.setItem(key, val); + } catch (e) { + var expires = new Date(); + // 默认存储300天 + expires.setTime(expires.getTime() + 24 * 3600 * 1000 * 300); + try { + document.cookie = key + '=' + escape(val) + ';expires=' + expires.toUTCString() + ';path=/;'; + } catch (e) {} + } +} + +var classCallCheck = createCommonjsModule$$1(function (module, exports) { + +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$$1(classCallCheck); + +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +_export(_export.S + _export.F * !_descriptors, 'Object', { defineProperty: _objectDp.f }); + +var $Object = _core.Object; +var defineProperty$3 = function defineProperty(it, key, desc) { + return $Object.defineProperty(it, key, desc); +}; + +var defineProperty$1 = createCommonjsModule$$1(function (module) { +module.exports = { "default": defineProperty$3, __esModule: true }; +}); + +unwrapExports$$1(defineProperty$1); + +var createClass = createCommonjsModule$$1(function (module, exports) { + +exports.__esModule = true; + + + +var _defineProperty2 = _interopRequireDefault(defineProperty$1); + +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$$1(createClass); +// 19.1.2.1 Object.assign(target, source, ...) + + + + + +var $assign = Object.assign; + +// should work with symbols and should have deterministic property order (V8 bug) +var _objectAssign = !$assign || _fails(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = _toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = _objectGops.f; + var isEnum = _objectPie.f; + while (aLen > index) { + var S = _iobject(arguments[index++]); + var keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; +} : $assign; + +// 19.1.3.1 Object.assign(target, source) + + +_export(_export.S + _export.F, 'Object', { assign: _objectAssign }); + +var assign$1 = _core.Object.assign; + +var assign = createCommonjsModule$$1(function (module) { +module.exports = { "default": assign$1, __esModule: true }; +}); + +var _Object$assign = unwrapExports$$1(assign); + +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +_export(_export.S, 'Object', { create: _objectCreate }); + +var $Object$1 = _core.Object; +var create$1 = function create(P, D) { + return $Object$1.create(P, D); +}; + +var create = createCommonjsModule$$1(function (module) { +module.exports = { "default": create$1, __esModule: true }; +}); + +var _Object$create = unwrapExports$$1(create); + +/** + * chimee-helper-events v0.1.0 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** +* @module event +* @author huzunjie +* @description 自定义事件基础类 +*/ + +/* 缓存事件监听方法及包装,内部数据格式: + * targetIndex_<type:'click|mouseup|done'>: [ [ + * function(){ ... handler ... }, + * function(){ ... handlerWrap ... handler.apply(target, arguments) ... }, + * isOnce + * ]] + */ +var _evtListenerCache = _Object$create(null); +_evtListenerCache.count = 0; + +/** + * 得到某对象的某事件类型对应的监听队列数组 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型(这里的时间类型不只是名称,还是缓存标识,可以通过添加后缀来区分) + * @return {Array} + */ +function getEvtTypeCache(target, type) { + + var evtId = target.__evt_id; + if (!evtId) { + + /* 设置__evt_id不可枚举 */ + Object.defineProperty(target, '__evt_id', { + writable: true, + enumerable: false, + configurable: true + }); + + /* 空对象初始化绑定索引 */ + evtId = target.__evt_id = ++_evtListenerCache.count; + } + + var typeCacheKey = evtId + '_' + type; + var evtTypeCache = _evtListenerCache[typeCacheKey]; + if (!evtTypeCache) { + evtTypeCache = _evtListenerCache[typeCacheKey] = []; + } + + return evtTypeCache; +} + +/** + * 触发事件监听方法 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Object} eventObj 触发事件时要传回的event对象 + * @return {undefined} + */ +function emitEventCache(target, type, eventObj) { + var evt = _Object$create(null); + evt.type = type; + evt.target = target; + if (eventObj) { + _Object$assign(evt, isObject$1(eventObj) ? eventObj : { data: eventObj }); + } + getEvtTypeCache(target, type).forEach(function (item) { + (item[1] || item[0]).apply(target, [evt]); + }); +} + +/** + * 添加事件监听到缓存 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 是否单次执行 + * @param {Function} handlerWrap + * @return {undefined} + */ +function addEventCache(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var handlerWrap = arguments[4]; + + if (isFunction(isOnce) && !handlerWrap) { + handlerWrap = isOnce; + isOnce = undefined; + } + var handlers = [handler, undefined, isOnce]; + if (isOnce && !handlerWrap) { + handlerWrap = function handlerWrap() { + removeEventCache(target, type, handler, isOnce); + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + handler.apply(target, args); + }; + } + if (handlerWrap) { + handlers[1] = handlerWrap; + } + getEvtTypeCache(target, type).push(handlers); +} + +/** + * 移除事件监听 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {undefined} + */ +function removeEventCache(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var typeCache = getEvtTypeCache(target, type); + + if (handler || isOnce) { + /* 有指定 handler 则清除对应监听 */ + var handlerId = -1; + var handlerWrap = void 0; + typeCache.find(function (item, i) { + if ((!handler || item[0] === handler) && (!isOnce || item[2])) { + handlerId = i; + handlerWrap = item[1]; + return true; + } + }); + if (handlerId !== -1) { + typeCache.splice(handlerId, 1); + } + return handlerWrap; + } else { + /* 未指定 handler 则清除type对应的所有监听 */ + typeCache.length = 0; + } +} + +/** + * @class CustEvent + * @description + * Event 自定义事件类 + * 1. 可以使用不传参得到的实例作为eventBus使用 + * 2. 可以通过指定target,用多个实例操作同一target对象的事件管理 + * 3. 当设定target时,可以通过设置assign为true,来给target实现"on\once\off\emit"方法 + * @param {Object} target 发生事件的对象(空则默认为event实例) + * @param {Boolean} assign 是否将"on\once\off\emit"方法实现到target对象上 + * @return {event} + */ +var CustEvent = function () { + function CustEvent(target, assign$$1) { + var _this = this; + + _classCallCheck(this, CustEvent); + + /* 设置__target不可枚举 */ + Object.defineProperty(this, '__target', { + writable: true, + enumerable: false, + configurable: true + }); + this.__target = this; + + if (target) { + + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') { + throw new Error('CusEvent target are not object'); + } + this.__target = target; + + /* 为target实现on\once\off\emit */ + if (assign$$1) { + ['on', 'once', 'off', 'emit'].forEach(function (mth) { + target[mth] = _this[mth]; + }); + } + } + } + + /** + * 添加事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + + _createClass(CustEvent, [{ + key: 'on', + value: function on(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + addEventCache(this.__target, type, handler, isOnce); + return this; + } + + /** + * 添加事件监听,并且只执行一次 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {event} + */ + + }, { + key: 'once', + value: function once(type, handler) { + return this.on(type, handler, true); + } + + /** + * 移除事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数(不指定handler则清除type对应的所有事件监听) + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + }, { + key: 'off', + value: function off(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + removeEventCache(this.__target, type, handler, isOnce); + return this; + } + + /** + * 触发事件监听函数 + * @param {String} type 事件类型 + * @return {event} + */ + + }, { + key: 'emit', + value: function emit(type, data) { + emitEventCache(this.__target, type, { data: data }); + return this; + } + }]); + + return CustEvent; +}(); + +/** + * chimee-helper-dom v0.1.6 + * (c) 2017 huzunjie + * Released under MIT + */ + +/** + * chimee-helper-events v0.1.0 + * (c) 2017 toxic-johann + * Released under MIT + */ + +/** +* @module event +* @author huzunjie +* @description 自定义事件基础类 +*/ + +/* 缓存事件监听方法及包装,内部数据格式: + * targetIndex_<type:'click|mouseup|done'>: [ [ + * function(){ ... handler ... }, + * function(){ ... handlerWrap ... handler.apply(target, arguments) ... }, + * isOnce + * ]] + */ +var _evtListenerCache$1 = _Object$create(null); +_evtListenerCache$1.count = 0; + +/** + * 得到某对象的某事件类型对应的监听队列数组 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型(这里的时间类型不只是名称,还是缓存标识,可以通过添加后缀来区分) + * @return {Array} + */ +function getEvtTypeCache$1(target, type) { + + var evtId = target.__evt_id; + if (!evtId) { + + /* 设置__evt_id不可枚举 */ + Object.defineProperty(target, '__evt_id', { + writable: true, + enumerable: false, + configurable: true + }); + + /* 空对象初始化绑定索引 */ + evtId = target.__evt_id = ++_evtListenerCache$1.count; + } + + var typeCacheKey = evtId + '_' + type; + var evtTypeCache = _evtListenerCache$1[typeCacheKey]; + if (!evtTypeCache) { + evtTypeCache = _evtListenerCache$1[typeCacheKey] = []; + } + + return evtTypeCache; +} + +/** + * 触发事件监听方法 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Object} eventObj 触发事件时要传回的event对象 + * @return {undefined} + */ +function emitEventCache$1(target, type, eventObj) { + var evt = _Object$create(null); + evt.type = type; + evt.target = target; + if (eventObj) { + _Object$assign(evt, isObject$1(eventObj) ? eventObj : { data: eventObj }); + } + getEvtTypeCache$1(target, type).forEach(function (item) { + (item[1] || item[0]).apply(target, [evt]); + }); +} + +/** + * 添加事件监听到缓存 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 是否单次执行 + * @param {Function} handlerWrap + * @return {undefined} + */ +function addEventCache$1(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var handlerWrap = arguments[4]; + + if (isFunction(isOnce) && !handlerWrap) { + handlerWrap = isOnce; + isOnce = undefined; + } + var handlers = [handler, undefined, isOnce]; + if (isOnce && !handlerWrap) { + handlerWrap = function handlerWrap() { + removeEventCache$1(target, type, handler, isOnce); + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + handler.apply(target, args); + }; + } + if (handlerWrap) { + handlers[1] = handlerWrap; + } + getEvtTypeCache$1(target, type).push(handlers); +} + +/** + * 移除事件监听 + * @param {Object} target 发生事件的对象 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {undefined} + */ +function removeEventCache$1(target, type, handler) { + var isOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var typeCache = getEvtTypeCache$1(target, type); + + if (handler || isOnce) { + /* 有指定 handler 则清除对应监听 */ + var handlerId = -1; + var handlerWrap = void 0; + typeCache.find(function (item, i) { + if ((!handler || item[0] === handler) && (!isOnce || item[2])) { + handlerId = i; + handlerWrap = item[1]; + return true; + } + }); + if (handlerId !== -1) { + typeCache.splice(handlerId, 1); + } + return handlerWrap; + } else { + /* 未指定 handler 则清除type对应的所有监听 */ + typeCache.length = 0; + } +} + +/** + * @class CustEvent + * @description + * Event 自定义事件类 + * 1. 可以使用不传参得到的实例作为eventBus使用 + * 2. 可以通过指定target,用多个实例操作同一target对象的事件管理 + * 3. 当设定target时,可以通过设置assign为true,来给target实现"on\once\off\emit"方法 + * @param {Object} target 发生事件的对象(空则默认为event实例) + * @param {Boolean} assign 是否将"on\once\off\emit"方法实现到target对象上 + * @return {event} + */ +var CustEvent$1 = function () { + function CustEvent(target, assign$$1) { + var _this = this; + + _classCallCheck(this, CustEvent); + + /* 设置__target不可枚举 */ + Object.defineProperty(this, '__target', { + writable: true, + enumerable: false, + configurable: true + }); + this.__target = this; + + if (target) { + + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') { + throw new Error('CusEvent target are not object'); + } + this.__target = target; + + /* 为target实现on\once\off\emit */ + if (assign$$1) { + ['on', 'once', 'off', 'emit'].forEach(function (mth) { + target[mth] = _this[mth]; + }); + } + } + } + + /** + * 添加事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + + _createClass(CustEvent, [{ + key: 'on', + value: function on(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + addEventCache$1(this.__target, type, handler, isOnce); + return this; + } + + /** + * 添加事件监听,并且只执行一次 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数 + * @return {event} + */ + + }, { + key: 'once', + value: function once(type, handler) { + return this.on(type, handler, true); + } + + /** + * 移除事件监听 + * @param {String} type 事件类型 + * @param {Function} handler 监听函数(不指定handler则清除type对应的所有事件监听) + * @param {Boolean} isOnce 单次监听类型 + * @return {event} + */ + + }, { + key: 'off', + value: function off(type, handler) { + var isOnce = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + removeEventCache$1(this.__target, type, handler, isOnce); + return this; + } + + /** + * 触发事件监听函数 + * @param {String} type 事件类型 + * @return {event} + */ + + }, { + key: 'emit', + value: function emit(type, data) { + emitEventCache$1(this.__target, type, { data: data }); + return this; + } + }]); + + return CustEvent; +}(); + +/** + * chimee-helper-utils v0.2.0 + * (c) 2017 toxic-johann + * Released under MIT + */ + +// ********************** judgement ************************ +/** + * check if the code running in browser environment (not include worker env) + * @returns {Boolean} + */ +var inBrowser$1 = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; + +// ********************** 对象操作 ************************ +/** + * 转变一个类数组对象为数组 + */ +function makeArray$1(obj) { + return _Array$from(obj); +} + +/** +* @module dom +* @author huzunjie +* @description 一些常用的DOM判断及操作方法,可以使用dom.$('*')包装DOM,实现类jQuery的链式操作;当然这里的静态方法也可以直接使用。 +*/ + +var _divEl = document.createElement('div'); +var _textAttrName = 'innerText'; +'textContent' in _divEl && (_textAttrName = 'textContent'); +var _arrPrototype = Array.prototype; + +/** + * 读取HTML元素属性值 + * @param {HTMLElement} el 目标元素 + * @param {String} attrName 目标属性名称 + * @return {String} + */ +function getAttr(el, attrName) { + return el.getAttribute(attrName); +} + +/** + * 设置HTML元素属性值 + * @param {HTMLElement} el 目标元素 + * @param {String} attrName 目标属性名称 + * @param {String} attrVal 目标属性值 + */ +function setAttr(el, attrName, attrVal) { + if (attrVal === undefined) { + el.removeAttribute(attrName); + } else { + el.setAttribute(attrName, attrVal); + } +} + +/** + * 为HTML元素添加className + * @param {HTMLElement} el 目标元素 + * @param {String} cls 要添加的className(多个以空格分割) + */ +function addClassName(el, cls) { + if (!cls || !(cls = cls.trim())) { + return; + } + var clsArr = cls.split(/\s+/); + if (el.classList) { + clsArr.forEach(function (c) { + return el.classList.add(c); + }); + } else { + var curCls = ' ' + (el.className || '') + ' '; + clsArr.forEach(function (c) { + curCls.indexOf(' ' + c + ' ') === -1 && (curCls += ' ' + c); + }); + el.className = curCls.trim(); + } +} + +/** + * 为HTML元素移除className + * @param {HTMLElement} el 目标元素 + * @param {String} cls 要移除的className(多个以空格分割) + */ +function removeClassName(el, cls) { + if (!cls || !(cls = cls.trim())) { + return; + } + + var clsArr = cls.split(/\s+/); + if (el.classList) { + clsArr.forEach(function (c) { + return el.classList.remove(c); + }); + } else { + var curCls = ' ' + el.className + ' '; + clsArr.forEach(function (c) { + var tar = ' ' + c + ' '; + while (curCls.indexOf(tar) !== -1) { + curCls = curCls.replace(tar, ' '); + } + }); + el.className = curCls.trim(); + } +} + +/** + * 检查HTML元素是否已设置className + * @param {HTMLElement} el 目标元素 + * @param {String} className 要检查的className + * @return {Boolean} + */ +function hasClassName(el, className) { + return new RegExp('(?:^|\\s)' + className + '(?=\\s|$)').test(el.className); +} + +// Test via a getter in the options object to see +// if the passive property is accessed +exports.supportsPassive = false; +try { + var opts = Object.defineProperty({}, 'passive', { + get: function get() { + exports.supportsPassive = true; + } + }); + window.addEventListener("test", null, opts); +} catch (e) {} + +// Use our detect's results. +// passive applied if supported, capture will be false either way. +var defaultCapture = exports.supportsPassive ? { passive: true } : false; + +/** + * 为HTML元素移除事件监听 + * @param {HTMLElement} el 目标元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段的监听 + */ +function removeEvent(el, type, handler) { + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultCapture; + + if (once) { + /* 尝试从缓存中读取包装后的方法 */ + var handlerWrap = removeEventCache$1(el, type + '_once', handler); + if (handlerWrap) { + handler = handlerWrap; + } + } + el.removeEventListener(type, handler, capture); +} + +/** + * 为HTML元素添加事件监听 + * @param {HTMLElement} el 目标元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段监听 + */ +function addEvent(el, type, handler) { + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultCapture; + + if (once) { + var oldHandler = handler; + handler = function () { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + oldHandler.apply(this, args); + removeEvent(el, type, handler, once, capture); + }; + }(); + /* 将包装后的方法记录到缓存中 */ + addEventCache$1(el, type + '_once', oldHandler, handler); + } + + el.addEventListener(type, handler, capture); +} + +/** + * 为HTML元素添加事件代理 + * @param {HTMLElement} el 目标元素 + * @param {String} selector 要被代理的元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + */ +function addDelegate(el, selector, type, handler) { + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultCapture; + + + var handlerWrap = function handlerWrap(e) { + var targetElsArr = findParents(e.target || e.srcElement, el, true); + var targetElArr = query(selector, el, true); + var retEl = void 0; + if (targetElArr.find) { + retEl = targetElArr.find(function (seEl) { + return targetElsArr.find(function (tgEl) { + return seEl === tgEl; + }); + }); + } else { + // Fixed IE11 Array.find not defined bug + targetElArr.forEach(function (seEl) { + return !retEl && targetElsArr.forEach(function (tgEl) { + if (!retEl && seEl === tgEl) { + retEl = tgEl; + } + }); + }); + } + retEl && handler.apply(retEl, arguments); + }; + /* 将包装后的方法记录到缓存中 */ + addEventCache$1(el, type + '_delegate_' + selector, handler, handlerWrap); + el.addEventListener(type, handlerWrap, capture); +} + +/** + * 为HTML元素移除事件代理 + * @param {HTMLElement} el 目标元素 + * @param {String} selector 要被代理的元素 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + */ +function removeDelegate(el, selector, type, handler) { + var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultCapture; + + /* 尝试从缓存中读取包装后的方法 */ + var handlerWrap = removeEventCache$1(el, type + '_delegate_' + selector, handler); + handlerWrap && el.removeEventListener(type, handlerWrap, capture); +} + +/** + * 读取HTML元素样式值 + * @param {HTMLElement} el 目标元素 + * @param {String} key 样式key + * @return {String} + */ +function getStyle(el, key) { + return (el.currentStyle || document.defaultView.getComputedStyle(el, null))[key] || el.style[key]; +} + +/** + * 设置HTML元素样式值 + * @param {HTMLElement} el 目标元素 + * @param {String} key 样式key + * @param {String} val 样式值 + */ +function setStyle(el, key, val) { + if (isObject$1(key)) { + for (var k in key) { + setStyle(el, k, key[k]); + } + } else { + el.style[key] = val; + } +} + +/** + * 根据选择器查询目标元素 + * @param {String} selector 选择器,用于 querySelectorAll + * @param {HTMLElement} container 父容器 + * @param {Boolean} toArray 强制输出为数组 + * @return {NodeList|Array} + */ +function query(selector) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; + var toArray = arguments[2]; + + var retNodeList = container.querySelectorAll(selector); + return toArray ? _Array$from(retNodeList) : retNodeList; +} + +/** + * 从DOM树中移除el + * @param {HTMLElement} el 目标元素 + */ +function removeEl(el) { + el.parentNode.removeChild(el); +} + +/** + * 查找元素的父节点们 + * @param {HTMLElement} el 目标元素 + * @param {HTMLElement} endEl 最大父容器(不指定则找到html) + * @param {Boolean} haveEl 包含当前元素 + * @param {Boolean} haveEndEl 包含设定的最大父容器 + */ +function findParents(el) { + var endEl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var haveEl = arguments[2]; + var haveEndEl = arguments[3]; + + var retEls = []; + if (haveEl) { + retEls.push(el); + } + while (el && el.parentNode !== endEl) { + el = el.parentNode; + el && retEls.push(el); + } + if (haveEndEl) { + retEls.push(endEl); + } + return retEls; +} + +/** + * 根据选择器查询并得到目标元素的wrap包装器 + * @param {String} selector 选择器,另外支持 HTMLString||NodeList||NodeArray||HTMLElement + * @param {HTMLElement} container 父容器 + * @return {Object} + */ +function $(selector, container) { + return selector.constructor === NodeWrap ? selector : new NodeWrap(selector, container); +} + +/** + * @class NodeWrap + * @description + * NodeWrap DOM包装器,用以实现基本的链式操作 + * new dom.NodeWrap('*') 相当于 dom.$('*') + * 这里面用于DOM操作的属性方法都是基于上面静态方法实现,有需要可以随时修改补充 + * @param {String} selector 选择器(兼容 String||HTMLString||NodeList||NodeArray||HTMLElement) + * @param {HTMLElement} container 父容器(默认为document) + */ + +var NodeWrap = function () { + function NodeWrap(selector) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; + + _classCallCheck(this, NodeWrap); + + var _this = this; + _this.selector = selector; + + /* String||NodeList||HTMLElement 识别处理 */ + var elsArr = void 0; + if (selector && selector.constructor === NodeList) { + /* 支持直接传入NodeList来构建包装器 */ + elsArr = makeArray$1(selector); + } else if (isArray(selector)) { + /* 支持直接传入Node数组来构建包装器 */ + elsArr = selector; + } else if (isString(selector)) { + if (selector.indexOf('<') === 0) { + /* 支持直接传入HTML字符串来新建DOM并构建包装器 */ + _divEl.innerHTML = selector; + elsArr = query('*', _divEl, true); + } else { + /* 支持直接传入字符串选择器来查找DOM并构建包装器 */ + elsArr = query(selector, container, true); + } + } else { + /* 其他任意对象直接构建包装器 */ + elsArr = [selector]; + } + _Object$assign(_this, elsArr); + + /* NodeWrap本意可以 extends Array省略构造方法中下面这部分代码,但目前编译不支持 */ + _this.length = elsArr.length; + } + + /** + * 循环遍历DOM集合 + * @param {Function} fn 遍历函数 fn(item, i) + * @return {Object} + */ + + + _createClass(NodeWrap, [{ + key: 'each', + value: function each() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + _arrPrototype.forEach.apply(this, args); + return this; + } + }, { + key: 'push', + + + /** + * 添加元素到DOM集合 + * @param {HTMLElement} el 要加入的元素 + * @return {this} + */ + value: function push() { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + _arrPrototype.push.apply(this, args); + return this; + } + }, { + key: 'splice', + + + /** + * 截取DOM集合片段,并得到新的包装器splice + * @param {Nubmer} start + * @param {Nubmer} count + * @return {NodeWrap} 新的DOM集合包装器 + */ + value: function splice() { + for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + return $(_arrPrototype.splice.apply(this, args)); + } + }, { + key: 'find', + + + /** + * 查找子元素 + * @param {String} selector 选择器 + * @return {NodeWrap} 新的DOM集合包装器 + */ + value: function find(selector) { + var childs = []; + this.each(function (el) { + childs = childs.concat(query(selector, el, true)); + }); + var childsWrap = $(childs); + childsWrap.parent = this; + childsWrap.selector = selector; + return childsWrap; + } + + /** + * 添加子元素 + * @param {HTMLElement} childEls 要添加的HTML元素 + * @return {this} + */ + + }, { + key: 'append', + value: function append(childEls) { + var childsWrap = $(childEls); + var firstEl = this[0]; + childsWrap.each(function (newEl) { + return firstEl.appendChild(newEl); + }); + return this; + } + + /** + * 将元素集合添加到指定容器 + * @param {HTMLElement} parentEl 要添加到父容器 + * @return {this} + */ + + }, { + key: 'appendTo', + value: function appendTo(parentEl) { + $(parentEl).append(this); + return this; + } + + /** + * DOM集合text内容读写操作 + * @param {String} val 文本内容(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'text', + value: function text(val) { + if (arguments.length === 0) { + return this[0][_textAttrName]; + } + return this.each(function (el) { + el[_textAttrName] = val; + }); + } + + /** + * DOM集合HTML内容读写操作 + * @param {String} html html内容(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'html', + value: function html(_html) { + if (arguments.length === 0) { + return this[0].innerHTML; + } + return this.each(function (el) { + el.innerHTML = _html; + }); + } + + /** + * DOM集合属性读写操作 + * @param {String} name 属性名称 + * @param {String} val 属性值(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'attr', + value: function attr(name, val) { + if (arguments.length === 1) { + return getAttr(this[0], name); + } + return this.each(function (el) { + return setAttr(el, name, val); + }); + } + + /** + * DOM集合dataset读写操作 + * @param {String} key 键名 + * @param {Any} val 键值(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'data', + value: function data(key, val) { + if (arguments.length === 0) { + return this[0].dataset || {}; + } + if (arguments.length === 1) { + return (this[0].dataset || {})[key]; + } + return this.each(function (el) { + (el.dataset || (el.dataset = {}))[key] = val; + }); + } + + /** + * DOM集合样式读写操作 + * @param {String} key 样式key + * @param {String} val 样式值(如果有设置该参数则执行写操作,否则执行读操作) + * @return {this} + */ + + }, { + key: 'css', + value: function css(key, val) { + if (arguments.length === 1 && !isObject$1(key)) { + return getStyle(this[0], key); + } + return this.each(function (el) { + return setStyle(el, key, val); + }); + } + + /** + * 为DOM集合增加className + * @param {String} cls 要增加的className + * @return {this} + */ + + }, { + key: 'addClass', + value: function addClass(cls) { + return this.each(function (el) { + return addClassName(el, cls); + }); + } + + /** + * 移除当前DOM集合的className + * @param {String} cls 要移除的className + * @return {this} + */ + + }, { + key: 'removeClass', + value: function removeClass(cls) { + return this.each(function (el) { + return removeClassName(el, cls); + }); + } + + /** + * 检查索引0的DOM是否有className + * @param {String} cls 要检查的className + * @return {this} + */ + + }, { + key: 'hasClass', + value: function hasClass(cls) { + return hasClassName(this[0], cls); + } + + /** + * 为DOM集合添加事件监听 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'on', + value: function on(type, handler) { + var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultCapture; + + return this.each(function (el) { + return addEvent(el, type, handler, once, capture); + }); + } + + /** + * 为DOM集合解除事件监听 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} once 是否只监听一次 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'off', + value: function off(type, handler) { + var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultCapture; + + return this.each(function (el) { + return removeEvent(el, type, handler, once, capture); + }); + } + + /** + * 为DOM集合绑定事件代理 + * @param {String} selector 目标子元素选择器 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'delegate', + value: function delegate(selector, type, handler) { + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultCapture; + + return this.each(function (el) { + return addDelegate(el, selector, type, handler, capture); + }); + } + + /** + * 为DOM集合解绑事件代理 + * @param {String} selector 目标子元素选择器 + * @param {String} type 事件名称 + * @param {Function} handler 处理函数 + * @param {Boolean} capture 是否在捕获阶段监听 + * @return {this} + */ + + }, { + key: 'undelegate', + value: function undelegate(selector, type, handler) { + var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultCapture; + + return this.each(function (el) { + return removeDelegate(el, selector, type, handler, capture); + }); + } + + /** + * 从DOM树中移除 + * @return {this} + */ + + }, { + key: 'remove', + value: function remove() { + return this.each(function (el) { + return removeEl(el); + }); + } + }]); + + return NodeWrap; +}(); + +/** + * chimee-helper-log v0.1.2 + * (c) 2017 toxic-johann + * Released under MIT + */ + +function formatter(tag, msg) { + if (!isString(tag)) throw new TypeError('Log\'s method only acccept string as argument, but not ' + tag + ' in ' + (typeof tag === 'undefined' ? 'undefined' : _typeof(tag))); + if (!isString(msg)) return '[' + Log.GLOBAL_TAG + '] > ' + tag; + tag = Log.FORCE_GLOBAL_TAG ? Log.GLOBAL_TAG : tag || Log.GLOBAL_TAG; + return '[' + tag + '] > ' + msg; +} +/** + * Log Object + */ + +var Log = function () { + function Log() { + _classCallCheck(this, Log); + } + + _createClass(Log, null, [{ + key: 'error', + + /** + * equal to console.error, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + value: function error(tag, msg) { + if (!Log.ENABLE_ERROR) { + return; + } + + (console.error || console.warn || console.log)(formatter(tag, msg)); + } + /** + * equal to console.info, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {boolean} + */ + + /** + * @member {string} + */ + + }, { + key: 'info', + value: function info(tag, msg) { + if (!Log.ENABLE_INFO) { + return; + } + (console.info || console.log)(formatter(tag, msg)); + } + /** + * equal to console.warn, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'warn', + value: function warn(tag, msg) { + if (!Log.ENABLE_WARN) { + return; + } + (console.warn || console.log)(formatter(tag, msg)); + } + /** + * equal to console.debug, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'debug', + value: function debug(tag, msg) { + if (!Log.ENABLE_DEBUG) { + return; + } + (console.debug || console.log)(formatter(tag, msg)); + } + /** + * equal to console.verbose, output `[${tag}] > {$msg}` + * @param {string} tag optional, the header of log + * @param {string} msg the message + */ + + }, { + key: 'verbose', + value: function verbose(tag, msg) { + if (!Log.ENABLE_VERBOSE) { + return; + } + console.log(formatter(tag, msg)); + } + }]); + + return Log; +}(); + +Log.GLOBAL_TAG = 'chimee'; +Log.FORCE_GLOBAL_TAG = false; +Log.ENABLE_ERROR = true; +Log.ENABLE_INFO = true; +Log.ENABLE_WARN = true; +Log.ENABLE_DEBUG = true; +Log.ENABLE_VERBOSE = true; + +var uaParser = createCommonjsModule$$1(function (module, exports) { +/** + * UAParser.js v0.7.17 + * Lightweight JavaScript-based User-Agent string parser + * https://github.com/faisalman/ua-parser-js + * + * Copyright © 2012-2016 Faisal Salman <fyzlman@gmail.com> + * Dual licensed under GPLv2 & MIT + */ + +(function (window, undefined) { + + ////////////// + // Constants + ///////////// + + + var LIBVERSION = '0.7.17', + EMPTY = '', + UNKNOWN = '?', + FUNC_TYPE = 'function', + UNDEF_TYPE = 'undefined', + OBJ_TYPE = 'object', + STR_TYPE = 'string', + MAJOR = 'major', // deprecated + MODEL = 'model', + NAME = 'name', + TYPE = 'type', + VENDOR = 'vendor', + VERSION = 'version', + ARCHITECTURE= 'architecture', + CONSOLE = 'console', + MOBILE = 'mobile', + TABLET = 'tablet', + SMARTTV = 'smarttv', + WEARABLE = 'wearable', + EMBEDDED = 'embedded'; + + + /////////// + // Helper + ////////// + + + var util = { + extend : function (regexes, extensions) { + var margedRegexes = {}; + for (var i in regexes) { + if (extensions[i] && extensions[i].length % 2 === 0) { + margedRegexes[i] = extensions[i].concat(regexes[i]); + } else { + margedRegexes[i] = regexes[i]; + } + } + return margedRegexes; + }, + has : function (str1, str2) { + if (typeof str1 === "string") { + return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; + } else { + return false; + } + }, + lowerize : function (str) { + return str.toLowerCase(); + }, + major : function (version) { + return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g,'').split(".")[0] : undefined; + }, + trim : function (str) { + return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + } + }; + + + /////////////// + // Map helper + ////////////// + + + var mapper = { + + rgx : function (ua, arrays) { + + //var result = {}, + var i = 0, j, k, p, q, matches, match;//, args = arguments; + + /*// construct object barebones + for (p = 0; p < args[1].length; p++) { + q = args[1][p]; + result[typeof q === OBJ_TYPE ? q[0] : q] = undefined; + }*/ + + // loop through all regexes maps + while (i < arrays.length && !matches) { + + var regex = arrays[i], // even sequence (0,2,4,..) + props = arrays[i + 1]; // odd sequence (1,3,5,..) + j = k = 0; + + // try matching uastring with regexes + while (j < regex.length && !matches) { + + matches = regex[j++].exec(ua); + + if (!!matches) { + for (p = 0; p < props.length; p++) { + match = matches[++k]; + q = props[p]; + // check if given property is actually array + if (typeof q === OBJ_TYPE && q.length > 0) { + if (q.length == 2) { + if (typeof q[1] == FUNC_TYPE) { + // assign modified match + this[q[0]] = q[1].call(this, match); + } else { + // assign given value, ignore regex match + this[q[0]] = q[1]; + } + } else if (q.length == 3) { + // check whether function or regex + if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) { + // call function (usually string mapper) + this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; + } else { + // sanitize match using given regex + this[q[0]] = match ? match.replace(q[1], q[2]) : undefined; + } + } else if (q.length == 4) { + this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; + } + } else { + this[q] = match ? match : undefined; + } + } + } + } + i += 2; + } + // console.log(this); + //return this; + }, + + str : function (str, map) { + + for (var i in map) { + // check if array + if (typeof map[i] === OBJ_TYPE && map[i].length > 0) { + for (var j = 0; j < map[i].length; j++) { + if (util.has(map[i][j], str)) { + return (i === UNKNOWN) ? undefined : i; + } + } + } else if (util.has(map[i], str)) { + return (i === UNKNOWN) ? undefined : i; + } + } + return str; + } + }; + + + /////////////// + // String map + ////////////// + + + var maps = { + + browser : { + oldsafari : { + version : { + '1.0' : '/8', + '1.2' : '/1', + '1.3' : '/3', + '2.0' : '/412', + '2.0.2' : '/416', + '2.0.3' : '/417', + '2.0.4' : '/419', + '?' : '/' + } + } + }, + + device : { + amazon : { + model : { + 'Fire Phone' : ['SD', 'KF'] + } + }, + sprint : { + model : { + 'Evo Shift 4G' : '7373KT' + }, + vendor : { + 'HTC' : 'APA', + 'Sprint' : 'Sprint' + } + } + }, + + os : { + windows : { + version : { + 'ME' : '4.90', + 'NT 3.11' : 'NT3.51', + 'NT 4.0' : 'NT4.0', + '2000' : 'NT 5.0', + 'XP' : ['NT 5.1', 'NT 5.2'], + 'Vista' : 'NT 6.0', + '7' : 'NT 6.1', + '8' : 'NT 6.2', + '8.1' : 'NT 6.3', + '10' : ['NT 6.4', 'NT 10.0'], + 'RT' : 'ARM' + } + } + } + }; + + + ////////////// + // Regex map + ///////////// + + + var regexes = { + + browser : [[ + + // Presto based + /(opera\smini)\/([\w\.-]+)/i, // Opera Mini + /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet + /(opera).+version\/([\w\.]+)/i, // Opera > 9.80 + /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80 + ], [NAME, VERSION], [ + + /(opios)[\/\s]+([\w\.]+)/i // Opera mini on iphone >= 8.0 + ], [[NAME, 'Opera Mini'], VERSION], [ + + /\s(opr)\/([\w\.]+)/i // Opera Webkit + ], [[NAME, 'Opera'], VERSION], [ + + // Mixed + /(kindle)\/([\w\.]+)/i, // Kindle + /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i, + // Lunascape/Maxthon/Netfront/Jasmine/Blazer + + // Trident based + /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i, + // Avant/IEMobile/SlimBrowser/Baidu + /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer + + // Webkit/KHTML based + /(rekonq)\/([\w\.]+)*/i, // Rekonq + /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i + // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser + ], [NAME, VERSION], [ + + /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11 + ], [[NAME, 'IE'], VERSION], [ + + /(edge)\/((\d+)?[\w\.]+)/i // Microsoft Edge + ], [NAME, VERSION], [ + + /(yabrowser)\/([\w\.]+)/i // Yandex + ], [[NAME, 'Yandex'], VERSION], [ + + /(puffin)\/([\w\.]+)/i // Puffin + ], [[NAME, 'Puffin'], VERSION], [ + + /((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i + // UCBrowser + ], [[NAME, 'UCBrowser'], VERSION], [ + + /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon + ], [[NAME, /_/g, ' '], VERSION], [ + + /(micromessenger)\/([\w\.]+)/i // WeChat + ], [[NAME, 'WeChat'], VERSION], [ + + /(QQ)\/([\d\.]+)/i // QQ, aka ShouQ + ], [NAME, VERSION], [ + + /m?(qqbrowser)[\/\s]?([\w\.]+)/i // QQBrowser + ], [NAME, VERSION], [ + + /xiaomi\/miuibrowser\/([\w\.]+)/i // MIUI Browser + ], [VERSION, [NAME, 'MIUI Browser']], [ + + /;fbav\/([\w\.]+);/i // Facebook App for iOS & Android + ], [VERSION, [NAME, 'Facebook']], [ + + /headlesschrome(?:\/([\w\.]+)|\s)/i // Chrome Headless + ], [VERSION, [NAME, 'Chrome Headless']], [ + + /\swv\).+(chrome)\/([\w\.]+)/i // Chrome WebView + ], [[NAME, /(.+)/, '$1 WebView'], VERSION], [ + + /((?:oculus|samsung)browser)\/([\w\.]+)/i + ], [[NAME, /(.+(?:g|us))(.+)/, '$1 $2'], VERSION], [ // Oculus / Samsung Browser + + /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i // Android Browser + ], [VERSION, [NAME, 'Android Browser']], [ + + /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i + // Chrome/OmniWeb/Arora/Tizen/Nokia + ], [NAME, VERSION], [ + + /(dolfin)\/([\w\.]+)/i // Dolphin + ], [[NAME, 'Dolphin'], VERSION], [ + + /((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS + ], [[NAME, 'Chrome'], VERSION], [ + + /(coast)\/([\w\.]+)/i // Opera Coast + ], [[NAME, 'Opera Coast'], VERSION], [ + + /fxios\/([\w\.-]+)/i // Firefox for iOS + ], [VERSION, [NAME, 'Firefox']], [ + + /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari + ], [VERSION, [NAME, 'Mobile Safari']], [ + + /version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile + ], [VERSION, NAME], [ + + /webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Google Search Appliance on iOS + ], [[NAME, 'GSA'], VERSION], [ + + /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0 + ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [ + + /(konqueror)\/([\w\.]+)/i, // Konqueror + /(webkit|khtml)\/([\w\.]+)/i + ], [NAME, VERSION], [ + + // Gecko based + /(navigator|netscape)\/([\w\.-]+)/i // Netscape + ], [[NAME, 'Netscape'], VERSION], [ + /(swiftfox)/i, // Swiftfox + /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i, + // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror + /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i, + // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix + /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla + + // Other + /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i, + // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir + /(links)\s\(([\w\.]+)/i, // Links + /(gobrowser)\/?([\w\.]+)*/i, // GoBrowser + /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser + /(mosaic)[\/\s]([\w\.]+)/i // Mosaic + ], [NAME, VERSION] + + /* ///////////////////// + // Media players BEGIN + //////////////////////// + + , [ + + /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i, // Generic Apple CoreMedia + /(coremedia) v((\d+)[\w\._]+)/i + ], [NAME, VERSION], [ + + /(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i // Aqualung/Lyssna/BSPlayer + ], [NAME, VERSION], [ + + /(ares|ossproxy)\s((\d+)[\w\.-]+)/i // Ares/OSSProxy + ], [NAME, VERSION], [ + + /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i, + // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC + // NSPlayer/PSP-InternetRadioPlayer/Videos + /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i, // Clementine/MPD + /(lg player|nexplayer)\s((\d+)[\d\.]+)/i, + /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i // NexPlayer/LG Player + ], [NAME, VERSION], [ + /(nexplayer)\s((\d+)[\w\.-]+)/i // Nexplayer + ], [NAME, VERSION], [ + + /(flrp)\/((\d+)[\w\.-]+)/i // Flip Player + ], [[NAME, 'Flip Player'], VERSION], [ + + /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i + // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit + ], [NAME], [ + + /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i + // Gstreamer + ], [NAME, VERSION], [ + + /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i, // HTC Streaming Player + /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i, + // Java/urllib/requests/wget/cURL + /(lavf)((\d+)[\d\.]+)/i // Lavf (FFMPEG) + ], [NAME, VERSION], [ + + /(htc_one_s)\/((\d+)[\d\.]+)/i // HTC One S + ], [[NAME, /_/g, ' '], VERSION], [ + + /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i + // MPlayer SVN + ], [NAME, VERSION], [ + + /(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i // MPlayer + ], [NAME, VERSION], [ + + /(mplayer)/i, // MPlayer (no other info) + /(yourmuze)/i, // YourMuze + /(media player classic|nero showtime)/i // Media Player Classic/Nero ShowTime + ], [NAME], [ + + /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i // Nero Home/Nero Scout + ], [NAME, VERSION], [ + + /(nokia\d+)\/((\d+)[\w\.-]+)/i // Nokia + ], [NAME, VERSION], [ + + /\s(songbird)\/((\d+)[\w\.-]+)/i // Songbird/Philips-Songbird + ], [NAME, VERSION], [ + + /(winamp)3 version ((\d+)[\w\.-]+)/i, // Winamp + /(winamp)\s((\d+)[\w\.-]+)/i, + /(winamp)mpeg\/((\d+)[\w\.-]+)/i + ], [NAME, VERSION], [ + + /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info) + // inlight radio + ], [NAME], [ + + /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i + // QuickTime/RealMedia/RadioApp/RadioClientApplication/ + // SoundTap/Totem/Stagefright/Streamium + ], [NAME, VERSION], [ + + /(smp)((\d+)[\d\.]+)/i // SMP + ], [NAME, VERSION], [ + + /(vlc) media player - version ((\d+)[\w\.]+)/i, // VLC Videolan + /(vlc)\/((\d+)[\w\.-]+)/i, + /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i, // XBMC/gvfs/Xine/XMMS/irapp + /(foobar2000)\/((\d+)[\d\.]+)/i, // Foobar2000 + /(itunes)\/((\d+)[\d\.]+)/i // iTunes + ], [NAME, VERSION], [ + + /(wmplayer)\/((\d+)[\w\.-]+)/i, // Windows Media Player + /(windows-media-player)\/((\d+)[\w\.-]+)/i + ], [[NAME, /-/g, ' '], VERSION], [ + + /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i + // Windows Media Server + ], [VERSION, [NAME, 'Windows']], [ + + /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i // RiseUP Radio Alarm + ], [NAME, VERSION], [ + + /(rad.io)\s((\d+)[\d\.]+)/i, // Rad.io + /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i + ], [[NAME, 'rad.io'], VERSION] + + ////////////////////// + // Media players END + ////////////////////*/ + + ], + + cpu : [[ + + /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64 + ], [[ARCHITECTURE, 'amd64']], [ + + /(ia32(?=;))/i // IA32 (quicktime) + ], [[ARCHITECTURE, util.lowerize]], [ + + /((?:i[346]|x)86)[;\)]/i // IA32 + ], [[ARCHITECTURE, 'ia32']], [ + + // PocketPC mistakenly identified as PowerPC + /windows\s(ce|mobile);\sppc;/i + ], [[ARCHITECTURE, 'arm']], [ + + /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC + ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [ + + /(sun4\w)[;\)]/i // SPARC + ], [[ARCHITECTURE, 'sparc']], [ + + /((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i + // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC + ], [[ARCHITECTURE, util.lowerize]] + ], + + device : [[ + + /\((ipad|playbook);[\w\s\);-]+(rim|apple)/i // iPad/PlayBook + ], [MODEL, VENDOR, [TYPE, TABLET]], [ + + /applecoremedia\/[\w\.]+ \((ipad)/ // iPad + ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [ + + /(apple\s{0,1}tv)/i // Apple TV + ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [ + + /(archos)\s(gamepad2?)/i, // Archos + /(hp).+(touchpad)/i, // HP TouchPad + /(hp).+(tablet)/i, // HP Tablet + /(kindle)\/([\w\.]+)/i, // Kindle + /\s(nook)[\w\s]+build\/(\w+)/i, // Nook + /(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i // Kindle Fire HD + ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [ + /(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i // Fire Phone + ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [ + + /\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone + ], [MODEL, VENDOR, [TYPE, MOBILE]], [ + /\((ip[honed|\s\w*]+);/i // iPod/iPhone + ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [ + + /(blackberry)[\s-]?(\w+)/i, // BlackBerry + /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i, + // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron + /(hp)\s([\w\s]+\w)/i, // HP iPAQ + /(asus)-?(\w+)/i // Asus + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + /\(bb10;\s(\w+)/i // BlackBerry 10 + ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [ + // Asus Tablets + /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i + ], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [ + + /(sony)\s(tablet\s[ps])\sbuild\//i, // Sony + /(sony)?(?:sgp.+)\sbuild\//i + ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [ + /android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i + ], [MODEL, [VENDOR, 'Sony'], [TYPE, MOBILE]], [ + + /\s(ouya)\s/i, // Ouya + /(nintendo)\s([wids3u]+)/i // Nintendo + ], [VENDOR, MODEL, [TYPE, CONSOLE]], [ + + /android.+;\s(shield)\sbuild/i // Nvidia + ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [ + + /(playstation\s[34portablevi]+)/i // Playstation + ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [ + + /(sprint\s(\w+))/i // Sprint Phones + ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [ + + /(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i // Lenovo tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i, // HTC + /(zte)-(\w+)*/i, // ZTE + /(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i + // Alcatel/GeeksPhone/Lenovo/Nexian/Panasonic/Sony + ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [ + + /(nexus\s9)/i // HTC Nexus 9 + ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [ + + /d\/huawei([\w\s-]+)[;\)]/i, + /(nexus\s6p)/i // Huawei + ], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [ + + /(microsoft);\s(lumia[\s\w]+)/i // Microsoft Lumia + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + + /[\s\(;](xbox(?:\sone)?)[\s\);]/i // Microsoft Xbox + ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [ + /(kin\.[onetw]{3})/i // Microsoft Kin + ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [ + + // Motorola + /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i, + /mot[\s-]?(\w+)*/i, + /(XT\d{3,4}) build\//i, + /(nexus\s6)/i + ], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [ + /android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i + ], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [ + + /hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i // HbbTV devices + ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [ + + /hbbtv.+maple;(\d+)/i + ], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [ + + /\(dtv[\);].+(aquos)/i // Sharp + ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [ + + /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i, + /((SM-T\w+))/i + ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [ // Samsung + /smart-tv.+(samsung)/i + ], [VENDOR, [TYPE, SMARTTV], MODEL], [ + /((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i, + /(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i, + /sec-((sgh\w+))/i + ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [ + + /sie-(\w+)*/i // Siemens + ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [ + + /(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia + /(nokia)[\s_-]?([\w-]+)*/i + ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [ + + /android\s3\.[\s\w;-]{10}(a\d{3})/i // Acer + ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [ + + /android.+([vl]k\-?\d{3})\s+build/i // LG Tablet + ], [MODEL, [VENDOR, 'LG'], [TYPE, TABLET]], [ + /android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i // LG Tablet + ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [ + /(lg) netcast\.tv/i // LG SmartTV + ], [VENDOR, MODEL, [TYPE, SMARTTV]], [ + /(nexus\s[45])/i, // LG + /lg[e;\s\/-]+(\w+)*/i, + /android.+lg(\-?[\d\w]+)\s+build/i + ], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [ + + /android.+(ideatab[a-z0-9\-\s]+)/i // Lenovo + ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [ + + /linux;.+((jolla));/i // Jolla + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + + /((pebble))app\/[\d\.]+\s/i // Pebble + ], [VENDOR, MODEL, [TYPE, WEARABLE]], [ + + /android.+;\s(oppo)\s?([\w\s]+)\sbuild/i // OPPO + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + + /crkey/i // Google Chromecast + ], [[MODEL, 'Chromecast'], [VENDOR, 'Google']], [ + + /android.+;\s(glass)\s\d/i // Google Glass + ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [ + + /android.+;\s(pixel c)\s/i // Google Pixel C + ], [MODEL, [VENDOR, 'Google'], [TYPE, TABLET]], [ + + /android.+;\s(pixel xl|pixel)\s/i // Google Pixel + ], [MODEL, [VENDOR, 'Google'], [TYPE, MOBILE]], [ + + /android.+(\w+)\s+build\/hm\1/i, // Xiaomi Hongmi 'numeric' models + /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Hongmi + /android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Mi + /android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i // Redmi Phones + ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [ + /android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i // Mi Pad tablets + ],[[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, TABLET]], [ + /android.+;\s(m[1-5]\snote)\sbuild/i // Meizu Tablet + ], [MODEL, [VENDOR, 'Meizu'], [TYPE, TABLET]], [ + + /android.+a000(1)\s+build/i // OnePlus + ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [ + + /android.+[;\/]\s*(RCT[\d\w]+)\s+build/i // RCA Tablets + ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Venue[\d\s]*)\s+build/i // Dell Venue Tablets + ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i // Verizon Tablet + ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [ + + /android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i // Barnes & Noble Tablet + ], [[VENDOR, 'Barnes & Noble'], MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i // Barnes & Noble Tablet + ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i // ZTE K Series Tablet + ], [[VENDOR, 'ZTE'], MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*(gen\d{3})\s+build.*49h/i // Swiss GEN Mobile + ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [ + + /android.+[;\/]\s*(zur\d{3})\s+build/i // Swiss ZUR Tablet + ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i // Zeki Tablets + ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [ + + /(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i, + /android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i // Dragon Touch Tablet + ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*(NS-?.+)\s+build/i // Insignia Tablets + ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*((NX|Next)-?.+)\s+build/i // NextBook Tablets + ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i + ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [ // Voice Xtreme Phones + + /android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i // LvTel Phones + ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [ + + /android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i // Envizen Tablets + ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i // Le Pan Tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i // MachSpeed Tablets + ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [ + + /android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i // Trinity Tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /android.+[;\/]\s*TU_(1491)\s+build/i // Rotor Tablets + ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [ + + /android.+(KS(.+))\s+build/i // Amazon Kindle Tablets + ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [ + + /android.+(Gigaset)[\s\-]+(Q.+)\s+build/i // Gigaset Tablets + ], [VENDOR, MODEL, [TYPE, TABLET]], [ + + /\s(tablet|tab)[;\/]/i, // Unidentifiable Tablet + /\s(mobile)(?:[;\/]|\ssafari)/i // Unidentifiable Mobile + ], [[TYPE, util.lowerize], VENDOR, MODEL], [ + + /(android.+)[;\/].+build/i // Generic Android Device + ], [MODEL, [VENDOR, 'Generic']] + + + /*////////////////////////// + // TODO: move to string map + //////////////////////////// + + /(C6603)/i // Sony Xperia Z C6603 + ], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ + /(C6903)/i // Sony Xperia Z 1 + ], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ + + /(SM-G900[F|H])/i // Samsung Galaxy S5 + ], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-G7102)/i // Samsung Galaxy Grand 2 + ], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-G530H)/i // Samsung Galaxy Grand Prime + ], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-G313HZ)/i // Samsung Galaxy V + ], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-T805)/i // Samsung Galaxy Tab S 10.5 + ], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ + /(SM-G800F)/i // Samsung Galaxy S5 Mini + ], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ + /(SM-T311)/i // Samsung Galaxy Tab 3 8.0 + ], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ + + /(T3C)/i // Advan Vandroid T3C + ], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [ + /(ADVAN T1J\+)/i // Advan Vandroid T1J+ + ], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [ + /(ADVAN S4A)/i // Advan Vandroid S4A + ], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [ + + /(V972M)/i // ZTE V972M + ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [ + + /(i-mobile)\s(IQ\s[\d\.]+)/i // i-mobile IQ + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + /(IQ6.3)/i // i-mobile IQ IQ 6.3 + ], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ + /(i-mobile)\s(i-style\s[\d\.]+)/i // i-mobile i-STYLE + ], [VENDOR, MODEL, [TYPE, MOBILE]], [ + /(i-STYLE2.1)/i // i-mobile i-STYLE 2.1 + ], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ + + /(mobiistar touch LAI 512)/i // mobiistar touch LAI 512 + ], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [ + + ///////////// + // END TODO + ///////////*/ + + ], + + engine : [[ + + /windows.+\sedge\/([\w\.]+)/i // EdgeHTML + ], [VERSION, [NAME, 'EdgeHTML']], [ + + /(presto)\/([\w\.]+)/i, // Presto + /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m + /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links + /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab + ], [NAME, VERSION], [ + + /rv\:([\w\.]+).*(gecko)/i // Gecko + ], [VERSION, NAME] + ], + + os : [[ + + // Windows based + /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes) + ], [NAME, VERSION], [ + /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT + /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i, // Windows Phone + /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i + ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ + /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i + ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ + + // Mobile/Embedded OS + /\((bb)(10);/i // BlackBerry 10 + ], [[NAME, 'BlackBerry'], VERSION], [ + /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry + /(tizen)[\/\s]([\w\.]+)/i, // Tizen + /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i, + // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki + /linux;.+(sailfish);/i // Sailfish OS + ], [NAME, VERSION], [ + /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian + ], [[NAME, 'Symbian'], VERSION], [ + /\((series40);/i // Series 40 + ], [NAME], [ + /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS + ], [[NAME, 'Firefox OS'], VERSION], [ + + // Console + /(nintendo|playstation)\s([wids34portablevu]+)/i, // Nintendo/Playstation + + // GNU/Linux based + /(mint)[\/\s\(]?(\w+)*/i, // Mint + /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux + /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i, + // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware + // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus + /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux + /(gnu)\s?([\w\.]+)*/i // GNU + ], [NAME, VERSION], [ + + /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS + ], [[NAME, 'Chromium OS'], VERSION],[ + + // Solaris + /(sunos)\s?([\w\.]+\d)*/i // Solaris + ], [[NAME, 'Solaris'], VERSION], [ + + // BSD based + /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly + ], [NAME, VERSION],[ + + /(haiku)\s(\w+)/i // Haiku + ], [NAME, VERSION],[ + + /cfnetwork\/.+darwin/i, + /ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i // iOS + ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [ + + /(mac\sos\sx)\s?([\w\s\.]+\w)*/i, + /(macintosh|mac(?=_powerpc)\s)/i // Mac OS + ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [ + + // Other + /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i, // Solaris + /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX + /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i, + // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS + /(unix)\s?([\w\.]+)*/i // UNIX + ], [NAME, VERSION] + ] + }; + + + ///////////////// + // Constructor + //////////////// + /* + var Browser = function (name, version) { + this[NAME] = name; + this[VERSION] = version; + }; + var CPU = function (arch) { + this[ARCHITECTURE] = arch; + }; + var Device = function (vendor, model, type) { + this[VENDOR] = vendor; + this[MODEL] = model; + this[TYPE] = type; + }; + var Engine = Browser; + var OS = Browser; + */ + var UAParser = function (uastring, extensions) { + + if (typeof uastring === 'object') { + extensions = uastring; + uastring = undefined; + } + + if (!(this instanceof UAParser)) { + return new UAParser(uastring, extensions).getResult(); + } + + var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); + var rgxmap = extensions ? util.extend(regexes, extensions) : regexes; + //var browser = new Browser(); + //var cpu = new CPU(); + //var device = new Device(); + //var engine = new Engine(); + //var os = new OS(); + + this.getBrowser = function () { + var browser = { name: undefined, version: undefined }; + mapper.rgx.call(browser, ua, rgxmap.browser); + browser.major = util.major(browser.version); // deprecated + return browser; + }; + this.getCPU = function () { + var cpu = { architecture: undefined }; + mapper.rgx.call(cpu, ua, rgxmap.cpu); + return cpu; + }; + this.getDevice = function () { + var device = { vendor: undefined, model: undefined, type: undefined }; + mapper.rgx.call(device, ua, rgxmap.device); + return device; + }; + this.getEngine = function () { + var engine = { name: undefined, version: undefined }; + mapper.rgx.call(engine, ua, rgxmap.engine); + return engine; + }; + this.getOS = function () { + var os = { name: undefined, version: undefined }; + mapper.rgx.call(os, ua, rgxmap.os); + return os; + }; + this.getResult = function () { + return { + ua : this.getUA(), + browser : this.getBrowser(), + engine : this.getEngine(), + os : this.getOS(), + device : this.getDevice(), + cpu : this.getCPU() + }; + }; + this.getUA = function () { + return ua; + }; + this.setUA = function (uastring) { + ua = uastring; + //browser = new Browser(); + //cpu = new CPU(); + //device = new Device(); + //engine = new Engine(); + //os = new OS(); + return this; + }; + return this; + }; + + UAParser.VERSION = LIBVERSION; + UAParser.BROWSER = { + NAME : NAME, + MAJOR : MAJOR, // deprecated + VERSION : VERSION + }; + UAParser.CPU = { + ARCHITECTURE : ARCHITECTURE + }; + UAParser.DEVICE = { + MODEL : MODEL, + VENDOR : VENDOR, + TYPE : TYPE, + CONSOLE : CONSOLE, + MOBILE : MOBILE, + SMARTTV : SMARTTV, + TABLET : TABLET, + WEARABLE: WEARABLE, + EMBEDDED: EMBEDDED + }; + UAParser.ENGINE = { + NAME : NAME, + VERSION : VERSION + }; + UAParser.OS = { + NAME : NAME, + VERSION : VERSION + }; + //UAParser.Utils = util; + + /////////// + // Export + ////////// + + + // check js environment + if ('object' !== UNDEF_TYPE) { + // nodejs env + if ('object' !== UNDEF_TYPE && module.exports) { + exports = module.exports = UAParser; + } + // TODO: test!!!!!!!! + /* + if (require && require.main === module && process) { + // cli + var jsonize = function (arr) { + var res = []; + for (var i in arr) { + res.push(new UAParser(arr[i]).getResult()); + } + process.stdout.write(JSON.stringify(res, null, 2) + '\n'); + }; + if (process.stdin.isTTY) { + // via args + jsonize(process.argv.slice(2)); + } else { + // via pipe + var str = ''; + process.stdin.on('readable', function() { + var read = process.stdin.read(); + if (read !== null) { + str += read; + } + }); + process.stdin.on('end', function () { + jsonize(str.replace(/\n$/, '').split('\n')); + }); + } + } + */ + exports.UAParser = UAParser; + } else { + // requirejs env (optional) + if (typeof(undefined) === FUNC_TYPE && undefined.amd) { + undefined(function () { + return UAParser; + }); + } else if (window) { + // browser env + window.UAParser = UAParser; + } + } + + // jQuery/Zepto specific (optional) + // Note: + // In AMD env the global scope should be kept clean, but jQuery is an exception. + // jQuery always exports to global scope, unless jQuery.noConflict(true) is used, + // and we should catch that. + var $ = window && (window.jQuery || window.Zepto); + if (typeof $ !== UNDEF_TYPE) { + var parser = new UAParser(); + $.ua = parser.getResult(); + $.ua.get = function () { + return parser.getUA(); + }; + $.ua.set = function (uastring) { + parser.setUA(uastring); + var result = parser.getResult(); + for (var prop in result) { + $.ua[prop] = result[prop]; + } + }; + } + +})(typeof window === 'object' ? window : commonjsGlobal$$1); +}); + +exports.Log = Log; +exports.UAParser = uaParser; +exports.genTraversalHandler = genTraversalHandler; +exports.deepClone = deepClone; +exports.deepAssign = deepAssign; +exports.camelize = camelize; +exports.hypenate = hypenate; +exports.bind = bind; +exports.uuid = uuid; +exports.S4 = S4; +exports.rand = rand; +exports.getDeepProperty = getDeepProperty; +exports.defined = defined$1; +exports.isVoid = isVoid; +exports.isArray = isArray; +exports.isFunction = isFunction; +exports.isObject = isObject$1; +exports.isNumber = isNumber; +exports.isNumeric = isNumeric; +exports.isInteger = isInteger; +exports.isEmpty = isEmpty; +exports.isEvent = isEvent; +exports.isBlob = isBlob; +exports.isFile = isFile; +exports.isDate = isDate; +exports.isString = isString; +exports.isBoolean = isBoolean; +exports.isPromise = isPromise; +exports.isPrimitive = isPrimitive; +exports.isUrl = isUrl; +exports.isNode = isNode; +exports.isElement = isElement; +exports.isChildNode = isChildNode; +exports.isPosterityNode = isPosterityNode; +exports.isHTMLString = isHTMLString; +exports.isError = isError; +exports.isRegExp = isRegExp; +exports.inBrowser = inBrowser; +exports.makeArray = makeArray; +exports.transObjectAttrIntoArray = transObjectAttrIntoArray; +exports.runRejectableQueue = runRejectableQueue; +exports.runStoppableQueue = runStoppableQueue; +exports.decodeUTF8 = decodeUTF8; +exports.debounce = debounce; +exports.throttle = throttle; +exports.raf = raf; +exports.caf = caf; +exports.strRepeat = strRepeat; +exports.formatTime = formatTime; +exports.appendCSS = appendCSS; +exports.formatDate = formatDate; +exports.getLocalStorage = getLocalStorage; +exports.setLocalStorage = setLocalStorage; +exports.emitEventCache = emitEventCache; +exports.addEventCache = addEventCache; +exports.removeEventCache = removeEventCache; +exports.CustEvent = CustEvent; +exports.getAttr = getAttr; +exports.setAttr = setAttr; +exports.addClassName = addClassName; +exports.removeClassName = removeClassName; +exports.hasClassName = hasClassName; +exports.removeEvent = removeEvent; +exports.addEvent = addEvent; +exports.addDelegate = addDelegate; +exports.removeDelegate = removeDelegate; +exports.getStyle = getStyle; +exports.setStyle = setStyle; +exports.query = query; +exports.removeEl = removeEl; +exports.findParents = findParents; +exports.$ = $; +exports.NodeWrap = NodeWrap; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19))); + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }) +/******/ ])["default"]; +}); +}); + +var chimeeKernelFlv = unwrapExports(lib$2); + +function styleInject(css, ref) { + if ( ref === void 0 ) ref = {}; + var insertAt = ref.insertAt; + + if (!css || typeof document === 'undefined') { return; } + + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + + if (insertAt === 'top') { + if (head.firstChild) { + head.insertBefore(style, head.firstChild); + } else { + head.appendChild(style); + } + } else { + head.appendChild(style); + } + + if (style.styleSheet) { + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } +} + +var css = ".chimee-container container{position:relative;display:block;width:100%;height:100%}.chimee-container video{display:block;width:100%;height:100%;background:#000;outline:0}.chimee-container video:focus{outline:0}.chimee-container chimee-center-state-loading{box-sizing:initial}"; +styleInject(css); + +// import 'babel-polyfill'; + +Chimee.install(chimeeControl); +Chimee.install(chimeeCenterState); +Chimee.install(contextmenuConf); +Chimee.install(index$1); + +var ChimeePlayer = function (_Chimee) { + _inherits(ChimeePlayer, _Chimee); + + function ChimeePlayer(config) { + _classCallCheck(this, ChimeePlayer); + + if (!isObject(config)) throw new TypeError('You must pass an Object as config when you new ChimeePlayer'); + + // 添加UI插件 + config.plugin = config.plugin || config.plugins; + if (!isArray(config.plugin)) config.plugin = []; + var innerPlugins = [chimeeControl.name, chimeeCenterState.name, contextmenuConf.name, index$1.name]; + var configPluginNames = config.plugin.map(function (item) { + return isObject(item) ? item.name : item; + }); + innerPlugins.forEach(function (name) { + if (configPluginNames.indexOf(name) > -1) return; + config.plugin.push(name); + }); + + // 添加解码器 + if (!isObject(config.preset)) { + config.preset = { + hls: Hls, + flv: chimeeKernelFlv + }; + } + + // 右键菜单的播放暂停 + var _this = _possibleConstructorReturn(this, (ChimeePlayer.__proto__ || _Object$getPrototypeOf(ChimeePlayer)).call(this, config)); + + _this.on('play', function () { + return _this.chimeeContextmenu.updatemenu([{ text: '暂停', action: 'pause' }]); + }); + _this.on('pause', function () { + return _this.chimeeContextmenu.updatemenu([{ text: '播放', action: 'play' }]); + }); + return _this; + } + + return ChimeePlayer; +}(Chimee); +// 暴露浮层工厂方法 + + +ChimeePlayer.popupFactory = popupFactory; + +return ChimeePlayer; + +}))); diff --git a/libs/chimee-player/1.3.1/chimee-player.js b/libs/chimee-player/1.3.1/chimee-player.js new file mode 100644 index 000000000..c1588a2ae --- /dev/null +++ b/libs/chimee-player/1.3.1/chimee-player.js @@ -0,0 +1,84 @@ + +/** chimeePlayer + * chimee-player v1.3.1 + * (c) 2017 huzunjie + * Released under MIT + */ + +'use strict'; + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var styleInject = _interopDefault(require('../node_modules/style-inject/dist/style-inject.es.js')); +var _Object$getPrototypeOf = _interopDefault(require('babel-runtime/core-js/object/get-prototype-of')); +var _classCallCheck = _interopDefault(require('babel-runtime/helpers/classCallCheck')); +var _possibleConstructorReturn = _interopDefault(require('babel-runtime/helpers/possibleConstructorReturn')); +var _inherits = _interopDefault(require('babel-runtime/helpers/inherits')); +var Chimee = _interopDefault(require('chimee')); +var chimeeHelper = require('chimee-helper'); +var chimeeControl = _interopDefault(require('chimee-plugin-controlbar')); +var popupFactory = _interopDefault(require('chimee-plugin-popup')); +var chimeeContextmenu = _interopDefault(require('chimee-plugin-contextmenu')); +var chimeeLog = _interopDefault(require('chimee-plugin-log')); +var chimeeCenterState = _interopDefault(require('chimee-plugin-center-state')); +var chimeeKernelHls = _interopDefault(require('chimee-kernel-hls')); +var chimeeKernelFlv = _interopDefault(require('chimee-kernel-flv')); + +var css = ".chimee-container container{position:relative;display:block;width:100%;height:100%}.chimee-container video{display:block;width:100%;height:100%;background:#000;outline:0}.chimee-container video:focus{outline:0}.chimee-container chimee-center-state-loading{box-sizing:initial}"; +styleInject(css); + +// import 'babel-polyfill'; + +Chimee.install(chimeeControl); +Chimee.install(chimeeCenterState); +Chimee.install(chimeeContextmenu); +Chimee.install(chimeeLog); + +var ChimeePlayer = function (_Chimee) { + _inherits(ChimeePlayer, _Chimee); + + function ChimeePlayer(config) { + _classCallCheck(this, ChimeePlayer); + + if (!chimeeHelper.isObject(config)) throw new TypeError('You must pass an Object as config when you new ChimeePlayer'); + + // 添加UI插件 + config.plugin = config.plugin || config.plugins; + if (!chimeeHelper.isArray(config.plugin)) config.plugin = []; + var innerPlugins = [chimeeControl.name, chimeeCenterState.name, chimeeContextmenu.name, chimeeLog.name]; + var configPluginNames = config.plugin.map(function (item) { + return chimeeHelper.isObject(item) ? item.name : item; + }); + innerPlugins.forEach(function (name) { + if (configPluginNames.indexOf(name) > -1) return; + config.plugin.push(name); + }); + + // 添加解码器 + if (!chimeeHelper.isObject(config.preset)) { + config.preset = { + hls: chimeeKernelHls, + flv: chimeeKernelFlv + }; + } + + // 右键菜单的播放暂停 + var _this = _possibleConstructorReturn(this, (ChimeePlayer.__proto__ || _Object$getPrototypeOf(ChimeePlayer)).call(this, config)); + + _this.on('play', function () { + return _this.chimeeContextmenu.updatemenu([{ text: '暂停', action: 'pause' }]); + }); + _this.on('pause', function () { + return _this.chimeeContextmenu.updatemenu([{ text: '播放', action: 'play' }]); + }); + return _this; + } + + return ChimeePlayer; +}(Chimee); +// 暴露浮层工厂方法 + + +ChimeePlayer.popupFactory = popupFactory; + +module.exports = ChimeePlayer; diff --git a/libs/chimee-player/1.3.1/chimee-player.min.js b/libs/chimee-player/1.3.1/chimee-player.min.js new file mode 100644 index 000000000..d92ce8c1a --- /dev/null +++ b/libs/chimee-player/1.3.1/chimee-player.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.ChimeePlayer=t()}(this,function(){"use strict";var commonjsGlobal="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function unwrapExports(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var toString={}.toString,_cof=function(e){return toString.call(e).slice(8,-1)},_iobject=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==_cof(e)?e.split(""):Object(e)},_defined=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},_toIobject=function(e){return _iobject(_defined(e))},f={}.propertyIsEnumerable,_objectPie={f:f},_propertyDesc=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_isObject=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_toPrimitive=function(e,t){if(!_isObject(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!_isObject(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!_isObject(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!_isObject(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},hasOwnProperty={}.hasOwnProperty,_has=function(e,t){return hasOwnProperty.call(e,t)},_fails=function(e){try{return!!e()}catch(e){return!0}},_descriptors=!_fails(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),_global=createCommonjsModule(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)}),document$1=_global.document,is=_isObject(document$1)&&_isObject(document$1.createElement),_domCreate=function(e){return is?document$1.createElement(e):{}},_ie8DomDefine=!_descriptors&&!_fails(function(){return 7!=Object.defineProperty(_domCreate("div"),"a",{get:function(){return 7}}).a}),gOPD=Object.getOwnPropertyDescriptor,f$1=_descriptors?gOPD:function(e,t){if(e=_toIobject(e),t=_toPrimitive(t,!0),_ie8DomDefine)try{return gOPD(e,t)}catch(e){}if(_has(e,t))return _propertyDesc(!_objectPie.f.call(e,t),e[t])},_objectGopd={f:f$1},_core=createCommonjsModule(function(e){var t=e.exports={version:"2.5.3"};"number"==typeof __e&&(__e=t)}),_core_1=_core.version,_aFunction=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx=function(e,t,r){if(_aFunction(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)}},_anObject=function(e){if(!_isObject(e))throw TypeError(e+" is not an object!");return e},dP=Object.defineProperty,f$2=_descriptors?Object.defineProperty:function(e,t,r){if(_anObject(e),t=_toPrimitive(t,!0),_anObject(r),_ie8DomDefine)try{return dP(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},_objectDp={f:f$2},_hide=_descriptors?function(e,t,r){return _objectDp.f(e,t,_propertyDesc(1,r))}:function(e,t,r){return e[t]=r,e},PROTOTYPE="prototype",$export=function(e,t,r){var i,n,o,a=e&$export.F,s=e&$export.G,u=e&$export.S,c=e&$export.P,l=e&$export.B,d=e&$export.W,f=s?_core:_core[t]||(_core[t]={}),h=f[PROTOTYPE],p=s?_global:u?_global[t]:(_global[t]||{})[PROTOTYPE];for(i in s&&(r=t),r)(n=!a&&p&&void 0!==p[i])&&i in f||(o=n?p[i]:r[i],f[i]=s&&"function"!=typeof p[i]?r[i]:l&&n?_ctx(o,_global):d&&p[i]==o?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}(o):c&&"function"==typeof o?_ctx(Function.call,o):o,c&&((f.virtual||(f.virtual={}))[i]=o,e&$export.R&&h&&!h[i]&&_hide(h,i,o)))};$export.F=1,$export.G=2,$export.S=4,$export.P=8,$export.B=16,$export.W=32,$export.U=64,$export.R=128;var _export=$export,_objectSap=function(e,t){var r=(_core.Object||{})[e]||Object[e],i={};i[e]=t(r),_export(_export.S+_export.F*_fails(function(){r(1)}),"Object",i)},$getOwnPropertyDescriptor=_objectGopd.f;_objectSap("getOwnPropertyDescriptor",function(){return function(e,t){return $getOwnPropertyDescriptor(_toIobject(e),t)}});var $Object=_core.Object,getOwnPropertyDescriptor=function(e,t){return $Object.getOwnPropertyDescriptor(e,t)},getOwnPropertyDescriptor$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertyDescriptor,__esModule:!0}}),_Object$getOwnPropertyDescriptor=unwrapExports(getOwnPropertyDescriptor$1),ceil=Math.ceil,floor=Math.floor,_toInteger=function(e){return isNaN(e=+e)?0:(e>0?floor:ceil)(e)},_stringAt=function(e){return function(t,r){var i,n,o=String(_defined(t)),a=_toInteger(r),s=o.length;return a<0||a>=s?e?"":void 0:(i=o.charCodeAt(a))<55296||i>56319||a+1===s||(n=o.charCodeAt(a+1))<56320||n>57343?e?o.charAt(a):i:e?o.slice(a,a+2):n-56320+(i-55296<<10)+65536}},_library=!0,_redefine=_hide,_iterators={},min=Math.min,_toLength=function(e){return e>0?min(_toInteger(e),9007199254740991):0},max=Math.max,min$1=Math.min,_toAbsoluteIndex=function(e,t){return(e=_toInteger(e))<0?max(e+t,0):min$1(e,t)},_arrayIncludes=function(e){return function(t,r,i){var n,o=_toIobject(t),a=_toLength(o.length),s=_toAbsoluteIndex(i,a);if(e&&r!=r){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===r)return e||s||0;return!e&&-1}},SHARED="__core-js_shared__",store=_global[SHARED]||(_global[SHARED]={}),_shared=function(e){return store[e]||(store[e]={})},id=0,px=Math.random(),_uid=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id+px).toString(36))},shared=_shared("keys"),_sharedKey=function(e){return shared[e]||(shared[e]=_uid(e))},arrayIndexOf=_arrayIncludes(!1),IE_PROTO=_sharedKey("IE_PROTO"),_objectKeysInternal=function(e,t){var r,i=_toIobject(e),n=0,o=[];for(r in i)r!=IE_PROTO&&_has(i,r)&&o.push(r);for(;t.length>n;)_has(i,r=t[n++])&&(~arrayIndexOf(o,r)||o.push(r));return o},_enumBugKeys="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),_objectKeys=Object.keys||function(e){return _objectKeysInternal(e,_enumBugKeys)},_objectDps=_descriptors?Object.defineProperties:function(e,t){_anObject(e);for(var r,i=_objectKeys(t),n=i.length,o=0;n>o;)_objectDp.f(e,r=i[o++],t[r]);return e},document$2=_global.document,_html=document$2&&document$2.documentElement,IE_PROTO$1=_sharedKey("IE_PROTO"),Empty=function(){},PROTOTYPE$1="prototype",createDict=function(){var e,t=_domCreate("iframe"),r=_enumBugKeys.length;for(t.style.display="none",_html.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),createDict=e.F;r--;)delete createDict[PROTOTYPE$1][_enumBugKeys[r]];return createDict()},_objectCreate=Object.create||function(e,t){var r;return null!==e?(Empty[PROTOTYPE$1]=_anObject(e),r=new Empty,Empty[PROTOTYPE$1]=null,r[IE_PROTO$1]=e):r=createDict(),void 0===t?r:_objectDps(r,t)},_wks=createCommonjsModule(function(e){var t=_shared("wks"),r=_global.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:_uid)("Symbol."+e))}).store=t}),def=_objectDp.f,TAG=_wks("toStringTag"),_setToStringTag=function(e,t,r){e&&!_has(e=r?e:e.prototype,TAG)&&def(e,TAG,{configurable:!0,value:t})},IteratorPrototype={};_hide(IteratorPrototype,_wks("iterator"),function(){return this});var _iterCreate=function(e,t,r){e.prototype=_objectCreate(IteratorPrototype,{next:_propertyDesc(1,r)}),_setToStringTag(e,t+" Iterator")},_toObject=function(e){return Object(_defined(e))},IE_PROTO$2=_sharedKey("IE_PROTO"),ObjectProto=Object.prototype,_objectGpo=Object.getPrototypeOf||function(e){return e=_toObject(e),_has(e,IE_PROTO$2)?e[IE_PROTO$2]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ObjectProto:null},ITERATOR=_wks("iterator"),BUGGY=!([].keys&&"next"in[].keys()),FF_ITERATOR="@@iterator",KEYS="keys",VALUES="values",returnThis=function(){return this},_iterDefine=function(e,t,r,i,n,o,a){_iterCreate(r,t,i);var s,u,c,l=function(e){if(!BUGGY&&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)}},d=t+" Iterator",f=n==VALUES,h=!1,p=e.prototype,m=p[ITERATOR]||p[FF_ITERATOR]||n&&p[n],v=!BUGGY&&m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=_objectGpo(y.call(new e)))!==Object.prototype&&c.next&&(_setToStringTag(c,d,!0),_library||_has(c,ITERATOR)||_hide(c,ITERATOR,returnThis)),f&&m&&m.name!==VALUES&&(h=!0,v=function(){return m.call(this)}),_library&&!a||!BUGGY&&!h&&p[ITERATOR]||_hide(p,ITERATOR,v),_iterators[t]=v,_iterators[d]=returnThis,n)if(s={values:f?v:l(VALUES),keys:o?v:l(KEYS),entries:g},a)for(u in s)u in p||_redefine(p,u,s[u]);else _export(_export.P+_export.F*(BUGGY||h),t,s);return s},$at=_stringAt(!0);_iterDefine(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=$at(t,r),this._i+=e.length,{value:e,done:!1})});var _iterStep=function(e,t){return{value:t,done:!!e}},es6_array_iterator=_iterDefine(Array,"Array",function(e,t){this._t=_toIobject(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,_iterStep(1)):_iterStep(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values");_iterators.Arguments=_iterators.Array;for(var TO_STRING_TAG=_wks("toStringTag"),DOMIterables="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),i=0;i<DOMIterables.length;i++){var NAME=DOMIterables[i],Collection=_global[NAME],proto=Collection&&Collection.prototype;proto&&!proto[TO_STRING_TAG]&&_hide(proto,TO_STRING_TAG,NAME),_iterators[NAME]=_iterators.Array}var _redefineAll=function(e,t,r){for(var i in t)r&&e[i]?e[i]=t[i]:_hide(e,i,t[i]);return e},_anInstance=function(e,t,r,i){if(!(e instanceof t)||void 0!==i&&i in e)throw TypeError(r+": incorrect invocation!");return e},_iterCall=function(e,t,r,i){try{return i?t(_anObject(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&_anObject(n.call(e)),t}},ITERATOR$1=_wks("iterator"),ArrayProto=Array.prototype,_isArrayIter=function(e){return void 0!==e&&(_iterators.Array===e||ArrayProto[ITERATOR$1]===e)},TAG$1=_wks("toStringTag"),ARG="Arguments"==_cof(function(){return arguments}()),tryGet=function(e,t){try{return e[t]}catch(e){}},_classof=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=tryGet(t=Object(e),TAG$1))?r:ARG?_cof(t):"Object"==(i=_cof(t))&&"function"==typeof t.callee?"Arguments":i},ITERATOR$2=_wks("iterator"),core_getIteratorMethod=_core.getIteratorMethod=function(e){if(void 0!=e)return e[ITERATOR$2]||e["@@iterator"]||_iterators[_classof(e)]},_forOf=createCommonjsModule(function(e){var t={},r={},i=e.exports=function(e,i,n,o,a){var s,u,c,l,d=a?function(){return e}:core_getIteratorMethod(e),f=_ctx(n,o,i?2:1),h=0;if("function"!=typeof d)throw TypeError(e+" is not iterable!");if(_isArrayIter(d)){for(s=_toLength(e.length);s>h;h++)if((l=i?f(_anObject(u=e[h])[0],u[1]):f(e[h]))===t||l===r)return l}else for(c=d.call(e);!(u=c.next()).done;)if((l=_iterCall(c,f,u.value,i))===t||l===r)return l};i.BREAK=t,i.RETURN=r}),SPECIES=_wks("species"),_setSpecies=function(e){var t="function"==typeof _core[e]?_core[e]:_global[e];_descriptors&&t&&!t[SPECIES]&&_objectDp.f(t,SPECIES,{configurable:!0,get:function(){return this}})},_meta=createCommonjsModule(function(e){var t=_uid("meta"),r=_objectDp.f,i=0,n=Object.isExtensible||function(){return!0},o=!_fails(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!_isObject(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!_has(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!_has(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!_has(e,t)&&a(e),e}}}),_meta_1=_meta.KEY,_meta_2=_meta.NEED,_meta_3=_meta.fastKey,_meta_4=_meta.getWeak,_meta_5=_meta.onFreeze,_validateCollection=function(e,t){if(!_isObject(e)||e._t!==t)throw TypeError("Incompatible receiver, "+t+" required!");return e},dP$1=_objectDp.f,fastKey=_meta.fastKey,SIZE=_descriptors?"_s":"size",getEntry=function(e,t){var r,i=fastKey(t);if("F"!==i)return e._i[i];for(r=e._f;r;r=r.n)if(r.k==t)return r},_collectionStrong={getConstructor:function(e,t,r,i){var n=e(function(e,o){_anInstance(e,n,t,"_i"),e._t=t,e._i=_objectCreate(null),e._f=void 0,e._l=void 0,e[SIZE]=0,void 0!=o&&_forOf(o,r,e[i],e)});return _redefineAll(n.prototype,{clear:function(){for(var e=_validateCollection(this,t),r=e._i,i=e._f;i;i=i.n)i.r=!0,i.p&&(i.p=i.p.n=void 0),delete r[i.i];e._f=e._l=void 0,e[SIZE]=0},delete:function(e){var r=_validateCollection(this,t),i=getEntry(r,e);if(i){var n=i.n,o=i.p;delete r._i[i.i],i.r=!0,o&&(o.n=n),n&&(n.p=o),r._f==i&&(r._f=n),r._l==i&&(r._l=o),r[SIZE]--}return!!i},forEach:function(e){_validateCollection(this,t);for(var r,i=_ctx(e,arguments.length>1?arguments[1]:void 0,3);r=r?r.n:this._f;)for(i(r.v,r.k,this);r&&r.r;)r=r.p},has:function(e){return!!getEntry(_validateCollection(this,t),e)}}),_descriptors&&dP$1(n.prototype,"size",{get:function(){return _validateCollection(this,t)[SIZE]}}),n},def:function(e,t,r){var i,n,o=getEntry(e,t);return o?o.v=r:(e._l=o={i:n=fastKey(t,!0),k:t,v:r,p:i=e._l,n:void 0,r:!1},e._f||(e._f=o),i&&(i.n=o),e[SIZE]++,"F"!==n&&(e._i[n]=o)),e},getEntry:getEntry,setStrong:function(e,t,r){_iterDefine(e,t,function(e,r){this._t=_validateCollection(e,t),this._k=r,this._l=void 0},function(){for(var e=this._k,t=this._l;t&&t.r;)t=t.p;return this._t&&(this._l=t=t?t.n:this._t._f)?_iterStep(0,"keys"==e?t.k:"values"==e?t.v:[t.k,t.v]):(this._t=void 0,_iterStep(1))},r?"entries":"values",!r,!0),_setSpecies(t)}},_isArray=Array.isArray||function(e){return"Array"==_cof(e)},SPECIES$1=_wks("species"),_arraySpeciesConstructor=function(e){var t;return _isArray(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!_isArray(t.prototype)||(t=void 0),_isObject(t)&&null===(t=t[SPECIES$1])&&(t=void 0)),void 0===t?Array:t},_arraySpeciesCreate=function(e,t){return new(_arraySpeciesConstructor(e))(t)},_arrayMethods=function(e,t){var r=1==e,i=2==e,n=3==e,o=4==e,a=6==e,s=5==e||a,u=t||_arraySpeciesCreate;return function(t,c,l){for(var d,f,h=_toObject(t),p=_iobject(h),m=_ctx(c,l,3),v=_toLength(p.length),g=0,y=r?u(t,v):i?u(t,0):void 0;v>g;g++)if((s||g in p)&&(f=m(d=p[g],g,h),e))if(r)y[g]=f;else if(f)switch(e){case 3:return!0;case 5:return d;case 6:return g;case 2:y.push(d)}else if(o)return!1;return a?-1:n||o?o:y}},dP$2=_objectDp.f,each=_arrayMethods(0),_collection=function(e,t,r,i,n,o){var a=_global[e],s=a,u=n?"set":"add",c=s&&s.prototype,l={};return _descriptors&&"function"==typeof s&&(o||c.forEach&&!_fails(function(){(new s).entries().next()}))?(s=t(function(t,r){_anInstance(t,s,e,"_c"),t._c=new a,void 0!=r&&_forOf(r,n,t[u],t)}),each("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)&&_hide(s.prototype,e,function(r,i){if(_anInstance(this,s,e),!t&&o&&!_isObject(r))return"get"==e&&void 0;var n=this._c[e](0===r?0:r,i);return t?this:n})}),o||dP$2(s.prototype,"size",{get:function(){return this._c.size}})):(s=i.getConstructor(t,e,n,u),_redefineAll(s.prototype,r),_meta.NEED=!0),_setToStringTag(s,e),l[e]=s,_export(_export.G+_export.W+_export.F,l),o||i.setStrong(s,e,n),s},MAP="Map",es6_map=_collection(MAP,function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{get:function(e){var t=_collectionStrong.getEntry(_validateCollection(this,MAP),e);return t&&t.v},set:function(e,t){return _collectionStrong.def(_validateCollection(this,MAP),0===e?0:e,t)}},_collectionStrong,!0),_arrayFromIterable=function(e,t){var r=[];return _forOf(e,!1,r.push,r,t),r},_collectionToJson=function(e){return function(){if(_classof(this)!=e)throw TypeError(e+"#toJSON isn't generic");return _arrayFromIterable(this)}};_export(_export.P+_export.R,"Map",{toJSON:_collectionToJson("Map")});var _setCollectionOf=function(e){_export(_export.S,e,{of:function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];return new this(t)}})};_setCollectionOf("Map");var _setCollectionFrom=function(e){_export(_export.S,e,{from:function(e){var t,r,i,n,o=arguments[1];return _aFunction(this),(t=void 0!==o)&&_aFunction(o),void 0==e?new this:(r=[],t?(i=0,n=_ctx(o,arguments[2],2),_forOf(e,!1,function(e){r.push(n(e,i++))})):_forOf(e,!1,r.push,r),new this(r))}})};_setCollectionFrom("Map");var map=_core.Map,map$1=createCommonjsModule(function(e){e.exports={default:map,__esModule:!0}}),_Map=unwrapExports(map$1),_createProperty=function(e,t,r){t in e?_objectDp.f(e,t,_propertyDesc(0,r)):e[t]=r},ITERATOR$3=_wks("iterator"),SAFE_CLOSING=!1;try{var riter=[7][ITERATOR$3]();riter.return=function(){SAFE_CLOSING=!0}}catch(e){}var _iterDetect=function(e,t){if(!t&&!SAFE_CLOSING)return!1;var r=!1;try{var i=[7],n=i[ITERATOR$3]();n.next=function(){return{done:r=!0}},i[ITERATOR$3]=function(){return n},e(i)}catch(e){}return r};_export(_export.S+_export.F*!_iterDetect(function(e){}),"Array",{from:function(e){var t,r,i,n,o=_toObject(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,d=core_getIteratorMethod(o);if(c&&(u=_ctx(u,s>2?arguments[2]:void 0,2)),void 0==d||a==Array&&_isArrayIter(d))for(r=new a(t=_toLength(o.length));t>l;l++)_createProperty(r,l,c?u(o[l],l):o[l]);else for(n=d.call(o),r=new a;!(i=n.next()).done;l++)_createProperty(r,l,c?_iterCall(n,u,[i.value,l],!0):i.value);return r.length=l,r}});var from=_core.Array.from,from$1=createCommonjsModule(function(e){e.exports={default:from,__esModule:!0}}),_Array$from=unwrapExports(from$1),toConsumableArray=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=from$1)&&r.__esModule?r:{default:r};t.default=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(0,i.default)(e)}}),_toConsumableArray=unwrapExports(toConsumableArray),SPECIES$2=_wks("species"),_speciesConstructor=function(e,t){var r,i=_anObject(e).constructor;return void 0===i||void 0==(r=_anObject(i)[SPECIES$2])?t:_aFunction(r)},_invoke=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)},process=_global.process,setTask=_global.setImmediate,clearTask=_global.clearImmediate,MessageChannel=_global.MessageChannel,Dispatch=_global.Dispatch,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port,run=function(){var e=+this;if(queue.hasOwnProperty(e)){var t=queue[e];delete queue[e],t()}},listener=function(e){run.call(e.data)};setTask&&clearTask||(setTask=function(e){for(var t=[],r=1;arguments.length>r;)t.push(arguments[r++]);return queue[++counter]=function(){_invoke("function"==typeof e?e:Function(e),t)},defer(counter),counter},clearTask=function(e){delete queue[e]},"process"==_cof(process)?defer=function(e){process.nextTick(_ctx(run,e,1))}:Dispatch&&Dispatch.now?defer=function(e){Dispatch.now(_ctx(run,e,1))}:MessageChannel?(channel=new MessageChannel,port=channel.port2,channel.port1.onmessage=listener,defer=_ctx(port.postMessage,port,1)):_global.addEventListener&&"function"==typeof postMessage&&!_global.importScripts?(defer=function(e){_global.postMessage(e+"","*")},_global.addEventListener("message",listener,!1)):defer=ONREADYSTATECHANGE in _domCreate("script")?function(e){_html.appendChild(_domCreate("script"))[ONREADYSTATECHANGE]=function(){_html.removeChild(this),run.call(e)}}:function(e){setTimeout(_ctx(run,e,1),0)});var _task={set:setTask,clear:clearTask},macrotask=_task.set,Observer=_global.MutationObserver||_global.WebKitMutationObserver,process$1=_global.process,Promise$1=_global.Promise,isNode="process"==_cof(process$1),_microtask=function(){var e,t,r,i=function(){var i,n;for(isNode&&(i=process$1.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(isNode)r=function(){process$1.nextTick(i)};else if(!Observer||_global.navigator&&_global.navigator.standalone)if(Promise$1&&Promise$1.resolve){var n=Promise$1.resolve();r=function(){n.then(i)}}else r=function(){macrotask.call(_global,i)};else{var o=!0,a=document.createTextNode("");new Observer(i).observe(a,{characterData:!0}),r=function(){a.data=o=!o}}return function(i){var n={fn:i,next:void 0};t&&(t.next=n),e||(e=n,r()),t=n}};function PromiseCapability(e){var t,r;this.promise=new e(function(e,i){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=i}),this.resolve=_aFunction(t),this.reject=_aFunction(r)}var f$3=function(e){return new PromiseCapability(e)},_newPromiseCapability={f:f$3},_perform=function(e){try{return{e:!1,v:e()}}catch(e){return{e:!0,v:e}}},_promiseResolve=function(e,t){if(_anObject(e),_isObject(t)&&t.constructor===e)return t;var r=_newPromiseCapability.f(e);return(0,r.resolve)(t),r.promise},task=_task.set,microtask=_microtask(),PROMISE="Promise",TypeError$1=_global.TypeError,process$2=_global.process,$Promise=_global[PROMISE],isNode$1="process"==_classof(process$2),empty=function(){},Internal,newGenericPromiseCapability,OwnPromiseCapability,Wrapper,newPromiseCapability=newGenericPromiseCapability=_newPromiseCapability.f,USE_NATIVE=!!function(){try{var e=$Promise.resolve(1),t=(e.constructor={})[_wks("species")]=function(e){e(empty,empty)};return(isNode$1||"function"==typeof PromiseRejectionEvent)&&e.then(empty)instanceof t}catch(e){}}(),isThenable=function(e){var t;return!(!_isObject(e)||"function"!=typeof(t=e.then))&&t},notify=function(e,t){if(!e._n){e._n=!0;var r=e._c;microtask(function(){for(var i=e._v,n=1==e._s,o=0,a=function(t){var r,o,a=n?t.ok:t.fail,s=t.resolve,u=t.reject,c=t.domain;try{a?(n||(2==e._h&&onHandleUnhandled(e),e._h=1),!0===a?r=i:(c&&c.enter(),r=a(i),c&&c.exit()),r===t.promise?u(TypeError$1("Promise-chain cycle")):(o=isThenable(r))?o.call(r,s,u):s(r)):u(i)}catch(e){u(e)}};r.length>o;)a(r[o++]);e._c=[],e._n=!1,t&&!e._h&&onUnhandled(e)})}},onUnhandled=function(e){task.call(_global,function(){var t,r,i,n=e._v,o=isUnhandled(e);if(o&&(t=_perform(function(){isNode$1?process$2.emit("unhandledRejection",n,e):(r=_global.onunhandledrejection)?r({promise:e,reason:n}):(i=_global.console)&&i.error&&i.error("Unhandled promise rejection",n)}),e._h=isNode$1||isUnhandled(e)?2:1),e._a=void 0,o&&t.e)throw t.v})},isUnhandled=function(e){return 1!==e._h&&0===(e._a||e._c).length},onHandleUnhandled=function(e){task.call(_global,function(){var t;isNode$1?process$2.emit("rejectionHandled",e):(t=_global.onrejectionhandled)&&t({promise:e,reason:e._v})})},$reject=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()),notify(t,!0))},$resolve=function(e){var t,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw TypeError$1("Promise can't be resolved itself");(t=isThenable(e))?microtask(function(){var i={_w:r,_d:!1};try{t.call(e,_ctx($resolve,i,1),_ctx($reject,i,1))}catch(e){$reject.call(i,e)}}):(r._v=e,r._s=1,notify(r,!1))}catch(e){$reject.call({_w:r,_d:!1},e)}}};USE_NATIVE||($Promise=function(e){_anInstance(this,$Promise,PROMISE,"_h"),_aFunction(e),Internal.call(this);try{e(_ctx($resolve,this,1),_ctx($reject,this,1))}catch(e){$reject.call(this,e)}},Internal=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},Internal.prototype=_redefineAll($Promise.prototype,{then:function(e,t){var r=newPromiseCapability(_speciesConstructor(this,$Promise));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=isNode$1?process$2.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&¬ify(this,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),OwnPromiseCapability=function(){var e=new Internal;this.promise=e,this.resolve=_ctx($resolve,e,1),this.reject=_ctx($reject,e,1)},_newPromiseCapability.f=newPromiseCapability=function(e){return e===$Promise||e===Wrapper?new OwnPromiseCapability(e):newGenericPromiseCapability(e)}),_export(_export.G+_export.W+_export.F*!USE_NATIVE,{Promise:$Promise}),_setToStringTag($Promise,PROMISE),_setSpecies(PROMISE),Wrapper=_core[PROMISE],_export(_export.S+_export.F*!USE_NATIVE,PROMISE,{reject:function(e){var t=newPromiseCapability(this);return(0,t.reject)(e),t.promise}}),_export(_export.S+_export.F*(_library||!USE_NATIVE),PROMISE,{resolve:function(e){return _promiseResolve(_library&&this===Wrapper?$Promise:this,e)}}),_export(_export.S+_export.F*!(USE_NATIVE&&_iterDetect(function(e){$Promise.all(e).catch(empty)})),PROMISE,{all:function(e){var t=this,r=newPromiseCapability(t),i=r.resolve,n=r.reject,o=_perform(function(){var r=[],o=0,a=1;_forOf(e,!1,function(e){var s=o++,u=!1;r.push(void 0),a++,t.resolve(e).then(function(e){u||(u=!0,r[s]=e,--a||i(r))},n)}),--a||i(r)});return o.e&&n(o.v),r.promise},race:function(e){var t=this,r=newPromiseCapability(t),i=r.reject,n=_perform(function(){_forOf(e,!1,function(e){t.resolve(e).then(r.resolve,i)})});return n.e&&i(n.v),r.promise}}),_export(_export.P+_export.R,"Promise",{finally:function(e){var t=_speciesConstructor(this,_core.Promise||_global.Promise),r="function"==typeof e;return this.then(r?function(r){return _promiseResolve(t,e()).then(function(){return r})}:e,r?function(r){return _promiseResolve(t,e()).then(function(){throw r})}:e)}}),_export(_export.S,"Promise",{try:function(e){var t=_newPromiseCapability.f(this),r=_perform(e);return(r.e?t.reject:t.resolve)(r.v),t.promise}});var promise=_core.Promise,promise$1=createCommonjsModule(function(e){e.exports={default:promise,__esModule:!0}}),_Promise=unwrapExports(promise$1),classCallCheck=createCommonjsModule(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")}}),_classCallCheck=unwrapExports(classCallCheck);_export(_export.S+_export.F*!_descriptors,"Object",{defineProperty:_objectDp.f});var $Object$1=_core.Object,defineProperty=function(e,t,r){return $Object$1.defineProperty(e,t,r)},defineProperty$1=createCommonjsModule(function(e){e.exports={default:defineProperty,__esModule:!0}}),_Object$defineProperty=unwrapExports(defineProperty$1),createClass=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=defineProperty$1)&&r.__esModule?r:{default:r};t.default=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),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()}),_createClass=unwrapExports(createClass),f$4=_wks,_wksExt={f:f$4},iterator=_wksExt.f("iterator"),iterator$1=createCommonjsModule(function(e){e.exports={default:iterator,__esModule:!0}});unwrapExports(iterator$1);var defineProperty$2=_objectDp.f,_wksDefine=function(e){var t=_core.Symbol||(_core.Symbol=_library?{}:_global.Symbol||{});"_"==e.charAt(0)||e in t||defineProperty$2(t,e,{value:_wksExt.f(e)})},f$5=Object.getOwnPropertySymbols,_objectGops={f:f$5},_enumKeys=function(e){var t=_objectKeys(e),r=_objectGops.f;if(r)for(var i,n=r(e),o=_objectPie.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t},hiddenKeys=_enumBugKeys.concat("length","prototype"),f$6=Object.getOwnPropertyNames||function(e){return _objectKeysInternal(e,hiddenKeys)},_objectGopn={f:f$6},gOPN=_objectGopn.f,toString$1={}.toString,windowNames="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],getWindowNames=function(e){try{return gOPN(e)}catch(e){return windowNames.slice()}},f$7=function(e){return windowNames&&"[object Window]"==toString$1.call(e)?getWindowNames(e):gOPN(_toIobject(e))},_objectGopnExt={f:f$7},META=_meta.KEY,gOPD$1=_objectGopd.f,dP$3=_objectDp.f,gOPN$1=_objectGopnExt.f,$Symbol=_global.Symbol,$JSON=_global.JSON,_stringify=$JSON&&$JSON.stringify,PROTOTYPE$2="prototype",HIDDEN=_wks("_hidden"),TO_PRIMITIVE=_wks("toPrimitive"),isEnum={}.propertyIsEnumerable,SymbolRegistry=_shared("symbol-registry"),AllSymbols=_shared("symbols"),OPSymbols=_shared("op-symbols"),ObjectProto$1=Object[PROTOTYPE$2],USE_NATIVE$1="function"==typeof $Symbol,QObject=_global.QObject,setter=!QObject||!QObject[PROTOTYPE$2]||!QObject[PROTOTYPE$2].findChild,setSymbolDesc=_descriptors&&_fails(function(){return 7!=_objectCreate(dP$3({},"a",{get:function(){return dP$3(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=gOPD$1(ObjectProto$1,t);i&&delete ObjectProto$1[t],dP$3(e,t,r),i&&e!==ObjectProto$1&&dP$3(ObjectProto$1,t,i)}:dP$3,wrap=function(e){var t=AllSymbols[e]=_objectCreate($Symbol[PROTOTYPE$2]);return t._k=e,t},isSymbol=USE_NATIVE$1&&"symbol"==typeof $Symbol.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof $Symbol},$defineProperty=function(e,t,r){return e===ObjectProto$1&&$defineProperty(OPSymbols,t,r),_anObject(e),t=_toPrimitive(t,!0),_anObject(r),_has(AllSymbols,t)?(r.enumerable?(_has(e,HIDDEN)&&e[HIDDEN][t]&&(e[HIDDEN][t]=!1),r=_objectCreate(r,{enumerable:_propertyDesc(0,!1)})):(_has(e,HIDDEN)||dP$3(e,HIDDEN,_propertyDesc(1,{})),e[HIDDEN][t]=!0),setSymbolDesc(e,t,r)):dP$3(e,t,r)},$defineProperties=function(e,t){_anObject(e);for(var r,i=_enumKeys(t=_toIobject(t)),n=0,o=i.length;o>n;)$defineProperty(e,r=i[n++],t[r]);return e},$create=function(e,t){return void 0===t?_objectCreate(e):$defineProperties(_objectCreate(e),t)},$propertyIsEnumerable=function(e){var t=isEnum.call(this,e=_toPrimitive(e,!0));return!(this===ObjectProto$1&&_has(AllSymbols,e)&&!_has(OPSymbols,e))&&(!(t||!_has(this,e)||!_has(AllSymbols,e)||_has(this,HIDDEN)&&this[HIDDEN][e])||t)},$getOwnPropertyDescriptor$1=function(e,t){if(e=_toIobject(e),t=_toPrimitive(t,!0),e!==ObjectProto$1||!_has(AllSymbols,t)||_has(OPSymbols,t)){var r=gOPD$1(e,t);return!r||!_has(AllSymbols,t)||_has(e,HIDDEN)&&e[HIDDEN][t]||(r.enumerable=!0),r}},$getOwnPropertyNames=function(e){for(var t,r=gOPN$1(_toIobject(e)),i=[],n=0;r.length>n;)_has(AllSymbols,t=r[n++])||t==HIDDEN||t==META||i.push(t);return i},$getOwnPropertySymbols=function(e){for(var t,r=e===ObjectProto$1,i=gOPN$1(r?OPSymbols:_toIobject(e)),n=[],o=0;i.length>o;)!_has(AllSymbols,t=i[o++])||r&&!_has(ObjectProto$1,t)||n.push(AllSymbols[t]);return n};USE_NATIVE$1||($Symbol=function(){if(this instanceof $Symbol)throw TypeError("Symbol is not a constructor!");var e=_uid(arguments.length>0?arguments[0]:void 0),t=function(r){this===ObjectProto$1&&t.call(OPSymbols,r),_has(this,HIDDEN)&&_has(this[HIDDEN],e)&&(this[HIDDEN][e]=!1),setSymbolDesc(this,e,_propertyDesc(1,r))};return _descriptors&&setter&&setSymbolDesc(ObjectProto$1,e,{configurable:!0,set:t}),wrap(e)},_redefine($Symbol[PROTOTYPE$2],"toString",function(){return this._k}),_objectGopd.f=$getOwnPropertyDescriptor$1,_objectDp.f=$defineProperty,_objectGopn.f=_objectGopnExt.f=$getOwnPropertyNames,_objectPie.f=$propertyIsEnumerable,_objectGops.f=$getOwnPropertySymbols,_descriptors&&!_library&&_redefine(ObjectProto$1,"propertyIsEnumerable",$propertyIsEnumerable,!0),_wksExt.f=function(e){return wrap(_wks(e))}),_export(_export.G+_export.W+_export.F*!USE_NATIVE$1,{Symbol:$Symbol});for(var es6Symbols="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),j=0;es6Symbols.length>j;)_wks(es6Symbols[j++]);for(var wellKnownSymbols=_objectKeys(_wks.store),k=0;wellKnownSymbols.length>k;)_wksDefine(wellKnownSymbols[k++]);_export(_export.S+_export.F*!USE_NATIVE$1,"Symbol",{for:function(e){return _has(SymbolRegistry,e+="")?SymbolRegistry[e]:SymbolRegistry[e]=$Symbol(e)},keyFor:function(e){if(!isSymbol(e))throw TypeError(e+" is not a symbol!");for(var t in SymbolRegistry)if(SymbolRegistry[t]===e)return t},useSetter:function(){setter=!0},useSimple:function(){setter=!1}}),_export(_export.S+_export.F*!USE_NATIVE$1,"Object",{create:$create,defineProperty:$defineProperty,defineProperties:$defineProperties,getOwnPropertyDescriptor:$getOwnPropertyDescriptor$1,getOwnPropertyNames:$getOwnPropertyNames,getOwnPropertySymbols:$getOwnPropertySymbols}),$JSON&&_export(_export.S+_export.F*(!USE_NATIVE$1||_fails(function(){var e=$Symbol();return"[null]"!=_stringify([e])||"{}"!=_stringify({a:e})||"{}"!=_stringify(Object(e))})),"JSON",{stringify:function(e){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);if(r=t=i[1],(_isObject(t)||void 0!==e)&&!isSymbol(e))return _isArray(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!isSymbol(t))return t}),i[1]=t,_stringify.apply($JSON,i)}}),$Symbol[PROTOTYPE$2][TO_PRIMITIVE]||_hide($Symbol[PROTOTYPE$2],TO_PRIMITIVE,$Symbol[PROTOTYPE$2].valueOf),_setToStringTag($Symbol,"Symbol"),_setToStringTag(Math,"Math",!0),_setToStringTag(_global.JSON,"JSON",!0),_wksDefine("asyncIterator"),_wksDefine("observable");var symbol=_core.Symbol,symbol$1=createCommonjsModule(function(e){e.exports={default:symbol,__esModule:!0}});unwrapExports(symbol$1);var _typeof_1=createCommonjsModule(function(e,t){t.__esModule=!0;var r=o(iterator$1),i=o(symbol$1),n="function"==typeof i.default&&"symbol"==typeof r.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};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}),_typeof=unwrapExports(_typeof_1);_objectSap("keys",function(){return function(e){return _objectKeys(_toObject(e))}});var keys=_core.Object.keys,keys$1=createCommonjsModule(function(e){e.exports={default:keys,__esModule:!0}}),_Object$keys=unwrapExports(keys$1),floor$1=Math.floor,_isInteger=function(e){return!_isObject(e)&&isFinite(e)&&floor$1(e)===e};_export(_export.S,"Number",{isInteger:_isInteger});var isInteger=_core.Number.isInteger,isInteger$1=createCommonjsModule(function(e){e.exports={default:isInteger,__esModule:!0}}),_Number$isInteger=unwrapExports(isInteger$1),_stringWs="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff",space="["+_stringWs+"]",non="​…",ltrim=RegExp("^"+space+space+"*"),rtrim=RegExp(space+space+"*$"),exporter=function(e,t,r){var i={},n=_fails(function(){return!!_stringWs[e]()||non[e]()!=non}),o=i[e]=n?t(trim):_stringWs[e];r&&(i[r]=o),_export(_export.P+_export.F*n,"String",i)},trim=exporter.trim=function(e,t){return e=String(_defined(e)),1&t&&(e=e.replace(ltrim,"")),2&t&&(e=e.replace(rtrim,"")),e},_stringTrim=exporter,$parseFloat=_global.parseFloat,$trim=_stringTrim.trim,_parseFloat=1/$parseFloat(_stringWs+"-0")!=-1/0?function(e){var t=$trim(String(e),3),r=$parseFloat(t);return 0===r&&"-"==t.charAt(0)?-0:r}:$parseFloat;_export(_export.S+_export.F*(Number.parseFloat!=_parseFloat),"Number",{parseFloat:_parseFloat});var _parseFloat$1=parseFloat,_parseFloat$2=createCommonjsModule(function(e){e.exports={default:_parseFloat$1,__esModule:!0}}),_Number$parseFloat=unwrapExports(_parseFloat$2);function defined(e){return void 0!==e}function isVoid(e){return void 0===e||null===e}function isArray(e){return Array.isArray(e)}function isFunction(e){return"function"==typeof e}function isObject(e){return Object(e)===e&&"[object Object]"===String(e)&&!isFunction(e)&&!isArray(e)}function isNumber(e){return"number"==typeof e}function isNumeric(e){return!isArray(e)&&e-_Number$parseFloat(e)+1>=0}function isInteger$2(e){return _Number$isInteger(e)}function isEmpty(e){return isArray(e)?0===e.length:isObject(e)?0===_Object$keys(e).length:!e}function isEvent(e){return e instanceof Event||(e&&e.originalEvent)instanceof Event}function isBlob(e){return e instanceof Blob}function isFile(e){return isBlob(e)&&isString(e.name)}function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)}function isString(e){return"string"==typeof e||e instanceof String}function isBoolean(e){return"boolean"==typeof e}function isPromise(e){return!!e&&("object"===(void 0===e?"undefined":_typeof(e))||"function"==typeof e)&&"function"==typeof e.then}function isPrimitive(e){return isVoid(e)||isBoolean(e)||isString(e)||isNumber(e)}function isUrl(e){return isString(e)&&!!e.match(/^((https?|ftp|rtsp|mms):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6}|localhost)(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i)}function isNode$2(e){return!!("object"===("undefined"==typeof Node?"undefined":_typeof(Node))?e instanceof Node:e&&"object"===(void 0===e?"undefined":_typeof(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}function isElement(e){return!!("object"===("undefined"==typeof HTMLElement?"undefined":_typeof(HTMLElement))?e instanceof HTMLElement:e&&"object"===(void 0===e?"undefined":_typeof(e))&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)}function isChildNode(e,t){return!(!isNode$2(e)||!isNode$2(t))&&t.parentNode===e}function isPosterityNode(e,t){if(!isNode$2(e)||!isNode$2(t))return!1;for(;t.parentNode;)if((t=t.parentNode)===e)return!0;return!1}function isHTMLString(e){return/<[^>]+?>/.test(e)}function isError(e){return e instanceof Error}function isRegExp(e){return e instanceof RegExp}function formatter(e,t){if(!isString(e))throw new TypeError("Log's method only acccept string as argument, but not "+e+" in "+(void 0===e?"undefined":_typeof(e)));return isString(t)?"["+(e=Log$1.FORCE_GLOBAL_TAG?Log$1.GLOBAL_TAG:e||Log$1.GLOBAL_TAG)+"] > "+t:"["+Log$1.GLOBAL_TAG+"] > "+e}var Log$1=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(formatter(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(formatter(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(formatter(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(formatter(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(formatter(t,r))}}]),e}();Log$1.GLOBAL_TAG="chimee",Log$1.FORCE_GLOBAL_TAG=!1,Log$1.ENABLE_ERROR=!0,Log$1.ENABLE_INFO=!0,Log$1.ENABLE_WARN=!0,Log$1.ENABLE_DEBUG=!0,Log$1.ENABLE_VERBOSE=!0;var uaParser=createCommonjsModule(function(e,t){!function(r,i){var n="model",o="name",a="type",s="vendor",u="version",c="mobile",l="tablet",d={extend:function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r},has:function(e,t){return"string"==typeof e&&-1!==t.toLowerCase().indexOf(e.toLowerCase())},lowerize:function(e){return e.toLowerCase()},major:function(e){return"string"==typeof e?e.replace(/[^\d\.]/g,"").split(".")[0]:void 0},trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},f={rgx:function(e,t){for(var r,i,n,o,a,s,u=0;u<t.length&&!a;){var c=t[u],l=t[u+1];for(r=i=0;r<c.length&&!a;)if(a=c[r++].exec(e))for(n=0;n<l.length;n++)s=a[++i],"object"==typeof(o=l[n])&&o.length>0?2==o.length?"function"==typeof o[1]?this[o[0]]=o[1].call(this,s):this[o[0]]=o[1]:3==o.length?"function"!=typeof o[1]||o[1].exec&&o[1].test?this[o[0]]=s?s.replace(o[1],o[2]):void 0:this[o[0]]=s?o[1].call(this,s,o[2]):void 0:4==o.length&&(this[o[0]]=s?o[3].call(this,s.replace(o[1],o[2])):void 0):this[o]=s||void 0;u+=2}},str:function(e,t){for(var r in t)if("object"==typeof t[r]&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(d.has(t[r][i],e))return"?"===r?void 0:r}else if(d.has(t[r],e))return"?"===r?void 0:r;return e}},h={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2000:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}},p={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[o,u],[/(opios)[\/\s]+([\w\.]+)/i],[[o,"Opera Mini"],u],[/\s(opr)\/([\w\.]+)/i],[[o,"Opera"],u],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]+)*/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i],[o,u],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[o,"IE"],u],[/(edge)\/((\d+)?[\w\.]+)/i],[o,u],[/(yabrowser)\/([\w\.]+)/i],[[o,"Yandex"],u],[/(puffin)\/([\w\.]+)/i],[[o,"Puffin"],u],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[o,"UCBrowser"],u],[/(comodo_dragon)\/([\w\.]+)/i],[[o,/_/g," "],u],[/(micromessenger)\/([\w\.]+)/i],[[o,"WeChat"],u],[/(QQ)\/([\d\.]+)/i],[o,u],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[o,u],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[u,[o,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[u,[o,"Facebook"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[u,[o,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[o,/(.+)/,"$1 WebView"],u],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[o,/(.+(?:g|us))(.+)/,"$1 $2"],u],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[u,[o,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[o,u],[/(dolfin)\/([\w\.]+)/i],[[o,"Dolphin"],u],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[o,"Chrome"],u],[/(coast)\/([\w\.]+)/i],[[o,"Opera Coast"],u],[/fxios\/([\w\.-]+)/i],[u,[o,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[u,[o,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[u,o],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[o,"GSA"],u],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[o,[u,f.str,h.browser.oldsafari.version]],[/(konqueror)\/([\w\.]+)/i,/(webkit|khtml)\/([\w\.]+)/i],[o,u],[/(navigator|netscape)\/([\w\.-]+)/i],[[o,"Netscape"],u],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]+)*/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[o,u]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",d.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",d.lowerize]],[/(sun4\w)[;\)]/i],[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[["architecture",d.lowerize]]],device:[[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],[n,s,[a,l]],[/applecoremedia\/[\w\.]+ \((ipad)/],[n,[s,"Apple"],[a,l]],[/(apple\s{0,1}tv)/i],[[n,"Apple TV"],[s,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[s,n,[a,l]],[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],[n,[s,"Amazon"],[a,l]],[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],[[n,f.str,h.device.amazon.model],[s,"Amazon"],[a,c]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[n,s,[a,c]],[/\((ip[honed|\s\w*]+);/i],[n,[s,"Apple"],[a,c]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[s,n,[a,c]],[/\(bb10;\s(\w+)/i],[n,[s,"BlackBerry"],[a,c]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i],[n,[s,"Asus"],[a,l]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[s,"Sony"],[n,"Xperia Tablet"],[a,l]],[/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i],[n,[s,"Sony"],[a,c]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[s,n,[a,"console"]],[/android.+;\s(shield)\sbuild/i],[n,[s,"Nvidia"],[a,"console"]],[/(playstation\s[34portablevi]+)/i],[n,[s,"Sony"],[a,"console"]],[/(sprint\s(\w+))/i],[[s,f.str,h.device.sprint.vendor],[n,f.str,h.device.sprint.model],[a,c]],[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],[s,n,[a,l]],[/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,/(zte)-(\w+)*/i,/(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i],[s,[n,/_/g," "],[a,c]],[/(nexus\s9)/i],[n,[s,"HTC"],[a,l]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[n,[s,"Huawei"],[a,c]],[/(microsoft);\s(lumia[\s\w]+)/i],[s,n,[a,c]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[n,[s,"Microsoft"],[a,"console"]],[/(kin\.[onetw]{3})/i],[[n,/\./g," "],[s,"Microsoft"],[a,c]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w+)*/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[n,[s,"Motorola"],[a,c]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[n,[s,"Motorola"],[a,l]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[s,d.trim],[n,d.trim],[a,"smarttv"]],[/hbbtv.+maple;(\d+)/i],[[n,/^/,"SmartTV"],[s,"Samsung"],[a,"smarttv"]],[/\(dtv[\);].+(aquos)/i],[n,[s,"Sharp"],[a,"smarttv"]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[s,"Samsung"],n,[a,l]],[/smart-tv.+(samsung)/i],[s,[a,"smarttv"],n],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,/sec-((sgh\w+))/i],[[s,"Samsung"],n,[a,c]],[/sie-(\w+)*/i],[n,[s,"Siemens"],[a,c]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]+)*/i],[[s,"Nokia"],n,[a,c]],[/android\s3\.[\s\w;-]{10}(a\d{3})/i],[n,[s,"Acer"],[a,l]],[/android.+([vl]k\-?\d{3})\s+build/i],[n,[s,"LG"],[a,l]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[s,"LG"],n,[a,l]],[/(lg) netcast\.tv/i],[s,n,[a,"smarttv"]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w+)*/i,/android.+lg(\-?[\d\w]+)\s+build/i],[n,[s,"LG"],[a,c]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[n,[s,"Lenovo"],[a,l]],[/linux;.+((jolla));/i],[s,n,[a,c]],[/((pebble))app\/[\d\.]+\s/i],[s,n,[a,"wearable"]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[s,n,[a,c]],[/crkey/i],[[n,"Chromecast"],[s,"Google"]],[/android.+;\s(glass)\s\d/i],[n,[s,"Google"],[a,"wearable"]],[/android.+;\s(pixel c)\s/i],[n,[s,"Google"],[a,l]],[/android.+;\s(pixel xl|pixel)\s/i],[n,[s,"Google"],[a,c]],[/android.+(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,c]],[/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,l]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[n,[s,"Meizu"],[a,l]],[/android.+a000(1)\s+build/i],[n,[s,"OnePlus"],[a,c]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[n,[s,"RCA"],[a,l]],[/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i],[n,[s,"Dell"],[a,l]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[n,[s,"Verizon"],[a,l]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[s,"Barnes & Noble"],n,[a,l]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[n,[s,"NuVision"],[a,l]],[/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i],[[s,"ZTE"],n,[a,l]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[n,[s,"Swiss"],[a,c]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[n,[s,"Swiss"],[a,l]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[n,[s,"Zeki"],[a,l]],[/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i],[[s,"Dragon Touch"],n,[a,l]],[/android.+[;\/]\s*(NS-?.+)\s+build/i],[n,[s,"Insignia"],[a,l]],[/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i],[n,[s,"NextBook"],[a,l]],[/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[s,"Voice"],n,[a,c]],[/android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i],[[s,"LvTel"],n,[a,c]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[n,[s,"Envizen"],[a,l]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[n,[s,"MachSpeed"],[a,l]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[n,[s,"Rotor"],[a,l]],[/android.+(KS(.+))\s+build/i],[n,[s,"Amazon"],[a,l]],[/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i],[s,n,[a,l]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[a,d.lowerize],s,n],[/(android.+)[;\/].+build/i],[n,[s,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[u,[o,"EdgeHTML"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[o,u],[/rv\:([\w\.]+).*(gecko)/i],[u,o]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[o,u],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[o,[u,f.str,h.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[o,"Windows"],[u,f.str,h.os.windows.version]],[/\((bb)(10);/i],[[o,"BlackBerry"],u],[/(blackberry)\w*\/?([\w\.]+)*/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,/linux;.+(sailfish);/i],[o,u],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],[[o,"Symbian"],u],[/\((series40);/i],[o],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[o,"Firefox OS"],u],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w+)*/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,/(hurd|linux)\s?([\w\.]+)*/i,/(gnu)\s?([\w\.]+)*/i],[o,u],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[o,"Chromium OS"],u],[/(sunos)\s?([\w\.]+\d)*/i],[[o,"Solaris"],u],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],[o,u],[/(haiku)\s(\w+)/i],[o,u],[/cfnetwork\/.+darwin/i,/ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[u,/_/g,"."],[o,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,/(macintosh|mac(?=_powerpc)\s)/i],[[o,"Mac OS"],[u,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,/(unix)\s?([\w\.]+)*/i],[o,u]]},m=function(e,t){if("object"==typeof e&&(t=e,e=void 0),!(this instanceof m))return new m(e,t).getResult();var i=e||(r&&r.navigator&&r.navigator.userAgent?r.navigator.userAgent:""),n=t?d.extend(p,t):p;return this.getBrowser=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.browser),e.major=d.major(e.version),e},this.getCPU=function(){var e={architecture:void 0};return f.rgx.call(e,i,n.cpu),e},this.getDevice=function(){var e={vendor:void 0,model:void 0,type:void 0};return f.rgx.call(e,i,n.device),e},this.getEngine=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.engine),e},this.getOS=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=e,this},this};m.VERSION="0.7.17",m.BROWSER={NAME:o,MAJOR:"major",VERSION:u},m.CPU={ARCHITECTURE:"architecture"},m.DEVICE={MODEL:n,VENDOR:s,TYPE:a,CONSOLE:"console",MOBILE:c,SMARTTV:"smarttv",TABLET:l,WEARABLE:"wearable",EMBEDDED:"embedded"},m.ENGINE={NAME:o,VERSION:u},m.OS={NAME:o,VERSION:u},e.exports&&(t=e.exports=m),t.UAParser=m;var v=r&&(r.jQuery||r.Zepto);if(void 0!==v){var g=new m;v.ua=g.getResult(),v.ua.get=function(){return g.getUA()},v.ua.set=function(e){g.setUA(e);var t=g.getResult();for(var r in t)v.ua[r]=t[r]}}}("object"==typeof window?window:commonjsGlobal)}),uaParser_1=uaParser.UAParser;function genTraversalHandler(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t,r){e[t]=r};return function r(i,n,o){if(isArray(i)||isObject(i)){for(var a in n=isPrimitive(n)?isObject(i)?{}:[]:n,i)t(n,a,r(i[a],n[a],a));return n}return e(i,n,o)}}var _deepAssign=genTraversalHandler(function(e){return e});function deepClone(e){if(isPrimitive(e))throw new TypeError("deepClone only accept non primitive type");return _deepAssign(e)}function deepAssign(){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(isPrimitive(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return _deepAssign(e,n)}),n}function camelize(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 hypenate(e){return camelize(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}function bind(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(_toConsumableArray(i)))}}function uuid(){return S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()}function S4(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function getDeepProperty(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(isString(t)&&(t=t.split(".")),!isArray(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(isVoid(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s}var inBrowser="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window);function makeArray(e){return _Array$from(e)}function transObjectAttrIntoArray(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return _Object$keys(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])}function runRejectableQueue(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 _Promise(function(t,i){!function n(o){if(!(o>=e.length)){var a=isFunction(e[o])?e[o].apply(e,_toConsumableArray(r)):e[o];return!1===a?i("stop"):_Promise.resolve(a).then(function(){return n(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})}function runStoppableQueue(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!==(isFunction(e[i])?e[i].apply(e,_toConsumableArray(r)):e[i])&&t(++i)}(0)}var raf=inBrowser&&(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame)||function(e){return setTimeout(e,17)},caf=inBrowser&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.oCancelAnimationFrame)||function(e){clearTimeout(e)};function strRepeat(e,t){var r=t,i=(e=""+(e||"")).length;return(((t=(t||i)-i)>0?e.repeat?"0".repeat(t):new Array(t+1).join("0"):"")+e).slice(0,r)}function formatTime(e){var t=Math.floor(e/3600);e=Math.floor(e%3600);var r=strRepeat(Math.floor(e/60),2),i=strRepeat(e=Math.floor(e%60),2);return t>=1?t+":"+r+":"+i:r+":"+i}function formatDate(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"yyyy-MM-dd hh:mm:ss.i",r=e.getFullYear().toString(),i={M:e.getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),i:e.getMilliseconds()};t=t.replace(/(y+)/gi,function(e,t){return r.substr(4-Math.min(4,t.length))});var n=function(e){t=t.replace(new RegExp("("+e+"+)","g"),function(t,r){return(i[e]<10&&r.length>1?"0":"")+i[e]})};for(var o in i)n(o);return t}function getLocalStorage(e){try{return window.localStorage.getItem(e)}catch(r){try{var t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]*)(;|$)"));return isArray(t)?unescape(t[2]):""}catch(e){return""}}}function setLocalStorage(e,t){try{window.localStorage.setItem(e,t)}catch(i){var r=new Date;r.setTime(r.getTime()+2592e7);try{document.cookie=e+"="+escape(t)+";expires="+r.toUTCString()+";path=/;"}catch(e){console.error(e)}}}var $assign=Object.assign,_objectAssign=!$assign||_fails(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=$assign({},e)[r]||Object.keys($assign({},t)).join("")!=i})?function(e,t){for(var r=_toObject(e),i=arguments.length,n=1,o=_objectGops.f,a=_objectPie.f;i>n;)for(var s,u=_iobject(arguments[n++]),c=o?_objectKeys(u).concat(o(u)):_objectKeys(u),l=c.length,d=0;l>d;)a.call(u,s=c[d++])&&(r[s]=u[s]);return r}:$assign;_export(_export.S+_export.F,"Object",{assign:_objectAssign});var assign=_core.Object.assign,assign$1=createCommonjsModule(function(e){e.exports={default:assign,__esModule:!0}}),_Object$assign=unwrapExports(assign$1);_export(_export.S,"Object",{create:_objectCreate});var $Object$2=_core.Object,create=function(e,t){return $Object$2.create(e,t)},create$1=createCommonjsModule(function(e){e.exports={default:create,__esModule:!0}}),_Object$create=unwrapExports(create$1),_evtListenerCache=_Object$create(null);function getEvtTypeCache(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++_evtListenerCache.count);var i=r+"_"+t,n=_evtListenerCache[i];return n||(n=_evtListenerCache[i]=[]),n}function emitEventCache(e,t,r){var i=_Object$create(null);i.type=t,i.target=e,r&&_Object$assign(i,isObject(r)?r:{data:r}),getEvtTypeCache(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function addEventCache(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];isFunction(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){removeEventCache(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),getEvtTypeCache(e,t).push(o)}function removeEventCache(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=getEvtTypeCache(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}_evtListenerCache.count=0;var CustEvent=function(){function e(t,r){var i=this;if(_classCallCheck(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":_typeof(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 _createClass(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return addEventCache(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 removeEventCache(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return emitEventCache(this.__target,e,{data:t}),this}}]),e}(),_divEl=inBrowser?document.createElement("div"):{},_textAttrName="innerText";"textContent"in _divEl&&(_textAttrName="textContent");var _arrPrototype=Array.prototype;function getAttr(e,t){return e.getAttribute(t)}function setAttr(e,t,r){void 0===r?e.removeAttribute(t):e.setAttribute(t,r)}function addClassName(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 removeClassName(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 hasClassName(e,t){return new RegExp("(?:^|\\s)"+t+"(?=\\s|$)").test(e.className)}var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});inBrowser&&window.addEventListener("test",null,opts)}catch(e){console.error(e)}function removeEvent(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(void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0}),i){var o=removeEventCache(e,t+"_once",r);o&&(r=o)}e.removeEventListener(t,r,n)}function addEvent(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(void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0}),i){var o=r;addEventCache(e,t+"_once",o,r=function(){for(var a=arguments.length,s=Array(a),u=0;u<a;u++)s[u]=arguments[u];o.apply(this,s),removeEvent(e,t,r,i,n)})}e.addEventListener(t,r,n)}function addDelegate(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0});var o=function(r){var n=findParents(r.target||r.srcElement,e,!0),o=query(t,e,!0),a=void 0;o.find?a=o.find(function(e){return n.find(function(t){return e===t})}):o.forEach(function(e){return!a&&n.forEach(function(t){a||e!==t||(a=t)})}),a&&i.apply(a,arguments)};addEventCache(e,r+"_delegate_"+t,i,o),e.addEventListener(r,o,n)}function removeDelegate(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0});var o=removeEventCache(e,r+"_delegate_"+t,i);o&&e.removeEventListener(r,o,n)}function getStyle(e,t){return(e.currentStyle||document.defaultView.getComputedStyle(e,null))[t]||e.style[t]}function setStyle(e,t,r){if(isObject(t))for(var i in t)setStyle(e,i,t[i]);else e.style[t]=r}function query(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document,r=arguments[2],i=t.querySelectorAll(e);return r?_Array$from(i):i}function removeEl(e){e.parentNode.removeChild(e)}function findParents(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}var NodeWrap=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;_classCallCheck(this,e);this.selector=t;var i=void 0;t&&t.constructor===NodeList?i=makeArray(t):isArray(t)?i=t:isString(t)?0===t.indexOf("<")?(_divEl.innerHTML=t,i=query("*",_divEl,!0)):i=query(t,r,!0):i=[t],_Object$assign(this,i),this.length=i.length}return _createClass(e,[{key:"each",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return _arrPrototype.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 _arrPrototype.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 $(_arrPrototype.splice.apply(this,t))}},{key:"find",value:function(e){var t=[];this.each(function(r){t=t.concat(query(e,r,!0))});var r=$(t);return r.parent=this,r.selector=e,r}},{key:"append",value:function(e){var t=$(e),r=this[0];return t.each(function(e){return r.appendChild(e)}),this}},{key:"appendTo",value:function(e){return $(e).append(this),this}},{key:"text",value:function(e){return 0===arguments.length?this[0][_textAttrName]:this.each(function(t){t[_textAttrName]=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?getAttr(this[0],e):this.each(function(r){return setAttr(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||isObject(e)?this.each(function(r){return setStyle(r,e,t)}):getStyle(this[0],e)}},{key:"addClass",value:function(e){return this.each(function(t){return addClassName(t,e)})}},{key:"removeClass",value:function(e){return this.each(function(t){return removeClassName(t,e)})}},{key:"hasClass",value:function(e){return hasClassName(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 addEvent(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 removeEvent(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 addDelegate(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 removeDelegate(n,e,t,r,i)})}},{key:"remove",value:function(){return this.each(function(e){return removeEl(e)})}}]),e}();function $(e,t){return e.constructor===NodeWrap?e:new NodeWrap(e,t)}var Reflect=_global.Reflect,_ownKeys=Reflect&&Reflect.ownKeys||function(e){var t=_objectGopn.f(_anObject(e)),r=_objectGops.f;return r?t.concat(r(e)):t};_export(_export.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,r,i=_toIobject(e),n=_objectGopd.f,o=_ownKeys(i),a={},s=0;o.length>s;)void 0!==(r=n(i,t=o[s++]))&&_createProperty(a,t,r);return a}});var getOwnPropertyDescriptors=_core.Object.getOwnPropertyDescriptors,getOwnPropertyDescriptors$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertyDescriptors,__esModule:!0}}),_Object$getOwnPropertyDescriptors=unwrapExports(getOwnPropertyDescriptors$1),getOwnPropertySymbols=_core.Object.getOwnPropertySymbols,getOwnPropertySymbols$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertySymbols,__esModule:!0}}),_Object$getOwnPropertySymbols=unwrapExports(getOwnPropertySymbols$1);_objectSap("getOwnPropertyNames",function(){return _objectGopnExt.f});var $Object$3=_core.Object,getOwnPropertyNames=function(e){return $Object$3.getOwnPropertyNames(e)},getOwnPropertyNames$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertyNames,__esModule:!0}}),_Object$getOwnPropertyNames=unwrapExports(getOwnPropertyNames$1);function bind$1(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(_toConsumableArray(i)))}}function getDeepProperty$1(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(isString(t)&&(t=t.split(".")),!isArray(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(isVoid(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s}var ITERATOR$4=_wks("iterator"),core_isIterable=_core.isIterable=function(e){var t=Object(e);return void 0!==t[ITERATOR$4]||"@@iterator"in t||_iterators.hasOwnProperty(_classof(t))},isIterable=core_isIterable,isIterable$1=createCommonjsModule(function(e){e.exports={default:isIterable,__esModule:!0}});unwrapExports(isIterable$1);var core_getIterator=_core.getIterator=function(e){var t=core_getIteratorMethod(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return _anObject(t.call(e))},getIterator=core_getIterator,getIterator$1=createCommonjsModule(function(e){e.exports={default:getIterator,__esModule:!0}});unwrapExports(getIterator$1);var slicedToArray=createCommonjsModule(function(e,t){t.__esModule=!0;var r=n(isIterable$1),i=n(getIterator$1);function n(e){return e&&e.__esModule?e:{default:e}}t.default=function(){return function(e,t){if(Array.isArray(e))return e;if((0,r.default)(Object(e)))return function(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var s,u=(0,i.default)(e);!(n=(s=u.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&u.return&&u.return()}finally{if(o)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()}),_slicedToArray=unwrapExports(slicedToArray);_objectSap("getPrototypeOf",function(){return function(e){return _objectGpo(_toObject(e))}});var getPrototypeOf=_core.Object.getPrototypeOf,getPrototypeOf$1=createCommonjsModule(function(e){e.exports={default:getPrototypeOf,__esModule:!0}}),_Object$getPrototypeOf=unwrapExports(getPrototypeOf$1),getWeak=_meta.getWeak,arrayFind=_arrayMethods(5),arrayFindIndex=_arrayMethods(6),id$1=0,uncaughtFrozenStore=function(e){return e._l||(e._l=new UncaughtFrozenStore)},UncaughtFrozenStore=function(){this.a=[]},findUncaughtFrozen=function(e,t){return arrayFind(e.a,function(e){return e[0]===t})};UncaughtFrozenStore.prototype={get:function(e){var t=findUncaughtFrozen(this,e);if(t)return t[1]},has:function(e){return!!findUncaughtFrozen(this,e)},set:function(e,t){var r=findUncaughtFrozen(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=arrayFindIndex(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}};var _collectionWeak={getConstructor:function(e,t,r,i){var n=e(function(e,o){_anInstance(e,n,t,"_i"),e._t=t,e._i=id$1++,e._l=void 0,void 0!=o&&_forOf(o,r,e[i],e)});return _redefineAll(n.prototype,{delete:function(e){if(!_isObject(e))return!1;var r=getWeak(e);return!0===r?uncaughtFrozenStore(_validateCollection(this,t)).delete(e):r&&_has(r,this._i)&&delete r[this._i]},has:function(e){if(!_isObject(e))return!1;var r=getWeak(e);return!0===r?uncaughtFrozenStore(_validateCollection(this,t)).has(e):r&&_has(r,this._i)}}),n},def:function(e,t,r){var i=getWeak(_anObject(t),!0);return!0===i?uncaughtFrozenStore(e).set(t,r):i[e._i]=r,e},ufstore:uncaughtFrozenStore},es6_weakMap=createCommonjsModule(function(e){var t,r=_arrayMethods(0),i=_meta.getWeak,n=Object.isExtensible,o=_collectionWeak.ufstore,a={},s=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},u={get:function(e){if(_isObject(e)){var t=i(e);return!0===t?o(_validateCollection(this,"WeakMap")).get(e):t?t[this._i]:void 0}},set:function(e,t){return _collectionWeak.def(_validateCollection(this,"WeakMap"),e,t)}},c=e.exports=_collection("WeakMap",s,u,_collectionWeak,!0,!0);_fails(function(){return 7!=(new c).set((Object.freeze||Object)(a),7).get(a)})&&(t=_collectionWeak.getConstructor(s,"WeakMap"),_objectAssign(t.prototype,u),_meta.NEED=!0,r(["delete","has","get","set"],function(e){var r=c.prototype,i=r[e];_redefine(r,e,function(r,o){if(_isObject(r)&&!n(r)){this._f||(this._f=new t);var a=this._f[e](r,o);return"set"==e?this:a}return i.call(this,r,o)})}))});_setCollectionOf("WeakMap"),_setCollectionFrom("WeakMap");var weakMap=_core.WeakMap,weakMap$1=createCommonjsModule(function(e){e.exports={default:weakMap,__esModule:!0}}),_WeakMap=unwrapExports(weakMap$1),defineProperty$3=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=defineProperty$1)&&r.__esModule?r:{default:r};t.default=function(e,t,r){return t in e?(0,i.default)(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}}),_defineProperty=unwrapExports(defineProperty$3),meta=_meta.onFreeze;_objectSap("preventExtensions",function(e){return function(t){return e&&_isObject(t)?e(meta(t)):t}});var preventExtensions=_core.Object.preventExtensions,preventExtensions$1=createCommonjsModule(function(e){e.exports={default:preventExtensions,__esModule:!0}});unwrapExports(preventExtensions$1);var getOwnPropertyDescriptor$2=_Object$getOwnPropertyDescriptor;function isDescriptor(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 isAccessorDescriptor(e){return!!e&&(isFunction(e.get)||isFunction(e.set))&&isBoolean(e.configurable)&&isBoolean(e.enumerable)&&void 0===e.writable}function isDataDescriptor(e){return!!e&&e.hasOwnProperty("value")&&isBoolean(e.configurable)&&isBoolean(e.enumerable)&&isBoolean(e.writable)}function isInitializerDescriptor(e){return!!e&&isFunction(e.initializer)&&isBoolean(e.configurable)&&isBoolean(e.enumerable)&&isBoolean(e.writable)}function createDefaultSetter(e){return function(t){return _Object$defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t}),t}}function compressOneArgFnArray(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"You must pass me an array of function";if(!isArray(e)||e.length<1)throw new TypeError(t);if(1===e.length){if(!isFunction(e[0]))throw new TypeError(t);return e[0]}return e.reduce(function(e,r){if(!isFunction(r)||!isFunction(e))throw new TypeError(t);return function(t){return bind$1(r,this)(bind$1(e,this)(t))}})}function getOwnKeysFn(){var e=_Object$getOwnPropertyNames,t=_Object$getOwnPropertySymbols;return isFunction(t)?function(r){return _Array$from(e(r).concat(t(r)))}:e}var getOwnKeys=getOwnKeysFn();function getOwnPropertyDescriptorsFn(){return isFunction(_Object$getOwnPropertyDescriptors)?_Object$getOwnPropertyDescriptors:function(e){return getOwnKeys(e).reduce(function(t,r){return t[r]=getOwnPropertyDescriptor$2(e,r),t},{})}}var getOwnPropertyDescriptors$2=getOwnPropertyDescriptorsFn();function compressMultipleDecorators(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(!t.length)throw new TypeError("You must pass in decorators in compressMultipleDecorators");return t.forEach(function(e){if(!isFunction(e))throw new TypeError('Decorators must be a function, but not "'+e+'" in '+(void 0===e?"undefined":_typeof(e)))}),1===t.length?t[0]:function(e,r,i){return t.reduce(function(t,i){return i(e,r,t)},i)}}function accessor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.get,r=e.set,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.preGet,o=void 0!==n&&n,a=i.preSet,s=void 0===a||a;if(!(isFunction(t)||isFunction(r)||isArray(t)&&t.length>0||isArray(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 u="@accessor only accept function or array of function as getter/setter";return t=isArray(t)?compressOneArgFnArray(t,u):t,r=isArray(r)?compressOneArgFnArray(r,u):r,function(e,i,n){var a=n||{},u=a.configurable,c=void 0===u||u,l=a.enumerable,d=void 0===l||l,f=isFunction(t),h=isFunction(r),p=function(e){return f?bind$1(t,this)(e):e},m=function(e){return h?bind$1(r,this)(e):e};if(isAccessorDescriptor(n)){var v=n.get,g=n.set,y=isFunction(v),_=isFunction(g);return{get:y||f?function(){var e=this,t=bind$1(p,this),r=function(){return y?bind$1(v,e)():void 0};return(o?[t,r]:[r,t]).reduce(function(e,t){return t(e)},void 0)}:void 0,set:_||h?function(e){var t=this,r=bind$1(m,this),i=function(e){return _?bind$1(g,t)(e):e};return(s?[r,i]:[i,r]).reduce(function(e,t){return t(e)},e)}:void 0,configurable:c,enumerable:d}}if(isInitializerDescriptor(n)){var b=n.initializer,w=void 0,E=!1;return{get:function(){var e=bind$1(p,this);return E?e(w):(w=bind$1(b,this)(),E=!0,e(w))},set:function(e){var t=bind$1(m,this);return w=s?t(e):e,E=!0,s||t(w),w},configurable:c,enumerable:d}}var S=(n||{}).value;return{get:function(){return bind$1(p,this)(S)},set:function(e){var t=bind$1(m,this);return S=s?t(e):e,s||t(S),S},configurable:c,enumerable:d}}}function before(){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&&isDescriptor(t[2]))throw new Error("You may use @before straightly, @before return decorators, you should call it before you set it as decorator.");for(var i=t.length-1;i>-1;i--)if(!isFunction(t[i]))throw new TypeError("@before only accept function parameter");return function(e,r,i){var n=i||{},o=n.value,a=n.configurable,s=n.enumerable,u=n.writable;if(!isFunction(o))throw new TypeError('@before can only be used on function, please check the property "'+r+'" is a method or not.');return{value:function(){for(var e=this,r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];var a=t.reduce(function(t,r){var i=bind$1(r,e).apply(void 0,_toConsumableArray(t));return void 0===i?t:isArray(i)?i:[i]},i);return bind$1(o,this).apply(void 0,_toConsumableArray(a))},configurable:a,enumerable:s,writable:u}}}function after(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@after accept at least one parameter. If you don't need to preprocess after your function, do not add @after decorators");if(t.length>2&&isDescriptor(t[2]))throw new Error("You may have used @after straightly. @after return decorators. You should call it before you use it as decorators");var i=compressOneArgFnArray(t,"@after only accept function parameter");return function(e,t,r){var n=r||{},o=n.value,a=n.configurable,s=n.enumerable,u=n.writable;if(!isFunction(o))throw new TypeError('@after can only be used on function, please checkout your property "'+t+'" is a method or not.');return{value:function(){var e=bind$1(o,this).apply(void 0,arguments);return bind$1(i,this)(e)},configurable:a,enumerable:s,writable:u}}}function initialize(){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&&isDescriptor(t[2]))throw new Error("You may use @initialize straightly, @initialize return decorators, you need to call it");var i=compressOneArgFnArray(t,"@initialize only accept function parameter");return function(e,t,r){if(void 0===r)return{value:bind$1(i,e)(),configurable:!0,writable:!0,enumerable:!0};if(isAccessorDescriptor(r)){var n=!1;return accessor({get:function(e){return n?e:bind$1(i,this)(e)},set:r.set?function(e){return n=!0,e}:void 0})(e,t,r)}if(isInitializerDescriptor(r)){var o=r.initializer;return{initializer:function(){return bind$1(i,this)(bind$1(o,this)())},configurable:r.configurable,writable:r.writable,enumerable:r.enumerable}}return{value:bind$1(i,this)(r.value),writable:r.writable,configurable:r.configurable,enumerable:r.enumerable}}}var getOwnPropertyDescriptor$1$1=_Object$getOwnPropertyDescriptor,defineProperty$4=_Object$defineProperty;function setAlias(e,t,r,i,n,o){var a=r.configurable,s=r.enumerable,u=o.force,c=o.omit,l=getOwnPropertyDescriptor$1$1(i,n);if(void 0!==l){if(c)return;if(!u)throw new Error('"'+t+'" is an existing property, if you want to override it, please set "force" true in @alias option.');if(!l.configurable)throw new Error('property "'+t+'" is unconfigurable.')}defineProperty$4(i,n,{get:function(){return e[t]},set:function(r){return e[t]=r,t},configurable:a,enumerable:s})}function alias(e,t,r){if(2===arguments.length?isString(e)&&(r=t,t=e,e=void 0):1===arguments.length&&(t=e,e=void 0),!isString(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&&isPrimitive(e))throw new TypeError(i);var n=isObject(r)?r:{force:!1,omit:!1},o=n.force,a=n.omit;return function(r,n,s){function u(e,t,r){var n=isPrimitive(e)?t:e,o=r.split("."),a=o.slice(-1),s=_slicedToArray(a,1)[0];if(isPrimitive(n=getDeepProperty$1(n,o.slice(0,-1),{throwError:!0})))throw new TypeError(i);return{target:n,name:s}}if(isInitializerDescriptor(s=s||{value:void 0,configurable:!0,writable:!0,enumerable:!0}))return initialize(function(r){var i=u(e,this,t),c=i.target,l=i.name;return setAlias(this,n,s,c,l,{force:o,omit:a}),r})(r,n,s);if(isAccessorDescriptor(s)){var c=void 0,l=function(r){if(c)return r;var i=u(e,this,t),l=i.target,d=i.name;return setAlias(this,n,s,l,d,{force:o,omit:a}),c=!0,r};return accessor({get:l,set:l})(r,n,s)}var d=u(e,r,t),f=d.target,h=d.name;return setAlias(r,n,s,f,h,{force:o,omit:a}),s}}var defineProperty$1$1=_Object$defineProperty;function classify(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.requirement,i=t.customArgs,n=void 0!==i&&i;return function(){for(var t=arguments.length,i=Array(t>1?t-1:0),o=1;o<t;o++)i[o-1]=arguments[o];var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=a.exclude,u=void 0===s?[]:s,c=a.include,l=void 0===c?[]:c,d=a.construct,f=void 0!==d&&d,h=a.self,p=void 0!==h&&h;if(!isArray(u))throw new TypeError("options.exclude must be an array");if(!isArray(l))throw new TypeError("options.include must be an array");return function(t){var o=isFunction(t);if(!p&&!o)throw new TypeError("@"+e.name+"Class can only be used on class");if(p&&isPrimitive(t))throw new TypeError("@"+e.name+"Class must be used on non-primitive type value in 'self' mode");var a=p?t:t.prototype;if(isVoid(a))throw new Error("The prototype of the "+t.name+" is empty, please check it");var s=getOwnPropertyDescriptors$2(a);getOwnKeys(a).concat(l).forEach(function(t){var c=s[t];"constructor"===t&&!f||p&&o&&["name","length","prototype"].indexOf(t)>-1||u.indexOf(t)>-1||isFunction(r)&&!1===r(a,t,c,{self:p})||defineProperty$1$1(a,t,(n?e.apply(void 0,_toConsumableArray(i)):e)(a,t,c))})}}}var autobindClass=classify(autobind,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)}}),mapStore=void 0;function getBoundSuper(e,t){if(void 0===_WeakMap)throw new Error("Using @autobind on "+t.name+"() requires WeakMap support due to its use of super."+t.name+"()");mapStore||(mapStore=new _WeakMap),!1===mapStore.has(e)&&mapStore.set(e,new _WeakMap);var r=mapStore.get(e);return!1===r.has(t)&&r.set(t,bind$1(t,e)),r.get(t)}function autobind(e,t,r){if(1===arguments.length)return autobindClass()(e);var i=r||{},n=i.value,o=i.configurable;if(!isFunction(n))throw new TypeError('@autobind can only be used on functions, not "'+n+'" in '+(void 0===n?"undefined":_typeof(n))+' on property "'+t+'"');var a=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(_toConsumableArray(t)))};return this===e?n:this.constructor!==a&&_Object$getPrototypeOf(this).constructor===a?n:this.constructor!==a&&t in this.constructor.prototype?getBoundSuper(this,n):(_Object$defineProperty(this,t,{configurable:!0,writable:!0,enumerable:!1,value:i}),i)},set:createDefaultSetter(t)}}var defineProperty$2$1=_Object$defineProperty;function frozen(e,t,r){if(void 0===r)return{value:void 0,writable:!1,enumerable:!1,configurable:!1};if(r.enumerable=!1,r.configurable=!1,isAccessorDescriptor(r)){var i=r.get;if(r.set=void 0,!isFunction(i))return;return{get:function(){var e=bind$1(i,this)();return defineProperty$2$1(this,t,{value:e,writable:!1,configurable:!1,enumerable:!1}),e},set:void 0,configurable:!1,enumerable:!1}}return r.writable=!1,r}var getOwnPropertyDescriptor$2$1=_Object$getOwnPropertyDescriptor,defineProperty$3$1=_Object$defineProperty;function waituntil(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).other;if(!isFunction(e)&&!isPromise(e)&&!isString(e))throw new TypeError("@waitUntil only accept Function, Promise or String");return function(r,i,n){var o=n||{},a=o.value,s=o.configurable;if(!isFunction(a))throw new TypeError("@waituntil can only be used on function, but not "+a+' on property "'+i+'"');var u=!1,c=[],l=isPromise(e)?function(){return e}:isFunction(e)?e:function(){var r=e.split("."),i=r.slice(-1),n=isPrimitive(t)?this:t;if(!u){var o=getDeepProperty$1(n,r.slice(0,-1));if(isVoid(o))return o;var a=getOwnPropertyDescriptor$2$1(o,i),s=function(e){if(!0===e)for(;c.length>0;)c[0](),c.shift();return e},l=isDescriptor(a)?accessor({set:s})(o,i,a):accessor({set:s})(o,i,{value:void 0,configurable:!0,enumerable:!0,writable:!0});defineProperty$3$1(o,i,l),u=!0}return getDeepProperty$1(n,r)};return{value:function(){for(var e=this,t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];var n=bind$1(a,this),o=bind$1(l,this).apply(void 0,r);return isPromise(o)?_Promise.resolve(o).then(function(){return bind$1(a,e).apply(void 0,r)}):!0===o?bind$1(a,this).apply(void 0,r):new _Promise(function(e){c.push(function(){n.apply(void 0,r),e()})})},enumerable:!1,configurable:s,writable:!1}}}function nonenumerable(e,t,r){return void 0===r?{value:void 0,enumerable:!1,configurable:!0,writable:!0}:(r.enumerable=!1,r)}var defineProperty$6=_Object$defineProperty,getOwnPropertyDescriptor$3=_Object$getOwnPropertyDescriptor;function applyDecorators(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.self,n=void 0!==i&&i,o=r.omit,a=void 0!==o&&o,s=isFunction(t);if(s||isArray(t)){if(!isFunction(e))throw new TypeError("If you want to decorator class, you must pass it a legal class");if(s)t(e);else for(var u=0,c=t.length;u<c;u++){var l=t[u];if(!isFunction(l))throw new TypeError("If you want to decorate an class, you must pass it function or array of function");l(e)}return e}if(!n&&!isFunction(e))throw new TypeError("applyDecorators only accept class as first arguments. If you want to modify instance, you should set options.self true.");if(n&&isPrimitive(e))throw new TypeError("We can't apply docorators on a primitive value, even in self mode");if(!isObject(t))throw new TypeError("applyDecorators only accept object as second arguments");var d=n?e:e.prototype;if(isVoid(d))throw new Error("The class muse have a prototype, please take a check");for(var f in t){var h=t[f],p=isArray(h)?h:[h],m=void 0;try{m=compressMultipleDecorators.apply(void 0,_toConsumableArray(p))}catch(e){throw new Error("The decorators set on props must be Function or Array of Function")}var v=getOwnPropertyDescriptor$3(d,f);if(!v||v.configurable)defineProperty$6(d,f,m(d,f,v));else if(!a)throw new Error(f+" of "+d+" is unconfigurable")}return e}var arrayChangeMethod=["push","pop","unshift","shift","splice","sort","reverse"];function deepProxy(e,t,r){var i,n=r.diff,o=r.operationPrefix,a={},s=!1,u=new Proxy(e,{get:function(e,r,i){var u=e[r];if(isArray(e)&&arrayChangeMethod.indexOf(r)>-1)return function(){s=!0,bind$1(u,i).apply(void 0,arguments),s=!1,t()};if(!0===a[r])return u;if(isObject(u)||isArray(u)){var c=a[r]||deepProxy(u,t,{diff:n,operationPrefix:o});return a[r]=c,c}return a[r]=!0,u},set:function(e,r,i){var u=e[r],c=isObject(i)||isArray(i)?deepProxy(i,t,{diff:n,operationPrefix:o}):i;return e[r]=c,a[r]=!0,!!(s||n&&u===c)||(t(),!0)},deleteProperty:function(e,r){return delete e[r],delete a[r],!!s||(t(),!0)}}),c=(_defineProperty(i={},o+"set",[initialize(function(e){return function(e,t){u[e]=t}}),nonenumerable]),_defineProperty(i,o+"del",[initialize(function(e){return function(e){delete u[e]}}),nonenumerable]),i);return applyDecorators(u,c,{self:!0}),u}function deepObserve(e,t,r){var i,n=this,o=r.operationPrefix,a=r.diff,s={},u=!1;function c(e){var r=void 0;return e.reduce(function(e,i){return e[i]=[accessor({set:function(e){return r=this[i],e}}),accessor({get:function(e){return s[i]?e:((isObject(e)||isArray(e))&&deepObserve(e,t,{operationPrefix:o,diff:a}),s[i]=!0,e)},set:function(e){return(isObject(e)||isArray(e))&&deepObserve(e,t,{operationPrefix:o,diff:a}),s[i]=!0,u||a&&r===e||t(),e}},{preSet:!1})],e},{})}var l=c(getOwnKeys(e));if(applyDecorators(e,l,{self:!0,omit:!0}),isArray(e)){var d=arrayChangeMethod.reduce(function(r,i){return r[i]=[initialize(function(r){return r=isFunction(r)?r:Array.prototype[i],function(){var i=e.length;if(u=!0,bind$1(r,e).apply(void 0,arguments),u=!1,i<e.length){var n=c(new Array(e.length-i).fill(1).map(function(e,t){return(t+i).toString()}));applyDecorators(e,n,{self:!0,omit:!0})}t()}}),nonenumerable],r},{});applyDecorators(e,d,{self:!0})}var f=(_defineProperty(i={},o+"set",[initialize(function(t){return function(r,i){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=o.disable,s=o.isNewVal;if(s=s||-1===getOwnKeys(e).indexOf(r),isFunction(t)&&bind$1(t,n)(r,i,{disable:!0,isNewVal:s}),s){var u=c([r]);applyDecorators(e,u,{self:!0,omit:!0})}a||(e[r]=i)}}),nonenumerable]),_defineProperty(i,o+"del",[initialize(function(r){return function(i){isFunction(r)?bind$1(r,n)(i):delete e[i],t()}}),nonenumerable]),i);return applyDecorators(e,f,{self:!0}),e}function watch(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isObject(t[t.length-1])?t[t.length-1]:{},n=i.deep,o=i.omit,a=i.other,s=i.operationPrefix,u=void 0===s?"__":s,c=i.diff,l=void 0===c||c,d=i.proxy;if("function"!=typeof Proxy&&(d=!1),!t.length)throw new TypeError("You must pass a function or a string to find the hanlder function.");if(void 0!==a&&isPrimitive(a))throw new TypeError("If you want us to trigger function on the other instance, you must pass in a legal instance");if(!isString(u))throw new TypeError("operationPrefix must be an string");return function(e,r,i){var s=t.reduce(function(r,i,n){if(!isString(i)&&!isFunction(i)){if(!n||n!==t.length-1)throw new TypeError("You can only pass function or string as handler");return r}return r.push(isString(i)?function(t,r){var n=getDeepProperty$1(a||e,i);if(isFunction(n))return bind$1(n,this)(t,r);if(!o)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},[]),c=function(e,t){var r=this;s.forEach(function(i){return bind$1(i,r)(e,t)})},f=!1,h=void 0,p=void 0,m=void 0;return compressMultipleDecorators(accessor({set:function(e){var t=this;h=this[r],m=void 0;var i=function(){return bind$1(c,t)(p,h)};return n&&(isObject(e)||isArray(e))?d?deepProxy(e,i,{diff:l,operationPrefix:u}):deepObserve(e,i,{operationPrefix:u,diff:l}):e},get:function(e){var t=this;if(m)return m;if(!f){f=!0;var r=function(){return bind$1(c,t)(p,h)};if(n&&(isObject(e)||isArray(e))){if(d)return m=deepProxy(e,r,{diff:l,operationPrefix:u}),h=m,p=m,m;deepObserve(e,r,{operationPrefix:u,diff:l})}h=e,p=e}return e}},{preSet:!0}),accessor({set:function(e){return p=e,l&&h===e||bind$1(c,this)(p,h),h=e,e}},{preSet:!1}))(e,r,i)}}function runnable(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.other,i=t.backup;if(!isFunction(e)&&!isString(e))throw new TypeError("@runnable only accept Function or String");return function(t,n,o){var a=o||{},s=a.value,u=a.configurable;if(!isFunction(s))throw new TypeError("@runnable can only be used on method, but not "+s+' on property "'+n+'".');var c=isFunction(e)?e:function(){var t=e.split(".");return getDeepProperty$1(isPrimitive(r)?this:r,t)};return i=isFunction(i)?i:function(){},{value:function(){return!0===bind$1(c,this).apply(void 0,arguments)?bind$1(s,this).apply(void 0,arguments):bind$1(i,this).apply(void 0,arguments)},enumerable:!1,configurable:u,writable:!1}}}function nonconfigurable(e,t,r){return void 0===r?{value:void 0,enumerable:!0,configurable:!0,writable:!0}:(r.configurable=!0,r)}function string(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isString(t[0])?t.shift():"";return t.unshift(function(e){return isString(e)?e:i}),initialize.apply(void 0,t)}function boolean(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=!!isBoolean(t[0])&&t.shift();return t.unshift(function(e){return isBoolean(e)?e:i}),initialize.apply(void 0,t)}function string$1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isString(t[0])?t.shift():"";return t.unshift(function(e){return isString(e)?e:i}),accessor({set:t,get:t})}function boolean$1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=!!isBoolean(t[0])&&t.shift();return t.unshift(function(e){return isBoolean(e)?e:i}),accessor({set:t,get:t})}function number$1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isNumber(t[0])?t.shift():0;return t.unshift(function(e){return isNumber(e)?e:i}),accessor({set:t,get:t})}var before$1=classify(before,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0}),after$1=classify(after,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0}),runnable$1=classify(runnable,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0}),waituntil$1=classify(waituntil,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0});_export(_export.S,"Number",{isNaN:function(e){return e!=e}});var isNan=_core.Number.isNaN,isNan$1=createCommonjsModule(function(e){e.exports={default:isNan,__esModule:!0}}),_Number$isNaN=unwrapExports(isNan$1),$JSON$1=_core.JSON||(_core.JSON={stringify:JSON.stringify}),stringify=function(e){return $JSON$1.stringify.apply($JSON$1,arguments)},stringify$1=createCommonjsModule(function(e){e.exports={default:stringify,__esModule:!0}}),_JSON$stringify=unwrapExports(stringify$1),possibleConstructorReturn=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=_typeof_1)&&r.__esModule?r:{default:r};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,i.default)(t))&&"function"!=typeof t?e:t}}),_possibleConstructorReturn=unwrapExports(possibleConstructorReturn),get=createCommonjsModule(function(e,t){t.__esModule=!0;var r=n(getPrototypeOf$1),i=n(getOwnPropertyDescriptor$1);function n(e){return e&&e.__esModule?e:{default:e}}t.default=function e(t,n,o){null===t&&(t=Function.prototype);var a=(0,i.default)(t,n);if(void 0===a){var s=(0,r.default)(t);return null===s?void 0:e(s,n,o)}if("value"in a)return a.value;var u=a.get;return void 0!==u?u.call(o):void 0}}),_get=unwrapExports(get),check=function(e,t){if(_anObject(e),!_isObject(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},_setProto={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=_ctx(Function.call,_objectGopd.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return check(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:check};_export(_export.S,"Object",{setPrototypeOf:_setProto.set});var setPrototypeOf=_core.Object.setPrototypeOf,setPrototypeOf$1=createCommonjsModule(function(e){e.exports={default:setPrototypeOf,__esModule:!0}});unwrapExports(setPrototypeOf$1);var inherits=createCommonjsModule(function(e,t){t.__esModule=!0;var r=o(setPrototypeOf$1),i=o(create$1),n=o(_typeof_1);function o(e){return e&&e.__esModule?e:{default:e}}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,n.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}}),_inherits=unwrapExports(inherits),VENDOR_PREFIXES=["","o","ms","moz","webkit","webkitCurrent"],SYNONYMS=[["",""],["exit","cancel"],["screen","Screen"]],DESKTOP_FULLSCREEN_STYLE={position:"fixed",zIndex:"2147483647",left:0,top:0,right:0,bottom:0,overflow:"hidden",width:"100%",height:"100%"},FULLSCREEN_CHANGE=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],FULLSCREEN_ERROR=["fullscreenerror","webkitfullscreenerror","mozfullscreenerror","MSFullscreenError"],supportDocument="undefined"!=typeof document,_dec,_dec2,_dec3,_dec4,_dec5,_class,_class2;function setStyle$1(e,t,r){if(isObject(t))for(var i in t)setStyle$1(e,i,t[i]);else e.style[t]=r}function native(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};isObject(t)&&(r=t),isString(e)&&(t=e);var i=r.keyOnly,n=void 0!==i&&i;if(!supportDocument)return n?"":void 0;if(isElement(e)||(e=document),!isString(t))throw new Error("You must pass in a string as name, but not "+(void 0===t?"undefined":_typeof(t))+".");for(var o=0;o<SYNONYMS.length;o++){t=t.replace(SYNONYMS[o][0],SYNONYMS[o][1]);for(var a=0;a<VENDOR_PREFIXES.length;a++){var s=0===a?t:VENDOR_PREFIXES[a]+t.charAt(0).toUpperCase()+t.substr(1);if(void 0!==e[s])return n?s:e[s]}}return n?"":void 0}function dispatchEvent(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.bubbles,n=void 0===i||i,o=r.cancelable,a=void 0===o||o,s=void 0;if(isFunction(Event)?s=new Event(t,{bubbles:n,cancelable:a}):supportDocument&&document.createEvent?(s=document.createEvent("HTMLEvents")).initEvent(t,!0,!0):supportDocument&&document.createEventObject&&((s=document.createEventObject()).eventType=t,s.eventName=t),!isObject(s)&&!isEvent(s))throw new Error("We can't create an object on this browser, please report to author");e.dispatchEvent?e.dispatchEvent(s):e.fireEvent?e.fireEvent("on"+s.eventType,s):e[t]?e[t]():e["on"+t]&&e["on"+t]()}function _applyDecoratedDescriptor(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var fullscreenEnabled=native("fullscreenEnabled"),useStyleFirst=!1,ESFullScreen=(_dec=autobindClass(),_dec2=alias("requestFullscreen"),_dec3=alias("exitFullscreen"),_dec4=alias("addEventListener"),_dec5=alias("removeEventListener"),_dec((_class2=function(){function e(){_classCallCheck(this,e),this._fullscreenElement=null,this.isNativelySupport=defined(native("fullscreenElement"))&&(!defined(fullscreenEnabled)||!0===fullscreenEnabled),this._openKey=supportDocument?native(document.body||document.documentElement,"requestFullscreen",{keyOnly:!0}):"",this._exitKey=native("exitFullscreen",{keyOnly:!0}),this._useStyleFirst=!1,this.hasUsedStyle=!1}return _createClass(e,[{key:"open",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).force,r=void 0!==t&&t,i=this.fullscreenElement;if(i&&i!==e){if(!r)return dispatchEvent(document,"fullscreenerror"),!1;this.exit()}if(!this.useStyleFirst){if(this.isNativelySupport)return isFunction(e[this._openKey])&&e[this._openKey](),!0;if(e instanceof HTMLVideoElement&&e.webkitSupportsFullscreen&&isFunction(e.webkitEnterFullscreen))return e.webkitEnterFullscreen(),this._fullscreenElement=e,!0}return this._savedStyles=_Object$keys(DESKTOP_FULLSCREEN_STYLE).reduce(function(t,r){return t[r]=e.style[r],t},{}),setStyle$1(e,DESKTOP_FULLSCREEN_STYLE),document.body&&(this._bodyOverflow=document.body.style.overflow,document.body.style.overflow="hidden"),document.documentElement&&(this._htmlOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden"),this._fullscreenElement=e,this.hasUsedStyle=!0,dispatchEvent(e,"fullscreenchange"),!0}},{key:"exit",value:function(){if(!this.isFullscreen)return!1;if(this.isNativelySupport&&!this.useStyleFirst&&!this.hasUsedStyle)return document[this._exitKey](),!0;var e=this._fullscreenElement;return setStyle$1(e,this._savedStyles),document.body&&(document.body.style.overflow=this._bodyOverflow),document.documentElement&&(document.documentElement.style.overflow=this._htmlOverflow),this._fullscreenElement=null,this._savedStyles={},dispatchEvent(e,"fullscreenchange"),!0}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document;this._handleEvent(r,"addEventListener",e,t)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document;this._handleEvent(r,"removeEventListener",e,t)}},{key:"_handleEvent",value:function(e,t,r,i){("fullscreenchange"===r?FULLSCREEN_CHANGE:"fullscreenerror"===r?FULLSCREEN_ERROR:[r]).forEach(function(r){e[t](r,i)})}},{key:"useStyleFirst",get:function(){return useStyleFirst},set:function(e){return(e=!!e)===useStyleFirst?e:(useStyleFirst=e,dispatchEvent(document,"esfullscreenmethodchange"),e)}},{key:"fullscreenElement",get:function(){return["fullscreenElement","webkitFullscreenElement","mozFullScreenElement","msFullscreenElement"].reduce(function(e,t){return e||document[t]},null)||this._fullscreenElement}},{key:"isFullscreen",get:function(){return isElement(this.fullscreenElement)}}]),e}(),_applyDecoratedDescriptor(_class2.prototype,"open",[_dec2],_Object$getOwnPropertyDescriptor(_class2.prototype,"open"),_class2.prototype),_applyDecoratedDescriptor(_class2.prototype,"exit",[_dec3],_Object$getOwnPropertyDescriptor(_class2.prototype,"exit"),_class2.prototype),_applyDecoratedDescriptor(_class2.prototype,"on",[_dec4],_Object$getOwnPropertyDescriptor(_class2.prototype,"on"),_class2.prototype),_applyDecoratedDescriptor(_class2.prototype,"off",[_dec5],_Object$getOwnPropertyDescriptor(_class2.prototype,"off"),_class2.prototype),_class=_class2))||_class),index=new ESFullScreen,isEnum$1=_objectPie.f,_objectToArray=function(e){return function(t){for(var r,i=_toIobject(t),n=_objectKeys(i),o=n.length,a=0,s=[];o>a;)isEnum$1.call(i,r=n[a++])&&s.push(e?[r,i[r]]:i[r]);return s}},$entries=_objectToArray(!0);_export(_export.S,"Object",{entries:function(e){return $entries(e)}});var entries=_core.Object.entries,entries$1=createCommonjsModule(function(e){e.exports={default:entries,__esModule:!0}}),_Object$entries=unwrapExports(entries$1),tempCurrentTime=0,NativeVideoKernel=function(e){function t(e,r,i){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(!isElement(e))throw new Error("You must pass in an legal video element but not "+(void 0===e?"undefined":_typeof(e)));return n.video=e,n.config=r,n.customConfig=i,n}return _inherits(t,CustEvent),_createClass(t,null,[{key:"isSupport",value:function(){return!0}}]),_createClass(t,[{key:"load",value:function(e){this.video.setAttribute("src",e),this.video.src=e}},{key:"startLoad",value:function(e){var t=this.video.currentTime||tempCurrentTime;this.load(e),this.seek(t)}},{key:"stopLoad",value:function(){tempCurrentTime=this.video.currentTime,this.video.src="",this.video.removeAttribute("src")}},{key:"destroy",value:function(){isElement(this.video)&&this.stopLoad()}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}},{key:"refresh",value:function(){this.video.src=this.config.src}},{key:"attachMedia",value:function(){}},{key:"seek",value:function(e){this.video.currentTime=e}}]),t}(),defaultConfig={isLive:!1,box:"",preset:{},presetConfig:{}},LOG_TAG="chimee-kernel",kernelEvents=["mediaInfo","heartbeat","error"],boxSuffixMap={flv:".flv",hls:".m3u8",mp4:".mp4"},ChimeeKernel=function(e){function t(e,r){_classCallCheck(this,t);var i=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(i.VERSION="1.4.0",!isElement(e))throw new Error("You must pass in an video element to the chimee-kernel");return i.config=deepAssign({},defaultConfig,r),i.videoElement=e,i.initVideoKernel(),i.bindEvents(i.videoKernel),i}return _inherits(t,CustEvent),_createClass(t,[{key:"destroy",value:function(){this.bindEvents(this.videoKernel,!0),this.videoKernel.destroy()}},{key:"initVideoKernel",value:function(){var e=this.config,t=this.chooseBox(e);this.box=t;var r=this.chooseVideoKernel(this.box,e.preset);if(!isFunction(r))throw new Error("We can't find video kernel for "+t+". Please check your config and make sure it's installed or provided");var i=e.presetConfig[this.box]||{};deepAssign(e,i),this.videoKernel=new r(this.videoElement,e,i)}},{key:"chooseBox",value:function(e){var t=e.src,r=e.box;if(isString(r)&&r)return r;for(var i in t=t.toLowerCase(),boxSuffixMap){var n=boxSuffixMap[i];if(t.indexOf(n)>-1)return i}return"native"}},{key:"chooseVideoKernel",value:function(e,t){switch(e){case"native":return NativeVideoKernel;case"mp4":return this.getMp4Kernel(t.mp4);case"flv":case"hls":return t[e];default:throw new Error("We currently do not support box "+e+", please contact us through https://github.com/Chimeejs/chimee/issues.")}}},{key:"getMp4Kernel",value:function(e){var t=e&&isFunction(e.isSupport);return t&&e.isSupport()?e:(t&&this.warnLog("mp4 decode is not support in this browser, we will switch to the native video kernel"),this.box="native",NativeVideoKernel)}},{key:"errorLog",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.emit("error",new Error(t[0])),Log$1.error.apply(Log$1,[LOG_TAG].concat(t))}},{key:"warnLog",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return Log$1.warn.apply(Log$1,[LOG_TAG].concat(t))}},{key:"bindEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];kernelEvents.forEach(function(i){e[r?"off":"on"](i,function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).data;t.emit(i,e)})})}},{key:"attachMedia",value:function(){this.videoKernel.attachMedia()}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.src;this.config.src=e,this.videoKernel.load(e)}},{key:"startLoad",value:function(){if(!isFunction(this.videoKernel.startLoad))throw new Error("This video kernel do not support startLoad, please contact us on https://github.com/Chimeejs/chimee/issues");this.videoKernel.startLoad(this.config.src)}},{key:"stopLoad",value:function(){isFunction(this.videoKernel.stopLoad)&&this.videoKernel.stopLoad()}},{key:"play",value:function(){this.videoKernel.play()}},{key:"pause",value:function(){this.videoKernel.pause()}},{key:"seek",value:function(e){isNumber(e)?this.videoKernel.seek(e):this.errorLog("When you try to seek, you must offer us a number, but not "+(void 0===e?"undefined":_typeof(e)))}},{key:"refresh",value:function(){this.videoKernel.refresh()}},{key:"currentTime",get:function(){return this.videoElement.currentTime||0}}]),t}(),_global$1=createCommonjsModule(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)}),_core$1=createCommonjsModule(function(e){var t=e.exports={version:"2.5.3"};"number"==typeof __e&&(__e=t)}),_core_1$1=_core$1.version,_isObject$1=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_anObject$1=function(e){if(!_isObject$1(e))throw TypeError(e+" is not an object!");return e},_fails$1=function(e){try{return!!e()}catch(e){return!0}},_descriptors$1=!_fails$1(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),document$3=_global$1.document,is$1=_isObject$1(document$3)&&_isObject$1(document$3.createElement),_domCreate$1=function(e){return is$1?document$3.createElement(e):{}},_ie8DomDefine$1=!_descriptors$1&&!_fails$1(function(){return 7!=Object.defineProperty(_domCreate$1("div"),"a",{get:function(){return 7}}).a}),_toPrimitive$1=function(e,t){if(!_isObject$1(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!_isObject$1(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!_isObject$1(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!_isObject$1(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},dP$4=Object.defineProperty,f$8=_descriptors$1?Object.defineProperty:function(e,t,r){if(_anObject$1(e),t=_toPrimitive$1(t,!0),_anObject$1(r),_ie8DomDefine$1)try{return dP$4(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},_objectDp$1={f:f$8},_propertyDesc$1=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_hide$1=_descriptors$1?function(e,t,r){return _objectDp$1.f(e,t,_propertyDesc$1(1,r))}:function(e,t,r){return e[t]=r,e},hasOwnProperty$1={}.hasOwnProperty,_has$1=function(e,t){return hasOwnProperty$1.call(e,t)},id$2=0,px$1=Math.random(),_uid$1=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id$2+px$1).toString(36))},_redefine$1=createCommonjsModule(function(e){var t=_uid$1("src"),r=Function.toString,i=(""+r).split("toString");_core$1.inspectSource=function(e){return r.call(e)},(e.exports=function(e,r,n,o){var a="function"==typeof n;a&&(_has$1(n,"name")||_hide$1(n,"name",r)),e[r]!==n&&(a&&(_has$1(n,t)||_hide$1(n,t,e[r]?""+e[r]:i.join(String(r)))),e===_global$1?e[r]=n:o?e[r]?e[r]=n:_hide$1(e,r,n):(delete e[r],_hide$1(e,r,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[t]||r.call(this)})}),_aFunction$1=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx$1=function(e,t,r){if(_aFunction$1(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)}},PROTOTYPE$3="prototype",$export$1=function(e,t,r){var i,n,o,a,s=e&$export$1.F,u=e&$export$1.G,c=e&$export$1.S,l=e&$export$1.P,d=e&$export$1.B,f=u?_global$1:c?_global$1[t]||(_global$1[t]={}):(_global$1[t]||{})[PROTOTYPE$3],h=u?_core$1:_core$1[t]||(_core$1[t]={}),p=h[PROTOTYPE$3]||(h[PROTOTYPE$3]={});for(i in u&&(r=t),r)o=((n=!s&&f&&void 0!==f[i])?f:r)[i],a=d&&n?_ctx$1(o,_global$1):l&&"function"==typeof o?_ctx$1(Function.call,o):o,f&&_redefine$1(f,i,o,e&$export$1.U),h[i]!=o&&_hide$1(h,i,a),l&&p[i]!=o&&(p[i]=o)};_global$1.core=_core$1,$export$1.F=1,$export$1.G=2,$export$1.S=4,$export$1.P=8,$export$1.B=16,$export$1.W=32,$export$1.U=64,$export$1.R=128;var _export$1=$export$1;_export$1(_export$1.G,{global:_global$1});var global$1=_core$1.global,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"],videoReadOnlyProperties=["buffered","currentSrc","duration","error","ended","networkState","paused","readyState","seekable","sinkId","controlsList","tabIndex","dataset","offsetHeight","offsetLeft","offsetParent","offsetTop","offsetWidth"],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","mousewheel","fullscreenchange","contextmenu","touchstart","touchmove","touchend"],passiveEvents=["wheel","mousewheel","touchstart","touchmove"],selfProcessorEvents=["silentLoad","fullscreen"],kernelMethods=["play","pause","seek","startLoad","stopLoad"],dispatcherMethods=["load"],kernelEvents$1=["mediaInfo","heartbeat","error"],domMethods=["focus","fullscreen","requestFullscreen","exitFullscreen"],videoMethods=["canPlayType","captureStream","setSinkId"],_dec$1,_dec2$1,_dec3$1,_dec4$1,_class$1;function _applyDecoratedDescriptor$1(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var secondaryReg=/^(before|after|_)/;function secondaryChecker(e){return!e.match(secondaryReg)}var Bus=(_dec$1=runnable(secondaryChecker),_dec2$1=runnable(secondaryChecker,{backup:function(){return!1}}),_dec3$1=runnable(secondaryChecker),_dec4$1=runnable(secondaryChecker,{backup:function(){return!1}}),_class$1=function(){function e(t){_classCallCheck(this,e),this.events={},this.onceMap={},this.__dispatcher=t}return _createClass(e,[{key:"on",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,o=i.key;this._addEvent([o,n,e],r)}},{key:"off",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,o=[i.key,n,e];if(!this._removeEvent(o,r)){var a=this._getHandlerFromOnceMap(o,r);isFunction(a)&&this._removeEvent(o,a)&&this._removeFromOnceMap(o,r,a)}}},{key:"once",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,o=this,a=[i.key,n,e],s=function e(){bind(r,this).apply(void 0,arguments),o._removeEvent(a,e),o._removeFromOnceMap(a,r,e)};this._addEvent(a,s),this._addToOnceMap(a,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];var o=this.events[e];if(isEmpty(o))return selfProcessorEvents.indexOf(e)>-1?_Promise.resolve():this._eventProcessor.apply(this,[e,{sync:!1}].concat(_toConsumableArray(i)));var a=this._getEventQueue(o.before,this.__dispatcher.order);return runRejectableQueue.apply(void 0,[a].concat(_toConsumableArray(i))).then(function(){if(!(selfProcessorEvents.indexOf(e)>-1))return t._eventProcessor.apply(t,[e,{sync:!1}].concat(_toConsumableArray(i)))}).catch(function(e){return isError(e)&&t.__dispatcher.throwError(e),_Promise.reject(e)})}},{key:"emitSync",value:function(e){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(isEmpty(t))return selfProcessorEvents.indexOf(e)>-1||this._eventProcessor.apply(this,[e,{sync:!0}].concat(_toConsumableArray(i)));var o=this._getEventQueue(t.before,this.__dispatcher.order);return runStoppableQueue.apply(void 0,[o].concat(_toConsumableArray(i)))&&(selfProcessorEvents.indexOf(e)>-1||this._eventProcessor.apply(this,[e,{sync:!0}].concat(_toConsumableArray(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];var o=this.events[e];if(isEmpty(o))return _Promise.resolve(!0);var a=this._getEventQueue(o.main,this.__dispatcher.order);return runRejectableQueue.apply(void 0,[a].concat(_toConsumableArray(i))).then(function(){var e=t._getEventQueue(o.after,t.__dispatcher.order);return runRejectableQueue.apply(void 0,[e].concat(_toConsumableArray(i)))}).then(function(){return t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(_toConsumableArray(i)))}).catch(function(r){return isError(r)&&t.__dispatcher.throwError(r),t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(_toConsumableArray(i)))})}},{key:"triggerSync",value:function(e){var t=this.events[e];if(isEmpty(t))return!0;for(var r=this._getEventQueue(t.main,this.__dispatcher.order),i=this._getEventQueue(t.after,this.__dispatcher.order),n=arguments.length,o=Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];var s=runStoppableQueue.apply(void 0,[r].concat(_toConsumableArray(o)))&&runStoppableQueue.apply(void 0,[i].concat(_toConsumableArray(o)));return this._runSideEffectEvent.apply(this,[e,this.__dispatcher.order].concat(_toConsumableArray(o))),s}},{key:"destroy",value:function(){delete this.events,delete this.__dispatcher}},{key:"_addEvent",value:function(e,t){var r=(e=deepClone(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=deepClone(e)).pop(),i=this.events,n=0,o=e.length;n<o;n++){var a=i[e[n]];if(isEmpty(a))return;i=a}var s=i[r]||[],u=s.indexOf(t),c=u>-1;return c&&s.splice(u,1),s.length<1&&delete i[r],c}},{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],o=n.get(t),a=o.indexOf(r);o.splice(a,1),isEmpty(o)&&n.delete(t)}},{key:"_getHandlerFromOnceMap",value:function(e,t){var r=e.join("-"),i=this.onceMap[r];if(!isVoid(i)&&i.has(t))return i.get(t)[0]}},{key:"_getEventStage",value:function(e){var t=e.match(secondaryReg),r=t&&t[0]||"main";return t&&(e=camelize(e.replace(secondaryReg,""))),{stage:r,key:e}}},{key:"_getEventQueue",value:function(e,t){var r=this;return t=isArray(t)?t.concat(["_vm"]):["_vm"],isEmpty(e)?[]:t.reduce(function(t,i){return isEmpty(e[i])||!isArray(e[i])||!r.__dispatcher.plugins[i]&&"_vm"!==i?t:t.concat(e[i].map(function(e){return bind(e,r.__dispatcher.plugins[i]||r.__dispatcher.vm)}))},[])}},{key:"_eventProcessor",value:function(e,t){for(var r=t.sync,i=kernelMethods.indexOf(e)>-1,n=domMethods.indexOf(e)>-1,o=dispatcherMethods.indexOf(e)>-1,a=arguments.length,s=Array(a>2?a-2:0),u=2;u<a;u++)s[u-2]=arguments[u];if(i||n||o){var c,l;if(o)(c=this.__dispatcher)[e].apply(c,_toConsumableArray(s));else(l=this.__dispatcher[i?"kernel":"dom"])[e].apply(l,_toConsumableArray(s));if(videoEvents.indexOf(e)>-1||domEvents.indexOf(e)>-1)return!0}return this[r?"triggerSync":"trigger"].apply(this,[e].concat(_toConsumableArray(s)))}},{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 o=this.events[e];return!isEmpty(o)&&(this._getEventQueue(o._,t).forEach(function(e){return e.apply(void 0,_toConsumableArray(i))}),!0)}}]),e}(),_applyDecoratedDescriptor$1(_class$1.prototype,"emit",[_dec$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"emit"),_class$1.prototype),_applyDecoratedDescriptor$1(_class$1.prototype,"emitSync",[_dec2$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"emitSync"),_class$1.prototype),_applyDecoratedDescriptor$1(_class$1.prototype,"trigger",[_dec3$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"trigger"),_class$1.prototype),_applyDecoratedDescriptor$1(_class$1.prototype,"triggerSync",[_dec4$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"triggerSync"),_class$1.prototype),_class$1),_dec$1$1,_dec2$1$1,_class$1$1,_descriptor,_descriptor2,_descriptor3,_descriptor4,_descriptor5,_descriptor6,_descriptor7;function eventBinderCheck(e,t){if(!isString(e))throw new TypeError("key parameter must be String");if(!isFunction(t))throw new TypeError("fn parameter must be Function")}function attrAndStyleCheck(){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 _initDefineProp(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 _applyDecoratedDescriptor$1$1(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function stringOrVoid(e){return isString(e)?e:void 0}function accessorVideoProperty(e){return accessor({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 accessorVideoAttribute(e){var t=isObject(e)?e:{set:e,get:e,isBoolean:!1},r=t.set,i=t.get,n=t.isBoolean;return accessor({get:function(e){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement[i]:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;var t=n?e?"":void 0:null===e?void 0:e;return this.dom.setAttr("video",r,t),e}},{preSet:!1})}function accessorCustomAttribute(e,t){return accessor({get:function(r){var i=this.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:null===r?void 0:r;return this.dom.setAttr("video",e,i),r}})}function accessorWidthAndHeight(e){return accessor({get:function(t){if(!this.dispatcher.videoConfigReady||!this.inited)return t;var r=this.dom.getAttr("video",e),i=this.dom.videoElement[e];return isNumeric(r)&&isNumber(i)?i:r||void 0},set:function(t){if(!this.dispatcher.videoConfigReady)return t;var r=void 0;return void 0===t||isNumber(t)?r=t:isString(t)&&!_Number$isNaN(parseFloat(t))&&(r=t),this.dom.setAttr("video",e,r),r}})}var accessorMap={src:[string$1(),accessor({set:function(e){return this.dispatcher.readySync&&this.autoload&&e!==this.src&&(this.needToLoadSrc=!0),e}}),accessor({set:function(e){return this.needToLoadSrc&&(this.needToLoadSrc=!1,this.dispatcher.bus.emit("load",e)),e}},{preSet:!1})],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:!0})],muted:[boolean$1(),accessorVideoProperty("muted")],preload:[accessor({set:function(e){return["none","auto","metadata",""].indexOf(e)>-1?e:"none"}},{preSet:!0}),accessorVideoAttribute("preload")],poster:[string$1(),accessor({get:function(e){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement.poster:e},set:function(e){return this.dispatcher.videoConfigReady?(e.length&&this.dom.setAttr("video","poster",e),e):e}})],playsInline:[accessor({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-playsinline",t),e}}),boolean$1()],x5VideoPlayerFullscreen:[accessor({set:function(e){return!!e},get:function(e){return!!e}}),accessorCustomAttribute("x5-video-player-fullscreen",!0)],x5VideoOrientation:[accessor({set:stringOrVoid}),accessorCustomAttribute("x5-video-orientation")],x5VideoPlayerType:[accessor({set:function(e){if(!this.dispatcher.videoConfigReady)return e;var t="h5"===e?"h5":void 0;return this.dom.setAttr("video","x5-video-player-type",t),e},get:function(){return this.dom.getAttr("video","x5-video-player-type")?"h5":void 0}})],xWebkitAirplay:[accessor({set:function(e){return!!e},get:function(e){return!!e}}),accessorCustomAttribute("x-webkit-airplay",!0)],playbackRate:[number$1(1),accessorVideoProperty("playbackRate")],defaultPlaybackRate:[accessorVideoProperty("defaultPlaybackRate"),number$1(1)],disableRemotePlayback:[boolean$1(),accessorVideoProperty("disableRemotePlayback")],volume:[number$1(1),accessorVideoProperty("volume")]},VideoConfig=(_dec$1$1=boolean(),_dec2$1$1=string(function(e){return e.toLocaleLowerCase()}),_class$1$1=function(){function e(t,r){_classCallCheck(this,e),_initDefineProp(this,"needToLoadSrc",_descriptor,this),_initDefineProp(this,"changeWatchable",_descriptor2,this),_initDefineProp(this,"inited",_descriptor3,this),this.src="",_initDefineProp(this,"isLive",_descriptor4,this),_initDefineProp(this,"box",_descriptor5,this),this.preset={},this.presetConfig={},this.autoload=!0,this.autoplay=!1,this.controls=!1,this.width="100%",this.height="100%",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.x5VideoPlayerType=void 0,this.xWebkitAirplay=!1,this.playbackRate=1,this.defaultPlaybackRate=1,this.disableRemotePlayback=!1,this.volume=1,_initDefineProp(this,"_kernelProperty",_descriptor6,this),_initDefineProp(this,"_realDomAttr",_descriptor7,this),applyDecorators(this,accessorMap,{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}),deepAssign(this,r)}return _createClass(e,[{key:"init",value:function(){var e=this;this._realDomAttr.forEach(function(t){e[t]=e[t]}),this.inited=!0}}]),e}(),_descriptor=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"needToLoadSrc",[nonenumerable],{enumerable:!0,initializer:function(){return!1}}),_descriptor2=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"changeWatchable",[nonenumerable],{enumerable:!0,initializer:function(){return!0}}),_descriptor3=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"inited",[nonenumerable],{enumerable:!0,initializer:function(){return!1}}),_descriptor4=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"isLive",[_dec$1$1,nonconfigurable],{enumerable:!0,initializer:function(){return!1}}),_descriptor5=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"box",[_dec2$1$1,nonconfigurable],{enumerable:!0,initializer:function(){return""}}),_descriptor6=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"_kernelProperty",[frozen],{enumerable:!0,initializer:function(){return["isLive","box","preset","kernels","presetConfig"]}}),_descriptor7=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"_realDomAttr",[frozen],{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","x5VideoPlayerType"]}}),_class$1$1),_dec$2,_dec2$2,_dec3$1$1,_dec4$1$1,_dec5$1,_dec6,_dec7,_dec8,_dec9,_dec10,_dec11,_dec12,_dec13,_dec14,_dec15,_dec16,_dec17,_dec18,_dec19,_class$2,_class2$1;function _applyDecoratedDescriptor$2(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var VideoWrapper=(_dec$2=autobindClass(),_dec2$2=alias("silentLoad"),_dec3$1$1=alias("fullScreen"),_dec4$1$1=alias("$fullScreen"),_dec5$1=alias("fullscreen"),_dec6=alias("emit"),_dec7=alias("emitSync"),_dec8=alias("on"),_dec9=alias("addEventListener"),_dec10=before(eventBinderCheck),_dec11=alias("off"),_dec12=alias("removeEventListener"),_dec13=before(eventBinderCheck),_dec14=alias("once"),_dec15=before(eventBinderCheck),_dec16=alias("css"),_dec17=before(attrAndStyleCheck),_dec18=alias("attr"),_dec19=before(attrAndStyleCheck),_dec$2((_class2$1=function(){function e(){_classCallCheck(this,e),this.__events={},this.__unwatchHandlers=[]}return _createClass(e,[{key:"__wrapAsVideo",value:function(e){var t=this;videoReadOnlyProperties.forEach(function(e){_Object$defineProperty(t,e,{get:function(){return this.__dispatcher.dom.videoElement[e]},set:void 0,configurable:!1,enumerable:!1})}),videoMethods.forEach(function(e){_Object$defineProperty(t,e,{get:function(){var t=this.__dispatcher.dom.videoElement;return bind(t[e],t)},set:void 0,configurable:!1,enumerable:!1})}),applyDecorators(this,e._realDomAttr.concat(e._kernelProperty).reduce(function(t,r){return t[r]=[accessor({get:function(){return e[r]},set:function(t){return e[r]=t,t}}),nonenumerable],t},{}),{self:!0}),kernelMethods.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){var n;t.__dispatcher.bus.once(t.__id,"_"+e,r),(n=t.__dispatcher.bus)[/^(seek)$/.test(e)?"emitSync":"emit"].apply(n,[e].concat(_toConsumableArray(i)))})},configurable:!0,enumerable:!1,writable:!0})}),domMethods.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]:{},n=i.deep,o=i.diff,a=void 0===o||o,s=i.other,u=i.proxy,c=void 0!==u&&u;if(!isString(e)&&!isArray(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":_typeof(e)));var l=!0,d=function e(){l=!1;var t=r.__unwatchHandlers.indexOf(e);t>-1&&r.__unwatchHandlers.splice(t,1)},f=isString(e)?e.split("."):e,h=f.pop(),p=this.__dispatcher.videoConfig;return applyDecorators(0===f.length&&!s&&p._realDomAttr.indexOf(h)>-1?p:["isFullscreen","fullscreenElement"].indexOf(h)>-1?this.__dispatcher.dom:getDeepProperty(s||this,f,{throwError:!0}),_defineProperty({},h,watch(function(){!l||this instanceof VideoConfig&&!this.dispatcher.changeWatchable||bind(t,this).apply(void 0,arguments)},{deep:n,diff:a,proxy:c})),{self:!0}),this.__unwatchHandlers.push(d),d}},{key:"$set",value:function(e,t,r){if(!isObject(e)&&!isArray(e))throw new TypeError("$set only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":_typeof(e)));isFunction(e.__set)?e.__set(t,r):e[t]=r}},{key:"$del",value:function(e,t){if(!isObject(e)&&!isArray(e))throw new TypeError("$del only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":_typeof(e)));isFunction(e.__del)?e.__del(t):delete e[t]}},{key:"load",value:function(){for(var e=this,t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];return new _Promise(function(t){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),i=0;i<t;i++)r[i]=arguments[i];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(!isString(e))throw new TypeError("emit 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];(t=this.__dispatcher.bus).emit.apply(t,[e].concat(_toConsumableArray(i)))}},{key:"$emitSync",value:function(e){var t;if(!isString(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(_toConsumableArray(i)))}},{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(){bind(t,this).apply(void 0,arguments),r.__removeEvents(e,i)};r.__addEvents(e,i),this.__dispatcher.bus.once(this.__id,e,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 i[2];if(this.__dispatcher.videoConfig._realDomAttr.indexOf(i[1])>-1){var o=i[1],a=i[2];return this.__dispatcher.videoConfig[o]=a,a}}return(t=this.__dispatcher.dom)[e+"Attr"].apply(t,i)}},{key:"__addEvents",value:function(e,t){this.__events[e]=this.__events[e]||[],this.__events[e].push(t)}},{key:"__removeEvents",value:function(e,t){if(!isEmpty(this.__events[e])){var r=this.__events[e].indexOf(t);r<0||(this.__events[e].splice(r,1),isEmpty(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){isArray(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 this.__dispatcher.dom.wrapper}},{key:"$container",get:function(){return this.__dispatcher.dom.container}},{key:"$video",get:function(){return this.__dispatcher.dom.videoElement}},{key:"isFullscreen",get:function(){return this.__dispatcher.dom.isFullscreen}},{key:"fullscreenElement",get:function(){return this.__dispatcher.dom.fullscreenElement}},{key:"container",get:function(){return this.__dispatcher.containerConfig},set:function(e){if(!isObject(e))throw new Error("The config of container must be Object, but not "+(void 0===e?"undefined":_typeof(e))+".");return deepAssign(this.__dispatcher.containerConfig,e),this.__dispatcher.container}}]),e}(),_applyDecoratedDescriptor$2(_class2$1.prototype,"$silentLoad",[_dec2$2],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$silentLoad"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$fullscreen",[_dec3$1$1,_dec4$1$1,_dec5$1],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$fullscreen"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$emit",[_dec6],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$emit"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$emitSync",[_dec7],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$emitSync"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$on",[_dec8,_dec9,_dec10],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$on"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$off",[_dec11,_dec12,_dec13],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$off"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$once",[_dec14,_dec15],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$once"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$css",[_dec16,_dec17],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$css"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$attr",[_dec18,_dec19],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$attr"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$plugins",[nonenumerable],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$plugins"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$pluginOrder",[nonenumerable],_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),_class$2=_class2$1))||_class$2),_dec$3,_class$3,Plugin=(_dec$3=autobindClass(),_dec$3(_class$3=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.id,i=e.name,n=e.level,o=void 0===n?0:n,a=e.operable,s=void 0===a||a,u=e.beforeCreate,c=e.create,l=e.init,d=e.inited,f=e.destroy,h=e.events,p=void 0===h?{}:h,m=e.data,v=void 0===m?{}:m,g=e.computed,y=void 0===g?{}:g,_=e.methods,b=void 0===_?{}:_,w=e.el,E=e.penetrate,S=void 0!==E&&E,T=e.inner,O=void 0===T||T,A=e.autoFocus,$=e.className,k=arguments[1],D=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{name:i};_classCallCheck(this,t);var I=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(I.destroyed=!1,I.VERSION="0.9.3",I.__operable=!0,I.__level=0,isEmpty(k))throw new TypeError("lack of dispatcher");if(!isString(r))throw new TypeError("id of PluginConfig must be string");I.__id=r,I.__dispatcher=k,I.$videoConfig=I.__dispatcher.videoConfig,I.__wrapAsVideo(I.$videoConfig),I.beforeCreate=I.beforeCreate||u;try{isFunction(I.beforeCreate)&&I.beforeCreate({events:p,data:v,computed:y,methods:b},D)}catch(e){I.$throwError(e)}if(!isEmpty(b)&&isObject(b)&&_Object$keys(b).forEach(function(e){var t=b[e];if(!isFunction(t))throw new TypeError("plugins methods must be Function");_Object$defineProperty(I,e,{value:bind(t,I),writable:!0,enumerable:!1,configurable:!0})}),!isEmpty(p)&&isObject(p)&&_Object$keys(p).forEach(function(e){if(!isFunction(p[e]))throw new TypeError("plugins events hook must bind with Function");I.$on(e,p[e])}),!isEmpty(v)&&isObject(v)&&deepAssign(I,v),!isEmpty(y)&&isObject(y)){var x=_Object$keys(y).reduce(function(e,t){var r=y[t];return isFunction(r)?(e[t]=accessor({get:r}),e):isObject(r)&&(isFunction(r.get)||isFunction(r.set))?(e[t]=accessor(r),e):e},{});applyDecorators(I,x,{self:!0})}I.create=I.create||c,I.init=I.init||l,I.inited=I.inited||d,I.destroy=I.destroy||f,I.$dom=I.__dispatcher.dom.insertPlugin(I.__id,w,{penetrate:S,inner:O,autoFocus:A,className:$}),I.$inner=O,I.$autoFocus=A,I.$penetrate=S,applyDecorators(I,{$inner:frozen,$autoFocus:frozen,$penetrate:frozen},{self:!0}),I.$operable=isBoolean(D.operable)?D.operable:s,I.__level=isInteger$2(D.level)?D.level:o,I.$config=D;try{isFunction(I.create)&&I.create()}catch(e){I.$throwError(e)}return I}return _inherits(t,VideoWrapper),_createClass(t,[{key:"__init",value:function(e){try{isFunction(this.init)&&this.init(e)}catch(e){this.$throwError(e)}}},{key:"__inited",value:function(){var e=this,t=void 0;try{t=isFunction(this.inited)&&this.inited()}catch(e){this.$throwError(e)}return this.readySync=!isPromise(t),this.ready=this.readySync?_Promise.resolve():t.then(function(t){return e.readySync=!0,t}).catch(function(t){return isError(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(){isFunction(this.destroy)&&this.destroy(),_get(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){isBoolean(e)&&(this.$dom.style.pointerEvents=e?"auto":"none",this.__operable=e)},get:function(){return this.__operable}},{key:"$level",set:function(e){isInteger$2(e)&&(this.__level=e,this.__dispatcher._sortZIndex())},get:function(){return this.__level}}]),t}())||_class$3),_dec$4,_dec2$3,_dec3$2,_dec4$2,_dec5$1$1,_dec6$1,_class$4;function _applyDecoratedDescriptor$3(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function targetCheck(e){if("video"===e&&(e="videoElement"),!isElement(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 attrOperationCheck(e,t,r){if(!isString(t))throw new TypeError("to handle dom's attribute or style, your attr parameter must be string, but not "+t+" in "+(void 0===t?"undefined":_typeof(t)));if(!isString(e))throw new TypeError("to handle dom's attribute or style, your target parameter must be string, , but not "+e+" in "+(void 0===e?"undefined":_typeof(e)));return[e,t,r]}var Dom=(_dec$4=waituntil("__dispatcher.videoConfigReady"),_dec2$3=before(attrOperationCheck,targetCheck),_dec3$2=before(attrOperationCheck,targetCheck),_dec4$2=before(attrOperationCheck,targetCheck),_dec5$1$1=before(attrOperationCheck,targetCheck),_dec6$1=before(targetCheck),_class$4=function(){function e(t,r){var i=this;if(_classCallCheck(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,!isElement(t)&&!isString(t))throw new TypeError("Wrapper can only be string or HTMLElement, but not "+(void 0===t?"undefined":_typeof(t)));var n=$(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 o=n.find("video")[0];o||(o=document.createElement("video")),this.installVideo(o),this._addDomEvents(this.container,this.containerDomEventHandlerList,function(e){return function(){for(var t,r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return(t=i.__dispatcher.bus).triggerSync.apply(t,["c_"+e].concat(_toConsumableArray(n)))}}),this._addDomEvents(this.wrapper,this.wrapperDomEventHandlerList,function(e){return function(){for(var t,r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return(t=i.__dispatcher.bus).triggerSync.apply(t,["w_"+e].concat(_toConsumableArray(n)))}}),this._fullscreenMonitor(),index.on("fullscreenchange",this._fullscreenMonitor)}return _createClass(e,[{key:"installVideo",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).bindEvent,r=void 0===t||t;if(this.__videoExtendedNodes.push(e),setAttr(e,"tabindex",-1),this._autoFocusToVideo(e),isElement(this.container)){var i=this.container;0===i.childNodes.length?i.appendChild(e):i.insertBefore(e,i.childNodes[0])}else e.parentElement&&isElement(e.parentElement)&&e.parentElement!==this.wrapper?this.container=e.parentElement:(this.container=document.createElement("container"),$(this.container).append(e));return this.container.parentElement!==this.wrapper&&$(this.wrapper).append(this.container),r&&this.bindVideoEvents(e),this.videoElement=e,e}},{key:"bindVideoEvents",value:function(e){var t=this;videoEvents.forEach(function(r){var i=function(){for(var e,i=arguments.length,n=Array(i),o=0;o<i;o++)n[o]=arguments[o];return(e=t.__dispatcher.bus).trigger.apply(e,[r].concat(_toConsumableArray(n)))};t.videoEventHandlerList.push(i),addEvent(e,r,i)}),this._addDomEvents(e,this.videoDomEventHandlerList,function(e){return t._getEventHandler(e,{penetrate:!0})})}},{key:"removeVideo",value:function(){var e=this,t=this.videoElement;return this._autoFocusToVideo(this.videoElement,!1),videoEvents.forEach(function(t,r){removeEvent(e.videoElement,t,e.videoEventHandlerList[r])}),this.videoEventHandlerList=[],domEvents.forEach(function(t,r){removeEvent(e.videoElement,t,e.videoDomEventHandlerList[r])}),this.videoDomEventHandlerList=[],$(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(!isString(e))throw new TypeError("insertPlugin id parameter must be string");if(isElement(this.plugins[e])&&this.removePlugin(e),isString(t))if(isHTMLString(t)){var n=document.createElement("div");n.innerHTML=t,t=n.children[0]}else t=document.createElement(hypenate(t));else isObject(t)&&(i=t);var o=i,a=o.inner,s=o.penetrate,u=o.autoFocus,c=i.className,l=t&&isElement(t)?t:document.createElement("div");isArray(c)&&(c=c.join(" ")),isString(c)&&addClassName(l,c),this.plugins[e]=l;var d=a?this.container:this.wrapper,f=a?this.videoElement:this.container;return(isBoolean(u)?u:a)&&this._autoFocusToVideo(l),s&&(this.__domEventHandlerList[e]=this.__domEventHandlerList[e]||[],this._addDomEvents(l,this.__domEventHandlerList[e],function(e){return r._getEventHandler(e,{penetrate:s})}),this.__videoExtendedNodes.push(l)),d.lastChild===f?(d.appendChild(l),l):(d.insertBefore(l,f.nextSibling),l)}},{key:"removePlugin",value:function(e){var t=this;if(isString(e)){var r=this.plugins[e];isElement(r)&&(r.parentNode&&r.parentNode.removeChild(r),this._autoFocusToVideo(r,!0)),isEmpty(this.__domEventHandlerList[e])||(domEvents.forEach(function(r,i){removeEvent(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 setStyle(e.match(/^(videoElement|container)$/)?t[e]:t.plugins[e],"z-index",++r)})}},{key:"setAttr",value:function(e,t,r){setAttr(this[e],t,r)}},{key:"getAttr",value:function(e,t){return getAttr(this[e],t)}},{key:"setStyle",value:function(e,t,r){setStyle(this[e],t,r)}},{key:"getStyle",value:function(e,t){return getStyle(this[e],t)}},{key:"requestFullscreen",value:function(e){return index.open(this[e])}},{key:"exitFullscreen",value:function(){return index.exit()}},{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(_toConsumableArray(i))):this.exitFullscreen.apply(this,_toConsumableArray(i))}},{key:"focus",value:function(){this.videoElement.focus()}},{key:"destroy",value:function(){var e=this;this.removeVideo(),domEvents.forEach(function(t,r){removeEvent(e.container,t,e.containerDomEventHandlerList[r]),removeEvent(e.wrapper,t,e.wrapperDomEventHandlerList[r])}),index.off("fullscreenchange",this._fullscreenMonitor),this.wrapper.innerHTML=this.originHTML,delete this.wrapper,delete this.plugins}},{key:"_addDomEvents",value:function(e,t,r){domEvents.forEach(function(i){var n=r(i);t.push(n),passiveEvents.indexOf(i)>-1?addEvent(e,i,n,!1,{passive:!0}):addEvent(e,i,n)})}},{key:"_autoFocusToVideo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];isElement(e)&&((t?removeEvent:addEvent)(e,"mouseup",this._focusToVideo,!1,!0),(t?removeEvent:addEvent)(e,"touchend",this._focusToVideo,!1,!0))}},{key:"_focusToVideo",value:function(){var e=window.scrollX,t=window.scrollY;isFunction(this.videoElement.focus)&&this.videoElement.focus(),window.scrollTo(e,t)}},{key:"_fullscreenMonitor",value:function(e){var t=index.fullscreenElement,r=this.isFullscreen;!t||!isPosterityNode(this.wrapper,t)&&t!==this.wrapper?(this.isFullscreen=!1,this.fullscreenElement=void 0):(this.isFullscreen=!0,this.fullscreenElement=this.wrapper===t?"wrapper":this.container===t?"container":this.videoElement===t?"video":t),isEvent(e)&&r!==this.isFullscreen&&this.__dispatcher.bus.triggerSync("fullscreenchange",e)}},{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),o=0;o<i;o++)n[o]=arguments[o];(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||isPosterityNode(r,e)},!1)};return function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var o,a,s=t[0],u=s.toElement,c=s.currentTarget,l=s.relatedTarget,d=s.type,f=u||l;return r.__mouseInVideo&&"mouseleave"===d&&!i(f)?(r.__mouseInVideo=!1,(o=r.__dispatcher.bus).triggerSync.apply(o,["mouseleave"].concat(t))):!r.__mouseInVideo&&"mouseenter"===d&&i(c)?(r.__mouseInVideo=!0,(a=r.__dispatcher.bus).triggerSync.apply(a,["mouseenter"].concat(t))):void 0}}}]),e}(),_applyDecoratedDescriptor$3(_class$4.prototype,"setAttr",[_dec$4,_dec2$3],_Object$getOwnPropertyDescriptor(_class$4.prototype,"setAttr"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"getAttr",[_dec3$2],_Object$getOwnPropertyDescriptor(_class$4.prototype,"getAttr"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"setStyle",[_dec4$2],_Object$getOwnPropertyDescriptor(_class$4.prototype,"setStyle"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"getStyle",[_dec5$1$1],_Object$getOwnPropertyDescriptor(_class$4.prototype,"getStyle"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"requestFullscreen",[_dec6$1],_Object$getOwnPropertyDescriptor(_class$4.prototype,"requestFullscreen"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"_focusToVideo",[autobind],_Object$getOwnPropertyDescriptor(_class$4.prototype,"_focusToVideo"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"_fullscreenMonitor",[autobind],_Object$getOwnPropertyDescriptor(_class$4.prototype,"_fullscreenMonitor"),_class$4.prototype),_class$4),defaultContainerConfig={width:"100%",height:"100%",position:"relative",display:"block"},Vessel=function e(t,r,i){var n=this;_classCallCheck(this,e),this.__dispatcher=t,this.__target=r,["width","height","position","display"].forEach(function(e){_Object$defineProperty(n,e,{get:function(){return this.__dispatcher.dom.getStyle(this.__target,e)},set:function(t){if(isNumber(t)&&(t+="px"),!isString(t))throw new Error("The value of "+e+" in "+this.__target+"Config must be string, but not "+(void 0===t?"undefined":_typeof(t))+".");return this.__dispatcher.dom.setStyle(this.__target,e,t),t},configurable:!0,enumerable:!0})}),deepAssign(this,i)},_dec$5,_dec2$4,_dec3$3,_dec4$3,_dec5$2,_class$5;function _applyDecoratedDescriptor$4(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var pluginConfigSet={},kernelsSet={};function convertNameIntoId(e){if(!isString(e))throw new Error("Plugin's name must be a string, but not \""+e+'" in '+(void 0===e?"undefined":_typeof(e)));return camelize(e)}function checkPluginConfig(e){if(isFunction(e)){if(!(e.prototype instanceof Plugin))throw new TypeError("Your are trying to install plugin "+e.name+", but it's not extends from Chimee.plugin.")}else{if(!isObject(e)||isEmpty(e))throw new TypeError("plugin's config must be an Object, but not \""+e+'" in '+(void 0===e?"undefined":_typeof(e)));var t=e.name;if(!isString(t)||t.length<1)throw new TypeError('plugin must have a legal namea, but not "'+t+'" in '+(void 0===t?"undefined":_typeof(t)))}}var Dispatcher=(_dec$5=before(convertNameIntoId),_dec2$4=before(checkPluginConfig),_dec3$3=before(convertNameIntoId),_dec4$3=before(convertNameIntoId),_dec5$2=before(convertNameIntoId),_class$5=function(){function e(t,r){var i=this;if(_classCallCheck(this,e),this.plugins={},this.order=[],this.readySync=!1,this.zIndexMap={inner:[],outer:[]},this.changeWatchable=!0,this.kernelEventHandlerList=[],!isObject(t))throw new TypeError('UserConfig must be an Object, but not "'+t+'" in '+(void 0===t?"undefined":_typeof(t)));this.dom=new Dom(t.wrapper,this),this.bus=new Bus(this),this.vm=r,this.videoConfigReady=!1,this.videoConfig=new VideoConfig(this,t),isArray(t.plugins)&&!isArray(t.plugin)&&(t.plugin=t.plugins,delete t.plugins),this._initUserPlugin(t.plugin);var n=deepAssign({},defaultContainerConfig,t.container||{});this.order.forEach(function(e){return i.plugins[e].__init(i.videoConfig,n)}),this.videoConfigReady=!0,this.videoConfig.init(),this.containerConfig=new Vessel(this,"container",n),this.kernel=this._createKernel(this.dom.videoElement,this.videoConfig),this._bindKernelEvents(this.kernel);var o=[];this.order.forEach(function(e){var t=i.plugins[e].__inited();isPromise(t)&&o.push(t)}),this.readySync=0===o.length,this.ready=this.readySync?_Promise.resolve():_Promise.all(o).then(function(){i.readySync=!0,i.bus.trigger("ready"),i._autoloadVideoSrcAtFirst()}),this.readySync&&this._autoloadVideoSrcAtFirst()}return _createClass(e,[{key:"use",value:function(t){if(isString(t)&&(t={name:t,alias:void 0}),!isObject(t)||isObject(t)&&!isString(t.name))throw new TypeError("pluginConfig do not match requirement");isString(t.alias)||(t.alias=void 0);var r=t,i=r.name,n=r.alias;t.name=n||i,delete t.alias;var o=camelize(i),a=camelize(n||i),s=t,u=e.getPluginConfig(o);if(isEmpty(u))throw new TypeError("You have not installed plugin "+o);isObject(u)&&(u.id=a);var c=isFunction(u)?new u({id:a},this,s):new Plugin(u,this,s);return this.plugins[a]=c,_Object$defineProperty(this.vm,a,{value:c,configurable:!0,enumerable:!1,writable:!1}),this.order.push(a),this._sortZIndex(),this.videoConfigReady&&c.__inited(),c.ready}},{key:"unuse",value:function(e){var t=this.plugins[e];if(isObject(t)&&isFunction(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]:{},i=r.duration,n=void 0===i?3:i,o=r.bias,a=void 0===o?0:o,s=r.repeatTimes,u=void 0===s?0:s,c=r.increment,l=void 0===c?0:c,d=r.isLive,f=void 0===d?this.videoConfig.isLive:d,h=r.box,p=void 0===h?this.videoConfig.box:h,m=r.kernels,v=void 0===m?this.videoConfig.kernels:m,g=r.preset,y=void 0===g?this.videoConfig.preset:g,_=r.immediate||f,b={isLive:f,box:p,src:e,kernels:v,preset:y};return runRejectableQueue(new Array(u+1).fill(1).map(function(e,i){return function(){return new _Promise(function(e,o){r.abort&&o({error:!0,message:"user abort the mission"});var s=document.createElement("video"),c=t.kernel.currentTime+n+l*i;s.muted=!0;var d=!1,h=void 0,p=void 0,m=void 0,v=void 0,g=function r(){var i=t.kernel.currentTime;if(a<=0&&i>=c||a>0&&(Math.abs(c-i)<=a&&d||i-c>a))return removeEvent(t.dom.videoElement,"timeupdate",r),removeEvent(s,"error",p,!0),d?o({error:!1,video:s,kernel:h}):(removeEvent(s,"canplay",m,!0),removeEvent(s,"loadedmetadata",v,!0),h.destroy(),e())};m=function(){if(d=!0,_)return removeEvent(t.dom.videoElement,"timeupdate",g),removeEvent(s,"error",p,!0),o({error:!1,video:s,kernel:h})},v=function(){f||h.seek(c)},p=function(r){removeEvent(s,"canplay",m,!0),removeEvent(s,"loadedmetadata",v,!0),removeEvent(t.dom.videoElement,"timeupdate",g),h.off("error",p);var n=void 0;if(r.target===h){var a=r.data.errmsg;Log$1.error("chimee's silentload bump into a kernel error",a),n=new Error(a)}else n=isEmpty(s.error)?new Error("unknow video error"):new Error(s.error.message),Log$1.error("chimee's silentload",n.message);return h.destroy(),t._silentLoadTempKernel=void 0,i===u?o(n):e(n)},addEvent(s,"canplay",m,!0),addEvent(s,"loadedmetadata",v,!0),addEvent(s,"error",p,!0),h=t._createKernel(s,b),t._silentLoadTempKernel=h,h.on("error",p),addEvent(t.dom.videoElement,"timeupdate",g),h.load()})}})).then(function(){var t="The silentLoad for "+e+" timed out. Please set a longer duration or check your network";return _Promise.reject(new Error(t))}).catch(function(e){if(isError(e))return _Promise.reject(e);if(e.error)return _Promise.reject(new Error(e.message));var i=e.video,n=e.kernel;return r.abort?(n.destroy(),_Promise.reject(new Error("user abort the mission"))):t.dom.videoElement.paused?(t.switchKernel({video:i,kernel:n,config:b}),_Promise.resolve()):new _Promise(function(e){addEvent(i,"play",function(){t.switchKernel({video:i,kernel:n,config:b}),e()},!0),i.play()})})}},{key:"load",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=isString(e)?e:isObject(e)&&isString(e.src)?e.src:"";isObject(e)&&(delete e.src,t=e);var i=this.kernel.box,n=this.videoConfig,o=t,a=o.isLive,s=void 0===a?n.isLive:a,u=o.box,c=void 0===u?n.box:u,l=o.preset,d=void 0===l?n.preset:l,f=o.kernels,h=void 0===f?n.kernels:f;if("native"!==c||c!==i||!isEmpty(t)){var p=document.createElement("video"),m={isLive:s,box:c,preset:d,src:r,kernels:h},v=this._createKernel(p,m);this.switchKernel({video:p,kernel:v,config:m})}var g=this.videoConfig.autoload;this._changeUnwatchable(this.videoConfig,"autoload",!1),this.videoConfig.src=r||this.videoConfig.src,this.kernel.load(this.videoConfig.src),this._changeUnwatchable(this.videoConfig,"autoload",g)}},{key:"switchKernel",value:function(e){var t=this,r=e.video,i=e.kernel,n=e.config,o=this.kernel,a=deepClone(this.videoConfig);this.dom.removeVideo(),this.dom.installVideo(r,{bindEvent:!1}),this.videoConfig.changeWatchable=!1,this.videoConfig.autoload=!1,this.videoConfig.src=n.src,this.videoConfig._realDomAttr.forEach(function(e){"src"!==e&&(t.videoConfig[e]=a[e])}),this.videoConfig.changeWatchable=!0,this._bindKernelEvents(o,!0),this._bindKernelEvents(i),this.kernel=i,this._silentLoadTempKernel=void 0;var s=n.isLive,u=n.box,c=n.preset,l=n.kernels;_Object$assign(this.videoConfig,{isLive:s,box:u,preset:c,kernels:l}),o.destroy(),setTimeout(function(){return t.dom.bindVideoEvents(r)})}},{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._bindKernelEvents(this.kernel,!0),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 isArray(t)||(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(isEmpty(i))return t;var n=t[i.$inner?"inner":"outer"],o=i.$level;return n[o]=n[o]||[],n[o].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=transObjectAttrIntoArray(r),o=transObjectAttrIntoArray(i);this.dom.setPluginsZIndex(n),this.dom.setPluginsZIndex(o),this.zIndexMap.inner=n,this.zIndexMap.outer=o}},{key:"_getTopLevel",value:function(e){var t=this.zIndexMap[e?"inner":"outer"],r=this.plugins[t[t.length-1]];return isEmpty(r)?0:r.$level}},{key:"_autoloadVideoSrcAtFirst",value:function(){if(this.videoConfig.autoload){if(!this.videoConfig.src)return void Log$1.warn("You have not set the src, so you better set autoload to be false. Accroding to https://github.com/Chimeejs/chimee/blob/master/doc/zh-cn/chimee-api.md#src.");this.bus.emit("load",this.videoConfig.src)}}},{key:"_changeUnwatchable",value:function(e,t,r){this.changeWatchable=!1,e[t]=r,this.changeWatchable=!0}},{key:"_createKernel",value:function(e,t){var r=t.kernels,i=t.preset,n={},o={};return isArray(r)&&(o=r.reduce(function(e,t){if(isString(t)){var r=kernelsSet[t];return isFunction(r)?(e[t]=r,e):(Log$1.warn("You have not installed kernel for "+t+"."),e)}if(isObject(t)){var i=t.name,o=t.handler;if(isString(o)){var a=kernelsSet[o];return isFunction(a)?(e[o]=a,n[o]=t,e):(Log$1.warn("You have not installed kernel for "+o+"."),e)}if(isFunction(o)){var s=i||o.name;return e[s]=o,n[s]=t,e}return Log$1.warn("When you pass in an SingleKernelConfig in Array, you must clarify it's handler, we only support handler in string or function but not "+(void 0===o?"undefined":_typeof(o))),e}return Log$1.warn("If you pass in kernels as array, you must pass in kernels in string or function, but not "+(void 0===t?"undefined":_typeof(t))),e},{})),isObject(r)&&_Object$entries(r).forEach(function(e){var t=_slicedToArray(e,2),i=t[0],a=t[1];if(!isFunction(a)){if(isObject(a)){var s=a.handler;if(isString(s)){var u=kernelsSet[s];return isFunction(u)?(o[i]=u,void(n[i]=a)):void Log$1.warn("You have not installed kernel for "+s+".")}return isFunction(s)?(o[i]=s,void(n[i]=a)):void Log$1.warn("When you pass in an SingleKernelConfig in Object, you must clarify it's handler, we only support handler in string or function but not "+(void 0===s?"undefined":_typeof(s)))}return Log$1.warn("If you pass in kernels as object, you must pass in kernels in string or function, but not "+(void 0===a?"undefined":_typeof(a))),r}o[i]=a}),t.preset=_Object$assign(o,i),t.presetConfig=n,new ChimeeKernel(e,t)}},{key:"_bindKernelEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];kernelEvents$1.forEach(function(i,n){if(!r){var o=function(){for(var e,r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return(e=t.bus).triggerSync.apply(e,[i].concat(_toConsumableArray(n)))};return e.on(i,o),void t.kernelEventHandlerList.push(o)}var a=t.kernelEventHandlerList[n];e.off(i,a)}),r?(this.kernelEventHandlerList=[],e.off("error",this.throwError)):e.on("error",this.throwError)}}],[{key:"install",value:function(e){var t=camelize(e.name);isEmpty(pluginConfigSet[t]);var r=isFunction(e)?e:deepAssign({id:t},e);return pluginConfigSet[t]=r,t}},{key:"hasInstalled",value:function(e){return!isEmpty(pluginConfigSet[e])}},{key:"uninstall",value:function(e){delete pluginConfigSet[e]}},{key:"getPluginConfig",value:function(e){return pluginConfigSet[e]}},{key:"installKernel",value:function(e,t){(isObject(e)?_Object$entries(e):[[e,t]]).forEach(function(e){var t=_slicedToArray(e,2),r=t[0],i=t[1];if(!isFunction(i))throw new Error("The kernel you install on "+r+" must be a Function, but not "+(void 0===i?"undefined":_typeof(i)));isFunction(kernelsSet[r])&&Log$1.warn("You have alrady install a kernel on "+r+", and now we will replace it"),kernelsSet[r]=i})}},{key:"uninstallKernel",value:function(e){delete kernelsSet[e]}},{key:"hasInstalledKernel",value:function(e){return isFunction(kernelsSet[e])}}]),e}(),_applyDecoratedDescriptor$4(_class$5.prototype,"unuse",[_dec$5],_Object$getOwnPropertyDescriptor(_class$5.prototype,"unuse"),_class$5.prototype),_applyDecoratedDescriptor$4(_class$5.prototype,"throwError",[autobind],_Object$getOwnPropertyDescriptor(_class$5.prototype,"throwError"),_class$5.prototype),_applyDecoratedDescriptor$4(_class$5,"install",[_dec2$4],_Object$getOwnPropertyDescriptor(_class$5,"install"),_class$5),_applyDecoratedDescriptor$4(_class$5,"hasInstalled",[_dec3$3],_Object$getOwnPropertyDescriptor(_class$5,"hasInstalled"),_class$5),_applyDecoratedDescriptor$4(_class$5,"uninstall",[_dec4$3],_Object$getOwnPropertyDescriptor(_class$5,"uninstall"),_class$5),_applyDecoratedDescriptor$4(_class$5,"getPluginConfig",[_dec5$2],_Object$getOwnPropertyDescriptor(_class$5,"getPluginConfig"),_class$5),_class$5),_class$6,_descriptor$1;function _initDefineProp$1(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 _applyDecoratedDescriptor$5(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var GlobalConfig=(_class$6=function(){function e(){_classCallCheck(this,e),this.log={error:!0,info:!0,warn:!0,debug:!0,verbose:!0},_initDefineProp$1(this,"_silent",_descriptor$1,this),this.errorHandler=void 0;var t=_Object$keys(this.log).reduce(function(e,t){return e[t]=accessor({get:function(){return Log$1["ENABLE_"+t.toUpperCase()]},set:function(e){return Log$1["ENABLE_"+t.toUpperCase()]=e,!0===e&&(this.silent=!1),e}}),e},{});applyDecorators(this.log,t,{self:!0})}return _createClass(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}(),_descriptor$1=_applyDecoratedDescriptor$5(_class$6.prototype,"_silent",[nonenumerable],{enumerable:!0,initializer:function(){return!1}}),_class$6),_dec$6,_class$7,_class2$1$1,_descriptor$2,_descriptor2$1,_descriptor3$1,_init,_init2,_init3,_init4,_init5,_init6,_init7,_init8,_init9,_class3,_temp;function _initDefineProp$2(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 _applyDecoratedDescriptor$6(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var Chimee=(_dec$6=autobindClass(),_dec$6((_temp=_class3=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(r.destroyed=!1,_initDefineProp$2(r,"__id",_descriptor$2,r),_initDefineProp$2(r,"version",_descriptor2$1,r),_initDefineProp$2(r,"config",_descriptor3$1,r),isString(e)||isElement(e))e={wrapper:e,controls:!0};else{if(!isObject(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 Dispatcher(e,r),r.ready=r.__dispatcher.ready,r.readySync=r.__dispatcher.readySync,r.__wrapAsVideo(r.__dispatcher.videoConfig),r}return _inherits(t,VideoWrapper),_createClass(t,[{key:"destroy",value:function(){_get(t.prototype.__proto__||_Object$getPrototypeOf(t.prototype),"__destroy",this).call(this),this.__dispatcher.destroy(),Object.defineProperty(this,"__dispatcher",{get:function(){throw new Error("This instance has been destroyed.")},enumerable:!0,configurable:!0}),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){isString(e)&&(e=new Error(e));var r=this.config.errorHandler||t.config.errorHandler;if(isFunction(r))return r(e);if(!t.config.silent)throw e}}]),t}(),_class3.plugin=Plugin,_class3.config=new GlobalConfig,_class3.install=Dispatcher.install,_class3.uninstall=Dispatcher.uninstall,_class3.hasInstalled=Dispatcher.hasInstalled,_class3.installKernel=Dispatcher.installKernel,_class3.uninstallKernel=Dispatcher.uninstallKernel,_class3.hasInstalledKernel=Dispatcher.hasInstalledKernel,_class3.getPluginConfig=Dispatcher.getPluginConfig,_class2$1$1=_temp,_descriptor$2=_applyDecoratedDescriptor$6(_class2$1$1.prototype,"__id",[frozen],{enumerable:!0,initializer:function(){return"_vm"}}),_descriptor2$1=_applyDecoratedDescriptor$6(_class2$1$1.prototype,"version",[frozen],{enumerable:!0,initializer:function(){return"0.9.3"}}),_descriptor3$1=_applyDecoratedDescriptor$6(_class2$1$1.prototype,"config",[frozen],{enumerable:!0,initializer:function(){return{errorHandler:void 0}}}),_applyDecoratedDescriptor$6(_class2$1$1,"plugin",[frozen],(_init=_Object$getOwnPropertyDescriptor(_class2$1$1,"plugin"),_init=_init?_init.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"config",[frozen],(_init2=_Object$getOwnPropertyDescriptor(_class2$1$1,"config"),_init2=_init2?_init2.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init2}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"install",[frozen],(_init3=_Object$getOwnPropertyDescriptor(_class2$1$1,"install"),_init3=_init3?_init3.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init3}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"uninstall",[frozen],(_init4=_Object$getOwnPropertyDescriptor(_class2$1$1,"uninstall"),_init4=_init4?_init4.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init4}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"hasInstalled",[frozen],(_init5=_Object$getOwnPropertyDescriptor(_class2$1$1,"hasInstalled"),_init5=_init5?_init5.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init5}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"installKernel",[frozen],(_init6=_Object$getOwnPropertyDescriptor(_class2$1$1,"installKernel"),_init6=_init6?_init6.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init6}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"uninstallKernel",[frozen],(_init7=_Object$getOwnPropertyDescriptor(_class2$1$1,"uninstallKernel"),_init7=_init7?_init7.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init7}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"hasInstalledKernel",[frozen],(_init8=_Object$getOwnPropertyDescriptor(_class2$1$1,"hasInstalledKernel"),_init8=_init8?_init8.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init8}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"getPluginConfig",[frozen],(_init9=_Object$getOwnPropertyDescriptor(_class2$1$1,"getPluginConfig"),_init9=_init9?_init9.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init9}}),_class2$1$1),_class$7=_class2$1$1))||_class$7);function __$styleInject(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function unwrapExports$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule$1(e,t){return e(t={exports:{}},t.exports),t.exports}__$styleInject('container{position:relative}container,video{display:block;width:100%;height:100%;background:#000;outline:none}video:focus{outline:none}.chimee-flex-component svg:hover g,.chimee-flex-component svg g{fill:#fff;stroke:#fff}chimee-clarity-list,chimee-control-state-pause,chimee-control-state-play,chimee-progressbar-tip,chimee-screen-full,chimee-screen-small,chimee-volume-state-high,chimee-volume-state-low,chimee-volume-state-mute{display:none}chimee-control.full chimee-screen-full,chimee-control.pause chimee-control-state-pause,chimee-control.play chimee-control-state-play,chimee-control.small chimee-screen-small,chimee-volume.high chimee-volume-state-high,chimee-volume.low chimee-volume-state-low,chimee-volume.mute chimee-volume-state-mute{display:inline-block;width:1.4em;height:100%}chimee-control{display:block;height:100%;line-height:2em;font-size:14px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden;font-family:Roboto,Arial,Helvetica,sans-serif;-webkit-transition:visibility .5s ease;transition:visibility .5s ease}chimee-control,chimee-control-wrap{position:absolute;bottom:0;left:0;width:100%}chimee-control-wrap{height:2.2em;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start;background:rgba(0,0,0,.5);-webkit-transition:bottom .5s ease;transition:bottom .5s ease;pointer-events:auto}.chimee-flex-component{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1;-webkit-box-flex:0;-ms-flex-positive:0;flex-grow:0;height:2em;cursor:pointer}.chimee-flex-component svg{vertical-align:middle;width:2em;height:1.5em}chimee-control-state.chimee-flex-component{-ms-flex-preferred-size:3em;flex-basis:3em;text-align:right;margin-right:1em}chimee-control-state .left,chimee-control-state .right{-webkit-transition:d .2s ease-in-out;transition:d .2s ease-in-out}chimee-progresstime.chimee-flex-component{color:#fff;font-weight:400;text-align:center;white-space:nowrap}chimee-progresstime-pass,chimee-progresstime-total{display:inline}chimee-progressbar.chimee-flex-component{position:relative;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1}chimee-progressbar-wrap{display:inline-block;height:100%;position:absolute;left:1em;right:1em;top:0}chimee-progressbar.progressbar-layout-top{position:static}chimee-progressbar.progressbar-layout-top chimee-progressbar-wrap{top:-1.6em;height:1.6em;left:0;right:0}chimee-progressbar.progressbar-layout-top .chimee-progressbar-line{left:0;top:.8em}.chimee-progressbar-line{position:absolute;top:.9em;left:0;display:inline-block;height:3px}chimee-progressbar-bg{width:100%;background:#4c4c4c}chimee-progressbar-buffer{width:0;background:#6f6f6f}chimee-progressbar-all{background:#de698c}chimee-progressbar-ball{content:"";position:absolute;right:-.8em;top:-.3em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-progressbar-tip{position:absolute;bottom:.5em;top:-1.5em;left:0;z-index:1;padding:0 .5em;height:1.5em;background:#fff;line-height:1.5em;border-radius:4px;color:#000;text-align:center}chimee-volume.chimee-flex-component{cursor:pointer;padding:0;-ms-flex-preferred-size:7em;flex-basis:7em;white-space:nowrap;margin-right:1em;position:relative}chimee-volume.chimee-flex-component.vertical{padding-right:1em;-ms-flex-preferred-size:2em;flex-basis:2em}chimee-volume-state{display:inline-block;width:2em;vertical-align:top}chimee-volume .line,chimee-volume .ring1,chimee-volume .ring2{stroke-dasharray:150;stroke-dashoffset:150;-webkit-transition:stroke-dashoffset .7s ease-in-out;transition:stroke-dashoffset .7s ease-in-out}chimee-volume.high .ring1,chimee-volume.high .ring2,chimee-volume.low .ring2,chimee-volume.mute .line,chimee-volume.mute .ring1,chimee-volume.mute .ring2{stroke-dashoffset:0}chimee-volume.vertical:hover chimee-volume-bar{display:inline-block}chimee-volume.vertical chimee-volume-bar{position:absolute;top:-7em;left:-.2em;width:2em;height:4em;padding-bottom:3em;display:none;vertical-align:middle}chimee-volume.vertical chimee-volume-bar:before{content:"";position:absolute;left:0;right:0;top:0;bottom:1em;background:#212121;border-radius:4px}chimee-volume.vertical chimee-volume-bar-wrap{display:inline-block;position:absolute;bottom:1em;left:0;top:1em;right:0;height:4em}chimee-volume.vertical chimee-volume-bar-all,chimee-volume.vertical chimee-volume-bar-bg{position:absolute;bottom:0;left:1em;display:inline-block;width:2px;border-radius:4px}chimee-volume.vertical chimee-volume-bar-bg{height:4em;background:#4c4c4c;opacity:.5}chimee-volume.vertical chimee-volume-bar-all{background:#de698c}chimee-volume.vertical chimee-volume-bar-all:after{content:"";position:absolute;right:-.34em;top:-.4em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-volume.horizonal chimee-volume-bar{position:relative;height:1.2em;width:4em;display:inline-block;vertical-align:middle}chimee-volume.horizonal chimee-volume-bar-all,chimee-volume.horizonal chimee-volume-bar-bg{position:absolute;top:.4em;left:0;display:inline-block;height:2px}chimee-volume.horizonal chimee-volume-bar-bg{width:4em;background:#4c4c4c;opacity:.5}chimee-volume.horizonal chimee-volume-bar-all{background:#de698c}chimee-volume.horizonal chimee-volume-bar-all:after{content:"";position:absolute;right:-.4em;top:-.3em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-screen.chimee-flex-component{-ms-flex-preferred-size:3em;flex-basis:3em;text-align:left}chimee-clarity.chimee-flex-component{position:relative;color:#fff;width:6em;height:1.75em;padding:0;padding-right:1em;padding-left:1em;text-align:center;vertical-align:middle;font-size:16px}chimee-clarity.chimee-flex-component:hover chimee-clarity-list{display:inline-block}chimee-clarity.chimee-flex-component svg{width:auto;height:auto}chimee-clarity-list{position:absolute;left:0;bottom:1em;width:100%;padding-bottom:1.5em;opacity:.8;-webkit-box-sizing:content-box;box-sizing:content-box;line-height:0}chimee-clarity-list ul{margin:0;padding:.5em 0;background:#292929;line-height:2em}chimee-clarity-list li{list-style-type:none}chimee-clarity-list li.active,chimee-clarity-list li:hover{color:#de698c}chimee-clarity-list-arrow{position:absolute;bottom:1.5em;width:100%}',void 0);var _defined$1=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},_toObject$1=function(e){return Object(_defined$1(e))},hasOwnProperty$2={}.hasOwnProperty,_has$2=function(e,t){return hasOwnProperty$2.call(e,t)},toString$2={}.toString,_cof$1=function(e){return toString$2.call(e).slice(8,-1)},_iobject$1=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==_cof$1(e)?e.split(""):Object(e)},_toIobject$1=function(e){return _iobject$1(_defined$1(e))},ceil$1=Math.ceil,floor$2=Math.floor,_toInteger$1=function(e){return isNaN(e=+e)?0:(e>0?floor$2:ceil$1)(e)},min$2=Math.min,_toLength$1=function(e){return e>0?min$2(_toInteger$1(e),9007199254740991):0},max$1=Math.max,min$1$1=Math.min,_toAbsoluteIndex$1=function(e,t){return(e=_toInteger$1(e))<0?max$1(e+t,0):min$1$1(e,t)},_arrayIncludes$1=function(e){return function(t,r,i){var n,o=_toIobject$1(t),a=_toLength$1(o.length),s=_toAbsoluteIndex$1(i,a);if(e&&r!=r){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===r)return e||s||0;return!e&&-1}},_global$2=createCommonjsModule$1(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)}),SHARED$1="__core-js_shared__",store$1=_global$2[SHARED$1]||(_global$2[SHARED$1]={}),_shared$1=function(e){return store$1[e]||(store$1[e]={})},id$3=0,px$2=Math.random(),_uid$2=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id$3+px$2).toString(36))},shared$1=_shared$1("keys"),_sharedKey$1=function(e){return shared$1[e]||(shared$1[e]=_uid$2(e))},arrayIndexOf$1=_arrayIncludes$1(!1),IE_PROTO$3=_sharedKey$1("IE_PROTO"),_objectKeysInternal$1=function(e,t){var r,i=_toIobject$1(e),n=0,o=[];for(r in i)r!=IE_PROTO$3&&_has$2(i,r)&&o.push(r);for(;t.length>n;)_has$2(i,r=t[n++])&&(~arrayIndexOf$1(o,r)||o.push(r));return o},_enumBugKeys$1="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),_objectKeys$1=Object.keys||function(e){return _objectKeysInternal$1(e,_enumBugKeys$1)},_core$2=createCommonjsModule$1(function(e){var t=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=t)}),_aFunction$2=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx$2=function(e,t,r){if(_aFunction$2(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)}},_isObject$2=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_anObject$2=function(e){if(!_isObject$2(e))throw TypeError(e+" is not an object!");return e},_fails$2=function(e){try{return!!e()}catch(e){return!0}},_descriptors$2=!_fails$2(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),document$1$1=_global$2.document,is$2=_isObject$2(document$1$1)&&_isObject$2(document$1$1.createElement),_domCreate$2=function(e){return is$2?document$1$1.createElement(e):{}},_ie8DomDefine$2=!_descriptors$2&&!_fails$2(function(){return 7!=Object.defineProperty(_domCreate$2("div"),"a",{get:function(){return 7}}).a}),_toPrimitive$2=function(e,t){if(!_isObject$2(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!_isObject$2(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!_isObject$2(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!_isObject$2(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},dP$5=Object.defineProperty,f$9=_descriptors$2?Object.defineProperty:function(e,t,r){if(_anObject$2(e),t=_toPrimitive$2(t,!0),_anObject$2(r),_ie8DomDefine$2)try{return dP$5(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},_objectDp$2={f:f$9},_propertyDesc$2=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_hide$2=_descriptors$2?function(e,t,r){return _objectDp$2.f(e,t,_propertyDesc$2(1,r))}:function(e,t,r){return e[t]=r,e},PROTOTYPE$4="prototype",$export$2=function(e,t,r){var i,n,o,a=e&$export$2.F,s=e&$export$2.G,u=e&$export$2.S,c=e&$export$2.P,l=e&$export$2.B,d=e&$export$2.W,f=s?_core$2:_core$2[t]||(_core$2[t]={}),h=f[PROTOTYPE$4],p=s?_global$2:u?_global$2[t]:(_global$2[t]||{})[PROTOTYPE$4];for(i in s&&(r=t),r)(n=!a&&p&&void 0!==p[i])&&i in f||(o=n?p[i]:r[i],f[i]=s&&"function"!=typeof p[i]?r[i]:l&&n?_ctx$2(o,_global$2):d&&p[i]==o?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$4]=e[PROTOTYPE$4],t}(o):c&&"function"==typeof o?_ctx$2(Function.call,o):o,c&&((f.virtual||(f.virtual={}))[i]=o,e&$export$2.R&&h&&!h[i]&&_hide$2(h,i,o)))};$export$2.F=1,$export$2.G=2,$export$2.S=4,$export$2.P=8,$export$2.B=16,$export$2.W=32,$export$2.U=64,$export$2.R=128;var _export$2=$export$2,_objectSap$1=function(e,t){var r=(_core$2.Object||{})[e]||Object[e],i={};i[e]=t(r),_export$2(_export$2.S+_export$2.F*_fails$2(function(){r(1)}),"Object",i)};_objectSap$1("keys",function(){return function(e){return _objectKeys$1(_toObject$1(e))}});var keys$1$1=_core$2.Object.keys,keys$2=createCommonjsModule$1(function(e){e.exports={default:keys$1$1,__esModule:!0}}),_Object$keys$1=unwrapExports$1(keys$2),IE_PROTO$1$1=_sharedKey$1("IE_PROTO"),ObjectProto$2=Object.prototype,_objectGpo$1=Object.getPrototypeOf||function(e){return e=_toObject$1(e),_has$2(e,IE_PROTO$1$1)?e[IE_PROTO$1$1]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ObjectProto$2:null};_objectSap$1("getPrototypeOf",function(){return function(e){return _objectGpo$1(_toObject$1(e))}});var getPrototypeOf$1$1=_core$2.Object.getPrototypeOf,getPrototypeOf$2=createCommonjsModule$1(function(e){e.exports={default:getPrototypeOf$1$1,__esModule:!0}}),_Object$getPrototypeOf$1=unwrapExports$1(getPrototypeOf$2),classCallCheck$1=createCommonjsModule$1(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")}}),_classCallCheck$1=unwrapExports$1(classCallCheck$1);_export$2(_export$2.S+_export$2.F*!_descriptors$2,"Object",{defineProperty:_objectDp$2.f});var $Object$4=_core$2.Object,defineProperty$2$2=function(e,t,r){return $Object$4.defineProperty(e,t,r)},defineProperty$7=createCommonjsModule$1(function(e){e.exports={default:defineProperty$2$2,__esModule:!0}});unwrapExports$1(defineProperty$7);var createClass$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r,i=(r=defineProperty$7)&&r.__esModule?r:{default:r};t.default=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),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()}),_createClass$1=unwrapExports$1(createClass$1),_stringAt$1=function(e){return function(t,r){var i,n,o=String(_defined$1(t)),a=_toInteger$1(r),s=o.length;return a<0||a>=s?e?"":void 0:(i=o.charCodeAt(a))<55296||i>56319||a+1===s||(n=o.charCodeAt(a+1))<56320||n>57343?e?o.charAt(a):i:e?o.slice(a,a+2):n-56320+(i-55296<<10)+65536}},_library$1=!0,_redefine$2=_hide$2,_iterators$1={},_objectDps$1=_descriptors$2?Object.defineProperties:function(e,t){_anObject$2(e);for(var r,i=_objectKeys$1(t),n=i.length,o=0;n>o;)_objectDp$2.f(e,r=i[o++],t[r]);return e},document$2$1=_global$2.document,_html$1=document$2$1&&document$2$1.documentElement,IE_PROTO$2$1=_sharedKey$1("IE_PROTO"),Empty$1=function(){},PROTOTYPE$1$1="prototype",createDict$1=function(){var e,t=_domCreate$2("iframe"),r=_enumBugKeys$1.length;for(t.style.display="none",_html$1.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),createDict$1=e.F;r--;)delete createDict$1[PROTOTYPE$1$1][_enumBugKeys$1[r]];return createDict$1()},_objectCreate$1=Object.create||function(e,t){var r;return null!==e?(Empty$1[PROTOTYPE$1$1]=_anObject$2(e),r=new Empty$1,Empty$1[PROTOTYPE$1$1]=null,r[IE_PROTO$2$1]=e):r=createDict$1(),void 0===t?r:_objectDps$1(r,t)},_wks$1=createCommonjsModule$1(function(e){var t=_shared$1("wks"),r=_global$2.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:_uid$2)("Symbol."+e))}).store=t}),def$1=_objectDp$2.f,TAG$2=_wks$1("toStringTag"),_setToStringTag$1=function(e,t,r){e&&!_has$2(e=r?e:e.prototype,TAG$2)&&def$1(e,TAG$2,{configurable:!0,value:t})},IteratorPrototype$1={};_hide$2(IteratorPrototype$1,_wks$1("iterator"),function(){return this});var _iterCreate$1=function(e,t,r){e.prototype=_objectCreate$1(IteratorPrototype$1,{next:_propertyDesc$2(1,r)}),_setToStringTag$1(e,t+" Iterator")},ITERATOR$5=_wks$1("iterator"),BUGGY$1=!([].keys&&"next"in[].keys()),FF_ITERATOR$1="@@iterator",KEYS$1="keys",VALUES$1="values",returnThis$1=function(){return this},_iterDefine$1=function(e,t,r,i,n,o,a){_iterCreate$1(r,t,i);var s,u,c,l=function(e){if(!BUGGY$1&&e in p)return p[e];switch(e){case KEYS$1:case VALUES$1:return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f=n==VALUES$1,h=!1,p=e.prototype,m=p[ITERATOR$5]||p[FF_ITERATOR$1]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=_objectGpo$1(y.call(new e)))!==Object.prototype&&c.next&&(_setToStringTag$1(c,d,!0),_library$1||_has$2(c,ITERATOR$5)||_hide$2(c,ITERATOR$5,returnThis$1)),f&&m&&m.name!==VALUES$1&&(h=!0,v=function(){return m.call(this)}),_library$1&&!a||!BUGGY$1&&!h&&p[ITERATOR$5]||_hide$2(p,ITERATOR$5,v),_iterators$1[t]=v,_iterators$1[d]=returnThis$1,n)if(s={values:f?v:l(VALUES$1),keys:o?v:l(KEYS$1),entries:g},a)for(u in s)u in p||_redefine$2(p,u,s[u]);else _export$2(_export$2.P+_export$2.F*(BUGGY$1||h),t,s);return s},$at$1=_stringAt$1(!0);_iterDefine$1(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=$at$1(t,r),this._i+=e.length,{value:e,done:!1})});var _iterStep$1=function(e,t){return{value:t,done:!!e}},es6_array_iterator$1=_iterDefine$1(Array,"Array",function(e,t){this._t=_toIobject$1(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,_iterStep$1(1)):_iterStep$1(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values");_iterators$1.Arguments=_iterators$1.Array;for(var TO_STRING_TAG$1=_wks$1("toStringTag"),DOMIterables$1="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),i$1=0;i$1<DOMIterables$1.length;i$1++){var NAME$1=DOMIterables$1[i$1],Collection$1=_global$2[NAME$1],proto$1=Collection$1&&Collection$1.prototype;proto$1&&!proto$1[TO_STRING_TAG$1]&&_hide$2(proto$1,TO_STRING_TAG$1,NAME$1),_iterators$1[NAME$1]=_iterators$1.Array}var f$1$1=_wks$1,_wksExt$1={f:f$1$1},iterator$2$1=_wksExt$1.f("iterator"),iterator$3=createCommonjsModule$1(function(e){e.exports={default:iterator$2$1,__esModule:!0}});unwrapExports$1(iterator$3);var _meta$1=createCommonjsModule$1(function(e){var t=_uid$2("meta"),r=_objectDp$2.f,i=0,n=Object.isExtensible||function(){return!0},o=!_fails$2(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!_isObject$2(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!_has$2(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!_has$2(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!_has$2(e,t)&&a(e),e}}}),defineProperty$4$2=_objectDp$2.f,_wksDefine$1=function(e){var t=_core$2.Symbol||(_core$2.Symbol=_library$1?{}:_global$2.Symbol||{});"_"==e.charAt(0)||e in t||defineProperty$4$2(t,e,{value:_wksExt$1.f(e)})},f$2$1=Object.getOwnPropertySymbols,_objectGops$1={f:f$2$1},f$3$1={}.propertyIsEnumerable,_objectPie$1={f:f$3$1},_enumKeys$1=function(e){var t=_objectKeys$1(e),r=_objectGops$1.f;if(r)for(var i,n=r(e),o=_objectPie$1.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t},_isArray$1=Array.isArray||function(e){return"Array"==_cof$1(e)},hiddenKeys$1=_enumBugKeys$1.concat("length","prototype"),f$5$1=Object.getOwnPropertyNames||function(e){return _objectKeysInternal$1(e,hiddenKeys$1)},_objectGopn$1={f:f$5$1},gOPN$1$1=_objectGopn$1.f,toString$1$1={}.toString,windowNames$1="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],getWindowNames$1=function(e){try{return gOPN$1$1(e)}catch(e){return windowNames$1.slice()}},f$4$1=function(e){return windowNames$1&&"[object Window]"==toString$1$1.call(e)?getWindowNames$1(e):gOPN$1$1(_toIobject$1(e))},_objectGopnExt$1={f:f$4$1},gOPD$1$1=Object.getOwnPropertyDescriptor,f$6$1=_descriptors$2?gOPD$1$1:function(e,t){if(e=_toIobject$1(e),t=_toPrimitive$2(t,!0),_ie8DomDefine$2)try{return gOPD$1$1(e,t)}catch(e){}if(_has$2(e,t))return _propertyDesc$2(!_objectPie$1.f.call(e,t),e[t])},_objectGopd$1={f:f$6$1},META$1=_meta$1.KEY,gOPD$2=_objectGopd$1.f,dP$1$1=_objectDp$2.f,gOPN$2=_objectGopnExt$1.f,$Symbol$1=_global$2.Symbol,$JSON$2=_global$2.JSON,_stringify$1=$JSON$2&&$JSON$2.stringify,PROTOTYPE$2$1="prototype",HIDDEN$1=_wks$1("_hidden"),TO_PRIMITIVE$1=_wks$1("toPrimitive"),isEnum$2={}.propertyIsEnumerable,SymbolRegistry$1=_shared$1("symbol-registry"),AllSymbols$1=_shared$1("symbols"),OPSymbols$1=_shared$1("op-symbols"),ObjectProto$1$1=Object[PROTOTYPE$2$1],USE_NATIVE$2="function"==typeof $Symbol$1,QObject$1=_global$2.QObject,setter$1=!QObject$1||!QObject$1[PROTOTYPE$2$1]||!QObject$1[PROTOTYPE$2$1].findChild,setSymbolDesc$1=_descriptors$2&&_fails$2(function(){return 7!=_objectCreate$1(dP$1$1({},"a",{get:function(){return dP$1$1(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=gOPD$2(ObjectProto$1$1,t);i&&delete ObjectProto$1$1[t],dP$1$1(e,t,r),i&&e!==ObjectProto$1$1&&dP$1$1(ObjectProto$1$1,t,i)}:dP$1$1,wrap$1=function(e){var t=AllSymbols$1[e]=_objectCreate$1($Symbol$1[PROTOTYPE$2$1]);return t._k=e,t},isSymbol$1=USE_NATIVE$2&&"symbol"==typeof $Symbol$1.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof $Symbol$1},$defineProperty$1=function(e,t,r){return e===ObjectProto$1$1&&$defineProperty$1(OPSymbols$1,t,r),_anObject$2(e),t=_toPrimitive$2(t,!0),_anObject$2(r),_has$2(AllSymbols$1,t)?(r.enumerable?(_has$2(e,HIDDEN$1)&&e[HIDDEN$1][t]&&(e[HIDDEN$1][t]=!1),r=_objectCreate$1(r,{enumerable:_propertyDesc$2(0,!1)})):(_has$2(e,HIDDEN$1)||dP$1$1(e,HIDDEN$1,_propertyDesc$2(1,{})),e[HIDDEN$1][t]=!0),setSymbolDesc$1(e,t,r)):dP$1$1(e,t,r)},$defineProperties$1=function(e,t){_anObject$2(e);for(var r,i=_enumKeys$1(t=_toIobject$1(t)),n=0,o=i.length;o>n;)$defineProperty$1(e,r=i[n++],t[r]);return e},$create$1=function(e,t){return void 0===t?_objectCreate$1(e):$defineProperties$1(_objectCreate$1(e),t)},$propertyIsEnumerable$1=function(e){var t=isEnum$2.call(this,e=_toPrimitive$2(e,!0));return!(this===ObjectProto$1$1&&_has$2(AllSymbols$1,e)&&!_has$2(OPSymbols$1,e))&&(!(t||!_has$2(this,e)||!_has$2(AllSymbols$1,e)||_has$2(this,HIDDEN$1)&&this[HIDDEN$1][e])||t)},$getOwnPropertyDescriptor$2=function(e,t){if(e=_toIobject$1(e),t=_toPrimitive$2(t,!0),e!==ObjectProto$1$1||!_has$2(AllSymbols$1,t)||_has$2(OPSymbols$1,t)){var r=gOPD$2(e,t);return!r||!_has$2(AllSymbols$1,t)||_has$2(e,HIDDEN$1)&&e[HIDDEN$1][t]||(r.enumerable=!0),r}},$getOwnPropertyNames$1=function(e){for(var t,r=gOPN$2(_toIobject$1(e)),i=[],n=0;r.length>n;)_has$2(AllSymbols$1,t=r[n++])||t==HIDDEN$1||t==META$1||i.push(t);return i},$getOwnPropertySymbols$1=function(e){for(var t,r=e===ObjectProto$1$1,i=gOPN$2(r?OPSymbols$1:_toIobject$1(e)),n=[],o=0;i.length>o;)!_has$2(AllSymbols$1,t=i[o++])||r&&!_has$2(ObjectProto$1$1,t)||n.push(AllSymbols$1[t]);return n};USE_NATIVE$2||($Symbol$1=function(){if(this instanceof $Symbol$1)throw TypeError("Symbol is not a constructor!");var e=_uid$2(arguments.length>0?arguments[0]:void 0),t=function(r){this===ObjectProto$1$1&&t.call(OPSymbols$1,r),_has$2(this,HIDDEN$1)&&_has$2(this[HIDDEN$1],e)&&(this[HIDDEN$1][e]=!1),setSymbolDesc$1(this,e,_propertyDesc$2(1,r))};return _descriptors$2&&setter$1&&setSymbolDesc$1(ObjectProto$1$1,e,{configurable:!0,set:t}),wrap$1(e)},_redefine$2($Symbol$1[PROTOTYPE$2$1],"toString",function(){return this._k}),_objectGopd$1.f=$getOwnPropertyDescriptor$2,_objectDp$2.f=$defineProperty$1,_objectGopn$1.f=_objectGopnExt$1.f=$getOwnPropertyNames$1,_objectPie$1.f=$propertyIsEnumerable$1,_objectGops$1.f=$getOwnPropertySymbols$1,_descriptors$2&&!_library$1&&_redefine$2(ObjectProto$1$1,"propertyIsEnumerable",$propertyIsEnumerable$1,!0),_wksExt$1.f=function(e){return wrap$1(_wks$1(e))}),_export$2(_export$2.G+_export$2.W+_export$2.F*!USE_NATIVE$2,{Symbol:$Symbol$1});for(var es6Symbols$1="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),j$1=0;es6Symbols$1.length>j$1;)_wks$1(es6Symbols$1[j$1++]);for(var wellKnownSymbols$1=_objectKeys$1(_wks$1.store),k$1=0;wellKnownSymbols$1.length>k$1;)_wksDefine$1(wellKnownSymbols$1[k$1++]);_export$2(_export$2.S+_export$2.F*!USE_NATIVE$2,"Symbol",{for:function(e){return _has$2(SymbolRegistry$1,e+="")?SymbolRegistry$1[e]:SymbolRegistry$1[e]=$Symbol$1(e)},keyFor:function(e){if(!isSymbol$1(e))throw TypeError(e+" is not a symbol!");for(var t in SymbolRegistry$1)if(SymbolRegistry$1[t]===e)return t},useSetter:function(){setter$1=!0},useSimple:function(){setter$1=!1}}),_export$2(_export$2.S+_export$2.F*!USE_NATIVE$2,"Object",{create:$create$1,defineProperty:$defineProperty$1,defineProperties:$defineProperties$1,getOwnPropertyDescriptor:$getOwnPropertyDescriptor$2,getOwnPropertyNames:$getOwnPropertyNames$1,getOwnPropertySymbols:$getOwnPropertySymbols$1}),$JSON$2&&_export$2(_export$2.S+_export$2.F*(!USE_NATIVE$2||_fails$2(function(){var e=$Symbol$1();return"[null]"!=_stringify$1([e])||"{}"!=_stringify$1({a:e})||"{}"!=_stringify$1(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!isSymbol$1(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&&_isArray$1(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!isSymbol$1(t))return t}),i[1]=t,_stringify$1.apply($JSON$2,i)}}}),$Symbol$1[PROTOTYPE$2$1][TO_PRIMITIVE$1]||_hide$2($Symbol$1[PROTOTYPE$2$1],TO_PRIMITIVE$1,$Symbol$1[PROTOTYPE$2$1].valueOf),_setToStringTag$1($Symbol$1,"Symbol"),_setToStringTag$1(Math,"Math",!0),_setToStringTag$1(_global$2.JSON,"JSON",!0),_wksDefine$1("asyncIterator"),_wksDefine$1("observable");var symbol$2$1=_core$2.Symbol,symbol$3=createCommonjsModule$1(function(e){e.exports={default:symbol$2$1,__esModule:!0}});unwrapExports$1(symbol$3);var _typeof_1$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r=o(iterator$3),i=o(symbol$3),n="function"==typeof i.default&&"symbol"==typeof r.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};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}});unwrapExports$1(_typeof_1$1);var possibleConstructorReturn$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r,i=(r=_typeof_1$1)&&r.__esModule?r:{default:r};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,i.default)(t))&&"function"!=typeof t?e:t}}),_possibleConstructorReturn$1=unwrapExports$1(possibleConstructorReturn$1),$getOwnPropertyDescriptor$1$1=_objectGopd$1.f;_objectSap$1("getOwnPropertyDescriptor",function(){return function(e,t){return $getOwnPropertyDescriptor$1$1(_toIobject$1(e),t)}});var $Object$1$1=_core$2.Object,getOwnPropertyDescriptor$1$2=function(e,t){return $Object$1$1.getOwnPropertyDescriptor(e,t)},getOwnPropertyDescriptor$4=createCommonjsModule$1(function(e){e.exports={default:getOwnPropertyDescriptor$1$2,__esModule:!0}}),_Object$getOwnPropertyDescriptor$1=unwrapExports$1(getOwnPropertyDescriptor$4),get$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r=n(getPrototypeOf$2),i=n(getOwnPropertyDescriptor$4);function n(e){return e&&e.__esModule?e:{default:e}}t.default=function e(t,n,o){null===t&&(t=Function.prototype);var a=(0,i.default)(t,n);if(void 0===a){var s=(0,r.default)(t);return null===s?void 0:e(s,n,o)}if("value"in a)return a.value;var u=a.get;return void 0!==u?u.call(o):void 0}}),_get$1=unwrapExports$1(get$1),check$1=function(e,t){if(_anObject$2(e),!_isObject$2(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},_setProto$1={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=_ctx$2(Function.call,_objectGopd$1.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return check$1(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:check$1};_export$2(_export$2.S,"Object",{setPrototypeOf:_setProto$1.set});var setPrototypeOf$2$1=_core$2.Object.setPrototypeOf,setPrototypeOf$3=createCommonjsModule$1(function(e){e.exports={default:setPrototypeOf$2$1,__esModule:!0}});unwrapExports$1(setPrototypeOf$3),_export$2(_export$2.S,"Object",{create:_objectCreate$1});var $Object$2$1=_core$2.Object,create$2=function(e,t){return $Object$2$1.create(e,t)},create$3=createCommonjsModule$1(function(e){e.exports={default:create$2,__esModule:!0}});unwrapExports$1(create$3);var inherits$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r=o(setPrototypeOf$3),i=o(create$3),n=o(_typeof_1$1);function o(e){return e&&e.__esModule?e:{default:e}}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,n.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}}),_inherits$1=unwrapExports$1(inherits$1),_iterCall$1=function(e,t,r,i){try{return i?t(_anObject$2(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&_anObject$2(n.call(e)),t}},ITERATOR$1$1=_wks$1("iterator"),ArrayProto$1=Array.prototype,_isArrayIter$1=function(e){return void 0!==e&&(_iterators$1.Array===e||ArrayProto$1[ITERATOR$1$1]===e)},_createProperty$1=function(e,t,r){t in e?_objectDp$2.f(e,t,_propertyDesc$2(0,r)):e[t]=r},TAG$1$1=_wks$1("toStringTag"),ARG$1="Arguments"==_cof$1(function(){return arguments}()),tryGet$1=function(e,t){try{return e[t]}catch(e){}},_classof$1=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=tryGet$1(t=Object(e),TAG$1$1))?r:ARG$1?_cof$1(t):"Object"==(i=_cof$1(t))&&"function"==typeof t.callee?"Arguments":i},ITERATOR$2$1=_wks$1("iterator"),core_getIteratorMethod$1=_core$2.getIteratorMethod=function(e){if(void 0!=e)return e[ITERATOR$2$1]||e["@@iterator"]||_iterators$1[_classof$1(e)]},ITERATOR$3$1=_wks$1("iterator"),SAFE_CLOSING$1=!1;try{var riter$1=[7][ITERATOR$3$1]();riter$1.return=function(){SAFE_CLOSING$1=!0}}catch(e){}var _iterDetect$1=function(e,t){if(!t&&!SAFE_CLOSING$1)return!1;var r=!1;try{var i=[7],n=i[ITERATOR$3$1]();n.next=function(){return{done:r=!0}},i[ITERATOR$3$1]=function(){return n},e(i)}catch(e){}return r};_export$2(_export$2.S+_export$2.F*!_iterDetect$1(function(e){}),"Array",{from:function(e){var t,r,i,n,o=_toObject$1(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,d=core_getIteratorMethod$1(o);if(c&&(u=_ctx$2(u,s>2?arguments[2]:void 0,2)),void 0==d||a==Array&&_isArrayIter$1(d))for(r=new a(t=_toLength$1(o.length));t>l;l++)_createProperty$1(r,l,c?u(o[l],l):o[l]);else for(n=d.call(o),r=new a;!(i=n.next()).done;l++)_createProperty$1(r,l,c?_iterCall$1(n,u,[i.value,l],!0):i.value);return r.length=l,r}});var from$1$1=_core$2.Array.from,from$2=createCommonjsModule$1(function(e){e.exports={default:from$1$1,__esModule:!0}}),_Array$from$1=unwrapExports$1(from$2),toConsumableArray$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r,i=(r=from$2)&&r.__esModule?r:{default:r};t.default=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(0,i.default)(e)}}),_toConsumableArray$1=unwrapExports$1(toConsumableArray$1),floor$1$1=Math.floor,_isInteger$1=function(e){return!_isObject$2(e)&&isFinite(e)&&floor$1$1(e)===e};_export$2(_export$2.S,"Number",{isInteger:_isInteger$1});var isInteger$2$1=_core$2.Number.isInteger,isInteger$1$1=createCommonjsModule$1(function(e){e.exports={default:isInteger$2$1,__esModule:!0}});unwrapExports$1(isInteger$1$1);var _stringWs$1="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff",space$1="["+_stringWs$1+"]",non$1="​…",ltrim$1=RegExp("^"+space$1+space$1+"*"),rtrim$1=RegExp(space$1+space$1+"*$"),exporter$1=function(e,t,r){var i={},n=_fails$2(function(){return!!_stringWs$1[e]()||non$1[e]()!=non$1}),o=i[e]=n?t(trim$1):_stringWs$1[e];r&&(i[r]=o),_export$2(_export$2.P+_export$2.F*n,"String",i)},trim$1=exporter$1.trim=function(e,t){return e=String(_defined$1(e)),1&t&&(e=e.replace(ltrim$1,"")),2&t&&(e=e.replace(rtrim$1,"")),e},_stringTrim$1=exporter$1,$parseFloat$1=_global$2.parseFloat,$trim$1=_stringTrim$1.trim,_parseFloat$3=1/$parseFloat$1(_stringWs$1+"-0")!=-1/0?function(e){var t=$trim$1(String(e),3),r=$parseFloat$1(t);return 0===r&&"-"==t.charAt(0)?-0:r}:$parseFloat$1;_export$2(_export$2.S+_export$2.F*(Number.parseFloat!=_parseFloat$3),"Number",{parseFloat:_parseFloat$3});var _parseFloat$1$1=parseFloat,_parseFloat$4=createCommonjsModule$1(function(e){e.exports={default:_parseFloat$1$1,__esModule:!0}});function bind$2(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(_toConsumableArray$1(i)))}}unwrapExports$1(_parseFloat$4);var Base=function(){function e(t){_classCallCheck$1(this,e),this.parent=t}return _createClass$1(e,[{key:"create",value:function(){this.createEl(),this.addAllEvent()}},{key:"destroy",value:function(){this.removeAllEvent()}},{key:"createEl",value:function(){this.$dom=document.createElement(this.option.tag),this.$dom.innerHTML=this.option.html,this.parent.$wrap.appendChild(this.$dom)}},{key:"addAllEvent",value:function(){var e=this;this.option.defaultEvent&&_Object$keys$1(this.option.defaultEvent).forEach(function(t){var r=e.option.defaultEvent[t];e[r]=bind$2(e[r],e),addEvent(e.$dom,t,e[r],!1,!1)}),this.option.event&&_Object$keys$1(this.option.event).forEach(function(t){var r="__"+t;e[r]=bind$2(e.option.event[t],e),addEvent(e.$dom,t,e[r],!1,!1)})}},{key:"removeAllEvent",value:function(){var e=this;this.option.defaultEvent&&_Object$keys$1(this.option.defaultEvent).forEach(function(t){var r=e.option.defaultEvent[t];e[r]=bind$2(e[r],e),removeEvent(e.$dom,t,e[r],!1,!1)}),this.option.event&&_Object$keys$1(this.option.event).forEach(function(t){var r="__"+t;e[r]=bind$2(e.option.event[t],e),removeEvent(e.$dom,t,e[r],!1,!1)})}}]),e}(),Component=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=r,i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),addClassName(this.$dom,"chimee-flex-component")}}]),t}(),defaultOption={tag:"chimee-control-state",html:"\n <chimee-control-state-play></chimee-control-state-play>\n <chimee-control-state-pause></chimee-control-state-pause>\n ",animate:{icon:'\n <svg viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <g fill="#ffffff" stroke="#ffffff">\n <path class="left"></path>\n <path class="right"></path>\n </g>\n </svg>\n ',path:{play:{left:"M0.921875,0.265625L0.921875,197.074852L95.7890625,149L96.2929688,49Z",right:"M90.3142151,45.9315226L90.3142151,151.774115L201.600944,99.9938782L201.600944,98.0237571Z"},pause:{left:"M0.921875,1.265625L0.921875,198.074852L79.3611677,198.074852L79.3611677,0.258923126Z",right:"M126.921875,1.265625L126.921875,198.074852L205.361168,198.074852L205.361168,0.258923126Z"}}},defaultEvent:{click:"click"}},Play=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption,isObject(r)?r:{}),i.animate=!1,i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$dom.addClass("chimee-flex-component"),this.option.icon&&this.option.icon.play&&this.option.icon.pause?(this.$play=this.$dom.find("chimee-control-state-play"),this.$pause=this.$dom.find("chimee-control-state-pause"),this.$play.html(this.option.icon.play),this.$pause.html(this.option.icon.pause)):this.option.bitmap||(this.animate=!0,this.option.animate.path=this.option.path?this.option.path:this.option.animate.path,this.$dom.html(this.option.animate.icon),this.$left=this.$dom.find(".left"),this.$right=this.$dom.find(".right")),this.changeState("pause")}},{key:"changeState",value:function(e){var t="play"===e?"pause":"play";this.state=e,addClassName(this.parent.$dom,t),removeClassName(this.parent.$dom,e),this.animate&&this.setPath(t)}},{key:"setPath",value:function(e){var t=this.option.animate.path;"play"===e?(this.$left.attr("d",t.play.left),this.$right.attr("d",t.play.right)):(this.$left.attr("d",t.pause.left),this.$right.attr("d",t.pause.right))}},{key:"click",value:function(e){var t="play"===this.state?"pause":"play";this.changeState(t),this.parent.$emit(t)}}]),t}(),_class$8;function _applyDecoratedDescriptor$7(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var defaultOption$1={tag:"chimee-volume",html:"\n <chimee-volume-state>\n <chimee-volume-state-mute></chimee-volume-state-mute>\n <chimee-volume-state-low></chimee-volume-state-low>\n <chimee-volume-state-high></chimee-volume-state-high>\n </chimee-volume-state>\n <chimee-volume-bar>\n <chimee-volume-bar-wrap>\n <chimee-volume-bar-bg></chimee-volume-bar-bg>\n <chimee-volume-bar-all>\n <chimee-volume-bar-ball></chimee-volume-bar-ball>\n </chimee-volume-bar-all>\n <chimee-volume-bar-track></chimee-volume-bar-track>\n </chimee-volume-bar-wrap>\n </chimee-volume-bar>\n ",animate:{icon:'\n <svg viewBox="0 0 107 101" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <g class="volume">\n <polygon class="horn" points="0.403399942 30 27.3842118 30 56.8220589 2.84217094e-14 57.9139815 100 27.3842118 70 0.403399942 70"></polygon>\n <path class="ring1" d="M63,5.00975239 C69.037659,4.78612057 75.9178585,8.40856146 83.6405984,15.877075 C95.2247083,27.0798454 100,34.7975125 100,50.9608558 C100,67.1241991 95.3628694,73.7907482 83.6405984,83.8306724 C75.8257511,90.5239552 68.9455516,94.0320644 63,94.355" fill-opacity="0" stroke-width="10"></path>\n <path class="ring2" d="M65.2173913,29.4929195 C67.8779343,29.3931169 70.9097496,31.0097416 74.3128371,34.3427934 C79.4174684,39.3423712 81.5217391,42.7866154 81.5217391,50 C81.5217391,57.2133846 79.4783502,60.1885354 74.3128371,64.6691576 C70.8691617,67.656239 67.8373465,69.2218397 65.2173913,69.3659595" fill-opacity="0" stroke-width="10"></path>\n <path class="line" d="M4.19119202,3.65220497 L102,96" stroke-width="10"></path>\n </g>\n </svg>\n '},defaultEvent:{mousedown:"mousedown"}},getElementPath=function(e){var t=[];if(null===e)return t;for(t.push(e);null!==e.parentNode;)e=e.parentNode,t.push(e);return t},Volume=(_class$8=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.parent.preVolume=0,i.option=deepAssign(defaultOption$1,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){var e=this;_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$state=this.$dom.find("chimee-volume-state"),this.$bar=this.$dom.find("chimee-volume-bar"),this.$all=this.$dom.find("chimee-volume-bar-all"),this.$bg=this.$dom.find("chimee-volume-bar-bg"),this.layout="vertical"===this.option.layout?"vertical":"horizonal",this.option.icon&&this.option.icon.mute&&this.option.icon.low?(this.option.icon.high=this.option.icon.high||this.option.icon.low,this.$mute=this.$dom.find("chimee-volume-state-mute"),this.$low=this.$dom.find("chimee-volume-state-low"),this.$high=this.$dom.find("chimee-volume-state-high"),this.$mute.html(this.option.icon.mute),this.$low.html(this.option.icon.low),this.$high.html(this.option.icon.high)):this.option.bitmap||(this.animate=!0,this.$state.html(this.option.animate.icon)),this.$dom.addClass("chimee-flex-component "+this.layout),this.changeState(),this.watch_muted=this.parent.$watch("muted",function(t){e.update()})}},{key:"inited",value:function(){this.update()}},{key:"destroy",value:function(){this.watch_muted(),_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"destroy",this).call(this)}},{key:"changeState",value:function(){this.parent.muted||0===this.parent.volume?this.state="mute":this.parent.volume>0&&this.parent.volume<=.5?this.state="low":this.parent.volume>.5&&this.parent.volume<=1&&(this.state="high"),this.$dom.removeClass("mute low high"),this.$dom.addClass(this.state)}},{key:"click",value:function(e){var t=e.path||getElementPath(e.target);return-1!==t.indexOf(this.$state[0])?(this.stateClick(e),"state"):-1!==t.indexOf(this.$bar[0])?(this.barClick(e),"bar"):"padding"}},{key:"stateClick",value:function(){if(this.parent.muted)this.parent.muted=!1;else{var e=this.parent.volume;this.parent.volume=0===e?this.parent.preVolume:0,this.parent.preVolume=e,this.changeState()}}},{key:"barClick",value:function(e){var t="vertical"===this.layout?1-e.offsetY/this.$bg[0].offsetHeight:e.offsetX/this.$bg[0].offsetWidth;this.parent.volume=t<0?0:t>1?1:t,this.update()}},{key:"mousedown",value:function(e){"bar"===this.click(e)&&(this.startX="vertical"===this.layout?e.clientY:e.clientX,this.startVolume=this.parent.volume,addEvent(window,"mousemove",this.draging),addEvent(window,"mouseup",this.dragEnd),addEvent(window,"contextmenu",this.dragEnd))}},{key:"update",value:function(){this.changeState();var e=this.parent.muted?0:this.parent.volume;"vertical"===this.layout?this.$all.css("height",100*e+"%"):this.$all.css("width",100*e+"%")}},{key:"draging",value:function(e){this.endX="vertical"===this.layout?e.clientY:e.clientX;var t="vertical"===this.layout?(this.startX-this.endX)/this.$bg[0].offsetHeight:(this.endX-this.startX)/this.$bg[0].offsetWidth,r=+(this.startVolume+t).toFixed(2);this.parent.volume=r<0?0:r>1?1:r,this.parent.muted=!1}},{key:"dragEnd",value:function(){this.startX=0,this.startVolume=0,removeEvent(window,"mousemove",this.draging),removeEvent(window,"mouseup",this.dragEnd),removeEvent(window,"contextmenu",this.dragEnd)}}]),t}(),_applyDecoratedDescriptor$7(_class$8.prototype,"draging",[autobind],_Object$getOwnPropertyDescriptor$1(_class$8.prototype,"draging"),_class$8.prototype),_applyDecoratedDescriptor$7(_class$8.prototype,"dragEnd",[autobind],_Object$getOwnPropertyDescriptor$1(_class$8.prototype,"dragEnd"),_class$8.prototype),_class$8),_class$1$2;function _applyDecoratedDescriptor$1$2(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var defaultOption$2={tag:"chimee-progressbar",html:'\n <chimee-progressbar-wrap>\n <chimee-progressbar-bg class="chimee-progressbar-line"></chimee-progressbar-bg>\n <chimee-progressbar-buffer class="chimee-progressbar-line"></chimee-progressbar-buffer>\n <chimee-progressbar-all class="chimee-progressbar-line">\n <chimee-progressbar-ball></chimee-progressbar-ball>\n </chimee-progressbar-all>\n <chimee-progressbar-tip></chimee-progressbar-tip>\n </chimee-progressbar-wrap>\n '},ProgressBar=(_class$1$2=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption$2,isObject(r)?r:{}),i.visiable=!1!==r,i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$wrap=this.$dom.find("chimee-progressbar-wrap"),this.$buffer=this.$dom.find("chimee-progressbar-buffer"),this.$all=this.$dom.find("chimee-progressbar-all"),this.$tip=this.$dom.find("chimee-progressbar-tip"),this.$track=this.$dom.find("chimee-progressbar-track"),this.$line=this.$dom.find(".chimee-progressbar-line"),this.$ball=this.$dom.find("chimee-progressbar-ball"),this.$dom.addClass("chimee-flex-component"),!this.visiable&&this.$dom.css("visibility","hidden"),"top"===this.option.layout&&(this.$dom.addClass("progressbar-layout-top"),this.$wrap.css({top:-this.$ball[0].offsetHeight+"px"}),setStyle(this.parent.$wrap,"paddingTop",this.$ball[0].offsetHeight+"px")),this.addWrapEvent()}},{key:"destroy",value:function(){this.removeWrapEvent(),this.watch_screen&&this.watch_screen(),_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"destroy",this).call(this)}},{key:"addWrapEvent",value:function(){this.$wrap.on("mousedown",this.mousedown),this.$wrap.on("mousemove",this.tipShow),this.$wrap.on("mouseleave",this.tipEnd)}},{key:"removeWrapEvent",value:function(){this.$wrap.off("mousedown",this.mousedown),this.$wrap.off("mousemove",this.tipShow),this.$wrap.off("mouseleave",this.tipEnd)}},{key:"progress",value:function(){var e=0;try{e=this.parent.buffered.end(0)}catch(e){}var t=e/this.parent.duration*100+"%";this.$buffer.css("width",t)}},{key:"update",value:function(){var e=void 0!==this._currentTime?this._currentTime:this.parent.currentTime,t=e?e/this.parent.duration:0;this.$all.css("width","calc("+100*t+"% - "+this.$ball[0].offsetWidth/2+"px")}},{key:"mousedown",value:function(e){e.target!==this.$tip[0]&&(this._currentTime=e.offsetX/this.$wrap[0].offsetWidth*this.parent.duration,this.startX=e.clientX,this.startTime=this._currentTime,addEvent(window,"mousemove",this.draging),addEvent(window,"mouseup",this.dragEnd),addEvent(window,"contextmenu",this.dragEnd))}},{key:"draging",value:function(e){this.endX=e.clientX;var t=(this.endX-this.startX)/this.$wrap[0].offsetWidth*this.parent.duration,r=+(this.startTime+t).toFixed(2);this._currentTime=r<0?0:r>this.parent.duration?this.parent.duration:r,this.update()}},{key:"dragEnd",value:function(){this.update(),this.startX=0,this.startTime=0,this.parent.currentTime=this._currentTime,this._currentTime=void 0,removeEvent(window,"mousemove",this.draging),removeEvent(window,"mouseup",this.dragEnd),removeEvent(window,"contextmenu",this.dragEnd)}},{key:"tipShow",value:function(e){if(e.target!==this.$tip[0]&&e.target!==this.$ball[0]){var t=e.offsetX/this.$wrap[0].offsetWidth*this.parent.duration,r=formatTime(t=t<0?0:t>this.parent.duration?this.parent.duration:t),i=e.offsetX-this.$tip[0].offsetWidth/2,n=this.$wrap[0].offsetWidth-this.$tip[0].offsetWidth;i=i<0?0:i>n?n:i,this.$tip.text(r),this.$tip.css("display","inline-block"),this.$tip.css("left",i+"px")}else this.$tip.css("display","none")}},{key:"tipEnd",value:function(){this.$tip.css("display","none")}}]),t}(),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"mousedown",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"mousedown"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"draging",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"draging"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"dragEnd",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"dragEnd"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"tipShow",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"tipShow"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"tipEnd",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"tipEnd"),_class$1$2.prototype),_class$1$2),defaultOption$3={tag:"chimee-progresstime",html:"\n <chimee-progresstime-pass>00:00</chimee-progresstime-pass\n ><chimee-progresstime-total\n ><span>/</span\n ><chimee-progresstime-total-value>00:00</chimee-progresstime-total-value>\n </chimee-progresstime-total>\n "},ProgressTime=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption$3,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$total=this.$dom.find("chimee-progresstime-total-value"),this.$pass=this.$dom.find("chimee-progresstime-pass"),this.$dom.addClass("chimee-flex-component")}},{key:"updatePass",value:function(){this.$pass.text(formatTime(this.parent.currentTime))}},{key:"updateTotal",value:function(){this.$total.text(formatTime(this.parent.duration))}}]),t}(),_class$2$1;function _applyDecoratedDescriptor$2$1(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var defaultOption$4={tag:"chimee-screen",html:'\n <chimee-screen-full>\n <svg viewBox="0 0 67 66" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n \x3c!-- Generator: Sketch 43.1 (39012) - http://www.bohemiancoding.com/sketch --\x3e\n <desc>Created with Sketch.</desc>\n <defs></defs>\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n <g id="screen-small" transform="translate(33.756308, 32.621867) rotate(45.000000) translate(-33.756308, -32.621867) translate(18.756308, -10.378133)" fill="#FFFFFF">\n <polygon id="Path" transform="translate(14.967695, 66.389245) rotate(180.000000) translate(-14.967695, -66.389245) " points="11.5190786 46.9431778 11.7210093 70.7913773 0.565180527 70.7913773 15.4674455 85.8353125 29.3702096 70.7913773 18.5573247 70.7702156 18.5573247 46.9431778"></polygon>\n <polygon id="Path" points="11.5190786 0.274130278 11.7210093 24.1223298 0.565180527 24.1223298 15.4674455 39.1662649 29.3702096 24.1223298 18.5573247 24.1011681 18.5573247 0.274130278"></polygon>\n </g>\n </g>\n </svg>\n </chimee-screen-full>\n <chimee-screen-small>\n <svg viewBox="0 0 61 62" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n \x3c!-- Generator: Sketch 43.1 (39012) - http://www.bohemiancoding.com/sketch --\x3e\n <desc>Created with Sketch.</desc>\n <defs></defs>\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n <g id="Group" transform="translate(30.756308, 30.621867) rotate(45.000000) translate(-30.756308, -30.621867) translate(15.756308, -12.378133)" fill="#FFFFFF">\n <polygon id="Path" points="11.5190786 46.9431778 11.7210093 70.7913773 0.565180527 70.7913773 15.4674455 85.8353125 29.3702096 70.7913773 18.5573247 70.7702156 18.5573247 46.9431778"></polygon>\n <polygon id="Path" transform="translate(14.967695, 19.720198) rotate(180.000000) translate(-14.967695, -19.720198) " points="11.5190786 0.274130278 11.7210093 24.1223298 0.565180527 24.1223298 15.4674455 39.1662649 29.3702096 24.1223298 18.5573247 24.1011681 18.5573247 0.274130278"></polygon>\n </g>\n </g>\n </svg>\n </chimee-screen-small>\n ',defaultEvent:{click:"click"}},Screen=(_class$2$1=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.state="small",i.option=deepAssign(defaultOption$4,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.changeState(this.state),this.$dom.addClass("chimee-flex-component"),this.$full=this.$dom.find("chimee-screen-full"),this.$small=this.$dom.find("chimee-screen-small"),this.option.icon&&this.option.icon.full&&this.option.icon.small?(this.$full.html(this.option.icon.full),this.$small.html(this.option.icon.small)):this.option.bitmap&&(this.$full.html(""),this.$small.html(""))}},{key:"changeState",value:function(e){var t="small"===e?"full":"small";addClassName(this.parent.$dom,e),removeClassName(this.parent.$dom,t)}},{key:"click",value:function(){var e=!1;"small"===this.state?(this.state="full",e=!0):(this.state="small",e=!1),this.changeState(this.state),this.parent.$fullscreen(e,"container"),e?this.watch_screen=this.parent.$watch("isFullscreen",this.screenChange):this.watch_screen()}},{key:"screenChange",value:function(){this.parent.fullscreenElement&&(this.state="small",this.changeState("small"),this.parent.$fullscreen(!1,"container"))}}]),t}(),_applyDecoratedDescriptor$2$1(_class$2$1.prototype,"screenChange",[autobind],_Object$getOwnPropertyDescriptor$1(_class$2$1.prototype,"screenChange"),_class$2$1.prototype),_class$2$1),defaultOption$5={tag:"chimee-clarity",width:"2em",html:'\n <chimee-clarity-text></chimee-clarity-text>\n <chimee-clarity-list>\n <ul></ul>\n <div class="chimee-clarity-list-arrow">\n <svg viewBox="0 0 115 6" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <g id="Group-3-Copy" fill="#57B0F6">\n <polygon id="Path-2" points="0.0205224145 0.0374249581 0.0205224145 2.12677903 53.9230712 2.12677903 57.1127727 5.3468462 60.2283558 2.12677903 113.820935 2.12677903 113.820935 0.0374249581"></polygon>\n </g>\n </svg>\n </div>\n </chimee-clarity-list>\n ',defaultEvent:{click:"click"},duration:10,increment:1},Clarity=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption$5,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),addClassName(this.$dom,"chimee-flex-component"),this.$text=$(this.$dom).find("chimee-clarity-text"),this.$list=$(this.$dom).find("chimee-clarity-list"),this.$listUl=this.$list.find("ul"),this.option.width&&setStyle(this.$dom,"width",this.option.width),this.initTextList()}},{key:"initTextList",value:function(){var e=this;this.option.list.forEach(function(t){var r=$(document.createElement("li"));r.attr("data-url",t.src),r.text(t.name),t.src===e.parent.$videoConfig.src&&(e.$text.text(t.name),r.addClass("active")),e.$listUl.append(r)})}},{key:"click",value:function(e){var t=this,r=e.target;if("LI"===r.tagName){var i=r.getAttribute("data-url")||"";this.switchClarity(i).then(function(){t.loadOption=void 0,_Array$from$1(r.parentElement.children).map(function(e){removeClassName(e,"active")}),addClassName(e.target,"active"),t.$text.text(e.target.textContent)}).catch(function(e){console.warn(e)})}}},{key:"switchClarity",value:function(e){return this.loadOption&&(this.loadOption.abort=!0),this.loadOption={duration:this.option.duration,repeatTimes:3,immediate:!0,increment:this.option.increment},this.parent.$silentLoad(e,this.loadOption)}}]),t}();function hundleChildren(e){return e.$config.children?e.$config.children:e.isLive?{play:!0,progressTime:!1,progressBar:!1,volume:!0,screen:!0}:{play:!0,progressTime:!0,progressBar:!0,volume:!0,screen:!0}}function createChild(e){var t=e.config.children=hundleChildren(e),r={};return t?_Object$keys$1(t).forEach(function(i){switch(i){case"play":t.play&&(r.play=new Play(e,t.play));break;case"progressTime":t.progressTime&&(r.progressTime=new ProgressTime(e,t.progressTime));break;case"progressBar":r.progressBar=new ProgressBar(e,t.progressBar);break;case"volume":t.volume&&(r.volume=new Volume(e,t.volume));break;case"screen":t.screen&&(r.screen=new Screen(e,t.screen));break;case"clarity":t.clarity&&Array.isArray(t.clarity.list)&&(r.clarity=new Clarity(e,t.clarity));break;default:r[i]=new Component(e,t[i])}}):(r.play=new Play(e),r.progressTime=new ProgressTime(e),r.progressBar=new ProgressBar(e),r.volume=new Volume(e),r.screen=new Screen(e)),r}var majorColorStyle="\n .chimee-flex-component svg *{\n fill: majorColor;\n stroke: majorColor;\n }\n chimee-progressbar-all{\n background: majorColor;\n }\n chimee-volume.chimee-flex-component chimee-volume-bar-all{\n background: majorColor; \n }\n chimee-clarity-list li:hover,\n chimee-clarity-list li.active {\n color: majorColor;\n }\n",hoverColorStyle="\n .chimee-flex-component svg:hover *{\n fill: hoverColor;\n stroke: hoverColor;\n }\n",defaultConfig$1={hideBarTime:2e3,barShowByMouse:"move"},chimeeControl={name:"chimeeControl",el:"chimee-control",data:{children:{},show:!1,disabled:!0},level:99,operable:!1,penetrate:!1,create:function(){},init:function(e){e.controls&&(this.show=!0,e.controls=!1);var t=this;applyDecorators(e,{controls:accessor({get:function(){return t.show},set:function(e){return t.show=Boolean(e),t._display(),!1}},{preSet:!0})},{self:!0}),this.config=isObject(this.$config)?deepAssign(defaultConfig$1,this.$config):defaultConfig$1,this.config.hideBarTime="move"===this.config.barShowByMouse?this.config.hideBarTime:0,this.$dom.innerHTML="<chimee-control-wrap></chimee-control-wrap>",this.$wrap=this.$dom.querySelector("chimee-control-wrap"),this.children=createChild(this),this._setStyle()},destroy:function(){window.clearTimeout(this.timeId)},inited:function(){for(var e in this.children)this.children[e].inited&&this.children[e].inited()},events:{loadstart:function(){this._disable(!0)},canplay:function(){this._disable(!1)},play:function(){this.children.play&&this.children.play.changeState("play"),"move"===this.config.barShowByMouse&&this._hideItself()},pause:function(){this.children.play&&this.children.play.changeState("pause"),this._showItself()},c_mouseenter:function(){"move"!==this.config.barShowByMouse&&this._showItself()},c_mousemove:function(){this._mousemove()},c_mouseleave:function(){"move"!==this.config.barShowByMouse&&this._hideItself()},durationchange:function(){this.children.progressTime&&this.children.progressTime.updateTotal()},timeupdate:function(){this._progressUpdate()},progress:function(){this.children.progressBar&&this.children.progressBar.progress()},volumechange:function(){this.children.volume&&this.children.volume.update()},keydown:function(e){if(!this.disabled)switch(e.stopPropagation(),e.keyCode){case 32:e.preventDefault(),this.children.play&&this.children.play.click(e);break;case 37:e.preventDefault();var t=this.currentTime-10;this.currentTime=t<0?0:t,this._mousemove();break;case 39:e.preventDefault();var r=this.currentTime+10;this.currentTime=r>this.duration?this.duration:r,this._mousemove();break;case 38:e.preventDefault();var i=this.volume+.1;this.volume=i>1?1:i,this._mousemove();break;case 40:e.preventDefault();var n=this.volume-.1;this.volume=n<0?0:n,this._mousemove()}},click:function(e){var t=this,r=new Date,i=this.clickTime;this.clickTime=r,r-i<300?clearTimeout(this.clickTimeId):this.clickTimeId=setTimeout(function(){!t.disabled&&t.children.play&&t.children.play.click(e)},300)},dblclick:function(e){!this.disabled&&this.children.screen&&this.children.screen.click()}},methods:{_progressUpdate:function(){this.children.progressBar&&this.children.progressBar.update(),this.children.progressTime&&this.children.progressTime.updatePass()},_hideItself:function(){var e=this;window.clearTimeout(this.timeId),this.timeId=setTimeout(function(){var t=e.$wrap.offsetHeight;t=e.children.progressBar?e.children.progressBar.$wrap[0].offsetTop-t:-t,setStyle(e.$wrap,{bottom:t+"px"}),setStyle(e.$dom,{visibility:"hidden"})},this.config.hideBarTime)},_showItself:function(){window.clearTimeout(this.timeId),setStyle(this.$wrap,{bottom:"0"}),setStyle(this.$dom,{visibility:"visible"})},_display:function(){var e=this.show?"block":"none";setStyle(this.$dom,{display:e})},_mousemove:function(e){this.paused||"enter"===this.config.barShowByMouse||(this._showItself(),this._hideItself())},_disable:function(e){this.show&&(this.disabled=e,setStyle(this.$wrap,"pointerEvents",e?"none":"auto"))},_setStyle:function(){var e="";e+=this.config.majorColor?majorColorStyle.replace(/majorColor/g,this.config.majorColor):"",e+=this.config.hoverColor?hoverColorStyle.replace(/hoverColor/g,this.config.hoverColor):"";var t=document.createElement("style");t.setAttribute("type","text/css"),t.innerHTML=e,document.head.appendChild(t)}}};function __$styleInject$1(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function popupFactory(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,k=e.computed,D=e.methods,I=void 0===D?{}:D,x=e.penetrate,C=void 0!==x&&x,M=e.operable,P=void 0===M||M,L=e.hide,R=void 0!==L&&L,N=e.opened,j=e.closed,F=e.autoFocus,B={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];isObject(i)&&(isObject(i.events)&&deepAssign(t,i.events),isObject(i.methods)&&deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=isObject(this.$config)?deepAssign(B,this.$config):B;(this.$domWrap=$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=R;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:k,penetrate:C,operable:P,autoFocus:F,methods:deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),isFunction(N)&&N.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),isFunction(j)&&j.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray(t,2),i=r[0],n=r[1];return""!==i&&(this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),"transform"in document.createElement("a").style||!window.console||!window.console.warn||console.warn("[chimee-plugin-popup] 当前环境不支持CSS3的transform特性,Dom元素无法正常使用translate。")),this}},I)}}function __$styleInject$2(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function popupFactory$1(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,k=e.computed,D=e.methods,I=void 0===D?{}:D,x=e.penetrate,C=void 0!==x&&x,M=e.operable,P=void 0===M||M,L=e.hide,R=void 0!==L&&L,N=e.opened,j=e.closed,F=e.autoFocus,B={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];isObject(i)&&(isObject(i.events)&&deepAssign(t,i.events),isObject(i.methods)&&deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=isObject(this.$config)?deepAssign(B,this.$config):B;(this.$domWrap=$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=R;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:k,penetrate:C,operable:P,autoFocus:F,methods:deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),isFunction(N)&&N.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),isFunction(j)&&j.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&"auto"!==t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray(t,2),i=r[0],n=r[1];return i&&this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),this}},I)}}function __$styleInject$3(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}__$styleInject$1("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0),__$styleInject$2("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0),__$styleInject$3("chimee-menu{position:absolute;color:#fff;background-color:rgba(37,37,37,.7);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);border-radius:2px;padding:2px;box-shadow:0 1px 4px rgba(0,0,0,.6)}chimee-menu ul{margin:0;padding:0;font-size:12px}chimee-menu li{cursor:pointer;padding:0 4px;line-height:24px;list-style:none;white-space:nowrap;margin:0;border:0;font-size:12px;font-weight:400}chimee-menu li:hover{background-color:hsla(0,0%,100%,.1)}chimee-menu li[disable]{opacity:.5;cursor:default}chimee-menu li a{color:#fff;text-decoration:none}chimee-menu li a:hover{color:#fff}",void 0);var logPopupOpenEvt="openLogPopup",contextmenuConf=popupFactory$1({tagName:"chimee-menu",name:"chimeeContextmenu",html:"<ul></ul>",offset:"0",hide:!0,data:{baseMenus:[{text:"查看日志",action:logPopupOpenEvt,hide:!0},{text:"Chimee {VERSION} © 360",url:"http://chimee.org",disable:!0}]},create:function(){var e=this,t=this.$config,r=t.baseMenus,i=t.menus;isArray(r)&&(this.baseMenus=r),this.updatemenu(i),this.$domWrap.on("click",this.clickHandler),this.$plugins.chimeeLog&&this.switchLogMenu(!1),this._doc=new this.$domWrap.constructor(document),this._doc_click=function(t){return e.close()},this._doc.on("click",this._doc_click)},destroy:function(){this._doc.off("click",this._doc_click)},opened:function(){this.$bumpToTop()},events:{contextmenu:function(e){var t=e.offsetX,r=e.offsetY,i=this.$dom.parentElement;if(isFunction(i.getBoundingClientRect)){var n=i.getBoundingClientRect();t=e.pageX-n.left-(document.documentElement.scrollLeft||document.body.scrollLeft||0),r=e.pageY-n.top-(document.documentElement.scrollTop||document.body.scrollTop||0)}this.offset(t+"px "+r+"px").open(e),e.preventDefault()},logPluginDestroy:function(){this.switchLogMenu(!0)},logPluginCreate:function(){this.switchLogMenu(!1)}},methods:{switchLogMenu:function(e){var t=this.baseMenus.find(function(e){return e.action===logPopupOpenEvt});t&&(t.hide=e,this.$domWrap.find('[data-action="'+logPopupOpenEvt+'"]').css("display",e?"none":""))},updatemenu:function(e){var t=this,r=[];isArray(e)&&(r=r.concat(e));var i=r.concat(this.baseMenus).map(function(e){var r=e.hide,i=e.disable,n=e.action,o=e.className,a=e.text,s=e.url,u=i?"disable":"",c=n?'data-action="'+n+'"':"",l=o?'class="'+o+'"':"",d=r?'style="display:none"':"",f=a.replace(/\{([^)]*)\}/g,function(e,r){return t[r]});return s&&(f='<a href="'+s+'" target="_blank">'+f+"</a>"),"<li "+u+" "+c+" "+l+" "+d+">"+f+"</li>"}).join("");this.$domWrap.find("ul").html(i)},clickHandler:function(e){var t=e.target;if(!t.disable){var r=t.dataset.action;r&&(this.$emit(r),isFunction(this[r])&&this[r](e)),this.close()}e.stopPropagation()}}});function __$styleInject$4(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function popupFactory$2(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,k=e.computed,D=e.methods,I=void 0===D?{}:D,x=e.penetrate,C=void 0!==x&&x,M=e.operable,P=void 0===M||M,L=e.hide,R=void 0!==L&&L,N=e.opened,j=e.closed,F=e.autoFocus,B={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];isObject(i)&&(isObject(i.events)&&deepAssign(t,i.events),isObject(i.methods)&&deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=isObject(this.$config)?deepAssign(B,this.$config):B;(this.$domWrap=$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=R;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:k,penetrate:C,operable:P,autoFocus:F,methods:deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),isFunction(N)&&N.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),isFunction(j)&&j.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&"auto"!==t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray(t,2),i=r[0],n=r[1];return i&&this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),this}},I)}}function __$styleInject$5(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}__$styleInject$4("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0),__$styleInject$5(".chimee-log{padding:2px;box-shadow:0 1px 4px rgba(0,0,0,.6)}.chimee-log label{margin-left:10px;font-weight:100;font-size:12px}.chimee-log label input{vertical-align:middle;display:inline;width:auto;padding:0;margin:0}.chimee-log vs-pp-body{padding:3px}.chimee-log textarea{display:block;width:100%;height:200px;margin:-3px;border:1px solid hsla(0,0%,100%,.5);background-color:hsla(0,0%,100%,.9)}",void 0);var pageLoadedTimestamp=(new Date).getTime().toString();setLocalStorage("_chimee_t",pageLoadedTimestamp);var supportLS=getLocalStorage("_chimee_t")===pageLoadedTimestamp,defaultEvents=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i={};return t.forEach(function(e){i[e]=function(t){for(var r=this,i=arguments.length,n=Array(i>1?i-1:0),o=1;o<i;o++)n[o-1]=arguments[o];this.writeLog(t);var a=this.box,s=this.type,u=this.src,c=this._waiting_num,l=this.currentTime,d=this._is_seek,f=void 0!==d&&d,h=this._is_play,p=void 0!==h&&h,m=this.playingTimestamp,v=this.loadstartTimestamp,g=this.waitingTimestamp;switch(e){case"loadstart":this.sendLog(e,{box:a,type:s,src:u}),this._ls_timeout=setTimeout(function(){r.sendLog("timeout",{src:u})},this.timeoutDelay),this._total_waiting_time=0;break;case"seeking":this._is_seek=!0;break;case"play":this._is_play=!0;break;case"pause":this.sendLog(e,{src:u,currentTime:l});break;case"canplay":clearTimeout(this._ls_timeout);var y=this.canplayTimestamp;this.sendLog(e,{src:u,currentTime:l,waitingNum:c,waitingTime:y-(v||g||y)});break;case"playing":clearTimeout(this._ls_timeout);var _=m-(v||g||m);this._total_waiting_time+=_,this.sendLog(e,{src:u,waitingNum:c,currentTime:l,isSeek:f,isPlay:p,waitingTime:_}),this.loadstartTimestamp=0,this.waitingTimestamp=0,this._is_seek=!1,this._is_play=!1;break;case"ended":this.sendLog(e,{src:u,waitingNum:c,totalWaitingTime:this._total_waiting_time});break;case"waiting":this._waiting_num++,this.sendLog(e,{src:u,waitingNum:c,currentTime:l,isSeek:f,isPlay:p});break;case"error":this.sendLog(e,{src:u,args:n})}}}),i}("loadstart","abort","durationchange","loadedmetadata","loadeddata","progress","canplay","canplaythrough","pause","play","playing","emptied","ended","seeking","seeked","stalled","suspend","timeupdate","waiting","error"),index$1=popupFactory$2({name:"chimeeLog",className:"chimee-log",title:"日志信息"+(supportLS?'<label><input type="checkbox">下次自动打开</label>':""),body:"<textarea>Chimee logs:</textarea>",offset:"0",width:"400px",hide:!0,autoFocus:!1,logPostUrl:void 0,beforeCreate:function(e,t){isUrl(t.logPostUrl)&&(this.logPostUrl=t.logPostUrl),t.timeoutDelay&&(this.timeoutDelay=t.timeoutDelay)},create:function(){this.logBase.ver=this.VERSION;var e=this.$domWrap;if(this.$txtEl=e.find("textarea"),supportLS){var t="1"===getLocalStorage("auto_on");e.find('input[type="checkbox"]').on("change",function(e){setLocalStorage("auto_on",+this.checked)})[0].checked=t,this._hide=!t}this.writeLog({type:"ready"}),this.$emitSync("logPluginCreate")},destroy:function(){clearTimeout(this._ls_timeout),this.$emitSync("logPluginDestroy"),this.sendLog("destroy")},inited:function(){},closed:function(){this.$txtEl.text("")},opened:function(){this.$bumpToTop()},methods:{writeLog:function(e){var t=e.type;if(this[t+"Timestamp"]=+new Date,!this._hide){var r=void 0,i="write_"+t+"_log";if(this[i]){for(var n=arguments.length,o=Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];r=this[i](t,o)}var s=this.$txtEl.text()+"\n["+formatDate(new Date(this[t+"Timestamp"]),"yyyy-MM-dd hh:mm:ss.i")+"] "+t+" "+(void 0!==r?_JSON$stringify(r):""),u=this.$txtEl.text(s)[0];u.scrollTop=u.scrollHeight}},write_loadstart_log:function(e){return{box:this.box,type:this.type,src:this.src}},write_durationchange_log:function(){return{duration:this.duration}},write_timeupdate_log:function(){return{currentTime:this.currentTime}},send_inited_log:function(){var e=this.box,t=this.type,r=this.src,i=this.controls,n=this.loop;return{pro:location.protocol,box:e,type:t,src:r,ctrs:i,loop:n}},sendLog:function(e,t){var r=this.logPostUrl;if(r){var i=deepAssign(t||{},this.logBase),n="send_"+e+"_log";this[n]&&deepAssign(i,this[n](e,i)),deepAssign(i,{evt:e,_t:+new Date,_r:Math.random()});var o=[];_Object$keys(i).forEach(function(e){return o.push(encodeURIComponent(e)+"="+encodeURIComponent(i[e]))});var a=new Image;a.onload=a.onerror=function(e){a=null},a.src=r+"?"+o.join("&")}}},events:deepAssign(defaultEvents,{openLogPopup:function(){this.open()}}),data:{timeoutDelay:3e4,pageLoadedTimestamp:pageLoadedTimestamp,_waiting_num:0,_total_waiting_time:0,logBase:{uid:(uid=getLocalStorage("_chimee_uid"),uid||setLocalStorage("_chimee_uid",uid=uuid()),uid),ref:location.href}},computed:{type:function(){return this.$videoConfig.isLive?"live":"vod"}}}),uid;function genTraversalHandler$2(e){return function t(r,i,n){if(isArray(r)||isObject(r)){for(var o in i=isPrimitive(i)?isObject(r)?{}:[]:i,r)i[o]=t(r[o],i[o],o);return i}return e(r,i,n)}}var _deepAssign$2=genTraversalHandler$2(function(e){return e});function deepClone$2(e){if(isPrimitive(e))throw new TypeError("deepClone only accept non primitive type");return _deepAssign$2(e)}function deepAssign$2(){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(isPrimitive(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return _deepAssign$2(e,n)}),n}function camelize$2(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 hypenate$2(e){return camelize$2(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}function bind$3(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(_toConsumableArray(i)))}}function uuid$2(){return S4$2()+S4$2()+"-"+S4$2()+"-"+S4$2()+"-"+S4$2()+"-"+S4$2()+S4$2()+S4$2()}function S4$2(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function rand$2(e){for(var t="";t.length<e;)t+=S4$2();return t.slice(0,e)}function getDeepProperty$2(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(isString(t)&&(t=t.split(".")),!isArray(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(isVoid(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s}var inBrowser$1="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window);function makeArray$1(e){return _Array$from(e)}function transObjectAttrIntoArray$1(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return _Object$keys(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])}function runRejectableQueue$1(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 _Promise(function(t,i){!function n(o){if(!(o>=e.length)){var a=isFunction(e[o])?e[o].apply(e,_toConsumableArray(r)):e[o];return!1===a?i("stop"):_Promise.resolve(a).then(function(){return n(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})}function runStoppableQueue$1(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!==(isFunction(e[i])?e[i].apply(e,_toConsumableArray(r)):e[i])&&t(++i)}(0)}function setFrozenAttr(e,t,r){if(isPrimitive(e))throw TypeError("setFrozenAttr obj parameter can not be primitive type");if(!isString(t))throw TypeError("setFrozenAttr key parameter must be String");_Object$defineProperty(e,t,{value:r,configurable:!1,enumerable:!1,writable:!1})}function setAttrGetterAndSetter(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.get,n=r.set,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"__";if(isPrimitive(e))throw TypeError("setFrozenAttr obj parameter can not be primitive type");if(!isString(t))throw TypeError("setAttrGetterAndSetter key parameter must be String");var a=e[t];if(!isFunction(i)&&(_Object$defineProperty(e,o+t,{value:a,configurable:!0,writable:!0,enumerable:!1}),i=function(){return this[o+t]},n&&isFunction(n))){var s=n;n=function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];this[o+t]=s.call.apply(s,[this].concat(r))}}_Object$defineProperty(e,t,{get:i,set:n})}function checkContinuation$1(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 decodeUTF8$1(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(checkContinuation$1(r,i,1)){var o=(31&r[i])<<6|63&r[i+1];if(o>=128){t.push(String.fromCharCode(65535&o)),i+=2;continue}}}else if(r[i]<240){if(checkContinuation$1(r,i,2)){var a=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(a>=2048&&55296!=(63488&a)){t.push(String.fromCharCode(65535&a)),i+=3;continue}}}else if(r[i]<248&&checkContinuation$1(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 debounce$1(e,t,r){var i=void 0,n=void 0,o=void 0,a=void 0,s=void 0,u=function u(){var c=new Date-a;c<t&&c>=0?i=setTimeout(u,t-c):(i=null,r||(s=e.apply(o,n),i||(o=n=null)))};return function(){o=this,n=arguments,a=new Date;var c=r&&!i;return i||(i=setTimeout(u,t)),c&&(s=e.apply(o,n),o=n=null),s}}function throttle$1(e,t,r,i){var n=void 0,o=void 0,a=void 0,s=null,u=0;r||(r={});var c=function(){u=!1===r.leading?0:new Date-0,s=null,a=e.apply(n,o),s||(n=o=null)};return t=t||0,function(){var l=new Date;u||!1!==r.leading||(u=l);var d=t-(l-u);return n=i||this,o=arguments,d<=0||d>t?(s&&(clearTimeout(s),s=null),u=l,a=e.apply(n,o),s||(n=o=null)):s||!1===r.trailing||(s=setTimeout(c,d)),a}}var raf$1=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(e){return setTimeout(e,17)},caf$1=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.oCancelAnimationFrame||function(e){clearTimeout(e)};function strRepeat$1(e,t){var r=t,i=(e=""+(e||"")).length;return(((t=(t||i)-i)>0?e.repeat?"0".repeat(t):new Array(t+1).join("0"):"")+e).slice(0,r)}function formatTime$1(e){var t=Math.floor(e/3600);e=Math.floor(e%3600);var r=strRepeat$1(Math.floor(e/60),2),i=strRepeat$1(e=Math.floor(e%60),2);return t>=1?t+":"+r+":"+i:r+":"+i}function addTransMethod(e){setFrozenAttr(e,"trans",function(t){return e.__fns||setFrozenAttr(e,"__fns",{}),e.__fns[t]||(e.__fns[t]=function(){if(!isFunction(e[t]))throw TypeError("obj.trans(methodName) parameter must be Function");return e[t].apply(e,arguments)}),e.__fns[t]})}function appendCSS$1(e){var t=document,r=t.querySelector("style");if(!r){r=t.createElement("style");var i=t.querySelector("head");i&&i.appendChild(r)}return r.appendChild(t.createTextNode(e)),r}function formatDate$1(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"yyyy-MM-dd hh:mm:ss.i",r=e.getFullYear().toString(),i={M:e.getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),i:e.getMilliseconds()};t=t.replace(/(y+)/gi,function(e,t){return r.substr(4-Math.min(4,t.length))});var n=function(e){t=t.replace(new RegExp("("+e+"+)","g"),function(t,r){return(i[e]<10&&r.length>1?"0":"")+i[e]})};for(var o in i)n(o);return t}function getLocalStorage$1(e){try{return window.localStorage.getItem(e)}catch(r){try{var t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]*)(;|$)"));return isArray(t)?unescape(t[2]):""}catch(e){return""}}}function setLocalStorage$1(e,t){try{window.localStorage.setItem(e,t)}catch(i){var r=new Date;r.setTime(r.getTime()+2592e7);try{document.cookie=e+"="+escape(t)+";expires="+r.toUTCString()+";path=/;"}catch(e){}}}var lib=Object.freeze({Log:Log$1,genTraversalHandler:genTraversalHandler$2,deepClone:deepClone$2,deepAssign:deepAssign$2,camelize:camelize$2,hypenate:hypenate$2,bind:bind$3,uuid:uuid$2,S4:S4$2,rand:rand$2,getDeepProperty:getDeepProperty$2,defined:defined,isVoid:isVoid,isArray:isArray,isFunction:isFunction,isObject:isObject,isNumber:isNumber,isNumeric:isNumeric,isInteger:isInteger$2,isEmpty:isEmpty,isEvent:isEvent,isBlob:isBlob,isFile:isFile,isDate:isDate,isString:isString,isBoolean:isBoolean,isPromise:isPromise,isPrimitive:isPrimitive,isUrl:isUrl,isNode:isNode$2,isElement:isElement,isChildNode:isChildNode,isPosterityNode:isPosterityNode,isHTMLString:isHTMLString,isError:isError,isRegExp:isRegExp,inBrowser:inBrowser$1,makeArray:makeArray$1,transObjectAttrIntoArray:transObjectAttrIntoArray$1,runRejectableQueue:runRejectableQueue$1,runStoppableQueue:runStoppableQueue$1,setFrozenAttr:setFrozenAttr,setAttrGetterAndSetter:setAttrGetterAndSetter,decodeUTF8:decodeUTF8$1,debounce:debounce$1,throttle:throttle$1,raf:raf$1,caf:caf$1,strRepeat:strRepeat$1,formatTime:formatTime$1,addTransMethod:addTransMethod,appendCSS:appendCSS$1,formatDate:formatDate$1,getLocalStorage:getLocalStorage$1,setLocalStorage:setLocalStorage$1,emitEventCache:emitEventCache,addEventCache:addEventCache,removeEventCache:removeEventCache,CustEvent:CustEvent,getAttr:getAttr,setAttr:setAttr,addClassName:addClassName,removeClassName:removeClassName,hasClassName:hasClassName,get supportsPassive(){return supportsPassive},removeEvent:removeEvent,addEvent:addEvent,addDelegate:addDelegate,removeDelegate:removeDelegate,getStyle:getStyle,setStyle:setStyle,query:query,removeEl:removeEl,findParents:findParents,NodeWrap:NodeWrap,$:$}),chimeeHelper=lib;function __$styleInject$6(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),r.appendChild(i),t}function _interopDefault$1(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var _slicedToArray$1=_interopDefault$1(slicedToArray);function popupFactory$3(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,$=e.computed,k=e.methods,D=void 0===k?{}:k,I=e.penetrate,x=void 0!==I&&I,C=e.operable,M=void 0===C||C,P=e.hide,L=void 0!==P&&P,R=e.opened,N=e.closed,j=e.autoFocus,F={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];chimeeHelper.isObject(i)&&(chimeeHelper.isObject(i.events)&&chimeeHelper.deepAssign(t,i.events),chimeeHelper.isObject(i.methods)&&chimeeHelper.deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=chimeeHelper.isObject(this.$config)?chimeeHelper.deepAssign(F,this.$config):F;(this.$domWrap=chimeeHelper.$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=L;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:$,penetrate:x,operable:M,autoFocus:j,methods:chimeeHelper.deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),chimeeHelper.isFunction(R)&&R.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),chimeeHelper.isFunction(N)&&N.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&"auto"!==t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray$1(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray$1(t,2),i=r[0],n=r[1];return i&&this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),this}},D)}}__$styleInject$6("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;opacity:.8;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0);var lib$1=popupFactory$3;function __$styleInject$7(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}__$styleInject$7('chimee-center-state{position:absolute}@keyframes a{0%{opacity:1}to{transform:scale(2);opacity:0}}@keyframes b{0%{transform:rotate(0)}to{transform:rotate(1turn)}}chimee-center-state-correct,chimee-center-state-error,chimee-center-state-loading,chimee-center-state-tip{display:none}chimee-center-state.correct chimee-center-state-correct,chimee-center-state.error chimee-center-state-error,chimee-center-state.loading chimee-center-state-loading,chimee-center-state.tip chimee-center-state-tip{display:inline-block}chimee-center-state-correct{width:104px;height:104px}chimee-center-state-tip{position:absolute;left:26px;bottom:26px;width:52px;height:52px;border-radius:26px;background:rgba(0,0,0,.5);animation:a .5s linear 1 normal forwards}chimee-center-state.play span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjQycHgiIGhlaWdodD0iNTFweCIgdmlld0JveD0iMCAwIDQyIDUxIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0My4xICgzOTAxMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxwb2x5Z29uIGlkPSJUcmlhbmdsZSIgZmlsbD0iI0ZGRkZGRiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjEuMDAwMDAwLCAyNS41MDAwMDApIHJvdGF0ZSg5MC4wMDAwMDApIHRyYW5zbGF0ZSgtMjEuMDAwMDAwLCAtMjUuNTAwMDAwKSAiIHBvaW50cz0iMjEgNSA0NiA0NiAtNCA0NiI+PC9wb2x5Z29uPgogICAgPC9nPgo8L3N2Zz4=")}chimee-center-state.pause span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjUwcHgiIGhlaWdodD0iNTBweCIgdmlld0JveD0iMCAwIDUwIDUwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0My4xICgzOTAxMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjAiIHdpZHRoPSIyMCIgaGVpZ2h0PSI1MCI+PC9yZWN0PgogICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUiIGZpbGw9IiNGRkZGRkYiIHg9IjMwIiB5PSIwIiB3aWR0aD0iMjAiIGhlaWdodD0iNTAiPjwvcmVjdD4KICAgIDwvZz4KPC9zdmc+")}chimee-center-state.back span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjczMXB4IiBoZWlnaHQ9Ijg4NHB4IiB2aWV3Qm94PSIwIDAgNzMxIDg4NCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iNzcxLeWNlee6v++8jOWIt+aWsCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzY1LjUwMDAwMCwgNDQyLjAwMDAwMCkgc2NhbGUoLTEsIDEpIHRyYW5zbGF0ZSgtMzY1LjUwMDAwMCwgLTQ0Mi4wMDAwMDApICIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjZmZmZmZmIj4KICAgICAgICAgICAgPHBhdGggZD0iTTcwNS4xMTg1NTgsNDkyLjQxNDIwMyBDNjkwLjk4OTc2OSw0OTIuNDE0MjAzIDY3OS41MzU5MDMsNTAzLjg2ODA2OSA2NzkuNTM1OTAzLDUxNy45OTY4NTggQzY3OS41MzU5MDMsNjkxLjA2MDQ0OSA1MzguNzM3MTU3LDgzMS44NTkxOTUgMzY1LjY3MzU2Niw4MzEuODU5MTk1IEMxOTIuNjA4OTUyLDgzMS44NTkxOTUgNTEuODEyMjUyLDY5MS4wNjA0NDkgNTEuODEyMjUyLDUxNy45OTY4NTggQzUxLjgxMjI1MiwzNTUuMDM4NDE2IDE3Ni42NTI1MzgsMjIwLjcwNjk2NSAzMzUuNzE0MjMsMjA1LjU3MzI4OSBMMjIzLjYwMDgwMywzMTcuNjg2NzE2IEMyMTMuNjEwMjY1LDMyNy42NzcyNTQgMjEzLjYxMDI2NSwzNDMuODc1MTY4IDIyMy42MDA4MDMsMzUzLjg2NTcwNyBDMjI4LjU5NjU4NCwzNTguODYwNDY1IDIzNS4xNDM2OTcsMzYxLjM1ODM1NSAyNDEuNjkwODEsMzYxLjM1ODM1NSBDMjQ4LjIzNzkyMywzNjEuMzU4MzU1IDI1NC43ODUwMzYsMzU4Ljg2MDQ2NSAyNTkuNzgwODE3LDM1My44NjU3MDcgTDQxNC43MzcwMDUsMTk4LjkwOTUxOSBDNDI0LjcyNzU0MywxODguOTE4OTgxIDQyNC43Mjc1NDMsMTcyLjcyMTA2NyA0MTQuNzM3MDA1LDE2Mi43MzA1MjggTDI1OS43Nzk3OTMsNy43NzQzNDEgQzI0OS43ODgyMzEsLTIuMjE2MTk3IDIzMy41OTEzNDEsLTIuMjE2MTk3IDIyMy42MDA4MDIsNy43NzQzNDEgQzIxMy42MTAyNjQsMTcuNzY0ODc5IDIxMy42MTAyNjQsMzMuOTYyNzkzIDIyMy42MDA4MDIsNDMuOTUzMzMyIEwzMzMuOTkwOTgxLDE1NC4zNDM1MTEgQzI5NS45MDE0NzgsMTU3LjYwMjc0MSAyNTguODgyMzUzLDE2Ni43MzM3MDIgMjIzLjU4MTM1OSwxODEuNjY0NzYzIEMxODAuMTExMzEyLDIwMC4wNTE1MjkgMTQxLjA3NjI3MywyMjYuMzY3ODk0IDEwNy41NjA5NDksMjU5Ljg4MzIxOSBDNzQuMDQ1NjI1LDI5My4zOTg1NDQgNDcuNzI5MjU5LDMzMi40MzI1NTkgMjkuMzQyNDkzLDM3NS45MDM2MjkgQzEwLjMwMTgzNSw0MjAuOTIxOTM5IDAuNjQ2OTQxLDQ2OC43Mjk3ODEgMC42NDY5NDEsNTE3Ljk5NTgzNCBDMC42NDY5NDEsNTY3LjI2MzkzNCAxMC4zMDE4MzUsNjE1LjA2OTczIDI5LjM0MjQ5Myw2NjAuMDg5MDYzIEM0Ny43MjkyNTksNzAzLjU1ODA4NyA3NC4wNDU2MjQsNzQyLjU5NDE0OSAxMDcuNTYwOTQ5LDc3Ni4xMDk0NzMgQzE0MS4wNzYyNzQsODA5LjYyNDc5NyAxODAuMTEwMjg5LDgzNS45NDExNjMgMjIzLjU4MTM1OSw4NTQuMzI2OTA2IEMyNjguNTk5NjY5LDg3My4zNjg1ODggMzE2LjQwNjQ4OCw4ODMuMDIzNDgyIDM2NS42NzM1NjQsODgzLjAyMzQ4MiBDNDE0Ljk0MTY2NCw4ODMuMDIzNDgyIDQ2Mi43NDc0Niw4NzMuMzY4NTg4IDUwNy43NjY3OTMsODU0LjMyNjkwNiBDNTUxLjIzNTgxNyw4MzUuOTQxMTY0IDU5MC4yNzE4NzksODA5LjYyNDc5OCA2MjMuNzg3MjAzLDc3Ni4xMDk0NzMgQzY1Ny4zMDI1MjcsNzQyLjU5NDE0OCA2ODMuNjE4ODkzLDcwMy41NTkxMSA3MDIuMDA0NjM2LDY2MC4wODkwNjMgQzcyMS4wNDYzMTgsNjE1LjA2OTczIDczMC43MDEyMTIsNTY3LjI2MjkxMSA3MzAuNzAxMjEyLDUxNy45OTU4MzQgQzczMC43MDEyMTMsNTAzLjg2ODA2OSA3MTkuMjQ4MzcsNDkyLjQxNDIwMyA3MDUuMTE4NTU4LDQ5Mi40MTQyMDMgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgPC9nPgogICAgICAgIDx0ZXh0IGlkPSIxMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgZm9udC1zaXplPSIyODgiIGZvbnQtd2VpZ2h0PSJub3JtYWwiIGZpbGw9IiNmZmZmZmYiPgogICAgICAgICAgICA8dHNwYW4geD0iMjExIiB5PSI2MzQiPjEwPC90c3Bhbj4KICAgICAgICA8L3RleHQ+CiAgICA8L2c+Cjwvc3ZnPg==")}chimee-center-state.forward span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjczMXB4IiBoZWlnaHQ9Ijg4NHB4IiB2aWV3Qm94PSIwIDAgNzMxIDg4NCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iNzcxLeWNlee6v++8jOWIt+aWsCIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjZmZmZmZmIj4KICAgICAgICAgICAgPHBhdGggZD0iTTcwNS4xMTg1NTgsNDkyLjQxNDIwMyBDNjkwLjk4OTc2OSw0OTIuNDE0MjAzIDY3OS41MzU5MDMsNTAzLjg2ODA2OSA2NzkuNTM1OTAzLDUxNy45OTY4NTggQzY3OS41MzU5MDMsNjkxLjA2MDQ0OSA1MzguNzM3MTU3LDgzMS44NTkxOTUgMzY1LjY3MzU2Niw4MzEuODU5MTk1IEMxOTIuNjA4OTUyLDgzMS44NTkxOTUgNTEuODEyMjUyLDY5MS4wNjA0NDkgNTEuODEyMjUyLDUxNy45OTY4NTggQzUxLjgxMjI1MiwzNTUuMDM4NDE2IDE3Ni42NTI1MzgsMjIwLjcwNjk2NSAzMzUuNzE0MjMsMjA1LjU3MzI4OSBMMjIzLjYwMDgwMywzMTcuNjg2NzE2IEMyMTMuNjEwMjY1LDMyNy42NzcyNTQgMjEzLjYxMDI2NSwzNDMuODc1MTY4IDIyMy42MDA4MDMsMzUzLjg2NTcwNyBDMjI4LjU5NjU4NCwzNTguODYwNDY1IDIzNS4xNDM2OTcsMzYxLjM1ODM1NSAyNDEuNjkwODEsMzYxLjM1ODM1NSBDMjQ4LjIzNzkyMywzNjEuMzU4MzU1IDI1NC43ODUwMzYsMzU4Ljg2MDQ2NSAyNTkuNzgwODE3LDM1My44NjU3MDcgTDQxNC43MzcwMDUsMTk4LjkwOTUxOSBDNDI0LjcyNzU0MywxODguOTE4OTgxIDQyNC43Mjc1NDMsMTcyLjcyMTA2NyA0MTQuNzM3MDA1LDE2Mi43MzA1MjggTDI1OS43Nzk3OTMsNy43NzQzNDEgQzI0OS43ODgyMzEsLTIuMjE2MTk3IDIzMy41OTEzNDEsLTIuMjE2MTk3IDIyMy42MDA4MDIsNy43NzQzNDEgQzIxMy42MTAyNjQsMTcuNzY0ODc5IDIxMy42MTAyNjQsMzMuOTYyNzkzIDIyMy42MDA4MDIsNDMuOTUzMzMyIEwzMzMuOTkwOTgxLDE1NC4zNDM1MTEgQzI5NS45MDE0NzgsMTU3LjYwMjc0MSAyNTguODgyMzUzLDE2Ni43MzM3MDIgMjIzLjU4MTM1OSwxODEuNjY0NzYzIEMxODAuMTExMzEyLDIwMC4wNTE1MjkgMTQxLjA3NjI3MywyMjYuMzY3ODk0IDEwNy41NjA5NDksMjU5Ljg4MzIxOSBDNzQuMDQ1NjI1LDI5My4zOTg1NDQgNDcuNzI5MjU5LDMzMi40MzI1NTkgMjkuMzQyNDkzLDM3NS45MDM2MjkgQzEwLjMwMTgzNSw0MjAuOTIxOTM5IDAuNjQ2OTQxLDQ2OC43Mjk3ODEgMC42NDY5NDEsNTE3Ljk5NTgzNCBDMC42NDY5NDEsNTY3LjI2MzkzNCAxMC4zMDE4MzUsNjE1LjA2OTczIDI5LjM0MjQ5Myw2NjAuMDg5MDYzIEM0Ny43MjkyNTksNzAzLjU1ODA4NyA3NC4wNDU2MjQsNzQyLjU5NDE0OSAxMDcuNTYwOTQ5LDc3Ni4xMDk0NzMgQzE0MS4wNzYyNzQsODA5LjYyNDc5NyAxODAuMTEwMjg5LDgzNS45NDExNjMgMjIzLjU4MTM1OSw4NTQuMzI2OTA2IEMyNjguNTk5NjY5LDg3My4zNjg1ODggMzE2LjQwNjQ4OCw4ODMuMDIzNDgyIDM2NS42NzM1NjQsODgzLjAyMzQ4MiBDNDE0Ljk0MTY2NCw4ODMuMDIzNDgyIDQ2Mi43NDc0Niw4NzMuMzY4NTg4IDUwNy43NjY3OTMsODU0LjMyNjkwNiBDNTUxLjIzNTgxNyw4MzUuOTQxMTY0IDU5MC4yNzE4NzksODA5LjYyNDc5OCA2MjMuNzg3MjAzLDc3Ni4xMDk0NzMgQzY1Ny4zMDI1MjcsNzQyLjU5NDE0OCA2ODMuNjE4ODkzLDcwMy41NTkxMSA3MDIuMDA0NjM2LDY2MC4wODkwNjMgQzcyMS4wNDYzMTgsNjE1LjA2OTczIDczMC43MDEyMTIsNTY3LjI2MjkxMSA3MzAuNzAxMjEyLDUxNy45OTU4MzQgQzczMC43MDEyMTMsNTAzLjg2ODA2OSA3MTkuMjQ4MzcsNDkyLjQxNDIwMyA3MDUuMTE4NTU4LDQ5Mi40MTQyMDMgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgPC9nPgogICAgICAgIDx0ZXh0IGlkPSIxMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgZm9udC1zaXplPSIyODgiIGZvbnQtd2VpZ2h0PSJub3JtYWwiIGZpbGw9IiNmZmZmZmYiPgogICAgICAgICAgICA8dHNwYW4geD0iMjExIiB5PSI2MzQiPjEwPC90c3Bhbj4KICAgICAgICA8L3RleHQ+CiAgICA8L2c+Cjwvc3ZnPg==")}chimee-center-state.volume-high span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEwN3B4IiBoZWlnaHQ9IjEwMXB4IiB2aWV3Qm94PSIwIDAgMTA3IDEwMSIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEuMDAwMDAwLCAwLjAwMDAwMCkiIHN0cm9rZT0iI0ZGRkZGRiI+CiAgICAgICAgPHBvbHlnb24gaWQ9IlBhdGgiIGZpbGw9IiNmZmZmZmYiIHBvaW50cz0iMC40MDczMTY0NDYgMzAgMjcuNjUwMDc3OSAzMCA1Ny4zNzM3MjkzIDIuODQyMTcwOTRlLTE0IDU4LjQ3NjI1MzIgMTAwIDI3LjY1MDA3NzkgNzAgMC40MDczMTY0NDYgNzAiPjwvcG9seWdvbj4KICAgICAgICA8cGF0aCBkPSJNNjMuNjExNjUwNSw1LjAwOTc1MjM5IEM2OS43MDc5Mjc1LDQuNzg2MTIwNTcgNzYuNjU0OTI1MSw4LjQwODU2MTQ2IDg0LjQ1MjY0MzEsMTUuODc3MDc1IEM5Ni4xNDkyMjAxLDI3LjA3OTg0NTQgMTAwLjk3MDg3NCwzNC43OTc1MTI1IDEwMC45NzA4NzQsNTAuOTYwODU1OCBDMTAwLjk3MDg3NCw2Ny4xMjQxOTkxIDk2LjI4ODcyMjUsNzMuNzkwNzQ4MiA4NC40NTI2NDMxLDgzLjgzMDY3MjQgQzc2LjU2MTkyMzQsOTAuNTIzOTU1MiA2OS42MTQ5MjU5LDk0LjAzMjA2NDQgNjMuNjExNjUwNSw5NC4zNTUiIGlkPSLlpJbnjq8iIHN0cm9rZS13aWR0aD0iMTAiPjwvcGF0aD4KICAgICAgICA8cGF0aCBkPSJNNjUuODUwNTY5OSwyOS40OTI5MTk1IEM2OC41MzY5NDM0LDI5LjM5MzExNjkgNzEuNTk4MTkzOCwzMS4wMDk3NDE2IDc1LjAzNDMyMSwzNC4zNDI3OTM0IEM4MC4xODg1MTE4LDM5LjM0MjM3MTIgODIuMzEzMjEyMyw0Mi43ODY2MTU0IDgyLjMxMzIxMjMsNTAgQzgyLjMxMzIxMjMsNTcuMjEzMzg0NiA4MC4yNDk5ODQ3LDYwLjE4ODUzNTQgNzUuMDM0MzIxLDY0LjY2OTE1NzYgQzcxLjU1NzIxMTksNjcuNjU2MjM5IDY4LjQ5NTk2MTUsNjkuMjIxODM5NyA2NS44NTA1Njk5LDY5LjM2NTk1OTUiIGlkPSLlhoXnjq8iIHN0cm9rZS13aWR0aD0iMTAiPjwvcGF0aD4KICAgIDwvZz4KPC9zdmc+")}chimee-center-state.volume-low span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9Ijg5cHgiIGhlaWdodD0iMTAxcHgiIHZpZXdCb3g9IjAgMCA4OSAxMDEiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDQ0LjEgKDQxNDU1KSAtIGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCAtLT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9Ikdyb3VwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxLjAwMDAwMCwgMC4wMDAwMDApIiBzdHJva2U9IiNGRkZGRkYiPgogICAgICAgIDxwb2x5Z29uIGlkPSJQYXRoIiBmaWxsPSIjZmZmZmZmIiBwb2ludHM9IjAuNDA3MzE2NDQ2IDMwIDI3LjY1MDA3NzkgMzAgNTcuMzczNzI5MyAyLjg0MjE3MDk0ZS0xNCA1OC40NzYyNTMyIDEwMCAyNy42NTAwNzc5IDcwIDAuNDA3MzE2NDQ2IDcwIj48L3BvbHlnb24+CiAgICAgICAgPHBhdGggZD0iTTY1Ljg1MDU2OTksMjkuNDkyOTE5NSBDNjguNTM2OTQzNCwyOS4zOTMxMTY5IDcxLjU5ODE5MzgsMzEuMDA5NzQxNiA3NS4wMzQzMjEsMzQuMzQyNzkzNCBDODAuMTg4NTExOCwzOS4zNDIzNzEyIDgyLjMxMzIxMjMsNDIuNzg2NjE1NCA4Mi4zMTMyMTIzLDUwIEM4Mi4zMTMyMTIzLDU3LjIxMzM4NDYgODAuMjQ5OTg0Nyw2MC4xODg1MzU0IDc1LjAzNDMyMSw2NC42NjkxNTc2IEM3MS41NTcyMTE5LDY3LjY1NjIzOSA2OC40OTU5NjE1LDY5LjIyMTgzOTcgNjUuODUwNTY5OSw2OS4zNjU5NTk1IiBpZD0i5YaF546vIiBzdHJva2Utd2lkdGg9IjEwIj48L3BhdGg+CiAgICA8L2c+Cjwvc3ZnPg==")}chimee-center-state-tip span{display:inline-block;width:24px;height:24px;margin:14px;background-origin:content-box;background-size:auto 100%;background-repeat:no-repeat;background-position:50%;box-sizing:initial}chimee-center-state.play span{background-position:110% 50%}chimee-center-state-loading{width:52px;height:52px;padding:26px;background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjgwcHgiIGhlaWdodD0iODBweCIgdmlld0JveD0iMCAwIDgwIDgwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0Ny4xICg0NTQyMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJsb2FkaW5nIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTAuMDAwMDAwLCAtMTAuMDAwMDAwKSIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjRkZGRkZGIj4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjEiIHg9IjQ3IiB5PSIxMCIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDY1LjAwMDAwMCwgMjQuMDE5MjM4KSByb3RhdGUoMzAuMDAwMDAwKSB0cmFuc2xhdGUoLTY1LjAwMDAwMCwgLTI0LjAxOTIzOCkgIiB4PSI2MiIgeT0iMTQuMDE5MjM3OSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjgiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDc1Ljk4MDc2MiwgMzUuMDAwMDAwKSByb3RhdGUoNjAuMDAwMDAwKSB0cmFuc2xhdGUoLTc1Ljk4MDc2MiwgLTM1LjAwMDAwMCkgIiB4PSI3Mi45ODA3NjIxIiB5PSIyNSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjciIHRyYW5zZm9ybT0idHJhbnNsYXRlKDgwLjAwMDAwMCwgNTAuMDAwMDAwKSByb3RhdGUoOTAuMDAwMDAwKSB0cmFuc2xhdGUoLTgwLjAwMDAwMCwgLTUwLjAwMDAwMCkgIiB4PSI3NyIgeT0iNDAiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGwtb3BhY2l0eT0iMC42IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg3NS45ODA3NjIsIDY1LjAwMDAwMCkgcm90YXRlKDEyMC4wMDAwMDApIHRyYW5zbGF0ZSgtNzUuOTgwNzYyLCAtNjUuMDAwMDAwKSAiIHg9IjcyLjk4MDc2MjEiIHk9IjU1IiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuNSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNjUuMDAwMDAwLCA3NS45ODA3NjIpIHJvdGF0ZSgxNTAuMDAwMDAwKSB0cmFuc2xhdGUoLTY1LjAwMDAwMCwgLTc1Ljk4MDc2MikgIiB4PSI2MiIgeT0iNjUuOTgwNzYyMSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDUwLjAwMDAwMCwgODAuMDAwMDAwKSByb3RhdGUoMTgwLjAwMDAwMCkgdHJhbnNsYXRlKC01MC4wMDAwMDAsIC04MC4wMDAwMDApICIgeD0iNDciIHk9IjcwIiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuMyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzUuMDAwMDAwLCA3NS45ODA3NjIpIHJvdGF0ZSgtMTUwLjAwMDAwMCkgdHJhbnNsYXRlKC0zNS4wMDAwMDAsIC03NS45ODA3NjIpICIgeD0iMzIiIHk9IjY1Ljk4MDc2MjEiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGwtb3BhY2l0eT0iMC4yIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNC4wMTkyMzgsIDY1LjAwMDAwMCkgcm90YXRlKC0xMjAuMDAwMDAwKSB0cmFuc2xhdGUoLTI0LjAxOTIzOCwgLTY1LjAwMDAwMCkgIiB4PSIyMS4wMTkyMzc5IiB5PSI1NSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjMiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDIwLjAwMDAwMCwgNTAuMDAwMDAwKSByb3RhdGUoLTkwLjAwMDAwMCkgdHJhbnNsYXRlKC0yMC4wMDAwMDAsIC01MC4wMDAwMDApICIgeD0iMTciIHk9IjQwIiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuNCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjQuMDE5MjM4LCAzNS4wMDAwMDApIHJvdGF0ZSgtNjAuMDAwMDAwKSB0cmFuc2xhdGUoLTI0LjAxOTIzOCwgLTM1LjAwMDAwMCkgIiB4PSIyMS4wMTkyMzc5IiB5PSIyNSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDM1LjAwMDAwMCwgMjQuMDE5MjM4KSByb3RhdGUoLTMwLjAwMDAwMCkgdHJhbnNsYXRlKC0zNS4wMDAwMDAsIC0yNC4wMTkyMzgpICIgeD0iMzIiIHk9IjE0LjAxOTIzNzkiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+");background-origin:content-box;background-size:auto 100%;background-repeat:no-repeat;background-position:50%;animation:b 1.2s linear infinite}chimee-center-state-error{display:none;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:180px;font-size:16px;z-index:1;color:#ffcf00;text-shadow:0 0 3px red;font-weight:100;text-align:center}',void 0);var clss="correct tip play pause back forward volume-high volume-low",defaultConfig$2={errorTips:"加载失败,请刷新重试"},chimeeCenterState=lib$1({name:"chimeeCenterState",tagName:"chimee-center-state",html:"\n <chimee-center-state-correct>\n <chimee-center-state-loading></chimee-center-state-loading>\n <chimee-center-state-tip>\n <span></span>\n </chimee-center-state-tip>\n </chimee-center-state-correct>\n <chimee-center-state-error></chimee-center-state-error>\n ",offset:"50%",hide:!1,create:function(){},inited:function(){this.config=isObject(this.$config)?deepAssign$2(defaultConfig$2,this.$config):defaultConfig$2,this.$dom.querySelector("chimee-center-state-error").innerText=this.config.errorTips,this.src&&this.showLoading(!0)},penetrate:!0,operable:!1,destroy:function(){this.clearTimeout()},events:{pause:function(){this.showTip("pause"),this.showLoading(!1)},play:function(){this.showTip("play")},canplay:function(){this.playing()},playing:function(){this.playing()},loadstart:function(){this.waiting("loadstart")},waiting:function(){this.waiting()},timeupdate:function(){this.showLoading(!1),this.clearTimeout()},keydown:function(e){if(this.$videoConfig.plugin.some(function(e){return"chimeeControl"===(e.name||e)}))switch(e.stopPropagation(),e.keyCode){case 37:e.preventDefault(),!this.live&&this.showTip("back");break;case 39:e.preventDefault(),!this.live&&this.showTip("forward");break;case 38:e.preventDefault(),this.showTip("volume-high");break;case 40:e.preventDefault(),this.showTip("volume-low")}}},methods:{playing:function(){this.clearTimeout(),this.showLoading(!1),this.showError(!1)},waiting:function(e){var t=this;this.clearTimeout(),this._timeout=setTimeout(function(){return t.showError()},3e4),("loadstart"===e||!this.paused)&&this.showLoading(!0)},clearTimeout:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}),showTip:function(e){var t=this;this.$domWrap.removeClass(clss).addClass("correct tip "+e),setTimeout(function(){t.$domWrap.removeClass("tip "+e)},500)},showLoading:function(e){!1===e?this.$domWrap.removeClass("loading"):this.$domWrap.addClass("correct loading")},showError:function(e){!1===e?this.$domWrap.removeClass("error"):(this.$domWrap[0].className="",this.$domWrap.addClass("error"))}}}),hls=createCommonjsModule(function(e,t){var r;r=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/dist/",r(r.s=8)}([function(e,t,r){r.d(t,"a",function(){return u}),r.d(t,"b",function(){return c});var i="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};function n(){}var o={trace:n,debug:n,log:n,warn:n,info:n,error:n},a=o;function s(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){a[t]=e[t]?e[t].bind(e):function(e){var t=self.console[e];return t?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];i[0]&&(i[0]=function(e,t){return t="["+e+"] > "+t}(e,i[0])),t.apply(self.console,i)}:n}(t)})}var u=function(e){if(!0===e||"object"===(void 0===e?"undefined":i(e))){s(e,"debug","log","info","warn","error");try{a.log()}catch(e){a=o}}else a=o},c=o},function(e,t,r){t.a={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"}},function(e,t,r){r.d(t,"b",function(){return i}),r.d(t,"a",function(){return n});var i={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},n={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"}},function(e,t,r){r.d(t,"b",function(){return n});var i=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.isHeader=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},e.isFooter=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},e.getID3Data=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)},e._readSize=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]},e.getTimeStamp=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)}},e.isTimeStampFrame=function(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info},e._getFrameData=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)}},e.getID3Frames=function(t){for(var r=0,i=[];e.isHeader(t,r);){for(var n=e._readSize(t,r+6),o=(r+=10)+n;r+8<o;){var a=e._getFrameData(t.subarray(r)),s=e._decodeFrame(a);s&&i.push(s),r+=a.size+10}e.isFooter(t,r)&&(r+=10)}return i},e._decodeFrame=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},e._readTimeStamp=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)}},e._decodePrivFrame=function(t){if(!(t.size<2)){var r=e._utf8ArrayToStr(t.data,!0),i=new Uint8Array(t.data.subarray(r.length+1));return{key:t.type,info:r,data:i.buffer}}},e._decodeTextFrame=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 o=e._utf8ArrayToStr(t.data.subarray(1));return{key:t.type,data:o}}},e._decodeURLFrame=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 o=e._utf8ArrayToStr(t.data);return{key:t.type,data:o}},e._utf8ArrayToStr=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.length,i=void 0,n=void 0,o=void 0,a="",s=0;s<r;){if(0===(i=e[s++])&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=e[s++],a+=String.fromCharCode((31&i)<<6|63&n);break;case 14:n=e[s++],o=e[s++],a+=String.fromCharCode((15&i)<<12|(63&n)<<6|(63&o)<<0)}}return a},e}(),n=i._utf8ArrayToStr;t.a=i},function(e,t,r){var i=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.subtle=t,this.aesIV=r}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}();var n=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.subtle=t,this.key=r}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}();var o=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(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 e.prototype.uint8ArrayToUint32Array_=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},e.prototype.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],o=r[2],a=r[3],s=this.invSubMix,u=s[0],c=s[1],l=s[2],d=s[3],f=new Uint32Array(256),h=0,p=0,m=0;for(m=0;m<256;m++)f[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){var v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^255&v^99,e[h]=v,t[v]=h;var g=f[h],y=f[g],_=f[y],b=257*f[v]^16843008*v;i[h]=b<<24|b>>>8,n[h]=b<<16|b>>>16,o[h]=b<<8|b>>>24,a[h]=b,b=16843009*_^65537*y^257*g^16843008*h,u[v]=b<<24|b>>>8,c[v]=b<<16|b>>>16,l[v]=b<<8|b>>>24,d[v]=b,h?(h=g^f[f[f[_^g]]],p^=f[f[p]]):h=p=1}},e.prototype.expandKey=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 o=this.ksRows=4*(n+6+1),a=void 0,s=void 0,u=this.keySchedule=new Uint32Array(o),c=this.invKeySchedule=new Uint32Array(o),l=this.sBox,d=this.rcon,f=this.invSubMix,h=f[0],p=f[1],m=f[2],v=f[3],g=void 0,y=void 0;for(a=0;a<o;a++)a<n?g=u[a]=t[a]:(y=g,a%n==0?(y=l[(y=y<<8|y>>>24)>>>24]<<24|l[y>>>16&255]<<16|l[y>>>8&255]<<8|l[255&y],y^=d[a/n|0]<<24):n>6&&a%n==4&&(y=l[y>>>24]<<24|l[y>>>16&255]<<16|l[y>>>8&255]<<8|l[255&y]),u[a]=g=(u[a-n]^y)>>>0);for(s=0;s<o;s++)a=o-s,y=3&s?u[a]:u[a-4],c[s]=s<4||a<=4?y:h[l[y>>>24]]^p[l[y>>>16&255]]^m[l[y>>>8&255]]^v[l[255&y]],c[s]=c[s]>>>0}},e.prototype.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},e.prototype.decrypt=function(e,t,r){for(var i,n,o=this.keySize+6,a=this.invKeySchedule,s=this.invSBox,u=this.invSubMix,c=u[0],l=u[1],d=u[2],f=u[3],h=this.uint8ArrayToUint32Array_(r),p=h[0],m=h[1],v=h[2],g=h[3],y=new Int32Array(e),_=new Int32Array(y.length),b=void 0,w=void 0,E=void 0,S=void 0,T=void 0,O=void 0,A=void 0,$=void 0,k=void 0,D=void 0,I=void 0,x=void 0,C=this.networkToHostOrderSwap;t<y.length;){for(k=C(y[t]),D=C(y[t+1]),I=C(y[t+2]),x=C(y[t+3]),T=k^a[0],O=x^a[1],A=I^a[2],$=D^a[3],i=4,n=1;n<o;n++)b=c[T>>>24]^l[O>>16&255]^d[A>>8&255]^f[255&$]^a[i],w=c[O>>>24]^l[A>>16&255]^d[$>>8&255]^f[255&T]^a[i+1],E=c[A>>>24]^l[$>>16&255]^d[T>>8&255]^f[255&O]^a[i+2],S=c[$>>>24]^l[T>>16&255]^d[O>>8&255]^f[255&A]^a[i+3],T=b,O=w,A=E,$=S,i+=4;b=s[T>>>24]<<24^s[O>>16&255]<<16^s[A>>8&255]<<8^s[255&$]^a[i],w=s[O>>>24]<<24^s[A>>16&255]<<16^s[$>>8&255]<<8^s[255&T]^a[i+1],E=s[A>>>24]<<24^s[$>>16&255]<<16^s[T>>8&255]<<8^s[255&O]^a[i+2],S=s[$>>>24]<<24^s[T>>16&255]<<16^s[O>>8&255]<<8^s[255&A]^a[i+3],i+=3,_[t]=C(b^p),_[t+1]=C(S^m),_[t+2]=C(E^v),_[t+3]=C(w^g),p=k,m=D,v=I,g=x,t+=4}return _.buffer},e.prototype.destroy=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}(),a=r(2),s=r(0);var u=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(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 e.prototype.isSync=function(){return this.disableWebCrypto&&this.config.enableSoftwareAES},e.prototype.decrypt=function(e,t,r,a){var u=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(s.b.log("JS AES decrypt"),this.logEnabled=!1);var c=this.decryptor;c||(this.decryptor=c=new o),c.expandKey(t),a(c.decrypt(e,0,r))}else{this.logEnabled&&(s.b.log("WebCrypto AES decrypt"),this.logEnabled=!1);var l=this.subtle;this.key!==t&&(this.key=t,this.fastAesKey=new n(l,t)),this.fastAesKey.expandKey().then(function(n){new i(l,r).decrypt(e,n).catch(function(i){u.onWebCryptoError(i,e,t,r,a)}).then(function(e){a(e)})}).catch(function(i){u.onWebCryptoError(i,e,t,r,a)})}},e.prototype.onWebCryptoError=function(e,t,r,i,n){this.config.enableSoftwareAES?(s.b.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(t,r,i,n)):(s.b.error("decrypting error : "+e.message),this.observer.trigger(Event.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_DECRYPT_ERROR,fatal:!0,reason:e.message}))},e.prototype.destroy=function(){var e=this.decryptor;e&&(e.destroy(),this.decryptor=void 0)},e}();t.a=u},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function n(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,a,s,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||n(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(o(r=this._events[e]))return!1;if(i(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:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(n(r))for(s=Array.prototype.slice.call(arguments,1),a=(c=r.slice()).length,u=0;u<a;u++)c[u].apply(this,s);return!0},r.prototype.addListener=function(e,t){var a;if(!i(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,i(t.listener)?t.listener:t),this._events[e]?n(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,n(this._events[e])&&!this._events[e].warned&&(a=o(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&a>0&&this._events[e].length>a&&(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},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var r,o,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,o=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(n(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=s;break}if(o<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.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(i(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,r){var i,n,o,a,s;i=/^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,n=/^([^\/;?#]*)(.*)$/,o=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/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(!a)throw new Error("Error trying to parse base URL.");return i.path=s.normalizePath(i.path),s.buildURLFromParts(i)}var o=this.parseURL(t);if(!o)throw new Error("Error trying to parse relative URL.");if(o.scheme)return r.alwaysNormalize?(o.path=s.normalizePath(o.path),s.buildURLFromParts(o)):t;var a=this.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var u=n.exec(a.path);a.netLoc=u[1],a.path=u[2]}a.netLoc&&!a.path&&(a.path="/");var c={scheme:a.scheme,netLoc:o.netLoc,path:null,params:o.params,query:o.query,fragment:o.fragment};if(!o.netLoc&&(c.netLoc=a.netLoc,"/"!==o.path[0]))if(o.path){var l=a.path,d=l.substring(0,l.lastIndexOf("/")+1)+o.path;c.path=s.normalizePath(d)}else c.path=a.path,o.params||(c.params=a.params,o.query||(c.query=a.query));return null===c.path&&(c.path=r.alwaysNormalize?s.normalizePath(o.path):o.path),s.buildURLFromParts(c)},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(o,"");e.length!==(e=e.replace(a,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s},function(e,t,r){var i=r(1),n=r(2),o=r(4),a=r(0);function s(e,t){return 255===e[t]&&240==(246&e[t+1])}function u(e,t){return 1&e[t+1]?7:9}function c(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function l(e,t){return!!(t+1<e.length&&s(e,t))}function d(e,t){if(t+1<e.length&&s(e,t)){var r=u(e,t);t+5<e.length&&(r=c(e,t));var i=t+r;if(i===e.length||i+1<e.length&&s(e,i))return!0}return!1}function f(e,t,r,i,o){if(!e.samplerate){var s=function(e,t,r,i){var o,s,u,c,l,d=navigator.userAgent.toLowerCase(),f=i,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 c=(1&t[r+2])<<2,c|=(192&t[r+3])>>>6,a.b.log("manifest codec:"+i+",ADTS data:type:"+o+",sampleingIndex:"+s+"["+h[s]+"Hz],channelConfig:"+c),/firefox/i.test(d)?s>=6?(o=5,l=new Array(4),u=s-3):(o=2,l=new Array(2),u=s):-1!==d.indexOf("android")?(o=2,l=new Array(2),u=s):(o=5,l=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&s>=6?u=s-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(s>=6&&1===c||/vivaldi/i.test(d))||!i&&1===c)&&(o=2,l=new Array(2)),u=s)),l[0]=o<<3,l[0]|=(14&s)>>1,l[1]|=(1&s)<<7,l[1]|=c<<3,5===o&&(l[1]|=(14&u)>>1,l[2]=(1&u)<<7,l[2]|=8,l[3]=0),{config:l,samplerate:h[s],channelCount:c,codec:"mp4a.40."+o,manifestCodec:f};e.trigger(Event.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+s})}(t,r,i,o);e.config=s.config,e.samplerate=s.samplerate,e.channelCount=s.channelCount,e.codec=s.codec,e.manifestCodec=s.manifestCodec,a.b.log("parsed codec:"+e.codec+",rate:"+s.samplerate+",nb channel:"+s.channelCount)}}function h(e){return 9216e4/e}function p(e,t,r,i,n){var o=function(e,t,r,i,n){var o,a,s=e.length;if(o=u(e,t),a=c(e,t),(a-=o)>0&&t+o+a<=s)return{headerLength:o,frameLength:a,stamp:r+i*n}}(t,r,i,n,h(e.samplerate));if(o){var a=o.stamp,s=o.headerLength,l=o.frameLength,d={unit:t.subarray(r+s,r+s+l),pts:a,dts:a};return e.samples.push(d),e.len+=l,{sample:d,length:l+s}}}var m=r(3);var v=function(){function e(t,r,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=i,this.remuxer=r}return e.prototype.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},e.prototype.resetTimeStamp=function(){},e.probe=function(e){if(!e)return!1;for(var t=(m.a.getID3Data(e,0)||[]).length,r=e.length;t<r;t++)if(d(e,t))return a.b.log("ADTS sync word found !"),!0;return!1},e.prototype.append=function(e,t,r,i){for(var n=this._audioTrack,o=m.a.getID3Data(e,0)||[],s=m.a.getTimeStamp(o),u=s?90*s:9e4*t,c=0,d=u,h=e.length,v=o.length,g=[{pts:d,dts:d,data:o}];v<h-1;)if(l(e,v)&&v+5<h){f(n,this.observer,e,v,n.manifestCodec);var y=p(n,e,v,u,c);if(!y){a.b.log("Unable to parse AAC frame");break}v+=y.length,d=y.sample.pts,c++}else m.a.isHeader(e,v)?(o=m.a.getID3Data(e,v),g.push({pts:d,dts:d,data:o}),v+=o.length):v++;this.remuxer.remux(n,{samples:[]},{samples:g,inputTimeScale:9e4},{samples:[]},t,r,i)},e.prototype.destroy=function(){},e}();var g=Math.pow(2,32)-1,y=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.remuxer=r}return e.prototype.resetTimeStamp=function(e){this.initPTS=e},e.prototype.resetInitSegment=function(t,r,n,o){if(t&&t.byteLength){var a=this.initData=e.parseInitSegment(t);null==r&&(r="mp4a.40.5"),null==n&&(n="avc1.42e01e");var s={};a.audio&&a.video?s.audiovideo={container:"video/mp4",codec:r+","+n,initSegment:o?t:null}:(a.audio&&(s.audio={container:"audio/mp4",codec:r,initSegment:o?t:null}),a.video&&(s.video={container:"video/mp4",codec:n,initSegment:o?t:null})),this.observer.trigger(i.a.FRAG_PARSING_INIT_SEGMENT,{tracks:s})}else r&&(this.audioCodec=r),n&&(this.videoCodec=n)},e.probe=function(t){return e.findBox({data:t,start:0,end:Math.min(t.length,16384)},["moof"]).length>0},e.bin2str=function(e){return String.fromCharCode.apply(null,e)},e.readUint32=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},e.writeUint32=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},e.findBox=function(t,r){var i,n,o,a,s,u,c,l=[];if(t.data?(u=t.start,a=t.end,t=t.data):(u=0,a=t.byteLength),!r.length)return null;for(i=u;i<a;)n=e.readUint32(t,i),o=e.bin2str(t.subarray(i+4,i+8)),c=n>1?i+n:a,o===r[0]&&(1===r.length?l.push({data:t,start:i+8,end:c}):(s=e.findBox({data:t,start:i+8,end:c},r.slice(1))).length&&(l=l.concat(s))),i=c;return l},e.parseInitSegment=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],o=0===n?12:20,s=e.readUint32(i,o),u=e.findBox(t,["mdia","mdhd"])[0];if(u){o=0===(n=u.data[u.start])?12:20;var c=e.readUint32(u,o),l=e.findBox(t,["mdia","hdlr"])[0];if(l){var d={soun:"audio",vide:"video"}[e.bin2str(l.data.subarray(l.start+8,l.start+12))];if(d){var f=e.findBox(t,["mdia","minf","stbl","stsd"]);if(f.length){f=f[0];var h=e.bin2str(f.data.subarray(f.start+12,f.start+16));a.b.log("MP4Demuxer:"+d+":"+h+" found")}r[s]={timescale:c,type:d},r[d]={timescale:c,id:s}}}}}}),r},e.getStartDTS=function(t,r){var i,n,o;return i=e.findBox(r,["moof","traf"]),n=[].concat.apply([],i.map(function(r){return e.findBox(r,["tfhd"]).map(function(i){var n,o;return n=e.readUint32(i,4),o=t[n].timescale||9e4,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=Math.min.apply(null,n),isFinite(o)?o:0},e.offsetStartDTS=function(t,r,i){e.findBox(r,["moof","traf"]).map(function(r){return e.findBox(r,["tfhd"]).map(function(n){var o=e.readUint32(n,4),a=t[o].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*a);else{n*=Math.pow(2,32),n+=e.readUint32(t,8),n-=i*a,n=Math.max(n,0);var o=Math.floor(n/(g+1)),s=Math.floor(n%(g+1));e.writeUint32(t,4,o),e.writeUint32(t,8,s)}})})})},e.prototype.append=function(t,r,n,o){var a=this.initData;a||(this.resetInitSegment(t,this.audioCodec,this.videoCodec),a=this.initData);var s,u=this.initPTS;if(void 0===u){var c=e.getStartDTS(a,t);this.initPTS=u=c-r,this.observer.trigger(i.a.INIT_PTS_FOUND,{initPTS:u})}e.offsetStartDTS(a,t,u),s=e.getStartDTS(a,t),this.remuxer.remux(a.audio,a.video,null,null,s,n,o,t)},e.prototype.destroy=function(){},e}(),_={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],SamplesCoefficients:[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot:[0,1,1,4],appendFrame:function(e,t,r,i,n){if(!(r+24>t.length)){var o=this.parseHeader(t,r);if(o&&r+o.frameLength<=t.length){var a=i+n*(9e4*o.samplesPerFrame/o.sampleRate),s={unit:t.subarray(r,r+o.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=o.channelCount,e.samplerate=o.sampleRate,e.samples.push(s),e.len+=o.frameLength,{sample:s,length:o.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,o=e[t+2]>>2&3,a=e[t+2]>>1&1;if(1!==r&&0!==n&&15!==n&&3!==o){var s=3===r?3-i:3===i?3:4,u=1e3*_.BitratesMap[14*s+n-1],c=3===r?0:2===r?1:2,l=_.SamplingRateMap[3*c+o],d=e[t+3]>>6==3?1:2,f=_.SamplesCoefficients[r][i],h=_.BytesInSlot[i],p=8*f*h;return{sampleRate:l,channelCount:d,frameLength:parseInt(f*u/l+a,10)*h,samplesPerFrame:p}}},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}},b=_;var w=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}return e.prototype.loadWord=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},e.prototype.skipBits=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)},e.prototype.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&a.b.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},e.prototype.skipLZ=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()},e.prototype.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.prototype.skipEG=function(){this.skipBits(1+this.skipLZ())},e.prototype.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},e.prototype.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},e.prototype.readBoolean=function(){return 1===this.readBits(1)},e.prototype.readUByte=function(){return this.readBits(8)},e.prototype.readUShort=function(){return this.readBits(16)},e.prototype.readUInt=function(){return this.readBits(32)},e.prototype.skipScalingList=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},e.prototype.readSPS=function(){var e,t,r,i,n,o,a,s=0,u=0,c=0,l=0,d=this.readUByte.bind(this),f=this.readBits.bind(this),h=this.readUEG.bind(this),p=this.readBoolean.bind(this),m=this.skipBits.bind(this),v=this.skipEG.bind(this),g=this.skipUEG.bind(this),y=this.skipScalingList.bind(this);if(d(),e=d(),f(5),m(3),d(),g(),100===e||110===e||122===e||244===e||44===e||83===e||86===e||118===e||128===e){var _=h();if(3===_&&m(1),g(),g(),m(1),p())for(o=3!==_?8:12,a=0;a<o;a++)p()&&y(a<6?16:64)}g();var b=h();if(0===b)h();else if(1===b)for(m(1),v(),v(),t=h(),a=0;a<t;a++)v();g(),m(1),r=h(),i=h(),0===(n=f(1))&&m(1),m(1),p()&&(s=h(),u=h(),c=h(),l=h());var w=[1,1];if(p()&&p())switch(d()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[d()<<8|d(),d()<<8|d()]}return{width:Math.ceil(16*(r+1)-2*s-2*u),height:(2-n)*(i+1)*16-(n?2:4)*(c+l),pixelRatio:w}},e.prototype.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},e}();var E=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.decryptdata=i,this.discardEPB=n,this.decrypter=new o.a(t,r)}return e.prototype.decryptBuffer=function(e,t){this.decrypter.decrypt(e,this.decryptdata.key.buffer,this.decryptdata.iv.buffer,t)},e.prototype.decryptAacSample=function(e,t,r,i){var n=e[t].unit,o=n.subarray(16,n.length-n.length%16),a=o.buffer.slice(o.byteOffset,o.byteOffset+o.length),s=this;this.decryptBuffer(a,function(o){o=new Uint8Array(o),n.set(o,16),i||s.decryptAacSamples(e,t+1,r)})},e.prototype.decryptAacSamples=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}}},e.prototype.getAvcEncryptedData=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},e.prototype.getAvcDecryptedUnit=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},e.prototype.decryptAvcSample=function(e,t,r,i,n,o){var a=this.discardEPB(n.data),s=this.getAvcEncryptedData(a),u=this;this.decryptBuffer(s.buffer,function(s){n.data=u.getAvcDecryptedUnit(a,s),o||u.decryptAvcSamples(e,t,r+1,i)})},e.prototype.decryptAvcSamples=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 o=n[r];if(!(o.length<=48||1!==o.type&&5!==o.type)){var a=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,o,a),!a)return}}}},e}();var S={video:0,audio:1,id3:2,text:3},T=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=i,this.typeSupported=n,this.remuxer=r,this.sampleAes=null}return e.prototype.setDecryptData=function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new E(this.observer,this.config,e,this.discardEPB):this.sampleAes=null},e.probe=function(t){var r=e._syncOffset(t);return!(r<0)&&(r&&a.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},e._syncOffset=function(e){for(var t=Math.min(1e3,e.length-564),r=0;r<t;){if(71===e[r]&&71===e[r+188]&&71===e[r+376])return r;r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:S[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],len:0,dropped:"video"===e?0:void 0,isAAC:"audio"===e||void 0,duration:"audio"===e?t:void 0}},e.prototype.resetInitSegment=function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=e.createTrack("video",n),this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3",n),this._txtTrack=e.createTrack("text",n),this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},e.prototype.resetTimeStamp=function(){},e.prototype.append=function(t,r,o,s){var u,c,l,d,f,h=t.length,p=!1;this.contiguous=o;var m=this.pmtParsed,v=this._avcTrack,g=this._audioTrack,y=this._id3Track,_=v.pid,b=g.pid,w=y.pid,E=this._pmtId,S=v.pesData,T=g.pesData,O=y.pesData,A=this._parsePAT,$=this._parsePMT,k=this._parsePES,D=this._parseAVCPES.bind(this),I=this._parseAACPES.bind(this),x=this._parseMPEGPES.bind(this),C=this._parseID3PES.bind(this),M=e._syncOffset(t);for(h-=(h+M)%188,u=M;u<h;u+=188)if(71===t[u]){if(c=!!(64&t[u+1]),l=((31&t[u+1])<<8)+t[u+2],(48&t[u+3])>>4>1){if((d=u+5+t[u+4])===u+188)continue}else d=u+4;switch(l){case _:c&&(S&&(f=k(S))&&D(f,!1),S={data:[],size:0}),S&&(S.data.push(t.subarray(d,u+188)),S.size+=u+188-d);break;case b:c&&(T&&(f=k(T))&&(g.isAAC?I(f):x(f)),T={data:[],size:0}),T&&(T.data.push(t.subarray(d,u+188)),T.size+=u+188-d);break;case w:c&&(O&&(f=k(O))&&C(f),O={data:[],size:0}),O&&(O.data.push(t.subarray(d,u+188)),O.size+=u+188-d);break;case 0:c&&(d+=t[d]+1),E=this._pmtId=A(t,d);break;case E:c&&(d+=t[d]+1);var P=$(t,d,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);(_=P.avc)>0&&(v.pid=_),(b=P.audio)>0&&(g.pid=b,g.isAAC=P.isAAC),(w=P.id3)>0&&(y.pid=w),p&&!m&&(a.b.log("reparse from beginning"),p=!1,u=M-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=!0}}else this.observer.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});S&&(f=k(S))?(D(f,!0),v.pesData=null):v.pesData=S,T&&(f=k(T))?(g.isAAC?I(f):x(f),g.pesData=null):(T&&T.size&&a.b.log("last AAC PES packet truncated,might overlap between fragments"),g.pesData=T),O&&(f=k(O))?(C(f),y.pesData=null):y.pesData=O,null==this.sampleAes?this.remuxer.remux(g,v,y,this._txtTrack,r,o,s):this.decryptAndRemux(g,v,y,this._txtTrack,r,o,s)},e.prototype.decryptAndRemux=function(e,t,r,i,n,o,a){if(e.samples&&e.isAAC){var s=this;this.sampleAes.decryptAacSamples(e.samples,0,function(){s.decryptAndRemuxAvc(e,t,r,i,n,o,a)})}else this.decryptAndRemuxAvc(e,t,r,i,n,o,a)},e.prototype.decryptAndRemuxAvc=function(e,t,r,i,n,o,a){if(t.samples){var s=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,function(){s.remuxer.remux(e,t,r,i,n,o,a)})}else this.remuxer.remux(e,t,r,i,n,o,a)},e.prototype.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},e.prototype._parsePAT=function(e,t){return(31&e[t+10])<<8|e[t+11]},e.prototype._parsePMT=function(e,t,r,i){var n,o,s={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(o=(31&e[t+1])<<8|e[t+2],e[t]){case 207:if(!i){a.b.log("unkown stream type:"+e[t]);break}case 15:-1===s.audio&&(s.audio=o);break;case 21:-1===s.id3&&(s.id3=o);break;case 219:if(!i){a.b.log("unkown stream type:"+e[t]);break}case 27:-1===s.avc&&(s.avc=o);break;case 3:case 4:r?-1===s.audio&&(s.audio=o,s.isAAC=!1):a.b.log("MPEG audio found, not supported in this browser for now");break;case 36:a.b.warn("HEVC stream type found, not supported for now");break;default:a.b.log("unkown stream type:"+e[t])}t+=5+((15&e[t+3])<<8|e[t+4])}return s},e.prototype._parsePES=function(e){var t,r,i,n,o,s,u,c,l=0,d=e.data;if(!e||0===e.size)return null;for(;d[0].length<19&&d.length>1;){var f=new Uint8Array(d[0].length+d[1].length);f.set(d[0]),f.set(d[1],d[0].length),d[0]=f,d.splice(1,1)}if(1===((t=d[0])[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;192&(r=t[7])&&((s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2)>4294967295&&(s-=8589934592),64&r?((u=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>4294967295&&(u-=8589934592),s-u>54e5&&(a.b.warn(Math.round((s-u)/9e4)+"s delta between PTS and DTS, align them"),s=u)):u=s),c=(n=t[8])+9,e.size-=c,o=new Uint8Array(e.size);for(var h=0,p=d.length;h<p;h++){var m=(t=d[h]).byteLength;if(c){if(c>m){c-=m;continue}t=t.subarray(c),m-=c,c=0}o.set(t,l),l+=m}return i&&(i-=n+3),{data:o,pts:s,dts:u,len:i}}return null},e.prototype.pushAccesUnit=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&&a.b.log(e.pts+"/"+e.dts+":"+e.debug)},e.prototype._parseAVCPES=function(e,t){var r,i,n,o=this,a=this._avcTrack,s=this._parseAVCNALu(e.data),u=this.avcSample,c=!1,l=this.pushAccesUnit.bind(this),d=function(e,t,r,i){return{key:e,pts:t,dts:r,units:[],debug:i}};e.data=null,u&&s.length&&!a.audFound&&(l(u,a),u=this.avcSample=d(!1,e.pts,e.dts,"")),s.forEach(function(t){switch(t.type){case 1:i=!0,u||(u=o.avcSample=d(!0,e.pts,e.dts,"")),u.frame=!0;var s=t.data;if(c&&s.length>4){var f=new w(s).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(u.key=!0)}break;case 5:i=!0,u||(u=o.avcSample=d(!0,e.pts,e.dts,"")),u.key=!0,u.frame=!0;break;case 6:i=!0,(r=new w(o.discardEPB(t.data))).readUByte();for(var h=0,p=0,m=!1,v=0;!m&&r.bytesAvailable>1;){h=0;do{h+=v=r.readUByte()}while(255===v);p=0;do{p+=v=r.readUByte()}while(255===v);if(4===h&&0!==r.bytesAvailable){if(m=!0,181===r.readUByte())if(49===r.readUShort())if(1195456820===r.readUInt())if(3===r.readUByte()){var g=r.readUByte(),y=31&g,_=[g,r.readUByte()];for(n=0;n<y;n++)_.push(r.readUByte()),_.push(r.readUByte()),_.push(r.readUByte());o._insertSampleInOrder(o._txtTrack.samples,{type:3,pts:e.pts,bytes:_})}}else if(p<r.bytesAvailable)for(n=0;n<p;n++)r.readUByte()}break;case 7:if(i=!0,c=!0,!a.sps){var b=(r=new w(t.data)).readSPS();a.width=b.width,a.height=b.height,a.pixelRatio=b.pixelRatio,a.sps=[t.data],a.duration=o._duration;var E=t.data.subarray(1,4),S="avc1.";for(n=0;n<3;n++){var T=E[n].toString(16);T.length<2&&(T="0"+T),S+=T}a.codec=S}break;case 8:i=!0,a.pps||(a.pps=[t.data]);break;case 9:i=!1,a.audFound=!0,u&&l(u,a),u=o.avcSample=d(!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&&(l(u,a),this.avcSample=null)},e.prototype._insertSampleInOrder=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)},e.prototype._getLastNalUnit=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},e.prototype._parseAVCNALu=function(e){var t,r,i,n,o=0,a=e.byteLength,s=this._avcTrack,u=s.naluState||0,c=u,l=[],d=-1;for(-1===u&&(d=0,n=31&e[0],u=0,o=1);o<a;)if(t=e[o++],u)if(1!==u)if(t)if(1===t){if(d>=0)i={data:e.subarray(d,o-u-1),type:n},l.push(i);else{var f=this._getLastNalUnit();if(f&&(c&&o<=4-c&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-c)),(r=o-u-1)>0)){var h=new Uint8Array(f.data.byteLength+r);h.set(f.data,0),h.set(e.subarray(0,r),f.data.byteLength),f.data=h}}o<a?(d=o,n=31&e[o],u=0):u=-1}else u=0;else u=3;else u=t?0:2;else u=t?0:1;if(d>=0&&u>=0&&(i={data:e.subarray(d,a),type:n,state:u},l.push(i)),0===l.length){var p=this._getLastNalUnit();if(p){var m=new Uint8Array(p.data.byteLength+e.byteLength);m.set(p.data,0),m.set(e,p.data.byteLength),p.data=m}}return s.naluState=u,l},e.prototype.discardEPB=function(e){for(var t,r,i=e.byteLength,n=[],o=1;o<i-2;)0===e[o]&&0===e[o+1]&&3===e[o+2]?(n.push(o+2),o+=2):o++;if(0===n.length)return e;t=i-n.length,r=new Uint8Array(t);var a=0;for(o=0;o<t;a++,o++)a===n[0]&&(a++,n.shift()),r[o]=e[a];return r},e.prototype._parseAACPES=function(e){var t,r,o,s,u,c,d,m=this._audioTrack,v=e.data,g=e.pts,y=this.aacOverFlow,_=this.aacLastPTS;if(y){var b=new Uint8Array(y.byteLength+v.byteLength);b.set(y,0),b.set(v,y.byteLength),v=b}for(o=0,u=v.length;o<u-1&&!l(v,o);o++);if(o&&(o<u-1?(c="AAC PES did not start with ADTS header,offset:"+o,d=!1):(c="no ADTS header found in AAC PES",d=!0),a.b.warn("parsing error:"+c),this.observer.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:d,reason:c}),d))return;if(f(m,this.observer,v,o,this.audioCodec),r=0,t=h(m.samplerate),y&&_){var w=_+t;Math.abs(w-g)>1&&(a.b.log("AAC: align PTS for overlapping frames by "+Math.round((w-g)/90)),g=w)}for(;o<u;)if(l(v,o)&&o+5<u){var E=p(m,v,o,g,r);if(!E)break;o+=E.length,s=E.sample.pts,r++}else o++;y=o<u?v.subarray(o,u):null,this.aacOverFlow=y,this.aacLastPTS=s},e.prototype._parseMPEGPES=function(e){for(var t=e.data,r=t.length,i=0,n=0,o=e.pts;n<r;)if(b.isHeader(t,n)){var a=b.appendFrame(this._audioTrack,t,n,o,i);if(!a)break;n+=a.length,i++}else n++},e.prototype._parseID3PES=function(e){this._id3Track.samples.push(e)},e}();var O=function(){function e(t,r,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=i,this.remuxer=r}return e.prototype.resetInitSegment=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}},e.prototype.resetTimeStamp=function(){},e.probe=function(e){var t,r,i=m.a.getID3Data(e,0);if(i&&void 0!==m.a.getTimeStamp(i))for(t=i.length,r=Math.min(e.length-1,t+100);t<r;t++)if(b.probe(e,t))return a.b.log("MPEG Audio sync word found !"),!0;return!1},e.prototype.append=function(e,t,r,i){for(var n=m.a.getID3Data(e,0),o=m.a.getTimeStamp(n),a=o?90*o:9e4*t,s=n.length,u=e.length,c=0,l=0,d=this._audioTrack,f=[{pts:a,dts:a,data:n}];s<u;)if(b.isHeader(e,s)){var h=b.appendFrame(d,e,s,a,c);if(!h)break;s+=h.length,l=h.sample.pts,c++}else m.a.isHeader(e,s)?(n=m.a.getID3Data(e,s),f.push({pts:l,dts:l,data:n}),s+=n.length):s++;this.remuxer.remux(d,{samples:[]},{samples:f,inputTimeScale:9e4},{samples:[]},t,r,i)},e.prototype.destroy=function(){},e}();var A=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.getSilentFrame=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}();var $=Math.pow(2,32)-1,k=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.init=function(){var t;for(t in 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:[]},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]),o=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=o,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 a=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,a,u,a,s),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))},e.box=function(e){for(var t,r=Array.prototype.slice.call(arguments,1),i=8,n=r.length,o=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<o;n++)t.set(r[n],i),i+=r[n].byteLength;return t},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,r){r*=t;var i=Math.floor(r/($+1)),n=Math.floor(r%($+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]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=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))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=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)))},e.mvex=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))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/($+1)),n=Math.floor(r%($+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)},e.sdtp=function(t){var r,i,n=t.samples||[],o=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,o[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,o)},e.stbl=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))},e.avc1=function(t){var r,i,n,o=[],a=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,o.push(n>>>8&255),o.push(255&n),o=o.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));var s=e.box(e.types.avcC,new Uint8Array([1,o[3],o[4],o[5],255,224|t.sps.length].concat(o).concat([t.pps.length]).concat(a))),u=t.width,c=t.height,l=t.pixelRatio[0],d=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,c>>8&255,255&c,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([l>>24,l>>16&255,l>>8&255,255&l,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=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]))},e.mp4a=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)))},e.mp3=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]))},e.stsd=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))},e.tkhd=function(t){var r=t.id,i=t.duration*t.timescale,n=t.width,o=t.height,a=Math.floor(i/($+1)),s=Math.floor(i%($+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,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s,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]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,o=Math.floor(r/($+1)),a=Math.floor(r%($+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,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=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]))},e.trun=function(t,r){var i,n,o,a,s,u,c=t.samples||[],l=c.length,d=12+16*l,f=new Uint8Array(d);for(r+=8+d,f.set([0,0,15,1,l>>>24&255,l>>>16&255,l>>>8&255,255&l,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<l;i++)o=(n=c[i]).duration,a=n.size,s=n.flags,u=n.cts,f.set([o>>>24&255,o>>>16&255,o>>>8&255,255&o,a>>>24&255,a>>>16&255,a>>>8&255,255&a,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,f)},e.initSegment=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}();var D=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=r,this.typeSupported=i;var o=navigator.userAgent;this.isSafari=n&&n.indexOf("Apple")>-1&&o&&!o.match("CriOS"),this.ISGenerated=!1}return e.prototype.destroy=function(){},e.prototype.resetTimeStamp=function(e){this._initPTS=this._initDTS=e},e.prototype.resetInitSegment=function(){this.ISGenerated=!1},e.prototype.remux=function(e,t,r,n,o,s,u){if(this.ISGenerated||this.generateIS(e,t,o),this.ISGenerated){var c=e.samples.length,l=t.samples.length,d=o,f=o;if(c&&l){var h=(e.samples[0].dts-t.samples[0].dts)/t.inputTimeScale;d+=Math.max(0,h),f+=Math.max(0,-h)}if(c){e.timescale||(a.b.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,o));var p=this.remuxAudio(e,d,s,u);if(l){var m=void 0;p&&(m=p.endPTS-p.startPTS),t.timescale||(a.b.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,o)),this.remuxVideo(t,f,s,m,u)}}else{var v=void 0;l&&(v=this.remuxVideo(t,f,s,u)),v&&e.codec&&this.remuxEmptyAudio(e,d,s,v)}}r.samples.length&&this.remuxID3(r,o),n.samples.length&&this.remuxText(n,o),this.observer.trigger(i.a.FRAG_PARSED)},e.prototype.generateIS=function(e,t,r){var o,s,u=this.observer,c=e.samples,l=t.samples,d=this.typeSupported,f="audio/mp4",h={},p={tracks:h},m=void 0===this._initPTS;if(m&&(o=s=1/0),e.config&&c.length&&(e.timescale=e.samplerate,a.b.log("audio sampling rate : "+e.samplerate),e.isAAC||(d.mpeg?(f="audio/mpeg",e.codec=""):d.mp3&&(e.codec="mp3")),h.audio={container:f,codec:e.codec,initSegment:!e.isAAC&&d.mpeg?new Uint8Array:k.initSegment([e]),metadata:{channelCount:e.channelCount}},m&&(o=s=c[0].pts-e.inputTimeScale*r)),t.sps&&t.pps&&l.length){var v=t.inputTimeScale;t.timescale=v,h.video={container:"video/mp4",codec:t.codec,initSegment:k.initSegment([t]),metadata:{width:t.width,height:t.height}},m&&(o=Math.min(o,l[0].pts-v*r),s=Math.min(s,l[0].dts-v*r),this.observer.trigger(i.a.INIT_PTS_FOUND,{initPTS:o}))}Object.keys(h).length?(u.trigger(i.a.FRAG_PARSING_INIT_SEGMENT,p),this.ISGenerated=!0,m&&(this._initPTS=o,this._initDTS=s)):u.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},e.prototype.remuxVideo=function(e,t,r,o,s){var u,c,l,d,f,h,p,m=8,v=e.timescale,g=e.samples,y=[],_=g.length,b=this._PTSNormalize,w=this._initDTS,E=this.nextAvcDts,S=this.isSafari;S&&(r|=g.length&&E&&(s&&Math.abs(t-E/v)<.1||Math.abs(g[0].pts-E-w)<v/5)),r||(E=t*v),g.forEach(function(e){e.pts=b(e.pts-w,E),e.dts=b(e.dts-w,E)}),g.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||(i||e.id-t.id)});var T=g.reduce(function(e,t){return Math.max(Math.min(e,t.pts-t.dts),-18e3)},0);if(T<0){a.b.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(T/90)+" ms to overcome this issue");for(var O=0;O<g.length;O++)g[O].dts+=T}var A=g[0];f=Math.max(A.dts,0),d=Math.max(A.pts,0);var $=Math.round((f-E)/90);r&&$&&($>1?a.b.log("AVC:"+$+" ms hole between fragments detected,filling it"):$<-1&&a.b.log("AVC:"+-$+" ms overlapping between fragments detected"),f=E,g[0].dts=f,d=Math.max(d-$,E),g[0].pts=d,a.b.log("Video/PTS/DTS adjusted: "+Math.round(d/90)+"/"+Math.round(f/90)+",delta:"+$+" ms")),A=g[g.length-1],p=Math.max(A.dts,0),h=Math.max(A.pts,0,p),S&&(u=Math.round((p-f)/(g.length-1)));for(var D=0,I=0,x=0;x<_;x++){for(var C=g[x],M=C.units,P=M.length,L=0,R=0;R<P;R++)L+=M[R].data.length;I+=L,D+=P,C.length=L,C.dts=S?f+x*u:Math.max(C.dts,f),C.pts=Math.max(C.pts,C.dts)}var N=I+4*D+8;try{c=new Uint8Array(N)}catch(e){return void this.observer.trigger(i.a.ERROR,{type:n.b.MUX_ERROR,details:n.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating video mdat "+N})}var j=new DataView(c.buffer);j.setUint32(0,N),c.set(k.types.mdat,4);for(var F=0;F<_;F++){for(var B=g[F],U=B.units,z=0,G=void 0,W=0,H=U.length;W<H;W++){var V=U[W],Y=V.data,K=V.data.byteLength;j.setUint32(m,K),m+=4,c.set(Y,m),m+=K,z+=4+K}if(S)G=Math.max(0,u*Math.round((B.pts-B.dts)/u));else{if(F<_-1)u=g[F+1].dts-B.dts;else{var Z=this.config,Q=B.dts-g[F>0?F-1:F].dts;if(Z.stretchShortVideoTrack){var X=Z.maxBufferHole,q=Z.maxSeekHole,J=Math.floor(Math.min(X,q)*v),ee=(o?d+o*v:this.nextAudioPts)-B.pts;ee>J?((u=ee-Q)<0&&(u=Q),a.b.log("It is approximately "+ee/90+" ms to the next segment; using duration "+u/90+" ms for the last video frame.")):u=Q}else u=Q}G=Math.round(B.pts-B.dts)}y.push({size:z,duration:u,cts:G,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:B.key?2:1,isNonSync:B.key?0:1}})}this.nextAvcDts=p+u;var te=e.dropped;if(e.len=0,e.nbNalu=0,e.dropped=0,y.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var re=y[0].flags;re.dependsOn=2,re.isNonSync=0}e.samples=y,l=k.moof(e.sequenceNumber++,f,e),e.samples=[];var ie={data1:l,data2:c,startPTS:d/v,endPTS:(h+u)/v,startDTS:f/v,endDTS:this.nextAvcDts/v,type:"video",nb:y.length,dropped:te};return this.observer.trigger(i.a.FRAG_PARSING_DATA,ie),ie},e.prototype.remuxAudio=function(e,t,r,o){var s,u,c,l,d,f,h,p=e.inputTimeScale,m=e.timescale,v=p/m,g=(e.isAAC?1024:1152)*v,y=this._PTSNormalize,_=this._initDTS,b=!e.isAAC&&this.typeSupported.mpeg,w=e.samples,E=[],S=this.nextAudioPts;if(r|=w.length&&S&&(o&&Math.abs(t-S/p)<.1||Math.abs(w[0].pts-S-_)<20*g),w.forEach(function(e){e.pts=e.dts=y(e.pts-_,t*p)}),0!==(w=w.filter(function(e){return e.pts>=0})).length){if(r||(S=o?t*p:w[0].pts),e.isAAC)for(var T=this.config.maxAudioFramesDrift,O=0,$=S;O<w.length;){var D,I=w[O];D=I.pts-$;var x=Math.abs(1e3*D/p);if(D<=-T*g)a.b.warn("Dropping 1 audio frame @ "+($/p).toFixed(3)+"s due to "+Math.round(x)+" ms overlap."),w.splice(O,1),e.len-=I.unit.length;else if(D>=T*g&&x<1e4&&$){var C=Math.round(D/g);a.b.warn("Injecting "+C+" audio frame @ "+($/p).toFixed(3)+"s due to "+Math.round(1e3*D/p)+" ms gap.");for(var M=0;M<C;M++){var P=Math.max($,0);(c=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(a.b.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),c=I.unit.subarray()),w.splice(O,0,{unit:c,pts:P,dts:P}),e.len+=c.length,$+=g,O++}I.pts=I.dts=$,$+=g,O++}else I.pts=I.dts=$,$+=g,O++}for(var L=0,R=w.length;L<R;L++){var N=w[L],j=N.unit,F=N.pts;if(void 0!==h)u.duration=Math.round((F-h)/v);else{var B=Math.round(1e3*(F-S)/p),U=0;if(r&&e.isAAC&&B){if(B>0&&B<1e4)U=Math.round((F-S)/g),a.b.log(B+" ms hole between AAC samples detected,filling it"),U>0&&((c=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(c=j.subarray()),e.len+=U*c.length);else if(B<-12){a.b.log("drop overlapping AAC sample, expected/parsed/delta:"+(S/p).toFixed(3)+"s/"+(F/p).toFixed(3)+"s/"+-B+"ms"),e.len-=j.byteLength;continue}F=S}if(f=F,!(e.len>0))return;var z=b?e.len:e.len+8;s=b?0:8;try{l=new Uint8Array(z)}catch(e){return void this.observer.trigger(i.a.ERROR,{type:n.b.MUX_ERROR,details:n.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:z,reason:"fail allocating audio mdat "+z})}b||(new DataView(l.buffer).setUint32(0,z),l.set(k.types.mdat,4));for(var G=0;G<U;G++)(c=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(a.b.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),c=j.subarray()),l.set(c,s),s+=c.byteLength,u={size:c.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},E.push(u)}l.set(j,s);var W=j.byteLength;s+=W,u={size:W,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},E.push(u),h=F}var H=0,V=E.length;if(V>=2&&(H=E[V-2].duration,u.duration=H),V){this.nextAudioPts=S=h+v*H,e.len=0,e.samples=E,d=b?new Uint8Array:k.moof(e.sequenceNumber++,f/v,e),e.samples=[];var Y=f/p,K=S/p,Z={data1:d,data2:l,startPTS:Y,endPTS:K,startDTS:Y,endDTS:K,type:"audio",nb:V};return this.observer.trigger(i.a.FRAG_PARSING_DATA,Z),Z}return null}},e.prototype.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,o=n/(e.samplerate?e.samplerate:n),s=this.nextAudioPts,u=(void 0!==s?s:i.startDTS*n)+this._initDTS,c=i.endDTS*n+this._initDTS,l=1024*o,d=Math.ceil((c-u)/l),f=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(a.b.warn("remux empty Audio"),f){for(var h=[],p=0;p<d;p++){var m=u+p*l;h.push({unit:f,pts:m,dts:m}),e.len+=f.length}e.samples=h,this.remuxAudio(e,t,r)}else a.b.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!")},e.prototype.remuxID3=function(e,t){var r,n=e.samples.length,o=e.inputTimeScale,a=this._initPTS,s=this._initDTS;if(n){for(var u=0;u<n;u++)(r=e.samples[u]).pts=(r.pts-a)/o,r.dts=(r.dts-s)/o;this.observer.trigger(i.a.FRAG_PARSING_METADATA,{samples:e.samples})}e.samples=[],t=t},e.prototype.remuxText=function(e,t){e.samples.sort(function(e,t){return e.pts-t.pts});var r,n=e.samples.length,o=e.inputTimeScale,a=this._initPTS;if(n){for(var s=0;s<n;s++)(r=e.samples[s]).pts=(r.pts-a)/o;this.observer.trigger(i.a.FRAG_PARSING_USERDATA,{samples:e.samples})}e.samples=[],t=t},e.prototype._PTSNormalize=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}();var I=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t}return e.prototype.destroy=function(){},e.prototype.resetTimeStamp=function(){},e.prototype.resetInitSegment=function(){},e.prototype.remux=function(e,t,r,n,o,a,s,u){var c=this.observer,l="";e&&(l+="audio"),t&&(l+="video"),c.trigger(i.a.FRAG_PARSING_DATA,{data1:u,startPTS:o,startDTS:o,type:l,nb:1,dropped:0}),c.trigger(i.a.FRAG_PARSED)},e}();var x=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.typeSupported=r,this.config=i,this.vendor=n}return e.prototype.destroy=function(){var e=this.demuxer;e&&e.destroy()},e.prototype.push=function(e,t,r,n,a,s,u,c,l,d,f,h){if(e.byteLength>0&&null!=t&&null!=t.key&&"AES-128"===t.method){var p=this.decrypter;null==p&&(p=this.decrypter=new o.a(this.observer,this.config));var m,v=this;try{m=performance.now()}catch(e){m=Date.now()}p.decrypt(e,t.key.buffer,t.iv.buffer,function(e){var o;try{o=performance.now()}catch(e){o=Date.now()}v.observer.trigger(i.a.FRAG_DECRYPTED,{stats:{tstart:m,tdecrypt:o}}),v.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,a,s,u,c,l,d,f,h)})}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,a,s,u,c,l,d,f,h)},e.prototype.pushDecrypted=function(e,t,r,o,a,s,u,c,l,d,f,h){var p=this.demuxer;if(!p||u&&!this.probe(e)){for(var m=this.observer,g=this.typeSupported,_=this.config,b=[{demux:T,remux:D},{demux:y,remux:I},{demux:v,remux:D},{demux:O,remux:D}],w=0,E=b.length;w<E;w++){var S=b[w],A=S.demux.probe;if(A(e)){var $=this.remuxer=new S.remux(m,_,g,this.vendor);p=new S.demux(m,$,_,g),this.probe=A;break}}if(!p)return void m.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=p}var k=this.remuxer;(u||c)&&(p.resetInitSegment(r,o,a,d),k.resetInitSegment()),u&&(p.resetTimeStamp(h),k.resetTimeStamp(h)),"function"==typeof p.setDecryptData&&p.setDecryptData(t),p.append(e,s,l,f)},e}();t.a=x},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i={};r.d(i,"newCue",function(){return Ee});var n=r(6),o=r.n(n),a=r(1),s=r(2),u=r(0),c="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};var l=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hls=t,this.onEvent=this.onEvent.bind(this);for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];this.handledEvents=i,this.useGenericHandler=!0,this.registerListeners()}return e.prototype.destroy=function(){this.unregisterListeners()},e.prototype.isEventHandler=function(){return"object"===c(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent},e.prototype.registerListeners=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)},e.prototype.unregisterListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){this.hls.off(e,this.onEvent)},this)},e.prototype.onEvent=function(e,t){this.onEventGeneric(e,t)},e.prototype.onEventGeneric=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){u.b.error("internal error happened while processing "+e+":"+t.message),this.hls.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!1,event:e,err:t})}},e}();var d=/^(\d+)x(\d+)$/,f=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,h=function(){function e(t){for(var r in function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),"string"==typeof t&&(t=e.parseAttrList(t)),t)t.hasOwnProperty(r)&&(this[r]=t[r])}return e.prototype.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.prototype.hexadecimalInteger=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},e.prototype.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.prototype.decimalFloatingPoint=function(e){return parseFloat(this[e])},e.prototype.enumeratedString=function(e){return this[e]},e.prototype.decimalResolution=function(e){var t=d.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(f.lastIndex=0;null!==(t=f.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}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};function m(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}var v=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}}();function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var y=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,_=/#EXT-X-MEDIA:(.*)/g,b=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),w=/(?:(?:#(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?/,E=function(){function e(){g(this,e),this.method=null,this.key=null,this.iv=null,this._uri=null}return v(e,[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=o.a.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}]),e}(),S=function(){function e(){g(this,e),this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[]}return e.prototype.createInitializationVector=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t},e.prototype.fragmentDecryptdataFromLevelkey=function(e,t){var r=e;return e&&e.method&&e.uri&&!e.iv&&((r=new E).method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r},e.prototype.cloneObj=function(e){return JSON.parse(JSON.stringify(e))},v(e,[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=o.a.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 T(e,t){if(!e)return null;for(var r=null,i=0;i<e.length;i++){var n=e[i];n.id===t&&(r=n)}return r}var O=function(e){function t(r){g(this,t);var i=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}(this,e.call(this,r,a.a.MANIFEST_LOADING,a.a.LEVEL_LOADING,a.a.AUDIO_TRACK_LOADING,a.a.SUBTITLE_TRACK_LOADING));return i.loaders={},i}return 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)}(t,e),t.prototype.destroy=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},l.prototype.destroy.call(this)},t.prototype.onManifestLoading=function(e){this.load(e.url,{type:"manifest"})},t.prototype.onLevelLoading=function(e){this.load(e.url,{type:"level",level:e.level,id:e.id})},t.prototype.onAudioTrackLoading=function(e){this.load(e.url,{type:"audioTrack",id:e.id})},t.prototype.onSubtitleTrackLoading=function(e){this.load(e.url,{type:"subtitleTrack",id:e.id})},t.prototype.load=function(e,t){var r=this.loaders[t.type];if(void 0!==r){var i=r.context;if(i&&i.url===e)return void u.b.trace("playlist request ongoing");u.b.warn("abort previous loader for type:"+t.type),r.abort()}var n=this.hls.config,o=void 0,a=void 0,s=void 0,c=void 0;"manifest"===t.type?(o=n.manifestLoadingMaxRetry,a=n.manifestLoadingTimeOut,s=n.manifestLoadingRetryDelay,c=n.manifestLoadingMaxRetryTimeout):"level"===t.type?(o=0,a=n.levelLoadingTimeOut):(o=n.levelLoadingMaxRetry,a=n.levelLoadingTimeOut,s=n.levelLoadingRetryDelay,c=n.levelLoadingMaxRetryTimeout,u.b.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,d;l={timeout:a,maxRetry:o,retryDelay:s,maxRetryDelay:c},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},r.load(t,l,d)},t.prototype.resolve=function(e,t){return o.a.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},t.prototype.parseMasterPlaylist=function(e,t){var r=[],i=void 0;function n(e,t){["video","audio"].forEach(function(r){var i=e.filter(function(e){return function(e,t){var r=p[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)});if(i.length){var n=i.filter(function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)});t[r+"Codec"]=n.length>0?n[0]:i[0],e=e.filter(function(e){return-1===i.indexOf(e)})}}),t.unknownCodecs=e}for(y.lastIndex=0;null!=(i=y.exec(e));){var o={},a=o.attrs=new h(i[1]);o.url=this.resolve(i[2],t);var s=a.decimalResolution("RESOLUTION");s&&(o.width=s.width,o.height=s.height),o.bitrate=a.decimalInteger("AVERAGE-BANDWIDTH")||a.decimalInteger("BANDWIDTH"),o.name=a.NAME,n([].concat((a.CODECS||"").split(/[ ,]+/)),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=this.avc1toavcoti(o.videoCodec)),r.push(o)}return r},t.prototype.parseMasterPlaylistMedia=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],n=void 0,o=[],a=0;for(_.lastIndex=0;null!==(n=_.exec(e));){var s={},u=new h(n[1]);if(u.TYPE===r){if(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.length){var c=T(i,s.groupId);s.audioCodec=c?c.codec:i[0].codec}s.id=a++,o.push(s)}}return o},t.prototype.avc1toavcoti=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},t.prototype.parseLevelPlaylist=function(e,t,r,i){var n,o,a=0,s=0,c={type:null,version:null,url:t,fragments:[],live:!0,startSN:0},l=new E,d=0,f=null,p=new S;for(b.lastIndex=0;null!==(n=b.exec(e));){var m=n[1];if(m){p.duration=parseFloat(m);var v=(" "+n[2]).slice(1);p.title=v||null,p.tagList.push(v?["INF",m,v]:["INF",m])}else if(n[3]){if(!isNaN(p.duration)){var g=a++;p.type=i,p.start=s,p.levelkey=l,p.sn=g,p.level=r,p.cc=d,p.baseurl=t,p.relurl=(" "+n[3]).slice(1),c.fragments.push(p),f=p,s+=p.duration,p=new S}}else if(n[4]){if(p.rawByteRange=(" "+n[4]).slice(1),f){var y=f.byteRangeEndOffset;y&&(p.lastByteRangeEndOffset=y)}}else if(n[5])p.rawProgramDateTime=(" "+n[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),void 0===c.programDateTime&&(c.programDateTime=new Date(new Date(Date.parse(n[5]))-1e3*s));else{for(n=n[0].match(w),o=1;o<n.length&&void 0===n[o];o++);var _=(" "+n[o+1]).slice(1),T=(" "+n[o+2]).slice(1);switch(n[o]){case"#":p.tagList.push(T?[_,T]:[_]);break;case"PLAYLIST-TYPE":c.type=_.toUpperCase();break;case"MEDIA-SEQUENCE":a=c.startSN=parseInt(_);break;case"TARGETDURATION":c.targetduration=parseFloat(_);break;case"VERSION":c.version=parseInt(_);break;case"EXTM3U":break;case"ENDLIST":c.live=!1;break;case"DIS":d++,p.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":d=parseInt(_);break;case"KEY":var O=new h(_),A=O.enumeratedString("METHOD"),$=O.URI,k=O.hexadecimalInteger("IV");A&&(l=new E,$&&["AES-128","SAMPLE-AES"].indexOf(A)>=0&&(l.method=A,l.baseuri=t,l.reluri=$,l.key=null,l.iv=k));break;case"START":var D=new h(_).decimalFloatingPoint("TIME-OFFSET");isNaN(D)||(c.startTimeOffset=D);break;case"MAP":var I=new h(_);p.relurl=I.URI,p.rawByteRange=I.BYTERANGE,p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",c.initSegment=p,p=new S;break;default:u.b.warn("line parsed but not handled: "+n)}}}return(p=f)&&!p.relurl&&(c.fragments.pop(),s-=p.duration),c.totalduration=s,c.averagetargetduration=s/c.fragments.length,c.endSN=a-1,c.startCC=c.fragments[0]?c.fragments[0].cc:0,c.endCC=d,c},t.prototype.loadsuccess=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=e.data,o=e.url,c=r.type,l=r.id,d=r.level,f=this.hls;if(this.loaders[c]=void 0,void 0!==o&&0!==o.indexOf("data:")||(o=r.url),t.tload=performance.now(),0===n.indexOf("#EXTM3U"))if(n.indexOf("#EXTINF:")>0){var h="audioTrack"!==c&&"subtitleTrack"!==c,p=isNaN(d)?isNaN(l)?0:l:d,m=this.parseLevelPlaylist(n,o,p,"audioTrack"===c?"audio":"subtitleTrack"===c?"subtitle":"main");m.tload=t.tload,"manifest"===c&&f.trigger(a.a.MANIFEST_LOADED,{levels:[{url:o,details:m}],audioTracks:[],url:o,stats:t,networkDetails:i}),t.tparsed=performance.now(),m.targetduration?h?f.trigger(a.a.LEVEL_LOADED,{details:m,level:d||0,id:l||0,stats:t,networkDetails:i}):"audioTrack"===c?f.trigger(a.a.AUDIO_TRACK_LOADED,{details:m,id:l,stats:t,networkDetails:i}):"subtitleTrack"===c&&f.trigger(a.a.SUBTITLE_TRACK_LOADED,{details:m,id:l,stats:t,networkDetails:i}):f.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:!0,url:o,reason:"invalid targetduration",networkDetails:i})}else{var v=this.parseMasterPlaylist(n,o);if(v.length){var g=v.map(function(e){return{id:e.attrs.AUDIO,codec:e.audioCodec}}),y=this.parseMasterPlaylistMedia(n,o,"AUDIO",g),_=this.parseMasterPlaylistMedia(n,o,"SUBTITLES");if(y.length){var b=!1;y.forEach(function(e){e.url||(b=!0)}),!1===b&&v[0].audioCodec&&!v[0].attrs.AUDIO&&(u.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main"}))}f.trigger(a.a.MANIFEST_LOADED,{levels:v,audioTracks:y,subtitles:_,url:o,stats:t,networkDetails:i})}else f.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:!0,url:o,reason:"no level found in manifest",networkDetails:i})}else f.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:!0,url:o,reason:"no EXTM3U delimiter",networkDetails:i})},t.prototype.loaderror=function(e,t){var r,i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,o=t.loader;switch(t.type){case"manifest":r=s.a.MANIFEST_LOAD_ERROR,i=!0;break;case"level":r=s.a.LEVEL_LOAD_ERROR,i=!1;break;case"audioTrack":r=s.a.AUDIO_TRACK_LOAD_ERROR,i=!1}o&&(o.abort(),this.loaders[t.type]=void 0),this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:r,fatal:i,url:o.url,loader:o,response:e,context:t,networkDetails:n})},t.prototype.loadtimeout=function(e,t){var r,i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,o=t.loader;switch(t.type){case"manifest":r=s.a.MANIFEST_LOAD_TIMEOUT,i=!0;break;case"level":r=s.a.LEVEL_LOAD_TIMEOUT,i=!1;break;case"audioTrack":r=s.a.AUDIO_TRACK_LOAD_TIMEOUT,i=!1}o&&(o.abort(),this.loaders[t.type]=void 0),this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:r,fatal:i,url:o.url,loader:o,context:t,networkDetails:n})},t}(l);var A=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.FRAG_LOADING));return i.loaders={},i}return 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)}(t,e),t.prototype.destroy=function(){var e=this.loaders;for(var t in e){var r=e[t];r&&r.destroy()}this.loaders={},l.prototype.destroy.call(this)},t.prototype.onFragLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r],n=this.hls.config;t.loaded=0,i&&(u.b.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 o,a,s=void 0;s={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var c=t.byteRangeStartOffset,l=t.byteRangeEndOffset;isNaN(c)||isNaN(l)||(s.rangeStart=c,s.rangeEnd=l),o={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout},a={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},i.load(s,o,a)},t.prototype.loadsuccess=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=e.data,o=r.frag;o.loader=void 0,this.loaders[o.type]=void 0,this.hls.trigger(a.a.FRAG_LOADED,{payload:n,frag:o,stats:t,networkDetails:i})},t.prototype.loaderror=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(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})},t.prototype.loadtimeout=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(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})},t.prototype.loadprogress=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(a.a.FRAG_LOAD_PROGRESS,{frag:n,stats:e,networkDetails:i})},t}(l);var $=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.KEY_LOADING));return i.loaders={},i.decryptkey=null,i.decrypturl=null,i}return 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)}(t,e),t.prototype.destroy=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},l.prototype.destroy.call(this)},t.prototype.onKeyLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r],n=t.decryptdata,o=n.uri;if(o!==this.decrypturl||null===this.decryptkey){var s=this.hls.config;i&&(u.b.warn("abort previous key loader for type:"+r),i.abort()),t.loader=this.loaders[r]=new s.loader(s),this.decrypturl=o,this.decryptkey=null;var c,l,d;c={url:o,frag:t,responseType:"arraybuffer"},l={timeout:s.fragLoadingTimeOut,maxRetry:s.fragLoadingMaxRetry,retryDelay:s.fragLoadingRetryDelay,maxRetryDelay:s.fragLoadingMaxRetryTimeout},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},t.loader.load(c,l,d)}else this.decryptkey&&(n.key=this.decryptkey,this.hls.trigger(a.a.KEY_LOADED,{frag:t}))},t.prototype.loadsuccess=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(a.a.KEY_LOADED,{frag:i})},t.prototype.loaderror=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},t.prototype.loadtimeout=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}(l),k={search:function(e,t){for(var r=0,i=e.length-1,n=null,o=null;r<=i;){var a=t(o=e[n=(r+i)/2|0]);if(a>0)r=n+1;else{if(!(a<0))return o;i=n-1}}return null}},D={isBuffered:function(e,t){try{if(e)for(var r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)&&t<=r.end(i))return!0}catch(e){}return!1},bufferInfo:function(e,t,r){try{if(e){var i,n=e.buffered,o=[];for(i=0;i<n.length;i++)o.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(o,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}},bufferedInfo:function(e,t,r){var i,n,o,a,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 c=u.length;if(c){var l=u[c-1].end;e[s].start-l<r?e[s].end>l&&(u[c-1].end=e[s].end):u.push(e[s])}else u.push(e[s])}for(s=0,i=0,n=o=t;s<u.length;s++){var d=u[s].start,f=u[s].end;if(t+r>=d&&t<f)n=d,i=(o=f)-t;else if(t+r<d){a=d;break}}return{len:i,start:n,end:o,nextStart:a}}},I=r(7),x=r(5),C=r.n(x),M=r(9),P=r.n(M);function L(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}var R=L(),N=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hls=t,this.id=r;var i=this.observer=new C.a,n=t.config;i.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];i.emit.apply(i,[e,e].concat(r))},i.off=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];i.removeListener.apply(i,[e].concat(r))};var o=function(e,r){(r=r||{}).frag=this.frag,r.id=this.id,t.trigger(e,r)}.bind(this);i.on(a.a.FRAG_DECRYPTED,o),i.on(a.a.FRAG_PARSING_INIT_SEGMENT,o),i.on(a.a.FRAG_PARSING_DATA,o),i.on(a.a.FRAG_PARSED,o),i.on(a.a.ERROR,o),i.on(a.a.FRAG_PARSING_METADATA,o),i.on(a.a.FRAG_PARSING_USERDATA,o),i.on(a.a.INIT_PTS_FOUND,o);var c={mp4:R.isTypeSupported("video/mp4"),mpeg:R.isTypeSupported("audio/mpeg"),mp3:R.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(n.enableWorker&&"undefined"!=typeof Worker){u.b.log("demuxing in webworker");var d=void 0;try{d=this.w=P()(10),this.onwmsg=this.onWorkerMessage.bind(this),d.addEventListener("message",this.onwmsg),d.onerror=function(e){t.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:e.message+" ("+e.filename+":"+e.lineno+")"}})},d.postMessage({cmd:"init",typeSupported:c,vendor:l,id:r,config:JSON.stringify(n)})}catch(e){u.b.error("error while initializing DemuxerWorker, fallback on DemuxerInline"),d&&URL.revokeObjectURL(d.objectURL),this.demuxer=new I.a(i,c,n,l),this.w=void 0}}else this.demuxer=new I.a(i,c,n,l)}return e.prototype.destroy=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)},e.prototype.push=function(e,t,r,i,n,o,a,s){var c=this.w,l=isNaN(n.startDTS)?n.start:n.startDTS,d=n.decryptdata,f=this.frag,h=!(f&&n.cc===f.cc),p=!(f&&n.level===f.level),m=f&&n.sn===f.sn+1,v=!p&&m;if(h&&u.b.log(this.id+":discontinuity detected"),p&&u.b.log(this.id+":switch detected"),this.frag=n,c)c.postMessage({cmd:"demux",data:e,decryptdata:d,initSegment:t,audioCodec:r,videoCodec:i,timeOffset:l,discontinuity:h,trackSwitch:p,contiguous:v,duration:o,accurateTimeOffset:a,defaultInitPTS:s},e instanceof ArrayBuffer?[e]:[]);else{var g=this.demuxer;g&&g.push(e,d,t,r,i,l,h,p,v,o,a,s)}},e.prototype.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":URL.revokeObjectURL(this.w.objectURL);break;case a.a.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)}},e}();function j(e,t,r){var i=e[t],n=e[r],o=n.startPTS;isNaN(o)?n.start=r>t?i.start+i.duration:Math.max(i.start-n.duration,0):r>t?(i.duration=o-i.start,i.duration<0&&u.b.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!")):(n.duration=i.start-o,n.duration<0&&u.b.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!"))}function F(e,t,r,i,n,o){var a=r;if(!isNaN(t.startPTS)){var s=Math.abs(t.startPTS-r);isNaN(t.deltaPTS)?t.deltaPTS=s:t.deltaPTS=Math.max(s,t.deltaPTS),a=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),i=Math.max(i,t.endPTS),n=Math.min(n,t.startDTS),o=Math.max(o,t.endDTS)}var u=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=a,t.endPTS=i,t.startDTS=n,t.endDTS=o,t.duration=i-r;var c,l,d,f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;for(c=f-e.startSN,(l=e.fragments)[c]=t,d=c;d>0;d--)j(l,d,d-1);for(d=c;d<l.length-1;d++)j(l,d,d+1);return e.PTSKnown=!0,u}function B(e,t){var r,i=Math.max(e.startSN,t.startSN)-t.startSN,n=Math.min(e.endSN,t.endSN)-t.startSN,o=t.startSN-e.startSN,a=e.fragments,s=t.fragments,c=0;if(n<i)t.PTSKnown=!1;else{for(var l=i;l<=n;l++){var d=a[o+l],f=s[l];f&&d&&(c=d.cc-f.cc,isNaN(d.startPTS)||(f.start=f.startPTS=d.startPTS,f.endPTS=d.endPTS,f.duration=d.duration,f.backtracked=d.backtracked,f.dropped=d.dropped,r=f))}if(c)for(u.b.log("discontinuity sliding from playlist, take drift into account"),l=0;l<s.length;l++)s[l].cc+=c;if(r)F(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS);else if(o>=0&&o<a.length){var h=a[o].start;for(l=0;l<s.length;l++)s[l].start+=h}t.PTSKnown=e.PTSKnown}}var U={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}};function z(e,t){t.fragments.forEach(function(t){if(t){var r=t.start+e;t.start=t.startPTS=r,t.endPTS=r+t.duration}}),t.PTSKnown=!0}function G(e,t,r){if(function(e,t,r){var i=!1;return t&&t.details&&r&&(r.endCC>r.startCC||e&&e.cc<r.startCC)&&(i=!0),i}(e,t,r)){var i=function(e,t){var r=e.fragments,i=t.fragments;if(i.length&&r.length){var n=function(e,t){for(var r=null,i=0;i<e.length;i+=1){var n=e[i];if(n&&n.cc===t){r=n;break}}return r}(r,i[0].cc);if(n&&(!n||n.startPTS))return n;u.b.log("No frag in previous level to align on")}else u.b.log("No fragments to align")}(t.details,r);i&&(u.b.log("Adjusting PTS using last level due to CC increase within current level"),z(i.start,r))}if(!1===r.PTSKnown&&t&&t.details){var n=t.details.programDateTime,o=(r.programDateTime-n)/1e3+t.details.fragments[0].start;isNaN(o)||(u.b.log("adjusting PTS using programDateTime delta, sliding:"+o.toFixed(3)),z(o,r))}}var W=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}}();var H={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"},V=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.MANIFEST_LOADING,a.a.MANIFEST_PARSED,a.a.LEVEL_LOADED,a.a.KEY_LOADED,a.a.FRAG_LOADED,a.a.FRAG_LOAD_EMERGENCY_ABORTED,a.a.FRAG_PARSING_INIT_SEGMENT,a.a.FRAG_PARSING_DATA,a.a.FRAG_PARSED,a.a.ERROR,a.a.AUDIO_TRACK_SWITCHING,a.a.AUDIO_TRACK_SWITCHED,a.a.BUFFER_CREATED,a.a.BUFFER_APPENDED,a.a.BUFFER_FLUSHED));return i.config=r.config,i.audioCodecSwap=!1,i.ticks=0,i._state=H.STOPPED,i.ontick=i.tick.bind(i),i}return 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)}(t,e),t.prototype.destroy=function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),l.prototype.destroy.call(this),this.state=H.STOPPED},t.prototype.startLoad=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&&(u.b.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=H.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=H.STOPPED},t.prototype.stopLoad=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=H.STOPPED,this.forceStartLoad=!1},t.prototype.tick=function(){this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},t.prototype.doTick=function(){switch(this.state){case H.ERROR:break;case H.BUFFER_FLUSHING:this.fragLoadError=0;break;case H.IDLE:this._doTickIdle();break;case H.WAITING_LEVEL:var e=this.levels[this.level];e&&e.details&&(this.state=H.IDLE);break;case H.FRAG_LOADING_WAITING_RETRY:var t=performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(u.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=H.IDLE);break;case H.ERROR:case H.STOPPED:case H.FRAG_LOADING:case H.PARSING:case H.PARSED:case H.ENDED:}this._checkBuffer(),this._checkFragmentChanged()},t.prototype._doTickIdle=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,o=this.levels[n];if(o){var s=o.bitrate,c=void 0;c=s?Math.max(8*t.maxBufferSize/s,t.maxBufferLength):t.maxBufferLength,c=Math.min(c,t.maxMaxBufferLength);var l=D.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,t.maxBufferHole),d=l.len;if(!(d>=c)){u.b.trace("buffer length of "+d.toFixed(3)+" is below max of "+c.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=n;var f=o.details;if(void 0===f||!0===f.live&&this.levelLastLoaded!==n)this.state=H.WAITING_LEVEL;else{var h=this.fragPrevious;if(!f.live&&h&&!h.backtracked&&h.sn===f.endSN&&!l.nextStart)if(Math.min(r.duration,h.start+h.duration)-Math.max(l.end,h.start)<=Math.max(.2,h.duration)){var p={};return this.altAudio&&(p.type="video"),this.hls.trigger(a.a.BUFFER_EOS,p),void(this.state=H.ENDED)}this._fetchPayloadOrEos(i,l,f)}}}}},t.prototype._fetchPayloadOrEos=function(e,t,r){var i=this.fragPrevious,n=this.level,o=r.fragments,a=o.length;if(0!==a){var s=o[0].start,c=o[a-1].start+o[a-1].duration,l=t.end,d=void 0;if(r.initSegment&&!r.initSegment.data)d=r.initSegment;else if(r.live){var f=this.config.initialLiveManifestSize;if(a<f)return void u.b.warn("Can not start playback of a level, reason: not enough fragments "+a+" < "+f);if(null===(d=this._ensureFragmentAtLivePoint(r,l,s,c,i,o,a)))return}else l<s&&(d=o[0]);d||(d=this._findFragment(s,i,a,o,l,c,r)),d&&this._loadFragmentOrKey(d,n,r,e,l)}},t.prototype._ensureFragmentAtLivePoint=function(e,t,r,i,n,o,a){var s=this.hls.config,c=this.media,l=void 0,d=void 0!==s.liveMaxLatencyDuration?s.liveMaxLatencyDuration:s.liveMaxLatencyDurationCount*e.targetduration;if(t<Math.max(r-s.maxFragLookUpTolerance,i-d)){var f=this.liveSyncPosition=this.computeLivePosition(r,e);u.b.log("buffer end: "+t.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+f.toFixed(3)),t=f,c&&c.readyState&&c.duration>f&&(c.currentTime=f),this.nextLoadPosition=f}if(e.PTSKnown&&t>i&&c&&c.readyState)return null;if(this.startFragRequested&&!e.PTSKnown){if(n){var h=n.sn+1;if(h>=e.startSN&&h<=e.endSN){var p=o[h-e.startSN];n.cc===p.cc&&(l=p,u.b.log("live playlist, switching playlist, load frag with next SN: "+l.sn))}l||(l=k.search(o,function(e){return n.cc-e.cc}))&&u.b.log("live playlist, switching playlist, load frag with same CC: "+l.sn)}l||(l=o[Math.min(a-1,Math.round(a/2))],u.b.log("live playlist, switching playlist, unknown, load middle frag : "+l.sn))}return l},t.prototype._findFragment=function(e,t,r,i,n,o,a){var s=this.hls.config,c=void 0,l=void 0,d=s.maxFragLookUpTolerance,f=t?i[t.sn-i[0].sn+1]:void 0,h=function(e){var t=Math.min(d,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-t<=n?1:e.start-t>n&&e.start?-1:0};if(n<o?(n>o-d&&(d=0),l=f&&!h(f)?f:k.search(i,h)):l=i[r-1],l){var p=(c=l).sn-a.startSN,m=t&&c.level===t.level,v=i[p-1],g=i[p+1];if(t&&c.sn===t.sn)if(m&&!c.backtracked)if(c.sn<a.endSN){var y=t.deltaPTS;y&&y>s.maxBufferHole&&t.dropped&&p?(c=v,u.b.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--):(c=g,u.b.log("SN just loaded, load next one: "+c.sn))}else c=null;else c.backtracked&&(g&&g.backtracked?(u.b.warn("Already backtracked from fragment "+g.sn+", will not backtrack to fragment "+c.sn+". Loading fragment "+g.sn),c=g):(u.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),c.dropped=0,v?(v.loadCounter&&v.loadCounter--,(c=v).backtracked=!0):p&&(c=null)))}return c},t.prototype._loadFragmentOrKey=function(e,t,r,i,n){var o=this.hls,c=o.config;if(!e.decryptdata||null==e.decryptdata.uri||null!=e.decryptdata.key){if(u.b.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 l=c.fragLoadingLoopThreshold;if(e.loadCounter>l&&Math.abs(this.fragLoadIdx-e.loadIdx)<l)return void o.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:e})}else e.loadCounter=1;return e.loadIdx=this.fragLoadIdx,e.autoLevel=o.autoLevelEnabled,e.bitrateTest=this.bitrateTest,this.fragCurrent=e,this.startFragRequested=!0,isNaN(e.sn)||e.bitrateTest||(this.nextLoadPosition=e.start+e.duration),o.trigger(a.a.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new N(o,"main")),void(this.state=H.FRAG_LOADING)}u.b.log("Loading key for "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t),this.state=H.KEY_LOADING,o.trigger(a.a.KEY_LOADING,{frag:e})},t.prototype.getBufferedFrag=function(e){return k.search(this._bufferedFrags,function(t){return e<t.startPTS?-1:e>t.endPTS?1:0})},t.prototype.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.endPTS+.5):null},t.prototype._checkFragmentChanged=function(){var e,t,r=this.media;if(r&&r.readyState&&!1===r.seeking&&((t=r.currentTime)>r.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=t),D.isBuffered(r,t)?e=this.getBufferedFrag(t):D.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(a.a.FRAG_CHANGED,{frag:i});var n=i.level;this.fragPlaying&&this.fragPlaying.level===n||this.hls.trigger(a.a.LEVEL_SWITCHED,{level:n}),this.fragPlaying=i}}},t.prototype.immediateLevelSwitch=function(){if(u.b.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,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},t.prototype.immediateLevelSwitchEnd=function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,D.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())},t.prototype.nextLevelSwitch=function(){var e=this.media;if(e&&e.readyState){var t,r=void 0,i=void 0;if(void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),(t=this.getBufferedFrag(e.currentTime))&&t.startPTS>1&&this.flushMainBuffer(0,t.startPTS-1),e.paused)r=0;else{var n=this.hls.nextLoadLevel,o=this.levels[n],a=this.fragLastKbps;r=a&&this.fragCurrent?this.fragCurrent.duration*o.bitrate/(1e3*a)+1:0}if((i=this.getBufferedFrag(e.currentTime+r))&&(i=this.followingBufferedFrag(i))){var s=this.fragCurrent;s&&s.loader&&s.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(i.maxStartPTS,Number.POSITIVE_INFINITY)}}},t.prototype.flushMainBuffer=function(e,t){this.state=H.BUFFER_FLUSHING;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(a.a.BUFFER_FLUSHING,r)},t.prototype.onMediaAttached=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)},t.prototype.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(u.b.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()},t.prototype.onMediaSeeking=function(){var e=this.media,t=e?e.currentTime:void 0,r=this.config;isNaN(t)||u.b.log("media seeking to "+t.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:e,n=D.bufferInfo(i,t,this.config.maxBufferHole);if(this.state===H.FRAG_LOADING){var o=this.fragCurrent;if(0===n.len&&o){var a=r.maxFragLookUpTolerance,s=o.start-a,c=o.start+o.duration+a;t<s||t>c?(o.loader&&(u.b.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),o.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=H.IDLE):u.b.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===H.ENDED&&(0===n.len&&(this.fragPrevious=0),this.state=H.IDLE);e&&(this.lastCurrentTime=t),this.state!==H.FRAG_LOADING&&void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*r.fragLoadingLoopThreshold),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=t),this.tick()},t.prototype.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:void 0;isNaN(t)||u.b.log("media seeked to "+t.toFixed(3)),this.tick()},t.prototype.onMediaEnded=function(){u.b.log("media ended"),this.startPosition=this.lastCurrentTime=0},t.prototype.onManifestLoading=function(){u.b.log("trigger BUFFER_RESET"),this.hls.trigger(a.a.BUFFER_RESET),this._bufferedFrags=[],this.stalled=!1,this.startPosition=this.lastCurrentTime=0},t.prototype.onManifestParsed=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&&u.b.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1;var n=this.config;(n.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(n.startPosition)},t.prototype.onLevelLoaded=function(e){var t=e.details,r=e.level,i=this.levels[this.levelLastLoaded],n=this.levels[r],o=t.totalduration,s=0;if(u.b.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+o),t.live){var c=n.details;c&&t.fragments.length>0?(B(c,t),s=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(s,c),t.PTSKnown&&!isNaN(s)?u.b.log("live playlist sliding:"+s.toFixed(3)):(u.b.log("live playlist - outdated PTS, unknown sliding"),G(this.fragPrevious,i,t))):(u.b.log("live playlist - first load, unknown sliding"),t.PTSKnown=!1,G(this.fragPrevious,i,t))}else t.PTSKnown=!1;if(n.details=t,this.levelLastLoaded=r,this.hls.trigger(a.a.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var l=t.startTimeOffset;isNaN(l)?t.live?(this.startPosition=this.computeLivePosition(s,t),u.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(l<0&&(u.b.log("negative start time offset "+l+", count from end of last fragment"),l=s+o+l),u.b.log("start time offset found in playlist, adjust startPosition to "+l),this.startPosition=l),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===H.WAITING_LEVEL&&(this.state=H.IDLE),this.tick()},t.prototype.onKeyLoaded=function(){this.state===H.KEY_LOADING&&(this.state=H.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===H.FRAG_LOADING&&t&&"main"===r.type&&r.level===t.level&&r.sn===t.sn){var i=e.stats,n=this.levels[t.level],o=n.details;if(u.b.log("Loaded "+t.sn+" of ["+o.startSN+" ,"+o.endSN+"],level "+t.level),this.bitrateTest=!1,this.stats=i,!0===r.bitrateTest&&this.hls.nextLoadLevel)this.state=H.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=performance.now(),this.hls.trigger(a.a.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=H.IDLE,i.tparsed=i.tbuffered=performance.now(),o.initSegment.data=e.payload,this.hls.trigger(a.a.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else{this.state=H.PARSING;var s=o.totalduration,c=t.level,l=t.sn,d=this.config.defaultAudioCodec||n.audioCodec;this.audioCodecSwap&&(u.b.log("swapping playlist audio codec"),void 0===d&&(d=this.lastAudioCodec),d&&(d=-1!==d.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,u.b.log("Parsing "+l+" of ["+o.startSN+" ,"+o.endSN+"],level "+c+", cc "+t.cc);var f=this.demuxer;f||(f=this.demuxer=new N(this.hls,"main"));var h=this.media,p=!(h&&h.seeking)&&(o.PTSKnown||!o.live),m=o.initSegment?o.initSegment.data:[];f.push(e.payload,m,d,n.videoCodec,t,s,p,void 0)}}this.fragLoadError=0},t.prototype.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===H.PARSING){var i,n,o=e.tracks;if(o.audio&&this.altAudio&&delete o.audio,n=o.audio){var s=this.levels[this.level].audioCodec,c=navigator.userAgent.toLowerCase();s&&this.audioCodecSwap&&(u.b.log("swapping playlist audio codec"),s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===c.indexOf("firefox")&&(s="mp4a.40.5"),-1!==c.indexOf("android")&&"audio/mpeg"!==n.container&&(s="mp4a.40.2",u.b.log("Android: force audio codec to "+s)),n.levelCodec=s,n.id=e.id}for(i in(n=o.video)&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=e.id),this.hls.trigger(a.a.BUFFER_CODECS,o),o){n=o[i],u.b.log("main track:"+i+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var l=n.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(a.a.BUFFER_APPENDING,{type:i,data:l,parent:"main",content:"initSegment"}))}this.tick()}},t.prototype.onFragParsingData=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===H.PARSING){var n=this.levels[this.level],o=r;if(isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),u.b.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(o.dropped=e.dropped,o.dropped)if(o.backtracked)u.b.warn("Already backtracked on this fragment, appending with the gap");else{var s=n.details;if(!s||o.sn!==s.startSN)return u.b.warn("missing video frame(s), backtracking fragment"),o.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=H.IDLE,this.fragPrevious=o,void this.tick();u.b.warn("missing video frame(s) on first frag, appending with gap")}else o.backtracked=!1;var c=F(n.details,o,e.startPTS,e.endPTS,e.startDTS,e.endDTS),l=this.hls;l.trigger(a.a.LEVEL_PTS_UPDATED,{details:n.details,level:this.level,drift:c,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach(function(r){r&&r.length&&t.state===H.PARSING&&(t.appended=!0,t.pendingBuffering=!0,l.trigger(a.a.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))}),this.tick()}},t.prototype.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===H.PARSING&&(this.stats.tparsed=performance.now(),this.state=H.PARSED,this._checkAppendedParsed())},t.prototype.onAudioTrackSwitching=function(e){var t=!!e.url,r=e.id;if(!t){if(this.mediaBuffer!==this.media){u.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(u.b.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=H.IDLE}var n=this.hls;n.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),n.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}},t.prototype.onAudioTrackSwitched=function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(u.b.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()},t.prototype.onBufferCreated=function(e){var t=e.tracks,r=void 0,i=void 0,n=!1;for(var o in t){var a=t[o];"main"===a.id?(i=o,r=a,"video"===o&&(this.videoBuffer=t[o].buffer)):n=!0}n&&r?(u.b.log("alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},t.prototype.onBufferAppended=function(e){if("main"===e.parent){var t=this.state;t!==H.PARSING&&t!==H.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},t.prototype._checkAppendedParsed=function(){if(!(this.state!==H.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;u.b.log("main buffered : "+U.toString(t.buffered));var r=this._bufferedFrags.filter(function(e){return D.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(a.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.state=H.IDLE}this.tick()}},t.prototype.onError=function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=!!this.media&&D.isBuffered(this.media,this.media.currentTime)&&D.isBuffered(this.media,this.media.currentTime+.5);switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:if(!e.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var i=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);t.loadCounter=0,u.b.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=H.FRAG_LOADING_WAITING_RETRY}else u.b.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=H.ERROR;break;case s.a.FRAG_LOOP_LOADING_ERROR:e.fatal||(r?(this._reduceMaxBufferLength(t.duration),this.state=H.IDLE):t.autoLevel&&0!==t.level||(e.fatal=!0,this.state=H.ERROR));break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==H.ERROR&&(e.fatal?(this.state=H.ERROR,u.b.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==H.WAITING_LEVEL||(this.state=H.IDLE));break;case s.a.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==H.PARSING&&this.state!==H.PARSED||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=H.IDLE):(u.b.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},t.prototype._reduceMaxBufferLength=function(e){var t=this.config;t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,u.b.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*t.fragLoadingLoopThreshold))},t.prototype._checkBuffer=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 o=e.seeking?r:this.startPosition,c=D.isBuffered(i,o),l=n.start(0),d=!c&&Math.abs(o-l)<t.maxSeekHole;(r!==o||d)&&(u.b.log("target start position:"+o),d&&(o=l,u.b.log("target start position not buffered, seek to buffered.start(0) "+o)),u.b.log("adjust currentTime from "+r+" to "+o),e.currentTime=o)}else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var f=D.bufferInfo(e,r,0),h=!(e.paused||e.ended||0===e.buffered.length);if(r!==this.lastCurrentTime)this.stallReported&&(u.b.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(h){var p=performance.now(),m=this.hls;if(this.stalled){var v=p-this.stalled,g=f.len,y=this.nudgeRetry||0;if(g<=.5&&v>1e3*t.lowBufferWatchdogPeriod){this.stallReported||(this.stallReported=!0,u.b.warn("playback stalling in low buffer @"+r),m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:g}));var _=f.nextStart,b=_-r;if(_&&b<t.maxSeekHole&&b>0){this.nudgeRetry=++y;var w=y*t.nudgeOffset;u.b.log("adjust currentTime from "+e.currentTime+" to next buffered @ "+_+" + nudge "+w),e.currentTime=_+w,this.stalled=void 0,m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_SEEK_OVER_HOLE,fatal:!1,hole:_+w-r})}}else if(g>.5&&v>1e3*t.highBufferWatchdogPeriod)if(this.stallReported||(this.stallReported=!0,u.b.warn("playback stalling in high buffer @"+r),m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:g})),this.stalled=void 0,this.nudgeRetry=++y,y<t.nudgeMaxRetry){var E=e.currentTime,S=E+y*t.nudgeOffset;u.b.log("adjust currentTime from "+E+" to "+S),e.currentTime=S,m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_NUDGE_ON_STALL,fatal:!1})}else u.b.error("still stuck in high buffer @"+r+" after "+t.nudgeMaxRetry+", raise fatal error"),m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!0})}else this.stalled=p,this.stallReported=!1}}}},t.prototype.onFragLoadEmergencyAborted=function(){this.state=H.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},t.prototype.onBufferFlushed=function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;this._bufferedFrags=this._bufferedFrags.filter(function(t){return D.isBuffered(e,(t.startPTS+t.endPTS)/2)}),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.state=H.IDLE,this.fragPrevious=null},t.prototype.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},t.prototype.computeLivePosition=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)},W(t,[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,u.b.log("main stream:"+t+"->"+e),this.hls.trigger(a.a.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}(l),Y=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}}();var K=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MANIFEST_LOADED,a.a.LEVEL_LOADED,a.a.FRAG_LOADED,a.a.ERROR));return i.canload=!1,i.currentLevelIndex=null,i.manualLevelIndex=-1,i.timer=null,i}return 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)}(t,e),t.prototype.destroy=function(){this.cleanTimer(),this.manualLevelIndex=-1},t.prototype.cleanTimer=function(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)},t.prototype.startLoad=function(){var e=this._levels;this.canload=!0,this.levelRetryCount=0,e&&e.forEach(function(e){e.loadError=0;var t=e.details;t&&t.live&&(e.details=void 0)}),null!==this.timer&&this.loadLevel()},t.prototype.stopLoad=function(){this.canload=!1},t.prototype.onManifestLoaded=function(e){var t=[],r=void 0,i={},n=null,o=!1,c=!1,l=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),d=[];if(e.levels.forEach(function(e){e.loadError=0,e.fragmentError=!1,o=o||!!e.videoCodec,c=c||!!e.audioCodec||!(!e.attrs||!e.attrs.AUDIO),!0===l&&e.audioCodec&&-1!==e.audioCodec.indexOf("mp4a.40.34")&&(e.audioCodec=void 0),void 0===(n=i[e.bitrate])?(e.url=[e.url],e.urlId=0,i[e.bitrate]=e,t.push(e)):n.url.push(e.url)}),!0===o&&!0===c&&(t=t.filter(function(e){return!!e.videoCodec})),t=t.filter(function(e){var t=e.audioCodec,r=e.videoCodec;return(!t||m(t))&&(!r||m(r))}),e.audioTracks&&(d=e.audioTracks.filter(function(e){return!e.audioCodec||m(e.audioCodec,"audio")})),t.length>0){r=t[0].bitrate,t.sort(function(e,t){return e.bitrate-t.bitrate}),this._levels=t;for(var f=0;f<t.length;f++)if(t[f].bitrate===r){this._firstLevel=f,u.b.log("manifest loaded,"+t.length+" level(s) found, first bitrate:"+r);break}this.hls.trigger(a.a.MANIFEST_PARSED,{levels:t,audioTracks:d,firstLevel:this._firstLevel,stats:e.stats,audio:c,video:o,altAudio:d.length>0})}else this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:this.hls.url,reason:"no level with compatible codecs found in manifest"})},t.prototype.setLevelInternal=function(e){var t=this._levels,r=this.hls;if(e>=0&&e<t.length){if(this.cleanTimer(),this.currentLevelIndex!==e){u.b.log("switching to level "+e),this.currentLevelIndex=e;var i=t[e];i.level=e,r.trigger(a.a.LEVEL_SWITCH,i),r.trigger(a.a.LEVEL_SWITCHING,i)}var n=t[e],o=n.details;if(!o||!0===o.live){var c=n.urlId;r.trigger(a.a.LEVEL_LOADING,{url:n.url[c],level:e,id:c})}}else r.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:e,fatal:!1,reason:"invalid level idx"})},t.prototype.onError=function(e){if(!0!==e.fatal){var t=!1,r=!1,i=void 0;switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.FRAG_LOOP_LOADING_ERROR:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:i=e.frag.level,r=!0;break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i=e.context.level,t=!0;break;case s.a.REMUX_ALLOC_ERROR:i=e.level,t=!0}void 0!==i&&this.recoverLevel(e,i,t,r)}else e.type===s.b.NETWORK_ERROR&&this.cleanTimer()},t.prototype.recoverLevel=function(e,t,r,i){var n=this,o=this.hls.config,a=e.details,s=this._levels[t],c=void 0,l=void 0,d=void 0;if(s.loadError++,s.fragmentError=i,!0===r){if(!(this.levelRetryCount+1<=o.levelLoadingMaxRetry))return u.b.error("level controller, cannot recover from "+a+" error"),this.currentLevelIndex=null,this.cleanTimer(),void(e.fatal=!0);l=Math.min(Math.pow(2,this.levelRetryCount)*o.levelLoadingRetryDelay,o.levelLoadingMaxRetryTimeout),this.timer=setTimeout(function(){return n.loadLevel()},l),e.levelRetry=!0,this.levelRetryCount++,u.b.warn("level controller, "+a+", retry in "+l+" ms, current retry count is "+this.levelRetryCount)}!0!==r&&!0!==i||((c=s.url.length)>1&&s.loadError<c?(u.b.warn("level controller, "+a+" for level "+t+": switching to redundant stream id "+s.urlId),s.urlId=(s.urlId+1)%c,s.details=void 0):-1===this.manualLevelIndex?(d=0===t?this._levels.length-1:t-1,u.b.warn("level controller, "+a+": switch to "+d),this.hls.nextAutoLevel=this.currentLevelIndex=d):!0===i&&(u.b.warn("level controller, "+a+": reload a fragment"),this.currentLevelIndex=null))},t.prototype.onFragLoaded=function(e){var t=e.frag;if(void 0!==t&&"main"===t.type){var r=this._levels[t.level];void 0!==r&&(r.fragmentError=!1,r.loadError=0,this.levelRetryCount=0)}},t.prototype.onLevelLoaded=function(e){var t=this,r=e.level;if(r===this.currentLevelIndex){var i=this._levels[r];!1===i.fragmentError&&(i.loadError=0,this.levelRetryCount=0);var n=e.details;if(n.live){var o=1e3*(n.averagetargetduration?n.averagetargetduration:n.targetduration),a=i.details;a&&n.endSN===a.endSN&&(o/=2,u.b.log("same live playlist, reload twice faster")),o-=performance.now()-e.stats.trequest,o=Math.max(1e3,Math.round(o)),u.b.log("live playlist, reload in "+o+" ms"),this.timer=setTimeout(function(){return t.loadLevel()},o)}else this.cleanTimer()}},t.prototype.loadLevel=function(){var e=void 0,t=void 0;null!==this.currentLevelIndex&&!0===this.canload&&void 0!==(e=this._levels[this.currentLevelIndex])&&e.url.length>0&&(t=e.urlId,this.hls.trigger(a.a.LEVEL_LOADING,{url:e.url[t],level:this.currentLevelIndex,id:t}))},Y(t,[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;t&&(e=Math.min(e,t.length-1),this.currentLevelIndex===e&&void 0!==t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=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.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}]),t}(l),Z=r(3);var Q=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.FRAG_PARSING_METADATA));return i.id3Track=void 0,i.media=void 0,i}return 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)}(t,e),t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onMediaAttached=function(e){this.media=e.media,this.media},t.prototype.onMediaDetaching=function(){this.media=void 0},t.prototype.onFragParsingMetadata=function(e){var t=e.frag,r=e.samples;this.id3Track||(this.id3Track=this.media.addTextTrack("metadata","id3"),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,n=0;n<r.length;n++){var o=Z.a.getID3Frames(r[n].data);if(o){var a=r[n].pts,s=n<r.length-1?r[n+1].pts:t.endPTS;a===s&&(s+=1e-4);for(var u=0;u<o.length;u++){var c=o[u];if(!Z.a.isTimeStampFrame(c)){var l=new i(a,s,"");l.value=c,this.id3Track.addCue(l)}}}}},t}(l);var X=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=0,this.totalWeight_=0}return e.prototype.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},e.prototype.getTotalWeight=function(){return this.totalWeight_},e.prototype.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}return this.estimate_},e}();var q=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hls=t,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new X(r),this.fast_=new X(i)}return e.prototype.sample=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)},e.prototype.canEstimate=function(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_},e.prototype.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.prototype.destroy=function(){},e}(),J=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}}();var ee=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.FRAG_LOADING,a.a.FRAG_LOADED,a.a.FRAG_BUFFERED,a.a.ERROR));return i.lastLoadedFragLevel=0,i._nextAutoLevel=-1,i.hls=r,i.timer=null,i._bwEstimator=null,i.onCheck=i._abandonRulesCheck.bind(i),i}return 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)}(t,e),t.prototype.destroy=function(){this.clearTimer(),l.prototype.destroy.call(this)},t.prototype.onFragLoading=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,o=r.config,a=void 0,s=void 0;n?(a=o.abrEwmaFastLive,s=o.abrEwmaSlowLive):(a=o.abrEwmaFastVoD,s=o.abrEwmaSlowVoD),this._bwEstimator=new q(r,s,a,o.abrEwmaDefaultEstimate)}this.fragCurrent=t}},t.prototype._abandonRulesCheck=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 u.b.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);var o=i.stats;if(t&&o&&(!t.paused&&0!==t.playbackRate||!t.readyState)&&r.autoLevel&&r.level){var s=performance.now()-o.trequest,c=Math.abs(t.playbackRate);if(s>500*r.duration/c){var l=e.levels,d=Math.max(1,o.bw?o.bw/8:1e3*o.loaded/s),f=l[r.level],h=f.realBitrate?Math.max(f.realBitrate,f.bitrate):f.bitrate,p=o.total?o.total:Math.max(o.loaded,Math.round(r.duration*h/8)),m=t.currentTime,v=(p-o.loaded)/d,g=(D.bufferInfo(t,m,e.config.maxBufferHole).end-m)/c;if(g<2*r.duration/c&&v>g){var y=void 0,_=void 0;for(_=r.level-1;_>n;_--){var b=l[_].realBitrate?Math.max(l[_].realBitrate,l[_].bitrate):l[_].bitrate;if((y=r.duration*b/(6.4*d))<g)break}y<v&&(u.b.warn("loading too slow, abort fragment loading and switch to level "+_+":fragLoadedDelay["+_+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+y.toFixed(1)+"<"+v.toFixed(1)+":"+g.toFixed(1)),e.nextLoadLevel=_,this._bwEstimator.sample(s,o.loaded),i.abort(),this.clearTimer(),e.trigger(a.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,stats:o}))}}}},t.prototype.onFragLoaded=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 o=e.stats;o.tparsed=o.tbuffered=o.tload,this.onFragBuffered(e)}}},t.prototype.onFragBuffered=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;u.b.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}},t.prototype.onError=function(e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},t.prototype.clearTimer=function(){clearInterval(this.timer),this.timer=null},t.prototype._findBestLevel=function(e,t,r,i,n,o,a,s,c){for(var l=n;l>=i;l--){var d=c[l].details,f=d?d.totalduration/d.fragments.length:t,h=!!d&&d.live,p=void 0;p=l<=e?a*r:s*r;var m=c[l].realBitrate?Math.max(c[l].realBitrate,c[l].bitrate):c[l].bitrate,v=m*f/p;if(u.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+l+"/"+Math.round(p)+"/"+m+"/"+f+"/"+o+"/"+v),p>m&&(!v||h&&!this.bitrateTestDelay||v<o))return l}return-1},J(t,[{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,o=e.media,a=this.lastLoadedFragLevel,s=this.fragCurrent?this.fragCurrent.duration:0,c=o?o.currentTime:0,l=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,d=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,f=(D.bufferInfo(o,c,i.maxBufferHole).end-c)/l,h=this._findBestLevel(a,s,d,n,t,f,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(h>=0)return h;u.b.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,m=i.abrBandWidthFactor,v=i.abrBandWidthUpFactor;if(0===f){var g=this.bitrateTestDelay;if(g)p=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-g,u.b.trace("bitrate test took "+Math.round(1e3*g)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*p)+" ms"),m=v=1}return h=this._findBestLevel(a,s,d,n,t,f+p,m,v,r),Math.max(h,0)}}]),t}(l);var te=L(),re=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHING,a.a.MEDIA_DETACHING,a.a.MANIFEST_PARSED,a.a.BUFFER_RESET,a.a.BUFFER_APPENDING,a.a.BUFFER_CODECS,a.a.BUFFER_EOS,a.a.BUFFER_FLUSHING,a.a.LEVEL_PTS_UPDATED,a.a.LEVEL_UPDATED));return i._msDuration=null,i._levelDuration=null,i._live=null,i._objectUrl=null,i.onsbue=i.onSBUpdateEnd.bind(i),i.onsbe=i.onSBUpdateError.bind(i),i.pendingTracks={},i.tracks={},i}return 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)}(t,e),t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onLevelPtsUpdated=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,u.b.warn("can not abort audio buffer: "+e)}n?this.audioTimestampOffset=e.start:(u.b.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}},t.prototype.onManifestParsed=function(e){var t=e.audio,r=e.video||e.levels.length&&e.audio,i=0;e.altAudio&&(t||r)&&(i=(t?1:0)+(r?1:0),u.b.log(i+" sourceBuffer(s) expected")),this.sourceBufferNb=i},t.prototype.onMediaAttaching=function(e){var t=this.media=e.media;if(t){var r=this.mediaSource=new te;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),this._objectUrl=t.src}},t.prototype.onMediaDetaching=function(){u.b.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){u.b.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._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):u.b.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(a.a.MEDIA_DETACHED)},t.prototype.onMediaSourceOpen=function(){u.b.log("media source opened"),this.hls.trigger(a.a.MEDIA_ATTACHED,{media:this.media});var e=this.mediaSource;e&&e.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()},t.prototype.checkPendingTracks=function(){var e=this.pendingTracks,t=Object.keys(e).length;t&&(this.sourceBufferNb<=t||0===this.sourceBufferNb)&&(this.createSourceBuffers(e),this.pendingTracks={},this.doAppending())},t.prototype.onMediaSourceClose=function(){u.b.log("media source closed")},t.prototype.onMediaSourceEnded=function(){u.b.log("media source ended")},t.prototype.onSBUpdateEnd=function(){if(this.audioTimestampOffset){var e=this.sourceBuffer.audio;u.b.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(a.a.BUFFER_APPENDED,{parent:t,pending:r}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()},t.prototype.onSBUpdateError=function(e){u.b.error("sourceBuffer error:",e),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1})},t.prototype.onBufferReset=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},t.prototype.onBufferCodecs=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()}},t.prototype.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;for(var i in e)if(!t[i]){var n=e[i],o=n.levelCodec||n.codec,c=n.container+";codecs="+o;u.b.log("creating sourceBuffer("+c+")");try{var l=t[i]=r.addSourceBuffer(c);l.addEventListener("updateend",this.onsbue),l.addEventListener("error",this.onsbe),this.tracks[i]={codec:o,container:n.container},n.buffer=l}catch(e){u.b.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:c})}}this.hls.trigger(a.a.BUFFER_CREATED,{tracks:e})},t.prototype.onBufferAppending=function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())},t.prototype.onBufferAppendFail=function(e){u.b.error("sourceBuffer error:",e.event),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1})},t.prototype.onBufferEos=function(e){var t=this.sourceBuffer,r=e.type;for(var i in t)r&&i!==r||t[i].ended||(t[i].ended=!0,u.b.log(i+" sourceBuffer now EOS"));this.checkEos()},t.prototype.checkEos=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)}u.b.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){u.b.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}else this._needsEos=!1},t.prototype.onBufferFlushing=function(e){this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}),this.flushBufferCounter=0,this.doFlush()},t.prototype.onLevelUpdated=function(e){var t=e.details;t.fragments.length>0&&(this._levelDuration=t.totalduration+t.fragments[0].start,this._live=t.live,this.updateMediaElementDuration())},t.prototype.updateMediaElementDuration=function(){var e,t=this.hls.config;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer)if(!0===this.sourceBuffer[r].updating)return;e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(u.b.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||e===1/0||isNaN(e))&&(u.b.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},t.prototype.doFlush=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){u.b.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(a.a.BUFFER_FLUSHED)}},t.prototype.doAppending=function(){var e=this.hls,t=this.sourceBuffer,r=this.segments;if(Object.keys(t).length){if(this.media.error)return this.segments=[],void u.b.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){u.b.error("error while trying to append buffer:"+t.message),r.unshift(i);var o={type:s.b.MEDIA_ERROR,parent:i.parent};if(22===t.code)return this.segments=[],o.details=s.a.BUFFER_FULL_ERROR,o.fatal=!1,void e.trigger(a.a.ERROR,o);if(this.appendError?this.appendError++:this.appendError=1,o.details=s.a.BUFFER_APPEND_ERROR,this.appendError>e.config.appendErrorMaxRetry)return u.b.log("fail "+e.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],o.fatal=!0,void e.trigger(a.a.ERROR,o);o.fatal=!1,e.trigger(a.a.ERROR,o)}}}},t.prototype.flushBuffer=function(e,t,r){var i,n,o,a,s,c,l=this.sourceBuffer;if(Object.keys(l).length){if(u.b.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+e+"/"+t),this.flushBufferCounter<this.appended){for(var d in l)if(!r||d===r){if((i=l[d]).ended=!1,i.updating)return u.b.warn("cannot flush, sb updating in progress"),!1;try{for(n=0;n<i.buffered.length;n++)if(o=i.buffered.start(n),a=i.buffered.end(n),-1!==navigator.userAgent.toLowerCase().indexOf("firefox")&&t===Number.POSITIVE_INFINITY?(s=e,c=t):(s=Math.max(o,e),c=Math.min(a,t)),Math.min(c,a)-s>.5)return this.flushBufferCounter++,u.b.log("flush "+d+" ["+s+","+c+"], of ["+o+","+a+"], pos:"+this.media.currentTime),i.remove(s,c),!1}catch(e){u.b.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else u.b.warn("abort flushing too many retries");u.b.log("buffer flushed")}return!0},t}(l),ie=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}}();var ne=function(e){function t(r){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),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}(this,e.call(this,r,a.a.FPS_DROP_LEVEL_CAPPING,a.a.MEDIA_ATTACHING,a.a.MANIFEST_PARSED))}return 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)}(t,e),t.prototype.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=this.restrictedLevels=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer)))},t.prototype.onFpsDropLevelCapping=function(e){t.isLevelAllowed(e.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(e.droppedLevel)},t.prototype.onMediaAttaching=function(e){this.media=e.media instanceof HTMLVideoElement?e.media:null},t.prototype.onManifestParsed=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())},t.prototype.detectPlayerSize=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}}},t.prototype.getMaxLevel=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)},t.isLevelAllowed=function(e){return-1===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).indexOf(e)},t.getMaxLevelByMediaSize=function(e,t,r){if(!e||e&&!e.length)return-1;for(var i,n,o=e.length-1,a=0;a<e.length;a+=1){var s=e[a];if((s.width>=t||s.height>=r)&&(i=s,!(n=e[a+1])||i.width!==n.width||i.height!==n.height)){o=a;break}}return o},ie(t,[{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:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}]),t}(l);var oe=function(e){function t(r){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),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}(this,e.call(this,r,a.a.MEDIA_ATTACHING))}return 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)}(t,e),t.prototype.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},t.prototype.onMediaAttaching=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))},t.prototype.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,o=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,c=1e3*o/n,l=this.hls;if(l.trigger(a.a.FPS_DROP,{currentDropped:o,currentDecoded:s,totalDroppedFrames:r}),c>0&&o>l.config.fpsDroppedMonitoringThreshold*s){var d=l.currentLevel;u.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=d)&&(d-=1,l.trigger(a.a.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.prototype.checkFPSInterval=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}(l);var ae=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),t&&t.xhrSetup&&(this.xhrSetup=t.xhrSetup)}return e.prototype.destroy=function(){this.abort(),this.loader=null},e.prototype.abort=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},e.prototype.load=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()},e.prototype.loadInternal=function(){var e,t=this.context;e=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()},e.prototype.readystatechange=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 a=t.status;if(a>=200&&a<300){i.tload=Math.max(i.tfirst,performance.now());var s=void 0,c=void 0;c="arraybuffer"===n.responseType?(s=t.response).byteLength:(s=t.responseText).length,i.loaded=i.total=c;var l={url:t.responseURL,data:s};this.callbacks.onSuccess(l,i,n,t)}else i.retry>=o.maxRetry||a>=400&&a<499?(u.b.error(a+" while loading "+n.url),this.callbacks.onError({code:a,text:t.statusText},n,t)):(u.b.warn(a+" 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)},e.prototype.loadtimeout=function(){u.b.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},e.prototype.loadprogress=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}(),se=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}}();var ue=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MANIFEST_LOADING,a.a.MANIFEST_PARSED,a.a.AUDIO_TRACK_LOADED,a.a.ERROR));return i.ticks=0,i.ontick=i.tick.bind(i),i}return 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)}(t,e),t.prototype.destroy=function(){this.cleanTimer(),l.prototype.destroy.call(this)},t.prototype.cleanTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},t.prototype.tick=function(){this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},t.prototype.doTick=function(){this.updateTrack(this.trackId)},t.prototype.onError=function(e){e.fatal&&e.type===s.b.NETWORK_ERROR&&this.cleanTimer()},t.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},t.prototype.onManifestParsed=function(e){var t=this,r=e.audioTracks||[],i=!1;this.tracks=r,this.hls.trigger(a.a.AUDIO_TRACKS_UPDATED,{audioTracks:r});var n=0;r.forEach(function(e){if(e.default&&!i)return t.audioTrack=n,void(i=!0);n++}),!1===i&&r.length&&(u.b.log("no default audio track defined, use first audio track as default"),this.audioTrack=0)},t.prototype.onAudioTrackLoaded=function(e){e.id<this.tracks.length&&(u.b.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&&this.cleanTimer())},t.prototype.setAudioTrackInternal=function(e){if(e>=0&&e<this.tracks.length){this.cleanTimer(),this.trackId=e,u.b.log("switching to audioTrack "+e);var t=this.tracks[e],r=this.hls,i=t.type,n=t.url,o={id:e,type:i,url:n};r.trigger(a.a.AUDIO_TRACK_SWITCH,o),r.trigger(a.a.AUDIO_TRACK_SWITCHING,o);var s=t.details;!n||void 0!==s&&!0!==s.live||(u.b.log("(re)loading playlist for audioTrack "+e),r.trigger(a.a.AUDIO_TRACK_LOADING,{url:n,id:e}))}},t.prototype.updateTrack=function(e){if(e>=0&&e<this.tracks.length){this.cleanTimer(),this.trackId=e,u.b.log("updating audioTrack "+e);var t=this.tracks[e],r=t.url,i=t.details;!r||void 0!==i&&!0!==i.live||(u.b.log("(re)loading playlist for audioTrack "+e),this.hls.trigger(a.a.AUDIO_TRACK_LOADING,{url:r,id:e}))}},se(t,[{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}(l),ce=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}}();var le={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"},de=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.AUDIO_TRACKS_UPDATED,a.a.AUDIO_TRACK_SWITCHING,a.a.AUDIO_TRACK_LOADED,a.a.KEY_LOADED,a.a.FRAG_LOADED,a.a.FRAG_PARSING_INIT_SEGMENT,a.a.FRAG_PARSING_DATA,a.a.FRAG_PARSED,a.a.ERROR,a.a.BUFFER_RESET,a.a.BUFFER_CREATED,a.a.BUFFER_APPENDED,a.a.BUFFER_FLUSHED,a.a.INIT_PTS_FOUND));return i.config=r.config,i.audioCodecSwap=!1,i.ticks=0,i._state=le.STOPPED,i.ontick=i.tick.bind(i),i.initPTS=[],i.waitingFragment=null,i.videoTrackCC=null,i}return 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)}(t,e),t.prototype.destroy=function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),l.prototype.destroy.call(this),this.state=le.STOPPED},t.prototype.onInitPtsFound=function(e){var t=e.id,r=e.frag.cc,i=e.initPTS;"main"===t&&(this.initPTS[r]=i,this.videoTrackCC=r,u.b.log("InitPTS for cc:"+r+" found from video track:"+i),this.state===le.WAITING_INIT_PTS&&this.tick())},t.prototype.startLoad=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?(u.b.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=le.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=le.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=le.STOPPED},t.prototype.stopLoad=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=le.STOPPED},t.prototype.tick=function(){this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},t.prototype.doTick=function(){var e,t,r,i=this.hls,n=i.config;switch(this.state){case le.ERROR:case le.PAUSED:case le.BUFFER_FLUSHING:break;case le.STARTING:this.state=le.WAITING_TRACK,this.loadedmetadata=!1;break;case le.IDLE:var o=this.tracks;if(!o)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 c=this.mediaBuffer?this.mediaBuffer:this.media,l=this.videoBuffer?this.videoBuffer:this.media,d=D.bufferInfo(c,e,n.maxBufferHole),f=D.bufferInfo(l,e,n.maxBufferHole),h=d.len,p=d.end,m=this.fragPrevious,v=Math.max(n.maxBufferLength,f.len),g=this.audioSwitch,y=this.trackId;if((h<v||g)&&y<o.length){if(void 0===(r=o[y].details)){this.state=le.WAITING_TRACK;break}if(!g&&!r.live&&m&&m.sn===r.endSN&&!d.nextStart&&(!this.media.seeking||this.media.duration-p<m.duration/2)){this.hls.trigger(a.a.BUFFER_EOS,{type:"audio"}),this.state=le.ENDED;break}var _=r.fragments,b=_.length,w=_[0].start,E=_[b-1].start+_[b-1].duration,S=void 0;if(g)if(r.live&&!r.PTSKnown)u.b.log("switching audiotrack, live stream, unknown PTS,load first fragment"),p=0;else if(p=e,r.PTSKnown&&e<w){if(!(d.end>w||d.nextStart))return;u.b.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)S=r.initSegment;else if(p<=w){if(S=_[0],null!==this.videoTrackCC&&S.cc!==this.videoTrackCC&&(S=function(e,t){return k.search(e,function(e){return e.cc<t?1:e.cc>t?-1:0})}(_,this.videoTrackCC)),r.live&&S.loadIdx&&S.loadIdx===this.fragLoadIdx){var T=d.nextStart?d.nextStart:w;return u.b.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(T+.05)),void(this.media.currentTime=T+.05)}}else{var O=void 0,A=n.maxFragLookUpTolerance,$=m?_[m.sn-_[0].sn+1]:void 0,I=function(e){var t=Math.min(A,e.duration);return e.start+e.duration-t<=p?1:e.start-t>p&&e.start?-1:0};p<E?(p>E-A&&(A=0),O=$&&!I($)?$:k.search(_,I)):O=_[b-1],O&&(S=O,w=O.start,m&&S.level===m.level&&S.sn===m.sn&&(S.sn<r.endSN?(S=_[S.sn+1-r.startSN],u.b.log("SN just loaded, load next one: "+S.sn)):S=null))}if(S)if(S.decryptdata&&null!=S.decryptdata.uri&&null==S.decryptdata.key)u.b.log("Loading key for "+S.sn+" of ["+r.startSN+" ,"+r.endSN+"],track "+y),this.state=le.KEY_LOADING,i.trigger(a.a.KEY_LOADING,{frag:S});else{if(u.b.log("Loading "+S.sn+", cc: "+S.cc+" of ["+r.startSN+" ,"+r.endSN+"],track "+y+", currentTime:"+e+",bufferEnd:"+p.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,S.loadCounter){S.loadCounter++;var x=n.fragLoadingLoopThreshold;if(S.loadCounter>x&&Math.abs(this.fragLoadIdx-S.loadIdx)<x)return void i.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:S})}else S.loadCounter=1;S.loadIdx=this.fragLoadIdx,this.fragCurrent=S,this.startFragRequested=!0,isNaN(S.sn)||(this.nextLoadPosition=S.start+S.duration),i.trigger(a.a.FRAG_LOADING,{frag:S}),this.state=le.FRAG_LOADING}}break;case le.WAITING_TRACK:(t=this.tracks[this.trackId])&&t.details&&(this.state=le.IDLE);break;case le.FRAG_LOADING_WAITING_RETRY:var C=performance.now(),M=this.retryDate,P=(c=this.media)&&c.seeking;(!M||C>=M||P)&&(u.b.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=le.IDLE);break;case le.WAITING_INIT_PTS:var L=this.videoTrackCC;if(void 0===this.initPTS[L])break;var R=this.waitingFragment;if(R){var N=R.frag.cc;L!==N?(t=this.tracks[this.trackId]).details&&t.details.live&&(u.b.warn("Waiting fragment CC ("+N+") does not match video track CC ("+L+")"),this.waitingFragment=null,this.state=le.IDLE):(this.state=le.FRAG_LOADING,this.onFragLoaded(this.waitingFragment),this.waitingFragment=null)}else this.state=le.IDLE;break;case le.STOPPED:case le.FRAG_LOADING:case le.PARSING:case le.PARSED:case le.ENDED:}},t.prototype.onMediaAttached=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)},t.prototype.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(u.b.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=this.videoBuffer=null,this.loadedmetadata=!1,this.stopLoad()},t.prototype.onMediaSeeking=function(){this.state===le.ENDED&&(this.state=le.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()},t.prototype.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},t.prototype.onAudioTracksUpdated=function(e){u.b.log("audio tracks updated"),this.tracks=e.audioTracks},t.prototype.onAudioTrackSwitching=function(e){var t=!!e.url;this.trackId=e.id,this.fragCurrent=null,this.state=le.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=le.IDLE,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold)),this.tick()},t.prototype.onAudioTrackLoaded=function(e){var t=e.details,r=e.id,i=this.tracks[r],n=t.totalduration,o=0;if(u.b.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+n),t.live){var a=i.details;a&&t.fragments.length>0?(B(a,t),o=t.fragments[0].start,t.PTSKnown?u.b.log("live audio playlist sliding:"+o.toFixed(3)):u.b.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,u.b.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:(u.b.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s)}this.nextLoadPosition=this.startPosition}this.state===le.WAITING_TRACK&&(this.state=le.IDLE),this.tick()},t.prototype.onKeyLoaded=function(){this.state===le.KEY_LOADING&&(this.state=le.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===le.FRAG_LOADING&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var i=this.tracks[this.trackId],n=i.details,o=n.totalduration,s=t.level,c=t.sn,l=t.cc,d=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",f=this.stats=e.stats;if("initSegment"===c)this.state=le.IDLE,f.tparsed=f.tbuffered=performance.now(),n.initSegment.data=e.payload,this.hls.trigger(a.a.FRAG_BUFFERED,{stats:f,frag:t,id:"audio"}),this.tick();else{this.state=le.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new N(this.hls,"audio"));var h=this.initPTS[l],p=n.initSegment?n.initSegment.data:[];if(n.initSegment||void 0!==h){this.pendingBuffering=!0,u.b.log("Demuxing "+c+" of ["+n.startSN+" ,"+n.endSN+"],track "+s);this.demuxer.push(e.payload,p,d,null,t,o,!1,h)}else u.b.log("unknown video PTS for continuity counter "+l+", waiting for video PTS before demuxing audio frag "+c+" of ["+n.startSN+" ,"+n.endSN+"],track "+s),this.waitingFragment=e,this.state=le.WAITING_INIT_PTS}}this.fragLoadError=0},t.prototype.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===le.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(a.a.BUFFER_CODECS,i),u.b.log("audio track:audio,container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var o=n.initSegment;if(o){var s={type:"audio",data:o,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[s]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(a.a.BUFFER_APPENDING,s))}this.tick()}}},t.prototype.onFragParsingData=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===le.PARSING){var n=this.trackId,o=this.tracks[n],s=this.hls;isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),u.b.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),F(o.details,r,e.startPTS,e.endPTS);var c=this.audioSwitch,l=this.media,d=!1;if(c&&l)if(l.readyState){var f=l.currentTime;u.b.log("switching audio track : currentTime:"+f),f>=e.startPTS&&(u.b.log("switching audio track : flushing all audio"),this.state=le.BUFFER_FLUSHING,s.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),d=!0,this.audioSwitch=!1,s.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:n}))}else this.audioSwitch=!1,s.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:n});var h=this.pendingData;this.audioSwitch||([e.data1,e.data2].forEach(function(t){t&&t.length&&h.push({type:e.type,data:t,parent:"audio",content:"data"})}),!d&&h.length&&(h.forEach(function(e){t.state===le.PARSING&&(t.pendingBuffering=!0,t.hls.trigger(a.a.BUFFER_APPENDING,e))}),this.pendingData=[],this.appended=!0)),this.tick()}},t.prototype.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===le.PARSING&&(this.stats.tparsed=performance.now(),this.state=le.PARSED,this._checkAppendedParsed())},t.prototype.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},t.prototype.onBufferCreated=function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},t.prototype.onBufferAppended=function(e){if("audio"===e.parent){var t=this.state;t!==le.PARSING&&t!==le.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},t.prototype._checkAppendedParsed=function(){if(!(this.state!==le.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(a.a.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;u.b.log("audio buffered : "+U.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=le.IDLE}this.tick()}},t.prototype.onError=function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.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);u.b.warn("audioStreamController: frag loading failed, retry in "+n+" ms"),this.retryDate=performance.now()+n,this.state=le.FRAG_LOADING_WAITING_RETRY}else u.b.error("audioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=le.ERROR}break;case s.a.FRAG_LOOP_LOADING_ERROR:case s.a.AUDIO_TRACK_LOAD_ERROR:case s.a.AUDIO_TRACK_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.state!==le.ERROR&&(this.state=e.fatal?le.ERROR:le.IDLE,u.b.warn("audioStreamController: "+e.details+" while loading frag,switch to "+this.state+" state ..."));break;case s.a.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===le.PARSING||this.state===le.PARSED)){var o=this.mediaBuffer,c=this.media.currentTime;if(o&&D.isBuffered(o,c)&&D.isBuffered(o,c+.5)){var l=this.config;l.maxMaxBufferLength>=l.maxBufferLength&&(l.maxMaxBufferLength/=2,u.b.warn("audio:reduce max buffer length to "+l.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*l.fragLoadingLoopThreshold),this.state=le.IDLE}else u.b.warn("buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=le.BUFFER_FLUSHING,this.hls.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}},t.prototype.onBufferFlushed=function(){var e=this,t=this.pendingData;t&&t.length?(u.b.log("appending pending audio data on Buffer Flushed"),t.forEach(function(t){e.hls.trigger(a.a.BUFFER_APPENDING,t)}),this.appended=!0,this.pendingData=[],this.state=le.PARSED):(this.state=le.IDLE,this.fragPrevious=null,this.tick())},ce(t,[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,u.b.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}]),t}(l),fe=function(){if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var e="auto",t={"":!0,lr:!0,rl:!0},r={start:!0,middle:!0,end:!0,left:!0,right:!0};function i(e){return"string"==typeof e&&(!!r[e.toLowerCase()]&&e.toLowerCase())}function n(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 o(r,o,a){var s=this,u=function(){if("undefined"!=typeof navigator)return/MSIE\s8\.0/.test(navigator.userAgent)}(),c={};u?s=document.createElement("custom"):c.enumerable=!0,s.hasBeenReset=!1;var l="",d=!1,f=r,h=o,p=a,m=null,v="",g=!0,y="auto",_="start",b=50,w="middle",E=50,S="middle";if(Object.defineProperty(s,"id",n({},c,{get:function(){return l},set:function(e){l=""+e}})),Object.defineProperty(s,"pauseOnExit",n({},c,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(s,"startTime",n({},c,{get:function(){return f},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");f=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"endTime",n({},c,{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",n({},c,{get:function(){return p},set:function(e){p=""+e,this.hasBeenReset=!0}})),Object.defineProperty(s,"region",n({},c,{get:function(){return m},set:function(e){m=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"vertical",n({},c,{get:function(){return v},set:function(e){var r=function(e){return"string"==typeof e&&!!t[e.toLowerCase()]&&e.toLowerCase()}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");v=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"snapToLines",n({},c,{get:function(){return g},set:function(e){g=!!e,this.hasBeenReset=!0}})),Object.defineProperty(s,"line",n({},c,{get:function(){return y},set:function(t){if("number"!=typeof t&&t!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"lineAlign",n({},c,{get:function(){return _},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");_=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"position",n({},c,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"positionAlign",n({},c,{get:function(){return w},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"size",n({},c,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",n({},c,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),s.displayState=void 0,u)return s}return o.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},o}(),he=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};function pe(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new he,this.regionList=[]}function me(){this.values=Object.create(null)}function ve(e,t,r,i){var n=i?e.split(i):[e];for(var o in n)if("string"==typeof n[o]){var a=n[o].split(r);if(2===a.length)t(a[0],a[1])}}me.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 ge=new fe(0,0,0),ye="middle"===ge.align?"middle":"center";function _e(e,t,r){var i=e;function n(){var t=function(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}(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function o(){e=e.replace(/^\s+/,"")}if(o(),t.startTime=n(),o(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.substr(3),o(),t.endTime=n(),o(),function(e,t){var i=new me;ve(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 o=t.split(","),a=o[0];i.integer(e,a),i.percent(e,a)&&i.set("snapToLines",!1),i.alt(e,a,["auto"]),2===o.length&&i.alt("lineAlign",o[1],["start",ye,"end"]);break;case"position":o=t.split(","),i.percent(e,o[0]),2===o.length&&i.alt("positionAlign",o[1],["start",ye,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",ye,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===ge.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",ye);var o=i.get("position","auto");"auto"===o&&50===ge.position&&(o="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=o}(e,t)}function be(e){return e.replace(/<br(?: \/)?>/gi,"\n")}pe.prototype={parse:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=be(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.substr(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.substr(r),i}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var i;if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(i=r()).match(/^()?WEBVTT([ \t].*)?$/);if(!n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var o=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:i=r(),t.state){case"HEADER":/:/.test(i)?ve(i,function(e,t){switch(e){case"Region":console.log("parse region",t)}},/:/):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new fe(0,0,""),t.state="CUE",-1===i.indexOf("--\x3e")){t.cue.id=i;continue}case"CUE":try{_e(i,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var a=-1!==i.indexOf("--\x3e");if(!i||a&&(o=!0)){t.oncue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}t.cue.text&&(t.cue.text+="\n"),t.cue.text+=i;continue;case"BADCUE":i||(t.state="ID");continue}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){try{if(this.buffer+=this.decoder.decode(),(this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state)throw new Error("Malformed WebVTT signature.")}catch(e){throw e}return this.onflush&&this.onflush(),this}};var we=pe;function Ee(e,t,r,i){for(var n,o,a,s,u,c=window.VTTCue||window.TextTrackCue,l=0;l<i.rows.length;l++)if(a=!0,s=0,u="",!(n=i.rows[l]).isEmpty()){for(var d=0;d<n.chars.length;d++)n.chars[d].uchar.match(/\s/)&&a?s++:(u+=n.chars[d].uchar,a=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o=new c(t,r,be(u.trim())),s>=16?s--:s++,navigator.userAgent.match(/Firefox\//)?o.line=l+1:o.line=l>7?l-2:l+1,o.align="left",o.position=Math.max(0,Math.min(100,s/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),e.addCue(o)}}function Se(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var Te={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},Oe=function(e){var t=e;return Te.hasOwnProperty(e)&&(t=Te[e]),String.fromCharCode(t)},Ae=15,$e=100,ke={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},De={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ie={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},xe={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ce=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Me={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)}},Pe=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},Le=function(){function e(t,r,i,n,o){Se(this,e),this.foreground=t||"white",this.underline=r||!1,this.italics=i||!1,this.background=n||"black",this.flash=o||!1}return e.prototype.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},e.prototype.setStyles=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])}},e.prototype.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},e.prototype.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},e.prototype.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},e.prototype.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),Re=function(){function e(t,r,i,n,o,a){Se(this,e),this.uchar=t||" ",this.penState=new Le(r,i,n,o,a)}return e.prototype.reset=function(){this.uchar=" ",this.penState.reset()},e.prototype.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},e.prototype.setPenState=function(e){this.penState.copy(e)},e.prototype.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},e.prototype.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},e.prototype.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),Ne=function(){function e(){Se(this,e),this.chars=[];for(var t=0;t<$e;t++)this.chars.push(new Re);this.pos=0,this.currPenState=new Le}return e.prototype.equals=function(e){for(var t=!0,r=0;r<$e;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t},e.prototype.copy=function(e){for(var t=0;t<$e;t++)this.chars[t].copy(e.chars[t])},e.prototype.isEmpty=function(){for(var e=!0,t=0;t<$e;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},e.prototype.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(Me.log("ERROR","Negative cursor position "+this.pos),this.pos=0):this.pos>$e&&(Me.log("ERROR","Too large cursor position "+this.pos),this.pos=$e)},e.prototype.moveCursor=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)},e.prototype.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},e.prototype.insertChar=function(e){e>=144&&this.backSpace();var t=Oe(e);this.pos>=$e?Me.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))},e.prototype.clearFromPos=function(e){var t;for(t=e;t<$e;t++)this.chars[t].reset()},e.prototype.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.prototype.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.prototype.getTextString=function(){for(var e=[],t=!0,r=0;r<$e;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")},e.prototype.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),je=function(){function e(){Se(this,e),this.rows=[];for(var t=0;t<Ae;t++)this.rows.push(new Ne);this.currRow=Ae-1,this.nrRollUpRows=null,this.reset()}return e.prototype.reset=function(){for(var e=0;e<Ae;e++)this.rows[e].clear();this.currRow=Ae-1},e.prototype.equals=function(e){for(var t=!0,r=0;r<Ae;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t},e.prototype.copy=function(e){for(var t=0;t<Ae;t++)this.rows[t].copy(e.rows[t])},e.prototype.isEmpty=function(){for(var e=!0,t=0;t<Ae;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},e.prototype.backSpace=function(){this.rows[this.currRow].backSpace()},e.prototype.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.prototype.insertChar=function(e){this.rows[this.currRow].insertChar(e)},e.prototype.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},e.prototype.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},e.prototype.setCursor=function(e){Me.log("INFO","setCursor: "+e),this.rows[this.currRow].setCursor(e)},e.prototype.setPAC=function(e){Me.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<Ae;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var o=n.rows[i].cueStartTime;if(o&&o<Me.time)for(var a=0;a<this.nrRollUpRows;a++)this.rows[t-this.nrRollUpRows+a+1].copy(n.rows[i+a])}}this.currRow=t;var s=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);s.setCursor(e.indent),e.color=s.chars[c].penState.foreground}var l={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(l)},e.prototype.setBkgData=function(e){Me.log("INFO","bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)},e.prototype.setRollUpRows=function(e){this.nrRollUpRows=e},e.prototype.rollUp=function(){if(null!==this.nrRollUpRows){Me.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),Me.log("INFO","Rolling up")}else Me.log("DEBUG","roll_up but nrRollUpRows not set yet")},e.prototype.getDisplayText=function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Ae;n++){var o=this.rows[n].getTextString();o&&(i=n+1,e?t.push("Row "+i+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},e.prototype.getTextAndFormat=function(){return this.rows},e}(),Fe=function(){function e(t,r){Se(this,e),this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new je,this.nonDisplayedMemory=new je,this.lastOutputScreen=new je,this.currRollUpRow=this.displayedMemory.rows[Ae-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return e.prototype.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[Ae-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null},e.prototype.getHandler=function(){return this.outputFilter},e.prototype.setHandler=function(e){this.outputFilter=e},e.prototype.setPAC=function(e){this.writeScreen.setPAC(e)},e.prototype.setBkgData=function(e){this.writeScreen.setBkgData(e)},e.prototype.setMode=function(e){e!==this.mode&&(this.mode=e,Me.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)},e.prototype.insertChars=function(e){for(var t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";Me.log("INFO",r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(Me.log("TEXT","DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())},e.prototype.ccRCL=function(){Me.log("INFO","RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},e.prototype.ccBS=function(){Me.log("INFO","BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},e.prototype.ccAOF=function(){},e.prototype.ccAON=function(){},e.prototype.ccDER=function(){Me.log("INFO","DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},e.prototype.ccRU=function(e){Me.log("INFO","RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},e.prototype.ccFON=function(){Me.log("INFO","FON - Flash On"),this.writeScreen.setPen({flash:!0})},e.prototype.ccRDC=function(){Me.log("INFO","RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},e.prototype.ccTR=function(){Me.log("INFO","TR"),this.setMode("MODE_TEXT")},e.prototype.ccRTD=function(){Me.log("INFO","RTD"),this.setMode("MODE_TEXT")},e.prototype.ccEDM=function(){Me.log("INFO","EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},e.prototype.ccCR=function(){Me.log("CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},e.prototype.ccENM=function(){Me.log("INFO","ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},e.prototype.ccEOC=function(){if(Me.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,Me.log("TEXT","DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)},e.prototype.ccTO=function(e){Me.log("INFO","TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},e.prototype.ccMIDROW=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;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}Me.log("INFO","MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)},e.prototype.outputDataUpdate=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=Me.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),!0===e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue()),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},e.prototype.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),Be=function(){function e(t,r,i){Se(this,e),this.field=t||1,this.outputs=[r,i],this.channels=[new Fe(1,r),new Fe(2,i)],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 e.prototype.getHandler=function(e){return this.channels[e].getHandler()},e.prototype.setHandler=function(e,t){this.channels[e].setHandler(t)},e.prototype.addData=function(e,t){var r,i,n,o=!1;this.lastTime=e,Me.setTime(e);for(var a=0;a<t.length;a+=2)if(i=127&t[a],n=127&t[a+1],0!==i||0!==n){if(Me.log("DATA","["+Pe([t[a],t[a+1]])+"] -> ("+Pe([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)if(o=this.parseChars(i,n))if(this.currChNr&&this.currChNr>=0)this.channels[this.currChNr-1].insertChars(o);else Me.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:o?this.dataCounters.char+=2:(this.dataCounters.other+=2,Me.log("WARNING","Couldn't parse cleaned data "+Pe([i,n])+" orig: "+Pe([t[a],t[a+1]])))}else this.dataCounters.padding+=2},e.prototype.parseCmd=function(e,t){var r=null;if(!((20===e||28===e)&&32<=t&&t<=47)&&!((23===e||31===e)&&33<=t&&t<=35))return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,Me.log("DEBUG","Repeated command ("+Pe([e,t])+") is dropped"),!0;r=20===e||23===e?1:2;var i=this.channels[r-1];return 20===e||28===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0},e.prototype.parseMidrow=function(e,t){var r=null;return(17===e||25===e)&&32<=t&&t<=47&&((r=17===e?1:2)!==this.currChNr?(Me.log("ERROR","Mismatch channel in midrow parsing"),!1):(this.channels[r-1].ccMIDROW(t),Me.log("DEBUG","MIDROW ("+Pe([e,t])+")"),!0))},e.prototype.parsePAC=function(e,t){var r,i=null;if(!((17<=e&&e<=23||25<=e&&e<=31)&&64<=t&&t<=127)&&!((16===e||24===e)&&64<=t&&t<=95))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?ke[e]:Ie[e]:1===r?De[e]:xe[e];var n=this.interpretPAC(i,t);return this.channels[r-1].setPAC(n),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0},e.prototype.interpretPAC=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},e.prototype.parseChars=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 o=t;o=17===n?t+80:18===n?t+112:t+144,Me.log("INFO","Special char '"+Oe(o)+"' in channel "+r),i=[o]}else 32<=e&&e<=127&&(i=0===t?[e]:[e,t]);if(i){var a=Pe(i);Me.log("DEBUG","Char codes = "+a.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i},e.prototype.parseBackgroundAttributes=function(e,t){var r,i,n;return((16===e||24===e)&&32<=t&&t<=47||(23===e||31===e)&&45<=t&&t<=47)&&(r={},16===e||24===e?(i=Math.floor((t-32)/2),r.background=Ce[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)},e.prototype.reset=function(){for(var e=0;e<this.channels.length;e++)this.channels[e]&&this.channels[e].reset();this.lastCmdA=null,this.lastCmdB=null},e.prototype.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++)this.channels[t]&&this.channels[t].cueSplitAtTime(e)},e}();var Ue=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.timelineController=t,this.track=r,this.startTime=null,this.endTime=null,this.screen=null}return e.prototype.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues("textTrack"+this.track,this.startTime,this.endTime,this.screen),this.startTime=null)},e.prototype.newCue=function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.track)},e}(),ze=function(e,t,r){return e.substr(r||0,t.length)===t},Ge=function(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()},We={parse:function(e,t,r,i,n,o){var a=Object(Z.b)(new Uint8Array(e)).trim().replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),s="00:00.000",u=0,c=0,l=0,d=[],f=void 0,h=!0,p=new we;p.oncue=function(e){var t=r[i],n=r.ccOffset;t&&t.new&&(void 0!==c?n=r.ccOffset=t.start: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}(r,i,l)),l&&(n=l+r.ccOffset-r.presentationOffset),e.startTime+=n-c,e.endTime+=n-c,e.id=Ge(e.startTime.toString())+Ge(e.endTime.toString())+Ge(e.text),e.text=decodeURIComponent(encodeURIComponent(e.text)),e.endTime>0&&d.push(e)},p.onparsingerror=function(e){f=e},p.onflush=function(){f&&o?o(f):n(d)},a.forEach(function(e){if(h){if(ze(e,"X-TIMESTAMP-MAP=")){h=!1,e.substr(16).split(",").forEach(function(e){ze(e,"LOCAL:")?s=e.substr(6):ze(e,"MPEGTS:")&&(u=parseInt(e.substr(7)))});try{u-=t=t<0?t+8589934592:t,r=s,i=parseInt(r.substr(-3)),n=parseInt(r.substr(-6,2)),o=parseInt(r.substr(-9,2)),a=r.length>9?parseInt(r.substr(0,r.indexOf(":"))):0,c=(isNaN(i)||isNaN(n)||isNaN(o)||isNaN(a)?-1:(i+=1e3*n,i+=6e4*o,i+=36e5*a))/1e3,l=u/9e4,-1===c&&(f=new Error("Malformed X-TIMESTAMP-MAP: "+e))}catch(t){f=new Error("Malformed X-TIMESTAMP-MAP: "+e)}return}""===e&&(h=!1)}var r,i,n,o,a;p.parse(e+"\n")}),p.flush()}};function He(e){if(e&&e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}var Ve=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHING,a.a.MEDIA_DETACHING,a.a.FRAG_PARSING_USERDATA,a.a.FRAG_DECRYPTED,a.a.MANIFEST_LOADING,a.a.MANIFEST_LOADED,a.a.FRAG_LOADED,a.a.LEVEL_SWITCHING,a.a.INIT_PTS_FOUND));if(i.hls=r,i.config=r.config,i.enabled=!0,i.Cues=r.config.cueHandler,i.textTracks=[],i.tracks=[],i.unparsedVttFrags=[],i.initPTS=void 0,i.cueRanges=[],i.config.enableCEA708Captions){var n=new Ue(i,1),o=new Ue(i,2);i.cea608Parser=new Be(0,n,o)}return i}return 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)}(t,e),t.prototype.addCues=function(e,t,r,i){for(var n,o,a,s,u=this.cueRanges,c=!1,l=u.length;l--;){var d=u[l],f=(n=d[0],o=d[1],a=t,s=r,Math.min(o,s)-Math.max(n,a));if(f>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],r),c=!0,f/(r-t)>.5))return}c||u.push([t,r]),this.Cues.newCue(this[e],t,r,i)},t.prototype.onInitPtsFound=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=[])},t.prototype.getExistingTrack=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},t.prototype.sendAddTrackEvent=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)},t.prototype.createCaptionsTrack=function(e){var t="textTrack"+e;if(!this[t]){var r=this.getExistingTrack(e);if(r)this[t]=r,He(this[t]),this.sendAddTrackEvent(this[t],this.media);else{var i=this.createTextTrack("captions",this.config["captionsTextTrack"+e+"Label"],this.config.captionsTextTrack1LanguageCode);i&&(i[t]=!0,this[t]=i)}}},t.prototype.createTextTrack=function(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)},t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onMediaAttaching=function(e){this.media=e.media,this._cleanTracks()},t.prototype.onMediaDetaching=function(){He(this.textTrack1),He(this.textTrack2)},t.prototype.onManifestLoading=function(){this.lastSn=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0},this._cleanTracks()},t.prototype._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)He(t[r])}},t.prototype.onManifestLoaded=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 o=r[i];(function(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)})(o,e)&&(n=o)}n||(n=t.createTextTrack("subtitles",e.name,e.lang)),n.mode=e.default?"showing":"hidden",t.textTracks.push(n)})}},t.prototype.onLevelSwitching=function(){this.enabled="NONE"!==this.hls.currentLevel.closedCaptions},t.prototype.onFragLoaded=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 o=t.decryptdata;null!=o&&null!=o.key&&"AES-128"===o.method||this._parseVTTs(t,r)}else this.hls.trigger(a.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t})},t.prototype._parseVTTs=function(e,t){var r=this.vttCCs;r[e.cc]||(r[e.cc]={start:e.start,prevCC:this.prevCC,new:!0},this.prevCC=e.cc);var i=this.textTracks,n=this.hls;We.parse(t,this.initPTS,r,e.cc,function(t){var r=i[e.trackId];t.forEach(function(e){if(!r.cues.getCueById(e.id))try{r.addCue(e)}catch(i){var t=new window.TextTrackCue(e.startTime,e.endTime,e.text);t.id=e.id,r.addCue(t)}}),n.trigger(a.a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){u.b.log("Failed to parse VTT cue: "+t),n.trigger(a.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e})})},t.prototype.onFragDecrypted=function(e){var t=e.payload,r=e.frag;if("subtitle"===r.type){if(void 0===this.initPTS)return void this.unparsedVttFrags.push(e);this._parseVTTs(r,t)}},t.prototype.onFragParsingUserdata=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)}},t.prototype.extractCea608Data=function(e){for(var t,r,i,n=31&e[0],o=2,a=[],s=0;s<n;s++)t=e[o++],r=127&e[o++],i=127&e[o++],0===r&&0===i||0!=(4&t)&&0===(3&t)&&(a.push(r),a.push(i));return a},t}(l),Ye=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}}();function Ke(e){for(var t=[],r=0;r<e.length;r++)"subtitles"===e[r].kind&&t.push(e[r]);return t}var Ze=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.MANIFEST_LOADING,a.a.MANIFEST_LOADED,a.a.SUBTITLE_TRACK_LOADED));return i.tracks=[],i.trackId=-1,i.media=void 0,i.subtitleDisplay=!1,i}return 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)}(t,e),t.prototype._onTextTracksChanged=function(){if(this.media){for(var e=-1,t=Ke(this.media.textTracks),r=0;r<t.length;r++)"showing"===t[r].mode&&(e=r);this.subtitleTrack=e}},t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onMediaAttached=function(e){var t=this;this.media=e.media,this.media&&(void 0!==this.queuedDefaultTrack&&(this.subtitleTrack=this.queuedDefaultTrack,delete this.queuedDefaultTrack),this.trackChangeListener=this._onTextTracksChanged.bind(this),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.subtitlePollingInterval=setInterval(function(){t.trackChangeListener()},500):this.media.textTracks.addEventListener("change",this.trackChangeListener))},t.prototype.onMediaDetaching=function(){this.media&&(this.useTextTrackPolling?clearInterval(this.subtitlePollingInterval):this.media.textTracks.removeEventListener("change",this.trackChangeListener),this.media=void 0)},t.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},t.prototype.onManifestLoaded=function(e){var t=this,r=e.subtitles||[];this.tracks=r,this.trackId=-1,this.hls.trigger(a.a.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:r}),r.forEach(function(e){e.default&&(t.media?t.subtitleTrack=e.id:t.queuedDefaultTrack=e.id)})},t.prototype.onTick=function(){var e=this.trackId,t=this.tracks[e];if(t){var r=t.details;void 0!==r&&!0!==r.live||(u.b.log("(re)loading playlist for subtitle track "+e),this.hls.trigger(a.a.SUBTITLE_TRACK_LOADING,{url:t.url,id:e}))}},t.prototype.onSubtitleTrackLoaded=function(e){var t=this;e.id<this.tracks.length&&(u.b.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))},t.prototype.setSubtitleTrackInternal=function(e){if(!(e<-1||e>=this.tracks.length)){this.timer&&(clearInterval(this.timer),this.timer=null);var t=Ke(this.media.textTracks);if(-1!==this.trackId&&this.subtitleDisplay&&(t[this.trackId].mode="hidden"),this.trackId=e,u.b.log("switching to subtitle track "+e),this.hls.trigger(a.a.SUBTITLE_TRACK_SWITCH,{id:e}),-1!==e){var r=this.tracks[e];this.subtitleDisplay&&(t[e].mode="showing");var i=r.details;void 0!==i&&!0!==i.live||(u.b.log("(re)loading playlist for subtitle track "+e),this.hls.trigger(a.a.SUBTITLE_TRACK_LOADING,{url:r.url,id:e}))}}},Ye(t,[{key:"subtitleTracks",get:function(){return this.tracks}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.trackId!==e&&this.setSubtitleTrackInternal(e)}}]),t}(l),Qe=r(4);var Xe={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING"},qe=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.ERROR,a.a.KEY_LOADED,a.a.FRAG_LOADED,a.a.SUBTITLE_TRACKS_UPDATED,a.a.SUBTITLE_TRACK_SWITCH,a.a.SUBTITLE_TRACK_LOADED,a.a.SUBTITLE_FRAG_PROCESSED));return i.config=r.config,i.vttFragSNsProcessed={},i.vttFragQueues=void 0,i.currentlyProcessing=null,i.state=Xe.STOPPED,i.currentTrackId=-1,i.ticks=0,i.decrypter=new Qe.a(r.observer,r.config),i}return 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)}(t,e),t.prototype.destroy=function(){l.prototype.destroy.call(this),this.state=Xe.STOPPED},t.prototype.clearVttFragQueues=function(){var e=this;this.vttFragQueues={},this.tracks.forEach(function(t){e.vttFragQueues[t.id]=[]})},t.prototype.nextFrag=function(){if(null===this.currentlyProcessing&&this.currentTrackId>-1&&this.vttFragQueues[this.currentTrackId].length){var e=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.fragCurrent=e,this.hls.trigger(a.a.FRAG_LOADING,{frag:e}),this.state=Xe.FRAG_LOADING}},t.prototype.onSubtitleFragProcessed=function(e){e.success&&this.vttFragSNsProcessed[e.frag.trackId].push(e.frag.sn),this.currentlyProcessing=null,this.state=Xe.IDLE,this.nextFrag()},t.prototype.onMediaAttached=function(){this.state=Xe.IDLE},t.prototype.onError=function(e){var t=e.frag;t&&"subtitle"!==t.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())},t.prototype.tick=function(){var e=this;this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(function(){e.tick()},1),this.ticks=0)},t.prototype.doTick=function(){var e=this;switch(this.state){case Xe.IDLE:var t,r=this.tracks,i=this.currentTrackId,n=this.vttFragSNsProcessed[i],o=this.vttFragQueues[i],s=this.currentlyProcessing?this.currentlyProcessing.sn:-1;if(!r)break;if(i<r.length&&(t=r[i].details),void 0===t)break;t.fragments.forEach(function(t){(function(e){return n.indexOf(e.sn)>-1})(t)||t.sn===s||function(e){return o.some(function(t){return t.sn===e.sn})}(t)||(t.decryptdata&&null!=t.decryptdata.uri&&null==t.decryptdata.key?(u.b.log("Loading key for "+t.sn),e.state=Xe.KEY_LOADING,e.hls.trigger(a.a.KEY_LOADING,{frag:t})):(t.trackId=i,o.push(t),e.nextFrag()))})}},t.prototype.onSubtitleTracksUpdated=function(e){var t=this;u.b.log("subtitle tracks updated"),this.tracks=e.subtitleTracks,this.clearVttFragQueues(),this.vttFragSNsProcessed={},this.tracks.forEach(function(e){t.vttFragSNsProcessed[e.id]=[]})},t.prototype.onSubtitleTrackSwitch=function(e){this.currentTrackId=e.id,this.clearVttFragQueues()},t.prototype.onSubtitleTrackLoaded=function(){this.tick()},t.prototype.onKeyLoaded=function(){this.state===Xe.KEY_LOADING&&(this.state=Xe.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag.decryptdata,i=e.frag,n=this.hls;if(this.state===Xe.FRAG_LOADING&&t&&"subtitle"===e.frag.type&&t.sn===e.frag.sn&&e.payload.byteLength>0&&null!=r&&null!=r.key&&"AES-128"===r.method){var o;try{o=performance.now()}catch(e){o=Date.now()}this.decrypter.decrypt(e.payload,r.key.buffer,r.iv.buffer,function(e){var t;try{t=performance.now()}catch(e){t=Date.now()}n.trigger(a.a.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:o,tdecrypt:t}})})}},t}(l),Je={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,liveDurationInfinity:!1,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:ae,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,fetchSetup:void 0,abrController:ee,bufferController:re,capLevelController:ne,fpsController:oe,stretchShortVideoTrack:!1,maxAudioFramesDrift: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};Je.subtitleStreamController=qe,Je.subtitleTrackController=Ze,Je.timelineController=Ve,Je.cueHandler=i,Je.enableCEA708Captions=!0,Je.enableWebVTT=!0,Je.captionsTextTrack1Label="English",Je.captionsTextTrack1LanguageCode="en",Je.captionsTextTrack2Label="Spanish",Je.captionsTextTrack2LanguageCode="es",Je.audioStreamController=de,Je.audioTrackController=ue;var et=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}}();var tt=function(){function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(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 n in i)n in r||(r[n]=i[n]);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"');Object(u.a)(r.debug),this.config=r,this._autoLevelCapping=-1;var o=this.observer=new C.a;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 a=this.abrController=new r.abrController(this),s=new r.bufferController(this),c=new r.capLevelController(this),l=new r.fpsController(this),d=new O(this),f=new A(this),h=new $(this),p=new Q(this),m=[this.levelController=new K(this),this.streamController=new V(this)],v=r.audioStreamController;v&&m.push(new v(this)),this.networkControllers=m;var g=[d,f,h,a,s,c,l,p];if(v=r.audioTrackController){var y=new v(this);this.audioTrackController=y,g.push(y)}if(v=r.subtitleTrackController){var _=new v(this);this.subtitleTrackController=_,g.push(_)}[r.subtitleStreamController,r.timelineController].forEach(function(e){e&&g.push(new e(t))}),this.coreComponents=g}return e.isSupported=function(){return e=L(),t=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,!!r&&!!i;var e,t,r,i},et(e,null,[{key:"version",get:function(){return"0.8.9"}},{key:"Events",get:function(){return a.a}},{key:"ErrorTypes",get:function(){return s.b}},{key:"ErrorDetails",get:function(){return s.a}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Je},set:function(t){e.defaultConfig=t}}]),e.prototype.destroy=function(){u.b.log("destroy"),this.trigger(a.a.DESTROYING),this.detachMedia(),this.coreComponents.concat(this.networkControllers).forEach(function(e){e.destroy()}),this.url=null,this.observer.removeAllListeners(),this._autoLevelCapping=-1},e.prototype.attachMedia=function(e){u.b.log("attachMedia"),this.media=e,this.trigger(a.a.MEDIA_ATTACHING,{media:e})},e.prototype.detachMedia=function(){u.b.log("detachMedia"),this.trigger(a.a.MEDIA_DETACHING),this.media=null},e.prototype.loadSource=function(e){e=o.a.buildAbsoluteURL(window.location.href,e,{alwaysNormalize:!0}),u.b.log("loadSource:"+e),this.url=e,this.trigger(a.a.MANIFEST_LOADING,{url:e})},e.prototype.startLoad=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;u.b.log("startLoad("+e+")"),this.networkControllers.forEach(function(t){t.startLoad(e)})},e.prototype.stopLoad=function(){u.b.log("stopLoad"),this.networkControllers.forEach(function(e){e.stopLoad()})},e.prototype.swapAudioCodec=function(){u.b.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.prototype.recoverMediaError=function(){u.b.log("recoverMediaError");var e=this.media;this.detachMedia(),this.attachMedia(e)},et(e,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){u.b.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){u.b.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){u.b.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){u.b.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){u.b.log("set startLevel:"+e);-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){u.b.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.levels,t=this.config.minAutoBitrate,r=e?e.length:0,i=0;i<r;i++){if((e[i].realBitrate?Math.max(e[i].realBitrate,e[i].bitrate):e[i].bitrate)>t)return i}return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.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)}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}}]),e}();t.default=tt},function(e,t,r){function i(e){var t=[],r=e.toString(),i=r.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!i)return t;for(var n,o=i[1],a=new RegExp("(\\\\n|\\W)"+(o+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\w|/|@]+).*?\\)","g");n=a.exec(r);)t.push(n[3]);return t}e.exports=function(e,t){t=t||{};var n=r.m,o=t.all?Object.keys(n):function(e,t){for(var r=[t],n=[],o={};r.length;){var a=r.pop();if(!o[a]&&e[a]){o[a]=!0,n.push(a);var s=i(e[a]);r=r.concat(s)}}return n}(n,e),a="("+function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+o.map(function(e){return JSON.stringify(e)+": "+n[e].toString()}).join(",")+"})(self);",s=new window.Blob([a],{type:"text/javascript"});if(t.bare)return s;var u=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(s),c=new window.Worker(u);return c.objectURL=u,c}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=r(7),n=r(1),o=r(0),a=r(5),s=r.n(a);t.default=function(e){var t=new s.a;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(n){var a=n.data;switch(a.cmd){case"init":var s=JSON.parse(a.config);e.demuxer=new i.a(t,a.typeSupported,s,a.vendor);try{Object(o.a)(!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(n.a.FRAG_DECRYPTED,r),t.on(n.a.FRAG_PARSING_INIT_SEGMENT,r),t.on(n.a.FRAG_PARSED,r),t.on(n.a.ERROR,r),t.on(n.a.FRAG_PARSING_METADATA,r),t.on(n.a.FRAG_PARSING_USERDATA,r),t.on(n.a.INIT_PTS_FOUND,r),t.on(n.a.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)})}}]).default},e.exports=r()}),HlsCore=unwrapExports(hls),defaultCustomConfig={debug:!1,enableWorker:!0},_class$9;function _applyDecoratedDescriptor$8(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var LOG_TAG$1="chimee-kernel-hls",Hls=(_class$9=function(e){function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(n.version="1.2.0",!isElement(e))throw new Error("video element passed in "+LOG_TAG$1+" must be a HTMLVideoElement, but not "+(void 0===e?"undefined":_typeof(e)));if(!isObject(r))throw new Error("config of "+LOG_TAG$1+" must be an Object but not "+(void 0===r?"undefined":_typeof(r)));return n.video=e,n.config=r,n.customConfig=deepAssign({},defaultCustomConfig,i),n.hlsKernel=new HlsCore(n.customConfig),n.bindEvents(),n.attachMedia(),n}return _inherits(t,CustEvent),_createClass(t,null,[{key:"isSupport",value:function(){return HlsCore.isSupported()}}]),_createClass(t,[{key:"bindEvents",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.hlsKernel;t&&t[e?"off":"on"](HlsCore.Events.ERROR,this.hlsErrorHandler)}},{key:"load",value:function(){return this.hlsKernel.loadSource(this.config.src)}},{key:"startLoad",value:function(){return this.hlsKernel.startLoad()}},{key:"stopLoad",value:function(){return this.hlsKernel.stopLoad()}},{key:"attachMedia",value:function(){return this.hlsKernel.attachMedia(this.video)}},{key:"play",value:function(){return this.video.play()}},{key:"destroy",value:function(){return this.bindEvents(!0),this.hlsKernel.destroy()}},{key:"seek",value:function(e){this.video.currentTime=e}},{key:"pause",value:function(){return this.video.pause()}},{key:"refresh",value:function(){return this.hlsKernel.stopLoad(),this.hlsKernel.loadSource(this.config.src)}},{key:"hlsErrorHandler",value:function(e,t){this.emit("error",t),this.emit(e,t),Log$1.error(LOG_TAG$1+(e?" "+e:""),t.details)}}]),t}(),_applyDecoratedDescriptor$8(_class$9.prototype,"hlsErrorHandler",[autobind],_Object$getOwnPropertyDescriptor(_class$9.prototype,"hlsErrorHandler"),_class$9.prototype),_class$9),lib$2=createCommonjsModule(function(module,exports){var factory;factory=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=6)}([function(e,t,r){!function(e){function t(e){return e&&e.__esModule?e.default:e}function r(e,t){return e(t={exports:{}},t.exports),t.exports}var i=Math.ceil,n=Math.floor,o=function(e){return isNaN(e=+e)?0:(e>0?n:i)(e)},a=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},s=r(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)}),u=r(function(e){var t=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=t)}),c=function(e,t,r){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(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)}},l=function(e){return"object"==typeof e?null!==e:"function"==typeof e},d=function(e){if(!l(e))throw TypeError(e+" is not an object!");return e},f=function(e){try{return!!e()}catch(e){return!0}},h=!f(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),p=s.document,m=l(p)&&l(p.createElement),v=function(e){return m?p.createElement(e):{}},g=!h&&!f(function(){return 7!=Object.defineProperty(v("div"),"a",{get:function(){return 7}}).a}),y=function(e,t){if(!l(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!l(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!l(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!l(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},_=Object.defineProperty,b={f:h?Object.defineProperty:function(e,t,r){if(d(e),t=y(t,!0),d(r),g)try{return _(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}},w=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},E=h?function(e,t,r){return b.f(e,t,w(1,r))}:function(e,t,r){return e[t]=r,e},S=function(e,t,r){var i,n,o,a=e&S.F,l=e&S.G,d=e&S.S,f=e&S.P,h=e&S.B,p=e&S.W,m=l?u:u[t]||(u[t]={}),v=m.prototype,g=l?s:d?s[t]:(s[t]||{}).prototype;for(i in l&&(r=t),r)(n=!a&&g&&void 0!==g[i])&&i in m||(o=n?g[i]:r[i],m[i]=l&&"function"!=typeof g[i]?r[i]:h&&n?c(o,s):p&&g[i]==o?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}(o):f&&"function"==typeof o?c(Function.call,o):o,f&&((m.virtual||(m.virtual={}))[i]=o,e&S.R&&v&&!v[i]&&E(v,i,o)))};S.F=1,S.G=2,S.S=4,S.P=8,S.B=16,S.W=32,S.U=64,S.R=128;var T,O=S,A=E,$={}.hasOwnProperty,k=function(e,t){return $.call(e,t)},D={}.toString,I=function(e){return D.call(e).slice(8,-1)},x=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==I(e)?e.split(""):Object(e)},C=function(e){return x(a(e))},M=Math.min,P=Math.max,L=Math.min,R=s["__core-js_shared__"]||(s["__core-js_shared__"]={}),N=function(e){return R[e]||(R[e]={})},j=0,F=Math.random(),B=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++j+F).toString(36))},U=N("keys"),z=function(e){return U[e]||(U[e]=B(e))},G=(T=!1,function(e,t,r){var i,n,a=C(e),s=(n=a.length)>0?M(o(n),9007199254740991):0,u=function(e,t){return(e=o(e))<0?P(e+t,0):L(e,t)}(r,s);if(T&&t!=t){for(;s>u;)if((i=a[u++])!=i)return!0}else for(;s>u;u++)if((T||u in a)&&a[u]===t)return T||u||0;return!T&&-1}),W=z("IE_PROTO"),H=function(e,t){var r,i=C(e),n=0,o=[];for(r in i)r!=W&&k(i,r)&&o.push(r);for(;t.length>n;)k(i,r=t[n++])&&(~G(o,r)||o.push(r));return o},V="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),Y=Object.keys||function(e){return H(e,V)},K=h?Object.defineProperties:function(e,t){d(e);for(var r,i=Y(t),n=i.length,o=0;n>o;)b.f(e,r=i[o++],t[r]);return e},Z=s.document&&document.documentElement,Q=z("IE_PROTO"),X=function(){},q=function(){var e,t=v("iframe"),r=V.length;for(t.style.display="none",Z.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),q=e.F;r--;)delete q.prototype[V[r]];return q()},J=Object.create||function(e,t){var r;return null!==e?(X.prototype=d(e),r=new X,X.prototype=null,r[Q]=e):r=q(),void 0===t?r:K(r,t)},ee=r(function(e){var t=N("wks"),r=s.Symbol,i="function"==typeof r,n=e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:B)("Symbol."+e))};n.store=t}),te=b.f,re=ee("toStringTag"),ie=function(e,t,r){e&&!k(e=r?e:e.prototype,re)&&te(e,re,{configurable:!0,value:t})},ne={};E(ne,ee("iterator"),function(){return this});var oe,ae=function(e,t,r){e.prototype=J(ne,{next:w(1,r)}),ie(e,t+" Iterator")},se=function(e){return Object(a(e))},ue=z("IE_PROTO"),ce=Object.prototype,le=Object.getPrototypeOf||function(e){return e=se(e),k(e,ue)?e[ue]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ce:null},de=ee("iterator"),fe=!([].keys&&"next"in[].keys()),he=function(e,t,r,i,n,o,a){ae(r,t,i);var s,u,c,l=function(e){if(!fe&&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)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[de]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=le(y.call(new e)))!==Object.prototype&&ie(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(fe||h||!p[de])&&E(p,de,v),n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||A(p,u,s[u]);else O(O.P+O.F*(fe||h),t,s);return s},pe=(oe=!0,function(e,t){var r,i,n=String(a(e)),s=o(t),u=n.length;return s<0||s>=u?oe?"":void 0:(r=n.charCodeAt(s))<55296||r>56319||s+1===u||(i=n.charCodeAt(s+1))<56320||i>57343?oe?n.charAt(s):r:oe?n.slice(s,s+2):i-56320+(r-55296<<10)+65536});he(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=pe(t,r),this._i+=e.length,{value:e,done:!1})});for(var me=function(e,t){return{value:t,done:!!e}},ve=(he(Array,"Array",function(e,t){this._t=C(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,me(1)):me(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values"),ee("toStringTag")),ge=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],ye=0;ye<5;ye++){var _e=ge[ye],be=s[_e],we=be&&be.prototype;we&&!we[ve]&&E(we,ve,_e)}var Ee={f:ee},Se=Ee.f("iterator"),Te=r(function(e){e.exports={default:Se,__esModule:!0}}),Oe=r(function(e){var t=B("meta"),r=b.f,i=0,n=Object.isExtensible||function(){return!0},o=!f(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!l(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!k(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!k(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!k(e,t)&&a(e),e}}}),Ae=b.f,$e=function(e){var t=u.Symbol||(u.Symbol={});"_"==e.charAt(0)||e in t||Ae(t,e,{value:Ee.f(e)})},ke={f:Object.getOwnPropertySymbols},De={f:{}.propertyIsEnumerable},Ie=Array.isArray||function(e){return"Array"==I(e)},xe=V.concat("length","prototype"),Ce={f:Object.getOwnPropertyNames||function(e){return H(e,xe)}},Me=Ce.f,Pe={}.toString,Le="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Re={f:function(e){return Le&&"[object Window]"==Pe.call(e)?function(e){try{return Me(e)}catch(e){return Le.slice()}}(e):Me(C(e))}},Ne=Object.getOwnPropertyDescriptor,je={f:h?Ne:function(e,t){if(e=C(e),t=y(t,!0),g)try{return Ne(e,t)}catch(e){}if(k(e,t))return w(!De.f.call(e,t),e[t])}},Fe=Oe.KEY,Be=je.f,Ue=b.f,ze=Re.f,Ge=s.Symbol,We=s.JSON,He=We&&We.stringify,Ve=ee("_hidden"),Ye=ee("toPrimitive"),Ke={}.propertyIsEnumerable,Ze=N("symbol-registry"),Qe=N("symbols"),Xe=N("op-symbols"),qe=Object.prototype,Je="function"==typeof Ge,et=s.QObject,tt=!et||!et.prototype||!et.prototype.findChild,rt=h&&f(function(){return 7!=J(Ue({},"a",{get:function(){return Ue(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=Be(qe,t);i&&delete qe[t],Ue(e,t,r),i&&e!==qe&&Ue(qe,t,i)}:Ue,it=function(e){var t=Qe[e]=J(Ge.prototype);return t._k=e,t},nt=Je&&"symbol"==typeof Ge.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof Ge},ot=function(e,t,r){return e===qe&&ot(Xe,t,r),d(e),t=y(t,!0),d(r),k(Qe,t)?(r.enumerable?(k(e,Ve)&&e[Ve][t]&&(e[Ve][t]=!1),r=J(r,{enumerable:w(0,!1)})):(k(e,Ve)||Ue(e,Ve,w(1,{})),e[Ve][t]=!0),rt(e,t,r)):Ue(e,t,r)},at=function(e,t){d(e);for(var r,i=function(e){var t=Y(e),r=ke.f;if(r)for(var i,n=r(e),o=De.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=C(t)),n=0,o=i.length;o>n;)ot(e,r=i[n++],t[r]);return e},st=function(e){var t=Ke.call(this,e=y(e,!0));return!(this===qe&&k(Qe,e)&&!k(Xe,e))&&(!(t||!k(this,e)||!k(Qe,e)||k(this,Ve)&&this[Ve][e])||t)},ut=function(e,t){if(e=C(e),t=y(t,!0),e!==qe||!k(Qe,t)||k(Xe,t)){var r=Be(e,t);return!r||!k(Qe,t)||k(e,Ve)&&e[Ve][t]||(r.enumerable=!0),r}},ct=function(e){for(var t,r=ze(C(e)),i=[],n=0;r.length>n;)k(Qe,t=r[n++])||t==Ve||t==Fe||i.push(t);return i},lt=function(e){for(var t,r=e===qe,i=ze(r?Xe:C(e)),n=[],o=0;i.length>o;)!k(Qe,t=i[o++])||r&&!k(qe,t)||n.push(Qe[t]);return n};Je||(A((Ge=function(){if(this instanceof Ge)throw TypeError("Symbol is not a constructor!");var e=B(arguments.length>0?arguments[0]:void 0),t=function(r){this===qe&&t.call(Xe,r),k(this,Ve)&&k(this[Ve],e)&&(this[Ve][e]=!1),rt(this,e,w(1,r))};return h&&tt&&rt(qe,e,{configurable:!0,set:t}),it(e)}).prototype,"toString",function(){return this._k}),je.f=ut,b.f=ot,Ce.f=Re.f=ct,De.f=st,ke.f=lt,Ee.f=function(e){return it(ee(e))}),O(O.G+O.W+O.F*!Je,{Symbol:Ge});for(var dt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ft=0;dt.length>ft;)ee(dt[ft++]);for(var dt=Y(ee.store),ft=0;dt.length>ft;)$e(dt[ft++]);O(O.S+O.F*!Je,"Symbol",{for:function(e){return k(Ze,e+="")?Ze[e]:Ze[e]=Ge(e)},keyFor:function(e){if(nt(e))return function(e,t){for(var r,i=C(e),n=Y(i),o=n.length,a=0;o>a;)if(i[r=n[a++]]===t)return r}(Ze,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){tt=!0},useSimple:function(){tt=!1}}),O(O.S+O.F*!Je,"Object",{create:function(e,t){return void 0===t?J(e):at(J(e),t)},defineProperty:ot,defineProperties:at,getOwnPropertyDescriptor:ut,getOwnPropertyNames:ct,getOwnPropertySymbols:lt}),We&&O(O.S+O.F*(!Je||f(function(){var e=Ge();return"[null]"!=He([e])||"{}"!=He({a:e})||"{}"!=He(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!nt(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&&Ie(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!nt(t))return t}),i[1]=t,He.apply(We,i)}}}),Ge.prototype[Ye]||E(Ge.prototype,Ye,Ge.prototype.valueOf),ie(Ge,"Symbol"),ie(Math,"Math",!0),ie(s.JSON,"JSON",!0),$e("asyncIterator"),$e("observable");var ht=u.Symbol,pt=r(function(e){e.exports={default:ht,__esModule:!0}}),mt=t(r(function(e,t){t.__esModule=!0;var r=o(Te),i=o(pt),n="function"==typeof i.default&&"symbol"==typeof r.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};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}})),vt=t(r(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")}}));O(O.S+O.F*!h,"Object",{defineProperty:b.f});var gt=u.Object,yt=function(e,t,r){return gt.defineProperty(e,t,r)},_t=r(function(e){e.exports={default:yt,__esModule:!0}}),bt=t(r(function(e,t){t.__esModule=!0;var r,i=(r=_t)&&r.__esModule?r:{default:r};t.default=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),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),wt=Object.assign,Et=!wt||f(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=wt({},e)[r]||Object.keys(wt({},t)).join("")!=i})?function(e,t){for(var r=se(e),i=arguments.length,n=1,o=ke.f,a=De.f;i>n;)for(var s,u=x(arguments[n++]),c=o?Y(u).concat(o(u)):Y(u),l=c.length,d=0;l>d;)a.call(u,s=c[d++])&&(r[s]=u[s]);return r}:wt;O(O.S+O.F,"Object",{assign:Et});var St=u.Object.assign,Tt=t(r(function(e){e.exports={default:St,__esModule:!0}}));O(O.S,"Object",{create:J});var Ot,At,$t,kt,Dt=u.Object,It=function(e,t){return Dt.create(e,t)},xt=t(r(function(e){e.exports={default:It,__esModule:!0}}));Ot="keys",At=function(){return function(e){return Y(se(e))}},$t=(u.Object||{})[Ot]||Object[Ot],(kt={})[Ot]=At($t),O(O.S+O.F*f(function(){$t(1)}),"Object",kt);var Ct=u.Object.keys,Mt=(r(function(e){e.exports={default:Ct,__esModule:!0}}),Math.floor);O(O.S,"Number",{isInteger:function(e){return!l(e)&&isFinite(e)&&Mt(e)===e}});var Pt=u.Number.isInteger,Lt=(r(function(e){e.exports={default:Pt,__esModule:!0}}),"\t\n\v\f\r   ᠎              \u2028\u2029\ufeff"),Rt="["+Lt+"]",Nt=RegExp("^"+Rt+Rt+"*"),jt=RegExp(Rt+Rt+"*$"),Ft=function(e,t,r){var i={},n=f(function(){return!!Lt[e]()||"​…"!="​…"[e]()}),o=i[e]=n?t(Bt):Lt[e];r&&(i[r]=o),O(O.P+O.F*n,"String",i)},Bt=Ft.trim=function(e,t){return e=String(a(e)),1&t&&(e=e.replace(Nt,"")),2&t&&(e=e.replace(jt,"")),e},Ut=Ft,zt=s.parseFloat,Gt=Ut.trim,Wt=1/zt(Lt+"-0")!=-1/0?function(e){var t=Gt(String(e),3),r=zt(t);return 0===r&&"-"==t.charAt(0)?-0:r}:zt;O(O.S+O.F*(Number.parseFloat!=Wt),"Number",{parseFloat:Wt});var Ht=parseFloat;function Vt(e){return"function"==typeof e}function Yt(e){return Object(e)===e&&"[object Object]"===String(e)&&!Vt(e)&&(t=e,!Array.isArray(t));var t}r(function(e){e.exports={default:Ht,__esModule:!0}});var Kt=xt(null);function Zt(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++Kt.count);var i=r+"_"+t,n=Kt[i];return n||(n=Kt[i]=[]),n}function Qt(e,t,r){var i=xt(null);i.type=t,i.target=e,r&&Tt(i,Yt(r)?r:{data:r}),Zt(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function Xt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];Vt(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){qt(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),Zt(e,t).push(o)}function qt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=Zt(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}Kt.count=0;var Jt=function(){function e(t,r){var i=this;if(vt(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":mt(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 bt(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Xt(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 qt(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return Qt(this.__target,e,{data:t}),this}}]),e}();e.emitEventCache=Qt,e.addEventCache=Xt,e.removeEventCache=qt,e.CustEvent=Jt,Object.defineProperty(e,"__esModule",{value:!0})}(t)},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});t.ERRORNO={NET_ERROR:100,CODEC_ERROR:101,CANNOT_SEEK:102,ENDOFSTREAM_ERROR:103,MEDIASOURCE_ERROR:104,SOURCEBUFFER_ERROR:105,SBABORT_ERROR:106,APPENDBUFFER_ERROR:107}},function(e,t,r){e.exports=function(){function e(e){return e&&e.__esModule?e.default:e}function t(e,t){return e(t={exports:{}},t.exports),t.exports}var r=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")}})),i=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)}),n=t(function(e){var t=e.exports={version:"2.5.0"};"number"==typeof __e&&(__e=t)}),o=function(e,t,r){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(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)}},a=function(e){return"object"==typeof e?null!==e:"function"==typeof e},s=function(e){if(!a(e))throw TypeError(e+" is not an object!");return e},u=function(e){try{return!!e()}catch(e){return!0}},c=!u(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),l=i.document,d=a(l)&&a(l.createElement),f=function(e){return d?l.createElement(e):{}},h=!c&&!u(function(){return 7!=Object.defineProperty(f("div"),"a",{get:function(){return 7}}).a}),p=function(e,t){if(!a(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!a(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!a(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!a(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},m=Object.defineProperty,v={f:c?Object.defineProperty:function(e,t,r){if(s(e),t=p(t,!0),s(r),h)try{return m(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}},g=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},y=c?function(e,t,r){return v.f(e,t,g(1,r))}:function(e,t,r){return e[t]=r,e},_=function(e,t,r){var a,s,u,c=e&_.F,l=e&_.G,d=e&_.S,f=e&_.P,h=e&_.B,p=e&_.W,m=l?n:n[t]||(n[t]={}),v=m.prototype,g=l?i:d?i[t]:(i[t]||{}).prototype;for(a in l&&(r=t),r)(s=!c&&g&&void 0!==g[a])&&a in m||(u=s?g[a]:r[a],m[a]=l&&"function"!=typeof g[a]?r[a]:h&&s?o(u,i):p&&g[a]==u?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}(u):f&&"function"==typeof u?o(Function.call,u):u,f&&((m.virtual||(m.virtual={}))[a]=u,e&_.R&&v&&!v[a]&&y(v,a,u)))};_.F=1,_.G=2,_.S=4,_.P=8,_.B=16,_.W=32,_.U=64,_.R=128;var b=_;b(b.S+b.F*!c,"Object",{defineProperty:v.f});var w,E=n.Object,S=function(e,t,r){return E.defineProperty(e,t,r)},T=t(function(e){e.exports={default:S,__esModule:!0}}),O=e(t(function(e,t){t.__esModule=!0;var r,i=(r=T)&&r.__esModule?r:{default:r};t.default=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),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),A=Math.ceil,$=Math.floor,k=function(e){return isNaN(e=+e)?0:(e>0?$:A)(e)},D=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},I=y,x={}.hasOwnProperty,C=function(e,t){return x.call(e,t)},M={}.toString,P=function(e){return M.call(e).slice(8,-1)},L=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==P(e)?e.split(""):Object(e)},R=function(e){return L(D(e))},N=Math.min,j=Math.max,F=Math.min,B=i["__core-js_shared__"]||(i["__core-js_shared__"]={}),U=function(e){return B[e]||(B[e]={})},z=0,G=Math.random(),W=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++z+G).toString(36))},H=U("keys"),V=function(e){return H[e]||(H[e]=W(e))},Y=(w=!1,function(e,t,r){var i,n,o=R(e),a=(i=o.length)>0?N(k(i),9007199254740991):0,s=function(e,t){return(e=k(e))<0?j(e+t,0):F(e,t)}(r,a);if(w&&t!=t){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((w||s in o)&&o[s]===t)return w||s||0;return!w&&-1}),K=V("IE_PROTO"),Z=function(e,t){var r,i=R(e),n=0,o=[];for(r in i)r!=K&&C(i,r)&&o.push(r);for(;t.length>n;)C(i,r=t[n++])&&(~Y(o,r)||o.push(r));return o},Q="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),X=Object.keys||function(e){return Z(e,Q)},q=c?Object.defineProperties:function(e,t){s(e);for(var r,i=X(t),n=i.length,o=0;n>o;)v.f(e,r=i[o++],t[r]);return e},J=i.document,ee=J&&J.documentElement,te=V("IE_PROTO"),re=function(){},ie=function(){var e,t=f("iframe"),r=Q.length;for(t.style.display="none",ee.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),ie=e.F;r--;)delete ie.prototype[Q[r]];return ie()},ne=Object.create||function(e,t){var r;return null!==e?(re.prototype=s(e),r=new re,re.prototype=null,r[te]=e):r=ie(),void 0===t?r:q(r,t)},oe=t(function(e){var t=U("wks"),r=i.Symbol,n="function"==typeof r,o=e.exports=function(e){return t[e]||(t[e]=n&&r[e]||(n?r:W)("Symbol."+e))};o.store=t}),ae=v.f,se=oe("toStringTag"),ue=function(e,t,r){e&&!C(e=r?e:e.prototype,se)&&ae(e,se,{configurable:!0,value:t})},ce={};y(ce,oe("iterator"),function(){return this});var le,de=function(e,t,r){e.prototype=ne(ce,{next:g(1,r)}),ue(e,t+" Iterator")},fe=function(e){return Object(D(e))},he=V("IE_PROTO"),pe=Object.prototype,me=Object.getPrototypeOf||function(e){return e=fe(e),C(e,he)?e[he]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?pe:null},ve=oe("iterator"),ge=!([].keys&&"next"in[].keys()),ye=function(e,t,r,i,n,o,a){de(r,t,i);var s,u,c,l=function(e){if(!ge&&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)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[ve]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,_="Array"==t&&p.entries||m;if(_&&(c=me(_.call(new e)))!==Object.prototype&&c.next&&ue(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(ge||h||!p[ve])&&y(p,ve,v),n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||I(p,u,s[u]);else b(b.P+b.F*(ge||h),t,s);return s},_e=(le=!0,function(e,t){var r,i,n=String(D(e)),o=k(t),a=n.length;return o<0||o>=a?le?"":void 0:(r=n.charCodeAt(o))<55296||r>56319||o+1===a||(i=n.charCodeAt(o+1))<56320||i>57343?le?n.charAt(o):r:le?n.slice(o,o+2):i-56320+(r-55296<<10)+65536});ye(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=_e(t,r),this._i+=e.length,{value:e,done:!1})});for(var be=function(e,t){return{value:t,done:!!e}},we=(ye(Array,"Array",function(e,t){this._t=R(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,be(1)):be(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values"),oe("toStringTag")),Ee="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),Se=0;Se<Ee.length;Se++){var Te=Ee[Se],Oe=i[Te],Ae=Oe&&Oe.prototype;Ae&&!Ae[we]&&y(Ae,we,Te)}var $e={f:oe},ke=$e.f("iterator"),De=t(function(e){e.exports={default:ke,__esModule:!0}}),Ie=t(function(e){var t=W("meta"),r=v.f,i=0,n=Object.isExtensible||function(){return!0},o=!u(function(){return n(Object.preventExtensions({}))}),s=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},c=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!a(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!C(e,t)){if(!n(e))return"F";if(!r)return"E";s(e)}return e[t].i},getWeak:function(e,r){if(!C(e,t)){if(!n(e))return!0;if(!r)return!1;s(e)}return e[t].w},onFreeze:function(e){return o&&c.NEED&&n(e)&&!C(e,t)&&s(e),e}}}),xe=v.f,Ce=function(e){var t=n.Symbol||(n.Symbol={});"_"==e.charAt(0)||e in t||xe(t,e,{value:$e.f(e)})},Me={f:Object.getOwnPropertySymbols},Pe={f:{}.propertyIsEnumerable},Le=Array.isArray||function(e){return"Array"==P(e)},Re=Q.concat("length","prototype"),Ne={f:Object.getOwnPropertyNames||function(e){return Z(e,Re)}},je=Ne.f,Fe={}.toString,Be="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Ue={f:function(e){return Be&&"[object Window]"==Fe.call(e)?function(e){try{return je(e)}catch(e){return Be.slice()}}(e):je(R(e))}},ze=Object.getOwnPropertyDescriptor,Ge={f:c?ze:function(e,t){if(e=R(e),t=p(t,!0),h)try{return ze(e,t)}catch(e){}if(C(e,t))return g(!Pe.f.call(e,t),e[t])}},We=Ie.KEY,He=Ge.f,Ve=v.f,Ye=Ue.f,Ke=i.Symbol,Ze=i.JSON,Qe=Ze&&Ze.stringify,Xe=oe("_hidden"),qe=oe("toPrimitive"),Je={}.propertyIsEnumerable,et=U("symbol-registry"),tt=U("symbols"),rt=U("op-symbols"),it=Object.prototype,nt="function"==typeof Ke,ot=i.QObject,at=!ot||!ot.prototype||!ot.prototype.findChild,st=c&&u(function(){return 7!=ne(Ve({},"a",{get:function(){return Ve(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=He(it,t);i&&delete it[t],Ve(e,t,r),i&&e!==it&&Ve(it,t,i)}:Ve,ut=function(e){var t=tt[e]=ne(Ke.prototype);return t._k=e,t},ct=nt&&"symbol"==typeof Ke.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof Ke},lt=function(e,t,r){return e===it&<(rt,t,r),s(e),t=p(t,!0),s(r),C(tt,t)?(r.enumerable?(C(e,Xe)&&e[Xe][t]&&(e[Xe][t]=!1),r=ne(r,{enumerable:g(0,!1)})):(C(e,Xe)||Ve(e,Xe,g(1,{})),e[Xe][t]=!0),st(e,t,r)):Ve(e,t,r)},dt=function(e,t){s(e);for(var r,i=function(e){var t=X(e),r=Me.f;if(r)for(var i,n=r(e),o=Pe.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=R(t)),n=0,o=i.length;o>n;)lt(e,r=i[n++],t[r]);return e},ft=function(e){var t=Je.call(this,e=p(e,!0));return!(this===it&&C(tt,e)&&!C(rt,e))&&(!(t||!C(this,e)||!C(tt,e)||C(this,Xe)&&this[Xe][e])||t)},ht=function(e,t){if(e=R(e),t=p(t,!0),e!==it||!C(tt,t)||C(rt,t)){var r=He(e,t);return!r||!C(tt,t)||C(e,Xe)&&e[Xe][t]||(r.enumerable=!0),r}},pt=function(e){for(var t,r=Ye(R(e)),i=[],n=0;r.length>n;)C(tt,t=r[n++])||t==Xe||t==We||i.push(t);return i},mt=function(e){for(var t,r=e===it,i=Ye(r?rt:R(e)),n=[],o=0;i.length>o;)!C(tt,t=i[o++])||r&&!C(it,t)||n.push(tt[t]);return n};nt||(I((Ke=function(){if(this instanceof Ke)throw TypeError("Symbol is not a constructor!");var e=W(arguments.length>0?arguments[0]:void 0),t=function(r){this===it&&t.call(rt,r),C(this,Xe)&&C(this[Xe],e)&&(this[Xe][e]=!1),st(this,e,g(1,r))};return c&&at&&st(it,e,{configurable:!0,set:t}),ut(e)}).prototype,"toString",function(){return this._k}),Ge.f=ht,v.f=lt,Ne.f=Ue.f=pt,Pe.f=ft,Me.f=mt,$e.f=function(e){return ut(oe(e))}),b(b.G+b.W+b.F*!nt,{Symbol:Ke});for(var vt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),gt=0;vt.length>gt;)oe(vt[gt++]);for(var yt=X(oe.store),_t=0;yt.length>_t;)Ce(yt[_t++]);b(b.S+b.F*!nt,"Symbol",{for:function(e){return C(et,e+="")?et[e]:et[e]=Ke(e)},keyFor:function(e){if(ct(e))return function(e,t){for(var r,i=R(e),n=X(i),o=n.length,a=0;o>a;)if(i[r=n[a++]]===t)return r}(et,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){at=!0},useSimple:function(){at=!1}}),b(b.S+b.F*!nt,"Object",{create:function(e,t){return void 0===t?ne(e):dt(ne(e),t)},defineProperty:lt,defineProperties:dt,getOwnPropertyDescriptor:ht,getOwnPropertyNames:pt,getOwnPropertySymbols:mt}),Ze&&b(b.S+b.F*(!nt||u(function(){var e=Ke();return"[null]"!=Qe([e])||"{}"!=Qe({a:e})||"{}"!=Qe(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!ct(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&&Le(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!ct(t))return t}),i[1]=t,Qe.apply(Ze,i)}}}),Ke.prototype[qe]||y(Ke.prototype,qe,Ke.prototype.valueOf),ue(Ke,"Symbol"),ue(Math,"Math",!0),ue(i.JSON,"JSON",!0),Ce("asyncIterator"),Ce("observable");var bt,wt,Et,St,Tt=n.Symbol,Ot=t(function(e){e.exports={default:Tt,__esModule:!0}}),At=e(t(function(e,t){t.__esModule=!0;var r=o(De),i=o(Ot),n="function"==typeof i.default&&"symbol"==typeof r.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};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}));bt="keys",wt=function(){return function(e){return X(fe(e))}},Et=(n.Object||{})[bt]||Object[bt],(St={})[bt]=wt(Et),b(b.S+b.F*u(function(){Et(1)}),"Object",St);var $t=n.Object.keys,kt=(t(function(e){e.exports={default:$t,__esModule:!0}}),Math.floor);b(b.S,"Number",{isInteger:function(e){return!a(e)&&isFinite(e)&&kt(e)===e}});var Dt=n.Number.isInteger,It=(t(function(e){e.exports={default:Dt,__esModule:!0}}),"\t\n\v\f\r   ᠎              \u2028\u2029\ufeff"),xt="["+It+"]",Ct=RegExp("^"+xt+xt+"*"),Mt=RegExp(xt+xt+"*$"),Pt=function(e,t,r){var i={},n=u(function(){return!!It[e]()||"​…"!="​…"[e]()}),o=i[e]=n?t(Lt):It[e];r&&(i[r]=o),b(b.P+b.F*n,"String",i)},Lt=Pt.trim=function(e,t){return e=String(D(e)),1&t&&(e=e.replace(Ct,"")),2&t&&(e=e.replace(Mt,"")),e},Rt=Pt,Nt=i.parseFloat,jt=Rt.trim,Ft=1/Nt(It+"-0")!=-1/0?function(e){var t=jt(String(e),3),r=Nt(t);return 0===r&&"-"==t.charAt(0)?-0:r}:Nt;b(b.S+b.F*(Number.parseFloat!=Ft),"Number",{parseFloat:Ft});var Bt=parseFloat;function Ut(e){return"string"==typeof e||e instanceof String}function zt(e,t){if(!Ut(e))throw new TypeError("Log's method only acccept string as argument, but not "+e+" in "+(void 0===e?"undefined":At(e)));return Ut(t)?"["+(e=Gt.FORCE_GLOBAL_TAG?Gt.GLOBAL_TAG:e||Gt.GLOBAL_TAG)+"] > "+t:"["+Gt.GLOBAL_TAG+"] > "+e}t(function(e){e.exports={default:Bt,__esModule:!0}});var Gt=function(){function e(){r(this,e)}return O(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(zt(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(zt(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(zt(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(zt(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(zt(t,r))}}]),e}();return Gt.GLOBAL_TAG="chimee",Gt.FORCE_GLOBAL_TAG=!1,Gt.ENABLE_ERROR=!0,Gt.ENABLE_INFO=!0,Gt.ENABLE_WARN=!0,Gt.ENABLE_DEBUG=!0,Gt.ENABLE_VERBOSE=!0,Gt}()},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=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}}(),n=c(r(10)),o=c(r(12)),a=c(r(13)),s=c(r(14)),u=r(0);function c(e){return e&&e.__esModule?e:{default:e}}var l=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r.loader=null,r.config={},r.config=e||{},r.bufferSize=3145728,r.cacheBuffer=new ArrayBuffer(r.bufferSize),r.cacheRemain=0,r.stashByteStart=0,r.enableStash=!0,r.stashSize=r.config.stashSize||393216,r.resumeFrom=0,r.currentRange={},r.totalReceive=0,r.seekPonit=void 0,r.timer=null,r.heartBeatInterval=null,r.preTotalReceive=0,r.seekLock=!1,r.webSocketURLReg=/wss?:\/\/(.+?)/,r.selectLoader(),r.bindEvent(),r}return 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)}(t,u.CustEvent),i(t,[{key:"selectLoader",value:function(){var e=this.config,t=this.config.src;this.webSocketURLReg.test(t)?this.loader=new a.default(t,e,this.queryHandle):n.default.isSupport()?this.loader=new n.default(t,e,this.queryHandle):s.default.isSupport()?this.loader=new s.default(t,e,this.queryHandle):o.default.isSupport()&&(this.loader=new o.default(t,e,this.queryHandle)),this.loader.arrivalDataCallback=this.onLoaderChunkArrival.bind(this)}},{key:"bindEvent",value:function(){var e=this;this.loader.on("end",function(){var t=e.cacheBuffer.slice(0,e.cacheRemain);e.arrivalDataCallback(t,e.stashByteStart),e.emit("end")}),this.loader.on("error",function(t){e.emit("error",t.data)})}},{key:"onLoaderChunkArrival",value:function(e,t,r){if((!this.seekLock||void 0!==r)&&(void 0!==r&&(this.seekPonit=r,this.seekLock=!1),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),o=0;if(void 0!==this.seekPonit?(o=this.arrivalDataCallback(n,this.stashByteStart,this.seekPonit),this.seekPonit=void 0):o=this.arrivalDataCallback(n,this.stashByteStart),o<n.byteLength){if(o>0){var a=new Uint8Array(n,o);i.set(a,0),this.cacheRemain=a.byteLength,this.stashByteStart+=o}}else this.cacheRemain=0,this.stashByteStart+=o;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(void 0!==this.seekPonit?(s=this.arrivalDataCallback(e,t,this.seekPonit),this.seekPonit=void 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.cacheRemain=0,this.totalReceive=0,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,t){this.loader.open({from:e||0,to:-1},t),this.heartbeat()}},{key:"heartbeat",value:function(){var e=this;window.clearInterval(this.heartBeatInterval),this.heartBeatInterval=setInterval(function(){e.emit("heartbeat",{speed:e.totalReceive-e.preTotalReceive,totalReceive:e.totalReceive}),e.preTotalReceive=e.totalReceive},1e3)}},{key:"resume",value:function(){this.paused=!1;var e=this.totalReceive;this.open(e)}},{key:"seek",value:function(e,t,r){this.seekLock=!0,this.totalReceive=e,this.preTotalReceive=e,this.initCacheBuffer(),this.cacheRemain=0,this.stashByteStart=0,this.open(e,r)}},{key:"destroy",value:function(){this.pause(),this.initCacheBuffer(),window.clearInterval(this.heartBeatInterval),this.heartBeatInterval=null}}]),t}();t.default=l},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default=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}}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);r.n(i);function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var a=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},s=function(e){return Object(a(e))},u={}.hasOwnProperty,c=function(e,t){return u.call(e,t)},l=o(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)}),d=l["__core-js_shared__"]||(l["__core-js_shared__"]={}),f=function(e){return d[e]||(d[e]={})},h=0,p=Math.random(),m=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++h+p).toString(36))},g=f("keys"),y=function(e){return g[e]||(g[e]=m(e))},_=y("IE_PROTO"),b=Object.prototype,w=Object.getPrototypeOf||function(e){return e=s(e),c(e,_)?e[_]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?b:null},E=o(function(e){var t=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=t)}),S=function(e,t,r){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(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)}},T=function(e){return"object"==typeof e?null!==e:"function"==typeof e},O=function(e){if(!T(e))throw TypeError(e+" is not an object!");return e},A=function(e){try{return!!e()}catch(e){return!0}},$=!A(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),k=l.document,D=T(k)&&T(k.createElement),I=function(e){return D?k.createElement(e):{}},x=!$&&!A(function(){return 7!=Object.defineProperty(I("div"),"a",{get:function(){return 7}}).a}),C=function(e,t){if(!T(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!T(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!T(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!T(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},M=Object.defineProperty,P={f:$?Object.defineProperty:function(e,t,r){if(O(e),t=C(t,!0),O(r),x)try{return M(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}},L=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},R=$?function(e,t,r){return P.f(e,t,L(1,r))}:function(e,t,r){return e[t]=r,e},N=function(e,t,r){var i,n,o,a=e&N.F,s=e&N.G,u=e&N.S,c=e&N.P,d=e&N.B,f=e&N.W,h=s?E:E[t]||(E[t]={}),p=h.prototype,m=s?l:u?l[t]:(l[t]||{}).prototype;for(i in s&&(r=t),r)(n=!a&&m&&void 0!==m[i])&&i in h||(o=n?m[i]:r[i],h[i]=s&&"function"!=typeof m[i]?r[i]:d&&n?S(o,l):f&&m[i]==o?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}(o):c&&"function"==typeof o?S(Function.call,o):o,c&&((h.virtual||(h.virtual={}))[i]=o,e&N.R&&p&&!p[i]&&R(p,i,o)))};N.F=1,N.G=2,N.S=4,N.P=8,N.B=16,N.W=32,N.U=64,N.R=128;var j,F,B,U,z=N;j="getPrototypeOf",F=function(){return function(e){return w(s(e))}},B=(E.Object||{})[j]||Object[j],(U={})[j]=F(B),z(z.S+z.F*A(function(){B(1)}),"Object",U);var G,W=E.Object.getPrototypeOf,H=n(o(function(e){e.exports={default:W,__esModule:!0}})),V=Math.ceil,Y=Math.floor,K=function(e){return isNaN(e=+e)?0:(e>0?Y:V)(e)},Z=R,Q={}.toString,X=function(e){return Q.call(e).slice(8,-1)},q=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==X(e)?e.split(""):Object(e)},J=function(e){return q(a(e))},ee=Math.min,te=Math.max,re=Math.min,ie=(G=!1,function(e,t,r){var i,n,o=J(e),a=(i=o.length)>0?ee(K(i),9007199254740991):0,s=function(e,t){return(e=K(e))<0?te(e+t,0):re(e,t)}(r,a);if(G&&t!=t){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((G||s in o)&&o[s]===t)return G||s||0;return!G&&-1}),ne=y("IE_PROTO"),oe=function(e,t){var r,i=J(e),n=0,o=[];for(r in i)r!=ne&&c(i,r)&&o.push(r);for(;t.length>n;)c(i,r=t[n++])&&(~ie(o,r)||o.push(r));return o},ae="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),se=Object.keys||function(e){return oe(e,ae)},ue=$?Object.defineProperties:function(e,t){O(e);for(var r,i=se(t),n=i.length,o=0;n>o;)P.f(e,r=i[o++],t[r]);return e},ce=l.document,le=ce&&ce.documentElement,de=y("IE_PROTO"),fe=function(){},he=function(){var e,t=I("iframe"),r=ae.length;for(t.style.display="none",le.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),he=e.F;r--;)delete he.prototype[ae[r]];return he()},pe=Object.create||function(e,t){var r;return null!==e?(fe.prototype=O(e),r=new fe,fe.prototype=null,r[de]=e):r=he(),void 0===t?r:ue(r,t)},me=o(function(e){var t=f("wks"),r=l.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:m)("Symbol."+e))}).store=t}),ve=P.f,ge=me("toStringTag"),ye=function(e,t,r){e&&!c(e=r?e:e.prototype,ge)&&ve(e,ge,{configurable:!0,value:t})},_e={};R(_e,me("iterator"),function(){return this});var be,we=function(e,t,r){e.prototype=pe(_e,{next:L(1,r)}),ye(e,t+" Iterator")},Ee=me("iterator"),Se=!([].keys&&"next"in[].keys()),Te=function(e,t,r,i,n,o,a){we(r,t,i);var s,u,c,l=function(e){if(!Se&&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)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[Ee]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=w(y.call(new e)))!==Object.prototype&&c.next&&ye(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(Se||h||!p[Ee])&&R(p,Ee,v),n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||Z(p,u,s[u]);else z(z.P+z.F*(Se||h),t,s);return s},Oe=(be=!0,function(e,t){var r,i,n=String(a(e)),o=K(t),s=n.length;return o<0||o>=s?be?"":void 0:(r=n.charCodeAt(o))<55296||r>56319||o+1===s||(i=n.charCodeAt(o+1))<56320||i>57343?be?n.charAt(o):r:be?n.slice(o,o+2):i-56320+(r-55296<<10)+65536});Te(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=Oe(t,r),this._i+=e.length,{value:e,done:!1})});for(var Ae=function(e,t){return{value:t,done:!!e}},$e=(Te(Array,"Array",function(e,t){this._t=J(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,Ae(1)):Ae(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values"),me("toStringTag")),ke="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),De=0;De<ke.length;De++){var Ie=ke[De],xe=l[Ie],Ce=xe&&xe.prototype;Ce&&!Ce[$e]&&R(Ce,$e,Ie)}var Me={f:me},Pe=Me.f("iterator"),Le=o(function(e){e.exports={default:Pe,__esModule:!0}});n(Le);var Re=o(function(e){var t=m("meta"),r=P.f,i=0,n=Object.isExtensible||function(){return!0},o=!A(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!T(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!c(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!c(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!c(e,t)&&a(e),e}}}),Ne=P.f,je=function(e){var t=E.Symbol||(E.Symbol={});"_"==e.charAt(0)||e in t||Ne(t,e,{value:Me.f(e)})},Fe={f:Object.getOwnPropertySymbols},Be={f:{}.propertyIsEnumerable},Ue=Array.isArray||function(e){return"Array"==X(e)},ze=ae.concat("length","prototype"),Ge={f:Object.getOwnPropertyNames||function(e){return oe(e,ze)}},We=Ge.f,He={}.toString,Ve="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Ye={f:function(e){return Ve&&"[object Window]"==He.call(e)?function(e){try{return We(e)}catch(e){return Ve.slice()}}(e):We(J(e))}},Ke=Object.getOwnPropertyDescriptor,Ze={f:$?Ke:function(e,t){if(e=J(e),t=C(t,!0),x)try{return Ke(e,t)}catch(e){}if(c(e,t))return L(!Be.f.call(e,t),e[t])}},Qe=Re.KEY,Xe=Ze.f,qe=P.f,Je=Ye.f,et=l.Symbol,tt=l.JSON,rt=tt&&tt.stringify,it=me("_hidden"),nt=me("toPrimitive"),ot={}.propertyIsEnumerable,at=f("symbol-registry"),st=f("symbols"),ut=f("op-symbols"),ct=Object.prototype,lt="function"==typeof et,dt=l.QObject,ft=!dt||!dt.prototype||!dt.prototype.findChild,ht=$&&A(function(){return 7!=pe(qe({},"a",{get:function(){return qe(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=Xe(ct,t);i&&delete ct[t],qe(e,t,r),i&&e!==ct&&qe(ct,t,i)}:qe,pt=function(e){var t=st[e]=pe(et.prototype);return t._k=e,t},mt=lt&&"symbol"==typeof et.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof et},vt=function(e,t,r){return e===ct&&vt(ut,t,r),O(e),t=C(t,!0),O(r),c(st,t)?(r.enumerable?(c(e,it)&&e[it][t]&&(e[it][t]=!1),r=pe(r,{enumerable:L(0,!1)})):(c(e,it)||qe(e,it,L(1,{})),e[it][t]=!0),ht(e,t,r)):qe(e,t,r)},gt=function(e,t){O(e);for(var r,i=function(e){var t=se(e),r=Fe.f;if(r)for(var i,n=r(e),o=Be.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=J(t)),n=0,o=i.length;o>n;)vt(e,r=i[n++],t[r]);return e},yt=function(e){var t=ot.call(this,e=C(e,!0));return!(this===ct&&c(st,e)&&!c(ut,e))&&(!(t||!c(this,e)||!c(st,e)||c(this,it)&&this[it][e])||t)},_t=function(e,t){if(e=J(e),t=C(t,!0),e!==ct||!c(st,t)||c(ut,t)){var r=Xe(e,t);return!r||!c(st,t)||c(e,it)&&e[it][t]||(r.enumerable=!0),r}},bt=function(e){for(var t,r=Je(J(e)),i=[],n=0;r.length>n;)c(st,t=r[n++])||t==it||t==Qe||i.push(t);return i},wt=function(e){for(var t,r=e===ct,i=Je(r?ut:J(e)),n=[],o=0;i.length>o;)!c(st,t=i[o++])||r&&!c(ct,t)||n.push(st[t]);return n};lt||(Z((et=function(){if(this instanceof et)throw TypeError("Symbol is not a constructor!");var e=m(arguments.length>0?arguments[0]:void 0),t=function(r){this===ct&&t.call(ut,r),c(this,it)&&c(this[it],e)&&(this[it][e]=!1),ht(this,e,L(1,r))};return $&&ft&&ht(ct,e,{configurable:!0,set:t}),pt(e)}).prototype,"toString",function(){return this._k}),Ze.f=_t,P.f=vt,Ge.f=Ye.f=bt,Be.f=yt,Fe.f=wt,Me.f=function(e){return pt(me(e))}),z(z.G+z.W+z.F*!lt,{Symbol:et});for(var Et="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),St=0;Et.length>St;)me(Et[St++]);for(var Tt=se(me.store),Ot=0;Tt.length>Ot;)je(Tt[Ot++]);z(z.S+z.F*!lt,"Symbol",{for:function(e){return c(at,e+="")?at[e]:at[e]=et(e)},keyFor:function(e){if(!mt(e))throw TypeError(e+" is not a symbol!");for(var t in at)if(at[t]===e)return t},useSetter:function(){ft=!0},useSimple:function(){ft=!1}}),z(z.S+z.F*!lt,"Object",{create:function(e,t){return void 0===t?pe(e):gt(pe(e),t)},defineProperty:vt,defineProperties:gt,getOwnPropertyDescriptor:_t,getOwnPropertyNames:bt,getOwnPropertySymbols:wt}),tt&&z(z.S+z.F*(!lt||A(function(){var e=et();return"[null]"!=rt([e])||"{}"!=rt({a:e})||"{}"!=rt(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!mt(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&&Ue(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!mt(t))return t}),i[1]=t,rt.apply(tt,i)}}}),et.prototype[nt]||R(et.prototype,nt,et.prototype.valueOf),ye(et,"Symbol"),ye(Math,"Math",!0),ye(l.JSON,"JSON",!0),je("asyncIterator"),je("observable");var At=E.Symbol,$t=o(function(e){e.exports={default:At,__esModule:!0}});n($t);var kt=o(function(e,t){t.__esModule=!0;var r=o(Le),i=o($t),n="function"==typeof i.default&&"symbol"==typeof r.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};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}),Dt=n(kt),It=n(o(function(e,t){t.__esModule=!0;var r,i=(r=kt)&&r.__esModule?r:{default:r};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,i.default)(t))&&"function"!=typeof t?e:t}})),xt=function(e,t){if(O(e),!T(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},Ct={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=S(Function.call,Ze.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return xt(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:xt};z(z.S,"Object",{setPrototypeOf:Ct.set});var Mt=E.Object.setPrototypeOf,Pt=o(function(e){e.exports={default:Mt,__esModule:!0}});n(Pt),z(z.S,"Object",{create:pe});var Lt=E.Object,Rt=function(e,t){return Lt.create(e,t)},Nt=o(function(e){e.exports={default:Rt,__esModule:!0}});n(Nt);var jt=n(o(function(e,t){t.__esModule=!0;var r=o(Pt),i=o(Nt),n=o(kt);function o(e){return e&&e.__esModule?e:{default:e}}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,n.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}})),Ft=Object.assign,Bt=!Ft||A(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=Ft({},e)[r]||Object.keys(Ft({},t)).join("")!=i})?function(e,t){for(var r=s(e),i=arguments.length,n=1,o=Fe.f,a=Be.f;i>n;)for(var u,c=q(arguments[n++]),l=o?se(c).concat(o(c)):se(c),d=l.length,f=0;d>f;)a.call(c,u=l[f++])&&(r[u]=c[u]);return r}:Ft;z(z.S+z.F,"Object",{assign:Bt});var Ut=E.Object.assign,zt=n(o(function(e){e.exports={default:Ut,__esModule:!0}})),Gt=n(o(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")}}));z(z.S+z.F*!$,"Object",{defineProperty:P.f});var Wt=E.Object,Ht=function(e,t,r){return Wt.defineProperty(e,t,r)},Vt=o(function(e){e.exports={default:Ht,__esModule:!0}});n(Vt);var Yt=n(o(function(e,t){t.__esModule=!0;var r,i=(r=Vt)&&r.__esModule?r:{default:r};t.default=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),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),Kt=function(){function e(){Gt(this,e),this.tagType=-1,this.dataSize=-1,this.Timestamp=-1,this.StreamID=-1,this.body=-1,this.time=-1,this.arr=[],this.size=-1}return Yt(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}();function Zt(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(Qt(r,i,1)){var o=(31&r[i])<<6|63&r[i+1];if(o>=128){t.push(String.fromCharCode(65535&o)),i+=2;continue}}}else if(r[i]<240){if(Qt(r,i,2)){var a=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(a>=2048&&55296!=(63488&a)){t.push(String.fromCharCode(65535&a)),i+=3;continue}}}else if(r[i]<248&&Qt(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 Qt(e,t,r){var i=e;if(t+r<i.length){for(;r--;)if(128!=(192&i[++t]))return!1;return!0}return!1}var Xt=function(){function e(t){Gt(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 Yt(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),o=this._current_word>>>32-n;return this._current_word<<=n,this._current_word_bits_left-=n,r=r<<n|o}},{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}(),qt=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"_ebsp2rbsp",value:function(e){for(var t=e,r=t.byteLength,i=new Uint8Array(r),n=0,o=0;o<r;o++)o>=2&&3===t[o]&&0===t[o-1]&&0===t[o-2]||(i[n]=t[o],n++);return new Uint8Array(i.buffer,0,n)}},{key:"parseSPS",value:function(t){var r=e._ebsp2rbsp(t),i=new Xt(r);i.readByte();var n=i.readByte();i.readByte();var o=i.readByte();i.readUEG();var a=e.getProfileString(n),s=e.getLevelString(o),u=1,c=420,l=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&&(c=[0,420,422,444][u]),l=i.readUEG()+8,i.readUEG(),i.readBits(1),i.readBool()))for(var d=3!==u?8:12,f=0;f<d;f++)i.readBool()&&(f<6?e._skipScalingList(i,16):e._skipScalingList(i,64));i.readUEG();var h=i.readUEG();if(0===h)i.readUEG();else if(1===h){i.readBits(1),i.readSEG(),i.readSEG();for(var p=i.readUEG(),m=0;m<p;m++)i.readSEG()}i.readUEG(),i.readBits(1);var v=i.readUEG(),g=i.readUEG(),y=i.readBits(1);0===y&&i.readBits(1),i.readBits(1);var _=0,b=0,w=0,E=0;i.readBool()&&(_=i.readUEG(),b=i.readUEG(),w=i.readUEG(),E=i.readUEG());var S=1,T=1,O=0,A=!0,$=0,k=0;if(i.readBool()){if(i.readBool()){var D=i.readByte();D>0&&D<16?(S=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][D-1],T=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][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),x=i.readBits(32);A=i.readBool(),O=($=x)/(k=2*I)}}var C=1;1===S&&1===T||(C=S/T);var M=0,P=0;0===u?(M=1,P=2-y):(M=3===u?1:2,P=(1===u?2:1)*(2-y));var L=16*(v+1),R=16*(g+1)*(2-y);L-=(_+b)*M,R-=(w+E)*P;var N=Math.ceil(L*C);return i.destroy(),i=null,{profile_string:a,level_string:s,bit_depth:l,chroma_format:c,chroma_format_string:e.getChromaFormatString(c),frame_rate:{fixed:A,fps:O,fps_den:k,fps_num:$},sar_ratio:{width:S,height:T},codec_size:{width:L,height:R},present_size:{width:N,height:R}}}},{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}(),Jt=null,er=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"parseObject",value:function(t,r,i){var n=e.parseString(t,r,i),o=e.parseScript(t,r+n.size),a=o.objectEnd;return{data:{name:n.data,value:o.data},size:o.size,objectEnd:a}}},{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,!Jt);return{data:i>0?Zt(new Uint8Array(e,t+4,i)):"",size:4+i}}},{key:"parseDate",value:function(e,t,r){var i=new DataView(e,t),n=i.getFloat64(0,!Jt),o=i.getInt16(8,!Jt);return{data:new Date(n+=60*o*1e3),size:10}}},{key:"parseString",value:function(e,t,r){var i=new DataView(e,t).getUint16(0,!Jt);return{data:i>0?Zt(new Uint8Array(e,t+2,i)):"",size:2+i}}},{key:"parseMetadata",value:function(t){var r;r=new ArrayBuffer(2),new DataView(r).setInt16(0,256,!0),Jt=256===new Int16Array(r)[0];var i=e.parseScript(t,0),n=e.parseScript(t,i.size,t.length-i.size),o={};return o[i.data]=n.data,o}},{key:"parseScript",value:function(t,r,i){var n=r,o=new Uint8Array(t).buffer,a=new DataView(o,0,i),s=null,u=a.getUint8(n);switch(n+=1,u){case 0:s=a.getFloat64(n,!Jt),n+=8;break;case 1:s=!!a.getUint8(n),n+=1;break;case 2:var c=e.parseString(o,n);s=c.data,n+=c.size;break;case 3:s={};var l=0;for(9==(16777215&a.getUint32(i-4,!Jt))&&(l=3);n<i-4;){var d=e.parseObject(o,n,i-r-l);if(d.objectEnd)break;s[d.data.name]=d.data.value,n=d.size}if(n<=i-3)9===(16777215&v.getUint32(n-1,!Jt))&&(n+=3);break;case 8:for(s={},n+=4,a.getUint32(i-4,!Jt);n<i-8;){var f=e.parseVariable(o,n);if(f.objectEnd)break;s[f.data.name]=f.data.value,n=f.size}if(n<=i-3)9===(16777215&a.getUint32(n-1,!Jt))&&(n+=3);break;case 9:s=void 0,n=1;break;case 10:s=[];var h=a.getUint32(n,!Jt);n+=4;for(var p=0;p<h;p++){var m=e.parseScript(o,n);s.push(m.data),n=m.size}break;case 11:var g=e.parseDate(o,n+1,i-1);s=g.data,n+=g.size;break;case 12:var y=e.parseString(o,n+1,i-1);s=y.data,n+=y.size;break;default:n=i,console.log("AMF","Unsupported AMF value type "+u)}return{data:s,size:n}}}]),e}(),tr=function(){function e(){Gt(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 Yt(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}(),rr=function e(t){Gt(this,e),this.type=t},ir=function(){function e(){var t;Gt(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 tr,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:0,addcoefficient:2,samples:[],length:0},this._littleEndian=(t=new ArrayBuffer(2),new DataView(t).setInt16(0,256,!0),256===new Int16Array(t)[0])}return Yt(e,[{key:"onMediaInfo",value:function(e){this._onMediaInfo=e}},{key:"parseMetadata",value:function(e){var t=er.parseMetadata(e);this._parseScriptData(t)}},{key:"_parseScriptData",value:function(e){var t=e;if(t.hasOwnProperty("onMetaData")){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 o=n/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=o,this._referenceFrameRate.fps_num=n,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=o}}if("object"===Dt(r.keyframes)){this._mediaInfo.hasKeyframesIndex=!0;var a=r.keyframes;a.times=r.times,a.filepositions=r.filepositions,this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(a),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 rr(i,this._timestampBase,"夭寿啦这个视频不是从0开始");if(r<=1)console.log(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");else{var o=new Uint8Array(e,t,r)[0],a=(240&o)>>>4,s=15&o;7===s?this._parseAVCVideoPacket(e,t+1,r-1,i,n,a):this._onError&&this._onError("Flv: Unsupported codec in video frame: "+s)}}},{key:"_parseAVCVideoPacket",value:function(e,t,r,i,n,o){if(r<4)console.log(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var a=this._littleEndian,s=new DataView(e,t,r),u=s.getUint8(0),c=16777215&s.getUint32(0,!a);if(0===u)this._parseAVCDecoderConfigurationRecord(e,t+4,r-4);else if(1===u)this._parseAVCVideoData(e,t+4,r-4,i,n,o,c);else if(2!==u)return void this._onError("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,o=this._littleEndian,a=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=a.getUint8(0),u=a.getUint8(1);a.getUint8(2),a.getUint8(3);if(1===s&&0!==u)if(this._naluLengthSize=1+(3&a.getUint8(4)),3===this._naluLengthSize||4===this._naluLengthSize){var c=31&a.getUint8(5);if(0===c||c>1)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid H264 SPS count: "+c);else{for(var l=6,d=0;d<c;d++){var f=a.getUint16(l,!o);if(l+=2,0!==f){var h=new Uint8Array(e,t+l,f);l+=f;var p=qt.parseSPS(h);i.codecWidth=p.codec_size.width,i.codecHeight=p.codec_size.height,i.presentWidth=p.present_size.width,i.presentHeight=p.present_size.height,i.config=p,i.profile=p.profile_string,i.level=p.level_string,i.bitDepth=p.bit_depth,i.chromaFormat=p.chroma_format,i.sarRatio=p.sar_ratio,i.frameRate=p.frame_rate,!1!==p.frame_rate.fixed&&0!==p.frame_rate.fps_num&&0!==p.frame_rate.fps_den||(i.frameRate=this._referenceFrameRate);var m=i.frameRate.fps_den,v=i.frameRate.fps_num;i.refSampleDuration=Math.floor(i.timescale*(m/v));for(var g=h.subarray(1,4),y="avc1.",_=0;_<3;_++){var b=g[_].toString(16);b.length<2&&(b="0"+b),y+=b}i.codec=y;var w=this._mediaInfo;w.width=i.codecWidth,w.height=i.codecHeight,w.fps=i.frameRate.fps,w.profile=i.profile,w.level=i.level,w.chromaFormat=p.chroma_format_string,w.sarNum=i.sarRatio.width,w.sarDen=i.sarRatio.height,w.videoCodec=y,w.meta=i,w.hasAudio?null!=w.audioCodec&&(w.mimeType='video/x-flv; codecs="'+w.videoCodec+","+w.audioCodec+'"'):w.mimeType='video/x-flv; codecs="'+w.videoCodec+'"',w.isComplete()&&this._onMediaInfo(w)}}var E=a.getUint8(l);if(0===E||E>1)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid H264 PPS count: "+E);else{l++;for(var S=0;S<E;S++){var T=a.getUint16(l,!o);l+=2,0!==T&&(l+=T)}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,o,a){for(var s=this._littleEndian,u=new DataView(e,t,r),c=[],l=0,d=0,f=this._naluLengthSize,h=this._timestampBase+i,p=1===o;d<r;){if(d+4>=r){console.log(this.TAG,"Malformed Nalu near timestamp "+h+", offset = "+d+", dataSize = "+r);break}var m=u.getUint32(d,!s);if(3===f&&(m>>>=8),m>r-f)return void console.log(this.TAG,"Malformed Nalus near timestamp "+h+", NaluSize > DataSize!");var v=31&u.getUint8(d+f);5===v&&(p=!0);var g=new Uint8Array(e,t+d,f+m),y={type:v,data:g};c.push(y),l+=g.byteLength,d+=f+m}if(c.length){var _=this._videoTrack,b={units:c,length:l,isKeyframe:p,dts:h,cts:a,pts:h+a};p&&(b.fileposition=n),_.samples.push(b),_.length+=l}}},{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,o=this._audioTrack;if(!n||!n.codec){(n=this._audioMetadata={}).type="audio",n.id=o.id,n.timescale=this._timescale,n.duration=this._duration;var a=new DataView(e,t,r).getUint8(0),s=a>>>4;if(10!==s)return void this._onError(DemuxErrors.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+s);var u=0,c=(12&a)>>>2,l=[5500,11025,22050,44100,48e3];if(!(c<l.length))return void this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+c);u=l[c];var d=1&a;n.audioSampleRate=u,n.channelCount=0===d?1:2,n.refSampleDuration=Math.floor(1024/n.audioSampleRate*n.timescale),n.codec="mp4a.40.5"}var f=this._parseAACAudioData(e,t+1,r-1);if(void 0!=f){if(0===f.packetType){n.config&&console.log(this.TAG,"Found another AudioSpecificConfig!");var h=f.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;var p=this._mediaInfo;return p.audioCodec="mp4a.40."+h.originalAudioObjectType,p.audioSampleRate=n.audioSampleRate,p.audioChannelCount=n.channelCount,p.hasVideo?null!=p.videoCodec&&(p.mimeType='video/x-flv; codecs="'+p.videoCodec+","+p.audioCodec+'"'):p.mimeType='video/x-flv; codecs="'+p.audioCodec+'"',this._onTrackMetadata("audio",n),void(p.isComplete()&&this._onMediaInfo(p))}if(1===f.packetType){var m=this._timestampBase+i,v={unit:f.data,dts:m,pts:m};o.samples.push(v),o.length+=f.data.length}else console.log(this.TAG,"Flv: Unsupported AAC data type "+f.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,n,o=new Uint8Array(e,t,r),a=null,s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],u=0,c=null;if(u=i=o[0]>>>3,(n=(7&o[0])<<1|o[1]>>>7)<0||n>=s.length)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var l=s[n],d=(120&o[1])>>>3;if(!(d<0||d>=8)){5===u&&(c=(7&o[1])<<1|o[2]>>>7);var f=self.navigator.userAgent.toLowerCase();return-1!==f.indexOf("firefox")?n>=6?(u=5,a=new Array(4),c=n-3):(u=2,a=new Array(2),c=n):-1!==f.indexOf("android")?(u=2,a=new Array(2),c=n):(u=5,c=n,a=new Array(4),n>=6?c=n-3:1===d&&(u=2,a=new Array(2),c=n)),a[0]=u<<3,a[0]|=(15&n)>>>1,a[1]=(15&n)<<7,a[1]|=(15&d)<<3,5===u&&(a[1]|=(15&c)>>>1,a[2]=(1&c)<<7,a[2]|=8,a[3]=0),{config:a,samplingRate:l,channelCount:d,codec:"mp4a.40."+u,originalAudioObjectType:i}}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}},{key:"hasAudio",set:function(e){this._mediaInfo.hasAudio=this._hasAudio=e}},{key:"hasVideo",set:function(e){this._mediaInfo.hasVideo=this._hasVideo=e}}]),e}(),nr=function(){function e(){Gt(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,this._dispose=!1,this.busy=!1,this.busyArr=[]}return Yt(e,[{key:"setFlv",value:function(e){return this.busy=!0,this._dispose=!1,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.busy=!1,this.offset):this.frist?this.offset:(this.parse(),this.offset)}},{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=ir._hasAudio=i,this._hasVideo=ir._hasVideo=n,{match:!0,hasAudioTrack:i,hasVideoTrack:n}):r}},{key:"dispose",value:function(){}},{key:"parse",value:function(){for(;this.index<this.tempUint8.length&&!this.stop;){this.offset=this.index;var e=new Kt;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 rr("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&&0==this.arrTag.length&&this.arrTag.push(e),e.size=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}(),or=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"init",value:function(){for(var t in 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:[]},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,o=0;o<n;o++)t+=i[o].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 a=8,s=0;s<n;s++)r.set(i[s],a),a+=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 o=e.mvex(t);return t.length>1?e.box(e.types.moov,r,i,n,o):e.box(e.types.moov,r,i,o)}},{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,o=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,o>>>8&255,255&o,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,o=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,o,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])),o=e.box(e.types.tfdt,new Uint8Array([0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r])),a=e.sdtp(t),s=e.trun(t,a.byteLength+16+16+8+16+8+8);return e.box(e.types.traf,n,o,s,a)}},{key:"sdtp",value:function(t){for(var r=t.samples||[],i=r.length,n=new Uint8Array(4+i),o=0;o<i;o++){var a=r[o].flags;n[o+4]=a.isLeading<<6|a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy}return e.box(e.types.sdtp,n)}},{key:"trun",value:function(t,r){var i=t.samples||[],n=i.length,o=12+16*n,a=new Uint8Array(o);r+=8+o,a.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,c=i[s].size,l=i[s].flags,d=i[s].cts;a.set([u>>>24&255,u>>>16&255,u>>>8&255,255&u,c>>>24&255,c>>>16&255,c>>>8&255,255&c,l.isLeading<<2|l.dependsOn,l.isDependedOn<<6|l.hasRedundancy<<4|l.isNonSync,0,0,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*s)}return e.box(e.types.trun,a)}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}}]),e}(),ar=function(){function e(){Gt(this,e)}return Yt(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}(),sr={};!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 o=i.majorVersion.split(".");n.version={major:parseInt(i.majorVersion,10),string:i.version},o.length>1&&(n.version.minor=parseInt(o[1],10)),o.length>2&&(n.version.build=parseInt(o[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);for(var a in n.name=i.browser,n.platform=i.platform,sr)sr.hasOwnProperty(a)&&delete sr[a];sr=n}();var ur=sr,cr=function e(t,r,i,n,o){Gt(this,e),this.dts=t,this.pts=r,this.duration=i,this.originalDts=n,this.isSyncPoint=o,this.fileposition=null},lr=function(){function e(){Gt(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 Yt(e,[{key:"appendSyncPoint",value:function(e){e.isSyncPoint=!0,this.syncPoints.push(e)}}]),e}(),dr=(function(){function e(){Gt(this,e),this._list=[]}Yt(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,o=0,a=i;for(e<t[0].dts&&(r=0,o=a+1);o<=a;){if((n=o+Math.floor((a-o)/2))===i||e>=t[n].dts&&e<t[n+1].dts){r=n;break}t[n].dts<e?o=n+1:a=n-1}return this._list[r]}}])}(),function(){function e(t){Gt(this,e),this._type=t,this._list=[],this._lastAppendLocation=-1}return Yt(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,o=r,a=0;if(e<t[0].originalBeginDts)return a=-1;for(;n<=o;){if((i=n+Math.floor((o-n)/2))===r||e>t[i].lastSample.originalDts&&e<t[i+1].originalBeginDts){a=i;break}t[i].originalBeginDts<e?n=i+1:o=i-1}return a}},{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}()),fr=function(){function e(t){Gt(this,e),this.TAG="MP4Remuxer",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 dr("audio"),this._videoSegmentInfoList=new dr("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!ur.chrome||!(ur.version.major<50||50===ur.version.major&&ur.version.build<2661)),this._fillSilentAfterSeek=ur.msedge||ur.msie,this._mp3UseMpegAudio=!ur.firefox}return Yt(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 IllegalStateException("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,i="mp4",n=t.codec;if("audio"===e)this._audioMeta=t,"mp3"===t.codec&&this._mp3UseMpegAudio?(i="mpeg",n="",r=new Uint8Array):r=or.generateInitSegment(t);else{if("video"!==e)return;this._videoMeta=t,r=or.generateInitSegment(t)}if(!this._onInitSegment)throw new IllegalStateException("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(e,{type:e,data:r.buffer,codec:n,container:e+"/"+i,mediaDuration:t.duration})}},{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){if(null!=this._audioMeta){var t,r=e,i=r.samples,n=void 0,o=-1,a=this._audioMeta.refSampleDuration,s="mp3"===this._audioMeta.codec&&this._mp3UseMpegAudio,u=this._dtsBaseInited&&void 0===this._audioNextDts,c=!1;if(i&&!(i.length<=1)){var l=0,d=null,f=0;s?(l=0,f=r.length):(l=8,f=8+r.length);var h=i[0].dts-this._dtsBase;if(this._audioNextDts)n=h-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())n=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&"mp3"!==this._audioMeta.originalCodec&&(c=!0);else{var p=this._audioSegmentInfoList.getLastSampleBefore(h);if(null!=p){var m=h-(p.originalDts+p.duration);m<=3&&(m=0),n=h-(p.dts+p.duration+m)}else n=0}if(c){var v=h-n,g=this._videoSegmentInfoList.getLastSegmentBefore(h);if(null!=g&&g.beginDts<v){var y=ar.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount);if(y){var _=g.beginDts,b=v-g.beginDts;Log.v(this.TAG,"InsertPrefixSilentAudio: dts: "+_+", duration: "+b),i.unshift({unit:y,dts:_,pts:_}),f+=y.byteLength}}else c=!1}var w=[];n=0;for(var E=0;E+1<i.length;E++){var S=i[E],T=S.dts-this._dtsBase,O=T-n;-1===o&&(o=O);var A=0;if(E!==i.length-1)A=i[E+1].dts-this._dtsBase-n-O;else A=w.length>=1?w[w.length-1].duration:Math.floor(a);w.push({dts:O,pts:O,cts:0,unit:S.unit,size:S.unit.byteLength,duration:A,originalDts:T,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}})}if(s)d=new Uint8Array(f);else{for(var $=8,k=0;k<w.length;++k)$+=w[k].size;(d=new Uint8Array($))[0]=$>>>24&255,d[1]=$>>>16&255,d[2]=$>>>8&255,d[3]=255&$,d.set(or.types.mdat,4)}for(var D=0;D<w.length;D++){var I=w[D].unit;d.set(I,l),l+=I.byteLength}var x=w[w.length-1];t=x.dts+x.duration,this._audioNextDts=t;var C=new lr;C.beginDts=o,C.endDts=t,C.beginPts=o,C.endPts=t,C.originalBeginDts=w[0].originalDts,C.originalEndDts=x.originalDts+x.duration,C.firstSample=new cr(w[0].dts,w[0].pts,w[0].duration,w[0].originalDts,!1),C.lastSample=new cr(x.dts,x.pts,x.duration,x.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(C),r.samples=w,r.sequenceNumber++;var M=null;M=s?new Uint8Array:or.moof(r,o),r.samples=[i[i.length-1]],r.length=0;var P={type:"audio",data:this._mergeBoxes(M,d).buffer,sampleCount:w.length,info:C};s&&u&&(P.timestampOffset=o),this._onMediaSegment("audio",P)}}}},{key:"_remuxVideo",value:function(e){if(null!=this._videoMeta){var t,r,i=e,n=i.samples,o=void 0,a=-1,s=-1;if(n&&!(n.length<=1)){var u=n[0].dts-this._dtsBase;if(this._videoNextDts)o=Math.max(u-this._videoNextDts,0);else if(this._videoSegmentInfoList.isEmpty())o=0;else{var c=this._videoSegmentInfoList.getLastSampleBefore(u);if(null!=c){var l=u-(c.originalDts+c.duration);l<=3&&(l=0),o=u-(c.dts+c.duration+l)}else o=0}var d=new lr,f=[],h=o;o=0;for(var p=0;p+1<n.length;p++){var m=n[p],v=m.dts-this._dtsBase-(0==p?h:0),g=m.isKeyframe,y=v-o,_=m.cts,b=y+_;-1===a&&(a=y,s=b);var w=0;if(p!==n.length-1)w=n[p+1].dts-this._dtsBase-o-y;else w=f.length>=1?f[f.length-1].duration:Math.floor(this._videoMeta.refSampleDuration);if(g){var E=new cr(y,b,w,m.dts,!0);E.fileposition=m.fileposition,d.appendSyncPoint(E)}f.push({dts:y,pts:b,cts:_,units:m.units,size:m.length,isKeyframe:g,duration:w,originalDts:v,flags:{isLeading:0,dependsOn:g?2:1,isDependedOn:g?1:0,hasRedundancy:0,isNonSync:g?0:1}})}for(var S=8,T=8,O=0;O<f.length;++O)T+=f[O].size;var A=new Uint8Array(T);A[0]=T>>>24&255,A[1]=T>>>16&255,A[2]=T>>>8&255,A[3]=255&T,A.set(or.types.mdat,4);for(var $=0;$<f.length;$++)for(var k=f[$].units;k.length;){var D=k.shift().data;A.set(D,S),S+=D.byteLength}var I=f[f.length-1];if(t=I.dts+I.duration,r=I.pts+I.duration,this._videoNextDts=t,d.beginDts=a,d.endDts=t,d.beginPts=s,d.endPts=r,d.originalBeginDts=f[0].originalDts,d.originalEndDts=I.originalDts+I.duration,d.firstSample=new cr(f[0].dts,f[0].pts,f[0].duration,f[0].originalDts,f[0].isKeyframe),d.lastSample=new cr(I.dts,I.pts,I.duration,I.originalDts,I.isKeyframe),this._isLive||this._videoSegmentInfoList.append(d),i.samples=f,i.sequenceNumber++,this._forceFirstIDR){var x=f[0].flags;x.dependsOn=2,x.isNonSync=0}var C=or.moof(i,a);i.samples=[n[n.length-1]],i.length=0,this._onMediaSegment("video",{type:"video",data:this._mergeBoxes(C,A).buffer,sampleCount:f.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}(),hr=function(){function e(t){Gt(this,e),or.init(),this._config={_isLive:!1},zt(this._config,t),this.onInitSegment=null,this.onMediaSegment=null,this.onMediaInfo=null,this.seekCallBack=null,this.loadmetadata=!1,this.ftyp_moov=null,this._tagdemux=new ir,this._flvparse=new nr,this.ftyp_moov_v=null,this.ftyp_moov_a=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,this._tagdemux._onTrackMetadata=this.Metadata.bind(this),this._tagdemux._onMediaInfo=this.metaSucc.bind(this),this._tagdemux._onDataAvailable=this.onDataAvailable.bind(this),this._tagdemux._onError=this.error.bind(this),this.m4mof=new fr(this._config),this.m4mof.onMediaSegment=this.onMdiaSegment.bind(this)}return Yt(e,[{key:"seek",value:function(e){this._flvparse.dispose(),this.setflvBase=this.setflvBasefrist,void 0!=e&&0!=e||(e=0,this._pendingResolveSeekPoint=-1),this._tempBaseTime!=e&&(this._tempBaseTime=e,this._tagdemux._timestampBase=e,this.m4mof.seek(e),this.m4mof.insertDiscontinuity(),this._pendingResolveSeekPoint=e)}},{key:"setflvBasefrist",value:function(e,t){var r=0;try{r=this._flvparse.setFlv(new Uint8Array(e))}catch(e){this.error(e)}if(0==this._flvparse.arrTag.length)return r;if(this._flvparse.arrTag.length>0){this._tagdemux.hasAudio=this.hasAudio=this._flvparse._hasAudio,this._tagdemux.hasVideo=this.hasVideo=this._flvparse._hasVideo,0!=this._tempBaseTime&&this._tempBaseTime==this._flvparse.arrTag[0].getTime()&&(this._tagdemux._timestampBase=0);try{this._tagdemux.moofTag(this._flvparse.arrTag)}catch(e){this.error(e)}this.setflvBase=this.setflvBaseUsually}return r}},{key:"setflvBaseUsually",value:function(e,t){var r=0;try{r=this._flvparse.setFlv(new Uint8Array(e))}catch(e){this.error(e)}if(this._flvparse.arrTag.length>0)try{this._tagdemux.moofTag(this._flvparse.arrTag)}catch(e){this.error(e)}return r}},{key:"onMdiaSegment",value:function(e,t){if(this.onMediaSegment&&this.onMediaSegment(e,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(["video",t]),this.m4mof._videoMeta=t,this.hasVideo&&!this.hasAudio)return void this.metaSucc();break;case"audio":if(this.metas.push(["audio",t]),this.m4mof._audioMeta=t,!this.hasVideo&&this.hasAudio)return void this.metaSucc()}this.hasVideo&&this.hasAudio&&this.m4mof._videoMeta&&this.m4mof._audioMeta&&this.metaSucc()}},{key:"metaSucc",value:function(e){var t=this;this.onMediaInfo&&e&&this.onMediaInfo(e||this._tagdemux._mediaInfo,{hasAudio:this.hasAudio,hasVideo:this.hasVideo}),0!=this.metas.length?e||(this.metas.length>1?this.metas.map(function(e){"video"==e[0]?t.ftyp_moov_v=or.generateInitSegment([e[1]]):t.ftyp_moov_a=or.generateInitSegment([e[1]])}):this.ftyp_moov=or.generateInitSegment([this.metas[0][1]]),this.onInitSegment&&0==this.loadmetadata&&(this.ftyp_moov?this.onInitSegment(this.ftyp_moov):this.onInitSegment(this.ftyp_moov_v,this.ftyp_moov_a),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){nr.setFlv(new Uint8Array(e));if(nr.arrTag.length>0)return nr.arrTag}},{key:"error",value:function(e){this._error&&this._error(e)}}]),e}(),pr=function(e){function t(e){Gt(this,t);var r=It(this,(t.__proto__||H(t)).call(this));return r.f2m=new hr(e),r.f2m._error=r.error.bind(r),r._onInitSegment=null,r._onMediaSegment=null,r._onMediaInfo=null,r._seekCallBack=null,r}return jt(t,e),Yt(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}(i.CustEvent);t.default=pr},function(e,t,r){e.exports=r(7)},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=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}}(),n=u(r(8)),o=u(r(9)),a=u(r(17)),s=r(18);function u(e){return e&&e.__esModule?e:{default:e}}var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="flv-player",i.video=e,i.box="flv",i.timer=null,i.seekTimer=null,i.config=(0,s.deepAssign)({},a.default,r),i.requestSetTime=!1,i.throttle=null,i.bindEvents(),i.attachMedia(),i}return 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)}(t,s.CustEvent),i(t,null,[{key:"isSupport",value:function(){var e=(new s.UAParser).getBrowser();return!("Safari"===e.name&&parseInt(e.major)<10)&&!(!window.MediaSource||!window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640020,mp4a.40.2"'))}},{key:"version",get:function(){return"1.4.9"}}]),i(t,[{key:"internalPropertyHandle",value:function(){if(Object.getOwnPropertyDescriptor){var e=this,t=Object.getOwnPropertyDescriptor(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(){e.config.isLive&&e.video.play(),e.config.lockInternalProperty&&e.internalPropertyHandle()})}},{key:"attachMedia",value:function(){var e=this;this.mediaSource=new n.default(this.video,this.config),this.mediaSource.on("error",function(t){e.emit("error",t.data),e.transmuxer&&e.transmuxer.pause()}),this.mediaSource.on("bufferFull",function(){e.pauseTransmuxer()}),this.mediaSource.on("updateend",function(){e.onmseUpdateEnd()})}},{key:"load",value:function(e){e&&(this.config.src=e),this.transmuxer=new o.default(this.mediaSource,this.config,this.globalEvent),this.transmuxerEvent(this.transmuxer),this.transmuxer.loadSource()}},{key:"transmuxerEvent",value:function(e){var t=this,r=this.mediaSource;e.on("mediaSegment",function(e){r.emit("mediaSegment",e.data)}),e.on("mediaSegmentInit",function(e){r.emit("mediaSegmentInit",e.data)}),e.on("error",function(i){t.emit("error",i.data),e.pause(),r.pause()}),e.on("end",function(e){r.endOfStream()}),e.on("heartbeat",function(e){t.emit("heartbeat",e.data)}),e.on("mediaInfo",function(e){t.mediaInfo||(t.mediaInfo=e,t.emit("mediaInfo",e.data),r.init(e.data),t.video.src=URL.createObjectURL(r.mediaSource),t.video.addEventListener("seeking",t._throttle.call(t)))})}},{key:"_throttle",value:function(){return this.throttle=(0,s.throttle)(this._seek.bind(this),200,{leading:!1}),this.throttle}},{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){var t=this;this.currentTimeLock=!0;var r=(0,s.isNumber)(e)&&!isNaN(e)?e: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.getNearestKeyframe(Math.floor(1e3*r));i&&(this.requestSetTime=!0,this.video.currentTime=i.keyframetime/1e3)}}else{s.Log.verbose(this.tag,"do seek"),this.transmuxer.pause();var n=this.transmuxer.getNearestKeyframe(Math.floor(1e3*r));r=n.keyframetime/1e3,this.seekTimer=setTimeout(function(){t.mediaSource.seek(r),t.transmuxer.seek(n)},100),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&&(s.Log.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),o=t.end(i);if(e>=n&&e<o){e>=o-this.config.lazyLoadRecoverDuration&&(r=!0);break}}r&&(window.clearInterval(this.timer),this.timer=null,s.Log.verbose(this.tag,"Continue loading from paused position"),this.transmuxer.resume(),this.mediaSource.resume())}},{key:"pauseTransmuxer",value:function(){this.transmuxer.pause(),this.mediaSource.pause(),this.timer||(this.timer=setInterval(this.heartbeat.bind(this),1e3))}},{key:"resume",value:function(){this._seek(0)}},{key:"destroy",value:function(){window.clearInterval(this.timer),window.clearInterval(this.seekTimer),this.video.removeEventListener("seeking",this.throttle),this.video&&(URL.revokeObjectURL(this.video.src),this.video.src="",this.video.removeAttribute("src"),this.transmuxer&&(this.transmuxer.pause(),this.transmuxer.destroy(),this.transmuxer=null),this.mediaSource&&(this.mediaSource.destroy(),this.mediaSource=null))}},{key:"seek",value:function(e){return this._seek(e)}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}},{key:"refresh",value:function(){this.transmuxer&&this.mediaSource?this._seek(0):s.Log.verbose(this.tag,"transmuxer & mediaSource not ready")}},{key:"stopLoad",value:function(){this.transmuxer&&this.transmuxer.pause(),this.mediaSource&&this.mediaSource.pause()}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i,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}}(),o=r(0),a=r(2),s=(i=a)&&i.__esModule?i:{default:i},u=r(1);var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,(t.__proto__||Object.getPrototypeOf(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.hasVideo=!0,i.hasAudio=!0,i.removeRangesList={video:[],audio:[]},i.removeBucketing=!1,i.timer={video:null,audio:null},i.queue={video:[],audio:[]},i.sourceBuffer={video:null,audio:null},i.mimeCodec={video:null,audio:null},i.sourceBufferEvent(),i.complete=!1,i}return 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)}(t,o.CustEvent),n(t,[{key:"init",value:function(e){if(this.mediaSource)return s.default.Error(this.tag,"MediaSource has been attached to an HTMLMediaElement!"),void this.emit("error",{errno:u.ERRORNO.MEDIASOURCE_ERROR,errmsg:"MediaSource has been attached to an HTMLMediaElement!"});e.hasAudio?this.mimeCodec.audio='audio/mp4; codecs="'+e.audioCodec+'"':this.hasAudio=!1,e.hasVideo?this.mimeCodec.video='video/mp4; codecs="'+e.videoCodec+'"':this.hasVideo=!1;var t=this.mediaSource=new window.MediaSource;t.addEventListener("sourceopen",this.e.onSourceOpen),t.addEventListener("sourceended",this.e.onSourceEnded),t.addEventListener("sourceclose",this.e.onSourceClose)}},{key:"onSourceOpen",value:function(){s.default.verbose(this.tag,"MediaSource onSourceOpen"),this.mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this.hasAudio&&this.addSourceBuffer("audio"),this.hasVideo&&this.addSourceBuffer("video"),this.hasQueueList()&&this.doUpdate(),this.emit("source_open")}},{key:"addSourceBuffer",value:function(e){var t=this;this.sourceBuffer[e]=this.mediaSource.addSourceBuffer(this.mimeCodec[e]),s.default.verbose(this.tag,"add sourcebuffer "+e);var r=this.sourceBuffer[e];r.addEventListener("error",this.e.onSourceBufferError),r.addEventListener("abort",function(){return s.default.verbose(t.tag,"sourceBuffer: abort")}),r.addEventListener("updateend",function(){t.sourceBuffer&&(t.hasRemoveList()?(t.removeRangesList.video.length&&t.cleanRangesList("video"),t.removeRangesList.audio.length&&t.cleanRangesList("audio")):t.hasQueueList()?t.doUpdate():t.complete&&!t.sourceBuffer[e].updating&&t.endOfStream(),t.emit("updateend"))})}},{key:"hasRemoveList",value:function(){return this.removeRangesList.video.length||this.removeRangesList.audio.length}},{key:"hasQueueList",value:function(){return this.queue.video.length||this.queue.audio.length}},{key:"doUpdate",value:function(){for(var e in this.queue)if(this.queue[e].length>0&&!this.sourceBuffer[e].updating){var t=this.queue[e].shift();this.appendBuffer(t,e)}}},{key:"sourceBufferEvent",value:function(){var e=this;this.on("mediaSegment",function(t){var r=t.data,i=r.type;e.needCleanupSourceBuffer(i)&&e.doCleanupSourceBuffer(i),e.queue[i].push(r.data),e.sourceBuffer[i]&&!e.hasRemoveList()&&e.doUpdate()}),this.on("mediaSegmentInit",function(t){var r=t.data,i=r.type;e.queue[i].push(r.data)})}},{key:"needCleanupSourceBuffer",value:function(e){var t=this.video.currentTime,r=this.video.buffered;return r.length>=1&&t-r.start(0)>=this.config.autoCleanupMaxBackwardDuration}},{key:"doCleanupSourceBuffer",value:function(e){for(var t=this.video.currentTime,r=this.sourceBuffer[e].buffered,i=!1,n=0;n<r.length;n++){var o=r.start(n),a=r.end(n);if(o<=t&&t<a+3&&t-o>=this.config.autoCleanupMaxBackwardDuration){i=!0;var s=t-this.config.autoCleanupMinBackwardDuration;this.removeRangesList[e].push({start:o,end:s})}}i&&!this.sourceBuffer[e].updating&&this.cleanRangesList(e)}},{key:"cleanRangesList",value:function(e){if(!this.sourceBuffer[e].updating)for(var t=this.sourceBuffer[e];this.removeRangesList[e].length&&!t.updating;){var r=this.removeRangesList[e].shift();t.remove(r.start,r.end)}}},{key:"appendBuffer",value:function(e,t){if(this.sourceBuffer[t])try{this.sourceBuffer[t].appendBuffer(e.buffer)}catch(r){this.queue[t].unshift(e),22===r.code&&(s.default.verbose(this.tag,"MediaSource bufferFull"),this.emit("bufferFull"))}}},{key:"onSourceEnded",value:function(){s.default.verbose(this.tag,"MediaSource onSourceEnded")}},{key:"onSourceClose",value:function(){s.default.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){this.emit("error",{errnono:u.ERRORNO.SOURCEBUFFER_ERROR,errmsg:e}),s.default.error(this.tag,"SourceBuffer Error: "+e)}},{key:"seek",value:function(){for(var e in this.sourceBuffer){var t=this.sourceBuffer[e];if(t){if("open"===this.mediaSource.readyState)try{t.abort()}catch(e){this.emit("error",{errno:u.ERRORNO.SBABORT_ERROR,errmsg:e}),s.default.error(this.tag,e.message)}this.queue[e]=[];for(var r=0;r<t.buffered.length;r++){var i=t.buffered.start(r),n=t.buffered.end(r);this.removeRangesList[e].push({start:i,end:n})}t.updating||this.cleanRangesList(e)}}}},{key:"resume",value:function(){this.doUpdate()}},{key:"pause",value:function(){}},{key:"endOfStream",value:function(){if(this.mediaSource){var e=this.mediaSource;this.complete=!0;var t=this.sourceBuffer;if(t.video&&t.video.updating||t.audio&&t.audio.updating)return;if("open"===e.readyState)try{e.endOfStream(),this.complete=!1}catch(e){s.default.verbose(this.tag,e),this.emit("error",{errno:u.ERRORNO.ENDOFSTREAM_ERROR,errmsg:e})}}}},{key:"destroy",value:function(){if(this.mediaSource){var e=this.mediaSource;this.queue={video:[],audio:[]},this.sourceBuffer={video:null,audio:null},this.mimeCodec={video:null,audio:null};var t=this.sourceBuffer;this.complete=!1,this.endOfStream(),t&&("closed"!==e.readyState&&(e.removeSourceBuffer(t),t.removeEventListener("error",this.e.onSourceBufferError),t.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)),this.sourceBuffer=null),e.removeEventListener("sourceopen",this.e.onSourceOpen),e.removeEventListener("sourceended",this.e.onSourceEnded),e.removeEventListener("sourceclose",this.e.onSourceClose),this.mediaSource=null}}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=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}}(),n=c(r(3)),o=r(0),a=c(r(15)),s=c(r(5)),u=r(1);function c(e){return e&&e.__esModule?e:{default:e}}var l=function(e){function t(e,r,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return n.config=r||{},n.tag="transmuxer",n.loader=null,n.CPU=null,n.keyframePoint=!1,n.w=null,n.config.webWorker&&(n.w=(0,a.default)(16),n.w.addEventListener("message",function(e){n.parseCallback.call(n,e.data)}),n.w.postMessage({cmd:"init",data:r})),n.lock=0,n}return 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)}(t,o.CustEvent),i(t,[{key:"loadSource",value:function(){this.config.webWorker?this.w.postMessage({cmd:"loadSource"}):(this.loader=new n.default(this.config),this.loader.arrivalDataCallback=this.arrivalDataCallback.bind(this),this.loader.open(),this.loaderBindEvent(this.loader))}},{key:"loaderBindEvent",value:function(e){var t=this;e.on("end",function(){t.emit("end")}),e.on("error",function(e){t.emit("error",e.data)}),e.on("heartbeat",function(e){t.emit("heartbeat",e.data)})}},{key:"arrivalDataCallback",value:function(e,t,r){var i=this;return this.CPU||(this.config.isLive?this.config._isLive=!0:this.config._isLive=!1,this.CPU=new s.default(this.config),this.CPU.onInitSegment=this.onRemuxerInitSegmentArrival.bind(this),this.CPU.onMediaSegment=this.onRemuxerMediaSegmentArrival.bind(this),this.CPU.onMediaInfo=this.onMediaInfo.bind(this),this.CPU.on("error",function(e){i.emit("error",{errno:u.ERRORNO.CODEC_ERROR,errmsg:e.data})})),void 0!==r&&this.CPU.seek(r),this.CPU.setflv(e)}},{key:"parseCallback",value:function(e){switch(e.cmd){case"mediaSegmentInit":this.emit("mediaSegmentInit",e.source);break;case"mediaSegment":this.emit("mediaSegment",e.source);break;case"mediainfo":this.mediaInfo=e.source,this.emit("mediaInfo",e.source);break;case"error":this.emit("error",e.source)}}},{key:"onMediaInfo",value:function(e){this.mediaInfo=e,this.emit("mediaInfo",e)}},{key:"onRemuxerInitSegmentArrival",value:function(e,t){this.emit("mediaSegmentInit",{type:"video",data:e}),t&&this.emit("mediaSegmentInit",{type:"audio",data:t})}},{key:"onRemuxerMediaSegmentArrival",value:function(e,t){this.emit("mediaSegment",{type:e,data:t})}},{key:"getMediaInfo",value:function(){return this.mediaInfo}},{key:"pause",value:function(){this.config.webWorker?this.w.postMessage({cmd:"pause"}):this.loader.pause()}},{key:"resume",value:function(){this.config.webWorker?this.w.postMessage({cmd:"resume"}):this.loader.resume()}},{key:"isSeekable",value:function(){return this.mediaInfo.hasKeyframesIndex}},{key:"seek",value:function(e){if(!this.isSeekable())return this.emit("error",{errno:u.ERRORNO.CANNOT_SEEK,errmsg:"这个flv视频不支持seek"}),!1;this.config.webWorker?this.w.postMessage({cmd:"seek",keyframe:e}):this.loader.seek(e.keyframePoint,!1,e.keyframetime)}},{key:"destroy",value:function(){this.config.webWorker?this.w.postMessage({cmd:"destroy"}):(this.loader.destroy(),this.loader=null,this.CPU=null)}},{key:"getNearestKeyframe",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 o=i.length,a=Math.floor(o/2);if(1===o){var s=t.indexOf(i[0]);return{keyframetime:i[0],keyframePoint:r[s]}}if(i[a]>n)return e(i.slice(0,a),n);if(i[a]<n)return e(i.slice(a),n);var u=t.indexOf(i[0]);return{keyframetime:i[0],keyframePoint:r[u]}}(t,e)}return 0}}]),t}();t.default=l},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=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}}(),n=u(r(11)),o=r(0),a=u(r(2)),s=r(1);function u(e){return e&&e.__esModule?e:{default:e}}var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="fetch",i.fetching=!1,i.config=r,i.range={from:0,to:524288},i.src=e,i.totalRange=null,i.block=524288,i.reader=null,i.requestAbort=!1,i.arrivalDataCallback=null,i.bytesStart=0,i.heartbeat=null,i}return 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)}(t,o.CustEvent),i(t,null,[{key:"isSupport",value:function(){return!(!self.fetch||!self.ReadableStream)}}]),i(t,[{key:"open",value:function(e,t){var r=this;this.requestAbort=!1;var i=new Headers,o=e||{from:0,to:-1};if(!this.config.isLive){this.range.from=o.from,this.range.to=o.to;var a=(0,n.default)(o,this.config);if("string"==typeof a)this.src=this.config.src+a;else for(var u in a)i.append(u,a[u])}t&&(this.bytesStart=0),this.bytesStart=e.from;var c={method:"GET",headers:i,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};fetch(this.src,c).then(function(e){if(e.ok){var i=e.body.getReader();return r.pump(i,t)}}).catch(function(e){r.emit("error",{errno:s.ERRORNO.NET_ERROR,errmsg:e})})}},{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 r.requestAbort=!1,e.cancel();var n=i.value.buffer;return r.arrivalDataCallback&&(r.arrivalDataCallback(n,r.bytesStart,t),r.bytesStart+=n.byteLength),r.pump(e)}r.emit("end"),a.default.verbose(r.tag,"load end")}).catch(function(e){r.emit("error",{errno:s.ERRORNO.NET_ERROR,errmsg:e.message})})}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if("range"===t.seekType){var r={},i=void 0;return i=-1!==e.to?"bytes="+e.from.toString()+"-"+e.to.toString():"bytes="+e.from.toString()+"-",r.Range=i,r}return-1!==e.to?"?start="+e.from.toString()+"&end="+e.to.toString():"?start="+e.from.toString()}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i,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}}(),o=r(4),a=(i=o)&&i.__esModule?i:{default:i},s=r(0),u=r(1);var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="RangeLoader",i.xhr=null,i.src=e,i.totalLength=null,i.chunkSizeKB=524288,i.range={},i.bytesStart=0,i.needSeek=!1,i.keyframePoint=null,i}return 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)}(t,s.CustEvent),n(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}}}]),n(t,[{key:"open",value:function(e,t){var r=this.xhr=new XMLHttpRequest;r.open("GET",this.src,!0),r.responseType="arraybuffer",r.onreadystatechange=this.onReadyStateChange.bind(this),r.onprogress=this.onProgress.bind(this),r.onload=this.onLoad.bind(this),r.onerror=this.onXhrError.bind(this);var i=e||{from:0,to:-1};this.range.from=i.from,-1===i.to&&(i.to=i.from+this.chunkSizeKB),t&&(this.bytesStart=e.from,this.needSeek=!0,this.keyframePoint=t),this.range.to=i.to;var n=(0,a.default)(i).headers;for(var o in n)r.setRequestHeader(o,n[o]);r.send()}},{key:"pause",value:function(){this.abort()}},{key:"abort",value:function(){this.xhr&&(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("error",{errno:u.ERRORNO.NET_ERROR,errmsg:r})}}},{key:"onProgress",value:function(e){this.totalLength||(this.totalLength=e.total,this.abort(),this.open())}},{key:"onLoad",value:function(e){if(this.totalLength&&this.arrivalDataCallback){var t=e.target.response;this.needSeek?(this.needSeek=!1,this.arrivalDataCallback(t,this.bytesStart,this.keyframePoint)):this.arrivalDataCallback(t,this.bytesStart),this.bytesStart+=t.byteLength,this.open({from:this.bytesStart,to:-1})}}},{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("error",{errno:u.ERRORNO.NET_ERROR,errmsg:t})}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=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}}(),n=r(0),o=r(1);var a=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="WebSocket",i.src=e,i._ws=null,i._requestAbort=!1,i._receivedLength=0,i}return 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)}(t,n.CustEvent),i(t,null,[{key:"isSupported",value:function(){try{return void 0!==window.WebSocket}catch(e){return!1}}}]),i(t,[{key:"destroy",value:function(){this._ws&&this.abort()}},{key:"open",value:function(e,t){try{var r=this._ws=new self.WebSocket(this.src);r.binaryType="arraybuffer",r.onopen=this.onWebSocketOpen.bind(this),r.onclose=this.onWebSocketClose.bind(this),r.onmessage=this.onWebSocketMessage.bind(this),r.onerror=this.onWebSocketError.bind(this)}catch(e){var i={code:e.code,msg:e.message};this.emit("error",{errno:o.ERRORNO.NET_ERROR,errmsg:i})}}},{key:"abort",value:function(){var e=this._ws;!e||0!==e.readyState&&1!==e.readyState||(this._requestAbort=!0,e.close()),this._ws=null}},{key:"onWebSocketClose",value:function(e){!0!==this._requestAbort?this.emit("end"):this._requestAbort=!1}},{key:"onWebSocketOpen",value:function(){}},{key:"onWebSocketMessage",value:function(e){var t=this;if(e.data instanceof ArrayBuffer)this.dispatchArrayBuffer(e.data);else if(e.data instanceof Blob){var r=new FileReader;r.onload=function(){t.dispatchArrayBuffer(r.result)},r.readAsArrayBuffer(e.data)}else{var i={code:-1,msg:"Unsupported WebSocket message type: "+e.data.constructor.name};this.emit("error",{errno:o.ERRORNO.NET_ERROR,errmsg:i})}}},{key:"dispatchArrayBuffer",value:function(e){var t=e,r=this.receivedLength;this.receivedLength+=t.byteLength,this.arrivalDataCallback&&this.arrivalDataCallback(t,r)}},{key:"onWebSocketError",value:function(e){var t={code:e.code,msg:e.message};this.emit("error",{errno:o.ERRORNO.NET_ERROR,errmsg:t})}}]),t}();t.default=a},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i,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}}(),o=r(4),a=(i=o)&&i.__esModule?i:{default:i},s=r(0),u=r(1);var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=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}(this,(t.__proto__||Object.getPrototypeOf(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.keyframePoint=null,i}return 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)}(t,s.CustEvent),n(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}}}]),n(t,[{key:"open",value:function(e,t){var r=this.xhr=new XMLHttpRequest;if(r.open("GET",this.src,!0),r.responseType="moz-chunked-arraybuffer",r.onreadystatechange=this.onReadyStateChange.bind(this),r.onprogress=this.onProgress.bind(this),r.onload=this.onLoadEnd.bind(this),r.onerror=this.onXhrError.bind(this),!this.config.isLive){var i=e||{from:0,to:-1};this.range.from=i.from,this.range.to=i.to,t&&(this.needSeek=!0,this.keyframePoint=t);var n=(0,a.default)(i).headers;for(var o in n)r.setRequestHeader(o,n[o])}r.send()}},{key:"pause",value:function(){this.abort()}},{key:"abort",value:function(){this.xhr&&(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("error",{errno:u.ERRORNO.NET_ERROR,errmsg: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.needSeek?(this.needSeek=!1,this.arrivalDataCallback(t,this.bytesStart,this.keyframePoint)):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("error",{errno:u.ERRORNO.NET_ERROR,errmsg:t})}}]),t}();t.default=c},function(e,t,r){function i(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}var n="[\\.|\\-|\\+|\\w|/|@]+",o="\\((/\\*.*?\\*/)?s?.*?("+n+").*?\\)";function a(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function s(e,t,i){var s={};s[i]=[];var u=t.toString(),c=u.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!c)return s;for(var l,d=c[1],f=new RegExp("(\\\\n|\\W)"+a(d)+o,"g");l=f.exec(u);)"dll-reference"!==l[3]&&s[i].push(l[3]);for(f=new RegExp("\\("+a(d)+'\\("(dll-reference\\s('+n+'))"\\)\\)'+o,"g");l=f.exec(u);)e[l[2]]||(s[i].push(l[1]),e[l[2]]=r(l[1]).m),s[l[2]]=s[l[2]]||[],s[l[2]].push(l[4]);return s}function u(e){return Object.keys(e).reduce(function(t,r){return t||e[r].length>0},!1)}e.exports=function(e,t){t=t||{};var n={main:r.m},o=t.all?{main:Object.keys(n)}:function(e,t){for(var r={main:[t]},i={main:[]},n={main:{}};u(r);)for(var o=Object.keys(r),a=0;a<o.length;a++){var c=o[a],l=r[c].pop();if(n[c]=n[c]||{},!n[c][l]&&e[c][l]){n[c][l]=!0,i[c]=i[c]||[],i[c].push(l);for(var d=s(e,e[c][l],c),f=Object.keys(d),h=0;h<f.length;h++)r[f[h]]=r[f[h]]||[],r[f[h]]=r[f[h]].concat(d[f[h]])}}return i}(n,e),a="";Object.keys(o).filter(function(e){return"main"!==e}).forEach(function(e){for(var t=0;o[e][t];)t++;o[e].push(t),n[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",a=a+"var "+e+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+o[e].map(function(t){return JSON.stringify(t)+": "+n[e][t].toString()}).join(",")+"});\n"}),a=a+"("+i.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+o.main.map(function(e){return JSON.stringify(e)+": "+n.main[e].toString()}).join(",")+"})(self);";var c=new window.Blob([a],{type:"text/javascript"});if(t.bare)return c;var l=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(c),d=new window.Worker(l);return d.objectURL=l,d}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=null,r=null,o={};function a(e,t){self.postMessage({cmd:"mediaSegmentInit",source:{type:"video",data:e}}),t&&self.postMessage({cmd:"mediaSegmentInit",source:{type:"audio",data:t}})}function s(e,t){self.postMessage({cmd:"mediaSegment",source:{type:e,data:t}})}function u(e){self.postMessage({cmd:"error",source:e})}function c(e){self.postMessage({cmd:"mediainfo",source:e})}function l(e,r,n){return t||((t=new i.default).onInitSegment=a,t.onMediaSegment=s,t.onError=u,t.onMediaInfo=c,t.on("error",function(e){self.postMessage({cmd:"error",source:e.data})})),n&&t.seek(n),t.setflv(e)}e.addEventListener("message",function(e){switch(e.data.cmd){case"init":o=e.data.data;break;case"loadSource":(r=new n.default(o)).arrivalDataCallback=l,r.open();break;case"pause":r.pause();break;case"seek":i=e.data.keyframe,r.pause(),(r=new n.default(o)).arrivalDataCallback=l,r.seek(i.keyframePoint,!1,i.keyframetime);break;case"resume":r.resume();break;case"destroy":r.destroy(),r=null,t=null}var i})};var i=o(r(5)),n=o(r(3));function o(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default={isLive:!1,box:"flv",seekInKeyframe:!0,alwaysSeekKeyframe:!0,lazyLoadMaxDuration:120,lazyLoadRecoverDuration:30,lockInternalProperty:!1,debug:!0,webWorker:!1,autoCleanupSourceBuffer:!0,autoCleanupMaxBackwardDuration:30,autoCleanupMinBackwardDuration:30,stashSize:393216,seekType:"range"}},function(e,t,r){(function(e){(function(t){var r="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t){return e(t={exports:{}},t.exports),t.exports}var o=Math.ceil,a=Math.floor,s=function(e){return isNaN(e=+e)?0:(e>0?a:o)(e)},u=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},c=n(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)}),l=n(function(e){var t=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=t)}),d=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},f=function(e,t,r){if(d(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)}},h=function(e){return"object"==typeof e?null!==e:"function"==typeof e},p=function(e){if(!h(e))throw TypeError(e+" is not an object!");return e},m=function(e){try{return!!e()}catch(e){return!0}},v=!m(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),g=c.document,y=h(g)&&h(g.createElement),_=function(e){return y?g.createElement(e):{}},b=!v&&!m(function(){return 7!=Object.defineProperty(_("div"),"a",{get:function(){return 7}}).a}),w=function(e,t){if(!h(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!h(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!h(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!h(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},E=Object.defineProperty,S={f:v?Object.defineProperty:function(e,t,r){if(p(e),t=w(t,!0),p(r),b)try{return E(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}},T=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},O=v?function(e,t,r){return S.f(e,t,T(1,r))}:function(e,t,r){return e[t]=r,e},A=function(e,t,r){var i,n,o,a=e&A.F,s=e&A.G,u=e&A.S,d=e&A.P,h=e&A.B,p=e&A.W,m=s?l:l[t]||(l[t]={}),v=m.prototype,g=s?c:u?c[t]:(c[t]||{}).prototype;for(i in s&&(r=t),r)(n=!a&&g&&void 0!==g[i])&&i in m||(o=n?g[i]:r[i],m[i]=s&&"function"!=typeof g[i]?r[i]:h&&n?f(o,c):p&&g[i]==o?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}(o):d&&"function"==typeof o?f(Function.call,o):o,d&&((m.virtual||(m.virtual={}))[i]=o,e&A.R&&v&&!v[i]&&O(v,i,o)))};A.F=1,A.G=2,A.S=4,A.P=8,A.B=16,A.W=32,A.U=64,A.R=128;var $,k=A,D=O,I={}.hasOwnProperty,x=function(e,t){return I.call(e,t)},C={},M={}.toString,P=function(e){return M.call(e).slice(8,-1)},L=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==P(e)?e.split(""):Object(e)},R=function(e){return L(u(e))},N=Math.min,j=function(e){return e>0?N(s(e),9007199254740991):0},F=Math.max,B=Math.min,U=c["__core-js_shared__"]||(c["__core-js_shared__"]={}),z=function(e){return U[e]||(U[e]={})},G=0,W=Math.random(),H=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++G+W).toString(36))},V=z("keys"),Y=function(e){return V[e]||(V[e]=H(e))},K=($=!1,function(e,t,r){var i,n=R(e),o=j(n.length),a=function(e,t){return(e=s(e))<0?F(e+t,0):B(e,t)}(r,o);if($&&t!=t){for(;o>a;)if((i=n[a++])!=i)return!0}else for(;o>a;a++)if(($||a in n)&&n[a]===t)return $||a||0;return!$&&-1}),Z=Y("IE_PROTO"),Q=function(e,t){var r,i=R(e),n=0,o=[];for(r in i)r!=Z&&x(i,r)&&o.push(r);for(;t.length>n;)x(i,r=t[n++])&&(~K(o,r)||o.push(r));return o},X="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),q=Object.keys||function(e){return Q(e,X)},J=v?Object.defineProperties:function(e,t){p(e);for(var r,i=q(t),n=i.length,o=0;n>o;)S.f(e,r=i[o++],t[r]);return e},ee=c.document,te=ee&&ee.documentElement,re=Y("IE_PROTO"),ie=function(){},ne=function(){var e,t=_("iframe"),r=X.length;for(t.style.display="none",te.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),ne=e.F;r--;)delete ne.prototype[X[r]];return ne()},oe=Object.create||function(e,t){var r;return null!==e?(ie.prototype=p(e),r=new ie,ie.prototype=null,r[re]=e):r=ne(),void 0===t?r:J(r,t)},ae=n(function(e){var t=z("wks"),r=c.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:H)("Symbol."+e))}).store=t}),se=S.f,ue=ae("toStringTag"),ce=function(e,t,r){e&&!x(e=r?e:e.prototype,ue)&&se(e,ue,{configurable:!0,value:t})},le={};O(le,ae("iterator"),function(){return this});var de,fe=function(e,t,r){e.prototype=oe(le,{next:T(1,r)}),ce(e,t+" Iterator")},he=function(e){return Object(u(e))},pe=Y("IE_PROTO"),me=Object.prototype,ve=Object.getPrototypeOf||function(e){return e=he(e),x(e,pe)?e[pe]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?me:null},ge=ae("iterator"),ye=!([].keys&&"next"in[].keys()),_e=function(){return this},be=function(e,t,r,i,n,o,a){fe(r,t,i);var s,u,c,l=function(e){if(!ye&&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)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[ge]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=ve(y.call(new e)))!==Object.prototype&&c.next&&ce(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(ye||h||!p[ge])&&O(p,ge,v),C[t]=v,C[d]=_e,n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||D(p,u,s[u]);else k(k.P+k.F*(ye||h),t,s);return s},we=(de=!0,function(e,t){var r,i,n=String(u(e)),o=s(t),a=n.length;return o<0||o>=a?de?"":void 0:(r=n.charCodeAt(o))<55296||r>56319||o+1===a||(i=n.charCodeAt(o+1))<56320||i>57343?de?n.charAt(o):r:de?n.slice(o,o+2):i-56320+(r-55296<<10)+65536});be(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=we(t,r),this._i+=e.length,{value:e,done:!1})});var Ee=function(e,t,r,i){try{return i?t(p(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&p(n.call(e)),t}},Se=ae("iterator"),Te=Array.prototype,Oe=function(e){return void 0!==e&&(C.Array===e||Te[Se]===e)},Ae=function(e,t,r){t in e?S.f(e,t,T(0,r)):e[t]=r},$e=ae("toStringTag"),ke="Arguments"==P(function(){return arguments}()),De=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),$e))?r:ke?P(t):"Object"==(i=P(t))&&"function"==typeof t.callee?"Arguments":i},Ie=ae("iterator"),xe=l.getIteratorMethod=function(e){if(void 0!=e)return e[Ie]||e["@@iterator"]||C[De(e)]},Ce=ae("iterator"),Me=!1;try{[7][Ce]().return=function(){Me=!0}}catch(e){}var Pe=function(e,t){if(!t&&!Me)return!1;var r=!1;try{var i=[7],n=i[Ce]();n.next=function(){return{done:r=!0}},i[Ce]=function(){return n},e(i)}catch(e){}return r};k(k.S+k.F*!Pe(function(e){}),"Array",{from:function(e){var t,r,i,n,o=he(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,d=xe(o);if(c&&(u=f(u,s>2?arguments[2]:void 0,2)),void 0==d||a==Array&&Oe(d))for(r=new a(t=j(o.length));t>l;l++)Ae(r,l,c?u(o[l],l):o[l]);else for(n=d.call(o),r=new a;!(i=n.next()).done;l++)Ae(r,l,c?Ee(n,u,[i.value,l],!0):i.value);return r.length=l,r}});var Le=l.Array.from,Re=n(function(e){e.exports={default:Le,__esModule:!0}}),Ne=i(Re),je=i(n(function(e,t){t.__esModule=!0;var r,i=(r=Re)&&r.__esModule?r:{default:r};t.default=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(0,i.default)(e)}})),Fe=function(e,t){return{value:t,done:!!e}};be(Array,"Array",function(e,t){this._t=R(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,Fe(1)):Fe(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values");C.Arguments=C.Array;for(var Be=ae("toStringTag"),Ue="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),ze=0;ze<Ue.length;ze++){var Ge=Ue[ze],We=c[Ge],He=We&&We.prototype;He&&!He[Be]&&O(He,Be,Ge),C[Ge]=C.Array}var Ve={f:ae},Ye=Ve.f("iterator"),Ke=n(function(e){e.exports={default:Ye,__esModule:!0}});i(Ke);var Ze=n(function(e){var t=H("meta"),r=S.f,i=0,n=Object.isExtensible||function(){return!0},o=!m(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!h(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!x(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!x(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!x(e,t)&&a(e),e}}}),Qe=S.f,Xe=function(e){var t=l.Symbol||(l.Symbol={});"_"==e.charAt(0)||e in t||Qe(t,e,{value:Ve.f(e)})},qe={f:Object.getOwnPropertySymbols},Je={f:{}.propertyIsEnumerable},et=Array.isArray||function(e){return"Array"==P(e)},tt=X.concat("length","prototype"),rt={f:Object.getOwnPropertyNames||function(e){return Q(e,tt)}},it=rt.f,nt={}.toString,ot="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],at={f:function(e){return ot&&"[object Window]"==nt.call(e)?function(e){try{return it(e)}catch(e){return ot.slice()}}(e):it(R(e))}},st=Object.getOwnPropertyDescriptor,ut={f:v?st:function(e,t){if(e=R(e),t=w(t,!0),b)try{return st(e,t)}catch(e){}if(x(e,t))return T(!Je.f.call(e,t),e[t])}},ct=Ze.KEY,lt=ut.f,dt=S.f,ft=at.f,ht=c.Symbol,pt=c.JSON,mt=pt&&pt.stringify,vt=ae("_hidden"),gt=ae("toPrimitive"),yt={}.propertyIsEnumerable,_t=z("symbol-registry"),bt=z("symbols"),wt=z("op-symbols"),Et=Object.prototype,St="function"==typeof ht,Tt=c.QObject,Ot=!Tt||!Tt.prototype||!Tt.prototype.findChild,At=v&&m(function(){return 7!=oe(dt({},"a",{get:function(){return dt(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=lt(Et,t);i&&delete Et[t],dt(e,t,r),i&&e!==Et&&dt(Et,t,i)}:dt,$t=function(e){var t=bt[e]=oe(ht.prototype);return t._k=e,t},kt=St&&"symbol"==typeof ht.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof ht},Dt=function(e,t,r){return e===Et&&Dt(wt,t,r),p(e),t=w(t,!0),p(r),x(bt,t)?(r.enumerable?(x(e,vt)&&e[vt][t]&&(e[vt][t]=!1),r=oe(r,{enumerable:T(0,!1)})):(x(e,vt)||dt(e,vt,T(1,{})),e[vt][t]=!0),At(e,t,r)):dt(e,t,r)},It=function(e,t){p(e);for(var r,i=function(e){var t=q(e),r=qe.f;if(r)for(var i,n=r(e),o=Je.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=R(t)),n=0,o=i.length;o>n;)Dt(e,r=i[n++],t[r]);return e},xt=function(e){var t=yt.call(this,e=w(e,!0));return!(this===Et&&x(bt,e)&&!x(wt,e))&&(!(t||!x(this,e)||!x(bt,e)||x(this,vt)&&this[vt][e])||t)},Ct=function(e,t){if(e=R(e),t=w(t,!0),e!==Et||!x(bt,t)||x(wt,t)){var r=lt(e,t);return!r||!x(bt,t)||x(e,vt)&&e[vt][t]||(r.enumerable=!0),r}},Mt=function(e){for(var t,r=ft(R(e)),i=[],n=0;r.length>n;)x(bt,t=r[n++])||t==vt||t==ct||i.push(t);return i},Pt=function(e){for(var t,r=e===Et,i=ft(r?wt:R(e)),n=[],o=0;i.length>o;)!x(bt,t=i[o++])||r&&!x(Et,t)||n.push(bt[t]);return n};St||(D((ht=function(){if(this instanceof ht)throw TypeError("Symbol is not a constructor!");var e=H(arguments.length>0?arguments[0]:void 0),t=function(r){this===Et&&t.call(wt,r),x(this,vt)&&x(this[vt],e)&&(this[vt][e]=!1),At(this,e,T(1,r))};return v&&Ot&&At(Et,e,{configurable:!0,set:t}),$t(e)}).prototype,"toString",function(){return this._k}),ut.f=Ct,S.f=Dt,rt.f=at.f=Mt,Je.f=xt,qe.f=Pt,Ve.f=function(e){return $t(ae(e))}),k(k.G+k.W+k.F*!St,{Symbol:ht});for(var Lt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Rt=0;Lt.length>Rt;)ae(Lt[Rt++]);for(var Nt=q(ae.store),jt=0;Nt.length>jt;)Xe(Nt[jt++]);k(k.S+k.F*!St,"Symbol",{for:function(e){return x(_t,e+="")?_t[e]:_t[e]=ht(e)},keyFor:function(e){if(!kt(e))throw TypeError(e+" is not a symbol!");for(var t in _t)if(_t[t]===e)return t},useSetter:function(){Ot=!0},useSimple:function(){Ot=!1}}),k(k.S+k.F*!St,"Object",{create:function(e,t){return void 0===t?oe(e):It(oe(e),t)},defineProperty:Dt,defineProperties:It,getOwnPropertyDescriptor:Ct,getOwnPropertyNames:Mt,getOwnPropertySymbols:Pt}),pt&&k(k.S+k.F*(!St||m(function(){var e=ht();return"[null]"!=mt([e])||"{}"!=mt({a:e})||"{}"!=mt(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!kt(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&&et(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!kt(t))return t}),i[1]=t,mt.apply(pt,i)}}}),ht.prototype[gt]||O(ht.prototype,gt,ht.prototype.valueOf),ce(ht,"Symbol"),ce(Math,"Math",!0),ce(c.JSON,"JSON",!0),Xe("asyncIterator"),Xe("observable");var Ft=l.Symbol,Bt=n(function(e){e.exports={default:Ft,__esModule:!0}});i(Bt);var Ut,zt,Gt,Wt,Ht=i(n(function(e,t){t.__esModule=!0;var r=o(Ke),i=o(Bt),n="function"==typeof i.default&&"symbol"==typeof r.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};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}));Ut="keys",zt=function(){return function(e){return q(he(e))}},Gt=(l.Object||{})[Ut]||Object[Ut],(Wt={})[Ut]=zt(Gt),k(k.S+k.F*m(function(){Gt(1)}),"Object",Wt);var Vt=l.Object.keys,Yt=i(n(function(e){e.exports={default:Vt,__esModule:!0}})),Kt=Math.floor;k(k.S,"Number",{isInteger:function(e){return!h(e)&&isFinite(e)&&Kt(e)===e}});var Zt=l.Number.isInteger,Qt=i(n(function(e){e.exports={default:Zt,__esModule:!0}})),Xt="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff",qt="["+Xt+"]",Jt=RegExp("^"+qt+qt+"*"),er=RegExp(qt+qt+"*$"),tr=function(e,t,r){var i={},n=m(function(){return!!Xt[e]()||"​…"!="​…"[e]()}),o=i[e]=n?t(rr):Xt[e];r&&(i[r]=o),k(k.P+k.F*n,"String",i)},rr=tr.trim=function(e,t){return e=String(u(e)),1&t&&(e=e.replace(Jt,"")),2&t&&(e=e.replace(er,"")),e},ir=tr,nr=c.parseFloat,or=ir.trim,ar=1/nr(Xt+"-0")!=-1/0?function(e){var t=or(String(e),3),r=nr(t);return 0===r&&"-"==t.charAt(0)?-0:r}:nr;k(k.S+k.F*(Number.parseFloat!=ar),"Number",{parseFloat:ar});var sr=parseFloat,ur=i(n(function(e){e.exports={default:sr,__esModule:!0}}));function cr(e){return void 0===e||null===e}function lr(e){return Array.isArray(e)}function dr(e){return"function"==typeof e}function fr(e){return Object(e)===e&&"[object Object]"===String(e)&&!dr(e)&&!lr(e)}function hr(e){return"number"==typeof e}function pr(e){return e instanceof Blob}function mr(e){return"string"==typeof e||e instanceof String}function vr(e){return"boolean"==typeof e}function gr(e){return cr(e)||vr(e)||mr(e)||hr(e)}function yr(e){return!!("object"===("undefined"==typeof Node?"undefined":Ht(Node))?e instanceof Node:e&&"object"===(void 0===e?"undefined":Ht(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}function _r(e){return function t(r,i,n){if(lr(r)||fr(r)){for(var o in i=gr(i)?fr(r)?{}:[]:i,r)i[o]=t(r[o],i[o],o);return i}return e(r,i,n)}}var br=_r(function(e){return e});function wr(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 Er(){return(65536*(1+Math.random())|0).toString(16).substring(1)}var Sr,Tr,Or,Ar=n(function(e){var t={},r={},i=e.exports=function(e,i,n,o,a){var s,u,c,l,d=a?function(){return e}:xe(e),h=f(n,o,i?2:1),m=0;if("function"!=typeof d)throw TypeError(e+" is not iterable!");if(Oe(d)){for(s=j(e.length);s>m;m++)if((l=i?h(p(u=e[m])[0],u[1]):h(e[m]))===t||l===r)return l}else for(c=d.call(e);!(u=c.next()).done;)if((l=Ee(c,h,u.value,i))===t||l===r)return l};i.BREAK=t,i.RETURN=r}),$r=ae("species"),kr=function(e,t){var r,i=p(e).constructor;return void 0===i||void 0==(r=p(i)[$r])?t:d(r)},Dr=c.process,Ir=c.setImmediate,xr=c.clearImmediate,Cr=c.MessageChannel,Mr=c.Dispatch,Pr=0,Lr={},Rr=function(){var e=+this;if(Lr.hasOwnProperty(e)){var t=Lr[e];delete Lr[e],t()}},Nr=function(e){Rr.call(e.data)};Ir&&xr||(Ir=function(e){for(var t=[],r=1;arguments.length>r;)t.push(arguments[r++]);return Lr[++Pr]=function(){!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])}e.apply(r,t)}("function"==typeof e?e:Function(e),t)},Sr(Pr),Pr},xr=function(e){delete Lr[e]},"process"==P(Dr)?Sr=function(e){Dr.nextTick(f(Rr,e,1))}:Mr&&Mr.now?Sr=function(e){Mr.now(f(Rr,e,1))}:Cr?(Or=(Tr=new Cr).port2,Tr.port1.onmessage=Nr,Sr=f(Or.postMessage,Or,1)):c.addEventListener&&"function"==typeof postMessage&&!c.importScripts?(Sr=function(e){c.postMessage(e+"","*")},c.addEventListener("message",Nr,!1)):Sr="onreadystatechange"in _("script")?function(e){te.appendChild(_("script")).onreadystatechange=function(){te.removeChild(this),Rr.call(e)}}:function(e){setTimeout(f(Rr,e,1),0)});var jr={set:Ir,clear:xr},Fr=jr.set,Br=c.MutationObserver||c.WebKitMutationObserver,Ur=c.process,zr=c.Promise,Gr="process"==P(Ur);var Wr,Hr,Vr,Yr,Kr={f:function(e){return new function(e){var t,r;this.promise=new e(function(e,i){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=i}),this.resolve=d(t),this.reject=d(r)}(e)}},Zr=function(e){try{return{e:!1,v:e()}}catch(e){return{e:!0,v:e}}},Qr=function(e,t){if(p(e),h(t)&&t.constructor===e)return t;var r=Kr.f(e);return(0,r.resolve)(t),r.promise},Xr=ae("species"),qr=jr.set,Jr=function(){var e,t,r,i=function(){var i,n;for(Gr&&(i=Ur.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(Gr)r=function(){Ur.nextTick(i)};else if(Br){var n=!0,o=document.createTextNode("");new Br(i).observe(o,{characterData:!0}),r=function(){o.data=n=!n}}else if(zr&&zr.resolve){var a=zr.resolve();r=function(){a.then(i)}}else r=function(){Fr.call(c,i)};return function(i){var n={fn:i,next:void 0};t&&(t.next=n),e||(e=n,r()),t=n}}(),ei=c.TypeError,ti=c.process,ri=c.Promise,ii="process"==De(ti),ni=function(){},oi=Hr=Kr.f,ai=!!function(){try{var e=ri.resolve(1),t=(e.constructor={})[ae("species")]=function(e){e(ni,ni)};return(ii||"function"==typeof PromiseRejectionEvent)&&e.then(ni)instanceof t}catch(e){}}(),si=function(e){var t;return!(!h(e)||"function"!=typeof(t=e.then))&&t},ui=function(e,t){if(!e._n){e._n=!0;var r=e._c;Jr(function(){for(var i=e._v,n=1==e._s,o=0,a=function(t){var r,o,a=n?t.ok:t.fail,s=t.resolve,u=t.reject,c=t.domain;try{a?(n||(2==e._h&&di(e),e._h=1),!0===a?r=i:(c&&c.enter(),r=a(i),c&&c.exit()),r===t.promise?u(ei("Promise-chain cycle")):(o=si(r))?o.call(r,s,u):s(r)):u(i)}catch(e){u(e)}};r.length>o;)a(r[o++]);e._c=[],e._n=!1,t&&!e._h&&ci(e)})}},ci=function(e){qr.call(c,function(){var t,r,i,n=e._v,o=li(e);if(o&&(t=Zr(function(){ii?ti.emit("unhandledRejection",n,e):(r=c.onunhandledrejection)?r({promise:e,reason:n}):(i=c.console)&&i.error&&i.error("Unhandled promise rejection",n)}),e._h=ii||li(e)?2:1),e._a=void 0,o&&t.e)throw t.v})},li=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||!li(t.promise))return!1;return!0},di=function(e){qr.call(c,function(){var t;ii?ti.emit("rejectionHandled",e):(t=c.onrejectionhandled)&&t({promise:e,reason:e._v})})},fi=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()),ui(t,!0))},hi=function(e){var t,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw ei("Promise can't be resolved itself");(t=si(e))?Jr(function(){var i={_w:r,_d:!1};try{t.call(e,f(hi,i,1),f(fi,i,1))}catch(e){fi.call(i,e)}}):(r._v=e,r._s=1,ui(r,!1))}catch(e){fi.call({_w:r,_d:!1},e)}}};ai||(ri=function(e){!function(e,t,r,i){if(!(e instanceof t)||void 0!==i&&i in e)throw TypeError(r+": incorrect invocation!")}(this,ri,"Promise","_h"),d(e),Wr.call(this);try{e(f(hi,this,1),f(fi,this,1))}catch(e){fi.call(this,e)}},(Wr=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=function(e,t,r){for(var i in t)r&&e[i]?e[i]=t[i]:O(e,i,t[i]);return e}(ri.prototype,{then:function(e,t){var r=oi(kr(this,ri));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=ii?ti.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&&ui(this,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Vr=function(){var e=new Wr;this.promise=e,this.resolve=f(hi,e,1),this.reject=f(fi,e,1)},Kr.f=oi=function(e){return e===ri||e===Yr?new Vr(e):Hr(e)}),k(k.G+k.W+k.F*!ai,{Promise:ri}),ce(ri,"Promise"),function(e){var t="function"==typeof l[e]?l[e]:c[e];v&&t&&!t[Xr]&&S.f(t,Xr,{configurable:!0,get:function(){return this}})}("Promise"),Yr=l.Promise,k(k.S+k.F*!ai,"Promise",{reject:function(e){var t=oi(this);return(0,t.reject)(e),t.promise}}),k(k.S+!0*k.F,"Promise",{resolve:function(e){return Qr(this===Yr?ri:this,e)}}),k(k.S+k.F*!(ai&&Pe(function(e){ri.all(e).catch(ni)})),"Promise",{all:function(e){var t=this,r=oi(t),i=r.resolve,n=r.reject,o=Zr(function(){var r=[],o=0,a=1;Ar(e,!1,function(e){var s=o++,u=!1;r.push(void 0),a++,t.resolve(e).then(function(e){u||(u=!0,r[s]=e,--a||i(r))},n)}),--a||i(r)});return o.e&&n(o.v),r.promise},race:function(e){var t=this,r=oi(t),i=r.reject,n=Zr(function(){Ar(e,!1,function(e){t.resolve(e).then(r.resolve,i)})});return n.e&&i(n.v),r.promise}}),k(k.P+k.R,"Promise",{finally:function(e){var t=kr(this,l.Promise||c.Promise),r="function"==typeof e;return this.then(r?function(r){return Qr(t,e()).then(function(){return r})}:e,r?function(r){return Qr(t,e()).then(function(){throw r})}:e)}}),k(k.S,"Promise",{try:function(e){var t=Kr.f(this),r=Zr(e);return(r.e?t.reject:t.resolve)(r.v),t.promise}});var pi=l.Promise,mi=i(n(function(e){e.exports={default:pi,__esModule:!0}})),vi="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window);function gi(e,t,r){var i=e;if(t+r<i.length){for(;r--;)if(128!=(192&i[++t]))return!1;return!0}return!1}var yi=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(e){return setTimeout(e,17)},_i=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.oCancelAnimationFrame||function(e){clearTimeout(e)};function bi(e,t){var r=t,i=(e=""+(e||"")).length;return(((t=(t||i)-i)>0?e.repeat?"0".repeat(t):new Array(t+1).join("0"):"")+e).slice(0,r)}var wi=i(n(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")}}));k(k.S+k.F*!v,"Object",{defineProperty:S.f});var Ei=l.Object,Si=function(e,t,r){return Ei.defineProperty(e,t,r)},Ti=n(function(e){e.exports={default:Si,__esModule:!0}});i(Ti);var Oi=i(n(function(e,t){t.__esModule=!0;var r,i=(r=Ti)&&r.__esModule?r:{default:r};t.default=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),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),Ai=Object.assign,$i=!Ai||m(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=Ai({},e)[r]||Object.keys(Ai({},t)).join("")!=i})?function(e,t){for(var r=he(e),i=arguments.length,n=1,o=qe.f,a=Je.f;i>n;)for(var s,u=L(arguments[n++]),c=o?q(u).concat(o(u)):q(u),l=c.length,d=0;l>d;)a.call(u,s=c[d++])&&(r[s]=u[s]);return r}:Ai;k(k.S+k.F,"Object",{assign:$i});var ki=l.Object.assign,Di=i(n(function(e){e.exports={default:ki,__esModule:!0}}));k(k.S,"Object",{create:oe});var Ii=l.Object,xi=function(e,t){return Ii.create(e,t)},Ci=i(n(function(e){e.exports={default:xi,__esModule:!0}})),Mi=Ci(null);function Pi(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++Mi.count);var i=r+"_"+t,n=Mi[i];return n||(n=Mi[i]=[]),n}function Li(e,t,r){var i=Ci(null);i.type=t,i.target=e,r&&Di(i,fr(r)?r:{data:r}),Pi(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function Ri(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];dr(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){Ni(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),Pi(e,t).push(o)}function Ni(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=Pi(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}Mi.count=0;var ji=function(){function e(t,r){var i=this;if(wi(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":Ht(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 Oi(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ri(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 Ni(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return Li(this.__target,e,{data:t}),this}}]),e}(),Fi=Ci(null);function Bi(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++Fi.count);var i=r+"_"+t,n=Fi[i];return n||(n=Fi[i]=[]),n}function Ui(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];dr(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){zi(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),Bi(e,t).push(o)}function zi(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=Bi(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}Fi.count=0;(function(){function e(t,r){var i=this;if(wi(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":Ht(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}Oi(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ui(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 zi(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return function(e,t,r){var i=Ci(null);i.type=t,i.target=e,r&&Di(i,fr(r)?r:{data:r}),Bi(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}(this.__target,e,{data:t}),this}}])})(),"undefined"!=typeof window&&Object.prototype.toString.call(window);var Gi=document.createElement("div"),Wi="innerText";"textContent"in Gi&&(Wi="textContent");var Hi=Array.prototype;function Vi(e,t){return e.getAttribute(t)}function Yi(e,t,r){void 0===r?e.removeAttribute(t):e.setAttribute(t,r)}function Ki(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 Zi(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 Qi(e,t){return new RegExp("(?:^|\\s)"+t+"(?=\\s|$)").test(e.className)}t.supportsPassive=!1;try{var Xi=Object.defineProperty({},"passive",{get:function(){t.supportsPassive=!0}});window.addEventListener("test",null,Xi)}catch(e){}var qi=!!t.supportsPassive&&{passive:!0};function Ji(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi;if(i){var o=zi(e,t+"_once",r);o&&(r=o)}e.removeEventListener(t,r,n)}function en(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi;if(i){var o=r;Ui(e,t+"_once",o,r=function(){for(var a=arguments.length,s=Array(a),u=0;u<a;u++)s[u]=arguments[u];o.apply(this,s),Ji(e,t,r,i,n)})}e.addEventListener(t,r,n)}function tn(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi,o=function(r){var n=un(r.target||r.srcElement,e,!0),o=an(t,e,!0),a=void 0;o.find?a=o.find(function(e){return n.find(function(t){return e===t})}):o.forEach(function(e){return!a&&n.forEach(function(t){a||e!==t||(a=t)})}),a&&i.apply(a,arguments)};Ui(e,r+"_delegate_"+t,i,o),e.addEventListener(r,o,n)}function rn(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi,o=zi(e,r+"_delegate_"+t,i);o&&e.removeEventListener(r,o,n)}function nn(e,t){return(e.currentStyle||document.defaultView.getComputedStyle(e,null))[t]||e.style[t]}function on(e,t,r){if(fr(t))for(var i in t)on(e,i,t[i]);else e.style[t]=r}function an(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document,r=arguments[2],i=t.querySelectorAll(e);return r?Ne(i):i}function sn(e){e.parentNode.removeChild(e)}function un(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 cn(e,t){return e.constructor===ln?e:new ln(e,t)}var ln=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;wi(this,e);this.selector=t;var i=void 0;t&&t.constructor===NodeList?i=Ne(t):lr(t)?i=t:mr(t)?0===t.indexOf("<")?(Gi.innerHTML=t,i=an("*",Gi,!0)):i=an(t,r,!0):i=[t],Di(this,i),this.length=i.length}return Oi(e,[{key:"each",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return Hi.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 Hi.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 cn(Hi.splice.apply(this,t))}},{key:"find",value:function(e){var t=[];this.each(function(r){t=t.concat(an(e,r,!0))});var r=cn(t);return r.parent=this,r.selector=e,r}},{key:"append",value:function(e){var t=cn(e),r=this[0];return t.each(function(e){return r.appendChild(e)}),this}},{key:"appendTo",value:function(e){return cn(e).append(this),this}},{key:"text",value:function(e){return 0===arguments.length?this[0][Wi]:this.each(function(t){t[Wi]=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?Vi(this[0],e):this.each(function(r){return Yi(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||fr(e)?this.each(function(r){return on(r,e,t)}):nn(this[0],e)}},{key:"addClass",value:function(e){return this.each(function(t){return Ki(t,e)})}},{key:"removeClass",value:function(e){return this.each(function(t){return Zi(t,e)})}},{key:"hasClass",value:function(e){return Qi(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]:qi;return this.each(function(n){return en(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]:qi;return this.each(function(n){return Ji(n,e,t,r,i)})}},{key:"delegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:qi;return this.each(function(n){return tn(n,e,t,r,i)})}},{key:"undelegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:qi;return this.each(function(n){return rn(n,e,t,r,i)})}},{key:"remove",value:function(){return this.each(function(e){return sn(e)})}}]),e}();function dn(e,t){if(!mr(e))throw new TypeError("Log's method only acccept string as argument, but not "+e+" in "+(void 0===e?"undefined":Ht(e)));return mr(t)?"["+(e=fn.FORCE_GLOBAL_TAG?fn.GLOBAL_TAG:e||fn.GLOBAL_TAG)+"] > "+t:"["+fn.GLOBAL_TAG+"] > "+e}var fn=function(){function e(){wi(this,e)}return Oi(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(dn(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(dn(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(dn(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(dn(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(dn(t,r))}}]),e}();fn.GLOBAL_TAG="chimee",fn.FORCE_GLOBAL_TAG=!1,fn.ENABLE_ERROR=!0,fn.ENABLE_INFO=!0,fn.ENABLE_WARN=!0,fn.ENABLE_DEBUG=!0,fn.ENABLE_VERBOSE=!0;var hn=n(function(e,t){!function(r,i){var n="model",o="name",a="type",s="vendor",u="version",c="mobile",l="tablet",d={extend:function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r},has:function(e,t){return"string"==typeof e&&-1!==t.toLowerCase().indexOf(e.toLowerCase())},lowerize:function(e){return e.toLowerCase()},major:function(e){return"string"==typeof e?e.replace(/[^\d\.]/g,"").split(".")[0]:void 0},trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},f={rgx:function(e,t){for(var r,i,n,o,a,s,u=0;u<t.length&&!a;){var c=t[u],l=t[u+1];for(r=i=0;r<c.length&&!a;)if(a=c[r++].exec(e))for(n=0;n<l.length;n++)s=a[++i],"object"==typeof(o=l[n])&&o.length>0?2==o.length?"function"==typeof o[1]?this[o[0]]=o[1].call(this,s):this[o[0]]=o[1]:3==o.length?"function"!=typeof o[1]||o[1].exec&&o[1].test?this[o[0]]=s?s.replace(o[1],o[2]):void 0:this[o[0]]=s?o[1].call(this,s,o[2]):void 0:4==o.length&&(this[o[0]]=s?o[3].call(this,s.replace(o[1],o[2])):void 0):this[o]=s||void 0;u+=2}},str:function(e,t){for(var r in t)if("object"==typeof t[r]&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(d.has(t[r][i],e))return"?"===r?void 0:r}else if(d.has(t[r],e))return"?"===r?void 0:r;return e}},h={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2000:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}},p={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[o,u],[/(opios)[\/\s]+([\w\.]+)/i],[[o,"Opera Mini"],u],[/\s(opr)\/([\w\.]+)/i],[[o,"Opera"],u],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]+)*/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i],[o,u],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[o,"IE"],u],[/(edge)\/((\d+)?[\w\.]+)/i],[o,u],[/(yabrowser)\/([\w\.]+)/i],[[o,"Yandex"],u],[/(puffin)\/([\w\.]+)/i],[[o,"Puffin"],u],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[o,"UCBrowser"],u],[/(comodo_dragon)\/([\w\.]+)/i],[[o,/_/g," "],u],[/(micromessenger)\/([\w\.]+)/i],[[o,"WeChat"],u],[/(QQ)\/([\d\.]+)/i],[o,u],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[o,u],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[u,[o,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[u,[o,"Facebook"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[u,[o,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[o,/(.+)/,"$1 WebView"],u],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[o,/(.+(?:g|us))(.+)/,"$1 $2"],u],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[u,[o,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[o,u],[/(dolfin)\/([\w\.]+)/i],[[o,"Dolphin"],u],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[o,"Chrome"],u],[/(coast)\/([\w\.]+)/i],[[o,"Opera Coast"],u],[/fxios\/([\w\.-]+)/i],[u,[o,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[u,[o,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[u,o],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[o,"GSA"],u],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[o,[u,f.str,h.browser.oldsafari.version]],[/(konqueror)\/([\w\.]+)/i,/(webkit|khtml)\/([\w\.]+)/i],[o,u],[/(navigator|netscape)\/([\w\.-]+)/i],[[o,"Netscape"],u],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]+)*/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[o,u]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",d.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",d.lowerize]],[/(sun4\w)[;\)]/i],[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[["architecture",d.lowerize]]],device:[[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],[n,s,[a,l]],[/applecoremedia\/[\w\.]+ \((ipad)/],[n,[s,"Apple"],[a,l]],[/(apple\s{0,1}tv)/i],[[n,"Apple TV"],[s,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[s,n,[a,l]],[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],[n,[s,"Amazon"],[a,l]],[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],[[n,f.str,h.device.amazon.model],[s,"Amazon"],[a,c]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[n,s,[a,c]],[/\((ip[honed|\s\w*]+);/i],[n,[s,"Apple"],[a,c]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[s,n,[a,c]],[/\(bb10;\s(\w+)/i],[n,[s,"BlackBerry"],[a,c]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i],[n,[s,"Asus"],[a,l]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[s,"Sony"],[n,"Xperia Tablet"],[a,l]],[/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i],[n,[s,"Sony"],[a,c]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[s,n,[a,"console"]],[/android.+;\s(shield)\sbuild/i],[n,[s,"Nvidia"],[a,"console"]],[/(playstation\s[34portablevi]+)/i],[n,[s,"Sony"],[a,"console"]],[/(sprint\s(\w+))/i],[[s,f.str,h.device.sprint.vendor],[n,f.str,h.device.sprint.model],[a,c]],[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],[s,n,[a,l]],[/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,/(zte)-(\w+)*/i,/(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i],[s,[n,/_/g," "],[a,c]],[/(nexus\s9)/i],[n,[s,"HTC"],[a,l]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[n,[s,"Huawei"],[a,c]],[/(microsoft);\s(lumia[\s\w]+)/i],[s,n,[a,c]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[n,[s,"Microsoft"],[a,"console"]],[/(kin\.[onetw]{3})/i],[[n,/\./g," "],[s,"Microsoft"],[a,c]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w+)*/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[n,[s,"Motorola"],[a,c]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[n,[s,"Motorola"],[a,l]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[s,d.trim],[n,d.trim],[a,"smarttv"]],[/hbbtv.+maple;(\d+)/i],[[n,/^/,"SmartTV"],[s,"Samsung"],[a,"smarttv"]],[/\(dtv[\);].+(aquos)/i],[n,[s,"Sharp"],[a,"smarttv"]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[s,"Samsung"],n,[a,l]],[/smart-tv.+(samsung)/i],[s,[a,"smarttv"],n],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,/sec-((sgh\w+))/i],[[s,"Samsung"],n,[a,c]],[/sie-(\w+)*/i],[n,[s,"Siemens"],[a,c]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]+)*/i],[[s,"Nokia"],n,[a,c]],[/android\s3\.[\s\w;-]{10}(a\d{3})/i],[n,[s,"Acer"],[a,l]],[/android.+([vl]k\-?\d{3})\s+build/i],[n,[s,"LG"],[a,l]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[s,"LG"],n,[a,l]],[/(lg) netcast\.tv/i],[s,n,[a,"smarttv"]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w+)*/i,/android.+lg(\-?[\d\w]+)\s+build/i],[n,[s,"LG"],[a,c]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[n,[s,"Lenovo"],[a,l]],[/linux;.+((jolla));/i],[s,n,[a,c]],[/((pebble))app\/[\d\.]+\s/i],[s,n,[a,"wearable"]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[s,n,[a,c]],[/crkey/i],[[n,"Chromecast"],[s,"Google"]],[/android.+;\s(glass)\s\d/i],[n,[s,"Google"],[a,"wearable"]],[/android.+;\s(pixel c)\s/i],[n,[s,"Google"],[a,l]],[/android.+;\s(pixel xl|pixel)\s/i],[n,[s,"Google"],[a,c]],[/android.+(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,c]],[/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,l]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[n,[s,"Meizu"],[a,l]],[/android.+a000(1)\s+build/i],[n,[s,"OnePlus"],[a,c]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[n,[s,"RCA"],[a,l]],[/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i],[n,[s,"Dell"],[a,l]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[n,[s,"Verizon"],[a,l]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[s,"Barnes & Noble"],n,[a,l]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[n,[s,"NuVision"],[a,l]],[/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i],[[s,"ZTE"],n,[a,l]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[n,[s,"Swiss"],[a,c]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[n,[s,"Swiss"],[a,l]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[n,[s,"Zeki"],[a,l]],[/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i],[[s,"Dragon Touch"],n,[a,l]],[/android.+[;\/]\s*(NS-?.+)\s+build/i],[n,[s,"Insignia"],[a,l]],[/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i],[n,[s,"NextBook"],[a,l]],[/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[s,"Voice"],n,[a,c]],[/android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i],[[s,"LvTel"],n,[a,c]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[n,[s,"Envizen"],[a,l]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[n,[s,"MachSpeed"],[a,l]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[n,[s,"Rotor"],[a,l]],[/android.+(KS(.+))\s+build/i],[n,[s,"Amazon"],[a,l]],[/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i],[s,n,[a,l]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[a,d.lowerize],s,n],[/(android.+)[;\/].+build/i],[n,[s,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[u,[o,"EdgeHTML"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[o,u],[/rv\:([\w\.]+).*(gecko)/i],[u,o]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[o,u],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[o,[u,f.str,h.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[o,"Windows"],[u,f.str,h.os.windows.version]],[/\((bb)(10);/i],[[o,"BlackBerry"],u],[/(blackberry)\w*\/?([\w\.]+)*/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,/linux;.+(sailfish);/i],[o,u],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],[[o,"Symbian"],u],[/\((series40);/i],[o],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[o,"Firefox OS"],u],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w+)*/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,/(hurd|linux)\s?([\w\.]+)*/i,/(gnu)\s?([\w\.]+)*/i],[o,u],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[o,"Chromium OS"],u],[/(sunos)\s?([\w\.]+\d)*/i],[[o,"Solaris"],u],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],[o,u],[/(haiku)\s(\w+)/i],[o,u],[/cfnetwork\/.+darwin/i,/ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[u,/_/g,"."],[o,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,/(macintosh|mac(?=_powerpc)\s)/i],[[o,"Mac OS"],[u,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,/(unix)\s?([\w\.]+)*/i],[o,u]]},m=function(e,t){if("object"==typeof e&&(t=e,e=void 0),!(this instanceof m))return new m(e,t).getResult();var i=e||(r&&r.navigator&&r.navigator.userAgent?r.navigator.userAgent:""),n=t?d.extend(p,t):p;return this.getBrowser=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.browser),e.major=d.major(e.version),e},this.getCPU=function(){var e={architecture:void 0};return f.rgx.call(e,i,n.cpu),e},this.getDevice=function(){var e={vendor:void 0,model:void 0,type:void 0};return f.rgx.call(e,i,n.device),e},this.getEngine=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.engine),e},this.getOS=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=e,this},this};m.VERSION="0.7.17",m.BROWSER={NAME:o,MAJOR:"major",VERSION:u},m.CPU={ARCHITECTURE:"architecture"},m.DEVICE={MODEL:n,VENDOR:s,TYPE:a,CONSOLE:"console",MOBILE:c,SMARTTV:"smarttv",TABLET:l,WEARABLE:"wearable",EMBEDDED:"embedded"},m.ENGINE={NAME:o,VERSION:u},m.OS={NAME:o,VERSION:u},e.exports&&(t=e.exports=m),t.UAParser=m;var v=r&&(r.jQuery||r.Zepto);if(void 0!==v){var g=new m;v.ua=g.getResult(),v.ua.get=function(){return g.getUA()},v.ua.set=function(e){g.setUA(e);var t=g.getResult();for(var r in t)v.ua[r]=t[r]}}}("object"==typeof window?window:r)});t.Log=fn,t.UAParser=hn,t.genTraversalHandler=_r,t.deepClone=function(e){if(gr(e))throw new TypeError("deepClone only accept non primitive type");return br(e)},t.deepAssign=function(){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(gr(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return br(e,n)}),n},t.camelize=wr,t.hypenate=function(e){return wr(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})},t.bind=function(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(je(i)))}},t.uuid=function(){return Er()+Er()+"-"+Er()+"-"+Er()+"-"+Er()+"-"+Er()+Er()+Er()},t.S4=Er,t.rand=function(e){for(var t="";t.length<e;)t+=Er();return t.slice(0,e)},t.getDeepProperty=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(mr(t)&&(t=t.split(".")),!lr(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(cr(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s},t.defined=function(e){return void 0!==e},t.isVoid=cr,t.isArray=lr,t.isFunction=dr,t.isObject=fr,t.isNumber=hr,t.isNumeric=function(e){return!lr(e)&&e-ur(e)+1>=0},t.isInteger=function(e){return Qt(e)},t.isEmpty=function(e){return lr(e)?0===e.length:fr(e)?0===Yt(e).length:!e},t.isEvent=function(e){return e instanceof Event||(e&&e.originalEvent)instanceof Event},t.isBlob=pr,t.isFile=function(e){return pr(e)&&mr(e.name)},t.isDate=function(e){return"[object Date]"===Object.prototype.toString.call(e)},t.isString=mr,t.isBoolean=vr,t.isPromise=function(e){return!!e&&("object"===(void 0===e?"undefined":Ht(e))||"function"==typeof e)&&"function"==typeof e.then},t.isPrimitive=gr,t.isUrl=function(e){return mr(e)&&!!e.match(/^((https?|ftp|rtsp|mms):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6}|localhost)(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i)},t.isNode=yr,t.isElement=function(e){return!!("object"===("undefined"==typeof HTMLElement?"undefined":Ht(HTMLElement))?e instanceof HTMLElement:e&&"object"===(void 0===e?"undefined":Ht(e))&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)},t.isChildNode=function(e,t){return!(!yr(e)||!yr(t))&&t.parentNode===e},t.isPosterityNode=function(e,t){if(!yr(e)||!yr(t))return!1;for(;t.parentNode;)if((t=t.parentNode)===e)return!0;return!1},t.isHTMLString=function(e){return/<[^>]+?>/.test(e)},t.isError=function(e){return e instanceof Error},t.isRegExp=function(e){return e instanceof RegExp},t.inBrowser=vi,t.makeArray=function(e){return Ne(e)},t.transObjectAttrIntoArray=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return Yt(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])},t.runRejectableQueue=function(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 mi(function(t,i){!function n(o){if(!(o>=e.length)){var a=dr(e[o])?e[o].apply(e,je(r)):e[o];return!1===a?i("stop"):mi.resolve(a).then(function(){return n(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})},t.runStoppableQueue=function(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!==(dr(e[i])?e[i].apply(e,je(r)):e[i])&&t(++i)}(0)},t.decodeUTF8=function(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(gi(r,i,1)){var o=(31&r[i])<<6|63&r[i+1];if(o>=128){t.push(String.fromCharCode(65535&o)),i+=2;continue}}}else if(r[i]<240){if(gi(r,i,2)){var a=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(a>=2048&&55296!=(63488&a)){t.push(String.fromCharCode(65535&a)),i+=3;continue}}}else if(r[i]<248&&gi(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("")},t.debounce=function(e,t,r){var i=void 0,n=void 0,o=void 0,a=void 0,s=void 0,u=function u(){var c=new Date-a;c<t&&c>=0?i=setTimeout(u,t-c):(i=null,r||(s=e.apply(o,n),i||(o=n=null)))};return function(){o=this,n=arguments,a=new Date;var c=r&&!i;return i||(i=setTimeout(u,t)),c&&(s=e.apply(o,n),o=n=null),s}},t.throttle=function(e,t,r,i){var n=void 0,o=void 0,a=void 0,s=null,u=0;r||(r={});var c=function(){u=!1===r.leading?0:new Date-0,s=null,a=e.apply(n,o),s||(n=o=null)};return t=t||0,function(){var l=new Date;u||!1!==r.leading||(u=l);var d=t-(l-u);return n=i||this,o=arguments,d<=0||d>t?(s&&(clearTimeout(s),s=null),u=l,a=e.apply(n,o),s||(n=o=null)):s||!1===r.trailing||(s=setTimeout(c,d)),a}},t.raf=yi,t.caf=_i,t.strRepeat=bi,t.formatTime=function(e){var t=Math.floor(e/3600);e=Math.floor(e%3600);var r=bi(Math.floor(e/60),2),i=bi(e=Math.floor(e%60),2);return t>=1?t+":"+r+":"+i:r+":"+i},t.appendCSS=function(e){var t=document,r=t.querySelector("style");if(!r){r=t.createElement("style");var i=t.querySelector("head");i&&i.appendChild(r)}return r.appendChild(t.createTextNode(e)),r},t.formatDate=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"yyyy-MM-dd hh:mm:ss.i",r=e.getFullYear().toString(),i={M:e.getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),i:e.getMilliseconds()};t=t.replace(/(y+)/gi,function(e,t){return r.substr(4-Math.min(4,t.length))});var n=function(e){t=t.replace(new RegExp("("+e+"+)","g"),function(t,r){return(i[e]<10&&r.length>1?"0":"")+i[e]})};for(var o in i)n(o);return t},t.getLocalStorage=function(e){try{return window.localStorage.getItem(e)}catch(r){try{var t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]*)(;|$)"));return lr(t)?unescape(t[2]):""}catch(e){return""}}},t.setLocalStorage=function(e,t){try{window.localStorage.setItem(e,t)}catch(i){var r=new Date;r.setTime(r.getTime()+2592e7);try{document.cookie=e+"="+escape(t)+";expires="+r.toUTCString()+";path=/;"}catch(e){}}},t.emitEventCache=Li,t.addEventCache=Ri,t.removeEventCache=Ni,t.CustEvent=ji,t.getAttr=Vi,t.setAttr=Yi,t.addClassName=Ki,t.removeClassName=Zi,t.hasClassName=Qi,t.removeEvent=Ji,t.addEvent=en,t.addDelegate=tn,t.removeDelegate=rn,t.getStyle=nn,t.setStyle=on,t.query=an,t.removeEl=sn,t.findParents=un,t.$=cn,t.NodeWrap=ln,Object.defineProperty(t,"__esModule",{value:!0})})(t)}).call(t,r(19))},function(module,exports){var g;g=function(){return this}();try{g=g||Function("return this")()||eval("this")}catch(e){"object"==typeof window&&(g=window)}module.exports=g}]).default},module.exports=factory()}),chimeeKernelFlv=unwrapExports(lib$2);function styleInject(e,t){void 0===t&&(t={});var r=t.insertAt;if(e&&"undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===r&&i.firstChild?i.insertBefore(n,i.firstChild):i.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}var css=".chimee-container container{position:relative;display:block;width:100%;height:100%}.chimee-container video{display:block;width:100%;height:100%;background:#000;outline:0}.chimee-container video:focus{outline:0}.chimee-container chimee-center-state-loading{box-sizing:initial}";styleInject(css);var classCallCheck$2=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},inherits$2=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)},possibleConstructorReturn$2=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};Chimee.install(chimeeControl),Chimee.install(chimeeCenterState),Chimee.install(contextmenuConf),Chimee.install(index$1);var ChimeePlayer=function(e){function t(e){if(classCallCheck$2(this,t),!isObject(e))throw new TypeError("You must pass an Object as config when you new ChimeePlayer");e.plugin=e.plugin||e.plugins,isArray(e.plugin)||(e.plugin=[]);var r=[chimeeControl.name,chimeeCenterState.name,contextmenuConf.name,index$1.name],i=e.plugin.map(function(e){return isObject(e)?e.name:e});r.forEach(function(t){i.indexOf(t)>-1||e.plugin.push(t)}),isObject(e.preset)||(e.preset={hls:Hls,flv:chimeeKernelFlv});var n=possibleConstructorReturn$2(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.on("play",function(){return n.chimeeContextmenu.updatemenu([{text:"暂停",action:"pause"}])}),n.on("pause",function(){return n.chimeeContextmenu.updatemenu([{text:"播放",action:"play"}])}),n}return inherits$2(t,Chimee),t}();return ChimeePlayer.popupFactory=popupFactory,ChimeePlayer}); diff --git a/libs/chimee-player/package.json b/libs/chimee-player/package.json new file mode 100644 index 000000000..0d0835aa8 --- /dev/null +++ b/libs/chimee-player/package.json @@ -0,0 +1,24 @@ +-{ +- "name": "chimee-player", +- "filename": "chimee-player.min.js", +- "version": "1.3.1", +- +- // 其他 +- "description": "项目简介", +- "homepage": "https://github.com/Chimeejs/chimee-player", +- "keywords": [], +- "maintainers": [ +- { +- "name": "作者/维护者", +- "web": "http://chimee.org/", +- "mail": "feedback@chimee.org" +- } +- ], +- "repositories": [ +- { +- // svn 等 +- "type": "git", +- "url": "https://github.com/Chimeejs/chimee-player" +- } +- ] +-} \ No newline at end of file