1(function(root,factory){if('object'==typeof exports&&'object'==typeof module)module.exports=factory();else if('function'==typeof define&&define.amd)define([],factory);else{var a=factory();for(var i in a)('object'==typeof exports?exports:root)[i]=a[i]}})(this,function(){return function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:!1};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.loaded=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.p='./',__webpack_require__(0)}([function(module,exports,__webpack_require__){__webpack_require__(120),module.exports=__webpack_require__(121)},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(4),__webpack_require__(2)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,has,lang){function err(msg,cls){throw new Error('declare'+(cls?' '+cls:'')+': '+msg)}function c3mro(bases,className){for(var result=[],roots=[{cls:0,refs:[]}],nameMap={},clsCount=1,l=bases.length,i=0,j,lin,base,top,proto,rec,name,refs;i<l;++i){for(base=bases[i],base?'[object Function]'!=opts.call(base)&&err('mixin #'+i+' is not a callable constructor.',className):err('mixin #'+i+' is unknown. Did you use dojo.require to pull it in?',className),lin=base._meta?base._meta.bases:[base],top=0,j=lin.length-1;0<=j;--j)proto=lin[j].prototype,proto.hasOwnProperty('declaredClass')||(proto.declaredClass='uniqName_'+counter++),name=proto.declaredClass,nameMap.hasOwnProperty(name)||(nameMap[name]={count:0,refs:[],cls:lin[j]},++clsCount),rec=nameMap[name],top&&top!==rec&&(rec.refs.push(top),++top.count),top=rec;++top.count,roots[0].refs.push(top)}for(;roots.length;){for(top=roots.pop(),result.push(top.cls),--clsCount;refs=top.refs,1==refs.length;){if(top=refs[0],!top||--top.count){top=0;break}result.push(top.cls),--clsCount}if(top)for(i=0,l=refs.length;i<l;++i)top=refs[i],--top.count||roots.push(top)}return clsCount&&err('can\'t build consistent linearization',className),base=bases[0],result[0]=base?base._meta&&base===result[result.length-base._meta.bases.length]?base._meta.bases.length:1:0,result}function inherited(args,a,f){var cache=this._inherited=this._inherited||{},name,chains,bases,caller,meta,base,proto,opf,pos;if('string'==typeof args&&(name=args,args=a,a=f),f=0,caller=args.callee,name=name||caller.nom,name||err('can\'t deduce a name to call inherited()',this.declaredClass),meta=this.constructor._meta,bases=meta.bases,pos=cache.p,name!=cname){if(cache.c!==caller&&(pos=0,base=bases[0],meta=base._meta,meta.hidden[name]!==caller)){chains=meta.chains,chains&&'string'==typeof chains[name]&&err('calling chained method with inherited: '+name,this.declaredClass);do if(meta=base._meta,proto=base.prototype,meta&&(proto[name]===caller&&proto.hasOwnProperty(name)||meta.hidden[name]===caller))break;while(base=bases[++pos]);pos=base?pos:-1}if(base=bases[++pos],base)if(proto=base.prototype,base._meta&&proto.hasOwnProperty(name))f=proto[name];else{opf=op[name];do if(proto=base.prototype,f=proto[name],f&&(base._meta?proto.hasOwnProperty(name):f!==opf))break;while(base=bases[++pos])}f=base&&f||op[name]}else{if(cache.c!==caller&&(pos=0,meta=bases[0]._meta,meta&&meta.ctor!==caller)){for(chains=meta.chains,chains&&'manual'===chains.constructor||err('calling chained constructor with inherited',this.declaredClass);(base=bases[++pos])&&(meta=base._meta,!(meta&&meta.ctor===caller)););pos=base?pos:-1}for(;(base=bases[++pos])&&(meta=base._meta,f=meta?meta.ctor:base,!f););f=base&&f}return(cache.c=f,cache.p=pos,f)?!0===a?f:f.apply(this,a||args):void 0}function getInherited(name,args){return'string'==typeof name?this.__inherited(name,args,!0):this.__inherited(name,!0)}function isInstanceOf(cls){for(var bases=this.constructor._meta.bases,i=0,l=bases.length;i<l;++i)if(bases[i]===cls)return!0;return this instanceof cls}function mixOwn(target,source){for(var name in source)name!=cname&&source.hasOwnProperty(name)&&(target[name]=source[name]);if(has('bug-for-in-skips-shadowed'))for(var extraNames=lang._extraNames,i=extraNames.length;i;)name=extraNames[--i],name!=cname&&source.hasOwnProperty(name)&&(target[name]=source[name])}function safeMixin(target,source){var name,t;for(name in source)t=source[name],t===op[name]&&name in op||name==cname||('[object Function]'==opts.call(t)&&(t.nom=name),target[name]=t);if(has('bug-for-in-skips-shadowed'))for(var extraNames=lang._extraNames,i=extraNames.length;i;)name=extraNames[--i],t=source[name],t===op[name]&&name in op||name==cname||('[object Function]'==opts.call(t)&&(t.nom=name),target[name]=t);return target}function extend(source){return declare.safeMixin(this.prototype,source),this}function createSubclass(mixins,props){return declare([this].concat(mixins),props||{})}function chainedConstructor(bases,ctorSpecial){return function(){var a=arguments,args=a,a0=a[0],l=bases.length,f,i,m,preArgs;if(!(this instanceof a.callee))return applyNew(a);if(ctorSpecial&&(a0&&a0.preamble||this.preamble))for(preArgs=Array(bases.length),preArg
1s[0]=a,i=0;;){if(a0=a[0],a0&&(f=a0.preamble,f&&(a=f.apply(this,a)||a)),f=bases[i].prototype,f=f.hasOwnProperty('preamble')&&f.preamble,f&&(a=f.apply(this,a)||a),++i==l)break;preArgs[i]=a}for(i=l-1;0<=i;--i)f=bases[i],m=f._meta,f=m?m.ctor:f,f&&f.apply(this,preArgs?preArgs[i]:a);f=this.postscript,f&&f.apply(this,args)}}function singleConstructor(ctor,ctorSpecial){return function(){var a=arguments,t=a,a0=a[0],f;return this instanceof a.callee?void(ctorSpecial&&(a0&&(f=a0.preamble,f&&(t=f.apply(this,t)||t)),f=this.preamble,f&&f.apply(this,t)),ctor&&ctor.apply(this,a),f=this.postscript,f&&f.apply(this,a)):applyNew(a)}}function simpleConstructor(bases){return function(){var a=arguments,i=0,f,m;if(!(this instanceof a.callee))return applyNew(a);for(;f=bases[i];++i)if(m=f._meta,f=m?m.ctor:f,f){f.apply(this,a);break}f=this.postscript,f&&f.apply(this,a)}}function chain(name,bases,reversed){return function(){var i=0,step=1,b,m,f;for(reversed&&(i=bases.length-1,step=-1);b=bases[i];i+=step)m=b._meta,f=(m?m.hidden:b.prototype)[name],f&&f.apply(this,arguments)}}function forceNew(ctor){xtor.prototype=ctor.prototype;var t=new xtor;return xtor.prototype=null,t}function applyNew(args){var ctor=args.callee,t=forceNew(ctor);return ctor.apply(t,args),t}function declare(className,superclass,props){'string'!=typeof className&&(props=superclass,superclass=className,className=''),props=props||{};var mixins=1,parents=superclass,proto,i,t,ctor,name,bases,chains;if('[object Array]'==opts.call(superclass)?(bases=c3mro(superclass,className),t=bases[0],mixins=bases.length-t,superclass=bases[mixins]):(bases=[0],superclass?'[object Function]'==opts.call(superclass)?(t=superclass._meta,bases=bases.concat(t?t.bases:superclass)):err('base class is not a callable constructor.',className):null!==superclass&&err('unknown base class. Did you use dojo.require to pull it in?',className)),superclass)for(i=mixins-1;;--i){if(proto=forceNew(superclass),!i)break;t=bases[i],(t._meta?mixOwn:mix)(proto,t.prototype),ctor=new Function,ctor.superclass=superclass,ctor.prototype=proto,superclass=proto.constructor=ctor}else proto={};for(declare.safeMixin(proto,props),t=props.constructor,t!==op.constructor&&(t.nom=cname,proto.constructor=t),i=mixins-1;i;--i)t=bases[i]._meta,t&&t.chains&&(chains=mix(chains||{},t.chains));if(proto['-chains-']&&(chains=mix(chains||{},proto['-chains-'])),t=!chains||!chains.hasOwnProperty(cname),bases[0]=ctor=chains&&'manual'===chains.constructor?simpleConstructor(bases):1==bases.length?singleConstructor(props.constructor,t):chainedConstructor(bases,t),ctor._meta={bases:bases,hidden:props,chains:chains,parents:parents,ctor:props.constructor},ctor.superclass=superclass&&superclass.prototype,ctor.extend=extend,ctor.createSubclass=createSubclass,ctor.prototype=proto,proto.constructor=ctor,proto.getInherited=getInherited,proto.isInstanceOf=isInstanceOf,proto.inherited=inheritedImpl,proto.__inherited=inherited,className&&(proto.declaredClass=className,lang.setObject(className,ctor)),chains)for(name in chains)proto[name]&&'string'==typeof chains[name]&&name!=cname&&(t=proto[name]=chain(name,bases,'after'===chains[name]),t.nom=name);return ctor}var mix=lang.mixin,op=Object.prototype,opts=op.toString,xtor=new Function,counter=0,cname='constructor',inheritedImpl=dojo.config.isDebug?function(args,a1,a2){var f=this.getInherited(args,a1);if(f)return f.apply(this,a2||a1||args)}:inherited;return dojo.safeMixin=declare.safeMixin=safeMixin,dojo.declare=declare,declare}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(4),__webpack_require__(10)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,has){has.add('bug-for-in-skips-shadowed',function(){for(var i in{toString:1})return 0;return 1});var _extraNames=has('bug-for-in-skips-shadowed')?['hasOwnProperty','valueOf','isPrototypeOf','propertyIsEnumerable','toLocaleStr
1ing','toString','constructor']:[],_extraLen=_extraNames.length,getProp=function(parts,create,context){var i=0,dojoGlobal=dojo.global,p;if(!context){if(!parts.length)return dojoGlobal;p=parts[i++];try{context=dojo.scopeMap[p]&&dojo.scopeMap[p][1]}catch(e){}context=context||(p in dojoGlobal?dojoGlobal[p]:create?dojoGlobal[p]={}:void 0)}for(;context&&(p=parts[i++]);)context=p in context?context[p]:create?context[p]={}:void 0;return context},opts=Object.prototype.toString,efficient=function(obj,offset,startWith){return(startWith||[]).concat(Array.prototype.slice.call(obj,offset||0))},_pattern=/\{([^\}]+)\}/g,lang={_extraNames:_extraNames,_mixin:function(dest,source,copyFunc){var empty={},name,s,i;for(name in source)s=source[name],name in dest&&(dest[name]===s||name in empty&&empty[name]===s)||(dest[name]=copyFunc?copyFunc(s):s);if(has('bug-for-in-skips-shadowed')&&source)for(i=0;i<_extraLen;++i)name=_extraNames[i],s=source[name],name in dest&&(dest[name]===s||name in empty&&empty[name]===s)||(dest[name]=copyFunc?copyFunc(s):s);return dest},mixin:function(dest){dest||(dest={});for(var i=1,l=arguments.length;i<l;i++)lang._mixin(dest,arguments[i]);return dest},setObject:function(name,value,context){var parts=name.split('.'),p=parts.pop(),obj=getProp(parts,!0,context);return obj&&p?obj[p]=value:void 0},getObject:function(name,create,context){return getProp(name.split('.'),create,context)},exists:function(name,obj){return void 0!==lang.getObject(name,!1,obj)},isString:function(it){return'string'==typeof it||it instanceof String},isArray:function(it){return it&&(it instanceof Array||'array'==typeof it)},isFunction:function(it){return'[object Function]'===opts.call(it)},isObject:function(it){return void 0!==it&&(null===it||'object'==typeof it||lang.isArray(it)||lang.isFunction(it))},isArrayLike:function(it){return it&&void 0!==it&&!lang.isString(it)&&!lang.isFunction(it)&&!(it.tagName&&'form'==it.tagName.toLowerCase())&&(lang.isArray(it)||isFinite(it.length))},isAlien:function(it){return it&&!lang.isFunction(it)&&/\{\s*\[native code\]\s*\}/.test(it+'')},extend:function(ctor){for(var i=1,l=arguments.length;i<l;i++)lang._mixin(ctor.prototype,arguments[i]);return ctor},_hitchArgs:function(scope,method){var pre=lang._toArray(arguments,2),named=lang.isString(method);return function(){var args=lang._toArray(arguments),f=named?(scope||dojo.global)[method]:method;return f&&f.apply(scope||this,pre.concat(args))}},hitch:function(scope,method){if(2<arguments.length)return lang._hitchArgs.apply(dojo,arguments);if(method||(method=scope,scope=null),lang.isString(method)){if(scope=scope||dojo.global,!scope[method])throw['lang.hitch: scope["',method,'"] is null (scope="',scope,'")'].join('');return function(){return scope[method].apply(scope,arguments||[])}}return scope?function(){return method.apply(scope,arguments||[])}:method},delegate:function(){function TMP(){}return function(obj,props){TMP.prototype=obj;var tmp=new TMP;return TMP.prototype=null,props&&lang._mixin(tmp,props),tmp}}(),_toArray:has('ie')?function(){function slow(obj,offset,startWith){for(var arr=startWith||[],x=offset||0;x<obj.length;x++)arr.push(obj[x]);return arr}return function(obj){return(obj.item?slow:efficient).apply(this,arguments)}}():efficient,partial:function(){return lang.hitch.apply(dojo,[null].concat(lang._toArray(arguments)))},clone:function(src){if(!src||'object'!=typeof src||lang.isFunction(src))return src;if(src.nodeType&&'cloneNode'in src)return src.cloneNode(!0);if(src instanceof Date)return new Date(src.getTime());if(src instanceof RegExp)return new RegExp(src);var r,i,l;if(lang.isArray(src))for(r=[],i=0,l=src.length;i<l;++i)i in src&&r.push(lang.clone(src[i]));else r=src.constructor?new src.constructor:{};return lang._mixin(r,src,lang.clone)},trim:String.prototype.trim?function(str){return str.trim()}:function(str){return str.replace(/^\s\s*/,'').replace(/\s\s*$/,'')},replace:function(tmpl,map,pattern){return tmpl.replace(pattern||_pattern,lang.isFunction(map)?map:function(_,k){return lang.getObject(k,!1,map)})}};return has('extend-dojo')&&lang.mixin(dojo,lang),lang}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(36),__webpack_require__(5),__webpack_require__(10)],__WEBPACK_AMD_DEFINE_RESULT__=function(aspect,dojo,has){'use strict';function addListener(target,type,listener,dontFix,matchesTarget){var selector=type.match(/(.*):(.*)/);if(selector)return type=selector[2],selector=selector[1],on.selector(selector,type).
1call(matchesTarget,target,listener);if(has('touch')&&(touchEvents.test(type)&&(listener=fixTouchListener(listener)),!has('event-orientationchange')&&'orientationchange'==type&&(type='resize',target=window,listener=fixTouchListener(listener))),addStopImmediate&&(listener=addStopImmediate(listener)),target.addEventListener){var capture=type in captures,adjustedType=capture?captures[type]:type;return target.addEventListener(adjustedType,listener,capture),{remove:function(){target.removeEventListener(adjustedType,listener,capture)}}}if(type='on'+type,fixAttach&&target.attachEvent)return fixAttach(target,type,listener);throw new Error('Target must be an event emitter')}function syntheticPreventDefault(){this.cancelable=!1,this.defaultPrevented=!0}function syntheticStopPropagation(){this.bubbles=!1}if(has('dom')){var major=window.ScriptEngineMajorVersion;has.add('jscript',major&&major()+ScriptEngineMinorVersion()/10),has.add('event-orientationchange',has('touch')&&!has('android')),has.add('event-stopimmediatepropagation',window.Event&&!!window.Event.prototype&&!!window.Event.prototype.stopImmediatePropagation),has.add('event-focusin',function(global,doc,element){return!!element.attachEvent})}var on=function(target,type,listener,dontFix){return'function'!=typeof target.on||'function'==typeof type||target.nodeType?on.parse(target,type,listener,addListener,dontFix,this):target.on(type,listener)};on.pausable=function(target,type,listener,dontFix){var signal=on(target,type,function(){if(!paused)return listener.apply(this,arguments)},dontFix),paused;return signal.pause=function(){paused=!0},signal.resume=function(){paused=!1},signal},on.once=function(target,type,listener){var signal=on(target,type,function(){return signal.remove(),listener.apply(this,arguments)});return signal},on.parse=function(target,type,listener,addListener,dontFix,matchesTarget){if(type.call)return type.call(matchesTarget,target,listener);if(-1<type.indexOf(',')){for(var events=type.split(/\s*,\s*/),handles=[],i=0,eventName;eventName=events[i++];)handles.push(addListener(target,eventName,listener,dontFix,matchesTarget));return handles.remove=function(){for(var i=0;i<handles.length;i++)handles[i].remove()},handles}return addListener(target,type,listener,dontFix,matchesTarget)};var touchEvents=/^touch/;on.selector=function(selector,eventType,children){return function(target,listener){function select(eventTarget){for(matchesTarget=matchesTarget&&matchesTarget.matches?matchesTarget:dojo.query;!matchesTarget.matches(eventTarget,selector,target);)if(eventTarget==target||!1===children||!(eventTarget=eventTarget.parentNode)||1!=eventTarget.nodeType)return;return eventTarget}var matchesTarget='function'==typeof selector?{matches:selector}:this,bubble=eventType.bubble;return bubble?on(target,bubble(select),listener):on(target,eventType,function(event){var eventTarget=select(event.target);return eventTarget&&listener.call(eventTarget,event)})}};var slice=[].slice,syntheticDispatch=on.emit=function(target,type,event){var args=slice.call(arguments,2),method='on'+type;if('parentNode'in target){var newEvent=args[0]={};for(var i in event)newEvent[i]=event[i];newEvent.preventDefault=syntheticPreventDefault,newEvent.stopPropagation=syntheticStopPropagation,newEvent.target=target,newEvent.type=type,event=newEvent}do target[method]&&target[method].apply(target,args);while(event&&event.bubbles&&(target=target.parentNode));return event&&event.cancelable&&event},captures=has('event-focusin')?{}:{focusin:'focus',focusout:'blur'};if(!has('event-stopimmediatepropagation'))var stopImmediatePropagation=function(){this.immediatelyStopped=!0,this.modified=!0},addStopImmediate=function(listener){return function(event){if(!event.immediatelyStopped)return event.stopImmediatePropagation=stopImmediatePropagation,listener.apply(this,arguments)}};if(has('dom-addeventlistener'))on.emit=function(target,type,event){if(target.dispatchEvent&&document.createEvent){var nativeEvent=target.ownerDocument.createEvent('HTMLEvents');for(var i in nativeEvent.initEvent(type,!!event.bubbles,!!event.cancelable),event)i in nativeEvent||(nativeEvent[i]=event[i]);return target.dispatchEvent(nativeEvent)&&nativeEvent}return syntheticDispatch.apply(on,arguments)};else{on._fixEvent=function(evt,sender){if(!evt){var w=sender&&(sender.ownerDocument||sender.document||sender).parentWindow||window;evt=w.event}if(!evt)return evt;try{lastEvent&&evt.type==lastEvent.type&&evt.srcElement==lastEvent.target&&(evt=lastEvent)}catch(e){}if(!evt.target)switch(evt.target=evt.srcElement,evt.currentTarget=sender||evt.srcElement,'mouseover'==evt.type&&(evt.relatedTarget=evt.fromElement),'mouseout'==evt.type&&(evt.relatedTarget=evt.toElement),evt.stopPropagation||(evt.stopPropagation=stopPropagation,evt.preventDefault=preventDefault),evt.type){case'keypress':var c='charCo
1de'in evt?evt.charCode:evt.keyCode;10==c?(c=0,evt.keyCode=13):13==c||27==c?c=0:3==c&&(c=99),evt.charCode=c,_setKeyChar(evt);}return evt};var IESignal=function(handle){this.handle=handle},lastEvent;IESignal.prototype.remove=function(){delete _dojoIEListeners_[this.handle]};var fixListener=function(listener){return function(evt){evt=on._fixEvent(evt,this);var result=listener.call(this,evt);return evt.modified&&(!lastEvent&&setTimeout(function(){lastEvent=null}),lastEvent=evt),result}},fixAttach=function(target,type,listener){if(listener=fixListener(listener),((target.ownerDocument?target.ownerDocument.parentWindow:target.parentWindow||target.window||window)!=top||5.8>has('jscript'))&&!has('config-_allow_leaks')){'undefined'==typeof _dojoIEListeners_&&(_dojoIEListeners_=[]);var emitter=target[type];if(!emitter||!emitter.listeners){var oldListener=emitter;emitter=Function('event','var callee = arguments.callee; for(var i = 0; i<callee.listeners.length; i++){var listener = _dojoIEListeners_[callee.listeners[i]]; if(listener){listener.call(this,event);}}'),emitter.listeners=[],target[type]=emitter,emitter.global=this,oldListener&&emitter.listeners.push(_dojoIEListeners_.push(oldListener)-1)}var handle;return emitter.listeners.push(handle=emitter.global._dojoIEListeners_.push(listener)-1),new IESignal(handle)}return aspect.after(target,type,listener,!0)},_setKeyChar=function(evt){evt.keyChar=evt.charCode?String.fromCharCode(evt.charCode):'',evt.charOrCode=evt.keyChar||evt.keyCode},stopPropagation=function(){this.cancelBubble=!0},preventDefault=on._preventDefault=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(e){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0}}if(has('touch'))var Event=function(){},windowOrientation=window.orientation,fixTouchListener=function(listener){return function(originalEvent){var event=originalEvent.corrected;if(!event){var type=originalEvent.type;try{delete originalEvent.type}catch(e){}if(originalEvent.type){if(has('mozilla')){var event={};for(var name in originalEvent)event[name]=originalEvent[name]}else{Event.prototype=originalEvent;var event=new Event}event.preventDefault=function(){originalEvent.preventDefault()},event.stopPropagation=function(){originalEvent.stopPropagation()}}else event=originalEvent,event.type=type;if(originalEvent.corrected=event,'resize'==type)return windowOrientation==window.orientation?null:(windowOrientation=window.orientation,event.type='orientationchange',listener.call(this,event));'rotation'in event||(event.rotation=0,event.scale=1);var firstChangeTouch=event.changedTouches[0];for(var i in firstChangeTouch)delete event[i],event[i]=firstChangeTouch[i]}return listener.call(this,event)}};return on}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(30)],__WEBPACK_AMD_DEFINE_RESULT__=function(require){var module={config:function(){return{'config-deferredInstrumentation':0,'config-dojo-loader-catches':0,'config-tlmSiblingOfDojo':0,'dojo-amd-factory-scan':0,'dojo-combo-api':0,'dojo-config-api':1,'dojo-config-require':0,'dojo-debug-messages':0,'dojo-dom-ready-api':1,'dojo-firebug':0,'dojo-guarantee-console':1,'dojo-has-api':1,'dojo-inject-api':1,'dojo-loader':1,'dojo-log-api':0,'dojo-modulePaths':0,'dojo-moduleUrl':0,'dojo-publish-privates':0,'dojo-requirejs-api':0,'dojo-sniff':1,'dojo-sync-loader':0,'dojo-test-sniff':0,'dojo-timeout-api':0,'dojo-trace-api':0,'dojo-undef-api':0,'dojo-v1x-i18n-Api':1,'dom':1,'host-browser':1,'extend-dojo':1,'touch':0}}},has=require.has||function(){};if(!has('dojo-has-api')){var isBrowser='undefined'!=typeof window&&'undefined'!=typeof location&&'undefined'!=typeof document&&window.location==location&&window.document==document,global=this,doc=isBrowser&&document,element=doc&&doc.createElement('DiV'),cache=module.config&&module.config()||{};has=function(name){return'function'==typeof cache[name]?cache[name]=cache[name](global,doc,element):cache[name]},has.cache=cache,has.add=function(name,test,now,force){return('undefined'==typeof cache[name]||force)&&(cache[name]=test),now&&has(name)},has.add('host-browser',isBrowser),has.add('dom',isBrowser),has.add('dojo-dom-ready-api',1),has.add('dojo-sniff',1)}if(has('host-browser')){has.add('dom-addeventlistener',!!document.addEventListener),has.add('touch','ontouchstart'in document||0<window.navigator.msMaxTouchPoints),has.add('device-width',screen.availWi
1dth||innerWidth);var form=document.createElement('form');has.add('dom-attributes-explicit',0==form.attributes.length),has.add('dom-attributes-specified-flag',0<form.attributes.length&&40>form.attributes.length)}return has.clearElement=function(element){return element.innerHTML='',element},has.normalize=function(id,toAbsMid){var tokens=id.match(/[\?:]|[^:\?]*/g),i=0,get=function(skip){var term=tokens[i++];return':'==term?0:'?'==tokens[i++]?!skip&&has(term)?get():(get(!0),get(skip)):term||0};return id=get(),id&&toAbsMid(id)},has.load=function(id,parentRequire,loaded){id?parentRequire([id],loaded):loaded()},has}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;(function(module){__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4),__webpack_require__(80),__webpack_require__(30),module],__WEBPACK_AMD_DEFINE_RESULT__=function(has,config,require,module){module={id:'dojo/_base/kernel'};var dijit={},dojox={},dojo={config:config,global:this,dijit:dijit,dojox:dojox},scopeMap={dojo:['dojo',dojo],dijit:['dijit',dijit],dojox:['dojox',dojox]},packageMap=require.map&&require.map[module.id.match(/[^\/]+/)[0]],i,p,item;for(p in packageMap)scopeMap[p]?scopeMap[p][0]=packageMap[p]:scopeMap[p]=[packageMap[p],{}];for(p in scopeMap)item=scopeMap[p],item[1]._scopeName=item[0],config.noGlobals||(this[item[0]]=item[1]);dojo.scopeMap=scopeMap,dojo.baseUrl=dojo.config.baseUrl=require.baseUrl,dojo.isAsync=!has('dojo-loader')||require.async,dojo.locale=config.locale;var rev='$Rev: 31379 $'.match(/\d+/);if(dojo.version={major:1,minor:9,patch:0,flag:'',revision:rev?+rev[0]:NaN,toString:function(){var v=dojo.version;return v.major+'.'+v.minor+'.'+v.patch+v.flag+' ('+v.revision+')'}},has.add('extend-dojo',1),Function('d','d.eval = function(){return d.global.eval ? d.global.eval(arguments[0]) : eval(arguments[0]);}')(dojo),dojo.exit=has('host-rhino')?function(exitcode){quit(exitcode)}:function(){},has.add('dojo-guarantee-console',1),has('dojo-guarantee-console')){'undefined'!=typeof console||(console={});var cn=['assert','count','debug','dir','dirxml','error','group','groupEnd','info','profile','profileEnd','time','timeEnd','trace','warn','log'],tn;for(i=0;tn=cn[i++];)(function(){})||function(){var tcn=tn+'';console[tcn]=function(){},console[tcn]._fake=!0}()}if(has.add('dojo-debug-messages',!!config.isDebug),dojo.deprecated=dojo.experimental=function(){},has('dojo-debug-messages')&&(dojo.deprecated=function(behaviour,extra,removal){var message='DEPRECATED: '+behaviour;extra&&(message+=' '+extra),removal&&(message+=' -- will be removed in version: '+removal)},dojo.experimental=function(moduleName,extra){var message='EXPERIMENTAL: '+moduleName+' -- APIs subject to change without notice.';extra&&(message+=' '+extra)}),has.add('dojo-modulePaths',1),has('dojo-modulePaths')&&config.modulePaths){dojo.deprecated('dojo.modulePaths','use paths configuration');var paths={};for(p in config.modulePaths)paths[p.replace(/\./g,'/')]=config.modulePaths[p];require({paths:paths})}return has.add('dojo-moduleUrl',1),has('dojo-moduleUrl')&&(dojo.moduleUrl=function(module,url){dojo.deprecated('dojo.moduleUrl()','use require.toUrl','2.0');var result=null;return module&&(result=require.toUrl(module.replace(/\./g,'/')+(url?'/'+url:'')+'/*.*').replace(/\/\*\.\*/,'')+(url?'':'/')),result}),dojo._hasResource={},dojo}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}).call(exports,__webpack_require__(31)(module))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(4),__webpack_require__(2)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,has,lang){function buildFn(fn){return cache[fn]=new Function('item','index','array',fn)}function everyOrSome(some){return function(a,fn,o){var i=0,l=a&&a.length||0,result;if(l&&'string'==typeof a&&(a=a.split('')),'string'==typeof fn&&(fn=cache[f
1n]||buildFn(fn)),o){for(;i<l;++i)if(result=!fn.call(o,a[i],i,a),some^result)return!result;}else for(;i<l;++i)if(result=!fn(a[i],i,a),some^result)return!result;return!some}}function index(up){var delta=1,lOver=0,uOver=0;return up||(delta=lOver=uOver=-1),function(a,x,from,last){if(last&&0<delta)return array.lastIndexOf(a,x,from);var l=a&&a.length||0,end=up?l+uOver:lOver,i;for(from===u?i=up?lOver:l+uOver:0>from?(i=l+from,0>i&&(i=lOver)):i=from>=l?l+uOver:from,l&&'string'==typeof a&&(a=a.split(''));i!=end;i+=delta)if(a[i]==x)return i;return-1}}var cache={},array={every:everyOrSome(!1),some:everyOrSome(!0),indexOf:index(!0),lastIndexOf:index(!1),forEach:function(arr,callback,thisObject){var i=0,l=arr&&arr.length||0;if(l&&'string'==typeof arr&&(arr=arr.split('')),'string'==typeof callback&&(callback=cache[callback]||buildFn(callback)),thisObject)for(;i<l;++i)callback.call(thisObject,arr[i],i,arr);else for(;i<l;++i)callback(arr[i],i,arr)},map:function(arr,callback,thisObject,Ctr){var i=0,l=arr&&arr.length||0,out=new(Ctr||Array)(l);if(l&&'string'==typeof arr&&(arr=arr.split('')),'string'==typeof callback&&(callback=cache[callback]||buildFn(callback)),thisObject)for(;i<l;++i)out[i]=callback.call(thisObject,arr[i],i,arr);else for(;i<l;++i)out[i]=callback(arr[i],i,arr);return out},filter:function(arr,callback,thisObject){var i=0,l=arr&&arr.length||0,out=[],value;if(l&&'string'==typeof arr&&(arr=arr.split('')),'string'==typeof callback&&(callback=cache[callback]||buildFn(callback)),thisObject)for(;i<l;++i)value=arr[i],callback.call(thisObject,value,i,arr)&&out.push(value);else for(;i<l;++i)value=arr[i],callback(value,i,arr)&&out.push(value);return out},clearCache:function(){cache={}}},u;return has('extend-dojo')&&lang.mixin(dojo,array),array}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_RESULT__;(function(global,module){(function(){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2]);}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=null==array?0:array.length;++index<length;){var value=array[index];setter(accumulator,value,iteratee(value),array)}return accumulator}function arrayEach(array,iteratee){for(var index=-1,length=null==array?0:array.length;++index<length&&!(!1===iteratee(array[index],index,array)););return array}function arrayEachRight(array,iteratee){for(var length=null==array?0:array.length;length--&&!(!1===iteratee(array[length],length,array)););return array}function arrayEvery(array,predicate){for(var index=-1,length=null==array?0:array.length;++index<length;)if(!predicate(array[index],index,array))return!1;return!0}function arrayFilter(array,predicate){for(var index=-1,length=null==array?0:array.length,resIndex=0,result=[];++index<length;){var value=array[index];predicate(value,index,array)&&(result[resIndex++]=value)}return result}function arrayIncludes(array,value){var length=null==array?0:array.length;return!!length&&-1<baseIndexOf(array,value,0)}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=null==array?0:array.length;++index<length;)if(comparator(value,array[index]))return!0;return!1}function arrayMap(array,iteratee){for(var index=-1,length=null==array?0:array.length,result=Array(length);++index<length;)result[index]=iteratee(array[index],index,array);return result}function arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++index<length;)array[offset+index]=values[index];return array}function arrayReduce(array,iteratee,accumulator,initAccum){var index=-1,length=null==array?0:array.length;for(initAccum&&length&&(accumulator=array[++index]);++index<length;)accumulator=iteratee(accumulator,array[index],index,array);return accumulator}function arrayReduceRight(array,iteratee,accumulator,initAccum){var length=null==array?0:array.length;for(initAccum&&length&&(accumulator=array[--length]);length--;)accumulator=iteratee(accumulator,array[length],length,array);return accumulator}function arraySome(array,predicate){for(var index=-1,length=null==array?0:array.length;++index<length;)if(predicate(array[index],index,array))return!0;return!1}function asciiToArray(string){return string.split('')}function asciiWords(string){return string.match(reAsciiWord)||[]}function baseFindKey(collection,predicate,eachFunc){var result;return eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection))return result=key,!1}),result}function baseFindIndex(array,predicate,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?1:-1);fromRight?index--:++index<length;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){return value===value?strictIndexOf(array,value,fromIndex):baseFindIndex(array,baseIsNaN,fromIndex)}function baseIndexOfWith(array,value,fromIndex,comparator){for(var index=fromIndex-1,length=array.length;++index<length;)if(comparator(array[index],value))return index;return-1}function baseIsNaN(value){return value!==value}function baseMean(array,iteratee){var length=null==array?0:array.length;return length?baseSum(array,iteratee)/length:NAN}function baseProperty(key){return function(object){return null==object?void 0:object[key]}}function basePropertyOf(object){return function(key){return null==object?void 0:object[key]}}function baseReduce(collection,iteratee,accumulator,initAccum,eachFunc){return eachFunc(collection,function(value,index,collection){accumulator=initAccum?(initAccum=!1,value):iteratee(accumulator,value,index,collection)}),accumulator}function baseSortBy(array,comparer){var length=array.length;for(array.sort(comparer);length--;)array[length]=array[length].value;return array}function baseSum(array,iteratee){for(var index=-1,length=array.length,result;++index<length;){var current=iteratee(array[index]);current!==void 0&&(result=result===void 0?current:result+current)}return result}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index<n;)result[index]=iteratee(index);return result}function baseToPairs(object,props){return arrayMap(props,function(key){return[key,object[key]]})}function baseTrim(string){return string?string.slice(0,trimmedEndIndex(string)+1).replace(reTrimStart,''):string}function baseUnary(func){return function(value){return func(value)}}function baseValues(object,props){return arrayMap(props,function(key){return object[key]})}function cacheHas(cache,key){return cache.has(key)}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index<length&&-1<baseIndexOf(chrSymbols,strSymbols[index],0););return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&-1<baseIndexOf(chrSymbols,strSymbols[index],0););return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return'\\'+stringEscapes[chr]}function getValue(object,key){return null==object?void 0:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var result=[],data;!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);
vendor: 4,392 bytes, line 1
1return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++index<length;){var value=array[index];(value===placeholder||value===PLACEHOLDER)&&(array[index]=PLACEHOLDER,result[resIndex++]=index)}return result}function setToArray(set){var index=-1,result=Array(set.size);return set.forEach(function(value){result[++index]=value}),result}function setToPairs(set){var index=-1,result=Array(set.size);return set.forEach(function(value){result[++index]=[value,value]}),result}function strictIndexOf(array,value,fromIndex){for(var index=fromIndex-1,length=array.length;++index<length;)if(array[index]===value)return index;return-1}function strictLastIndexOf(array,value,fromIndex){for(var index=fromIndex+1;index--;)if(array[index]===value)return index;return index}function stringSize(string){return hasUnicode(string)?unicodeSize(string):asciiSize(string)}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function trimmedEndIndex(string){for(var index=string.length;index--&&reWhitespace.test(string.charAt(index)););return index}function unicodeSize(string){for(var result=reUnicode.lastIndex=0;reUnicode.test(string);)++result;return result}function unicodeToArray(string){return string.match(reUnicode)||[]}function unicodeWords(string){return string.match(reUnicodeWord)||[]}var LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT='Expected a function',HASH_UNDEFINED='__lodash_hash_undefined__',PLACEHOLDER='__lodash_placeholder__',CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4,COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,WRAP_BIND_FLAG=1,WRAP_BIND_KEY_FLAG=2,WRAP_CURRY_BOUND_FLAG=4,WRAP_CURRY_FLAG=8,WRAP_CURRY_RIGHT_FLAG=16,WRAP_PARTIAL_FLAG=32,WRAP_PARTIAL_RIGHT_FLAG=64,WRAP_ARY_FLAG=128,WRAP_REARG_FLAG=256,WRAP_FLIP_FLAG=512,LAZY_FILTER_FLAG=1,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,NAN=0/0,MAX_ARRAY_LENGTH=4294967295,wrapFlags=[['ary',WRAP_ARY_FLAG],['bind',WRAP_BIND_FLAG],['bindKey',WRAP_BIND_KEY_FLAG],['curry',WRAP_CURRY_FLAG],['curryRight',WRAP_CURRY_RIGHT_FLAG],['flip',WRAP_FLIP_FLAG],['partial',WRAP_PARTIAL_FLAG],['partialRight',WRAP_PARTIAL_RIGHT_FLAG],['rearg',WRAP_REARG_FLAG]],argsTag='[object Arguments]',arrayTag='[object Array]',boolTag='[object Boolean]',dateTag='[object Date]',errorTag='[object Error]',funcTag='[object Function]',genTag='[object GeneratorFunction]',mapTag='[object Map]',numberTag='[object Number]',objectTag='[object Object]',promiseTag='[object Promise]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',symbolTag='[object Symbol]',weakMapTag='[object WeakMap]',arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]',reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrimStart=/^\s+/,reWhitespace=/\s/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reForbiddenIdentifierChars=/[()=,{}\[\]\/\s]/,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u01
17f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange='\\ud800-\\udfff',rsDingbatRange='\\u2700-\\u27bf',rsLowerRange='a-z\\xdf-\\xf6\\xf8-\\xff',rsUpperRange='A-Z\\xc0-\\xd6\\xd8-\\xde',rsBreakRange='\\xac\\xb1\\xd7\\xf7'+'\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf'+'\\u2000-\\u206f'+' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',rsApos='[\'\u2019]',rsDigits='\\d+',rsLower='['+rsLowerRange+']',rsMisc='[^'+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+']',rsUpper='['+rsUpperRange+']',rsOptContrLower='(?:'+rsApos+'(?:d|ll|m|re|s|t|ve))?',rsOptContrUpper='(?:'+rsApos+'(?:D|LL|M|RE|S|T|VE))?',reOptMod='(?:'+('['+('\\u0300-\\u036f'+'\\ufe20-\\ufe2f'+'\\u20d0-\\u20ff')+']')+'|'+'\\ud83c[\\udffb-\\udfff]'+')'+'?',rsOptVar='['+'\\ufe0e\\ufe0f'+']?',reApos=/['ââ¬â¢]/g,reComboMark=/[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]/g,reUnicode=/\ud83c[\udffb-\udfff](?=\ud83c[\udffb-\udfff])|(?:[^\ud800-\udfff][\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]?|[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g,reUnicodeWord=RegExp([rsUpper+'?'+rsLower+'+'+rsOptContrLower+'(?='+'[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde]|$'+')','(?:'+rsUpper+'|'+rsMisc+')'+'+'+rsOptContrUpper+'(?='+'[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde](?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])|$'+')',rsUpper+'?'+('(?:'+rsLower+'|'+rsMisc+')')+'+'+rsOptContrLower,rsUpper+'+'+rsOptContrUpper,'\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])','\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',rsDigits,'(?:'+'[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff]'+')'+(rsOptVar+reOptMod+('(?:'+'\\u200d'+'(?:'+'[^\\ud800-\\udfff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff]'+')'+rsOptVar+reOptMod+')*'))].join('|'),'g'),reHasUnicode=/[\u200d\ud800-\udfff\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff\ufe0e\ufe0f]/,reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=['Array','Buffer','DataView','Date','Error','Float32Array','Float64Array','Function','Int8Array','Int16Array','Int32Array','Map','Math','Object','Promise','RegExp','Set','String','Symbol','TypeError','Uint8Array','Uint8ClampedArray','Uint16Array','Uint32Array','WeakMap','_','clearTimeout','isFinite','parseInt','setTimeout'],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var stringEscapes={'\\':'\\','\'':'\'','\n':'n','\r':'r','\u2028':'u2028','\u2029':'u2029'},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal='object'==typeof global&&global&&global.Object===Object&&global,freeSelf='object'==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function('return this')(),freeExports='object'==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&'object'==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{var types=freeModule&&freeModule.require&&freeModule.require('util').types;return types?types:freeProcess&&freeProcess.binding&&freeProcess.binding('util')}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,
1nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty('length'),deburrLetter=basePropertyOf({'\xC0':'A','\xC1':'A','\xC2':'A','\xC3':'A','\xC4':'A','\xC5':'A','\xE0':'a','\xE1':'a','\xE2':'a','\xE3':'a','\xE4':'a','\xE5':'a','\xC7':'C','\xE7':'c','\xD0':'D','\xF0':'d','\xC8':'E','\xC9':'E','\xCA':'E','\xCB':'E','\xE8':'e','\xE9':'e','\xEA':'e','\xEB':'e','\xCC':'I','\xCD':'I','\xCE':'I','\xCF':'I','\xEC':'i','\xED':'i','\xEE':'i','\xEF':'i','\xD1':'N','\xF1':'n','\xD2':'O','\xD3':'O','\xD4':'O','\xD5':'O','\xD6':'O','\xD8':'O','\xF2':'o','\xF3':'o','\xF4':'o','\xF5':'o','\xF6':'o','\xF8':'o','\xD9':'U','\xDA':'U','\xDB':'U','\xDC':'U','\xF9':'u','\xFA':'u','\xFB':'u','\xFC':'u','\xDD':'Y','\xFD':'y','\xFF':'y','\xC6':'Ae','\xE6':'ae','\xDE':'Th','\xFE':'th','\xDF':'ss','\u0100':'A','\u0102':'A','\u0104':'A','\u0101':'a','\u0103':'a','\u0105':'a','\u0106':'C','\u0108':'C','\u010A':'C','\u010C':'C','\u0107':'c','\u0109':'c','\u010B':'c','\u010D':'c','\u010E':'D','\u0110':'D','\u010F':'d','\u0111':'d','\u0112':'E','\u0114':'E','\u0116':'E','\u0118':'E','\u011A':'E','\u0113':'e','\u0115':'e','\u0117':'e','\u0119':'e','\u011B':'e','\u011C':'G','\u011E':'G','\u0120':'G','\u0122':'G','\u011D':'g','\u011F':'g','\u0121':'g','\u0123':'g','\u0124':'H','\u0126':'H','\u0125':'h','\u0127':'h','\u0128':'I','\u012A':'I','\u012C':'I','\u012E':'I','\u0130':'I','\u0129':'i','\u012B':'i','\u012D':'i','\u012F':'i','\u0131':'i','\u0134':'J','\u0135':'j','\u0136':'K','\u0137':'k','\u0138':'k','\u0139':'L','\u013B':'L','\u013D':'L','\u013F':'L','\u0141':'L','\u013A':'l','\u013C':'l','\u013E':'l','\u0140':'l','\u0142':'l','\u0143':'N','\u0145':'N','\u0147':'N','\u014A':'N','\u0144':'n','\u0146':'n','\u0148':'n','\u014B':'n','\u014C':'O','\u014E':'O','\u0150':'O','\u014D':'o','\u014F':'o','\u0151':'o','\u0154':'R','\u0156':'R','\u0158':'R','\u0155':'r','\u0157':'r','\u0159':'r','\u015A':'S','\u015C':'S','\u015E':'S','\u0160':'S','\u015B':'s','\u015D':'s','\u015F':'s','\u0161':'s','\u0162':'T','\u0164':'T','\u0166':'T','\u0163':'t','\u0165':'t','\u0167':'t','\u0168':'U','\u016A':'U','\u016C':'U','\u016E':'U','\u0170':'U','\u0172':'U','\u0169':'u','\u016B':'u','\u016D':'u','\u016F':'u','\u0171':'u','\u0173':'u','\u0174':'W','\u0175':'w','\u0176':'Y','\u0177':'y','\u0178':'Y','\u0179':'Z','\u017B':'Z','\u017D':'Z','\u017A':'z','\u017C':'z','\u017E':'z','\u0132':'IJ','\u0133':'ij','\u0152':'Oe','\u0153':'oe','\u0149':'\'n','\u017F':'s'}),escapeHtmlChar=basePropertyOf({'&':'&','<':'<','>':'>','"':'"','\'':'''}),unescapeHtmlChar=basePropertyOf({'&':'&','<':'<','>':'>','"':'"',''':'\''}),_=function runInContext(context){function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper)return value;if(hasOwnProperty.call(value,'__wrapped__'))return wrapperClone(value)}return new LodashWrapper(value)}function baseLodash(){}function LodashWrapper(value,chainAll){this.__wrapped__=value,this.__actions__=[],this.__chain__=!!chainAll,this.__index__=0,this.__values__=void 0}function LazyWrapper(value){this.__wrapped__=value,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=MAX_ARRAY_LENGTH,this.__views__=[]}function lazyClone(){var result=new LazyWrapper(this.__wrapped__);return result.__actions__=copyArray(this.__actions__),result.__dir__=this.__dir__,result.__filtered__=this.__filtered__,result.__iteratees__=copyArray(this.__iteratees__),result.__takeCount__=this.__takeCount__,result.__views__=copyArray(this.__views__),result}function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1,result.__filtered__=!0}else result=this.clone(),result.__dir__*=-1;return result}function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=0>dir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||!isRight&&arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&resIndex<takeCount;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndex<iterLength;){var data=iteratees[iterIndex],iteratee=data.iteratee,type=data.type,computed=iteratee(value);if(type==2)value=computed;else if(!computed)if(type==LAZY_FILTER_FLAG)continue outer;else break outer}result[resIndex++]=value}return result}function Hash(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result}function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0}function ListCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}function mapCacheDelete(key){var result=getMapData(this,key)['delete'](key);return this.size-=result?1:0,result}function SetCache(values){var index=-1,length=null==values?0:values.length;for(this.__data__=new MapCache;++index<length;)this.add(values[index])}function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size}function stackDelete(key){var data=this.__data__,result=data['delete'](key);return this.size=data.size,result}function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value)(inherited||hasOwnProperty.call(value,key))&&!(skipIndexes&&('length'==key||isBuff&&('offset'==key||'parent'==key)||isType&&('buffer'==key||'byteLength'==key||'byteOffset'==key)||isIndex(key,length)))&&result.push(key);return result}function arraySample(array){var length=array.length;return length?array[baseRandom(0,length-1)]:void 0}function arraySampleSize(array,n){return shuffleSelf(copyArray(array),baseClamp(n,0,array.length))}function arrayShuffle(array){return shuffleSelf(copyArray(array))}function assignMergeValue(object,key,value){(void 0===value||eq(object[key],value))&&(void 0!==value||key in object)||baseAssignValue(object,key,value)}function assignValue(object,key,value){var objValue=object[key];hasOwnProperty.call(object,key)&&eq(objValue,value)&&(void 0!==value||key in object)||baseAssignValue(object,key,value)}function assocIndexOf(array,key){for(var length=array.length;length--;)if(eq(array[length][0],key))return length;return-1}function baseAggregator(collection,setter,iteratee,accumulator){return baseEach(collection,function(value,key,collection){setter(accumulator,value,iteratee(value),collection)}),accumulator}function baseAssign(object,source){return object&©Object(source,keys(source),object)}function baseAssignIn(object,source){return object&©Object(source,keysIn(source),object)}function baseAssignValue(object,key,value){'__proto__'==key&&defineProperty?defineProperty(object,key,{'configurable':!0,'enumerable':!0,'value':value,'writable':!0}):object[key]=value}function baseAt(object,paths){for(var index=-1,length=paths.length,result=Array(length);++index<length;)result[index]=null==object?void 0:get(object,paths[index]);return result}function baseClamp(number,lower,upper){return number===number&&(void 0!==upper&&(number=number<=upper?number:upper),void 0!==lower&&(number=number>=lower?number:lower)),number}function baseClone(value,bitmask,customizer,key,object,stack){var isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),void 0!==result)return result;if(!isObject(value))return value;var isArr=isArray(value);if(!isArr){var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object)){if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,isDeep)}else if(result=isFlat||isFunc?{}:initCloneObject(value),!isDeep)return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value))}else if(result=initCloneArray(value),!isDeep)return copyArray(value,result);stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;stack.set(value,result),isSet(value)?value.forEach(function(subValue){result.add(baseClone(subValue,bitmask,customizer,subValue,value,stack))}):isMap(value)&&value.forEach(function(subValue,key){result.set(key,baseClone(subValue,bitmask,customizer,key,value,stack))});
1var keysFunc=bitmask&CLONE_SYMBOLS_FLAG?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys,props=isArr?void 0:keysFunc(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(void 0===value&&!(key in object)||!predicate(value))return!1}return!0}function baseDelay(func,wait,args){if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(void 0,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index<length;){var value=array[index],computed=null==iteratee?value:iteratee(value);if(value=comparator||0!==value?value:0,isCommon&&computed===computed){for(var valuesIndex=valuesLength;valuesIndex--;)if(values[valuesIndex]===computed)continue outer;result.push(value)}else includes(values,computed,comparator)||result.push(value)}return result}function baseEvery(collection,predicate){var result=!0;return baseEach(collection,function(value,index,collection){return result=!!predicate(value,index,collection),result}),result}function baseExtremum(array,iteratee,comparator){for(var index=-1,length=array.length;++index<length;){var value=array[index],current=iteratee(value);if(null!=current&&(void 0===computed?current===current&&!isSymbol(current):comparator(current,computed)))var computed=current,result=value}return result}function baseFill(array,value,start,end){var length=array.length;for(start=toInteger(start),0>start&&(start=-start>length?0:length+start),end=void 0===end||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);start<end;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index<length;){var value=array[index];0<depth&&predicate(value)?1<depth?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):!isStrict&&(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=castPath(path,object);for(var index=0,length=path.length;null!=object&&index<length;)object=object[toKey(path[index++])];return index&&index==length?object:void 0}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return null==value?void 0===value?'[object Undefined]':'[object Null]':symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number<nativeMax(start,end)}function baseIntersection(arrays,iteratee,comparator){for(var includes=comparator?arrayIncludesWith:arrayIncludes,length=arrays[0].length,othLength=arrays.length,othIndex=othLength,caches=Array(othLength),maxLength=Infinity,result=[],array;othIndex--;)array=arrays[othIndex],othIndex&&iteratee&&(array=arrayMap(array,baseUnary(iteratee))),maxLength=nativeMin(array.length,maxLength),caches[othIndex]=!comparator&&(iteratee||120<=length&&120<=array.length)?new SetCac
1he(othIndex&&array):void 0;array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index<length&&result.length<maxLength;){var value=array[index],computed=iteratee?iteratee(value):value;if(value=comparator||0!==value?value:0,seen?!cacheHas(seen,computed):!includes(result,computed,comparator)){for(othIndex=othLength;--othIndex;){var cache=caches[othIndex];if(cache?!cacheHas(cache,computed):!includes(arrays[othIndex],computed,comparator))continue outer}seen&&seen.push(computed),result.push(value)}}return result}function baseInverter(object,setter,iteratee,accumulator){return baseForOwn(object,function(value,key,object){setter(accumulator,iteratee(value),key,object)}),accumulator}function baseInvoke(object,path,args){path=castPath(path,object),object=parent(object,path);var func=null==object?object:object[toKey(last(path))];return null==func?void 0:apply(func,object,args)}function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag}function baseIsEqual(value,other,bitmask,customizer,stack){return value===other||(null!=value&&null!=other&&(isObjectLike(value)||isObjectLike(other))?baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack):value!==value&&other!==other)}function baseIsEqualDeep(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=objIsArr?arrayTag:getTag(object),othTag=othIsArr?arrayTag:getTag(other);objTag=objTag==argsTag?objectTag:objTag,othTag=othTag==argsTag?objectTag:othTag;var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer(object)){if(!isBuffer(other))return!1;objIsArr=!0,objIsObj=!1}if(isSameTag&&!objIsObj)return stack||(stack=new Stack),objIsArr||isTypedArray(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack);if(!(bitmask&COMPARE_PARTIAL_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,'__wrapped__'),othIsWrapped=othIsObj&&hasOwnProperty.call(other,'__wrapped__');if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;return stack||(stack=new Stack),equalFunc(objUnwrapped,othUnwrapped,bitmask,customizer,stack)}}return!!isSameTag&&(stack||(stack=new Stack),equalObjects(object,other,bitmask,customizer,equalFunc,stack))}function baseIsMap(value){return isObjectLike(value)&&getTag(value)==mapTag}function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(null==object)return!length;for(object=Object(object);index--;){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object))return!1}for(;++index<length;){data=matchData[index];var key=data[0],objValue=object[key],srcValue=data[1];if(!(noCustomizer&&data[2])){var stack=new Stack;if(customizer)var result=customizer(objValue,srcValue,key,object,source,stack);if(void 0===result?!baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG,customizer,stack):!result)return!1}else if(void 0===objValue&&!(key in object))return!1}return!0}function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}function baseIsSet(value){return isObjectLike(value)&&getTag(value)==setTag}function baseIteratee(value){return'function'==typeof value?value:null==value?identity:'object'==typeof value?isArray(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value):property(value)}function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty.call(object,key)&&'constructor'!=key&&result.push(key);return result}function baseKeysIn(object){if(!isObject(object))return nativeKeysIn(object);var isProto=isPrototype(object),result=[];for(var key in object)('constructor'!=key||!isProto&&hasOwnProperty.call(object,key))&&result.push(key);return result}function baseLt(value,other){return value<other}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return void 0===objValue&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){object===source||baseFor(source,function(srcValue,key){if(stack||(stack=new Stack),isObject(srcValue))baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(safeGet(object,key),srcValue,key+'',object,source,stack):void 0;void 0===newValue&&(newValue=srcValue),assignMergeValue(object,key,newValue)}},keysIn)}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=safeGet(object,key),srcValue=safeGet(source,key),stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+'',object,source,stack):void 0,isCommon=void 0===newValue;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue,isArr||isBuff||isTyped?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):isBuff?(isCommon=!1,newValue=cloneBuffer(srcValue,!0)):isTyped?(isCommon=!1,newValue=cloneTypedArray(srcValue,!0)):newValue=[]:isPlainObject(srcValue)||isArguments(srcValue)?(newValue=objValue,isArguments(objValue)?newValue=toPlainObject(objValue):(!isObject(objValue)||isFunction(objValue))&&(newValue=initCloneObject(srcValue))):isCommon=!1}
1isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack['delete'](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:void 0}function baseOrderBy(collection,iteratees,orders){iteratees=iteratees.length?arrayMap(iteratees,function(iteratee){return isArray(iteratee)?function(value){return baseGet(value,1===iteratee.length?iteratee[0]:iteratee)}:iteratee}):[identity];var index=-1;iteratees=arrayMap(iteratees,baseUnary(getIteratee()));var result=baseMap(collection,function(value){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{'criteria':criteria,'index':++index,'value':value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,paths){return basePickBy(object,paths,function(value,path){return hasIn(object,path)})}function basePickBy(object,paths,predicate){for(var index=-1,length=paths.length,result={};++index<length;){var path=paths[index],value=baseGet(object,path);predicate(value,path)&&baseSet(result,castPath(path,object),value)}return result}function basePropertyDeep(path){return function(object){return baseGet(object,path)}}function basePullAll(array,values,iteratee,comparator){var indexOf=comparator?baseIndexOfWith:baseIndexOf,index=-1,length=values.length,seen=array;for(array===values&&(values=copyArray(values)),iteratee&&(seen=arrayMap(array,baseUnary(iteratee)));++index<length;)for(var fromIndex=0,value=values[index],computed=iteratee?iteratee(value):value;-1<(fromIndex=indexOf(seen,computed,fromIndex,comparator));)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1,index;length--;)if(index=indexes[length],length==lastIndex||index!==previous){var previous=index;isIndex(index)?splice.call(array,index,1):baseUnset(array,index)}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result='';if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+'')}function baseSample(collection){return arraySample(values(collection))}function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length))}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=castPath(path,object);for(var index=-1,length=path.length,nested=object;null!=nested&&++index<length;){var key=toKey(path[index]),newValue=value;if('__proto__'===key||'constructor'===key||'prototype'===key)return object;if(index!=length-1){var objValue=nested[key];newValue=customizer?customizer(objValue,key,nested):void 0,void 0===newValue&&(newValue=isObject(objValue)?objValue:isIndex(path[index+1])?[]:{})}assignValue(nested,key,newValue),nested=nested[key]}return object}function baseShuffle(collection){return shuffleSelf(values(collection))}function baseSlice(array,start,end){var index=-1,length=array.length;0>start&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index<length;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseSortedIndex(array,value,retHighest){var low=0,high=null==array?low:array.length;if('number'==typeof value&&value===value&&high<=MAX_ARRAY_LENGTH>>>1){for(;low<high;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computed<value)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){var low=0,high=null==array?0:array.length;if(0===high)return 0;value=iteratee(value);for(var valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=void 0===value;low<high;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=void 0!==computed,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol
vendor: 2,648 bytes, line 1
1=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):!(othIsNull||othIsSymbol)&&(retHighest?computed<=value:computed<value);setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_LENGTH-1)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index<length;){var value=array[index],computed=iteratee?iteratee(value):value;if(!index||!eq(computed,seen)){var seen=computed;result[resIndex++]=0===value?0:value}}return result}function baseToNumber(value){return'number'==typeof value?value:isSymbol(value)?NAN:+value}function baseToString(value){if('string'==typeof value)return value;if(isArray(value))return arrayMap(value,baseToString)+'';if(isSymbol(value))return symbolToString?symbolToString.call(value):'';var result=value+'';return'0'==result&&1/value==-INFINITY?'-0':result}function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index<length;){var value=array[index],computed=iteratee?iteratee(value):value;if(value=comparator||0!==value?value:0,isCommon&&computed===computed){for(var seenIndex=seen.length;seenIndex--;)if(seen[seenIndex]===computed)continue outer;iteratee&&seen.push(computed),result.push(value)}else includes(seen,computed,comparator)||(seen!==result&&seen.push(computed),result.push(value))}return result}function baseUnset(object,path){return path=castPath(path,object),object=parent(object,path),null==object||delete object[toKey(last(path))]}function baseUpdate(object,path,updater,customizer){return baseSet(object,path,updater(baseGet(object,path)),customizer)}function baseWhile(array,predicate,isDrop,fromRight){for(var length=array.length,index=fromRight?length:-1;(fromRight?index--:++index<length)&&predicate(array[index],index,array););return isDrop?baseSlice(array,fromRight?0:index,fromRight?index+1:length):baseSlice(array,fromRight?index+1:0,fromRight?length:index)}function baseWrapperValue(value,actions){var result=value;return result instanceof LazyWrapper&&(result=result.value()),arrayReduce(actions,function(result,action){return action.func.apply(action.thisArg,arrayPush([result],action.args
1))},result)}function baseXor(arrays,iteratee,comparator){var length=arrays.length;if(2>length)return length?baseUniq(arrays[0]):[];for(var index=-1,result=Array(length);++index<length;)for(var array=arrays[index],othIndex=-1;++othIndex<length;)othIndex!=index&&(result[index]=baseDifference(result[index]||array,arrays[othIndex],iteratee,comparator));return baseUniq(baseFlatten(result,1),iteratee,comparator)}function baseZipObject(props,values,assignFunc){for(var index=-1,length=props.length,valsLength=values.length,result={},value;++index<length;)value=index<valsLength?values[index]:void 0,assignFunc(result,props[index],value);return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return'function'==typeof value?value:identity}function castPath(value,object){return isArray(value)?value:isKey(value,object)?[value]:stringToPath(toString(value))}function castSlice(array,start,end){var length=array.length;return end=void 0===end?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=void 0!==value,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=void 0!==other,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value<other||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length,result;++index<length;)if(result=compareAscending(objCriteria[index],othCriteria[index]),result){if(index>=ordersLength)return result;var order=orders[index];return result*('desc'==order?-1:1)}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndex<leftLength;)result[leftIndex]=partials[leftIndex];for(;++argsIndex<holdersLength;)(isUncurried||argsIndex<argsLength)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndex<rangeLength;)result[argsIndex]=args[argsIndex];for(var offset=argsIndex;++rightIndex<rightLength;)result[offset+rightIndex]=partials[rightIndex];for(;++holdersIndex<holdersLength;)(isUncurried||argsIndex<argsLength)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index<length;)array[index]=source[index];return array}function copyObject(source,props,object,customizer){var isNew=!object;object||(object={});for(var index=-1,length=props.length;++index<length;){var key=props[index],newValue=customizer?customizer(object[key],source[key],key,object,source):void 0;void 0===newValue&&(newValue=source[key]),isNew?baseAssignValue(object,key,newValue):assignValue(object,key,newValue)}return object}function copySymbols(source,object){return copyObject(source,getSymbols(source),object)}function copySymbolsIn(source,object){return copyObject(source,getSymbolsIn(source),object)}function createAggregator(setter,initializer){return function(collection,iteratee){var func=isArray(collection)?arrayAggregator:baseAggregator,accumulator=initializer?initializer():{};return func(collection,setter,getIteratee(iteratee,2),accumulator)}}function createAssigner(assigner){return baseRest(function(object,sources){var index=-1,length=sources.length,customizer=1<length?sources[length-1]:void 0,guard=2<length?sources[2]:void 0;for(customizer=3<assigner.length&&'function'==typeof customizer?(length--,customizer):void 0,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?void 0:customizer,length=1),object=Object(object);++index<length;){var source=sources[index];source&&assigner(object,source,index,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){if(null==collection)return collection;if(!isArrayLike(collection))return eachFunc(collection,iteratee);for(var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);(fromRight?index--:++index<length)&&!1!==iteratee(iterable[index],index,iterable););return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length,key;length--&&(key=props[fromRight?length:++index],!1!==iteratee(iterable[key],key,iterable)););return object}}function createBind(func,bitmask,thisArg){function wrapper(){var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return fn.apply(isBind?thisArg:this,arguments)}var isBind=bitmask&WRAP_BIND_FLAG,Ctor=createCtor(func);return wrapper}function createCaseFirst(methodName){return function(string){string=toString(string);var strSymbols=hasUnicode(string)?stringToArray(string):void 0,chr=strSymbols?strSymbols[0]:string.charAt(0),trailing=strSymbols?castSlice(strSymbols,1).join(''):string.slice(1);return chr[methodName]()+trailing}}function createCompounder(callback){return function(string){return arrayReduce(words(deburr(string).replace(reApos,'')),callback,'')}}function createCtor(Ctor){return function(){var args=arguments;switch(args.length){case 0:return new Ctor;case 1:return new Ctor(args[0]);case 2:return new Ctor(args[0],args[1]);case 3:return new Ctor(args[0],args[1],args[2]);case 4:return new Ctor(args[0],args[1],args[2],args[3]);case 5:return new Ctor(args[0],args[1],args[2],args[3],args[4]);case 6:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5]);case 7:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);}var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,args);return isObject(result)?result:thisBinding}}function createCurry(func,bitmask,arity){function wrapper(){for(var length=arguments.length,args=Array(length),index=length,placeholder=getHolder(wrapper);index--;)args[index]=arguments[index];var holders=3>
1length&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,length<arity)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,void 0,args,holders,void 0,void 0,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return-1<index?iterable[iteratee?collection[index]:index]:void 0}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&'wrapper'==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index<length;){func=funcs[index];var funcName=getFuncName(func),data='wrapper'==funcName?getData(func):void 0;wrapper=data&&isLaziable(data[0])&&data[1]==(WRAP_ARY_FLAG|WRAP_CURRY_FLAG|WRAP_PARTIAL_FLAG|WRAP_REARG_FLAG)&&!data[4].length&&1==data[9]?wrapper[getFuncName(data[0])].apply(wrapper,data[3]):1==func.length&&isLaziable(func)?wrapper[funcName]():wrapper.thru(func)}return function(){var args=arguments,value=args[0];if(wrapper&&1==args.length&&isArray(value))return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++index<length;)result=funcs[index].call(this,result);return result}})}function createHybrid(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){function wrapper(){for(var length=arguments.length,args=Array(length),index=length;index--;)args[index]=arguments[index];if(isCurried)var placeholder=getHolder(wrapper),holdersCount=countHolders(args,placeholder);if(partials&&(args=composeArgs(args,partials,holders,isCurried)),partialsRight&&(args=composeArgsRight(args,partialsRight,holdersRight,isCurried)),length-=holdersCount,isCurried&&length<arity){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&1<length&&args.reverse(),isAry&&ary<length&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&WRAP_ARY_FLAG,isBind=bitmask&WRAP_BIND_FLAG,isBindKey=bitmask&WRAP_BIND_KEY_FLAG,isCurried=bitmask&(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG),isFlip=bitmask&WRAP_FLIP_FLAG,Ctor=isBindKey?void 0:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(void 0===value&&void 0===other)return defaultValue;if(void 0!==value&&(result=value),void 0!==other){if(void 0===result)return other;'string'==typeof value||'string'==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=void 0===chars?' ':baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(''):result.slice(0,length)}
1function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndex<leftLength;)args[leftIndex]=partials[leftIndex];for(;argsLength--;)args[leftIndex++]=arguments[++argsIndex];return apply(fn,isBind?thisArg:this,args)}var isBind=bitmask&WRAP_BIND_FLAG,Ctor=createCtor(func);return wrapper}function createRange(fromRight){return function(start,end,step){return step&&'number'!=typeof step&&isIterateeCall(start,end,step)&&(end=step=void 0),start=toFinite(start),void 0===end?(end=start,start=0):end=toFinite(end),step=void 0===step?start<end?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return'string'==typeof value&&'string'==typeof other||(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&WRAP_CURRY_FLAG,newHolders=isCurry?holders:void 0,newHoldersRight=isCurry?void 0:holders,newPartials=isCurry?partials:void 0,newPartialsRight=isCurry?void 0:partials;bitmask|=isCurry?WRAP_PARTIAL_FLAG:WRAP_PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?WRAP_PARTIAL_RIGHT_FLAG:WRAP_PARTIAL_FLAG),bitmask&WRAP_CURRY_BOUND_FLAG||(bitmask&=~(WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(void 0,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=null==precision?0:nativeMin(toInteger(precision),292),precision&&nativeIsFinite(number)){var pair=(toString(number)+'e').split('e'),value=func(pair[0]+'e'+(+pair[1]+precision));return pair=(toString(value)+'e').split('e'),+(pair[0]+'e'+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&WRAP_BIND_KEY_FLAG;if(!isBindKey&&'function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(WRAP_PARTIAL_FLAG|WRAP_PARTIAL_RIGHT_FLAG),partials=holders=void 0),ary=void 0===ary?ary:nativeMax(toInteger(ary),0),arity=void 0===arity?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&WRAP_PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=void 0}var data=isBindKey?void 0:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=void 0===newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG)&&(bitmask&=~(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG)),!bitmask||bitmask==WRAP_BIND_FLAG)var result=createBind(func,bitmask,thisArg);else result=bitmask==WRAP_CURRY_FLAG||bitmask==WRAP_CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=WRAP_PARTIAL_FLAG&&bitmask!=(WRAP_BIND_FLAG|WRAP_PARTIAL_FLAG)||holders.length?createHybrid.apply(void 0,newData):createPartial(func,bitmask,thisArg,partials);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function customDefaultsAssignIn(objValue,srcValue,key,object){return void 0===objValue||eq(objValue,objectProto[key])&&!hasOwnProperty.call(object,key)?srcValue:objValue}function customDefaultsMerge(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,void 0,customDefaultsMerge,stack),stack['delete'](srcValue)),objValue}function customOmitClone(value){return isPlainObject(value)?void 0:value}function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var arrStacked=stack.get(array),othStacked=stack.get(other);if(arrStacked&&othStacked)return arrStacked==other&&othStacked==array;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCac
1he:void 0;for(stack.set(array,other),stack.set(other,array);++index<arrLength;){var arrValue=array[index],othValue=other[index];if(customizer)var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack);if(void 0!==compared){if(compared)continue;result=!1;break}if(seen){if(!arraySome(other,function(othValue,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack)))return seen.push(othIndex)})){result=!1;break}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){result=!1;break}}return stack['delete'](array),stack['delete'](other),result}function equalByTag(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case dataViewTag:if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset)return!1;object=object.buffer,other=other.buffer;case arrayBufferTag:return!!(object.byteLength==other.byteLength&&equalFunc(new Uint8Array(object),new Uint8Array(other)));case boolTag:case dateTag:case numberTag:return eq(+object,+other);case errorTag:return object.name==other.name&&object.message==other.message;case regexpTag:case stringTag:return object==other+'';case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&COMPARE_PARTIAL_FLAG;if(convert||(convert=setToArray),object.size!=other.size&&!isPartial)return!1;var stacked=stack.get(object);if(stacked)return stacked==other;bitmask|=COMPARE_UNORDERED_FLAG,stack.set(object,other);var result=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);return stack['delete'](object),result;case symbolTag:if(symbolValueOf)return symbolValueOf.call(object)==symbolValueOf.call(other);}return!1}function equalObjects(object,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,objProps=getAllKeys(object),objLength=objProps.length,othProps=getAllKeys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial)return!1;for(var index=objLength,key;index--;)if(key=objProps[index],isPartial?!(key in other):!hasOwnProperty.call(other,key))return!1;var objStacked=stack.get(object),othStacked=stack.get(other);if(objStacked&&othStacked)return objStacked==other&&othStacked==object;var result=!0;stack.set(object,other),stack.set(other,object);for(var skipCtor=isPartial;++index<objLength;){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer)var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack);if(void 0===compared?!(objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack)):!compared){result=!1;break}skipCtor||(skipCtor='constructor'==key)}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;objCtor!=othCtor&&'constructor'in object&&'constructor'in other&&!('function'==typeof objCtor&&objCtor instanceof objCtor&&'function'==typeof othCtor&&othCtor instanceof othCtor)&&(result=!1)}return stack['delete'](object),stack['delete'](other),result}function flatRest(func){return setToString(overRest(func,void 0,flatten),func+'')}function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols)}function getAllKeysIn(object){return baseGetAllKeys(object,keysIn,getSymbolsIn)}function getFuncName(func){for(var result=func.name+'',array=realNames[result],length=hasOwnProperty.call(realNames,result)?array.length:0;length--;){var data=array[length],otherFunc=data.func;if(null==otherFunc||otherFunc==func)return data.name}return result}function getHolder(func){var object=hasOwnProperty.call(lodash,'placeholder')?lodash:func;return object.placeholder}function getIteratee(){var result=lodash.iteratee||iteratee;return result=result===iteratee?baseIteratee:result,arguments.length?result(arguments[0],arguments[1]):result}function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data['string'==typeof key?'string':'hash']:data.map}function getMatchData(object){for(var result=keys(object),length=result.length;length--;){var key=result[length],value=object[key];result[length]=[key,value,isStrictComparable(value)]}return result}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=void 0}catch(e){}var result=nativeObjectToString.call(value);return isOwn?value[symToStringTag]=tag:delete value[symToStringTag],result}function getView(start,end,transforms){for(var index=-1,length=transforms.length;++index<length;){var data=transforms[index],size=data.size;switch(data.type){case'drop':start+=size;break;case'dropRight':end-=size;break;case'take':end=nativeMin(end,start+size);break;case'takeRight':start=nativeMax(start,end-size);}}return{'start':start,'end':end}}function getWrapDetails(source){var match=source.match(reWrapDetails);return match?match[1].split(reSplitDetails):[]}function hasPath(object,path,hasFunc){path=castPath(path,object);for(var index=-1,length=path.length,result=!1,key;++index<length&&(key=toKey(path[index]),!!(result=null!=object&&hasFunc(object,key)));)object=object[key];return result||++index!=length?result:(length=null==object?0:object.length,!!length&&isLength(length)&&isIndex(key,length)&&(isArray(object)||isArguments(object)))}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&'string'==typeof array[0]&&hasOwnProperty.call(array,'index')&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){return'function'!=typeof object.constructor||isPrototype(object)?{}:baseCreate(getPrototype(object))}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;return tag===arrayBufferTag?cloneArrayBuffer(object):tag===boolTag||tag===dateTag?new Ctor(+object):tag===dataViewTag?cloneDataView(object,isDeep):tag===float32Tag||tag===float64Tag||tag===int8Tag||tag===int16Tag||tag===int32Tag||tag===uint8Tag||tag===uint8ClampedTag||tag===uint16Tag||tag===uint32Tag?cloneTypedArray(object,isDeep):tag===mapTag?new Ctor:tag===numberTag||tag===stringTag?new Ctor(object):tag===regexpTag?cloneRegExp(object):tag===setTag?new Ctor:tag===symbolTag?cloneSymbol(object):void 0}
1function insertWrapDetails(source,details){var length=details.length;if(!length)return source;var lastIndex=length-1;return details[lastIndex]=(1<length?'& ':'')+details[lastIndex],details=details.join(2<length?', ':' '),source.replace(reWrapComment,'{\n/* [wrapped with '+details+'] */\n')}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){var type=typeof value;return length=null==length?MAX_SAFE_INTEGER:length,!!length&&('number'==type||'symbol'!=type&&reIsUint.test(value))&&-1<value&&0==value%1&&value<length}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return('number'==type?!!(isArrayLike(object)&&isIndex(index,object.length)):!!('string'==type&&index in object))&&eq(object[index],value)}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return!!('number'==type||'symbol'==type||'boolean'==type||null==value||isSymbol(value))||reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return'string'==type||'number'==type||'symbol'==type||'boolean'==type?'__proto__'!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if('function'!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto='function'==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null!=object&&object[key]===srcValue&&(void 0!==srcValue||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===500&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=newBitmask<(WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG|WRAP_ARY_FLAG),isCombo=srcBitmask==WRAP_ARY_FLAG&&bitmask==WRAP_CURRY_FLAG||srcBitmask==WRAP_ARY_FLAG&&bitmask==WRAP_REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(WRAP_ARY_FLAG|WRAP_REARG_FLAG)&&source[7].length<=source[8]&&bitmask==WRAP_CURRY_FLAG;if(!(isCommon||isCombo))return data;srcBitmask&WRAP_BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&WRAP_BIND_FLAG?0:WRAP_CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&WRAP_ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function objectToString(value){return nativeObjectToString.call(value)}function overRest(func,start,transform){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index<length;)array[index]=args[start+index];index=-1;for(var otherArgs=Array(start+1);++index<start;)otherArgs[index]=args[index];return otherArgs[start]=transform(array),apply(func,this,otherArgs)}}function parent(object,path){return 2>path.length?object:baseGet(object,baseSlice(path,0,-1))}function reorder(array,indexes){for(var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=copyArray(array),index;length--;)index=indexes[length],array[length]=isIndex(index,arrLength)?oldArray[index]:void 0;return array}function safeGet(object,key){return'constructor'===key&&'function'==typeof object[key]||'__proto__'==key?void 0:object[key]}function setWrapToString(wrapper,reference,bitmask){var source=reference+'';return setToString(wrapper,insertWrapDetails(source,updateWrapDetails(getWrapDetails(source),bitmask)))}function shortOut(func){var count=0,lastCalled=0;return function(){var stamp=nativeNow(),remaining=16-(stamp-lastCalled);if(lastCalled=stamp,!(0<remaining))count=0;else if(++count>=800)return arguments[0];return func.apply(void 0,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length;for(size=void 0===size?length:size;++index<size;){var rand=baseRandom(index,length-1),value=array[rand];array[rand]=array[index],array[index]=value}return array.length=size,array}function toKey(value){if('string'==typeof value||isSymbol(value))return value;var result=value+'';return'0'==result&&1/value==-INFINITY?'-0':result}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+''}catch(e){}}return''}
1function updateWrapDetails(details,bitmask){return arrayEach(wrapFlags,function(pair){var value='_.'+pair[0];bitmask&pair[1]&&!arrayIncludes(details,value)&&details.push(value)}),details.sort()}function wrapperClone(wrapper){if(wrapper instanceof LazyWrapper)return wrapper.clone();var result=new LodashWrapper(wrapper.__wrapped__,wrapper.__chain__);return result.__actions__=copyArray(wrapper.__actions__),result.__index__=wrapper.__index__,result.__values__=wrapper.__values__,result}function chunk(array,size,guard){size=(guard?isIterateeCall(array,size,guard):void 0===size)?1:nativeMax(toInteger(size),0);var length=null==array?0:array.length;if(!length||1>size)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));index<length;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=null==array?0:array.length,resIndex=0,result=[],value;++index<length;)value=array[index],value&&(result[resIndex++]=value);return result}function findIndex(array,predicate,fromIndex){var length=null==array?0:array.length;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=null==array?0:array.length;if(!length)return-1;var index=length-1;return void 0!==fromIndex&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=null==array?0:array.length;return length?baseFlatten(array,1):[]}function fromPairs(pairs){for(var index=-1,length=null==pairs?0:pairs.length,result={},pair;++index<length;)pair=pairs[index],result[pair[0]]=pair[1];return result}function head(array){return array&&array.length?array[0]:void 0}function last(array){var length=null==array?0:array.length;return length?array[length-1]:void 0}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function remove(array,predicate){var result=[];if(!(array&&array.length))return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++index<length;){var value=array[index];predicate(value,index,array)&&(result.push(value),indexes.push(index))}return basePullAt(array,indexes),result}function reverse(array){return null==array?array:nativeReverse.call(array)}function unzip(array){if(!(array&&array.length))return[];var length=0;return array=arrayFilter(array,function(group){if(isArrayLikeObject(group))return length=nativeMax(group.length,length),!0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!(array&&array.length))return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,void 0,group)})}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function thru(value,interceptor){return interceptor(value)}function wrapperPlant(value){for(var parent=this,result,clone;parent instanceof baseLodash;){clone=wrapperClone(parent),clone.__index__=0,clone.__values__=void 0,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function ary(func,n,guard){return n=guard?void 0:n,n=func&&null==n?func.length:n,createWrap(func,WRAP_ARY_FLAG,void 0,void 0,void 0,void 0,n)}function before(n,func){var result;if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return 0<--n&&(result=func.apply(this,arguments)),1>=n&&(func=void 0),result}}function curry(func,arity,guard){arity=guard?void 0:arity;var result=createWrap(func,WRAP_CURRY_FLAG,void 0,void 0,void 0,void 0,void 0,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?void 0:arity;var result=createWrap(func,WRAP_CURRY_RIGHT_FLAG,void 0,void 0,void 0,void 0,void 0,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=void 0,lastInvokeTime=time,result=func.apply(thisArg,args),result}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,timeWaiting=wait-timeSinceLastCall;return maxing?nativeMin(timeWaiting,maxWait-timeSinceLastInvoke):timeWaiting}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return void 0===lastCallTime||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return(timerId=void 0,trailing&&lastArgs)?invokeFunc(time):(lastArgs=lastThis=void 0,result)}function cancel(){void 0!==timerId&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=void 0}function flush(){return void 0===timerId?result:trailingEdge(now())}
1function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(void 0===timerId)return leadingEdge(lastCallTime);if(maxing)return clearTimeout(timerId),timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return void 0===timerId&&(timerId=setTimeout(timerExpired,wait)),result}var lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0,lastArgs,lastThis,maxWait,result,timerId,lastCallTime;if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing='maxWait'in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing='trailing'in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function memoize(func,resolver){if('function'!=typeof func||null!=resolver&&'function'!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if('function'!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2]);}return!predicate.apply(this,args)}}function throttle(func,wait,options){var leading=!0,trailing=!0;if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading='leading'in options?!!options.leading:leading,trailing='trailing'in options?!!options.trailing:trailing),debounce(func,wait,{'leading':leading,'maxWait':wait,'trailing':trailing})}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isEmpty(value){if(null==value)return!0;if(isArrayLike(value)&&(isArray(value)||'string'==typeof value||'function'==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqualWith(value,other,customizer){customizer='function'==typeof customizer?customizer:void 0;var result=customizer?customizer(value,other):void 0;return void 0===result?baseIsEqual(value,other,void 0,customizer):!!result}function isError(value){if(!isObjectLike(value))return!1;var tag=baseGetTag(value);return tag==errorTag||tag=='[object DOMException]'||'string'==typeof value.message&&'string'==typeof value.name&&!isPlainObject(value)}function isFunction(value){if(!isObject(value))return!1;var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag=='[object AsyncFunction]'||tag=='[object Proxy]'}function isInteger(value){return'number'==typeof value&&value==toInteger(value)}function isLength(value){return'number'==typeof value&&-1<value&&0==value%1&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return null!=value&&('object'==type||'function'==type)}function isObjectLike(value){return null!=value&&'object'==typeof value}function isNumber(value){return'number'==typeof value||isObjectLike(value)&&baseGetTag(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return'function'==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isString(value){return'string'==typeof value||!isArray(value)&&isObjectLike(value)&&baseGetTag(value)==stringTag}function isSymbol(value){return'symbol'==typeof value||isObjectLike(value)&&baseGetTag(value)==symbolTag}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(symIterator&&value[symIterator])return iteratorToArray(value[symIterator]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*17976931348623157e292}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if('number'==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other='function'==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+'':other}if('string'!=typeof value)return 0===value?value:+value;value=baseTrim(value);var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toString(value){return null==value?'':baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return null==properties?result:baseAssign(result,properties)}function get(object,path,defaultValue){var result=null==object?void 0:baseGet(object,path);return void 0===result?defaultValue:result}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function pickBy(object,predicate){if(null==object)return{};var props=arrayMap(getAllKeysIn(object),function(prop){return[prop]});return predicate=getIteratee(predicate),basePickBy(object,props,function(value,path){return predicate(value,path[0])})}function result(object,path,defaultValue){path=castPath(path,object);var index=-1,length=path.length;for(length||(length=1,object=void 0);++index<length;){var value=null==object?void 0:object[toKey(path[index])];void 0===value&&(index=length,value=defaultValue),object=isFunction(value)?value.call(object):value}return object}function values(object){return null==object?[]:baseValues(object,keys(object))}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,'')}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=void 0),string=toString(string),options=assignInWith({},options,settings,customDefaultsAssignIn);var imports=assignInWith({},options.imports,settings.imports,customDefaultsAssignIn),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source='__p += \'',reDelimiters=RegExp((options.escape||reNoMatch).source+'|'+interpolate.source+'|'+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+'|'+(options.evaluate||reNoMatch).source+'|$','g'),sourceURL='//# sourceURL='+(hasOwnProperty.call(options,'sourceURL')?(options.sourceURL+'').replace(/\s/g,' '):'lodash.templateSources['+ ++templateCounter+']')+'\n',isEscaping,isEvaluating;string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+='\' +\n__e('+escapeValue+') +\n\''),evaluateValue&&(isEvaluating=!0,source+='\';\n'+evaluateValue+';\n__p += \''),interpolateValue&&(source+='\' +\n((__t = ('+interpolateValue+')) == null ? \'\' : __t) +\n\''),index=offset+match.length,match}),source+='\';\n';var variable=hasOwnProperty.call(options,'variable')&&options.variable;if(!variable)source='with (obj) {\n'+source+'\n}\n';else if(reForbiddenIdentifierChars.test(variable))throw new Error('Invalid `variable` option passed into `_.template`');source=(isEvaluating?source.replace(reEmptyStringLeading,''):source).replace(reEmptyStringMiddle,'$1').replace(reEmptyStringTrailing,'$1;'),source='function('+(variable||'obj')+') {\n'+(variable?'':'obj || (obj = {});\n')+'var __t, __p = \'\''+(isEscaping?', __e = _.escape':'')+(isEvaluating?', __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, \'\') }\n':';\n')+source+'return __p\n}';var result=attempt(function(){return Function(importsKeys,sourceURL+'return '+source).apply(void 0,importsValues)});if(result.source=source,isError(result))throw result;return result}function truncate(string,options){var length=30,omission='...';if(isObject(options)){var separator='separator'in options?options.separator:separator;length='length'in options?toInteger(options.length):length,omission='omission'in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(''):string.slice(0,end);if(void 0===separator)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var substring=result,match;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+'g')),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,void 0===newEnd?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);-1<index&&(result=result.slice(0,index))}return result+omission}function words(string,pattern,guard){return string=toString(string),pattern=guard?void 0:pattern,void 0===pattern?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function constant(value){return function(){return value}}function identity(value){return value}function iteratee(func){return baseIteratee('function'==typeof func?func:baseClone(func,CLONE_DEEP_FLAG))}function mixin(object,source,options){var props=keys(source),methodNames=baseFunctions(source,props);null!=options||isObject(source)&&(methodNames.length||!props.length)||(options=source,source=object,object=this,methodNames=baseFunctions(source,keys(source)));
1var chain=!(isObject(options)&&'chain'in options)||!!options.chain,isFunc=isFunction(object);return arrayEach(methodNames,function(methodName){var func=source[methodName];object[methodName]=func,isFunc&&(object.prototype[methodName]=function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__),actions=result.__actions__=copyArray(this.__actions__);return actions.push({'func':func,'args':arguments,'thisArg':object}),result.__chain__=chainAll,result}return func.apply(object,arrayPush([this.value()],arguments))})}),object}function noop(){}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}function stubArray(){return[]}function stubFalse(){return!1}function times(n,iteratee){if(n=toInteger(n),1>n||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index<n;)iteratee(index);return result}function uniqueId(prefix){var id=++idCounter;return toString(prefix)+id}context=null==context?root:_.defaults(root.Object(),context,_.pick(root,contextProps));var Array=context.Array,Date=context.Date,Error=context.Error,Function=context.Function,Math=context.Math,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=context['__core-js_shared__'],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,idCounter=0,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||'');return uid?'Symbol(src)_1.'+uid:''}(),nativeObjectToString=objectProto.toString,objectCtorString=funcToString.call(Object),oldDash=root._,reIsNative=RegExp('^'+funcToString.call(hasOwnProperty).replace(reRegExpChar,'\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$'),Buffer=moduleExports?context.Buffer:void 0,Symbol=context.Symbol,Uint8Array=context.Uint8Array,allocUnsafe=Buffer?Buffer.allocUnsafe:void 0,getPrototype=overArg(Object.getPrototypeOf,Object),objectCreate=Object.create,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,symIterator=Symbol?Symbol.iterator:void 0,symToStringTag=Symbol?Symbol.toStringTag:void 0,defineProperty=function(){try{var func=getNative(Object,'defineProperty');return func({},'',{}),func}catch(e){}}(),ctxClearTimeout=context.clearTimeout!==root.clearTimeout&&context.clearTimeout,ctxNow=Date&&Date.now!==root.Date.now&&Date.now,ctxSetTimeout=context.setTimeout!==root.setTimeout&&context.setTimeout,nativeCeil=Math.ceil,nativeFloor=Math.floor,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeIsFinite=context.isFinite,nativeJoin=arrayProto.join,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,nativeMin=Math.min,nativeNow=Date.now,nativeParseInt=context.parseInt,nativeRandom=Math.random,nativeReverse=arrayProto.reverse,DataView=getNative(context,'DataView'),Map=getNative(context,'Map'),Promise=getNative(context,'Promise'),Set=getNative(context,'Set'),WeakMap=getNative(context,'WeakMap'),nativeCreate=getNative(Object,'create'),metaMap=WeakMap&&new WeakMap,realNames={},dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,baseCreate=function(){function object(){}return function(proto){if(!isObject(proto))return{};if(objectCreate)return objectCreate(proto);object.prototype=proto;var result=new object;return object.prototype=void 0,result}}();lodash.templateSettings={'escape':reEscape,'evaluate':reEvaluate,'interpolate':reInterpolate,'variable':'','imports':{'_':lodash}},lodash.prototype=baseLodash.prototype,lodash.prototype.constructor=lodash,LodashWrapper.prototype=baseCreate(baseLo
1dash.prototype),LodashWrapper.prototype.constructor=LodashWrapper,LazyWrapper.prototype=baseCreate(baseLodash.prototype),LazyWrapper.prototype.constructor=LazyWrapper,Hash.prototype.clear=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype['delete']=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype['delete']=function(key){var data=this.__data__,index=assocIndexOf(data,key);if(0>index)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]},ListCache.prototype.has=function(key){return-1<assocIndexOf(this.__data__,key)},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={'hash':new Hash,'map':new(Map||ListCache),'string':new Hash}},MapCache.prototype['delete']=mapCacheDelete,MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype['delete']=stackDelete,Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length<LARGE_ARRAY_SIZE-1)return pairs.push([key,value]),this.size=++data.size,this;data=this.__data__=new MapCache(pairs)}return data.set(key,value),this.size=data.size,this};var baseEach=createBaseEach(baseForOwn),baseEachRight=createBaseEach(baseForOwnRight,!0),baseFor=createBaseFor(),baseForRight=createBaseFor(!0),baseSetData=metaMap?function(func,data){return metaMap.set(func,data),func}:identity,baseSetToString=defineProperty?function(func,string){return defineProperty(func,'toString',{'configurable':!0,'enumerable':!1,'value':constant(string),'writable':!0})}:identity,clearTimeout=ctxClearTimeout||function(id){return root.clearTimeout(id)},createSet=Set&&1/setToArray(new Set([,-0]))[1]==INFINITY?function(values){return new Set(values)}:noop,getData=metaMap?function(func){return metaMap.get(func)}:noop,getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getSymbolsIn=nativeGetSymbols?function(object){for(var result=[];object;)arrayPush(result,getSymbols(object)),object=getPrototype(object);return result}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set)!=setTag||WeakMap&&getTag(new WeakMap)!=weakMapTag)&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):'';if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag;}return result});var isMaskable=coreJsData?isFunction:stubFalse,setData=shortOut(baseSetData),setTimeout=ctxSetTimeout||function(func,wait){return root.setTimeout(func,wait)},setToString=shortOut(baseSetToString),stringToPath=memoizeCapped(function(string){var result=[];return 46===string.charCodeAt(0)&&result.push(''),string.replace(rePropName,function(match,number,quote,subString){result.push(quote?subString.replace(reEscapeChar,'$1'):number||match)}),result}),difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0)):[]}),differenceBy=baseRest(function(array,values){var iteratee=last(values);return isArrayLikeObject(iteratee)&&(iteratee=void 0),isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0),getIteratee(iteratee,2)):[]}),differenceWith=baseRest(function(array,values){var comparator=last(values);return isArrayLikeObject(comparator)&&(comparator=void 0),isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0),void 0,comparator):[]}),intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[]}),intersectionBy=baseRest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);return iteratee===last(mapped)?iteratee=void 0:mapped.pop(),mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,getIteratee(iteratee,2)):[]}),intersectionWith=baseRest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);return comparator='function'==typeof comparator?comparator:void 0,comparator&&mapped.pop(),mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,void 0,comparator):[]}
1),pull=baseRest(pullAll),pullAt=flatRest(function(array,indexes){var length=null==array?0:array.length,result=baseAt(array,indexes);return basePullAt(array,arrayMap(indexes,function(index){return isIndex(index,length)?+index:index}).sort(compareAscending)),result}),union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0))}),unionBy=baseRest(function(arrays){var iteratee=last(arrays);return isArrayLikeObject(iteratee)&&(iteratee=void 0),baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0),getIteratee(iteratee,2))}),unionWith=baseRest(function(arrays){var comparator=last(arrays);return comparator='function'==typeof comparator?comparator:void 0,baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0),void 0,comparator)}),without=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[]}),xor=baseRest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject))}),xorBy=baseRest(function(arrays){var iteratee=last(arrays);return isArrayLikeObject(iteratee)&&(iteratee=void 0),baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee,2))}),xorWith=baseRest(function(arrays){var comparator=last(arrays);return comparator='function'==typeof comparator?comparator:void 0,baseXor(arrayFilter(arrays,isArrayLikeObject),void 0,comparator)}),zip=baseRest(unzip),zipWith=baseRest(function(arrays){var length=arrays.length,iteratee=1<length?arrays[length-1]:void 0;return iteratee='function'==typeof iteratee?(arrays.pop(),iteratee):void 0,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,
1interceptor=function(object){return baseAt(object,paths)};return 1<length||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)?this.thru(interceptor):(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({'func':thru,'args':[interceptor],'thisArg':void 0}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(void 0),array}))}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){result[++index]='function'==typeof path?apply(path,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return 1<length&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:2<length&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=WRAP_BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=WRAP_PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=WRAP_PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=baseRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index<length;)args[index]=transforms[index].call(this,args[index]);return apply(func,this,args)})}),partial=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partial));return createWrap(func,WRAP_PARTIAL_FLAG,void 0,partials,holders)}),partialRight=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrap(func,WRAP_PARTIAL_RIGHT_FLAG,void 0,partials,holders)}),rearg=flatRest(function(func,indexes){return createWrap(func,WRAP_REARG_FLAG,void 0,void 0,void 0,indexes)}),gt=createRelationalOperation(baseGt),gte=createRelationalOperation(function(value,other){return value>=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee')},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):function(value){return isObjectLike(value)&&baseGetTag(value)==arrayBufferTag},isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):function(value){return isObjectLike(value)&&baseGetTag(value)==dateTag},isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):function(value){return isObjectLike(value)&&baseGetTag(value)==regexpTag},isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return value<=other}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(object,sources){object=Object(object);var index=-1,length=sources.length,guard=2<length?sources[2]:void 0;for(guard&&isIterateeCall(sources[0],sources[1],guard)&&(length=1);++index<length;)for(var source=sources[index],props=keysIn(source),propsIndex=-1,propsLength=props.length;++propsIndex<propsLength;){var key=props[propsIndex],value=object[key];(void 0===value||eq(value,objectProto[key])&&!hasOwnProperty.call(object,key))&&(object[key]=source[key])}return object}),defaultsDeep=baseRest(function(args){return args.push(void 0,customDefaultsMerge),apply(mergeWith,void 0,args)}),invert=createInverter(function(result,value,key){null!=value&&'function'!=typeof value.toString&&(value=nativeObjectToString.call(value)),result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){null!=value&&'function'!=typeof value.toString&&(value=nativeObjectToString.call(value)),hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,paths){var result={};if(null==object)return result;var isDeep=!1;paths=arrayMap(paths,function(path){return path=castPath(path,object),isDeep||(isDeep=1<path.length),path}),copyObject(object,getAllKeysIn(object),result),isDeep&&(result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone));for(var length=paths.length;length--;)baseUnset(result,paths[length]);return result}),pick=flatRest(function(object,paths){return null==object?{}:basePick(object,paths)}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?'-':'')+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toLowerCase()}),lowerFirst=createCaseFirst('toLowerCase'),snakeCase=createCompounder(function(result,word,index){return result+(index?'_':'')+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?' ':'')+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toUpperCase()}
1),upperFirst=createCaseFirst('toUpperCase'),attempt=baseRest(function(func,args){try{return apply(func,void 0,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound('ceil'),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound('floor'),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound('round'),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=function(n,func){if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){if(1>--n)return func.apply(this,arguments)}},lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=function(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]},lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=function(){var length=arguments.length;if(!length)return[];for(var args=Array(length-1),array=arguments[0],index=length;index--;)args[index-1]=arguments[index];return arrayPush(isArray(array)?copyArray(array):[array],baseFlatten(args,1))},lodash.cond=function(pairs){var length=null==pairs?0:pairs.length,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if('function'!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1,pair;++index<length;)if(pair=pairs[index],apply(pair[0],this,args))return apply(pair[1],this,args)})},lodash.conforms=function(source){return baseConforms(baseClone(source,CLONE_DEEP_FLAG))},lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=function(array,n,guard){var length=null==array?0:array.length;return length?(n=guard||void 0===n?1:toInteger(n),baseSlice(array,0>n?0:n,length)):[]},lodash.dropRight=function(array,n,guard){var length=null==array?0:array.length;return length?(n=guard||void 0===n?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]},lodash.dropRightWhile=function(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]},lodash.dropWhile=function(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]},lodash.fill=function(array,value,start,end){var length=null==array?0:array.length;return length?(start&&'number'!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]},lodash.filter=function(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))},lodash.flatMap=function(collection,iteratee){return baseFlatten(map(collection,iteratee),1)},lodash.flatMapDeep=function(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)},lodash.flatMapDepth=function(collection,iteratee,depth){return depth=void 0===depth?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)},lodash.flatten=flatten,lodash.flattenDeep=function(array){var length=null==array?0:array.length;return length?baseFlatten(array,INFINITY):[]},lodash.flattenDepth=function(array,depth){var length=null==array?0:array.length;return length?(depth=void 0===depth?1:toInteger(depth),baseFlatten(array,depth)):[]},lodash.flip=function(func){return createWrap(func,WRAP_FLIP_FLAG)},lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=function(object){return null==object?[]:baseFunctions(object,keys(object))},lodash.functionsIn=function(object){return null==object?[]:baseFunctions(object,keysIn(object))},lodash.groupBy=groupBy,lodash.initial=function(array){var length=null==array?0:array.length;return length?baseSlice(array,0,-1):[]},lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=function(source){return baseMatches(baseClone(source,CLONE_DEEP_FLAG))},lodash.matchesProperty=function(path,srcValue){return baseMatchesProperty(path,baseClone(srcValue,CLONE_DEEP_FLAG))},lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=function(n){return n=toInteger(n),baseRest(function(args){return baseNth(args,n)})},lodash.omit=omit,lodash.omitBy=function(object,predicate){return pickBy(object,negate(getIteratee(predicate)))},lodash.once=function(func){return before(2,func)},lodash.orderBy=function(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?void 0:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))},lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=function(object){return function(path){return null==object?void 0:baseGet(object,path)}},lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=function(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array},lodash.pullAllWith=function(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,void 0,comparator):array},lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=function(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))},lodash.remove=remove,lodash.rest=function(func,start){if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?start:toInteger(start),baseRest(func,start)},lodash.reverse=reverse,lodash.sampleSize=function(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):void 0===n)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)},lodash.set=function(object,path,value){return null==object?object:baseSet(object,path,value)},lodash.setWith=function(object,path,value,customizer){return customizer='function'==typeof customizer?customizer:void 0,null==object?object:baseSet(object,path,value,customizer)},lodash.shuffle=function(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)},lodash.slice=function(array,start,end){var length=null==array?0:array.length;return length?(end&&'number'!=typeof end&&isIterateeCall(array,start,end)?(start=0,end=length):(start=null==start?0:toInteger(start),end=void 0===end?length:toInteger(end)),baseSlice(array,start,end)):[]},lodash.sortBy=sortBy,lodash.sortedUniq=function(array){return array&&array.length?baseSortedUniq(array):[]},lodash.sortedUniqBy=function(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]},lodash.split=function(string,separator,limit){return(limit&&'number'!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=void 0),limit=void 0===limit?MAX_ARRAY_LENGTH:limit>>>0,!limit)?[]:(string=toString(string),string&&('string'==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit))},lodash.spread=function(func,start){if('function'!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=null==start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})},lodash.tail=function(array){var length=null==array?0:array.length;return length?baseSlice(array,1,length):[]},lodash.take=function(array,n,guard){return array&&array.length?(n=guard||void 0===n?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]},lodash.takeRight=function(array,n,guard){var length=null==array?0:array.length;return length?(n=guard||void 0===n?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]},lodash.takeRightWhile=function(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]},lodash.takeWhile=function(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]},lodash.tap=function(value,interceptor){return interceptor(value),value},lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=function(value){return isArray(value)?arrayMap(value,toKey):isSymbol(value)?[value]:copyArray(stringToPath(toString(value)))},lodash.toPlainObject=toPlainObject,lodash.transform=function(object,iteratee,accumulator){var isArr=isArray(object),isArrLike=isArr||isBuffer(object)||isTypedArray(object);if(iteratee=getIteratee(iteratee,4),null==accumulator){var Ctor=object&&object.constructor;accumulator=isArrLike?isArr?new Ctor:[]:isObject(object)?isFunction(Ctor)?baseCreate(getPrototype(object)):{}:{}}return(isArrLike?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object)}),accumulator},lodash.unary=function(func){return ary(func,1)},lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=function(array){return array&&array.length?baseUniq(array):[]},lodash.uniqBy=function(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]},lodash.uniqWith=function(array,comparator){return comparator='function'==typeof comparator?comparator:void 0,array&&array.length?baseUniq(array,void 0,comparator):[]},lodash.unset=function(object,path){return null==object||baseUnset(object,path)},lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=function(object,path,updater){return null==object?object:baseUpdate(object,path,castFunction(updater))},lodash.updateWith=function(object,path,updater,customizer){return customizer='function'==typeof customizer?customizer:void 0,null==object?object:baseUpdate(object,path,castFunction(updater),customizer)},lodash.values=values,lodash.valuesIn=function(object){return null==object?[]:baseValues(object,keysIn(object))},lodash.without=without,lodash.words=words,lodash.wrap=function(value,wrapper){return partial(castFunction(wrapper),value)},lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=function(props,values){return baseZipObject(props||[],values||[],assignValue)},lodash.zipObjectDeep=function(props,values){return baseZipObject(props||[],values||[],baseSet)},lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=function(number,lower,upper){return void 0===upper&&(upper=lower,lower=void 0),void 0!==upper&&(upper=toNumber(upper),upper=upper===upper?up
1per:0),void 0!==lower&&(lower=toNumber(lower),lower=lower===lower?lower:0),baseClamp(toNumber(number),lower,upper)},lodash.clone=function(value){return baseClone(value,CLONE_SYMBOLS_FLAG)},lodash.cloneDeep=function(value){return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG)},lodash.cloneDeepWith=function(value,customizer){return customizer='function'==typeof customizer?customizer:void 0,baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG,customizer)},lodash.cloneWith=function(value,customizer){return customizer='function'==typeof customizer?customizer:void 0,baseClone(value,CLONE_SYMBOLS_FLAG,customizer)},lodash.conformsTo=function(object,source){return null==source||baseConformsTo(object,source,keys(source))},lodash.deburr=deburr,lodash.defaultTo=function(value,defaultValue){return null==value||value!==value?defaultValue:value},lodash.divide=divide,lodash.endsWith=function(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=void 0===position?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,0<=position&&string.slice(position,end)==target},lodash.eq=eq,lodash.escape=function(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string},lodash.escapeRegExp=function(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,'\\$&'):string},lodash.every=function(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=void 0),func(collection,getIteratee(predicate,3))},lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=function(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)},lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=function(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)},lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=function(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)},lodash.forInRight=function(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)},lodash.forOwn=function(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))},lodash.forOwnRight=function(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))},lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=function(object,path){return null!=object&&hasPath(object,path,baseHas)},lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=function(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?fromIndex<=length&&-1<collection.indexOf(value,fromIndex):!!length&&-1<baseIndexOf(collection,value,fromIndex)},lodash.indexOf=function(array,value,fromIndex){var length=null==array?0:array.length;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)},lodash.inRange=function(number,start,end){return start=toFinite(start),void 0===end?(end=start,start=0):end=toFinite(end),number=toNumber(number),baseInRange(number,start,end)},lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=function(value){return!0===value||!1===value||isObjectLike(value)&&baseGetTag(value)==boolTag},lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=function(value){return isObjectLike(value)&&1===value.nodeType&&!isPlainObject(value)},lodash.isEmpty=isEmpty,lodash.isEqual=function(value,other){return baseIsEqual(value,other)},lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=function(value){return'number'==typeof value&&nativeIsFinite(value)},lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=function(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))},lodash.isMatchWith=function(object,source,customizer){return customizer='function'==typeof customizer?customizer:void 0,baseIsMatch(object,source,getMatchData(source),customizer)},lodash.isNaN=function(value){return isNumber(value)&&value!=+value},lodash.isNative=function(value){if(isMaskable(value))throw new Error('Unsupported core-js use. Try https://npms.io/search?q=ponyfill.');return baseIsNative(value)},lodash.isNil=function(value){return null==value},lodash.isNull=function(value){return null===value},lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=function(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER}
1,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=function(value){return void 0===value},lodash.isWeakMap=isWeakMap,lodash.isWeakSet=function(value){return isObjectLike(value)&&baseGetTag(value)=='[object WeakSet]'},lodash.join=function(array,separator){return null==array?'':nativeJoin.call(array,separator)},lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=function(array,value,fromIndex){var length=null==array?0:array.length;if(!length)return-1;var index=length;return void 0!==fromIndex&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)},lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=function(array){return array&&array.length?baseExtremum(array,identity,baseGt):void 0},lodash.maxBy=function(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee,2),baseGt):void 0},lodash.mean=function(array){return baseMean(array,identity)},lodash.meanBy=function(array,iteratee){return baseMean(array,getIteratee(iteratee,2))},lodash.min=function(array){return array&&array.length?baseExtremum(array,identity,baseLt):void 0},lodash.minBy=function(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee,2),baseLt):void 0},lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=function(){return{}},lodash.stubString=function(){return''},lodash.stubTrue=function(){return!0},lodash.multiply=multiply,lodash.nth=function(array,n){return array&&array.length?baseNth(array,toInteger(n)):void 0},lodash.noConflict=function(){return root._===this&&(root._=oldDash),this},lodash.noop=noop,lodash.now=now,lodash.pad=function(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)},lodash.padEnd=function(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength<length?string+createPadding(length-strLength,chars):string},lodash.padStart=function(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength<length?createPadding(length-strLength,chars)+string:string},lodash.parseInt=function(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string).replace(reTrimStart,''),radix||0)},lodash.random=function(lower,upper,floating){if(floating&&'boolean'!=typeof floating&&isIterateeCall(lower,upper,floating)&&(upper=floating=void 0),void 0===floating&&('boolean'==typeof upper?(floating=upper,upper=void 0):'boolean'==typeof lower&&(floating=lower,lower=void 0)),void 0===lower&&void 0===upper?(lower=0,upper=1):(lower=toFinite(lower),void 0===upper?(upper=lower,lower=0):upper=toFinite(upper)),lower>upper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat('1e-'+((rand+'').length-1))),upper)}return baseRandom(lower,upper)},lodash.reduce=function(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=3>arguments.length;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)},lodash.reduceRight=function(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=3>arguments.length;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)},lodash.repeat=function(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):void 0===n)?1:toInteger(n),baseRepeat(toString(string),n)},lodash.replace=function(){var args=arguments,string=toString(args[0]);return 3>args.length?string:string.replace(args[1],args[2])},lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=function(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)},lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=function(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=void 0),func(collection,getIteratee(predicate,3))},lodash.sortedIndex=function(array,value){return baseSortedIndex(array,value)},lodash.sortedIndexBy=function(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2))},lodash.sortedIndexOf=function(array,value){var length=null==array?0:array.length;if(length){var index=baseSortedIndex(array,value);if(index<length&&eq(array[index],value))return index}return-1},lodash.sortedLastIndex=function(array,value){return baseSortedIndex(array,value,!0)},lodash.sortedLastIndexBy=function(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)},lodash.sortedLastIndexOf=function(array,value){var length=null==array?0:array.length;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1},lodash.startCase=startCase,lodash.startsWith=function(string,target,position){return string=toString(string),position=null==position?0:baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target},lodash.subtract=subtract,lodash.sum=function(array){return array&&array.length?baseSum(array,identity):0},lodash.sumBy=function(array,iteratee){return array&&array.length?baseSum(array,getIteratee(iteratee,2)):0},lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=function(value){return toString(value).toLowerCase()},lodash.toNumber=toNumber,lodash.toSafeInteger=function(value){return value?baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER):0===value?value:0},lodash.toString=toString,lodash.toUpper=function(value){return toString(value).toUpperCase()},lodash.trim=function(string,chars,guard){if(string=toString(string),string&&(guard||void 0===chars))return baseTrim(string);if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join('')},lodash.trimEnd=function(string,chars,guard){if(string=toString(string),string&&(guard||void 0===chars))return string.slice(0,trimmedEndIndex(string)+1);if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join('')},lodash.trimStart=function(string,chars,guard){if(string=toString(string),string&&(guard||void 0===chars))return string.replace(reTrimStart,'');if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join('')},lodash.truncate=truncate,lodash.unescape=function(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string},lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{'chain':!1}),lodash.VERSION='4.17.21',arrayEach(['bind','bindKey','curry','curryRight','partial','partialRight'],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(['drop','take'],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){n=void 0===n?1:nativeMax(toInteger(n),0);var result=this.__filtered__&&!index?new LazyWrapper(this):this.clone();return result.__filtered__?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({'size':nativeMin(n,MAX_ARRAY_LENGTH),'type':methodName+(0>result.__dir__?'Right':'')}),result},LazyWrapper.prototype[methodName+'Right']=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(['filter','map','takeWhile'],function(methodName,index){var type=index+1;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({'iteratee':getIteratee(iteratee,3),'type':type}),result.__filtered__=result.__filtered__||type==LAZY_FILTER_FLAG||type==3,result}}),arrayEach(['head','last'],function(methodName,index){var takeN
1ame='take'+(index?'Right':'');LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(['initial','tail'],function(methodName,index){var dropName='drop'+(index?'':'Right');LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return'function'==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(0<start||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),void 0!==end&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?'take'+('last'==methodName?'Right':''):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&'function'==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({'func':thru,'args':[interceptor],'thisArg':void 0}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(['pop','push','shift','sort','splice','unshift'],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?'tap':'thru',retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+'';hasOwnProperty.call(realNames,key)||(realNames[key]=[]),realNames[key].push({'name':methodName,'func':lodashFunc})}}),realNames[createHybrid(void 0,WRAP_BIND_KEY_FLAG).name]=[{'name':'wrapper','func':void 0}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=function(){return chain(this)},lodash.prototype.commit=function(){return new LodashWrapper(this.value(),this.__chain__)},lodash.prototype.next=function(){void 0===this.__values__&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?void 0:this.__values__[this.__index__++];return{'done':done,'value':value}},lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=function(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({'func':thru,'args':[reverse],'thisArg':void 0}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)},lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=function(){return baseWrapperValue(this.__wrapped__,this.__actions__)},lodash.prototype.first=lodash.prototype.head,symIterator&&(lodash.prototype[symIterator]=function(){return this}),lodash}();root._=_,__WEBPACK_AMD_DEFINE_RESULT__=function(){return _}.call(exports,__webpack_require__,exports,module),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}).call(this)}).call(exports,function(){return this}(),__webpack_require__(31)(module))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(10),__webpack_require__(17)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,win){if(7>
1=has('ie'))try{document.execCommand('BackgroundImageCache',!1,!0)}catch(e){}var dom={};dom.byId=has('ie')?function(id,doc){if('string'!=typeof id)return id;var _d=doc||win.doc,te=id&&_d.getElementById(id);if(te&&(te.attributes.id.value==id||te.id==id))return te;var eles=_d.all[id];(!eles||eles.nodeName)&&(eles=[eles]);for(var i=0;te=eles[i++];)if(te.attributes&&te.attributes.id&&te.attributes.id.value==id||te.id==id)return te}:function(id,doc){return('string'==typeof id?(doc||win.doc).getElementById(id):id)||null},dom.isDescendant=function(node,ancestor){try{for(node=dom.byId(node),ancestor=dom.byId(ancestor);node;){if(node==ancestor)return!0;node=node.parentNode}}catch(e){}return!1},has.add('css-user-select',function(global,doc,element){if(!element)return!1;var style=element.style,prefixes=['Khtml','O','ms','Moz','Webkit'],i=prefixes.length,name='userSelect';do if('undefined'!=typeof style[name])return name;while(i--&&(name=prefixes[i]+'UserSelect'));return!1});var cssUserSelect=has('css-user-select');return dom.setSelectable=cssUserSelect?function(node,selectable){dom.byId(node).style[cssUserSelect]=selectable?'':'none'}:function(node,selectable){node=dom.byId(node);var nodes=node.getElementsByTagName('*'),i=nodes.length;if(selectable)for(node.removeAttribute('unselectable');i--;)nodes[i].removeAttribute('unselectable');else for(node.setAttribute('unselectable','on');i--;)nodes[i].setAttribute('unselectable','on')},dom}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(57)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,xhr){var xhrProvider=declare([],{constructor:function(){'withCredentials'in new XMLHttpRequest?this.corsSupport='xhr':'object'==typeof XDomainRequest||'function'==typeof XDomainRequest?this.corsSupport='xd':void 0},request:function(url,requestData,requestArgs,successCallback,errorCallback){if('xd'==this.corsSupport){for(var queryParam in requestArgs.query)url+=-1==url.indexOf('?')?'?':'&',url+=queryParam+'='+requestArgs.query[queryParam];requestArgs.preventCache&&(url+=-1==url.indexOf('?')?'?':'&',url+='_cb='+new Date().getTime());var xdr=new XDomainRequest;xdr.open(requestArgs.method||'GET',url),xdr.timeout=0,xdr.onload=function(){if('json'==requestArgs.handleAs.toLowerCase())null!=successCallback&&void 0!=successCallback&&successCallback(requestData,JSON.parse(xdr.responseText));else{var response;if(window.DOMParser){var parser=new window.DOMParser;response=parser.parseFromString(xdr.responseText,'text/xml')}else response=new ActiveXObject('Microsoft.XMLDOM'),response.async=!1,response.loadXML(xdr.responseText);null!=successCallback&&successCallback!=void 0&&successCallback(requestData,response.documentElement||response)}},xdr.onprogress=function(){},xdr.ontimeout=function(){},xdr.onerror=function(){null!=errorCallback&&errorCallback!=void 0&&errorCallback(requestData,'An unexpected error occurred')},setTimeout(function(){xdr.send()},250)}else if('xhr'==this.corsSupport)xhr(url,requestArgs).then(function(data){null!=successCallback&&void 0!=successCallback&&successCallback(requestData,data.documentElement||data)},function(error){null!=errorCallback&&void 0!=errorCallback&&errorCallback(requestData,'An unexpected error occurred: '+error)});else;}});return xhrProvider}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4)],__WEBPACK_AMD_DEFINE_RESULT__=function(has){if(has('host-browser')){var n=navigator,dua=n.userAgent,dav=n.appVersion,tv=parseFloat(dav);if(has.add('ie11',0<=dua.indexOf('Trident')),has.add('air',0<=dua.indexOf('AdobeAIR')),has.add('msapp',parseFloat(dua.split('MSAppHost/')[1])||void 0),has.add('khtml',0<=dav.indexOf('Konqueror')?tv:void 0),has.add('webkit',parseFloat(dua.split('WebKit/')[1])||void 0),has.add('chrome',parseFloat(dua.split('Chrome/')[1])||void 0),has.add('safari',0<=dav.indexOf('Safari')&&!has('chrome')?parseFloat(dav.split('Version/')[1]):void 0),has.add('mac',0<=dav.indexOf('Macintosh')),has.add('quirks','BackCompat'==document.compatMode),dua.match(/(iPhone|iPod|iPad)/)){var p=RegExp.$1.replace(/P/,'p'),v=dua.match(/OS ([\d_]+)/)?RegExp.$1:'1',os=parseFloat(v.replace(/_/,'.').replace(/_/g,''));has.add(p,os),has.add('ios',os)}if(has.add('android',parseFloat(dua.split('Android ')[1])||void 0),has.add('bb',(0<=dua.indexOf('BlackBerry')||0<=dua.indexOf('BB10'))&&parseFloat(dua.split('Version/')[1])||void 0),has.add('svg','undefined'!=typeof SVGAngle),!has('webkit')){if(0<=dua.indexOf('Opera')&&has.add('opera',9.8<=tv?parseFloat(dua.split('Version/')[1])||tv:tv),!(0<=dua.indexOf('Gecko'))||has('khtml')||has('webkit')||has.add('mozilla',tv),has('mozilla')&&has.add('ff',parseFloat(dua.split('Firefox/')[1]||dua.split('Minefield/')[1])||void 0),document.all&&!has('opera')){var isIE=parseFloat(dav.split('MSIE ')[1])||void 0,mode=document.documentMode;mode&&5!=mode&&Math.floor(isIE)!=mode&&(isIE=mode),has.add('ie',isIE)}has.add('wii','undefined'!=typeof opera&&opera.wiiremote)}}return has}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[exports,__webpack_require__(5),__webpack_require__(10),__webpack_require__(17),__webpack_require__(8),__webpack_require__(20)],__WEBPACK_AMD_DEFINE_RESULT__=function(exports,dojo,has,win,dom,attr){function _insertBefore(node,ref){var parent=ref.parentNode;parent&&parent.insertBefore(node,ref)}function _insertAfter(node,ref){var parent=ref.parentNode;parent&&(parent.lastChild==ref?parent.appendChild(node):parent.insertBefore(node,ref.nextSibling))}function _empty(node){if(node.canHaveChildren)try{return void(node.innerHTML='')}catch(e){}for(var c;c=node.lastChild;)_destroy(c,node)}function _destroy(node,parent){node.firstChild&&_empty(node),parent&&(has('ie')&&parent.canHaveChildren&&'removeNode'in node?node.removeNode(!1):parent.removeChild(node))}var tagWrap={option:['select'],tbody:['table'],thead:['table'],tfoot:['table'],tr:['table','tbody'],td:['table','tbody','tr'],th:['table','thead','tr'],legend:['fieldset'],caption:['table'],colgroup:['table'],col:['table','colgroup'],li:['ul']},reTag=/<\s*([\w\:]+)/,masterNode={},masterNum=0,masterName='__'+dojo._scopeName+'ToDomId';for(var param in tagWrap)if(tagWrap.hasOwnProperty(param)){var tw=tagWrap[param];
1tw.pre='option'==param?'<select multiple="multiple">':'<'+tw.join('><')+'>',tw.post='</'+tw.reverse().join('></')+'>'}var html5domfix;8>=has('ie')&&(html5domfix=function(doc){doc.__dojo_html5_tested='yes';var div=create('div',{innerHTML:'<nav>a</nav>',style:{visibility:'hidden'}},doc.body);1!==div.childNodes.length&&'abbr article aside audio canvas details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.replace(/\b\w+\b/g,function(n){doc.createElement(n)}),destroy(div)}),exports.toDom=function(frag,doc){doc=doc||win.doc;var masterId=doc[masterName];masterId||(doc[masterName]=masterId=++masterNum+'',masterNode[masterId]=doc.createElement('div')),8>=has('ie')&&!doc.__dojo_html5_tested&&doc.body&&html5domfix(doc),frag+='';var match=frag.match(reTag),tag=match?match[1].toLowerCase():'',master=masterNode[masterId],wrap,i,fc,df;if(match&&tagWrap[tag])for(wrap=tagWrap[tag],master.innerHTML=wrap.pre+frag+wrap.post,i=wrap.length;i;--i)master=master.firstChild;else master.innerHTML=frag;if(1==master.childNodes.length)return master.removeChild(master.firstChild);for(df=doc.createDocumentFragment();fc=master.firstChild;)df.appendChild(fc);return df},exports.place=function(node,refNode,position){if(refNode=dom.byId(refNode),'string'==typeof node&&(node=/^\s*</.test(node)?exports.toDom(node,refNode.ownerDocument):dom.byId(node)),'number'==typeof position){var cn=refNode.childNodes;!cn.length||cn.length<=position?refNode.appendChild(node):_insertBefore(node,cn[0>position?0:position])}else switch(position){case'before':_insertBefore(node,refNode);break;case'after':_insertAfter(node,refNode);break;case'replace':refNode.parentNode.replaceChild(node,refNode);break;case'only':exports.empty(refNode),refNode.appendChild(node);break;case'first':if(refNode.firstChild){_insertBefore(node,refNode.firstChild);break}default:refNode.appendChild(node);}return node};var create=exports.create=function(tag,attrs,refNode,pos){var doc=win.doc||window.document;return refNode&&(refNode=dom.byId(refNode),doc=refNode.ownerDocument),'string'==typeof tag&&(tag=doc.createElement(tag)),attrs&&attr.set(tag,attrs),refNode&&exports.place(tag,refNode,pos),tag};exports.empty=function(node){_empty(dom.byId(node))};var destroy=exports.destroy=function(node){node=dom.byId(node);node&&_destroy(node,node.parentNode)}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on){var module=declare([],{INTERNAL_REQUEST_API_FUNCTIONS:{'get-vast-instream':'_onApiRequestGetVastInstream'},constructor:function(config,target){void 0,this.config=config,this.target=target},emit:function(eventName,data,targetNode){targetNode&&this.config.playerId!=targetNode.id||(void 0,on.emit(this.target,eventName,{data:data,bubbles:!0,cancelable:!0}))}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(36),__webpack_require__(3)],__WEBPACK_AMD_DEFINE_RESULT__=function(aspect,on){'use strict';function Evented(){}var after=aspect.after;return Evented.prototype={on:function(type,listener){return on.parse(this,type,listener,function(target,type){return after(target,'on'+type,listener,!0)})},emit:function(){var args=[this];return args.push.apply(args,arguments),on.emit.apply(on,args)}},Evented}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){function platformExists(platformId){var platformIds=_.keys(ENDPOINT_MAP);return platformId!=void 0&&-1<platformIds.indexOf(platformId)}var _=__webpack_require__(7),LocationHelper=__webpack_require__(24),PROTOCOL=LocationHelper.getProtocol(),ENDPOINT_MAP={prod01:{liveStream:'playerservices.streamtheworld.com/api/livestream',nowPlayingHistory:PROTOCOL+'//np.tritondigital.com/public/nowplaying',playerWebAdmin:PROTOCOL+'//pwav4.tritondigital.com/jsonconfig.php',coreModuleDir:PROTOCOL+'//sdk.listenlive.co/core/swf/',npe:PROTOCOL+'//npe2.listenlive.co/services/',see:PROTOCOL+'//see-p-elb-01.tritondigital.net/widget/{tenantId}/see.js',UA:'G-QQRTXPJ64L'},preprod01:{liveStream:'playerservices.preprod01.streamtheworld.net/api/livestream',nowPlayingHistory:PROTOCOL+'//playerservices.preprod01.streamtheworld.net/public/nowplaying',playerWebAdmin:PROTOCOL+'//pwav4.preprod01.tritondigital.com/jsonconfig.php',coreModuleDir:PROTOCOL+'//sdk.listenlive.co/core/swf/',npe:PROTOCOL+'//nowplaying.preprod01.streamtheworld.net/services/',see:PROTOCOL+'//see-stg-slb.tritondigital.net/widget/{tenantId}/see.js',UA:'G-QQRTXPJ64L'}},Platform=window.TdPlatform=function(platformId){var existingPlatform=platformExists(platformId)?platformId:'prod01';this.endpoint=ENDPOINT_MAP[existingPlatform]};module.exports=Platform},function(module,exports,__webpack_require__){var lodash=__webpack_require__(7),XmlToJSON=__webpack_require__(116);module.exports={parse:function(data){var parser,xmlDoc;return window.DOMParser?(parser=new DOMParser,xmlDoc=parser.parseFromString(data,'text/xml')):(xmlDoc=new ActiveXObject('Microsoft.XMLDOM'),xmlDoc.async=!1,xmlDoc.loadXML(data)),xmlDoc},textContent:function(node){var _result='';
1return node&&lodash.forEach(node.childNodes,function(child){switch(child.nodeType){case 3:case 2:case 4:_result+=child.nodeValue;}}),_result},xmlToJson:function(xml){return XmlToJSON.parseXML(xml,{mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!1,namespaceKey:'_ns',textKey:'_text',valueKey:'_value',attrKey:'_attr',cdataKey:'_cdata',attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1})}}},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(26),__webpack_require__(29),__webpack_require__(28),__webpack_require__(4),__webpack_require__(2),__webpack_require__(96)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,NewDeferred,Promise,CancelError,has,lang,when){var mutator=function(){},freeze=Object.freeze||function(){},Deferred=dojo.Deferred=function(canceller){function complete(value){if(finished)throw new Error('This deferred has already been resolved');result=value,finished=!0,notify()}function notify(){for(var mutated,listener;!mutated&&nextListener;){listener=nextListener,nextListener=nextListener.next,(mutated=listener.progress==mutator)&&(finished=!1);var func=isError?listener.error:listener.resolved;if(has('config-useDeferredInstrumentation')&&isError&&NewDeferred.instrumentRejected&&NewDeferred.instrumentRejected(result,!!func),func)try{var newResult=func(result);if(newResult&&'function'==typeof newResult.then){newResult.then(lang.hitch(listener.deferred,'resolve'),lang.hitch(listener.deferred,'reject'),lang.hitch(listener.deferred,'progress'));continue}var unchanged=mutated&&void 0===newResult;mutated&&!unchanged&&(isError=newResult instanceof Error),listener.deferred[unchanged&&isError?'reject':'resolve'](unchanged?result:newResult)}catch(e){listener.deferred.reject(e)}else isError?listener.deferred.reject(result):listener.deferred.resolve(result)}}var promise=this.promise=new Promise,result,finished,canceled,fired,isError,head,nextListener;this.isResolved=promise.isResolved=function(){return 0==fired},this.isRejected=promise.isRejected=function(){return 1==fired},this.isFulfilled=promise.isFulfilled=function(){return 0<=fired},this.isCanceled=promise.isCanceled=function(){return canceled},this.resolve=this.callback=function(value){this.fired=fired=0,this.results=[value,null],complete(value)},this.reject=this.errback=function(error){isError=!0,this.fired=fired=1,has('config-useDeferredInstrumentation')&&NewDeferred.instrumentRejected&&NewDeferred.instrumentRejected(error,!!nextListener),complete(error),this.results=[null,error]},this.progress=function(update){for(var listener=nextListener,progress;listener;)progress=listener.progress,progress&&progress(update),listener=listener.next},this.addCallbacks=function(callback,errback){return this.then(callback,errback,mutator),this},promise.then=this.then=function(resolvedCallback,errorCallback,progressCallback){var returnDeferred=progressCallback==mutator?this:new Deferred(promise.cancel),listener={resolved:resolvedCallback,error:errorCallback,progress:progressCallback,deferred:returnDeferred};return nextListener?head=head.next=listener:nextListener=head=listener,finished&¬ify(),returnDeferred.promise};var deferred=this;promise.cancel=this.cancel=function(){if(!finished){var error=canceller&&canceller(deferred);finished||(!(error instanceof Error)&&(error=new CancelError(error)),error.log=!1,deferred.reject(error))}canceled=!0},freeze(promise)};return lang.extend(Deferred,{addCallback:function(){return this.addCallbacks(lang.hitch.apply(dojo,arguments))},addErrback:function(){return this.addCallbacks(null,lang.hitch.apply(dojo,arguments))},addBoth:function(){var enclosed=lang.hitch.apply(dojo,arguments);return this.addCallbacks(enclosed,enclosed)},fired:-1}),Deferred.when=dojo.when=when,Deferred}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(2),__webpack_require__(10)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,lang,has){var ret={global:dojo.global,doc:this.document||null,body:function(doc){return doc=doc||dojo.doc,doc.body||doc.getElementsByTagName('body')[0]},setContext:function(globalObject,globalDocument){dojo.global=ret.global=globalObject,dojo.doc=ret.doc=globalDocument},withGlobal:function(globalObject,callback,thisObject,cbArguments){var oldGlob=dojo.global;try{return dojo.global=ret.global=globalObject,ret.withDoc.call(null,globalObject.document,callback,thisObject,cbArguments)}finally{dojo.global=ret.global=oldGlob}},withDoc:function(documentObject,callback,thisObject,cbArguments){var oldDoc=ret.doc,oldQ=has('quirks'),oldIE=has('ie'),isIE,mode,pwin;try{return dojo.doc=ret.doc=documentObject,dojo.isQuirks=has.add('quirks','BackCompat'==dojo.doc.compatMode,!0,!0),has('ie')&&(pwin=documentObject.parentWindow)&&pwin.navigator&&(isIE=parseFloat(pwin.navigator.appVersion.split('MSIE ')[1])||void 0,mode=documentObject.documentMode,mode&&5!=mode&&Math.floor(isIE)!=mode&&(isIE=mode),dojo.isIE=has.add('ie',isIE,!0,!0)),thisObject&&'string'==typeof callback&&(callback=thisObject[callback]),callback.apply(thisObject,cbArguments||[])}finally{dojo.doc=ret.doc=oldDoc,dojo.isQuirks=has.add('quirks',oldQ,!0,!0),dojo.isIE=has.add('ie',oldIE,!0,!0)}}};return has('extend-dojo')&&lang.mixin(dojo,ret),ret}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(13)],__WEBPACK_AMD_DEFINE_RESULT__=function(Evented){var hub=new Evented;return{publish:function(){return hub.emit.apply(hub,arguments)},subscribe:function(){return hub.on.apply(hub,arguments)}}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var _=__webpack_require__(7);window.lodash=_.noConflict();var I18n=function(){if('object'==typeof I18n.instance)return I18n.instance;var locale='en',localeSupported=['en','fr','pt','es'],scripts=document.getElementsByTagName('script');if(!_.isEmpty(scripts)){var tdsdkLang=scripts[scripts.length-1].getAttribute('tdsdk-lang');_.isEmpty(tdsdkLang)||(locale=tdsdkLang)}this.setLocalization=function(lang){locale=lang},this.getLocalization=function(){return-1<_.indexOf(localeSupported,locale)?__webpack_require__(118)('./'+locale+'.json'):__webpack_require__(60)},I18n.instance=this};module.exports=new I18n},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[exports,__webpack_require__(10),__webpack_require__(2),__webpack_require__(8),__webpack_require__(27),__webpack_require__(86)],__WEBPACK_AMD_DEFINE_RESULT__=function(exports,has,lang,dom,style,prop){function _hasAttr(node,name){var attr=node.getAttributeNode&&node.getAttributeNode(name);return attr&&attr.specified}var forcePropNames={innerHTML:1,className:1,htmlFor:has('ie'),value:1},attrNames={classname:'class',htmlfor:'for',tabindex:'tabIndex',readonly:'readOnly'};exports.has=function(node,name){var lc=name.toLowerCase();return forcePropNames[prop.names[lc]||name]||_hasAttr(dom.byId(node),attrNames[lc]||name)},exports.get=function(node,name){node=dom.byId(node);var lc=name.toLowerCase(),propName=prop.names[lc]||name,forceProp=forcePropNames[propName],value=node[propName];if(forceProp&&'undefined'!=typeof value)return value;if('href'!=propName&&('boolean'==typeof value||lang.isFunction(value)))return value;var attrName=attrNames[lc]||name;return _hasAttr(node,attrName)?node.getAttribute(attrName):null},exports.set=function(node,name,value){if(node=dom.byId(node),2==arguments.length){for(var x in name)exports.set(node,x,name[x]);return node}var lc=name.toLowerCase(),propName=prop.names[lc]||name,forceProp=forcePropNames[propName];return'style'==propName&&'string'!=typeof value?(style.set(node,value),node):forceProp||'boolean'==typeof value||lang.isFunction(value)?prop.set(node,name,value):(node.setAttribute(attrNames[lc]||name,value),node)},exports.remove=function(node,name){dom.byId(node).removeAttribute(attrNames[name.toLowerCase()]||name)},exports.getNodeProp=function(node,name){node=dom.byId(node);var lc=name.toLowerCase(),propName=prop.names[lc]||name;if(propName in node&&'href'!=propName)return node[propName];var attrName=attrNames[lc]||name;return _hasAttr(node,attrName)?node.getAttribute(attrName):null}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_RESULT__;(function(module,global){(function(){'use strict';function capitalize(string){return string+='',string.charAt(0).toUpperCase()+string.slice(1)}function cleanupOS(os,pattern,label){var data={'10.0':'10','6.4':'10 Technical Preview','6.3':'8.1','6.2':'8','6.1':'Server 2008 R2 / 7','6.0':'Server 2008 / Vista','5.2':'Server 2003 / XP 64-bit','5.1':'XP','5.01':'2000 SP1','5.0':'2000','4.0':'NT','4.90':'ME'};
1return pattern&&label&&/^Win/i.test(os)&&!/^Windows Phone /i.test(os)&&(data=data[/[\d.]+$/.exec(os)])&&(os='Windows '+data),os+='',pattern&&label&&(os=os.replace(RegExp(pattern,'i'),label)),os=format(os.replace(/ ce$/i,' CE').replace(/\bhpw/i,'web').replace(/\bMacintosh\b/,'Mac OS').replace(/_PowerPC\b/i,' OS').replace(/\b(OS X) [^ \d]+/i,'$1').replace(/\bMac (OS X)\b/,'$1').replace(/\/(\d)/,' $1').replace(/_/g,'.').replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,'').replace(/\bx86\.64\b/gi,'x86_64').replace(/\b(Windows Phone) OS\b/,'$1').replace(/\b(Chrome OS \w+) [\d.]+\b/,'$1').split(' on ')[0]),os}function each(object,callback){var index=-1,length=object?object.length:0;if('number'==typeof length&&-1<length&&length<=maxSafeInteger)for(;++index<length;)callback(object[index],index,object);else forOwn(object,callback)}function format(string){return string=trim(string),/^(?:webOS|i(?:OS|P))/.test(string)?string:capitalize(string)}function forOwn(object,callback){for(var key in object)hasOwnProperty.call(object,key)&&callback(object[key],key,object)}function getClassOf(value){return null==value?capitalize(value):toString.call(value).slice(8,-1)}function isHostType(object,property){var type=null==object?'number':typeof object[property];return!/^(?:boolean|number|string|undefined)$/.test(type)&&('object'!=type||!!object[property])}function qualify(string){return(string+'').replace(/([ -])(?!$)/g,'$1?')}function reduce(array,callback){var accumulator=null;return each(array,function(value,index){accumulator=callback(accumulator,value,index,array)}),accumulator}function trim(string){return(string+'').replace(/^ +| +$/g,'')}function parse(ua){function getProduct(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);return!result&&(result=RegExp('\\b'+pattern+' *\\d+[.\\w_]*','i').exec(ua)||RegExp('\\b'+pattern+' *\\w+-[\\w]*','i').exec(ua)||RegExp('\\b'+pattern+'(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)','i').exec(ua))&&((result=((guess.label&&!RegExp(pattern,'i').test(guess.label)?guess.label:result)+'').split('/'))[1]&&!/[\d.]+/.test(result[0])&&(result[0]+=' '+result[1]),guess=guess.label||guess,result=format(result[0].replace(RegExp(pattern,'i'),guess).replace(RegExp('; *(?:'+guess+'[_-])?','i'),' ').replace(RegExp('('+guess+')[-_.]?(\\w)','i'),'$1 $2'))),result})}function getVersion(patterns){return reduce(patterns,function(result,pattern){return result||(RegExp(pattern+'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)','i').exec(ua)||0)[1]||null})}var context=root,isCustomContext=ua&&'object'==typeof ua&&'String'!=getClassOf(ua);isCustomContext&&(context=ua,ua=null);var nav=context.navigator||{},userAgent=nav.userAgent||'';ua||(ua=userAgent);var likeChrome=isCustomContext?!!nav.likeChrome:/\bChrome\b/.test(ua)&&!/internal|\n/i.test(toString.toString()),objectClass='Object',airRuntimeClass=isCustomContext?objectClass:'ScriptBridgingProxyObject',enviroClass=isCustomContext?objectClass:'Environment',javaClass=isCustomContext&&context.java?'JavaPackage':getClassOf(context.java),phantomClass=isCustomContext?objectClass:'RuntimeObject',java=/\bJava/.test(javaClass)&&context.java,rhino=java&&getClassOf(context.environment)==enviroClass,alpha=java?'a':'\u03B1',beta=java?'b':'\u03B2',doc=context.document||{},opera=context.operamini||context.opera,operaClass=reOpera.test(operaClass=isCustomContext&&opera?opera['[[Class]]']:getClassOf(opera))?operaClass:opera=null,arch=ua,description=[],prerelease=null,useFeatures=ua==userAgent,version=useFeatures&&opera&&'function'==typeof opera.version&&opera.version(),layout=function(guesses){return reduce(guesses,function(result,guess){return result||RegExp('\\b'+(guess.pattern||qualify(guess))+'\\b','i').exec(ua)&&(guess.label||guess)})}([{'label':'EdgeHTML','pattern':'Edge'},'Trident',{'label':'WebKit','pattern':'AppleWebKit'},'iCab','Presto','NetFront','Tasman','KHTML','Gecko']),name=function(guesses){return reduce(guesses,function(result,guess){return result||RegExp('\\b'+(guess.pattern||qualify(guess))+'\\b','i').exec(ua)&&(guess.label||guess)})}(['Adobe AIR','Arora','Avant Browser','Breach','Camino','Electron','Epiphany','Fennec','Flock','Galeon','GreenBrowser','iCab','Iceweasel','K-Meleon','Konqueror','Lunascape','Ma
1xthon',{'label':'Microsoft Edge','pattern':'(?:Edge|Edg|EdgA|EdgiOS)'},'Midori','Nook Browser','PaleMoon','PhantomJS','Raven','Rekonq','RockMelt',{'label':'Samsung Internet','pattern':'SamsungBrowser'},'SeaMonkey',{'label':'Silk','pattern':'(?:Cloud9|Silk-Accelerated)'},'Sleipnir','SlimBrowser',{'label':'SRWare Iron','pattern':'Iron'},'Sunrise','Swiftfox','Vivaldi','Waterfox','WebPositive',{'label':'Yandex Browser','pattern':'YaBrowser'},{'label':'UC Browser','pattern':'UCBrowser'},'Opera Mini',{'label':'Opera Mini','pattern':'OPiOS'},'Opera',{'label':'Opera','pattern':'OPR'},'Chromium','Chrome',{'label':'Chrome','pattern':'(?:HeadlessChrome)'},{'label':'Chrome Mobile','pattern':'(?:CriOS|CrMo)'},{'label':'Firefox','pattern':'(?:Firefox|Minefield)'},{'label':'Firefox for iOS','pattern':'FxiOS'},{'label':'IE','pattern':'IEMobile'},{'label':'IE','pattern':'MSIE'},'Safari']),product=getProduct([{'label':'BlackBerry','pattern':'BB10'},'BlackBerry',{'label':'Galaxy S','pattern':'GT-I9000'},{'label':'Galaxy S2','pattern':'GT-I9100'},{'label':'Galaxy S3','pattern':'GT-I9300'},{'label':'Galaxy S4','pattern':'GT-I9500'},{'label':'Galaxy S5','pattern':'SM-G900'},{'label':'Galaxy S6','pattern':'SM-G920'},{'label':'Galaxy S6 Edge','pattern':'SM-G925'},{'label':'Galaxy S7','pattern':'SM-G930'},{'label':'Galaxy S7 Edge','pattern':'SM-G935'},'Google TV','Lumia','iPad','iPod','iPhone','Kindle',{'label':'Kindle Fire','pattern':'(?:Cloud9|Silk-Accelerated)'},'Nexus','Nook','PlayBook','PlayStation Vita','PlayStation','TouchPad','Transformer',{'label':'Wii U','pattern':'WiiU'},'Wii','Xbox One',{'label':'Xbox 360','pattern':'Xbox'},'Xoom']),manufacturer=function(guesses){return reduce(guesses,function(result,value,key){return result||(value[product]||value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)]||RegExp('\\b'+qualify(key)+'(?:\\b|\\w*\\d)','i').exec(ua))&&key})}({'Apple':{'iPad':1,'iPhone':1,'iPod':1},'Alcatel':{},'Archos':{},'Amazon':{'Kindle':1,'Kindle Fire':1},'Asus':{'Transformer':1},'Barnes & Noble':{'Nook':1},'BlackBerry':{'PlayBook':1},'Google':{'Google TV':1,'Nexus':1},'HP':{'TouchPad':1},'HTC':{},'Huawei':{},'Lenovo':{},'LG':{},'Microsoft':{'Xbox':1,'Xbox One':1},'Motorola':{'Xoom':1},'Nintendo':{'Wii U':1,'Wii':1},'Nokia':{'Lumia':1},'Oppo':{},'Samsung':{'Galaxy S':1,'Galaxy S2':1,'Galaxy S3':1,'Galaxy S4':1},'Sony':{'PlayStation':1,'PlayStation Vita':1},'Xiaomi':{'Mi':1,'Redmi':1}}),os=function(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);return!result&&(result=RegExp('\\b'+pattern+'(?:/[\\d.]+|[ \\w.]*)','i').exec(ua))&&(result=cleanupOS(result,pattern,guess.label||guess)),result})}(['Windows Phone','KaiOS','Android','CentOS',{'label':'Chrome OS','pattern':'CrOS'},'Debian',{'label':'DragonFly BSD','pattern':'DragonFly'},'Fedora','FreeBSD','Gentoo','Haiku','Kubuntu','Linux Mint','OpenBSD','Red Hat','SuSE','Ubuntu','Xubuntu','Cygwin','Symbian OS','hpwOS','webOS ','webOS','Tablet OS','Tizen','Linux','Mac OS X','Macintosh','Mac','Windows 98;','Windows ']),data,isSpecialCasedOS;
vendor: 4,872 bytes, line 1
1if(layout&&(layout=[layout]),/\bAndroid\b/.test(os)&&!product&&(data=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(ua))&&(product=trim(data[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,'')||null),manufacturer&&!product?product=getProduct([manufacturer]):manufacturer&&product&&(product=product.replace(RegExp('^('+qualify(manufacturer)+')[-_.\\s]','i'),manufacturer+' ').replace(RegExp('^('+qualify(manufacturer)+')[-_.]?(\\w)','i'),manufacturer+' $2')),(data=/\bGoogle TV\b/.exec(product))&&(product=data[0]),/\bSimulator\b/i.test(ua)&&(product=(product?product+' ':'')+'Simulator'),'Opera Mini'==name&&/\bOPiOS\b/.test(ua)&&description.push('running in Turbo/Uncompressed mode'),'IE'==name&&/\blike iPhone OS\b/.test(ua)?(data=parse(ua.replace(/like iPhone OS/,'')),manufacturer=data.manufacturer,product=data.product):/^iP/.test(product)?(name||(name='Safari'),os='iOS'+((data=/ OS ([\d_]+)/i.exec(ua))?' '+data[1].replace(/_/g,'.'):'')):'Konqueror'==name&&/^Linux\b/i.test(os)?os='Kubuntu':manufacturer&&'Google'!=manufacturer&&(/Chrome/.test(name)&&!/\bMobile Safari\b/i.test(ua)||/\bVita\b/.test(product))||/\bAndroid\b/.test(os)&&/^Chrome/.test(name)&&/\bVersion\//i.test(ua)?(name='Android Browser',os=/\bAndroid\b/.test(os)?os:'Android'):'Silk'==name?(!/\bMobi/i.test(ua)&&(os='Android',description.unshift('desktop mode')),/Accelerated *= *true/i.test(ua)&&description.unshift('accelerated')):'UC Browser'==name&&/\bUCWEB\b/.test(ua)?description.push('speed mode'):'PaleMoon'==name&&(data=/\bFirefox\/([\d.]+)\b/.exec(ua))?description.push('identifying as Firefox '+data[1]):'Firefox'==name&&(data=/\b(Mobile|Tablet|TV)\b/i.exec(ua))?(os||(os='Firefox OS'),product||(product=data[1])):!name||(data=!/\bMinefield\b/i.test(ua)&&/\b(?:Firefox|Safari)\b/.exec(name))?(name&&!product&&/[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data+'/')+8))&&(name=null),(data=product||manufacturer||os)&&(product||manufacturer||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))&&(name=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os)?os:data)+' Browser')):'Electron'==name&&(data=(/\bChrome\/([\d.]+)\b/.exec(ua)||0)[1])&&description.push('Chromium '+data),version||(version=getVersion(['(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)','Version',qualify(name),'(?:Firefox|Minefield|NetFront)'])),(data='iCab'==layout&&3<parseFloat(version)&&'WebKit'||/\bOpera\b/.test(name)&&(/\bOPR\b/.test(ua)?'Blink':'Presto')||/\b(?:Midori|Nook|Safari)\b/i.test(ua)&&!/^(?:Trident|EdgeHTML)$/.test(layout)&&'WebKit'||!layout&&/\bMSIE\b/i.test(ua)&&('Mac OS'==os?'Tasman':'Trident')||'WebKit'==layout&&/\bPlayStation\b(?! Vita\b)/i.test(name)&&'NetFront')&&(layout=[data]),'IE'==name&&(data=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua)||0)[1])?(name+=' Mobile',os='Windows Phone '+(/\+$/.test(data)?data:data+'.x'),description.unshift('desktop mode')):/\bWPDesktop\b/i.test(ua)?(name='IE Mobile',os='Windows Phone 8.x',description.unshift('desktop mode'),version||(version=(/\brv:([\d.]+)/.exec(ua)||0)[1])):'IE'!=name&&'Trident'==layout&&(data=/\brv:([\d.]+)/.exec(ua))&&(name&&description.push('identifying as '+name+(version?' '+version:'')),name='IE',version=data[1]),useFeatures){if(!isHostType(context,'global'))getClassOf(data=context.runtime)==airRuntimeClass?(name='Adobe AIR',os=data.flash.system.Capabilities.os):getClassOf(data=context.phantom)==phantomClass?(name='PhantomJS',version=(data=data.version||null)&&data.major+'.'+data.minor+'.'+data.patch):'number'==typeof doc.documentMode&&(data=/\bTrident\/(\d+)/i.exec(ua))?(version=[version,doc.documentMode],(data=+data[1]+4)!=version[1]&&(description.push('IE '+version[1]+' mode'),layout&&(layout[1]=''),version[1]=data),version='IE'==name?version[1].toFixed(1)+'':version[0]):'number'==typeof doc.documentMode&&/^(?:Chrome|Firefox)\b/.test(name)&&(description.push('masking as '+name+' '+version),name='IE',version='11.0',layout=['Trident'],os='Windows');else if(java&&(data=java.lang.System,arch=data.getProperty('os.arch'),os=os||data.getProperty('os.name')+' '+data.getProperty('os.version')),rhino){try{version=context.require('ringo/engine').version.join('.'),name='RingoJS'}catch(e){(data=context.system)&&data.global.system==context.system&&(name='Narwhal',os||(os=data[0].os||null))}name||(name='Rhino')}else'object'==typeof context.process&&!context.process.browser&&(data=context.process)&&('object'==typeof data.versions&&('string'==typeof data.versions.electron?(description.push('Node '+data.versions.node),name='Electron',version=data.versions.electron):'string'==typeof data.versions.nw&&(description.push('Chromium '+version,'Node '+data.versions.node),name='NW.js',version=data.versions.nw)),name||(name='Node.js',arch=data.arch,os=data.platform,version=/[\d.]+/.exec(data.version),version=version?ver
1sion[0]:null));os=os&&format(os)}if(version&&(data=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version)||/(?:alpha|beta)(?: ?\d)?/i.exec(ua+';'+(useFeatures&&nav.appMinorVersion))||/\bMinefield\b/i.test(ua)&&'a')&&(prerelease=/b/i.test(data)?'beta':'alpha',version=version.replace(RegExp(data+'\\+?$'),'')+('beta'==prerelease?beta:alpha)+(/\d+\+?/.exec(data)||'')),'Fennec'==name||'Firefox'==name&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(os))name='Firefox Mobile';else if('Maxthon'==name&&version)version=version.replace(/\.[\d.]+/,'.x');else if(/\bXbox\b/i.test(product))'Xbox 360'==product&&(os=null),'Xbox 360'==product&&/\bIEMobile\b/.test(ua)&&description.unshift('mobile mode');else if((/^(?:Chrome|IE|Opera)$/.test(name)||name&&!product&&!/Browser|Mobi/.test(name))&&('Windows CE'==os||/Mobi/i.test(ua)))name+=' Mobile';else if('IE'==name&&useFeatures)try{null===context.external&&description.unshift('platform preview')}catch(e){description.unshift('embedded')}else(/\bBlackBerry\b/.test(product)||/\bBB10\b/.test(ua))&&(data=(RegExp(product.replace(/ +/g,' *')+'/([.\\d]+)','i').exec(ua)||0)[1]||version)?(data=[data,/BB10/.test(ua)],os=(data[1]?(product=null,manufacturer='BlackBerry'):'Device Software')+' '+data[0],version=null):this!=forOwn&&'Wii'!=product&&(useFeatures&&opera||/Opera/.test(name)&&/\b(?:MSIE|Firefox)\b/i.test(ua)||'Firefox'==name&&/\bOS X (?:\d+\.){2,}/.test(os)||'IE'==name&&(os&&!/^Win/.test(os)&&5.5<version||/\bWindows XP\b/.test(os)&&8<version||8==version&&!/\bTrident\b/.test(ua)))&&!reOpera.test(data=parse.call(forOwn,ua.replace(reOpera,'')+';'))&&data.name&&(data='ing as '+data.name+((data=data.version)?' '+data:''),reOpera.test(name)?(/\bIE\b/.test(data)&&'Mac OS'==os&&(os=null),data='identify'+data):(data='mask'+data,name=operaClass?format(operaClass.replace(/([a-z])([A-Z])/g,'$1 $2')):'Opera',/\bIE\b/.test(data)&&(os=null),!useFeatures&&(version=null)),layout=['Presto'],description.push(data));(data=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua)||0)[1])&&(data=[parseFloat(data.replace(/\.(\d)$/,'.0$1')),data],'Safari'==name&&'+'==data[1].slice(-1)?(name='WebKit Nightly',prerelease='alpha',version=data[1].slice(0,-1)):(version==data[1]||version==(data[2]=(/\bSafari\/([\d.]+\+?)/i.exec(ua)||0)[1]))&&(version=null),data[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(ua)||0)[1],537.36==data[0]&&537.36==data[2]&&28<=parseFloat(data[1])&&'WebKit'==layout&&(layout=['Blink']),useFeatures&&(likeChrome||data[1])?(layout&&(layout[1]='like Chrome'),data=data[1]||(data=data[0],530>data?1:532>data?2:532.05>data?3:533>data?4:534.03>data?5:534.07>data?6:534.1>data?7:534.13>data?8:534.16>data?9:534.24>data?10:534.3>data?11:535.01>data?12:535.02>data?'13+':535.07>data?15:535.11>data?16:535.19>data?17:536.05>data?18:536.1>data?19:537.01>data?20:537.11>data?'21+':537.13>data?23:537.18>data?24:537.24>data?25:537.36>data?26:'Blink'==layout?'28':'27')):(layout&&(layout[1]='like Safari'),data=(data=data[0],400>data?1:500>data?2:526>data?3:533>data?4:534>data?'4+':535>data?5:537>data?6:538>data?7:601>data?8:602>data?9:604>data?10:606>data?11:608>data?12:'12')),layout&&(layout[1]+=' '+(data+='number'==typeof data?'.x':/[.+]/.test(data)?'':'+')),'Safari'==name&&(!version||45<parseInt(version))?version=data:'Chrome'==name&&/\bHeadlessChrome/i.test(ua)&&description.unshift('headless')),'Opera'==name&&(data=/\bzbov|zvav$/.exec(os))?(name+=' ',description.unshift('desktop mode'),'zvav'==data?(name+='Mini',version=null):name+='Mobile',os=os.replace(RegExp(' *'+data+'$'),'')):'Safari'==name&&/\bChrome\b/.exec(layout&&layout[1])?(description.unshift('desktop mode'),name='Chrome Mobile',version=null,/\bOS X\b/.test(os)?(manufacturer='Apple',os='iOS 4.3+'):os=null):/\bSRWare Iron\b/.test(name)&&!version&&(version=getVersion('Chrome')),version&&0==version.indexOf(data=/[\d.]+$/.exec(os))&&-1<ua.indexOf('/'+data+'-')&&(os=trim(os.replace(data,''))),os&&-1!=os.indexOf(name)&&!RegExp(name+' OS').test(os)&&(os=os.replace(RegExp(' *'+qualify(name)+' *'),'')),layout&&!/\b(?:Avant|Nook)\b/.test(name)&&(/Browser|Lunascape|Maxthon/.test(name)||'Safari'!=name&&/^iOS/.test(os)&&/\bSafari\b/.test(layout[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(name)&&layout[1])&&(data=layout[layout.length-1])&&description.push(data),description.length&&(description=['('+description.join('; ')+')']),manufacturer&&product&&0>product.indexOf(manufacturer)&&description.push('on '+manufacturer),product&&description.push((/^on /.test(description[description.length-1])?'':'on ')+product),os&&(data=/ ([\d.+]+)$/.exec(os),isSpecialCasedOS=data&&'/'==os.charAt(os.length-data[0].length-1),os={'architecture':32,'family':data&&!isSpecialCasedOS?os.replace(data[0],''):os,'version':data?data[1]:null,'toString':function(){var version=this.version;return this.family+(version&&!isSpecialCasedOS?' '+version:'')+(64==this.architecture?' 64-bit':'')}}),(data=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch))&&!/\bi686\b/i.test(arch)?(os&&(os.architecture=64,os.family=os.family.replace(RegExp(' *'+data),'')),name&&(/\bWOW64\b/i.test(ua)||useFeatures&&/\w(?:86|32)$/.test(nav.cpuClass||nav.platform)&&!/\bW
1in64; x64\b/i.test(ua))&&description.unshift('32-bit')):os&&/^OS X/.test(os.family)&&'Chrome'==name&&39<=parseFloat(version)&&(os.architecture=64),ua||(ua=null);var platform={};return platform.description=ua,platform.layout=layout&&layout[0],platform.manufacturer=manufacturer,platform.name=name,platform.prerelease=prerelease,platform.product=product,platform.ua=ua,platform.version=name&&version,platform.os=os||{'architecture':null,'family':null,'version':null,'toString':function(){return'null'}},platform.parse=parse,platform.toString=function(){return this.description||''},platform.version&&description.unshift(version),platform.name&&description.unshift(name),os&&name&&!(os==(os+'').split(' ')[0]&&(os==name.split(' ')[0]||product))&&description.push(product?'('+os+')':'on '+os),description.length&&(platform.description=description.join(' ')),platform}var objectTypes={'function':!0,'object':!0},root=objectTypes[typeof window]&&window||this,oldRoot=root,freeExports=objectTypes[typeof exports]&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&'object'==typeof global&&global;freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)&&(root=freeGlobal);var maxSafeInteger=Math.pow(2,53)-1,reOpera=/\bOpera/,thisBinding=this,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,toString=objectProto.toString,platform=parse();root.platform=platform,__WEBPACK_AMD_DEFINE_RESULT__=function(){return platform}.call(exports,__webpack_require__,exports,module),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}).call(this)}).call(exports,__webpack_require__(31)(module),function(){return this}())},function(module){module.exports={ABORT:'abort',CAN_PLAY:'canPlay',CAN_PLAY_THROUGH:'canPlayThrough',DATA_LOADING:'dataLoading',EMPTIED:'emptied',ENDED:'ended',ERROR:'error',LOAD_START:'loadStart',PAUSE:'pause',PLAY:'play',PROGRESS:'progress',STALLED:'stalled',STOP:'stop',SUSPEND:'suspend',TIME_UPDATE:'timeupdate',WAITING:'waiting',PLAY_NOT_ALLOWED:'playbackNotAllowed',GEOBLOCKED:'geoblocked'}},function(module,exports,__webpack_require__){var _=__webpack_require__(7);module.exports={toSafeArray:function(value){return value?_.isArray(value)?value:[value]:[]}}},function(module){module.exports={currentProtocolIsHttps:function(){return window.location.protocol==='https:'},getProtocol:function(){return window.location.protocol}}},function(module,exports,__webpack_require__){function _onLoadedData(){fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||this.emit('html5-playback-status',{type:PlaybackState.DATA_LOADING,mediaNode:this.audioNode})}function _onLoadStart(){fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||this.emit('html5-playback-status',{type:PlaybackState.LOAD_START,mediaNode:this.audioNode})}function _onCanPlay(){var context=this;if(this.timeshiftEnabled){var context=this;'Safari'===OsPlatform.name&&setTimeout(()=>{context.emit('timeshift-info',{programStartTime:context.audioNode.getStartDate().getTime()})},1e3)}fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||null!==this.url&&('IE'===OsPlatform.name&&'11.0'===OsPlatform.version&&7<=parseInt(OsPlatform.os.version)?this.audioNode.play():(context.emit('html5-playback-status',{type:PlaybackState.CAN_PLAY,mediaNode:context.audioNode}),this.audioNode.play().then(function(){}).catch(function(e){context.handleHTMLPlayError(e)}),-1<this.url.indexOf('CLOUD/HLS/program')&&null!=this.timeshiftOffset&&0<=this.timeshiftOffset&&!this.hls&&(this.seekStream(this.timeshiftOffset),this.timeshiftOffset=null)))}function _onCanPlayThrough(){var context=this;fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||null!==this.url&&('IE'===OsPlatform.name&&'11.0'===OsPlatform.version&&7<=parseInt(OsPlatform.os.version)?this.audioNode.play():this.audioNode.play().then(function(){context.emit('html5-playback-status',{type:PlaybackState.CAN_PLAY_THROUGH,mediaNode:context.audioNode})}).catch(function(e){context.handleHTMLPlayError(e)}))}function _onWaiting(){fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||this.emit
1('html5-playback-status',{type:PlaybackState.WAITING,mediaNode:this.audioNode})}function _onEmptied(){fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||this.emit('html5-playback-status',{type:PlaybackState.EMPTIED,mediaNode:this.audioNode})}function _onAbort(){fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED)||this.emit('html5-playback-status',{type:PlaybackState.ABORT,mediaNode:this.audioNode})}function _onEnded(){fsm.is(STATE.STOPPED)||this.emit('html5-playback-status',{type:PlaybackState.ENDED,mediaNode:this.audioNode})}function _onPlay(){null!==this.url&&this.emit('html5-playback-status',{type:PlaybackState.PLAY,mediaNode:this.audioNode})}function _onPause(){fsm.is(STATE.STOPPED)?this.emit('html5-playback-status',{type:PlaybackState.STOP,mediaNode:this.audioNode}):this.emit('html5-playback-status',{type:PlaybackState.PAUSE,mediaNode:this.audioNode})}function _onError(event){let errorMessage='',errorCode=null;event&&event.currentTarget&&event.currentTarget.error&&(errorMessage=event.currentTarget.error.message,errorCode=event.currentTarget.error.code);var audioNode=this.audioNode;fsm.is(STATE.STOPPED)?this.emit('html5-playback-status',{type:PlaybackState.STOP,mediaNode:audioNode}):3==audioNode.readyState?this.emit('html5-playback-status',{type:PlaybackState.STOP,mediaNode:audioNode}):(this.resetAudioNode(),this.emit('html5-playback-status',{type:PlaybackState.ERROR,mediaNode:audioNode,message:errorMessage,code:errorCode}))}function _onOffline(){void 0,'Safari'===OsPlatform.name&&this.stop()}function _onTimeUpdate(){if(!(fsm.is(STATE.STOPPED)||fsm.is(STATE.PAUSED))&&(this.audioNode.currentTime.toFixed(1)==this.audioNode.duration.toFixed(1)?this.emit('html5-playback-status',{type:PlaybackState.ENDED,mediaNode:this.audioNode}):!this.isLive&&this.emit('html5-playback-status',{type:PlaybackState.TIME_UPDATE,mediaNode:this.audioNode}),this.timeshiftEnabled&&!this.hls))if(0==timeupdateCounter){timeupdateCounter++;let startSeconds=parseInt(new Date().getTime()/1e3)-parseInt(this.audioNode.getStartDate().getTime()/1e3)-this.audioNode.currentTime;let c=parseInt(new Date().getTime())-1e3*startSeconds;this.emit('timeshift-info',{currentTime:c,programStartTime:this.audioNode.getStartDate().getTime(),totalduration:parseInt(new Date().getTime()/1e3)-parseInt(this.audioNode.getStartDate().getTime()/1e3)})}else timeupdateCounter++,40<timeupdateCounter&&(timeupdateCounter=0)}function attachEvents(){this.boundOnOffline=_onOffline.bind(this),this.audioNode.addEventListener('loadeddata',_onLoadedData.bind(this)),this.audioNode.addEventListener('loadstart',_onLoadStart.bind(this)),this.audioNode.addEventListener('canplay',_onCanPlay.bind(this)),this.audioNode.addEventListener('canplaythrough',_onCanPlayThrough.bind(this)),this.audioNode.addEventListener('waiting',_onWaiting.bind(this)),this.audioNode.addEventListener('emptied',_onEmptied.bind(this)),this.audioNode.addEventListener('abort',_onAbort.bind(this)),this.audioNode.addEventListener('ended',_onEnded.bind(this)),this.audioNode.addEventListener('play',_onPlay.bind(this)),this.audioNode.addEventListener('pause',_onPause.bind(this)),this.audioNode.addEventListener('timeupdate',_onTimeUpdate.bind(this)),this.audioNode.addEventListener('error',_onError.bind(this)),window.addEventListener('offline',this.boundOnOffline)}function removeEvents(){this.audioNode&&(this.audioNode.removeEventListener('loadeddata',_onLoadedData),this.audioNode.removeEventListener('loadstart',_onLoadStart),this.audioNode.removeEventListener('canplay',_onCanPlay),this.audioNode.removeEventListener('canplaythrough',_onCanPlayThrough),this.audioNode.removeEventListener('waiting',_onWaiting),this.audioNode.removeEventListener('emptied',_onEmptied),this.audioNode.removeEventListener('abort',_onAbort),this.audioNode.removeEventListener('ended',_onEnded),this.audioNode.removeEventListener('play',_onPlay),this.audioNode.removeEventListener('pause',_onPause),this.audioNode.removeEventListener('timeupdate',_onTimeUpdate),this.audioNode.removeEventListener('error',_onError),window.removeEventListener('offline',this.boundOnOffline))}function getAudioNode(){return this.audioNode||(this.audioNode=new Audio,this.audioNode.autoplay=!1,this.audioNode.preload='none',0!=localStorage.getItem('currentVolume')&&void 0!=localStorage.getItem('currentVolume')&&(this.audioNode.volume=localStorage.getItem('currentVolume')),attachEvents.call(this)),this.audioNode}var _=__webpack_require__(7),EventEmitter=__webpack_require__(97).EventEmitter,Hls=__webpack_require__(40),PlaybackState=__webpack_require__(22),StateMachine=__webpack_require__(98),OsPlatform=__webpack_require__(21),stwLSID=null,timeupdateCounter=0,STATE={IDLE:'IDLE',PLAYING:'PLAYING',STOPPED:'STOPPED',PAUSED:'PAUSED'},fsm=StateMachine.create({initial:STATE.STOPPED,error:function(){},events:[{name:'play',from:STATE.STOPPED,to:STATE.PLAYING},{name:'play',from:STATE.PLAYING,to:STATE.PLAYING},{name:'stop',from:STATE.PLAYING,to:STATE.STOPPED},{name:'stop',from:STATE.PAUSED,to:STATE.STOPPED},{name:'pause',from:STATE.PLAYING,to:STATE.PAUSED},{name:'resume',from:STATE.PAUSED,to:STATE.PLAYING}]});module.exports=_.assign(new EventEmitter,{audioNode:null,init:function(){this;this.audioNode=getAudioNode.call(this),this.url=null,this.audioNode.src=null},playAudio:function(url,useHlsLibrary,isLive,timeshiftOffset,timeshiftEnabled){if(this.timeshiftEnabled=timeshiftEnabled,this.audioNode&&this.stop(),this.audioNode=getAudioNode.call(this),this.url=url||this.url,stwLSID&&(this.url.includes('?')?this.url=this.url+'&lsid='+stwLSID:this.url=this.url+'?lsid='+stwLSID),this.isLive=isLive||this.isLive,this.useHlsLibrary=useHlsLibrary||this.useHlsLibrary,this.timeshiftOffset=void 0==timeshiftOffset?-1:timeshiftOffset,useHlsLibrary){this.hls=new Hls({'maxBufferLength':30,'autoStartLoad':!1}),this.hls.config.xhrSetup=function(xhr){xhr.onload=function(){let headers=xhr.getAllResponseHeaders();headers&&0<headers.indexOf('x-stw-lsid')&&(xhr.getResponseHeader('x-stw-lsid')&&(stwLSID=xhr.getResponseHeader('x-stw-lsid')),void 0)}},timeshiftEnabled&&(this.hls.on(Hls.Events.LEVEL_LOADED,this.levelsLoaded.bind(this)),this.hls.on(Hls.Events.FRAG_CHANGED,this.hlsFragChanged.bind(this))),this.hls.on(Hls.Events.ERROR,this.hlsError.bind(this)),this.hls.on(Hls.Events.MEDIA_ATTA
1CHED,this.hlsMediaAttached.bind(this)),this.hls.on(Hls.Events.MANIFEST_PARSED,this.hlsManifestParsed.bind(this)),this.hls.loadSource(this.url),this.hls.attachMedia(this.audioNode)}else this.audioNode.src=this.url,this.audioNode.load();fsm.play()},hlsMediaAttached:function(){},hlsFragChanged:function(id,data){this.emit('timeshift-info',{currentTime:data.frag.programDateTime})},levelsLoaded:function(event,data){this.emit('timeshift-info',{totalduration:data.details.totalduration,programStartTime:data.details.fragments[0].programDateTime})},hlsManifestParsed:function(){void 0,this.hls.startLoad(this.timeshiftOffset)},hlsError:function(event,data){453===data.response.code&&this.emit('html5-playback-status',{type:PlaybackState.GEOBLOCKED,mediaNode:this.audioNode}),data.fatal&&(void 0,this.stop())},stop:function(){var context=this;fsm.is(STATE.STOPPED)||(this.audioNode=getAudioNode.call(this),fsm.stop(),this.audioNode.pause(),'Safari'!==OsPlatform.name||-1<this.audioNode.src.indexOf('m3u8')||this.useHlsLibrary?setTimeout(function(){context.audioNode.src=null,context.url=null,context.resetAudioNode()},300):setTimeout(function(){context.url=null,context.resetAudioNode()},300),'iOS'===OsPlatform.os.family&&'Chrome Mobile'===OsPlatform.name&&window.stop(),this.useHlsLibrary&&(this.hls.off(Hls.Events.MEDIA_ATTACHED,this.hlsMediaAttached.bind(this)),this.hls.off(Hls.Events.LEVEL_LOADED,this.levelsLoaded.bind(this)),this.hls.off(Hls.Events.MANIFEST_PARSED,this.hlsManifestParsed.bind(this)),this.hls.off(Hls.Events.ERROR,this.hlsError.bind(this)),this.hls.off(Hls.Events.FRAG_CHANGED,this.hlsFragChanged.bind(this)),this.hls.stopLoad(),this.hls.detachMedia(),this.hls.destroy(),this.emit('html5-playback-status',{type:PlaybackState.STOP,mediaNode:this.audioNode})))},seekFromLive:function(seconds){this.hls?this.seekFromLiveWithLibrary(seconds):this.seekFromLiveNative(seconds)},seekFromLiveNative:function(seconds){let startSeconds=parseInt(new Date().getTime()/1e3)-parseInt(this.audioNode.getStartDate().getTime()/1e3);void 0,this.audioNode.currentTime=0<=seconds?startSeconds-seconds:startSeconds+seconds},seekFromLiveWithLibrary:function(seconds){this.audioNode.currentTime=0<=seconds?this.hls.liveSyncPosition-seconds:this.hls.liveSyncPosition+seconds},seekLive:function(){this.audioNode.currentTime=this.hls?this.hls.liveSyncPosition:0},pause:function(){fsm.is(STATE.PAUSED)||(this.audioNode=getAudioNode.call(this),this.audioNode.pause(),fsm.pause())},resume:function(){var context=this;fsm.is(STATE.PAUSED)&&(this.audioNode=getAudioNode.call(this),'IE'===OsPlatform.name&&'11.0'===OsPlatform.version&&7<=parseInt(OsPlatform.os.version)?this.audioNode.play():this.audioNode.play().catch(function(e){context.handleHTMLPlayError(e)}),fsm.resume())},mute:function(){fsm.is(STATE.PLAYING)&&(this.audioNode=getAudioNode.call(this),this.cfg&&this.cfg.streamWhileMuted?this.audioNode.muted=!0:this.stop())},unMute:function(){fsm.is(STATE.PLAYING)||(this.audioNode=getAudioNode.call(this))},setVolume:function(volume){this.audioNode=getAudioNode.call(this),localStorage.setItem('currentVolume',volume),this.audioNode.volume=volume,0==volume?this.mute():this.audioNode.muted=!1},isStopped:function(){return fsm.is(STATE.STOPPED)},resetAudioNode:function(){removeEvents.call(this),this.audioNode&&(this.audioNode.src=null,this.audioNode=null),fsm.can('stop')&&fsm.stop()},destroyAudioElement:function(){this.emit('destroyAudioElement')},handleHTMLPlayError:function(e){var context=this;'NotSupportedError'!==e.name&&'NotAllowedError'===e.name&&this.emit('html5-playback-status',{type:PlaybackState.PLAY_NOT_ALLOWED,mediaNode:context.audioNode})},seekStream:function(seconds){0===seconds?this.audioNode.currentTime=seconds:this.audioNode.currentTime+=seconds}})},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4),__webpack_require__(2),__webpack_require__(28),__webpack_require__(29),__webpack_require__(59)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,lang,CancelError,Promise,instrumentation){'use strict';var PROGRESS=0,RESOLVED=1,REJECTED=2,FULFILLED_ERROR_MESSAGE='This deferred has already been fulfilled.',freezeObject=Object.freeze||function(){},signalWaiting=function(waiting,type,result,rejection,deferred){has('config-deferredInstrumentation')&&type===REJECTED&&Deferred.instrumentRejected&&0===waiting.length&&Deferred.instrumentRejected(result,!1,rejection,deferred);for(var i=0;i<waiting.length;i++)signalListener(waiting[i],type,result,rejection)},signalListener=function(listener,type,result,rejection){var func=listener[type],deferred=listener.deferred;if(func)try{var newResult=func(result);if(type===PROGRESS)'undefined'!=typeof newResult&&signalDeferred(deferred,type,newResult);else{if(newResult&&'function'==typeof newResult.then)return listener.cancel=ne
1wResult.cancel,void newResult.then(makeDeferredSignaler(deferred,RESOLVED),makeDeferredSignaler(deferred,REJECTED),makeDeferredSignaler(deferred,PROGRESS));signalDeferred(deferred,RESOLVED,newResult)}}catch(error){signalDeferred(deferred,REJECTED,error)}else signalDeferred(deferred,type,result);has('config-deferredInstrumentation')&&type===REJECTED&&Deferred.instrumentRejected&&Deferred.instrumentRejected(result,!!func,rejection,deferred.promise)},makeDeferredSignaler=function(deferred,type){return function(value){signalDeferred(deferred,type,value)}},signalDeferred=function(deferred,type,result){deferred.isCanceled()||(type===PROGRESS?deferred.progress(result):type===RESOLVED?deferred.resolve(result):type===REJECTED?deferred.reject(result):void 0)},Deferred=function(canceler){var promise=this.promise=new Promise,deferred=this,canceled=!1,waiting=[],fulfilled,result,rejection;has('config-deferredInstrumentation')&&Error.captureStackTrace&&(Error.captureStackTrace(deferred,Deferred),Error.captureStackTrace(promise,Deferred)),this.isResolved=promise.isResolved=function(){return fulfilled===RESOLVED},this.isRejected=promise.isRejected=function(){return fulfilled===REJECTED},this.isFulfilled=promise.isFulfilled=function(){return!!fulfilled},this.isCanceled=promise.isCanceled=function(){return canceled},this.progress=function(update,strict){if(!fulfilled)return signalWaiting(waiting,PROGRESS,update,null,deferred),promise;if(!0===strict)throw new Error(FULFILLED_ERROR_MESSAGE);else return promise},this.resolve=function(value,strict){if(!fulfilled)return signalWaiting(waiting,fulfilled=RESOLVED,result=value,null,deferred),waiting=null,promise;if(!0===strict)throw new Error(FULFILLED_ERROR_MESSAGE);else return promise};var reject=this.reject=function(error,strict){if(!fulfilled)return has('config-deferredInstrumentation')&&Error.captureStackTrace&&Error.captureStackTrace(rejection={},reject),signalWaiting(waiting,fulfilled=REJECTED,result=error,rejection,deferred),waiting=null,promise;if(!0===strict)throw new Error(FULFILLED_ERROR_MESSAGE);else return promise};this.then=promise.then=function(callback,errback,progback){var listener=[progback,callback,errback];return listener.cancel=promise.cancel,listener.deferred=new Deferred(function(reason){return listener.cancel&&listener.cancel(reason)}),fulfilled&&!waiting?signalListener(listener,fulfilled,result,rejection):waiting.push(listener),listener.deferred.promise},this.cancel=promise.cancel=function(reason,strict){if(!fulfilled){if(canceler){var returnedReason=canceler(reason);reason='undefined'==typeof returnedReason?reason:returnedReason}if(canceled=!0,!fulfilled)return'undefined'==typeof reason&&(reason=new CancelError),reject(reason),reason;if(fulfilled===REJECTED&&result===reason)return reason}else if(!0===strict)throw new Error(FULFILLED_ERROR_MESSAGE)},freezeObject(promise)};return Deferred.prototype.toString=function(){return'[object Deferred]'},instrumentation&&instrumentation(Deferred),Deferred}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(10),__webpack_require__(8)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,dom){function _toStyleValue(node,type,value){if(type=type.toLowerCase(),has('ie')){if('auto'==value){if('height'==type)return node.offsetHeight;if('width'==type)return node.offsetWidth}if('fontweight'==type)switch(value){case 700:return'bold';case 400:default:return'normal';}}return type in _pixelNamesCache||(_pixelNamesCache[type]=_pixelRegExp.test(type)),_pixelNamesCache[type]?toPixel(node,value):value}var style={},getComputedStyle;getComputedStyle=has('webkit')?function(node){var s;if(1==node.nodeType){var dv=node.ownerDocument.defaultView;s=dv.getComputedStyle(node,null),!s&&node.style&&(node.style.display='',s=dv.getComputedStyle(node,null))}return s||{}}:has('ie')&&(9>has('ie')||has('quirks'))?function(node){return 1==node.nodeType&&node.currentStyle?node.currentStyle:{}}:function(node){return 1==node.nodeType?node.ownerDocument.defaultView.getComputedStyle(node,null):{}},style.getComputedStyle=getComputedStyle;var toPixel;toPixel=has('ie')?function(element,avalue){if(!avalue)return 0;if('medium'==avalue)return 4;if(avalue.slice&&'px'==avalue.slice(-2))return parseFloat(avalue);var s=element.style,rs=element.runtimeStyle,cs=element.currentStyle,sLeft=s.left,rsLeft=rs.left;rs.left=cs.left;try{s.left=avalue,avalue=s.pixelLeft}catch(e){avalue=0}return s.left=sLeft,rs.left=rsLeft,avalue}:function(element,value){return parseFloat(value)||0},style.toPixelValue=toPixel;var astr='DXImageTransform.Microsoft.Alpha',af=function(n,f){try{return n.filters.item(astr)}catch(e){return f?{}:null}},_getOpacity=9>has('ie')||10>has('ie')&&has('quirks')?function(node){try{return af(node).Opacity/100}catch(e){return 1}}:function(node){return getComputedStyle(node).opacity},_setOpacity=9>has('ie')||10>has('ie')&&has('quirks')?function(node,opacity){''===opacity&&(opacity=1);var ov=100*opacity,fullyOpaque=1===opacity;if(fullyOpaque?(node.style.zoom='',af(node)&&(node.style.filter=node.style.filter.replace(/\s*progid:DXImageTransform.Microsoft.Alpha\([^\)]+?\)/i,''))):(node.style.zoom=1,af(node)?af(node,1).Opacity=ov:node.style.filter+=' progid:'+astr+'(Opacity='+ov+')',af(node,1).Enabled=!0),'tr'==node.tagName.toLowerCase())for(var td=node.firstChild;td;td=td.nextSibling)'td'==td.tagName.toLowerCase()&&_setOpacity(td,opacity);return opacity}:function(node,opacity){return node.style.opacity=opacity},_pixelNamesCache={left:!0,top:!0},_pixelRegExp=/margin|padding|width|height|max|min|offset/,_floatAliases={cssFloat:1,styleFloat:1,float:1};return style.get=function(node,name){var n=dom.byId(node),l=arguments.length,op='opacity'==name;if(2==l&&op)return _getOpacity(n);name=_floatAliases[name]?'cssFloat'in n.style?'cssFloat':'styleFloat':name;var s=style.getComputedStyle(n);return 1==l?s:_toStyleValue(n,name,s[name]||n.style[name])},style.set=function(node,name,value){var n=dom.byId(node),l=arguments.length,op='opacity'==name;if(name=_floatAliases[name]?'cssFloat'in n.style?'cssFloat':'styleFloat':name,3==l)return op?_setOpacity(n,value):n.style[name]=value;for(var x in name)style.set(node,x,name[x]);return style.getComputedStyle(n)},style}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(38)],__WEBPACK_AMD_DEFINE_RESULT__=function(create){return create('CancelError',null,null,{dojoType:'cancel'})}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(2)],__WEBPACK_AMD_DEFINE_RESULT__=function(lang){'use strict';function throwAbstract(){throw new TypeError('abstract')}return lang.extend(function(){},{then:function(){throwAbstract()},cancel:function(){throwAbstract()},isResolved:function(){throwAbstract()},isRejected:function(){throwAbstract()},isFulfilled:function(){throwAbstract()},isCanceled:function(){throwAbstract()},always:function(callbackOrErrback){return this.then(callbackOrErrback,callbackOrErrback)},otherwise:function(errback){return this.then(null,errback)},trace:function(){return this},traceRejected:function(){return this},toString:function(){return'[object Promise]'}})}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){function dojoRequire(module,cb){if(module instanceof Array){var res=module.map(function(m){return dojoRequire(m)});cb&&cb.apply(this,res)}else if(registered_modules[module])return registered_modules[module]}var registered_modules={};dojoRequire.async=!0,dojoRequire.toUrl=function(url){return url},dojoRequire.register=function(module_name,module){return registered_modules[module_name]=module,module},dojoRequire.unregister=function(module_name){delete registered_modules[module_name]},module.exports=dojoRequire},function(module){module.exports=function(module){return module.webpackPolyfill||(module.deprecate=function(){},module.paths=[],module.children=[],module.webpackPolyfill=1),module}},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return{VAST_AD:'vastAd',MEDIA_AD:'mediaAd',ANDO_RUN_SPOT:'andoRunSpot',TRITON_AD_PLATFORM:'tap'}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return{AD_ID:'adId',AD_TYPE:'adType',CUE_TITLE:'cueTitle',CUE_TIME_DURATION:'cueTimeDuration',AD_URL:'adUrl',AD_VAST_URL:'adVastURL',AD_VAST:'adVast'}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var Const=__webpack_require__(43),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(6),__webpack_require__(26),__webpack_require__(117)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,array,deferred,GARequest){function _validateObject(object,key,val
1idValue){if(lang.isArray(validValue)){var valid=!1;return array.forEach(validValue,function(item){_validateValidValue(object,key,item)&&(valid=!0)}),valid}return _validateValidValue(object,key,validValue)}function _validateValidValue(object,key,validValue){return!!(_validateNotEmptyValue(object,key)&&object[key].toString()==validValue.toString())}function _validateNotEmptyValue(object,key){return!!(object.hasOwnProperty(key)&&null!=object[key]&&''!=object[key].toString()&&void 0!==object[key])}var GAEventRequest=declare([GARequest],{CATEGORY_INIT:'Init',CATEGORY_STREAMING:'Streaming',CATEGORY_AD:'Ad',CATEGORY_ON_DEMAND:'On Demand',CATEGORY_LISTENER:'Listener',CATEGORY_DEFAULT:'Default',ACTION_CONFIG:'Config',ACTION_CONNECTION:'Connection',ACTION_PREROLL:'Preroll',ACTION_PLAY:'Play',ACTION_STOP:'Stop',ACTION_PAUSE:'Pause',ACTION_RESUME:'Resume',ACTION_TRACKING:'Tracking',ACTION_MUTE:'Mute',ACTION_UNMUTE:'Unmute',ACTION_ALL:'All',LABEL_SUCCESS:'Success',LABEL_ERROR:'Error',LABEL_STREAM_ERROR:'Stream Error',LABEL_UNAVAILABLE:'Unavailable',LABEL_TRACK:'Track',LABEL_CUSTOM:'Custom',LABEL_SPEECH:'Speech',LABEL_BREAK:'Break',LABEL_END_BREAK:'End Break',LABEL_SMART:'Smart',LABEL_DUMB:'Dumb',constructor:function(){this.inherited(arguments),this.broadcasters=[]},shouldRequest:function(action){return!!this.active&&!!(this.trackingEvents&&0<this.trackingEvents.length&&this.trackingEvents.includes(action.toUpperCase()))},requestGA:function(category,action,label,dimensions,metrics){if(this.shouldRequest(action)){var self=this,data={hitType:'event',eventCategory:category,eventAction:action,eventLabel:label};if(lang.mixin(data,dimensions),lang.mixin(data,metrics),!this.validate(data,category,action,label));else if(!(data[this.DIM_STATION]||data[this.DIM_MOUNT]))this.request(data);else if(this.broadcasters[data[this.DIM_MOUNT]]){var tmpObj={};tmpObj[this.DIM_BROADCASTER]=this.broadcasters[data[this.DIM_MOUNT]],lang.mixin(data,tmpObj),this.request(data)}else this._getBroadcaster(data[this.DIM_MOUNT]).then(function(broadcaster){self.broadcasters[data[self.DIM_MOUNT]]=broadcaster;var tmpObj={};tmpObj[self.DIM_BROADCASTER]=broadcaster,lang.mixin(data,tmpObj),self.request(data)},function(){self.request(data)})}},_getBroadcaster:function(){var def=new deferred;return def.reject(),def.promise},validate:function(object,category,action,label){var valid=!1;if(this.validateType(object))switch(category){case this.CATEGORY_INIT:valid=this.validateInitConfig(object);break;case this.CATEGORY_STREAMING:action===this.ACTION_CONNECTION?valid=!!this.validateStreamingConnection(object)&&(label===this.LABEL_SUCCESS?this.validateStreamingConnectionSuccess(object):label!==this.LABEL_STREAM_ERROR||this.validateStreamingConnectionStreamError(object)):action===this.ACTION_PLAY?valid=!0:void 0;break;case this.CATEGORY_AD:switch(action){case this.ACTION_PREROLL:if(this.validateAdPreroll(object))valid=!0;else return!1;}break;case this.CATEGORY_ON_DEMAND:valid=this.validateOnDemand(object);break;case this.CATEGORY_LISTENER:valid=this.validateListener(object);break;case this.CATEGORY_DEFAULT:valid=!0;}return valid},validateType:function(object){return!!_validateObject(object,this.TYPE,'event')},validateInitConfig:function(object){return!!_validateObject(object,this.CATEGORY,'Init')&&!!_validateObject(object,this.ACTION,'Config')&&!!_validateObject(object,this.LABEL,['Success','Error'])&&!!_validateObject(object,this.DIM_TECH,['Flash','Html5'])&&!!_validateObject(object,this.DIM_ADBLOCK,['true','false'])&&!!_validateObject(object,this.DIM_SBM,['true','false'])&&!!_validateObject(object,this.DIM_HLS,['true','false'])&&!!_validateObject(object,this.DIM_AUDIO_ADAPTIVE,['true','false'])&&!!_validateObject(object,this.DIM_IDSYNC,['true','false'])&&!!_validateNotEmptyValue(object,this.METRIC_LOAD_TIME)},validateStreamingConnectionSuccess:function(object){return!!_validateObject(object,this.DIM_MEDIA_TYPE,[Const.AUDIO,Const.VIDEO])&&!!_validateObject(object,this.DIM_HLS,['true','false'])&&!!_validateObject(object,this.DIM_AUDIO_ADAPTIVE,['true','false'])&&!!_validateNotEmptyValue(object,this.METRIC_CONNECTION_TIME)},validateStreamingConnectionStreamError:function(object){return!!_validateObject(object,this.DIM_MEDIA_FORMAT,['AAC','MP3','FLV'])&&!!_validateObject(object,this.DIM_HLS,['true','false'])&&!!_validateObject(object,this.DIM_AUDIO_ADAPTIVE,['true','false'])&&!!_validateNotEmptyValue(object,this.METRIC_STREAM_ERROR_TIME)},validateStreamingConnection:function(object){return!!_validateObject(object,this.CATEGORY,'Streaming')&&!!_validateObject(object,this.ACTION,'Connection')&&!!_validateObject(object,this.LABEL,['Success','Unavailable','Stream Error','Failed'])&&!!(_validateNotEmptyValue(object,this.DIM_MOUNT)||_val
1idateNotEmptyValue(object,this.DIM_STATION))},validateAdPreroll:function(object){return!!_validateObject(object,this.CATEGORY,'Ad')&&!!_validateObject(object,this.ACTION,'Preroll')&&!!_validateObject(object,this.LABEL,['Success','Error'])&&!!_validateObject(object,this.DIM_AD_SOURCE,['TAP','CM3','Others'])&&!!_validateObject(object,this.DIM_AD_FORMAT,['VAST','DAAST'])&&!!_validateObject(object,this.DIM_AD_PARSER,['IMA','VASTModule','Direct'])&&!!_validateNotEmptyValue(object,this.METRIC_CONNECTION_TIME)},validateOnDemand:function(object){return!!_validateObject(object,this.CATEGORY,'On Demand')&&!!_validateObject(object,this.ACTION,'Play')&&!!_validateObject(object,this.LABEL,['Success','Error'])},validateListener:function(object){return!!_validateObject(object,this.CATEGORY,'Listener')&&!!_validateObject(object,this.ACTION,'Tracking')&&!!_validateObject(object,this.LABEL,['Smart','Dumb'])&&!!(_validateNotEmptyValue(object,this.DIM_MOUNT)||_validateNotEmptyValue(object,this.DIM_STATION))}});return null==this.GAEventRequestInstance&&(this.GAEventRequestInstance=new GAEventRequest),this.GAEventRequestInstance}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var Platform=__webpack_require__(14),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(6),__webpack_require__(3),__webpack_require__(13)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,array,on,Evented){var Inpe=declare([Evented],{constructor:function(data,platformId){this.data=data,this.platformId=platformId,this.url=data.staticURL,this.id=data.id,this.listeners=[],this.platform=new Platform(platformId),this.alreadyFetched=!1},getStaticUrl:function(){return this.data.staticURL},getDynamicUrl:function(){return this.platform.endpoint.npe},getDynamicArtistUrl:function(id){return this.getDynamicUrl()+'artist/'+id},getDynamicAlbumUrl:function(id){return this.getDynamicUrl()+'album/'+id},getDynamicTrackUrl:function(id){return this.getDynamicUrl()+'track/'+id},getDynamicArtistPictureUrl:function(artistId,pictureId){return this.getDynamicUrl()+'artist/'+artistId+'/picture/'+pictureId},getDynamicAlbumPictureUrl:function(albumId,pictureId){return this.getDynamicUrl()+'album/'+albumId+'/picture/'+pictureId},notify:function(type,event){void 0,this.emit(type,event)},getRequestArgs:function(){return{handleAs:'json',preventCache:!1,headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}}},addEventListener:function(eventName,callback){var itemIndex=-1;array.forEach(this.listeners,function(item,index){item.eventName==eventName&&item.callback==callback&&(itemIndex=index)},this),-1==itemIndex&&this.listeners.push({eventName:eventName,callback:callback,listener:on(this,eventName,lang.hitch(this,callback))})},removeEventListener:function(eventName,callback){var itemIndex=-1;array.forEach(this.listeners,function(item,index){item.eventName==eventName&&item.callback==callback&&(itemIndex=index)},this),-1<itemIndex&&(this.listeners[itemIndex].listener.remove(),this.listeners.splice(itemIndex,1))}});return Inpe}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){'use strict';function advise(dispatcher,type,advice,receiveArguments){var previous=dispatcher[type],around='around'==type,signal;if(around){var advised=advice(function(){return previous.advice(this,arguments)});signal={remove:function(){advised&&(advised=dispatcher=advice=null)},advice:function(target,args){return advised?advised.apply(target,args):previous.advice(target,args)}}}else signal={remove:function(){if(signal.advice){var previous=signal.previous,next=signal.next;next||previous?(previous?previous.next=next:dispatcher[type]=next,next&&(next.previous=previous)):delete dispatcher[type],dispatcher=advice=signal.advice=null}},id:nextId++,advice:advice,receiveArguments:receiveArguments};
1if(!previous||around)dispatcher[type]=signal;else if('after'==type){for(;previous.next&&(previous=previous.next););previous.next=signal,signal.previous=previous}else'before'==type&&(dispatcher[type]=signal,signal.next=previous,previous.previous=signal);return signal}function aspect(type){return function(target,methodName,advice,receiveArguments){var existing=target[methodName],dispatcher;existing&&existing.target==target||(target[methodName]=dispatcher=function(){for(var executionId=nextId,args=arguments,before=dispatcher.before;before;)args=before.advice.apply(this,args)||args,before=before.next;if(dispatcher.around)var results=dispatcher.around.advice(this,args);for(var after=dispatcher.after;after&&after.id<executionId;){if(after.receiveArguments){var newResults=after.advice.apply(this,args);results=void 0===newResults?results:newResults}else results=after.advice.call(this,results,args);after=after.next}return results},existing&&(dispatcher.around={advice:function(target,args){return existing.apply(target,args)}}),dispatcher.target=target);var results=advise(dispatcher||existing,type,advice,receiveArguments);return advice=null,results}}var nextId=0,after=aspect('after'),before=aspect('before'),around=aspect('around');return{before:before,around:around,after:after}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(38)],__WEBPACK_AMD_DEFINE_RESULT__=function(create){return create('RequestError',function(message,response){this.response=response})}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(2)],__WEBPACK_AMD_DEFINE_RESULT__=function(lang){return function(name,ctor,base,props){base=base||Error;var ErrorCtor=function(message){if(base===Error){Error.captureStackTrace&&Error.captureStackTrace(this,ErrorCtor);var err=Error.call(this,message),prop;for(prop in err)err.hasOwnProperty(prop)&&(this[prop]=err[prop]);this.message=message,this.stack=err.stack}else base.apply(this,arguments);ctor&&ctor.apply(this,arguments)};return ErrorCtor.prototype=lang.delegate(base.prototype,props),ErrorCtor.prototype.name=name,ErrorCtor.prototype.constructor=ErrorCtor,ErrorCtor}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(57)],__WEBPACK_AMD_DEFINE_RESULT__=function(request){return request}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){(function __HLS_WORKER_BUNDLE__(__IN_WORKER__){(function(global,factory){module.exports=factory()})(this,function(){'use strict';function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)}return t}function _objectSpread2(e){for(var r=1,t;r<arguments.length;r++)t=null==arguments[r]?{}:arguments[r],r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))});return e}function _toPrimitive(t,r){if('object'!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||'default');if('object'!=typeof i)return i;throw new TypeError('@@toPrimitive must return a primitive value.')}return('string'===r?String:Number)(t)}function _toPropertyKey(t){var i=_toPrimitive(t,'string');return'symbol'==typeof i?i:i+''}function _defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,_toPropertyKey(descriptor.key),descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,'prototype',{writable:!1}
1),Constructor}function _defineProperty(obj,key,value){return key=_toPropertyKey(key),key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _extends(){return _extends=Object.assign?Object.assign.bind():function(target){for(var i=1,source;i<arguments.length;i++)for(var key in source=arguments[i],source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target},_extends.apply(this,arguments)}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,_setPrototypeOf(subClass,superClass)}function _getPrototypeOf(o){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)},_getPrototypeOf(o)}function _setPrototypeOf(o,p){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o,p){return o.__proto__=p,o},_setPrototypeOf(o,p)}function _isNativeReflectConstruct(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function _construct(){return _construct=_isNativeReflectConstruct()?Reflect.construct.bind():function(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a),instance=new Constructor;return Class&&_setPrototypeOf(instance,Class.prototype),instance},_construct.apply(null,arguments)}function _isNativeFunction(fn){try{return-1!==Function.toString.call(fn).indexOf('[native code]')}catch(e){return'function'==typeof fn}}function _wrapNativeSuper(Class){var _cache='function'==typeof Map?new Map:void 0;return _wrapNativeSuper=function(Class){function Wrapper(){return _construct(Class,arguments,_getPrototypeOf(this).constructor)}if(null===Class||!_isNativeFunction(Class))return Class;if('function'!=typeof Class)throw new TypeError('Super expression must either be null or a function');if('undefined'!=typeof _cache){if(_cache.has(Class))return _cache.get(Class);_cache.set(Class,Wrapper)}return Wrapper.prototype=Object.create(Class.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(Wrapper,Class)},_wrapNativeSuper(Class)}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return self}function _unsupportedIterableToArray(o,minLen){if(o){if('string'==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return'Object'===n&&o.constructor&&(n=o.constructor.name),'Map'===n||'Set'===n?Array.from(o):'Arguments'===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(o,minLen):void 0}}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _createForOfIteratorHelperLoose(o,allowArrayLike){var it='undefined'!=typeof Symbol&&o[Symbol.iterator]||o['@@iterator'];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&'number'==typeof o.length){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError('Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.')}function consolePrintFn(type){var func=self.console[type];return func?func.bind(self.console,'['+type+'] >'):noop}function exportLoggerFunctions(debugConfig){for(var _len=arguments.length,functions=Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)functions[_key-1]=arguments[_key];functions.forEach(function(type){exportedLogger[type]=debugConfig[type]?debugConfig[type].bind(debugConfig):consolePrintFn(type)})}function enableLogs(debugConfig,id){if('object'==typeof console&&!0===debugConfig||'object'==typeof debugConfig){exportLoggerFunctions(debugConfig,'debug','log','info','warn','error');try{exportedLogger.log('Debug logs enabled for "'+id+'" in hls.js ver
1sion 1.5.17')}catch(e){exportedLogger=fakeLogger}}else exportedLogger=fakeLogger}function isDateRangeCueAttribute(attrName){return'ID'!==attrName&&'CLASS'!==attrName&&'START-DATE'!==attrName&&'DURATION'!==attrName&&'END-DATE'!==attrName&&'END-ON-NEXT'!==attrName}function isSCTE35Attribute(attrName){return'SCTE35-OUT'===attrName||'SCTE35-IN'===attrName}function base64Decode(base64encodedStr){return Uint8Array.from(atob(base64encodedStr),function(c){return c.charCodeAt(0)})}function getKeyIdBytes(str){var keyIdbytes=strToUtf8array(str).subarray(0,16),paddedkeyIdbytes=new Uint8Array(16);return paddedkeyIdbytes.set(keyIdbytes,16-keyIdbytes.length),paddedkeyIdbytes}function changeEndianness(keyId){var swap=function(array,from,to){var cur=array[from];array[from]=array[to],array[to]=cur};swap(keyId,0,3),swap(keyId,1,2),swap(keyId,4,5),swap(keyId,6,7)}function convertDataUriToArrayBytes(uri){var colonsplit=uri.split(':'),keydata=null;if('data'===colonsplit[0]&&2===colonsplit.length){var semicolonsplit=colonsplit[1].split(';'),commasplit=semicolonsplit[semicolonsplit.length-1].split(',');if(2===commasplit.length){var isbase64='base64'===commasplit[0],data=commasplit[1];isbase64?(semicolonsplit.splice(-1,1),keydata=base64Decode(data)):keydata=getKeyIdBytes(data)}}return keydata}function strToUtf8array(str){return Uint8Array.from(unescape(encodeURIComponent(str)),function(c){return c.charCodeAt(0)})}function keySystemFormatToKeySystemDomain(format){return format===KeySystemFormats.FAIRPLAY?KeySystems.FAIRPLAY:format===KeySystemFormats.PLAYREADY?KeySystems.PLAYREADY:format===KeySystemFormats.WIDEVINE?KeySystems.WIDEVINE:format===KeySystemFormats.
1CLEARKEY?KeySystems.CLEARKEY:void 0}function keySystemIdToKeySystemDomain(systemId){return systemId===KeySystemIds.WIDEVINE?KeySystems.WIDEVINE:systemId===KeySystemIds.PLAYREADY?KeySystems.PLAYREADY:systemId===KeySystemIds.CENC||systemId===KeySystemIds.CLEARKEY?KeySystems.CLEARKEY:void 0}function keySystemDomainToKeySystemFormat(keySystem){return keySystem===KeySystems.FAIRPLAY?KeySystemFormats.FAIRPLAY:keySystem===KeySystems.PLAYREADY?KeySystemFormats.PLAYREADY:keySystem===KeySystems.WIDEVINE?KeySystemFormats.WIDEVINE:keySystem===KeySystems.CLEARKEY?KeySystemFormats.CLEARKEY:void 0}function getKeySystemsForConfig(config){var drmSystems=config.drmSystems,widevineLicenseUrl=config.widevineLicenseUrl,keySystemsToAttempt=drmSystems?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter(function(keySystem){return!!drmSystems[keySystem]}):[];return!keySystemsToAttempt[KeySystems.WIDEVINE]&&widevineLicenseUrl&&keySystemsToAttempt.push(KeySystems.WIDEVINE),keySystemsToAttempt}function getSupportedMediaKeySystemConfigurations(keySystem,audioCodecs,videoCodecs,drmSystemOptions){var initDataTypes;switch(keySystem){case KeySystems.FAIRPLAY:initDataTypes=['cenc','sinf'];break;case KeySystems.WIDEVINE:case KeySystems.PLAYREADY:initDataTypes=['cenc'];break;case KeySystems.CLEARKEY:initDataTypes=['cenc','keyids'];break;default:throw new Error('Unknown key-system: '+keySystem);}return createMediaKeySystemConfigurations(initDataTypes,audioCodecs,videoCodecs,drmSystemOptions)}function createMediaKeySystemConfigurations(initDataTypes,audioCodecs,videoCodecs,drmSystemOptions){var baseConfig={initDataTypes:initDataTypes,persistentState:drmSystemOptions.persistentState||'optional',distinctiveIdentifier:drmSystemOptions.distinctiveIdentifier||'optional',sessionTypes:drmSystemOptions.sessionTypes||[drmSystemOptions.sessionType||'temporary'],audioCapabilities:audioCodecs.map(function(codec){return{contentType:'audio/mp4; codecs="'+codec+'"',robustness:drmSystemOptions.audioRobustness||'',encryptionScheme:drmSystemOptions.audioEncryptionScheme||null}}),videoCapabilities:videoCodecs.map(function(codec){return{contentType:'video/mp4; codecs="'+codec+'"',robustness:drmSystemOptions.videoRobustness||'',encryptionScheme:drmSystemOptions.videoEncryptionScheme||null}})};return[baseConfig]}function sliceUint8(array,start,end){return Uint8Array.prototype.slice?array.slice(start,end):new Uint8Array(Array.prototype.slice.call(array,start,end))}function getTextDecoder(){if(!navigator.userAgent.includes('PlayStation 4'))return decoder||'undefined'==typeof self.TextDecoder||(decoder=new self.TextDecoder('utf-8')),decoder}function bin2str(data){return String.fromCharCode.apply(null,data)}function readUint16(buffer,offset){var val=buffer[offset]<<8|buffer[offset+1];return 0>val?65536+val:val}function readUint32(buffer,offset){var val=readSint32(buffer,offset);return 0>val?4294967296+val:val}function readUint64(buffer,offset){var result=readUint32(buffer,offset);return result*=Math.pow(2,32),result+=readUint32(buffer,offset+4),result}function readSint32(buffer,offset){return buffer[offset]<<24|buffer[offset+1]<<16|buffer[offset+2]<<8|buffer[offset+3]}function writeUint32(buffer,offset,value){buffer[offset]=value>>24,buffer[offset+1]=255&value>>16,buffer[offset+2]=255&value>>8,buffer[offset+3]=255&value}function hasMoofData(data){for(var end=data.byteLength,i=0,size;i<end;){if(size=readUint32(data,i),8<size&&109===data[i+4]&&111===data[i+5]&&111===data[i+6]&&102===data[i+7])return!0;i=1<size?i+size:end}return!1}function findBox(data,path){var results=[];if(!path.length)return results;for(var end=data.byteLength,i=0;i<end;){var size=readUint32(data,i),type=bin2str(data.subarray(i+4,i+8)),endbox=1<size?i+size:end;if(type===path[0])if(1===path.length)results.push(data.subarray(i+8,endbox));else{var subresults=findBox(data.subarray(i+8,endbox),path.slice(1));subresults.length&&push.apply(results,subresults)}i=endbox}return results}function parseSegmentIndex(sidx){var references=[],version=sidx[0],index=8,timescale=readUint32(sidx,index);index+=4;var earliestPresentationTime=0,firstOffset=0;0===version?(earliestPresentationTime=readUint32(sidx,index),firstOffset=readUint32(sidx,index+4),index+=8):(earliestPresentationTime=readUint64(sidx,index),firstOffset=readUint64(sidx,index+8),index+=16),index+=2;var startByte=sidx.length+firstOffset,referencesCount=readUint16(sidx,index);index+=2;for(var i=0;i<referencesCount;i++){var referenceIndex=index,referenceInfo=readUint32(sidx,referenceIndex);referenceIndex+=4;var referenceSize=2147483647&referenceInfo;if(1==(2147483648&referenceInfo)>>>31)return logger.warn('SIDX has hierarchical references (not supported)'),null;var subsegmentDuration=readUint32(sidx,referenceIndex);referenceIndex+=4,references.push({referenceSize:referenceSize,subsegmentDuration:subsegmentDuration,info:{duration:subsegmentDuration/timescale,start:startByte,end:startByte+referenceSize-1}}),startByte+=referenceSize,referenceIndex+=4,index=referenceIndex}return{earliestPresentationTime:earliestPresentationTime,timescale:timescale,version:version,referencesCount:referencesCount,references:references}}function parseInitSegment(initSegment){for(var result=[],traks=findBox(initSegment,['moov','trak']),i=0;i<traks.length;i++){var trak=traks[i],tkhd=findBox(trak,['tkhd'])[0];if(tkhd){var version=tkhd[0],trackId=readUint32(tkhd,0===version?12:20),mdhd=findBox(trak,['mdia','mdhd'])[0];if(mdhd){version=mdhd[0];var timescale=readUint32(mdhd,0===version?12:20),hdlr=findBox(trak,['mdia','hdlr'])[0];if(hdlr){var hdlrType=bin2str(hdlr.subarray(8,12)),type={soun:ElementaryStreamTypes.AUDIO,vide:ElementaryStreamTypes.VIDEO}[hdlrType];if(type){var stsd=findBox(trak,['mdia','minf','stbl','stsd'])[0],stsdData=parseStsd(stsd);result[trackId]={timescale:timescale,type:type}
1,result[type]=_objectSpread2({timescale:timescale,id:trackId},stsdData)}}}}}var trex=findBox(initSegment,['moov','mvex','trex']);return trex.forEach(function(trex){var trackId=readUint32(trex,4),track=result[trackId];track&&(track.default={duration:readUint32(trex,12),flags:readUint32(trex,20)})}),result}function parseStsd(stsd){var sampleEntries=stsd.subarray(8),sampleEntriesEnd=sampleEntries.subarray(86),fourCC=bin2str(sampleEntries.subarray(4,8)),codec=fourCC,encrypted='enca'===fourCC||'encv'===fourCC;if(encrypted){var encBox=findBox(sampleEntries,[fourCC])[0],encBoxChildren=encBox.subarray('enca'===fourCC?28:78),sinfs=findBox(encBoxChildren,['sinf']);sinfs.forEach(function(sinf){var schm=findBox(sinf,['schm'])[0];if(schm){var scheme=bin2str(schm.subarray(4,8));if('cbcs'===scheme||'cenc'===scheme){var frma=findBox(sinf,['frma'])[0];frma&&(codec=bin2str(frma))}}})}switch(codec){case'avc1':case'avc2':case'avc3':case'avc4':{var avcCBox=findBox(sampleEntriesEnd,['avcC'])[0];codec+='.'+toHex(avcCBox[1])+toHex(avcCBox[2])+toHex(avcCBox[3]);break}case'mp4a':{var codecBox=findBox(sampleEntries,[fourCC])[0],esdsBox=findBox(codecBox.subarray(28),['esds'])[0];if(esdsBox&&12<esdsBox.length){var i=4;if(3!==esdsBox[i++])break;i=skipBERInteger(esdsBox,i),i+=2;var flags=esdsBox[i++];if(128&flags&&(i+=2),64&flags&&(i+=esdsBox[i++]),4!==esdsBox[i++])break;i=skipBERInteger(esdsBox,i);var objectType=esdsBox[i++];if(64===objectType)codec+='.'+toHex(objectType);else break;if(i+=12,5!==esdsBox[i++])break;i=skipBERInteger(esdsBox,i);var firstByte=esdsBox[i++],audioObjectType=(248&firstByte)>>3;31==audioObjectType&&(audioObjectType+=1+((7&firstByte)<<3)+((224&esdsBox[i])>>5)),codec+='.'+audioObjectType}break}case'hvc1':case'hev1':{var hvcCBox=findBox(sampleEntriesEnd,['hvcC'])[0],profileByte=hvcCBox[1],profileSpace=['','A','B','C'][profileByte>>6],profileCompat=readUint32(hvcCBox,2),tierFlag=(32&profileByte)>>5?'H':'L',levelIDC=hvcCBox[12],constraintIndicator=hvcCBox.subarray(6,12);codec+='.'+profileSpace+(31&profileByte),codec+='.'+profileCompat.toString(16).toUpperCase(),codec+='.'+tierFlag+levelIDC;for(var constraintString='',_i=constraintIndicator.length,_byte;_i--;)if(_byte=constraintIndicator[_i],_byte||constraintString){var encodedByte=_byte.toString(16).toUpperCase();constraintString='.'+encodedByte+constraintString}codec+=constraintString;break}case'dvh1':case'dvhe':{var dvcCBox=findBox(sampleEntriesEnd,['dvcC'])[0],profile=127&dvcCBox[2]>>1,level=32&dvcCBox[2]<<5|31&dvcCBox[3]>>3;codec+='.'+addLeadingZero(profile)+'.'+addLeadingZero(level);break}case'vp09':{var vpcCBox=findBox(sampleEntriesEnd,['vpcC'])[0],_profile=vpcCBox[4],_level=vpcCBox[5],bitDepth=15&vpcCBox[6]>>4;codec+='.'+addLeadingZero(_profile)+'.'+addLeadingZero(_level)+'.'+addLeadingZero(bitDepth);break}case'av01':{var av1CBox=findBox(sampleEntriesEnd,['av1C'])[0],_profile2=av1CBox[1]>>>5,_level2=31&av1CBox[1],_tierFlag=av1CBox[2]>>>7?'H':'M',highBitDepth=(64&av1CBox[2])>>6,twelveBit=(32&av1CBox[2])>>5,_bitDepth=2===_profile2&&highBitDepth?twelveBit?12:10:highBitDepth?10:8,monochrome=(16&av1CBox[2])>>4,chromaSubsamplingX=(8&av1CBox[2])>>3,chromaSubsamplingY=(4&av1CBox[2])>>2,chromaSamplePosition=3&av1CBox[2];codec+='.'+_profile2+'.'+addLeadingZero(_level2)+_tierFlag+'.'+addLeadingZero(_bitDepth)+'.'+monochrome+'.'+chromaSubsamplingX+chromaSubsamplingY+chromaSamplePosition+'.'+addLeadingZero(1)+'.'+addLeadingZero(1)+'.'+addLeadingZero(1)+'.'+0;break}}return{codec:codec,encrypted:encrypted}}function skipBERInteger(bytes,i){for(var limit=i+5;128&bytes[i++]&&i<limit;);return i}function toHex(x){return('0'+x.toString(16).toUpperCase()).slice(-2)}function addLeadingZero(num){return(10>num?'0':'')+num}function patchEncyptionData(initSegment,decryptdata){if(!initSegment||!decryptdata)return initSegment;var keyId=decryptdata.keyId;if(keyId&&decryptdata.isCommonEncryption){var traks=findBox(initSegment,['moov','trak']);traks.forEach(function(trak){var stsd=findBox(trak,['mdia','minf','stbl','stsd'])[0],sampleEntries=stsd.subarray(8),encBoxes=findBox(sampleEntries,['enca']),isAudio=0<encBoxes.length;isAudio||(encBoxes=findBox(sampleEntries,['encv'])),encBoxes.forEac
1h(function(enc){var encBoxChildren=isAudio?enc.subarray(28):enc.subarray(78),sinfBoxes=findBox(encBoxChildren,['sinf']);sinfBoxes.forEach(function(sinf){var tenc=parseSinf(sinf);if(tenc){var tencKeyId=tenc.subarray(8,24);tencKeyId.some(function(b){return 0!==b})||(logger.log('[eme] Patching keyId in \'enc'+(isAudio?'a':'v')+'>sinf>>tenc\' box: '+Hex.hexDump(tencKeyId)+' -> '+Hex.hexDump(keyId)),tenc.set(keyId,8))}})})})}return initSegment}function parseSinf(sinf){var schm=findBox(sinf,['schm'])[0];if(schm){var scheme=bin2str(schm.subarray(4,8));if('cbcs'===scheme||'cenc'===scheme)return findBox(sinf,['schi','tenc'])[0]}return null}function getStartDTS(initData,fmp4){return findBox(fmp4,['moof','traf']).reduce(function(result,traf){var tfdt=findBox(traf,['tfdt'])[0],version=tfdt[0],start=findBox(traf,['tfhd']).reduce(function(result,tfhd){var id=readUint32(tfhd,4),track=initData[id];if(track){var baseTime=readUint32(tfdt,4);if(1===version){if(baseTime===UINT32_MAX$1)return logger.warn('[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time'),result;baseTime*=UINT32_MAX$1+1,baseTime+=readUint32(tfdt,8)}var scale=track.timescale||9e4,startTime=baseTime/scale;if(isFiniteNumber(startTime)&&(null===result||startTime<result))return startTime}return result},null);return null!==start&&isFiniteNumber(start)&&(null===result||start<result)?start:result},null)}function getDuration(data,initData){for(var rawDuration=0,videoDuration=0,audioDuration=0,trafs=findBox(data,['moof','traf']),i=0;i<trafs.length;i++){var traf=trafs[i],tfhd=findBox(traf,['tfhd'])[0],id=readUint32(tfhd,4),track=initData[id];if(track){var trackDefault=track.default,tfhdFlags=readUint32(tfhd,0)|(null==trackDefault?void 0:trackDefault.flags),sampleDuration=null==trackDefault?void 0:trackDefault.duration;8&tfhdFlags&&(2&tfhdFlags?sampleDuration=readUint32(tfhd,12):sampleDuration=readUint32(tfhd,8));for(var timescale=track.timescale||9e4,truns=findBox(traf,['trun']),j=0;j<truns.length;j++){if(rawDuration=computeRawDurationFromSamples(truns[j]),!rawDuration&&sampleDuration){var sampleCount=readUint32(truns[j],4);rawDuration=sampleDuration*sampleCount}track.type===ElementaryStreamTypes.VIDEO?videoDuration+=rawDuration/timescale:track.type===ElementaryStreamTypes.AUDIO&&(audioDuration+=rawDuration/timescale)}}}if(0==videoDuration&&0==audioDuration){for(var sidxMinStart=Infinity,sidxMaxEnd=0,sidxDuration=0,sidxs=findBox(data,['sidx']),_i2=0,sidx;_i2<sidxs.length;_i2++)if(sidx=parseSegmentIndex(sidxs[_i2]),null!=sidx&&sidx.references){sidxMinStart=Math.min(sidxMinStart,sidx.earliestPresentationTime/sidx.timescale);var subSegmentDuration=sidx.references.reduce(function(dur,ref){return dur+ref.info.duration||0},0);sidxMaxEnd=Math.max(sidxMaxEnd,subSegmentDuration+sidx.earliestPresentationTime/sidx.timescale),sidxDuration=sidxMaxEnd-sidxMinStart}if(sidxDuration&&isFiniteNumber(sidxDuration))return sidxDuration}return videoDuration?videoDuration:audioDuration}function computeRawDurationFromSamples(trun){var flags=readUint32(trun,0),offset=8;1&flags&&(offset+=4),4&flags&&(offset+=4);for(var duration=0,sampleCount=readUint32(trun,4),i=0;i<sampleCount;i++){if(256&flags){var sampleDuration=readUint32(trun,offset);duration+=sampleDuration,offset+=4}512&flags&&(offset+=4),1024&flags&&(offset+=4),2048&flags&&(offset+=4)}return duration}function offsetStartDTS(initData,fmp4,timeOffset){findBox(fmp4,['moof','traf']).forEach(function(traf){findBox(traf,['tfhd']).forEac
1h(function(tfhd){var id=readUint32(tfhd,4),track=initData[id];if(track){var timescale=track.timescale||9e4;findBox(traf,['tfdt']).forEach(function(tfdt){var version=tfdt[0],offset=timeOffset*timescale;if(offset){var baseMediaDecodeTime=readUint32(tfdt,4);if(0===version)baseMediaDecodeTime-=offset,baseMediaDecodeTime=Math.max(baseMediaDecodeTime,0),writeUint32(tfdt,4,baseMediaDecodeTime);else{baseMediaDecodeTime*=Math.pow(2,32),baseMediaDecodeTime+=readUint32(tfdt,8),baseMediaDecodeTime-=offset,baseMediaDecodeTime=Math.max(baseMediaDecodeTime,0);var upper=Math.floor(baseMediaDecodeTime/(UINT32_MAX$1+1)),lower=Math.floor(baseMediaDecodeTime%(UINT32_MAX$1+1));writeUint32(tfdt,4,upper),writeUint32(tfdt,8,lower)}}})}})})}function segmentValidRange(data){var segmentedRange={valid:null,remainder:null},moofs=findBox(data,['moof']);if(2>moofs.length)return segmentedRange.remainder=data,segmentedRange;var last=moofs[moofs.length-1];return segmentedRange.valid=sliceUint8(data,0,last.byteOffset-8),segmentedRange.remainder=sliceUint8(data,last.byteOffset-8),segmentedRange}function appendUint8Array(data1,data2){var temp=new Uint8Array(data1.length+data2.length);return temp.set(data1),temp.set(data2,data1.length),temp}function parseSamples(timeOffset,track){var seiSamples=[],videoData=track.samples,timescale=track.timescale,trackId=track.id,isHEVCFlavor=!1,moofs=findBox(videoData,['moof']);return moofs.map(function(moof){var moofOffset=moof.byteOffset-8,trafs=findBox(moof,['traf']);trafs.map(function(traf){var baseTime=findBox(traf,['tfdt']).map(function(tfdt){var version=tfdt[0],result=readUint32(tfdt,4);return 1===version&&(result*=Math.pow(2,32),result+=readUint32(tfdt,8)),result/timescale})[0];return void 0!==baseTime&&(timeOffset=baseTime),findBox(traf,['tfhd']).map(function(tfhd){var id=readUint32(tfhd,4),tfhdFlags=16777215&readUint32(tfhd,0),defaultSampleDuration=0,defaultSampleSize=0,tfhdOffset=8;id===trackId&&(0!=(1&tfhdFlags)&&(tfhdOffset+=8),0!=(2&tfhdFlags)&&(tfhdOffset+=4),0!=(8&tfhdFlags)&&(defaultSampleDuration=readUint32(tfhd,tfhdOffset),tfhdOffset+=4),0!=(16&tfhdFlags)&&(defaultSampleSize=readUint32(tfhd,tfhdOffset),tfhdOffset+=4),0!=(32&tfhdFlags)&&(tfhdOffset+=4),'video'===track.type&&(isHEVCFlavor=isHEVC(track.codec)),findBox(traf,['trun']).map(function(trun){var version=trun[0],flags=16777215&readUint32(trun,0),dataOffset=0,sampleDuration=0,sampleSize=0,compositionOffset=0,sampleCount=readUint32(trun,4),trunOffset=8;0!=(1&flags)&&(dataOffset=readUint32(trun,trunOffset),trunOffset+=4),0!=(4&flags)&&(trunOffset+=4);for(var sampleOffset=dataOffset+moofOffset,ix=0;ix<sampleCount;ix++){if(0!=(256&flags)?(sampleDuration=readUint32(trun,trunOffset),trunOffset+=4):sampleDuration=defaultSampleDuration,0!=(512&flags)?(sampleSize=readUint32(trun,trunOffset),trunOffset+=4):sampleSize=defaultSampleSize,0!=(1024&flags)&&(trunOffset+=4),0!=(2048&flags)&&(compositionOffset=0===version?readUint32(trun,trunOffset):readSint32(trun,trunOffset),trunOffset+=4),track.type===ElementaryStreamTypes.VIDEO)for(var naluTotalSize=0,naluSize;naluTotalSize<sampleSize;){if(naluSize=readUint32(videoData,sampleOffset),sampleOffset+=4,isSEIMessage(isHEVCFlavor,videoData[sampleOffset])){var data=videoData.subarray(sampleOffset,sampleOffset+naluSize);parseSEIMessageFromNALu(data,isHEVCFlavor?2:1,timeOffset+compositionOffset/timescale,seiSamples)}sampleOffset+=naluSize,naluTotalSize+=naluSize+4}timeOffset+=sampleDuration/timescale}}))})})}),seiSamples}function isHEVC(codec){if(!codec)return!1;var delimit=codec.indexOf('.'),baseCodec=0>delimit?codec:codec.substring(0,delimit);return'hvc1'===baseCodec||'hev1'===baseCodec||'dvh1'===baseCodec||'dvhe'===baseCodec}function isSEIMessage(isHEVCFlavor,naluHeader){if(isHEVCFlavor){var naluType=63&naluHeader>>1;return 39==naluType||40==naluType}return 6==(31&naluHeader)}function parseSEIMessageFromNALu(unescapedData,headerSize,pts,samples){var data=discardEPB(unescapedData),seiPtr=0;seiPtr+=headerSize;for(var payloadType=0,payloadSize=0,b=0;seiPtr<data.length;){payloadType=0;do{if(seiPtr>=data.length)break;b=data[seiPtr++],payloadType+=b}while(255===b);payloadSize=0;do{if(seiPtr>=data.length)break;
1b=data[seiPtr++],payloadSize+=b}while(255===b);var leftOver=data.length-seiPtr,payPtr=seiPtr;if(payloadSize<leftOver)seiPtr+=payloadSize;else if(payloadSize>leftOver){logger.error('Malformed SEI payload. '+payloadSize+' is too small, only '+leftOver+' bytes left to parse.');break}if(4===payloadType){var countryCode=data[payPtr++];if(181===countryCode){var providerCode=readUint16(data,payPtr);if(payPtr+=2,49===providerCode){var userStructure=readUint32(data,payPtr);if(payPtr+=4,1195456820===userStructure){var userDataType=data[payPtr++];if(3===userDataType){var firstByte=data[payPtr++],enabled=64&firstByte,totalBytes=enabled?2+3*(31&firstByte):0,byteArray=new Uint8Array(totalBytes);if(enabled){byteArray[0]=firstByte;for(var i=1;i<totalBytes;i++)byteArray[i]=data[payPtr++]}samples.push({type:userDataType,payloadType:payloadType,pts:pts,bytes:byteArray})}}}}}else if(5===payloadType&&16<payloadSize){for(var uuidStrArray=[],_i3=0,_b;16>_i3;_i3++)_b=data[payPtr++].toString(16),uuidStrArray.push(1==_b.length?'0'+_b:_b),(3===_i3||5===_i3||7===_i3||9===_i3)&&uuidStrArray.push('-');for(var length=payloadSize-16,userDataBytes=new Uint8Array(length),_i4=0;_i4<length;_i4++)userDataBytes[_i4]=data[payPtr++];samples.push({payloadType:payloadType,pts:pts,uuid:uuidStrArray.join(''),userData:utf8ArrayToStr(userDataBytes),userDataBytes:userDataBytes})}}}function discardEPB(data){for(var length=data.byteLength,EPBPositions=[],i=1;i<length-2;)0===data[i]&&0===data[i+1]&&3===data[i+2]?(EPBPositions.push(i+2),i+=2):i++;if(0===EPBPositions.length)return data;var newLength=length-EPBPositions.length,newData=new Uint8Array(newLength),sourceIndex=0;for(i=0;i<newLength;sourceIndex++,i++)sourceIndex===EPBPositions[0]&&(sourceIndex++,EPBPositions.shift()),newData[i]=data[sourceIndex];return newData}function parseEmsg(data){var version=data[0],schemeIdUri='',value='',timeScale=0,presentationTimeDelta=0,presentationTime=0,eventDuration=0,id=0,offset=0;if(0===version){for(;'\0'!==bin2str(data.subarray(offset,offset+1));)schemeIdUri+=bin2str(data.subarray(offset,offset+1)),offset+=1;for(schemeIdUri+=bin2str(data.subarray(offset,offset+1)),offset+=1;'\0'!==bin2str(data.subarray(offset,offset+1));)value+=bin2str(data.subarray(offset,offset+1)),offset+=1;value+=bin2str(data.subarray(offset,offset+1)),offset+=1,timeScale=readUint32(data,12),presentationTimeDelta=readUint32(data,16),eventDuration=readUint32(data,20),id=readUint32(data,24),offset=28}else if(1===version){offset+=4,timeScale=readUint32(data,offset),offset+=4;var leftPresentationTime=readUint32(data,offset);offset+=4;var rightPresentationTime=readUint32(data,offset);for(offset+=4,presentationTime=Math.pow(2,32)*leftPresentationTime+rightPresentationTime,isSafeInteger(presentationTime)||(presentationTime=Number.MAX_SAFE_INTEGER,logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box')),eventDuration=readUint32(data,offset),offset+=4,id=readUint32(data,offset),offset+=4;'\0'!==bin2str(data.subarray(offset,offset+1));)schemeIdUri+=bin2str(data.subarray(offset,offset+1)),offset+=1;for(schemeIdUri+=bin2str(data.subarray(offset,offset+1)),offset+=1;'\0'!==bin2str(data.subarray(offset,offset+1));)value+=bin2str(data.subarray(offset,offset+1)),offset+=1;value+=bin2str(data.subarray(offset,offset+1)),offset+=1}var payload=data.subarray(offset,data.byteLength);return{schemeIdUri:schemeIdUri,value:value,timeScale:timeScale,presentationTime:presentationTime,presentationTimeDelta:presentationTimeDelta,eventDuration:eventDuration,id:id,payload:payload}}function mp4Box(type){for(var _len=arguments.length,payload=Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)payload[_key-1]=arguments[_key];for(var len=payload.length,size=8,i=len;i--;)size+=payload[i].byteLength;var result=new Uint8Array(size);for(result[0]=255&size>>24,result[1]=255&size>>16,result[2]=255&size>>8,result[3]=255&size,result.set(type,4),(i=0,size=8);i<len;i++)result.set(payload[i],size),size+=payload[i].byteLength;return result}function mp4pssh(systemId,keyids,data){if(16!==systemId.byteLength)throw new RangeError('Invalid system id');var version,kids;
1if(keyids){version=1,kids=new Uint8Array(16*keyids.length);for(var ix=0,k;ix<keyids.length;ix++){if(k=keyids[ix],16!==k.byteLength)throw new RangeError('Invalid key');kids.set(k,16*ix)}}else version=0,kids=new Uint8Array;var kidCount;0<version?(kidCount=new Uint8Array(4),0<keyids.length&&new DataView(kidCount.buffer).setUint32(0,keyids.length,!1)):kidCount=new Uint8Array;var dataSize=new Uint8Array(4);return data&&0<data.byteLength&&new DataView(dataSize.buffer).setUint32(0,data.byteLength,!1),mp4Box([112,115,115,104],new Uint8Array([version,0,0,0]),systemId,kidCount,kids,dataSize,data||new Uint8Array)}function parseMultiPssh(initData){var results=[];if(initData instanceof ArrayBuffer)for(var length=initData.byteLength,offset=0;offset+32<length;){var view=new DataView(initData,offset),pssh=parsePssh(view);results.push(pssh),offset+=pssh.size}return results}function parsePssh(view){var size=view.getUint32(0),offset=view.byteOffset,length=view.byteLength;if(length<size)return{offset:offset,size:length};var type=view.getUint32(4);if(1886614376!==type)return{offset:offset,size:size};var version=view.getUint32(8)>>>24;if(0!=version&&1!=version)return{offset:offset,size:size};var buffer=view.buffer,systemId=Hex.hexDump(new Uint8Array(buffer,offset+12,16)),dataSizeOrKidCount=view.getUint32(28),kids=null,data=null;if(0==version){if(size-32<dataSizeOrKidCount||22>dataSizeOrKidCount)return{offset:offset,size:size};data=new Uint8Array(buffer,offset+32,dataSizeOrKidCount)}else if(1==version){if(!dataSizeOrKidCount||length<offset+32+16*dataSizeOrKidCount+16)return{offset:offset,size:size};kids=[];for(var i=0;i<dataSizeOrKidCount;i++)kids.push(new Uint8Array(buffer,offset+32+16*i,16))}return{version:version,systemId:systemId,kids:kids,data:data,offset:offset,size:size}}function createInitializationVector(segmentNumber){for(var uint8View=new Uint8Array(16),i=12;16>i;i++)uint8View[i]=255&segmentNumber>>8*(15-i);return uint8View}function hasVariableReferences(str){return VARIABLE_REPLACEMENT_REGEX.test(str)}function substituteVariablesInAttributes(parsed,attr,attributeNames){if(null!==parsed.variableList||parsed.hasVariableRefs)for(var i=attributeNames.length;i--;){var name=attributeNames[i],value=attr[name];value&&(attr[name]=substituteVariables(parsed,value))}}function substituteVariables(parsed,value){if(null!==parsed.variableList||parsed.hasVariableRefs){var variableList=parsed.variableList;return value.replace(VARIABLE_REPLACEMENT_REGEX,function(variableReference){var variableName=variableReference.substring(2,variableReference.length-1),variableValue=null==variableList?void 0:variableList[variableName];return void 0===variableValue?(parsed.playlistParsingError||(parsed.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+variableName+'"')),variableReference):variableValue})}return value}function addVariableDefinition(parsed,attr,parentUrl){var variableList=parsed.variableList;variableList||(parsed.variableList=variableList={});var NAME,VALUE;if('QUERYPARAM'in attr){NAME=attr.QUERYPARAM;try{var searchParams=new self.URL(parentUrl).searchParams;if(searchParams.has(NAME))VALUE=searchParams.get(NAME);else throw new Error('"'+NAME+'" does not match any query parameter in URI: "'+parentUrl+'"')}catch(error){parsed.playlistParsingError||(parsed.playlistParsingError=new Error('EXT-X-DEFINE QUERYPARAM: '+error.message))}}else NAME=attr.NAME,VALUE=attr.VALUE;NAME in variableList?parsed.playlistParsingError||(parsed.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+NAME+'"')):variableList[NAME]=VALUE||''}function importVariableDefinition(parsed,attr,sourceVariableList){var IMPORT=attr.IMPORT;if(sourceVariableList&&IMPORT in sourceVariableList){var variableList=parsed.variableList;variableList||(parsed.variableList=variableList={}),variableList[IMPORT]=sourceVariableList[IMPORT]}else parsed.playlistParsingError||(parsed.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+IMPORT+'"'))}function getMediaSource(preferManagedMediaSource){if(void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),'undefined'!=typeof self){var mms=(preferManagedMediaSource||!self.MediaSource)&&self.ManagedMediaSource;return mms||self.MediaSource||self.WebKitMediaSource}}function isManagedMediaSource(source){return'undefined'!=typeof self&&source===self.ManagedMediaSource}function isCodecType(codec,type){var typeCodes=sampleEntryCodesISO[type];return!!typeCodes&&!!typeCodes[codec.slice(0,4)]}
1function areCodecsMediaSourceSupported(codecs,type,preferManagedMediaSource){return void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),!codecs.split(',').some(function(codec){return!isCodecMediaSourceSupported(codec,type,preferManagedMediaSource)})}function isCodecMediaSourceSupported(codec,type,preferManagedMediaSource){var _MediaSource$isTypeSu;void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0);var MediaSource=getMediaSource(preferManagedMediaSource);return null!=(_MediaSource$isTypeSu=null==MediaSource?void 0:MediaSource.isTypeSupported(mimeTypeForCodec(codec,type)))&&_MediaSource$isTypeSu}function mimeTypeForCodec(codec,type){return type+'/mp4;codecs="'+codec+'"'}function videoCodecPreferenceValue(videoCodec){if(videoCodec){var fourCC=videoCodec.substring(0,4);return sampleEntryCodesISO.video[fourCC]}return 2}function codecsSetSelectionPreferenceValue(codecSet){return codecSet.split(',').reduce(function(num,fourCC){var preferenceValue=sampleEntryCodesISO.video[fourCC];return preferenceValue?(2*preferenceValue+num)/(num?3:2):(sampleEntryCodesISO.audio[fourCC]+num)/(num?2:1)},0)}function getCodecCompatibleNameLower(lowerCaseCodec,preferManagedMediaSource){if(void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),CODEC_COMPATIBLE_NAMES[lowerCaseCodec])return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];for(var codecsToCheck={flac:['flac','fLaC','FLAC'],opus:['opus','Opus']}[lowerCaseCodec],i=0;i<codecsToCheck.length;i++)if(isCodecMediaSourceSupported(codecsToCheck[i],'audio',preferManagedMediaSource))return CODEC_COMPATIBLE_NAMES[lowerCaseCodec]=codecsToCheck[i],codecsToCheck[i];return lowerCaseCodec}function getCodecCompatibleName(codec,preferManagedMediaSource){return void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),codec.replace(AUDIO_CODEC_REGEXP,function(m){return getCodecCompatibleNameLower(m.toLowerCase(),preferManagedMediaSource)})}function pickMostCompleteCodecName(parsedCodec,levelCodec){return parsedCodec&&'mp4a'!==parsedCodec?parsedCodec:levelCodec?levelCodec.split(',')[0]:levelCodec}function convertAVC1ToAVCOTI(codec){for(var codecs=codec.split(','),i=0,avcdata;i<codecs.length;i++)if(avcdata=codecs[i].split('.'),2<avcdata.length){var result=avcdata.shift()+'.';result+=parseInt(avcdata.shift()).toString(16),result+=('000'+parseInt(avcdata.shift()).toString(16)).slice(-4),codecs[i]=result}return codecs.join(',')}function parseKey(keyTagAttributes,baseurl,parsed){var keyAttrs=new AttrList(keyTagAttributes),_keyAttrs$METHOD,_keyAttrs$KEYFORMAT;substituteVariablesInAttributes(parsed,keyAttrs,['KEYFORMAT','KEYFORMATVERSIONS','URI','IV','URI']);var decryptmethod=null==(_keyAttrs$METHOD=keyAttrs.METHOD)?'':_keyAttrs$METHOD,decrypturi=keyAttrs.URI,decryptiv=keyAttrs.hexadecimalInteger('IV'),decryptkeyformatversions=keyAttrs.KEYFORMATVERSIONS,decryptkeyformat=null==(_keyAttrs$KEYFORMAT=keyAttrs.KEYFORMAT)?'identity':_keyAttrs$KEYFORMAT;decrypturi&&keyAttrs.IV&&!decryptiv&&logger.error('Invalid IV: '+keyAttrs.IV);var resolvedUri=decrypturi?M3U8Parser.resolve(decrypturi,baseurl):'',keyFormatVersions=(decryptkeyformatversions?decryptkeyformatversions:'1').split('/').map(Number).filter(Number.isFinite);return new LevelKey(decryptmethod,resolvedUri,decryptkeyformat,keyFormatVersions,decryptiv)}function parseStartTimeOffset(startAttributes){var startAttrs=new AttrList(startAttributes),startTimeOffset=startAttrs.decimalFloatingPoint('TIME-OFFSET');return isFiniteNumber(startTimeOffset)?startTimeOffset:null}function setCodecs(codecsAttributeValue,level){var codecs=(codecsAttributeValue||'').split(/[ ,]+/).filter(function(c){return c});['video','audio','text'].forEach(function(type){var filtered=codecs.filter(function(codec){return isCodecType(codec,type)});filtered.length&&(level[type+'Codec']=filtered.join(','),codecs=codecs.filter(function(codec){return-1===filtered.indexOf(codec)}))}),level.unknownCodecs=codecs}function assignCodec(media,groupItem,codecProperty){var codecValue=groupItem[codecProperty];codecValue&&(media[codecProperty]=codecValue)}function backfillProgramDateTimes(fragments,firstPdtIndex){for(var fragPrev=fragments[firstPdtIndex],i=firstPdtIndex,frag;i--;){if(frag=fragments[i],!frag)return;frag.programDateTime=fragPrev.programDateTime-1e3*frag.duration,fragPrev=frag}}function assignProgramDateTime(frag,prevFrag){frag.rawProgramDateTime?frag.programDateTime=Date.parse(frag.rawProgramDateTime):null!=prevFrag&&prevFrag.programDateTime&&(frag.programDateTime=prevFrag.endProgramDateTime),isFiniteNumber(frag.programDateTime)||(frag.programDateTime=null,frag.rawProgramDateTime=null)}function setInitSegment(frag,mapAttrs,id,levelkeys){frag.relurl=mapAttrs.URI,mapAttrs.BYTERANGE&&frag.setByteRange(mapAttrs.BYTERANGE),frag.level=id,frag.sn='initSegment',levelkeys&&(frag.levelkeys=levelkeys),frag.initSegment=null}function setFragLevelKeys(frag,levelkeys,level){frag.levelkeys=levelkeys;var encryptedFragments=level.encryptedFragments;(!encryptedFragments.length||encryptedFragments[encryptedFragments.length-1].levelkeys!==levelkeys)&&Object.keys(levelkeys).some(function(format){return levelkeys[format].isCommonEncryption})&&encryptedFragments.push(frag)}function mapContextToLevelType(context){var type=context.type;return type===PlaylistContextType.AUDIO_TRACK?PlaylistLevelType.AUDIO:type===PlaylistContextType.SUBTITLE_TRACK?PlaylistLevelType.SUBTITLE:PlaylistLevelType.MAIN}function getResponseUrl(response,context){var url=response.url;return(void 0===url||0===url.indexOf('data:'))&&(url=context.url),url}function sendAddTrackEvent(track,videoEl){var event;try{event=new Event('addtrack')}catch(err){event=document.createEvent('Event'),event.initEvent('addtrack',!1,!1)}event.track=track,videoEl.dispatchEvent(event)}function addCueToTrack(track,cue){var mode=track.mode;if('disabled'===mode&&(track.mode='hidden'),track.cues&&!track.cues.getCueById(cue.id))try{if
1(track.addCue(cue),!track.cues.getCueById(cue.id))throw new Error('addCue is failed for: '+cue)}catch(err){logger.debug('[texttrack-utils]: '+err);try{var textTrackCue=new self.TextTrackCue(cue.startTime,cue.endTime,cue.text);textTrackCue.id=cue.id,track.addCue(textTrackCue)}catch(err2){logger.debug('[texttrack-utils]: Legacy TextTrackCue fallback failed: '+err2)}}'disabled'===mode&&(track.mode=mode)}function clearCurrentCues(track){var mode=track.mode;if('disabled'===mode&&(track.mode='hidden'),track.cues)for(var i=track.cues.length;i--;)track.removeCue(track.cues[i]);'disabled'===mode&&(track.mode=mode)}function removeCuesInRange(track,start,end,predicate){var mode=track.mode;if('disabled'===mode&&(track.mode='hidden'),track.cues&&0<track.cues.length)for(var cues=getCuesInRange(track.cues,start,end),i=0;i<cues.length;i++)(!predicate||predicate(cues[i]))&&track.removeCue(cues[i]);'disabled'===mode&&(track.mode=mode)}function getFirstCueIndexAfterTime(cues,time){if(time<cues[0].startTime)return 0;var len=cues.length-1;if(time>cues[len].endTime)return-1;for(var left=0,right=len,mid;left<=right;)if(mid=Math.floor((right+left)/2),time<cues[mid].startTime)right=mid-1;else if(time>cues[mid].startTime&&left<len)left=mid+1;else return mid;return cues[left].startTime-time<time-cues[right].startTime?left:right}function getCuesInRange(cues,start,end){var cuesFound=[],firstCueInRange=getFirstCueIndexAfterTime(cues,start);if(-1<firstCueInRange)for(var i=firstCueInRange,len=cues.length,_cue;i<len;i++)if(_cue=cues[i],_cue.startTime>=start&&_cue.endTime<=end)cuesFound.push(_cue);else if(_cue.startTime>end)return cuesFound;return cuesFound}function filterSubtitleTracks(textTrackList){for(var tracks=[],i=0,track;i<textTrackList.length;i++)track=textTrackList[i],('subtitles'===track.kind||'captions'===track.kind)&&track.label&&tracks.push(textTrackList[i]);return tracks}function getCueClass(){return'undefined'==typeof self?void 0:self.VTTCue||self.TextTrackCue}function createCueWithDataFields(Cue,startTime,endTime,data,type){var cue=new Cue(startTime,endTime,'');try{cue.value=data,type&&(cue.type=type)}catch(e){cue=new Cue(startTime,endTime,JSON.stringify(type?_objectSpread2({type:type},data):data))}return cue}function dateRangeDateToTimelineSeconds(date,offset){return date.getTime()/1e3-offset}function hexToArrayBuffer(str){return Uint8Array.from(str.replace(/^0x/,'').replace(/([\da-fA-F]{2}) ?/g,'0x$1 ').replace(/ +$/,'').split(' ')).buffer}function isHdcpLevel(value){return-1<HdcpLevels.indexOf(value)}function isVideoRange(value){return!!value&&-1<VideoRangeValues.indexOf(value)}function getSkipValue(details){var canSkipUntil=details.canSkipUntil,canSkipDateRanges=details.canSkipDateRanges,age=details.age;return canSkipUntil&&age<canSkipUntil/2?canSkipDateRanges?HlsSkip.v2:HlsSkip.Yes:HlsSkip.No}function hasGroup(groups,groupId){return!!(groupId&&groups)&&-1!==groups.indexOf(groupId)}function updateFromToPTS(fragFrom,fragTo){var fragToPTS=fragTo.startPTS;if(isFiniteNumber(fragToPTS)){var duration=0,frag;fragTo.sn>fragFrom.sn?(duration=fragToPTS-fragFrom.start,frag=fragFrom):(duration=fragFrom.start-fragToPTS,frag=fragTo),frag.duration!==duration&&(frag.duration=duration)}else if(fragTo.sn>fragFrom.sn){var contiguous=fragFrom.cc===fragTo.cc;fragTo.start=contiguous&&fragFrom.minEndPTS?fragFrom.start+(fragFrom.minEndPTS-fragFrom.start):fragFrom.start+fragFrom.duration}else fragTo.start=Math.max(fragFrom.start-fragTo.duration,0)}function updateFragPTSDTS(details,frag,startPTS,endPTS,startDTS,endDTS){var parsedMediaDuration=endPTS-startPTS;0>=parsedMediaDuration&&(logger.warn('Fragment should have a positive duration',frag),endPTS=startPTS+frag.duration,endDTS=startDTS+frag.duration);var maxStartPTS=startPTS,minEndPTS=endPTS,fragStartPts=frag.startPTS,fragEndPts=frag.endPTS;if(isFiniteNumber(fragStartPts)){var deltaPTS=Math.abs(fragStartPts-startPTS);frag.deltaPTS=isFiniteNumber(frag.deltaPTS)?Math.max(deltaPTS,frag.deltaPTS):deltaPTS,maxStartPTS=Math.max(startPTS,fragStartPts),startPTS=Math.min(startPTS,fragStartPts),startDTS=Math.min(startDTS,frag.startDTS),minEndPTS=Math.min(endPTS,fragEndPts),endPTS=Math.max(endPTS,fragEndPts),endDTS=Math.max(endDT
1S,frag.endDTS)}var drift=startPTS-frag.start;0!==frag.start&&(frag.start=startPTS),frag.duration=endPTS-frag.start,frag.startPTS=startPTS,frag.maxStartPTS=maxStartPTS,frag.startDTS=startDTS,frag.endPTS=endPTS,frag.minEndPTS=minEndPTS,frag.endDTS=endDTS;var sn=frag.sn;if(!details||sn<details.startSN||sn>details.endSN)return 0;var fragIdx=sn-details.startSN,fragments=details.fragments,i;for(fragments[fragIdx]=frag,i=fragIdx;0<i;i--)updateFromToPTS(fragments[i],fragments[i-1]);for(i=fragIdx;i<fragments.length-1;i++)updateFromToPTS(fragments[i],fragments[i+1]);return details.fragmentHint&&updateFromToPTS(fragments[fragments.length-1],details.fragmentHint),details.PTSKnown=details.alignedSliding=!0,drift}function mergeDetails(oldDetails,newDetails){for(var currentInitSegment=null,oldFragments=oldDetails.fragments,i=oldFragments.length-1,oldInit;0<=i;i--)if(oldInit=oldFragments[i].initSegment,oldInit){currentInitSegment=oldInit;break}oldDetails.fragmentHint&&delete oldDetails.fragmentHint.endPTS;var ccOffset=0,PTSFrag;if(mapFragmentIntersection(oldDetails,newDetails,function(oldFrag,newFrag){oldFrag.relurl&&(ccOffset=oldFrag.cc-newFrag.cc),isFiniteNumber(oldFrag.startPTS)&&isFiniteNumber(oldFrag.endPTS)&&(newFrag.start=newFrag.startPTS=oldFrag.startPTS,newFrag.startDTS=oldFrag.startDTS,newFrag.maxStartPTS=oldFrag.maxStartPTS,newFrag.endPTS=oldFrag.endPTS,newFrag.endDTS=oldFrag.endDTS,newFrag.minEndPTS=oldFrag.minEndPTS,newFrag.duration=oldFrag.endPTS-oldFrag.startPTS,newFrag.duration&&(PTSFrag=newFrag),newDetails.PTSKnown=newDetails.alignedSliding=!0),newFrag.elementaryStreams=oldFrag.elementaryStreams,newFrag.loader=oldFrag.loader,newFrag.stats=oldFrag.stats,oldFrag.initSegment&&(newFrag.initSegment=oldFrag.initSegment,currentInitSegment=oldFrag.initSegment)}),currentInitSegment){var fragmentsToCheck=newDetails.fragmentHint?newDetails.fragments.concat(newDetails.fragmentHint):newDetails.fragments;fragmentsToCheck.forEach(function(frag){var _currentInitSegment;frag&&(!frag.initSegment||frag.initSegment.relurl===(null==(_currentInitSegment=currentInitSegment)?void 0:_currentInitSegment.relurl))&&(frag.initSegment=currentInitSegment)})}if(newDetails.skippedSegments)if(newDetails.deltaUpdateFailed=newDetails.fragments.some(function(frag){return!frag}),newDetails.deltaUpdateFailed){logger.warn('[level-helper] Previous playlist missing segments ski
1pped in delta playlist');for(var _i=newDetails.skippedSegments;_i--;)newDetails.fragments.shift();newDetails.startSN=newDetails.fragments[0].sn,newDetails.startCC=newDetails.fragments[0].cc}else newDetails.canSkipDateRanges&&(newDetails.dateRanges=mergeDateRanges(oldDetails.dateRanges,newDetails.dateRanges,newDetails.recentlyRemovedDateranges));var newFragments=newDetails.fragments;if(ccOffset){logger.warn('discontinuity sliding from playlist, take drift into account');for(var _i2=0;_i2<newFragments.length;_i2++)newFragments[_i2].cc+=ccOffset}newDetails.skippedSegments&&(newDetails.startCC=newDetails.fragments[0].cc),mapPartIntersection(oldDetails.partList,newDetails.partList,function(oldPart,newPart){newPart.elementaryStreams=oldPart.elementaryStreams,newPart.stats=oldPart.stats}),PTSFrag?updateFragPTSDTS(newDetails,PTSFrag,PTSFrag.startPTS,PTSFrag.endPTS,PTSFrag.startDTS,PTSFrag.endDTS):adjustSliding(oldDetails,newDetails),newFragments.length&&(newDetails.totalduration=newDetails.edge-newFragments[0].start),newDetails.driftStartTime=oldDetails.driftStartTime,newDetails.driftStart=oldDetails.driftStart;var advancedDateTime=newDetails.advancedDateTime;if(newDetails.advanced&&advancedDateTime){var edge=newDetails.edge;newDetails.driftStart||(newDetails.driftStartTime=advancedDateTime,newDetails.driftStart=edge),newDetails.driftEndTime=advancedDateTime,newDetails.driftEnd=edge}else newDetails.driftEndTime=oldDetails.driftEndTime,newDetails.driftEnd=oldDetails.driftEnd,newDetails.advancedDateTime=oldDetails.advancedDateTime}function mergeDateRanges(oldDateRanges,deltaDateRanges,recentlyRemovedDateranges){var dateRanges=_extends({},oldDateRanges);return recentlyRemovedDateranges&&recentlyRemovedDateranges.forEach(function(id){delete dateRanges[id]}),Object.keys(deltaDateRanges).forEach(function(id){var dateRange=new DateRange(deltaDateRanges[id].attr,dateRanges[id]);dateRange.isValid?dateRanges[id]=dateRange:logger.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+JSON.stringify(deltaDateRanges[id].attr)+'"')}),dateRanges}function mapPartIntersection(oldParts,newParts,intersectionFn){if(oldParts&&newParts)for(var delta=0,i=0,len=oldParts.length;i<=len;i++){var _oldPart=oldParts[i],_newPart=newParts[i+delta];_oldPart&&_newPart&&_oldPart.index===_newPart.index&&_oldPart.fragment.sn===_newPart.fragment.sn?intersectionFn(_oldPart,_newPart):delta--}}function mapFragmentIntersection(oldDetails,newDetails,intersectionFn){for(var skippedSegments=newDetails.skippedSegments,start=Math.max(oldDetails.startSN,newDetails.startSN)-newDetails.startSN,end=(oldDetails.fragmentHint?1:0)+(skippedSegments?newDetails.endSN:Math.min(oldDetails.endSN,newDetails.endSN))-newDetails.startSN,delta=newDetails.startSN-oldDetails.startSN,newFrags=newDetails.fragmentHint?newDetails.fragments.concat(newDetails.fragmentHint):newDetails.fragments,oldFrags=oldDetails.fragmentHint?oldDetails.fragments.concat(oldDetails.fragmentHint):oldDetails.fragments,i=start;i<=end;i++){var _oldFrag=oldFrags[delta+i],_newFrag=newFrags[i];skippedSegments&&!_newFrag&&i<skippedSegments&&(_newFrag=newDetails.fragments[i]=_oldFrag),_oldFrag&&_newFrag&&intersectionFn(_oldFrag,_newFrag)}}function adjustSliding(oldDetails,newDetails){var delta=newDetails.startSN+newDetails.skippedSegments-oldDetails.startSN,oldFragments=oldDetails.fragments;0>delta||delta>=oldFragments.length||addSliding(newDetails,oldFragments[delta].start)}function addSliding(details,start){if(start){for(var fragments=details.fragments,i=details.skippedSegments;i<fragments.length;i++)fragments[i].start+=start;details.fragmentHint&&(details.fragmentHint.start+=start)}}function computeReloadInterval(newDetails,distanceToLiveEdgeMs){void 0===distanceToLiveEdgeMs&&(distanceToLiveEdgeMs=Infinity);var reloadInterval=1e3*newDetails.targetduration;if(newDetails.updated){var fragments=newDetails.fragments;if(fragments.length&&reloadInterval*4>distanceToLiveEdgeMs){var lastSegmentDuration=1e3*fragments[fragments.length-1].duration;lastSegmentDuration<reloadInterval&&(reloadInterval=lastSegmentDuration)}}else reloadInterval/=2;return Math.round(reloadInterval)}function getFragmentWithSN(level,sn,fragCurrent){if(!(null!=level&&level.details))return null;var levelDetails=level.details,fragment=levelDetails.fragments[sn-levelDetails.startSN];return fragment?fragment:(fragment=levelDetails.fragmentHint,fragment&&fragment.sn===sn?fragment:sn<levelDetails.startSN&&fragCurrent&&fragCurrent.sn===sn?fragCurrent:null)}function getPartWith(level,sn,partIndex){var _level$details;return null!=level&&level.details?findPart(null==(_level$details=level.details)?void 0:_level$details.partList,sn,partIndex):null}
1function findPart(partList,sn,partIndex){if(partList)for(var i=partList.length,part;i--;)if(part=partList[i],part.index===partIndex&&part.fragment.sn===sn)return part;return null}function reassignFragmentLevelIndexes(levels){levels.forEach(function(level,index){var details=level.details;null!=details&&details.fragments&&details.fragments.forEach(function(fragment){fragment.level=index})})}function isTimeoutError(error){switch(error.details){case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_TIMEOUT:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.MANIFEST_LOAD_TIMEOUT:return!0;}return!1}function getRetryConfig(loadPolicy,error){var isTimeout=isTimeoutError(error);return loadPolicy.default[(isTimeout?'timeout':'error')+'Retry']}function getRetryDelay(retryConfig,retryCount){var backoffFactor='linear'===retryConfig.backoff?1:Math.pow(2,retryCount);return Math.min(backoffFactor*retryConfig.retryDelayMs,retryConfig.maxRetryDelayMs)}function getLoaderConfigWithoutReties(loderConfig){return _objectSpread2(_objectSpread2({},loderConfig),{errorRetry:null,timeoutRetry:null})}function shouldRetry(retryConfig,retryCount,isTimeout,loaderResponse){if(!retryConfig)return!1;var httpStatus=null==loaderResponse?void 0:loaderResponse.code,retry=retryCount<retryConfig.maxNumRetry&&(retryForHttpStatus(httpStatus)||!!isTimeout);return retryConfig.shouldRetry?retryConfig.shouldRetry(retryConfig,retryCount,isTimeout,loaderResponse,retry):retry}function retryForHttpStatus(httpStatus){return 0===httpStatus&&!1===navigator.onLine||!!httpStatus&&(400>httpStatus||499<httpStatus)}function findFragmentByPDT(fragments,PDTValue,maxFragLookUpTolerance){if(null===PDTValue||!Array.isArray(fragments)||!fragments.length||!isFiniteNumber(PDTValue))return null;var startPDT=fragments[0].programDateTime;if(PDTValue<(startPDT||0))return null;var endPDT=fragments[fragments.length-1].endProgramDateTime;if(PDTValue>=(endPDT||0))return null;maxFragLookUpTolerance=maxFragLookUpTolerance||0;for(var seg=0,frag;seg<fragments.length;++seg)if(frag=fragments[seg],pdtWithinToleranceTest(PDTValue,maxFragLookUpTolerance,frag))return frag;return null}function findFragmentByPTS(fragPrevious,fragments,bufferEnd,maxFragLookUpTolerance,nextFragLookupTolerance){void 0===bufferEnd&&(bufferEnd=0),void 0===maxFragLookUpTolerance&&(maxFragLookUpTolerance=0),void 0===nextFragLookupTolerance&&(nextFragLookupTolerance=.005);var fragNext=null;if(fragPrevious){fragNext=fragments[fragPrevious.sn-fragments[0].sn+1]||null;var bufferEdgeError=fragPrevious.endDTS-bufferEnd;0<bufferEdgeError&&15e-7>bufferEdgeError&&(bufferEnd+=15e-7)}else 0===bufferEnd&&0===fragments[0].start&&(fragNext=fragments[0]);if(fragNext&&((!fragPrevious||fragPrevious.level===fragNext.level)&&0===fragmentWithinToleranceTest(bufferEnd,maxFragLookUpTolerance,fragNext)||fragmentWithinFastStartSwitch(fragNext,fragPrevious,Math.min(nextFragLookupTolerance,maxFragLookUpTolerance))))return fragNext;var foundFragment=BinarySearch.search(fragments,fragmentWithinToleranceTest.bind(null,bufferEnd,maxFragLookUpTolerance));return foundFragment&&(foundFragment!==fragPrevious||!fragNext)?foundFragment:fragNext}function fragmentWithinFastStartSwitch(fragNext,fragPrevious,nextFragLookupTolerance){if(fragPrevious&&0===fragPrevious.start&&fragPrevious.level<fragNext.level&&0<(fragPrevious.endPTS||0)){var firstDuration=fragPrevious.tagList.reduce(function(duration,tag){return'INF'===tag[0]&&(duration+=parseFloat(tag[1])),duration},nextFragLookupTolerance);return fragNext.start<=firstDuration}return!1}function fragmentWithinToleranceTest(bufferEnd,maxFragLookUpTolerance,candidate){if(void 0===bufferEnd&&(bufferEnd=0),void 0===maxFragLookUpTolerance&&(maxFragLookUpTolerance=0),candidate.start<=bufferEnd&&candidate.start+candidate.duration>bufferEnd)return 0;var candidateLookupTolerance=Math.min(maxFragLookUpTolerance,candidate.duration+(candidate.deltaPTS?candidate.deltaPTS:0));return candidate.start+candidate.duration-candidateLookupTolerance<=bufferEnd?1:candidate.start-candidateLookupTolerance>bufferEnd&&candidate.start?-1:0}function pdtWithinToleranceTest(pdtBufferEnd,maxFragLookUpTolerance,candidate){var candidateLookupTolerance=1e3*Math.min(maxFragLookUpTolerance,candidate.duration+(candidate.deltaPTS?candidate.deltaPTS:0)),endProgramDateTime=candidate.endProgramDateTime||0;return endProgramDateTime-candidateLookupTolerance>pdtBufferEnd}function findFragWithCC(fragments,cc){return BinarySearch.search(fragments,function(candidate){return candidate.cc<cc?1:candidate.cc>cc?-1:0})}function requiresMediaCapabilitiesDecodingInfo(level,audioTracksByGroup,currentVideoRange,currentFrameRate,currentBw,audioPreference){var audioGroups=level.audioCodec?level.audioGroups:null,audioCodecPreference=null==audioPreference?void 0:audioPreference.audioCodec,channelsPreference=null==audioPreference?void 0:audioPreference.channels,maxChannels=channelsPreference?parseInt(channelsPreference):audioCodecPreference?Infinity:2,audioChannels=null;if(null!=audioGroups&&audioGroups.length)try{audioChannels=1===audioGroups.length&&audioGroups[0]?audioTracksByGroup.groups[audioGroups[0]].channels:audioGroups.reduce(function(acc,groupId){if(groupId){var audioTrackGroup=audioTracksByGroup.groups[groupId];if(!audioTrackGroup)throw new Error('Audio track group '+groupId+' not found');
1Object.keys(audioTrackGroup.channels).forEach(function(key){acc[key]=(acc[key]||0)+audioTrackGroup.channels[key]})}return acc},{2:0})}catch(error){return!0}return void 0!==level.videoCodec&&(1920<level.width&&1088<level.height||1920<level.height&&1088<level.width||level.frameRate>Math.max(currentFrameRate,30)||'SDR'!==level.videoRange&&level.videoRange!==currentVideoRange||level.bitrate>Math.max(currentBw,8e6))||!!audioChannels&&isFiniteNumber(maxChannels)&&Object.keys(audioChannels).some(function(channels){return parseInt(channels)>maxChannels})}function getMediaDecodingInfoPromise(level,audioTracksByGroup,mediaCapabilities){var videoCodecs=level.videoCodec,audioCodecs=level.audioCodec;if(!videoCodecs||!audioCodecs||!mediaCapabilities)return Promise.resolve(SUPPORTED_INFO_DEFAULT);var baseVideoConfiguration={width:level.width,height:level.height,bitrate:Math.ceil(Math.max(.9*level.bitrate,level.averageBitrate)),framerate:level.frameRate||30},videoRange=level.videoRange;'SDR'!==videoRange&&(baseVideoConfiguration.transferFunction=videoRange.toLowerCase());var configurations=videoCodecs.split(',').map(function(videoCodec){return{type:'media-source',video:_objectSpread2(_objectSpread2({},baseVideoConfiguration),{},{contentType:mimeTypeForCodec(videoCodec,'video')})}});return audioCodecs&&level.audioGroups&&level.audioGroups.forEach(function(audioGroupId){var _audioTracksByGroup$g;audioGroupId&&(null==(_audioTracksByGroup$g=audioTracksByGroup.groups[audioGroupId])?void 0:_audioTracksByGroup$g.tracks.forEach(function(audioTrack){if(audioTrack.groupId===audioGroupId){var channels=audioTrack.channels||'',channelsNumber=parseFloat(channels);isFiniteNumber(channelsNumber)&&2<channelsNumber&&configurations.push.apply(configurations,audioCodecs.split(',').map(function(audioCodec){return{type:'media-source',audio:{contentType:mimeTypeForCodec(audioCodec,'audio'),channels:''+channelsNumber}}}))}}))}),Promise.all(configurations.map(function(configuration){var decodingInfoKey=getMediaDecodingInfoKey(configuration);return SUPPORTED_INFO_CACHE[decodingInfoKey]||(SUPPORTED_INFO_CACHE[decodingInfoKey]=mediaCapabilities.decodingInfo(configuration))})).then(function(decodingInfoResults){return{supported:!decodingInfoResults.some(function(info){return!info.supported}),configurations:configurations,decodingInfoResults:decodingInfoResults}}).catch(function(error){return{supported:!1,configurations:configurations,decodingInfoResults:[],error:error}})}function getMediaDecodingInfoKey(config){var audio=config.audio,video=config.video,mediaConfig=video||audio;if(mediaConfig){var codec=mediaConfig.contentType.split('"')[1];if(video)return'r'+video.height+'x'+video.width+'f'+Math.ceil(video.framerate)+(video.transferFunction||'sd')+'_'+codec+'_'+Math.ceil(video.bitrate/1e5);if(audio)return'c'+audio.channels+(audio.spatialRendering?'s':'n')+'_'+codec}return''}function isHdrSupported(){if('function'==typeof matchMedia){var mediaQueryList=matchMedia('(dynamic-range: high)'),badQuery=matchMedia('bad query');if(mediaQueryList.media!==badQuery.media)return!0===mediaQueryList.matches}return!1}function getVideoSelectionOptions(currentVideoRange,videoPreference){var preferHDR=!1,allowedVideoRanges=[];return currentVideoRange&&(preferHDR='SDR'!==currentVideoRange,allowedVideoRanges=[currentVideoRange]),videoPreference&&(allowedVideoRanges=videoPreference.allowedVideoRanges||VideoRangeValues.slice(0),preferHDR=void 0===videoPreference.preferHDR?isHdrSupported():videoPreference.preferHDR,allowedVideoRanges=preferHDR?allowedVideoRanges.filter(function(range){return'SDR'!==range}):['SDR']),{preferHDR:preferHDR,allowedVideoRanges:allowedVideoRanges}}function getStartCodecTier(codecTiers,currentVideoRange,currentBw,audioPreference,videoPreference){for(var codecSets=Object.keys(codecTiers),channelsPreference=null==audioPreference?void 0:audioPreference.channels,audioCodecPreference=null==audioPreference?void 0:audioPreference.audioCodec,preferStereo=channelsPreference&&2===parseInt(channelsPreference),hasStereo=!0,hasCurrentVideoRange=!1,minHeight=Infinity,minFramerate=Infinity,minBitrate=Infinity,selectedScore=0,videoRanges=[],_getVideoSelectionOpt=getVideoSelectionOptions(currentVideoRange,videoPreference),preferHDR=_getVideoSelectionOpt.preferHDR,allowedVideoRanges=_getVideoSelectionOpt.allowedVideoRanges,_loop=function(){var tier=codecTiers[codecSets[i]];hasStereo=0<tier.channels[2],minHeight=Math.min(minHeight,tier.minHeight),minFramerate=Math.min(minFramerate,tier.minFramerate),minBitrate=Math.min(minBitrate,tier.minBitrate);var matchingVideoRanges=allowedVideoRanges.filter(function(range){return 0<tier.videoRanges[range]});0<matchingVideoRanges.length&&(hasCurrentVideoRange=!0,videoRanges=matchingVideoRanges)},i=codecSets.length;i--;)_loop();minHeight=isFiniteNumber(minHeight)?minHeight:0,minFramerate=isFiniteNumber(minFramerate)?minFramerate:0;var maxHeight=Math.max(1080,minHeight),maxFramerate=Math.max(30,minFramerate);minBitrate=isFiniteNumber(minBitrate)?minBitrate:currentBw,currentBw=Math.max(minBitrate,currentBw),hasCurrentVideoRange||(currentVideoRange=void 0,videoRanges=[]);var codecSet=codecSets.reduce(function(selected,candidate){var candidateTier=codecTiers[candidate];if(candidate===selected)return selected;if(candidateTier.minBitrate>currentBw)return logStartCodecCandidateIgnored(candidate,'min bitrate of '+candidateTier.minBitrate+' > current estimate of '+currentBw),selected;if(!candidateTier.hasDefaultAudio)return logStartCodecCandidateIgnored(candidate,'no renditions with default or auto-select sound found'),selected;if(audioCodecPreference&&0!=candidate.indexOf(audioCodecPreference.substring(0,4))%5)return logStartCodecCandidateIgnored(candidate,'audio codec preference "'+audioCodecPreference+'" not found'),selected;if(channelsPreference&&!preferStereo){if(!candidateTier.channels[channelsPreference])return logStartCodecCandidateIgnored(candidate,'no renditions with '+channelsPreference+' channel sound found (channels options: '+Object.keys(candidateTier.channels)+')'),selected;}else if((!audioCodecPreference||preferStereo)&&hasStereo&&0===candidateTier.channels[2])return logStartCodecCandidateIgnored(candidate,'no renditions with stereo sound found'),selected;return candidateTier.minHeight>maxHeight?(logStartCodecCandidateIgnored(candidate,'min resolution of '+candidateTier.minHeight+' > maximum of '+maxHeight),selected):candidateTier.minFramerate>maxFramerate?(logStartCodecCandidateIgnored(candidate,'min framerate of '+candidateTier.minFramerate+' > maximum of '+maxFramerate),selected):videoRanges.some(function(range){return 0<candidateTier.videoRanges[range]})?candidateTier.maxScore<selectedScore?(logStartCodecCandidateIgnored(candidate,'max score of '+candidateTier.maxScore+' < selected max of '+selectedScore),selected):selected&&(codecsSetSelectionPreferenceValue(candidate)>=codecsSetSelectionPreferenceValue(selected)||candidateTier.fragmentError>codecTiers[selected].fragmentError)?selected:(selectedScore=candidateTier.maxScore,candidate):(logStartCodecCandidateIgnored(candidate,'no variants with VIDEO-RANGE of '+JSON.stringify(videoRanges)+' found'),selected)},void 0);return{codecSet:codecSet,videoRanges:videoRanges,preferHDR:preferHDR,minFramerate:minFramerate,minBitrate:minBitrate}}function logStartCodecCandidateIgnored(codeSet,reason){logger.log('[abr] start candidates with "'+codeSet+'" ignored because '+reason)}function getAudioTracksByGroup(allAudioTracks){return allAudioTracks.reduce(function(audioTracksByGroup,track){var trackGroup=audioTracksByGroup.groups[track.groupId];trackGroup||(trackGroup=audioTracksByGroup.groups[track.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),trackGroup.tracks.push(track);var channelsKey=track.channels||'2';return trackGroup.channels[channelsKey]=(trackGroup.channels[channelsKey]||0)+1,trackGroup.hasDefault=trackGroup.hasDefault||track.default,trackGroup.hasAutoSelect=trackGroup.hasAutoSelect||track.autoselect,trackGroup.hasDefault&&(audioTracksByGroup.hasDefaultAudio=!0),trackGroup.hasAutoSelect&&(audioTracksByGroup.hasAutoSelectAudio=!0),audioTracksByGroup},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function getCodecTiers(levels,audioTracksByGroup,minAutoLevel,maxAutoLevel){return levels.slice(minAutoLevel,maxAutoLevel+1).reduce(function(tiers,level){if(!level.codecSet)return tiers;var audioGroups=level.audioGroups,tier=tiers[level.codecSet];tier||(tiers[level.codecSet]=tier={minBitrate:Infinity,minHeight:Infinity,minFramerate:Infinity,maxScore:0,videoRanges:{SDR:0},channels:{'2':0},hasDefaultAudio:!audioGroups,fragmentError:0}
1),tier.minBitrate=Math.min(tier.minBitrate,level.bitrate);var lesserWidthOrHeight=Math.min(level.height,level.width);return tier.minHeight=Math.min(tier.minHeight,lesserWidthOrHeight),tier.minFramerate=Math.min(tier.minFramerate,level.frameRate),tier.maxScore=Math.max(tier.maxScore,level.score),tier.fragmentError+=level.fragmentError,tier.videoRanges[level.videoRange]=(tier.videoRanges[level.videoRange]||0)+1,audioGroups&&audioGroups.forEach(function(audioGroupId){if(audioGroupId){var audioGroup=audioTracksByGroup.groups[audioGroupId];audioGroup&&(tier.hasDefaultAudio=tier.hasDefaultAudio||audioTracksByGroup.hasDefaultAudio?audioGroup.hasDefault:audioGroup.hasAutoSelect||!audioTracksByGroup.hasDefaultAudio&&!audioTracksByGroup.hasAutoSelectAudio,Object.keys(audioGroup.channels).forEach(function(channels){tier.channels[channels]=(tier.channels[channels]||0)+audioGroup.channels[channels]}))}}),tiers},{})}function findMatchingOption(option,tracks,matchPredicate){if('attrs'in option){var index=tracks.indexOf(option);if(-1!==index)return index}for(var i=0,_track;i<tracks.length;i++)if(_track=tracks[i],matchesOption(option,_track,matchPredicate))return i;return-1}function matchesOption(option,track,matchPredicate){var groupId=option.groupId,name=option.name,lang=option.lang,assocLang=option.assocLang,characteristics=option.characteristics,isDefault=option.default,forced=option.forced;return(void 0===groupId||track.groupId===groupId)&&(void 0===name||track.name===name)&&(void 0===lang||track.lang===lang)&&(void 0===lang||track.assocLang===assocLang)&&(void 0===isDefault||track.default===isDefault)&&(void 0===forced||track.forced===forced)&&(void 0===characteristics||characteristicsMatch(characteristics,track.characteristics))&&(void 0===matchPredicate||matchPredicate(option,track))}function characteristicsMatch(characteristicsA,characteristicsB){void 0===characteristicsB&&(characteristicsB='');var arrA=characteristicsA.split(','),arrB=characteristicsB.split(',');return arrA.length===arrB.length&&!arrA.some(function(el){return-1===arrB.indexOf(el)})}function audioMatchPredicate(option,track){var audioCodec=option.audioCodec,channels=option.channels;return(void 0===audioCodec||(track.audioCodec||'').substring(0,4)===audioCodec.substring(0,4))&&(void 0===channels||channels===(track.channels||'2'))}function findClosestLevelWithAudioGroup(option,levels,allAudioTracks,searchIndex,matchPredicate){var currentLevel=levels[searchIndex],variants=levels.reduce(function(variantMap,level,index){var uri=level.uri,renditions=variantMap[uri]||(variantMap[uri]=[]);return renditions.push(index),variantMap},{}),renditions=variants[currentLevel.uri];1<renditions.length&&(searchIndex=Math.max.apply(Math,renditions));var currentVideoRange=currentLevel.videoRange,currentFrameRate=currentLevel.frameRate,currentVideoCodec=currentLevel.codecSet.substring(0,4),matchingVideo=searchDownAndUpList(levels,searchIndex,function(level){if(level.videoRange!==currentVideoRange||level.frameRate!==currentFrameRate||level.codecSet.substring(0,4)!==currentVideoCodec)return!1;var audioGroups=level.audioGroups,tracks=allAudioTracks.filter(function(track){return!audioGroups||-1!==audioGroups.indexOf(track.groupId)});return-1<findMatchingOption(option,tracks,matchPredicate)});return-1<matchingVideo?matchingVideo:searchDownAndUpList(levels,searchIndex,function(level){var audioGroups=level.audioGroups,tracks=allAudioTracks.filter(function(track){return!audioGroups||-1!==audioGroups.indexOf(track.groupId)});return-1<findMatchingOption(option,tracks,matchPredicate)})}function searchDownAndUpList(arr,searchIndex,predicate){for(var i=searchIndex;-1<i;i--)if(predicate(arr[i]))return i;for(var _i=searchIndex+1;_i<arr.length;_i++)if(predicate(arr[_i]))return _i;return-1}function isPartial(fragmentEntity){var _fragmentEntity$range,_fragmentEntity$range2,_fragmentEntity$range3;return fragmentEntity.buffered&&(fragmentEntity.body.gap||(null==(_fragmentEntity$range=fragmentEntity.range.video)?void 0:_fragmentEntity$range.partial)||(null==(_fragmentEntity$range2=fragmentEntity.range.audio)?void 0:_fragmentEntity$range2.partial)||(null==(_fragmentEntity$range3=fragmentEntity.range.audiovideo)?void 0:_fragmentEntity$range3.partial))}
1function getFragmentKey(fragment){return fragment.type+'_'+fragment.level+'_'+fragment.sn}function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}function findFirstFragWithCC(fragments,cc){for(var i=0,len=fragments.length;i<len;i++){var _fragments$i;if((null==(_fragments$i=fragments[i])?void 0:_fragments$i.cc)===cc)return fragments[i]}return null}function shouldAlignOnDiscontinuities(lastFrag,switchDetails,details){return!!(switchDetails&&(details.endCC>details.startCC||lastFrag&&lastFrag.cc<details.startCC))}function findDiscontinuousReferenceFrag(prevDetails,curDetails){var prevFrags=prevDetails.fragments,curFrags=curDetails.fragments;if(!curFrags.length||!prevFrags.length)return void logger.log('No fragments to align');var prevStartFrag=findFirstFragWithCC(prevFrags,curFrags[0].cc);return prevStartFrag&&(!prevStartFrag||prevStartFrag.startPTS)?prevStartFrag:void logger.log('No frag in previous level to align on')}function adjustFragmentStart(frag,sliding){if(frag){var start=frag.start+sliding;frag.start=frag.startPTS=start,frag.endPTS=start+frag.duration}}function adjustSlidingStart(sliding,details){for(var fragments=details.fragments,i=0,len=fragments.length;i<len;i++)adjustFragmentStart(fragments[i],sliding);details.fragmentHint&&adjustFragmentStart(details.fragmentHint,sliding),details.alignedSliding=!0}function alignStream(lastFrag,switchDetails,details){switchDetails&&(alignDiscontinuities(lastFrag,details,switchDetails),!details.alignedSliding&&switchDetails&&alignMediaPlaylistByPDT(details,switchDetails),!details.alignedSliding&&switchDetails&&!details.skippedSegments&&adjustSliding(switchDetails,details))}function alignDiscontinuities(lastFrag,details,switchDetails){if(shouldAlignOnDiscontinuities(lastFrag,switchDetails,details)){var referenceFrag=findDiscontinuousReferenceFrag(switchDetails,details);referenceFrag&&isFiniteNumber(referenceFrag.start)&&(logger.log('Adjusting PTS using last level due to CC increase within current level '+details.url),adjustSlidingStart(referenceFrag.start,details))}}function alignMediaPlaylistByPDT(details,refDetails){if(details.hasProgramDateTime&&refDetails.hasProgramDateTime){var fragments=details.fragments,refFragments=refDetails.fragments;if(fragments.length&&refFragments.length){var targetCC=Math.min(refDetails.endCC,details.endCC),refFrag,frag;refDetails.startCC<targetCC&&details.startCC<targetCC&&(refFrag=findFirstFragWithCC(refFragments,targetCC),frag=findFirstFragWithCC(fragments,targetCC)),refFrag&&frag||(refFrag=refFragments[Math.floor(refFragments.length/2)],frag=findFirstFragWithCC(fragments,refFrag.cc)||fragments[Math.floor(fragments.length/2)]);var refPDT=refFrag.programDateTime,targetPDT=frag.programDateTime;if(refPDT&&targetPDT){var delta=(targetPDT-refPDT)/1e3-(frag.start-refFrag.start);adjustSlidingStart(delta,details)}}}}function createLoaderContext(frag,part){void 0===part&&(part=null);var segment=part||frag,loaderContext={frag:frag,part:part,responseType:'arraybuffer',url:segment.url,headers:{},rangeStart:0,rangeEnd:0},start=segment.byteRangeStartOffset,end=segment.byteRangeEndOffset;if(isFiniteNumber(start)&&isFiniteNumber(end)){var byteRangeStart=start,byteRangeEnd=end,_frag$decryptdata;if('initSegment'===frag.sn&&'AES-128'===(null==(_frag$decryptdata=frag.decryptdata)?void 0:_frag$decryptdata.method)){var fragmentLen=end-start;fragmentLen%16&&(byteRangeEnd=end+(16-fragmentLen%16)),0!==start&&(loaderContext.resetIV=!0,byteRangeStart=start-16)}loaderContext.rangeStart=byteRangeStart,loaderContext.rangeEnd=byteRangeEnd}return loaderContext}function createGapLoadError(frag,part){var error=new Error('GAP '+(frag.gap?'tag':'attribute')+' found'),errorData={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:frag,error:error,networkDetails:null};return part&&(errorData.part=part),(part?part:frag).stats.aborted=!0,new LoadError(errorData)}function removePadding(array){var outputBytes=array.byteLength,paddingBytes=outputBytes&&new DataView(array.buffer).getUint8(outputBytes-1);return paddingBytes?sliceUint8(array,0,outputBytes-paddingBytes):array}function concatUint8Arrays(chunks,dataLength){for(var result=new Uint8Array(dataLength),offset=0,i=0,chunk;i<chunks.length;i++)chunk=chunks[i],result.set(chunk,offset),offset+=chunk.length;return result}function dummyTrack(type,inputTimeScale){return void 0===type&&(type=''),void 0===inputTimeScale&&(inputTimeScale=9e4),{type:type,id:-1,pid:-1,inputTimeScale:inputTimeScale,sequenceNumber:-1,samples:[],dropped:0}}function getAudioConfig(observer,data,offset,audioCodec){var userAgent=navigator.userAgent.toLowerCase(),adtsSamplingRates=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],adtsObjectType,adtsExtensionSamplingIndex,adtsChannelConfig,config;adtsObjectType=((192&data[offset+2])>>>6)+1;var adtsSamplingIndex=(60&data[offset+2])>>>2;if(adtsSamplingIndex>adtsSamplingRates.length-1){var error=new Error('invalid ADTS sampling index:'+adtsSamplingIndex);return void observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,error:error,reason:error.message})}return adtsChannelConfig=(1&data[offset+2])<<2,adtsChannelConfig|=(192&data[offset+3])>>>6,logger.log('manifest codec:'+audioCodec+', ADTS type:'+adtsObjectType+', samplingIndex:'+adtsSamplingIndex),/firefox/i.test(userAgent)?6<=adtsSamplingIndex?(adtsObjectType=5,config=[,,,,],adtsExtensionSamplingIndex=adtsSamplingIndex-3):(adtsObjectType=2,config=[,,],adtsExtensionSamplingIndex=adtsSamplingIndex):-1===userAgent.indexOf('android')?(adtsObjectType=5,config=[,,,,],audioCodec&&(-1!==audioCodec.indexOf('mp4a.40.29')||-1!==audioCodec.indexOf('mp4a.40.5'))||!audioCodec&&
16<=adtsSamplingIndex?adtsExtensionSamplingIndex=adtsSamplingIndex-3:((audioCodec&&-1!==audioCodec.indexOf('mp4a.40.2')&&(6<=adtsSamplingIndex&&1===adtsChannelConfig||/vivaldi/i.test(userAgent))||!audioCodec&&1===adtsChannelConfig)&&(adtsObjectType=2,config=[,,]),adtsExtensionSamplingIndex=adtsSamplingIndex)):(adtsObjectType=2,config=[,,],adtsExtensionSamplingIndex=adtsSamplingIndex),config[0]=adtsObjectType<<3,config[0]|=(14&adtsSamplingIndex)>>1,config[1]|=(1&adtsSamplingIndex)<<7,config[1]|=adtsChannelConfig<<3,5===adtsObjectType&&(config[1]|=(14&adtsExtensionSamplingIndex)>>1,config[2]=(1&adtsExtensionSamplingIndex)<<7,config[2]|=8,config[3]=0),{config:config,samplerate:adtsSamplingRates[adtsSamplingIndex],channelCount:adtsChannelConfig,codec:'mp4a.40.'+adtsObjectType,manifestCodec:audioCodec}}function isHeaderPattern$1(data,offset){return 255===data[offset]&&240==(246&data[offset+1])}function getHeaderLength(data,offset){return 1&data[offset+1]?7:9}function getFullFrameLength(data,offset){return(3&data[offset+3])<<11|data[offset+4]<<3|(224&data[offset+5])>>>5}function canGetFrameLength(data,offset){return offset+5<data.length}function isHeader$1(data,offset){return offset+1<data.length&&isHeaderPattern$1(data,offset)}function canParse$1(data,offset){return canGetFrameLength(data,offset)&&isHeaderPattern$1(data,offset)&&getFullFrameLength(data,offset)<=data.length-offset}function probe$1(data,offset){if(isHeader$1(data,offset)){var headerLength=getHeaderLength(data,offset);if(offset+headerLength>=data.length)return!1;var frameLength=getFullFrameLength(data,offset);if(frameLength<=headerLength)return!1;var newOffset=offset+frameLength;return newOffset===data.length||isHeader$1(data,newOffset)}return!1}function initTrackConfig(track,observer,data,offset,audioCodec){if(!track.samplerate){var config=getAudioConfig(observer,data,offset,audioCodec);if(!config)return;track.config=config.config,track.samplerate=config.samplerate,track.channelCount=config.channelCount,track.codec=config.codec,track.manifestCodec=config.manifestCodec,logger.log('parsed codec:'+track.codec+', rate:'+config.samplerate+', channels:'+config.channelCount)}
1}function getFrameDuration(samplerate){return 92160000/samplerate}function parseFrameHeader(data,offset){var headerLength=getHeaderLength(data,offset);if(offset+headerLength<=data.length){var frameLength=getFullFrameLength(data,offset)-headerLength;if(0<frameLength)return{headerLength:headerLength,frameLength:frameLength}}}function appendFrame$1(track,data,offset,pts,frameIndex){var frameDuration=getFrameDuration(track.samplerate),stamp=pts+frameIndex*frameDuration,header=parseFrameHeader(data,offset),unit;if(header){var frameLength=header.frameLength,headerLength=header.headerLength,_length=headerLength+frameLength,missing=Math.max(0,offset+_length-data.length);missing?(unit=new Uint8Array(_length-headerLength),unit.set(data.subarray(offset+headerLength,data.length),0)):unit=data.subarray(offset+headerLength,offset+_length);var _sample={unit:unit,pts:stamp};return missing||track.samples.push(_sample),{sample:_sample,length:_length,missing:missing}}var length=data.length-offset;unit=new Uint8Array(length),unit.set(data.subarray(offset,data.length),0);var sample={unit:unit,pts:stamp};return{sample:sample,length:length,missing:-1}}function appendFrame(track,data,offset,pts,frameIndex){if(!(offset+24>data.length)){var header=parseHeader(data,offset);if(header&&offset+header.frameLength<=data.length){var frameDuration=9e4*header.samplesPerFrame/header.sampleRate,stamp=pts+frameIndex*frameDuration,sample={unit:data.subarray(offset,offset+header.frameLength),pts:stamp,dts:stamp};return track.config=[],track.channelCount=header.channelCount,track.samplerate=header.sampleRate,track.samples.push(sample),{sample:sample,length:header.frameLength,missing:0}}}}function parseHeader(data,offset){var mpegVersion=3&data[offset+1]>>3,mpegLayer=3&data[offset+1]>>1,bitRateIndex=15&data[offset+2]>>4,sampleRateIndex=3&data[offset+2]>>2;if(1!=mpegVersion&&0!=bitRateIndex&&15!=bitRateIndex&&3!=sampleRateIndex){var paddingBit=1&data[offset+2]>>1,channelMode=data[offset+3]>>6,columnInBitrates=3==mpegVersion?3-mpegLayer:3==mpegLayer?3:4,bitRate=1e3*BitratesMap[14*columnInBitrates+bitRateIndex-1],columnInSampleRates=3==mpegVersion?0:2==mpegVersion?1:2,sampleRate=SamplingRateMap[3*columnInSampleRates+sampleRateIndex],channelCount=3===channelMode?1:2,sampleCoefficient=SamplesCoefficients[mpegVersion][mpegLayer],bytesInSlot=BytesInSlot[mpegLayer],frameLength=Math.floor(sampleCoefficient*bitRate/sampleRate+paddingBit)*bytesInSlot;if(null===chromeVersion$1){var userAgent=navigator.userAgent||'',result=userAgent.match(/Chrome\/(\d+)/i);chromeVersion$1=result?parseInt(result[1]):0}var needChromeFix=!!chromeVersion$1&&87>=chromeVersion$1;return needChromeFix&&2==mpegLayer&&224e3<=bitRate&&0==channelMode&&(data[offset+3]=128|data[offset+3]),{sampleRate:sampleRate,channelCount:channelCount,frameLength:frameLength,samplesPerFrame:8*sampleCoefficient*bytesInSlot}}}function isHeaderPattern(data,offset){return 255===data[offset]&&224==(224&data[offset+1])&&0!=(6&data[offset+1])}function isHeader(data,offset){return offset+1<data.length&&isHeaderPattern(data,offset)}function canParse(data,offset){return isHeaderPattern(data,offset)&&4<=data.length-offset}function probe(data,offset){if(offset+1<data.length&&isHeaderPattern(data,offset)){var header=parseHeader(data,offset),frameLength=4;null!=header&&header.frameLength&&(frameLength=header.frameLength);var newOffset=offset+frameLength;return newOffset===data.length||isHeader(data,newOffset)}return!1}function _appendFrame(track,data,start,pts,frameIndex){if(start+8>data.length)return-1;if(11!==data[start]||119!==data[start+1])return-1;var samplingRateCode=data[start+4]>>6;if(3<=samplingRateCode)return-1;var sampleRate=[48e3,44100,32e3][samplingRateCode],frameSizeCode=63&data[start+4],frameLength=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*frameSizeCode+samplingRateCode];if(start+frameLength>data.length)return-1;var channelMode=data[start+6]>>5,skipCount=0;2==channelMode?skipCount+=2:(1&channelMode&&1!=channelMode&&(skipCount+=2),4&
1channelMode&&(skipCount+=2));var lfeon=1&(data[start+6]<<8|data[start+7])>>12-skipCount,channelCount=[2,1,2,3,3,4,4,5][channelMode]+lfeon,bsid=data[start+5]>>3,bsmod=7&data[start+5],config=new Uint8Array([samplingRateCode<<6|bsid<<1|bsmod>>2,(3&bsmod)<<6|channelMode<<3|lfeon<<2|frameSizeCode>>4,224&frameSizeCode<<4]),unit=data.subarray(start,start+frameLength);return track.config=config,track.channelCount=channelCount,track.samplerate=sampleRate,track.samples.push({unit:unit,pts:pts+frameIndex*(9e4*(1536/sampleRate))}),frameLength}function parsePID(data,offset){return((31&data[offset+1])<<8)+data[offset+2]}function parsePAT(data,offset){return(31&data[offset+10])<<8|data[offset+11]}function parsePMT(data,offset,typeSupported,isSampleAes,observer){var result={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:'avc',segmentAudioCodec:'aac'},sectionLength=(15&data[offset+1])<<8|data[offset+2],tableEnd=offset+3+sectionLength-4,programInfoLength=(15&data[offset+10])<<8|data[offset+11];for(offset+=12+programInfoLength;offset<tableEnd;){var pid=parsePID(data,offset),esInfoLength=(15&data[offset+3])<<8|data[offset+4];switch(data[offset]){case 207:if(!isSampleAes){logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');break}case 15:-1===result.audioPid&&(result.audioPid=pid);break;case 21:-1===result.id3Pid&&(result.id3Pid=pid);break;case 219:if(!isSampleAes){logEncryptedSamplesFoundInUnencryptedStream('H.264');break}case 27:-1===result.videoPid&&(result.videoPid=pid,result.segmentVideoCodec='avc');break;case 3:case 4:typeSupported.mpeg||typeSupported.mp3?-1===result.audioPid&&(result.audioPid=pid,result.segmentAudioCodec='mp3'):logger.log('MPEG audio found, not supported in this browser');break;case 193:if(!isSampleAes){logEncryptedSamplesFoundInUnencryptedStream('AC-3');break}case 129:typeSupported.ac3?-1===result.audioPid&&(result.audioPid=pid,result.segmentAudioCodec='ac3'):logger.log('AC-3 audio found, not supported in this browser');break;case 6:if(-1===result.audioPid&&0<esInfoLength)for(var parsePos=offset+5,remaining=esInfoLength,descriptorId;2<remaining;){descriptorId=data[parsePos],106===descriptorId?!0===typeSupported.ac3?(result.audioPid=pid,result.segmentAudioCodec='ac3'):logger.log('AC-3 audio found, not supported in this browser for now'):void 0;var descriptorLen=data[parsePos+1]+2;parsePos+=descriptorLen,remaining-=descriptorLen}break;case 194:case 135:return emitParsingError(observer,new Error('Unsupported EC-3 in M2TS found')),result;case 36:return emitParsingError(observer,new Error('Unsupported HEVC in M2TS found')),result;}offset+=esInfoLength+5}return result}function emitParsingError(observer,error,levelRetry){logger.warn('parsing error: '+error.message),observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,levelRetry:levelRetry,error:error,reason:error.message})}function logEncryptedSamplesFoundInUnencryptedStream(type){logger.log(type+' with AES-128-CBC encryption found in unencrypted stream')}function parsePES(stream){var i=0,data=stream.data,frag,pesLen,pesHdrLen,pesPts,pesDts;if(!stream||0===stream.size)return null;for(;19>data[0].length&&1<data.length;)data[0]=appendUint8Array(data[0],data[1]),data.splice(1,1);frag=data[0];var pesPrefix=(frag[0]<<16)+(frag[1]<<8)+frag[2];if(1===pesPrefix){if(pesLen=(frag[4]<<8)+frag[5],pesLen&&pesLen>stream.size-6)return null;var pesFlags=frag[7];192&pesFlags&&(pesPts=536870912*(14&frag[9])+4194304*(255&frag[10])+16384*(254&frag[11])+128*(255&frag[12])+(254&frag[13])/2,64&pesFlags?(pesDts=536870912*(14&frag[14])+4194304*(255&frag[15])+16384*(254&frag[16])+128*(255&frag[17])+(254&frag[18])/2,5400000<pesPts-pesDts&&(logger.warn(Math.round((pesPts-pesDts)/9e4)+'s delta between PTS and DTS, align them'),pesPts=pesDts)):pesDts=pesPts),pesHdrLen=frag[8];var payloadStartOffset=pesHdrLen+9;if(stream.size<=payloadStartOffset)return null;stream.size-=payloadStartOffset;for(var pesData=new Uint8Array(stream.size),j=0,dataLen=data.length;j<dataLen;j++){frag=data[j];var len=frag.byteLength;if(payloadStartOffset)if(payloadStartOffset>len){payloadStartOffset-=len;continue}else frag=frag.subarray(payloadStartOffset),len-=payloadStartOffset,payloadStartOffset=0;pesData.set(frag,i),i+=len}return pesLen&&(pesLen-=pesHdrLen+3),{data:pesData,pts:pesPts,dts:pesDts,len:pesLen}}return null}function toTimescaleFromBase(baseTime,destScale,srcBase,round){void 0===srcBase&&(srcBase=1),void 0===round&&(round=!1);var result=baseTime*destScale*srcBase;return round?Math.round(result):result}function toTimescaleFromScale(baseTime,destScale,srcScale,round){return void 0===srcScale&&(srcScale=1),void 0===round&&(round=!1),toTimescaleFromBase(baseTime,destScale,1/srcScale,round)}function toMsFromMpegTsClock(baseTime,round){return void 0===round&&(round=!1),toTimescaleFromBase(baseTime,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,roun
1d)}function toMpegTsClockFromTimescale(baseTime,srcScale){return void 0===srcScale&&(srcScale=1),toTimescaleFromBase(baseTime,MPEG_TS_CLOCK_FREQ_HZ,1/srcScale)}function normalizePts(value,reference){var offset;if(null===reference)return value;for(offset=reference<value?-8589934592:8589934592;4294967296<Math.abs(value-reference);)value+=offset;return value}function findKeyframeIndex(samples){for(var i=0;i<samples.length;i++)if(samples[i].key)return i;return-1}function flushTextTrackMetadataCueSamples(track,timeOffset,initPTS,initDTS){var length=track.samples.length;if(length){for(var inputTimeScale=track.inputTimeScale,index=0,sample;index<length;index++)sample=track.samples[index],sample.pts=normalizePts(sample.pts-initPTS.baseTime*inputTimeScale/initPTS.timescale,timeOffset*inputTimeScale)/inputTimeScale,sample.dts=normalizePts(sample.dts-initDTS.baseTime*inputTimeScale/initDTS.timescale,timeOffset*inputTimeScale)/inputTimeScale;var samples=track.samples;return track.samples=[],{samples:samples}}}function flushTextTrackUserdataCueSamples(track,timeOffset,initPTS){var length=track.samples.length;if(length){for(var inputTimeScale=track.inputTimeScale,index=0,sample;index<length;index++)sample=track.samples[index],sample.pts=normalizePts(sample.pts-initPTS.baseTime*inputTimeScale/initPTS.timescale,timeOffset*inputTimeScale)/inputTimeScale;track.samples.sort(function(a,b){return a.pts-b.pts});var samples=track.samples;return track.samples=[],{samples:samples}}}function isInvalidInitPts(initPTS,startDTS,timeOffset,duration){if(null===initPTS)return!0;var minDuration=Math.max(duration,1),startTime=startDTS-initPTS.baseTime/initPTS.timescale;return Math.abs(startTime-timeOffset)>minDuration}function getParsedTrackCodec(track,type){var parsedCodec=null==track?void 0:track.codec;if(parsedCodec&&4<parsedCodec.length)return parsedCodec;if(type===ElementaryStreamTypes.AUDIO){if('ec-3'===parsedCodec||'ac-3'===parsedCodec||'alac'===parsedCodec)return parsedCodec;if('fLaC'===parsedCodec||'Opus'===parsedCodec){return getCodecCompatibleName(parsedCodec,!1)}var result='mp4a.40.5';return logger.info('Parsed audio codec "'+parsedCodec+'" or audio object type not handled. Using "'+result+'"'),result}return logger.warn('Unhandled video codec "'+parsedCodec+'"'),'hvc1'===parsedCodec||'hev1'===parsedCodec?'hvc1.1.6.L120.90':'av01'===parsedCodec?'av01.0.04M.08':'avc1.42e01e'}function getEncryptionType(data,decryptData){var encryptionType=null;return 0<data.byteLength&&null!=(null==decryptData?void 0:decryptData.key)&&null!==decryptData.iv&&null!=decryptData.method&&(encryptionType=decryptData),encryptionType}function isPromise(p){return'then'in p&&p.then instanceof Function}function emitTransmuxComplete(self,transmuxResult){if(isEmptyResult(transmuxResult.remuxResult))return!1;var transferable=[],_transmuxResult$remux=transmuxResult.remuxResult,audio=_transmuxResult$remux.audio,video=_transmuxResult$remux.video;return audio&&addToTransferable(transferable,audio),video&&addToTransferable(transferable,video),self.postMessage({event:'transmuxComplete',data:transmuxResult},transferable),!0}function addToTransferable(transferable,track){track.data1&&transferable.push(track.data1.buffer),track.data2&&transferable.push(track.data2.buffer)}function handleFlushResult(self,results,chunkMeta){var parsed=results.reduce(function(parsed,result){return emitTransmuxComplete(self,result)||parsed},!1);parsed||self.postMessage({event:'transmuxComplete',data:results[0]}),self.postMessage({event:'flush',data:chunkMeta})}function isEmptyResult(remuxResult){return!remuxResult.audio&&!remuxResult.video&&!remuxResult.text&&!remuxResult.id3&&!remuxResult.initSegment}function hasUMDWorker(){return'function'==typeof __HLS_WORKER_BUNDLE__}function injectWorker(){var blob=new self.Blob(['var exports={};var module={exports:exports};function define(f){f()};define.amd=true;('+__HLS_WORKER_BUNDLE__.toString()+')(true);'],{type:'text/javascript'}),objectURL=self.URL.createObjectURL(blob),worker=new self.Worker(objectURL);return{worker:worker,objectURL:objectURL}}function loadWorker(path){var scriptURL=new self.URL(path,self.location.href).href,worker=new self.Worker(scriptURL);return{worker:worker,scriptURL:scriptURL}}function subtitleOptionsIdentical(trackList1,trackList2){if(trackList1.length!==trackList2.length)return!1;for(var i=0;i<trackList1.length;i++)if(!mediaAttributesIdentical(trackList1[i].attrs,trackList2[i].attrs))return!1;return!0}function mediaAttributesIdentical(attrs1,attrs2,customAttributes){var stableRenditionId=attrs1['STABLE-RENDITION-ID'];return stableRenditionId&&!customAttributes?stableRenditionId===attrs2['STABLE-RENDITION-ID']:!(customAttributes||['LANGUAGE','NAME','CHARACTERISTICS','AUTOSELECT','DEFAULT','FORCED','ASSOC-LANGUAGE']).some(function(subtitleAttribute){return attrs1[subtitleAttribute]!==attrs2[subt
1itleAttribute]})}function subtitleTrackMatchesTextTrack(subtitleTrack,textTrack){return textTrack.label.toLowerCase()===subtitleTrack.name.toLowerCase()&&(!textTrack.language||textTrack.language.toLowerCase()===(subtitleTrack.lang||'').toLowerCase())}function removeSourceChildren(node){var sourceChildren=node.querySelectorAll('source');[].slice.call(sourceChildren).forEach(function(source){node.removeChild(source)})}function addSource(media,url){var source=self.document.createElement('source');source.type='video/mp4',source.src=url,media.appendChild(source)}function setLastCmd(a,b,cmdHistory){cmdHistory.a=a,cmdHistory.b=b}function hasCmdRepeated(a,b,cmdHistory){return cmdHistory.a===a&&cmdHistory.b===b}function createCmdHistory(){return{a:null,b:null}}function parseTimeStamp(input){function computeSeconds(h,m,s,f){return 3600*(0|h)+60*(0|m)+(0|s)+parseFloat(f||0)}var m=input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return m?59<parseFloat(m[2])?computeSeconds(m[2],m[3],0,m[4]):computeSeconds(m[1],m[2],m[3],m[4]):null}function parseOptions(input,callback,keyValueDelim,groupDelim){var groups=groupDelim?input.split(groupDelim):[input];for(var i in groups)if('string'==typeof groups[i]){var kv=groups[i].split(keyValueDelim);if(2===kv.length){var _k=kv[0],_v=kv[1];callback(_k,_v)}}}function parseCue(input,cue,regionList){function consumeTimeStamp(){var ts=parseTimeStamp(input);if(null===ts)throw new Error('Malformed timestamp: '+oInput);return input=input.replace(/^[^\sa-zA-Z-]+/,''),ts}function consumeCueSettings(input,cue){var settings=new Settings;parseOptions(input,function(k,v){var vals;switch(k){case'region':for(var i=regionList.length-1;0<=i;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':vals=v.split(','),settings.integer(k,vals[0]),settings.percent(k,vals[0])&&settings.set('snapToLines',!1),settings.alt(k,vals[0],['auto']),2===vals.length&&settings.alt('lineAlign',vals[1],['start',center,'end']);break;case'position':vals=v.split(','),settings.percent(k,vals[0]),2===vals.length&&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']);}},/:/,/\s/),cue.region=settings.get('region',null),cue.vertical=settings.get('vertical','');var line=settings.get('line','auto');'auto'===line&&-1===defaults.line&&(line=-1),cue.line=line,cue.lineAlign=settings.get('lineAlign','start'),cue.snapToLines=settings.get('snapToLines',!0),cue.size=settings.get('size',100),cue.align=settings.get('align',center);var position=settings.get('position','auto');'auto'===position&&50===defaults.position&&(position='start'===cue.align||'left'===cue.align?0:'end'===cue.align||'right'===cue.align?100:50),cue.position=position}function skipWhitespace(){input=input.replace(/^\s+/,'')}var oInput=input;if(skipWhitespace(),cue.startTime=consumeTimeStamp(),skipWhitespace(),'-->'!==input.slice(0,3))throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): '+oInput);input=input.slice(3),skipWhitespace(),cue.endTime=consumeTimeStamp(),skipWhitespace(),consumeCueSettings(input,cue)}function fixLineBreaks(input){return input.replace(/<br(?: \/)?>/gi,'\n')}function generateCueId(startTime,endTime,text){return hash(startTime.toString())+hash(endTime.toString())+hash(text)}function parseWebVTT(vttByteArray,initPTS,vttCCs,cc,timeOffset,callBack,errorCallBack){var parser=new VTTParser,vttLines=utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS,'\n').split('\n'),cues=[],init90kHz=initPTS?toMpegTsClockFromTimescale(initPTS.baseTime,initPTS.timescale):0,cueTime='00:00.000',timestampMapMPEGTS=0,timestampMapLOCAL=0,inHeader=!0,parsingError;parser.oncue=function(cue){var currCC=vttCCs[cc],cueOffset=vttCCs.ccOffset,webVttMpegTsMapOffset=(timestampMapMPEGTS-init90kHz)/9e4;if(null!=currCC&&currCC.new&&(void 0===timestampMapLOCAL?calculateOffset(vttCCs,cc,webVttMpegTsMapOffset):cueOffset=vttCCs.ccOffset=currCC.start),webVttMpegTsMapOffset){if(!initPTS)return void(parsingError=new Error('Missing initPTS for VTT MPEGTS'));
1cueOffset=webVttMpegTsMapOffset-vttCCs.presentationOffset}var duration=cue.endTime-cue.startTime,startTime=normalizePts(9e4*(cue.startTime+cueOffset-timestampMapLOCAL),9e4*timeOffset)/9e4;cue.startTime=Math.max(startTime,0),cue.endTime=Math.max(startTime+duration,0);var text=cue.text.trim();cue.text=decodeURIComponent(encodeURIComponent(text)),cue.id||(cue.id=generateCueId(cue.startTime,cue.endTime,text)),0<cue.endTime&&cues.push(cue)},parser.onparsingerror=function(error){parsingError=error},parser.onflush=function(){return parsingError?void errorCallBack(parsingError):void callBack(cues)},vttLines.forEach(function(line){if(inHeader){if(startsWith(line,'X-TIMESTAMP-MAP=')){inHeader=!1,line.slice(16).split(',').forEach(function(timestamp){startsWith(timestamp,'LOCAL:')?cueTime=timestamp.slice(6):startsWith(timestamp,'MPEGTS:')&&(timestampMapMPEGTS=parseInt(timestamp.slice(7)))});try{timestampMapLOCAL=cueString2millis(cueTime)/1e3}catch(error){parsingError=error}return}''===line&&(inHeader=!1)}parser.parse(line+'\n')}),parser.flush()}function parseIMSC1(payload,initPTS,callBack,errorCallBack){var results=findBox(new Uint8Array(payload),['mdat']);if(0===results.length)return void errorCallBack(new Error('Could not parse IMSC1 mdat'));var ttmlList=results.map(function(mdat){return utf8ArrayToStr(mdat)}),syncTime=toTimescaleFromScale(initPTS.baseTime,1,initPTS.timescale);try{ttmlList.forEach(function(ttml){return callBack(parseTTML(ttml,syncTime))})}catch(error){errorCallBack(error)}}function parseTTML(ttml,syncTime){var parser=new DOMParser,xmlDoc=parser.parseFromString(ttml,'text/xml'),tt=xmlDoc.getElementsByTagName('tt')[0];if(!tt)throw new Error('Invalid ttml');var defaultRateInfo={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},rateInfo=Object.keys(defaultRateInfo).reduce(function(result,key){return result[key]=tt.getAttribute('ttp:'+key)||defaultRateInfo[key],result},{}),trim='preserve'!==tt.getAttribute('xml:space'),styleElements=collectionToDictionary(getElementCollection(tt,'styling','style')),regionElements=collectionToDictionary(getElementCollection(tt,'layout','region')),cueElements=getElementCollection(tt,'body','[begin]');return[].map.call(cueElements,function(cueElement){var cueText=getTextContent(cueElement,trim);if(!cueText||!cueElement.hasAttribute('begin'))return null;var startTime=parseTtmlTime(cueElement.getAttribute('begin'),rateInfo),duration=parseTtmlTime(cueElement.getAttribute('dur'),rateInfo),endTime=parseTtmlTime(cueElement.getAttribute('end'),rateInfo);if(null===startTime)throw timestampParsingError(cueElement);if(null===endTime){if(null===duration)throw timestampParsingError(cueElement);endTime=startTime+duration}var cue=new VTTCue(startTime-syncTime,endTime-syncTime,cueText);cue.id=generateCueId(cue.startTime,cue.endTime,cue.text);var region=regionElements[cueElement.getAttribute('region')],style=styleElements[cueElement.getAttribute('style')],styles=getTtmlStyles(region,style,styleElements),textAlign=styles.textAlign;if(textAlign){var lineAlign=textAlignToLineAlign[textAlign];lineAlign&&(cue.lineAlign=lineAlign),cue.align=textAlign}return _extends(cue,styles),cue}).filter(function(cue){return null!==cue})}function getElementCollection(fromElement,parentName,childName){var parent=fromElement.getElementsByTagName(parentName)[0];return parent?[].slice.call(parent.querySelectorAll(childName)):[]}function collectionToDictionary(elementsWithId){return elementsWithId.reduce(function(dict,element){var id=element.getAttribute('xml:id');return id&&(dict[id]=element),dict},{})}function getTextContent(element,trim){return[].slice.call(element.childNodes).reduce(function(str,node,i){var _node$childNodes;return'br'===node.nodeName&&i?str+'\n':null!=(_node$childNodes=node.childNodes)&&_node$childNodes.length?getTextContent(node,trim):trim?str+node.textContent.trim().replace(/\s+/g,' '):str+node.textContent},'')}function getTtmlStyles(region,style,styleElements){var ttsNs='http://www.w3.org/ns/ttml#styling',regionStyle=null,regionStyleName=null!=region&®ion.hasAttribute('style')?region.getAttribute('style'):null;return regionStyleName&&styleElements.hasOwnProperty(regionStyleName)&&(regionStyle=styleElements[regionStyleName]),['displayAlign','textAlign','color','backgroundColor','fontSize','fontFamily'].reduce(function(styles,name){var value=getAttributeNS(style,ttsNs,name)||getAttributeNS(region,tt
1sNs,name)||getAttributeNS(regionStyle,ttsNs,name);return value&&(styles[name]=value),styles},{})}function getAttributeNS(element,ns,name){return element?element.hasAttributeNS(ns,name)?element.getAttributeNS(ns,name):null:null}function timestampParsingError(node){return new Error('Could not parse ttml timestamp '+node)}function parseTtmlTime(timeAttributeValue,rateInfo){if(!timeAttributeValue)return null;var seconds=parseTimeStamp(timeAttributeValue);return null===seconds&&(HMSF_REGEX.test(timeAttributeValue)?seconds=parseHoursMinutesSecondsFrames(timeAttributeValue,rateInfo):TIME_UNIT_REGEX.test(timeAttributeValue)&&(seconds=parseTimeUnits(timeAttributeValue,rateInfo))),seconds}function parseHoursMinutesSecondsFrames(timeAttributeValue,rateInfo){var m=HMSF_REGEX.exec(timeAttributeValue),frames=(0|m[4])+(0|m[5])/rateInfo.subFrameRate;return 3600*(0|m[1])+60*(0|m[2])+(0|m[3])+frames/rateInfo.frameRate}function parseTimeUnits(timeAttributeValue,rateInfo){var m=TIME_UNIT_REGEX.exec(timeAttributeValue),value=+m[1],unit=m[2];return'h'===unit?3600*value:'m'===unit?60*value:'ms'===unit?1e3*value:'f'===unit?value/rateInfo.frameRate:'t'===unit?value/rateInfo.tickRate:value}function captionsOrSubtitlesFromCharacteristics(track){return track.characteristics&&/transcribes-spoken-dialog/gi.test(track.characteristics)&&/describes-music-and-sound/gi.test(track.characteristics)?'captions':'subtitles'}function canReuseVttTextTrack(inUseTrack,manifestTrack){return!!inUseTrack&&inUseTrack.kind===captionsOrSubtitlesFromCharacteristics(manifestTrack)&&subtitleTrackMatchesTextTrack(manifestTrack,inUseTrack)}function intersection(x1,x2,y1,y2){return Math.min(x2,y2)-Math.max(x1,y1)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}function format(value){return Array.isArray(value)?JSON.stringify(value):value instanceof Map?'Map{}':value instanceof Set?'Set{}':'object'==typeof value?JSON.stringify(value):value+''}function throwError(action,src,type,cause){return new Error('failed to '+action+' "'+format(src)+'" as '+type,{cause:cause})}function isInvalidInt(value){return-999999999999999>value||999999999999999<value}function serializeError(src,type,cause){return throwError('serialize',src,type,cause)}function serializeBoolean(value){if('boolean'!=typeof value)throw serializeError(value,BOOLEAN);return value?'?1':'?0'}function base64encode(binary){return btoa(String.fromCharCode.apply(String,binary))}function serializeByteSequence(value){if(!1===ArrayBuffer.isView(value))throw serializeError(value,BYTES);return':'+base64encode(value)+':'}function serializeInteger(value){if(isInvalidInt(value))throw serializeError(value,INTEGER);return value.toString()}function serializeDate(value){return'@'+serializeInteger(value.getTime()/1e3)}function roundToEven(value,precision){if(0>value)return-roundToEven(-value,precision);var decimalShift=Math.pow(10,precision),isEquidistant=Math.abs(value*decimalShift%1-.5)<Number.EPSILON;if(isEquidistant){var flooredValue=Math.floor(value*decimalShift);return(0==flooredValue%2?flooredValue:flooredValue+1)/decimalShift}return Math.round(value*decimalShift)/decimalShift}function serializeDecimal(value){var roundedValue=roundToEven(value,3);if(12<Math.floor(Math.abs(roundedValue)).toString().length)throw serializeError(value,DECIMAL);var stringValue=roundedValue.toString();return stringValue.includes('.')?stringValue:stringValue+'.0'}function serializeString(value){if(STRING_REGEX.test(value))throw serializeError(value,STRING);return'"'+value.replace(/\\/g,'\\\\').replace(/"/g,'\\"')+'"'}function symbolToStr(symbol){return symbol.description||symbol.toString().slice(7,-1)}function serializeToken(token){var value=symbolToStr(token);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value))throw serializeError(value,TOKEN);return value}function serializeBareItem(value){switch(typeof value){case'number':if(!isFiniteNumber(value))throw serializeError(value,BARE_ITEM);return Number.isInteger(value)?serializeInteger(value):serializeDecimal(value);case'string':return serializeString(value);case'symbol':return serializeToken(value);case'boolean':return serializeBoolean(value);case'object':if(value instanceof Date)return serializeDate(value);if(value instanceof Uint8Array)return serializeByteSequence(value);if(value instanceof SfToken)return serializeToken(value);default:throw serializeError(value,BARE_ITEM);}}function serializeKey(value){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(value))throw serializeError(value,KEY);return value}function serializeParams(params){return null==params?'':Object.entries(params).map(function(_ref){var key=_ref[0],value=_ref[1];return!0===value?';'+serializeKey(key):';'+serializeKey(key)+'='+serializeBareItem(value)}).join('')}function serializeItem(value){return value instanceof SfItem?''+serializeBareItem(value.value)+serializeParams(value.params):serializeBareItem(value)}function serializeInnerList(value){return'('+value.value.map(serializeItem).join(' ')+')'+serializeParams(value.params)}function serializeDict(dict,options){var _options;if(void 0===options&&(options={whitespace:!0}),'object'!=typeof dict)throw serializeError(dict,DICT);var entries=dict instanceof Map?dict.entries():Object.entries(dict),optionalWhiteSpace=null!=(_options=options)&&_options.whitespace?' ':'';return Array.from(entries).map(function(_ref){var key=_ref[0],item=_ref[1];!1==item instanceof SfItem&&(item=new SfItem(item));var output=serializeKey(key);return!0===item.value?output+=serializeParams(item.params):(output+='=',output+=Array.isArray(item.value)?serializeInnerList(item):serializeItem(item)),output}).join(','+optionalWhiteSpace)}function encodeSfDict(value,options){return serializeDict(value,options)}function urlToRelativePath(url,base){var to=new URL(url),from=new URL(base);if(to.origin!==from.origin)return url;for(var toPath=to.pathname.split('/').slice(1),fromPath=from.pathname.split('/').slice(1,-1);toPath[0]===fromPath[0];)toPath.shift(),fromPath.shift();for(;fromPath.length;)fromPath.shift(),toPath.unshift('..');return toPath.join('/')}function uuid(){try{return crypto.randomUUID()}catch(error){try{var url=URL.createObjectURL(new Blob),_uuid=url.toString();return URL.revokeObjectURL(url),_uuid.slice(_uuid.lastIndexOf('/')+1)}catch(error){var dt=new Date().getTime(),_uuid2='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){var r=0|(dt+16*Math.random())%16;return dt=Math.floor(dt/16),('x'==c?r:8|3&r).toString(16)});return _uuid2}}}function processCmcd(obj,options){var results={};if(null==obj||'object'!=typeof obj)return results;var keys=Object.keys(obj).sort(),formatters=_extends({},CmcdFormatters,null==options?void 0:options.formatters),filter=null==options?void 0:options.filter;return keys.forEach(function(key){if(!(null!=filter&&filter(key))){var value=obj[key],formatter=formatters[key];formatter&&(value=formatter(value,options)),('v'!==key||1!==value)&&('pr'!=key||1!==value)&&isValid(value)&&(isTokenField(key)&&'string'==typeof value&&(value=new SfToken(value)),results[key]=value)}}),results}function encodeCmcd(cmcd,options){return void 0===options&&(options={}),cmcd?encodeSfDict(processCmcd(cmcd,options),_extends({whitespace:!1},options)):''}function toCmcdHeaders(cmcd,options){var _options;if(void 0===options&&(options={}),!cmcd)return{};var entries=Object.entries(cmcd),headerMap=Object.entries(CmcdHeaderMap).concat(Object.entries((null==(_options=options)?void 0:_options.customHeaderMap)||{})),shards=entries.reduce(function(acc,entry){var key=entry[0],value=entry[1],field=(null==(_headerMap$find=headerMap.find(function(entry){return entry[1].includes(key)}))?void 0:_headerMap$find[0])||CmcdHeaderField.REQUEST,_headerMap$find,_acc$field;return null==(_acc$field=acc[field])?acc[field]={}:_acc$field,acc[field][key]=value,acc},{});return Object.entries(shards).reduce(function(acc,_ref){var field=_ref[0],value=_ref[1];return acc[field]=encodeCmcd(value,options),acc},{})}function appendCmcdHeaders(headers,cmcd,options){return _extends(headers,toCmcdHeaders(cmcd,options))}function toCmcdQuery(cmcd,options){if(void 0===options&&(options={}),!cmcd)return'';var params=encodeCmcd(cmcd,options);return CMCD_PARAM+'='+encodeURIComponent(params)}function appendCmcdQuery(url,cmcd,options){var query=toCmcdQuery(cmcd,options);if(!query)return url;if(REGEX.test(url))return url.replace(REGEX,query);var separator=url.includes('?')?'&':'?';return''+url+separator+query}function cloneRenditionGroups(tracks,groupCloneMap,uriReplacement,cloneId){tracks&&Object.keys(groupCloneMap).forEac
1h(function(audioGroupId){var clonedTracks=tracks.filter(function(track){return track.groupId===audioGroupId}).map(function(track){var clonedTrack=_extends({},track);return clonedTrack.details=void 0,clonedTrack.attrs=new AttrList(clonedTrack.attrs),clonedTrack.url=clonedTrack.attrs.URI=performUriReplacement(track.url,track.attrs['STABLE-RENDITION-ID'],'PER-RENDITION-URIS',uriReplacement),clonedTrack.groupId=clonedTrack.attrs['GROUP-ID']=groupCloneMap[audioGroupId],clonedTrack.attrs['PATHWAY-ID']=cloneId,clonedTrack});tracks.push.apply(tracks,clonedTracks)})}function performUriReplacement(uri,stableId,perOptionKey,uriReplacement){var host=uriReplacement.HOST,params=uriReplacement.PARAMS,perOptionUris=uriReplacement[perOptionKey],perVariantUri;stableId&&(perVariantUri=null==perOptionUris?void 0:perOptionUris[stableId],perVariantUri&&(uri=perVariantUri));var url=new self.URL(uri);return host&&!perVariantUri&&(url.host=host),params&&Object.keys(params).sort().forEach(function(key){key&&url.searchParams.set(key,params[key])}),url.href}function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}function getRequestParameters(context,signal){var initParams={method:'GET',mode:'cors',credentials:'same-origin',signal:signal,headers:new self.Headers(_extends({},context.headers))};return context.rangeEnd&&initParams.headers.set('Range','bytes='+context.rangeStart+'-'+(context.rangeEnd-1+'')),initParams}function getByteRangeLength(byteRangeHeader){var result=BYTERANGE.exec(byteRangeHeader);if(result)return parseInt(result[2])-parseInt(result[1])+1}function getContentLength(headers){var contentRange=headers.get('Content-Range');if(contentRange){var byteRangeLength=getByteRangeLength(contentRange);if(isFiniteNumber(byteRangeLength))return byteRangeLength}var contentLength=headers.get('Content-Length');if(contentLength)return parseInt(contentLength)}function getRequest(context,initParams){return new self.Request(context.url,initParams)}function mergeConfig(defaultConfig,userConfig){if((userConfig.liveSyncDurationCount||userConfig.liveMaxLatencyDurationCount)&&(userConfig.liveSyncDuration||userConfig.liveMaxLatencyDuration))throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');if(void 0!==userConfig.liveMaxLatencyDurationCount&&(void 0===userConfig.liveSyncDurationCount||userConfig.liveMaxLatencyDurationCount<=userConfig.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==userConfig.liveMaxLatencyDuration&&(void 0===userConfig.liveSyncDuration||userConfig.liveMaxLatencyDuration<=userConfig.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var defaultsCopy=deepCpy(defaultConfig),deprecatedSettings=['TimeOut','MaxRetry','RetryDelay','MaxRetryTimeout'];return['manifest','level','frag'].forEach(function(type){var policyName=('level'===type?'playlist':type)+'LoadPolicy',policyNotSet=void 0===userConfig[policyName],report=[];deprecatedSettings.forEach(function(setting){var deprecatedSetting=type+'Loading'+setting,value=userConfig[deprecatedSetting];if(void 0!==value&&policyNotSet){report.push(deprecatedSetting);var settings=defaultsCopy[policyName].default;userConfig[policyName]={default:settings},'TimeOut'===setting?(settings.maxLoadTimeMs=value,settings.maxTimeToFirstByteMs=value):'MaxRetry'===setting?(settings.errorRetry.maxNumRetry=value,settings.timeoutRetry.maxNumRetry=value):'RetryDelay'===setting?(settings.errorRetry.retryDelayMs=value,settings.timeoutRetry.retryDelayMs=value):'MaxRetryTimeout'===setting?(settings.errorRetry.maxRetryDelayMs=value,settings.timeoutRetry.maxRetryDelayMs=value):void 0}}),report.length&&logger.warn('hls.js config: "'+report.join('", "')+'" setting(s) are deprecated, use "'+policyName+'": '+JSON.stringify(userConfig[policyName]))}
1),_objectSpread2(_objectSpread2({},defaultsCopy),userConfig)}function deepCpy(obj){return obj&&'object'==typeof obj?Array.isArray(obj)?obj.map(deepCpy):Object.keys(obj).reduce(function(result,key){return result[key]=deepCpy(obj[key]),result},{}):obj}function enableStreamingMode(config){var currentLoader=config.loader;if(currentLoader!==FetchLoader&¤tLoader!==XhrLoader)logger.log('[config]: Custom loader detected, cannot enable progressive streaming'),config.progressive=!1;else{var canStreamProgressively=fetchSupported();canStreamProgressively&&(config.loader=FetchLoader,config.progressive=!0,config.enableSoftwareAES=!0,logger.log('[config]: Progressive streaming enabled, using FetchLoader'))}}function assignTrackIdsByGroup(tracks){var groups={};tracks.forEach(function(track){var groupId=track.groupId||'';track.id=groups[groupId]=groups[groupId]||0,groups[groupId]++})}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){var mediaSource=getMediaSource();if(!mediaSource)return!1;var sourceBuffer=getSourceBuffer();return!sourceBuffer||sourceBuffer.prototype&&'function'==typeof sourceBuffer.prototype.appendBuffer&&'function'==typeof sourceBuffer.prototype.remove}function isSupported(){if(!isMSESupported())return!1;var mediaSource=getMediaSource();return'function'==typeof(null==mediaSource?void 0:mediaSource.isTypeSupported)&&(['avc1.42E01E,mp4a.40.2','av01.0.01M.08','vp09.00.50.08'].some(function(codecsForVideoContainer){return mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer,'video'))})||['mp4a.40.2','fLaC'].some(function(codecForAudioContainer){return mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer,'audio'))}))}function changeTypeSupported(){var sourceBuffer=getSourceBuffer(),_sourceBuffer$prototy;return'function'==typeof(null==sourceBuffer||null==(_sourceBuffer$prototy=sourceBuffer.prototype)?void 0:_sourceBuffer$prototy.changeType)}var urlToolkit={exports:{}};(function(module){(function(){var URL_REGEX=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,FIRST_SEGMENT_REGEX=/^(?=([^\/?#]*))\1([^]*)$/,SLASH_DOT_REGEX=/(?:\/|^)\.(?=\/)/g,SLASH_DOT_DOT_REGEX=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,URLToolkit={buildAbsoluteURL:function(baseURL,relativeURL,opts){if(opts=opts||{},baseURL=baseURL.trim(),relativeURL=relativeURL.trim(),!relativeURL){if(!opts.alwaysNormalize)return baseURL;var basePartsForNormalise=URLToolkit.parseURL(baseURL);if(!basePartsForNormalise)throw new Error('Error trying to parse base URL.');return basePartsForNormalise.path=URLToolkit.normalizePath(basePartsForNormalise.path),URLToolkit.buildURLFromParts(basePartsForNormalise)}var relativeParts=URLToolkit.parseURL(relativeURL);if(!relativeParts)throw new Error('Error trying to parse relative URL.');if(relativeParts.scheme)return opts.alwaysNormalize?(relativeParts.path=URLToolkit.normalizePath(relativeParts.path),URLToolkit.buildURLFromParts(relativeParts)):relativeURL;var baseParts=URLToolkit.parseURL(baseURL);if(!baseParts)throw new Error('Error trying to parse base URL.');if(!baseParts.netLoc&&baseParts.path&&'/'!==baseParts.path[0]){var pathParts=FIRST_SEGMENT_REGEX.exec(baseParts.path);baseParts.netLoc=pathParts[1],baseParts.path=pathParts[2]}baseParts.netLoc&&!baseParts.path&&(baseParts.path='/');var builtParts={scheme:baseParts.scheme,netLoc:relativeParts.netLoc,path:null,params:relativeParts.params,query:relativeParts.query,fragment:relativeParts.fragment};if(!relativeParts.netLoc&&(builtParts.netLoc=baseParts.netLoc,'/'!==relativeParts.path[0]))if(!relativeParts.path)builtParts.path=baseParts.path,relativeParts.params||(builtParts.params=baseParts.params,!relativeParts.query&&(builtParts.query=baseParts.query));else{var baseURLPath=baseParts.path,newPath=baseURLPath.substring(0,baseURLPath.lastIndexOf('/')+1)+relativeParts.path;builtParts.path=URLToolkit.normalizePath(newPath)}return null===builtParts.path&&(builtParts.path=opts.alwaysNormalize?URLToolkit.normalizePath(relativeParts.path):relativeParts.path),URLToolkit.buildURLFromParts(builtParts)},parseURL:function(url){var parts=URL_REGEX.exec(url);return parts?{scheme:parts[1]||'',netLoc:parts[2]||'',path:parts[3]||'',params:parts[4]||'',query:p
vendor: 5,344 bytes, line 1
1arts[5]||'',fragment:parts[6]||''}:null},normalizePath:function(path){for(path=path.split('').reverse().join('').replace(SLASH_DOT_REGEX,'');path.length!==(path=path.replace(SLASH_DOT_DOT_REGEX,'')).length;);return path.split('').reverse().join('')},buildURLFromParts:function(parts){return parts.scheme+parts.netLoc+parts.path+parts.params+parts.query+parts.fragment}};module.exports=URLToolkit})()})(urlToolkit);var urlToolkitExports=urlToolkit.exports,isFiniteNumber=Number.isFinite||function(value){return'number'==typeof value&&isFinite(value)},isSafeInteger=Number.isSafeInteger||function(value){return'number'==typeof value&&Math.abs(value)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991,Events=function(Events){return Events.MEDIA_ATTACHING='hlsMediaAttaching',Events.MEDIA_ATTACHED='hlsMediaAttached',Events.MEDIA_DETACHING='hlsMediaDetaching',Events.MEDIA_DETACHED='hlsMediaDetached',Events.BUFFER_RESET='hlsBufferReset',Events.BUFFER_CODECS='hlsBufferCodecs',Events.BUFFER_CREATED='hlsBufferCreated',Events.BUFFER_APPENDING='hlsBufferAppending',Events.BUFFER_APPENDED='hlsBufferAppended',Events.BUFFER_EOS='hlsBufferEos',Events.BUFFER_FLUSHING='hlsBufferFlushing',Events.BUFFER_FLUSHED='hlsBufferFlushed',Events.MANIFEST_LOADING='hlsManifestLoading',Events.MANIFEST_LOADED='hlsManifestLoaded',Events.MANIFEST_PARSED='hlsManifestParsed',Events.LEVEL_SWITCHING='hlsLevelSwitching',Events.LEVEL_SWITCHED='hlsLevelSwitched',Events.LEVEL_LOADING='hlsLevelLoading',Events.LEVEL_LOADED='hlsLevelLoaded',Events.LEVEL_UPDATED='hlsLevelUpdated',Events.LEVEL_PTS_UPDATED='hlsLevelPtsUpdated',Events.LEVELS_UPDATED='hlsLevelsUpdated',Events.AUDIO_TRACKS_UPDATED='hlsAudioTracksUpdated',Events.AUDIO_TRACK_SWITCHING='hlsAudioTrackSwitching',Events.AUDIO_TRACK_SWITCHED='hlsAudioTrackSwitched',Events.AUDIO_TRACK_LOADING='hlsAudioTrackLoading',Events.AUDIO_TRACK_LOADED='hlsAudioTrackLoaded',Events.SUBTITLE_TRACKS_UPDATED='hlsSubtitleTracksUpdated',Events.SUBTITLE_TRACKS_CLEARED='hlsSubtitleTracksCleared',Events.SUBTITLE_TRACK_SWITCH='hlsSubtitleTrackSwitch',Events.SUBTITLE_TRACK_LOADING='hlsSubtitleTrackLoading',Events.SUBTITLE_TRACK_LOADED='hlsSubtitleTrackLoaded',Events.SUBTITLE_FRAG_PROCESSED='hlsSubtitleFragProcessed',Events.CUES_PARSED='hlsCuesParsed',Events.NON_NATIVE_TEXT_TRACKS_FOUND='hlsNonNativeTextTracksFound',Events.INIT_PTS_FOUND='hlsInitPtsFound',Events.FRAG_LOADING='hlsFragLoading',Events.FRAG_LOAD_EMERGENCY_ABORTED='hlsFragLoadEmergencyAborted',Events.FRAG_LOADED='hlsFragLoaded',Events.FRAG_DECRYPTED='hlsFragDecrypted',Events.FRAG_PARSING_INIT_SEGMENT='hlsFragParsingInitSegment',Events.FRAG_PARSING_USERDATA='hlsFragParsingUserdata',Events.FRAG_PARSING_METADATA='hlsFragParsingMetadata',Events.FRAG_PARSED='hlsFragParsed',Events.FRAG_BUFFERED='hlsFragBuffered',Events.FRAG_CHANGED='hlsFragChanged',Events.FPS_DROP='hlsFpsDrop',Events.FPS_DROP_LEVEL_CAPPING='hlsFpsDropLevelCapping',Events.MAX_AUTO_LEVEL_UPDATED='hlsMaxAutoLevelUpdated',Events.ERROR='hlsError',Events.DESTROYING='hlsDestroying',Events.KEY_LOADING='hlsKeyLoading',Events.KEY_LOADED='hlsKeyLoaded',Events.LIVE_BACK_BUFFER_REACHED='hlsLiveBackBufferReached',Events.BACK_BUFFER_REACHED='hlsBackBufferReached',Events.STEERING_MANIFEST_LOADED='hlsSteeringManifestLoaded',Events}({}),ErrorTypes=function(ErrorTypes){return ErrorTypes.NETWORK_ERROR='networkError',ErrorTypes.MEDIA_ERROR='mediaError',ErrorTypes.KEY_SYSTEM_ERROR='keySystemError',ErrorTypes.MUX_ERROR='muxError',ErrorTypes.OTHER_ERROR='otherError',ErrorTypes}({}),ErrorDetails=function(ErrorDetails){return ErrorDetails.KEY_SYSTEM_NO_KEYS='keySystemNoKeys',ErrorDetails.KEY_SYSTEM_NO_ACCESS='keySystemNoAccess',ErrorDetails.KEY_SYSTEM_NO_SESSION='keySystemNoSession',ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE='keySystemNoConfiguredLicense',ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED='keySystemLicenseRequestFailed',ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED='keySystemServerCertificateRequestFailed',ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED='keySystemServerCertificateUpdateFailed',ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED='keySystemSessionUpdateFailed',ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED='keySystemStatusOutputRestricted',ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR='keySystemStatusInternalError',ErrorDetails.MANIFEST_LOAD_ERROR='manifestLoadError',ErrorDetails.MANIFEST_LOAD_TIMEOUT='manifestLoadTimeOut',ErrorDetails.MANIFEST_PARSING_ERROR='manifestParsingError',ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR='manifestIncompatibleCodecsError',ErrorDetails.LEVEL_EMPTY_ERROR='levelEmptyError',ErrorDetails.LEVEL_LOAD_ERROR='levelLoadError',ErrorDetails.LEVEL_LOAD_TIMEOUT='levelLoadTimeOut',ErrorDetails.LEVEL_PARSING_ERROR='levelParsingError',ErrorDetails.LEVEL_SWITCH_ERROR='levelSwitchError',ErrorDetails.AUDIO_TRACK_LOAD_ERROR='audioTrackLoadError',ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT='audioTrackLoadTimeOut',ErrorDetails.SUBTITLE_LOAD_ERROR='subtitleTrackLoadError',ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT='subtitleTrackLoadTimeOut',ErrorDetails.FRAG_LOAD_ERROR='fragLoadError',ErrorDetails.FRAG_LOAD_TIMEOUT='fragLoadTimeOut',ErrorDetails.FRAG_DECRYPT_ERROR='fragDecryptError',ErrorDetails.FRAG_PARSING_ERROR='fragParsingError',ErrorDetails.FRAG_GAP='fragGap',ErrorDetails.REMUX_ALLOC_ER
1ROR='remuxAllocError',ErrorDetails.KEY_LOAD_ERROR='keyLoadError',ErrorDetails.KEY_LOAD_TIMEOUT='keyLoadTimeOut',ErrorDetails.BUFFER_ADD_CODEC_ERROR='bufferAddCodecError',ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR='bufferIncompatibleCodecsError',ErrorDetails.BUFFER_APPEND_ERROR='bufferAppendError',ErrorDetails.BUFFER_APPENDING_ERROR='bufferAppendingError',ErrorDetails.BUFFER_STALLED_ERROR='bufferStalledError',ErrorDetails.BUFFER_FULL_ERROR='bufferFullError',ErrorDetails.BUFFER_SEEK_OVER_HOLE='bufferSeekOverHole',ErrorDetails.BUFFER_NUDGE_ON_STALL='bufferNudgeOnStall',ErrorDetails.INTERNAL_EXCEPTION='internalException',ErrorDetails.INTERNAL_ABORTED='aborted',ErrorDetails.UNKNOWN='unknown',ErrorDetails}({}),noop=function(){},fakeLogger={trace:noop,debug:noop,log:noop,warn:noop,info:noop,error:noop},exportedLogger=fakeLogger,logger=exportedLogger,DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g,AttrList=function(){function AttrList(attrs){'string'==typeof attrs&&(attrs=AttrList.parseAttrList(attrs)),_extends(this,attrs)}var _proto=AttrList.prototype;return _proto.decimalInteger=function(attrName){var intValue=parseInt(this[attrName],10);return intValue>Number.MAX_SAFE_INTEGER?Infinity:intValue},_proto.hexadecimalInteger=function(attrName){if(this[attrName]){var stringValue=(this[attrName]||'0x').slice(2);stringValue=(1&stringValue.length?'0':'')+stringValue;for(var value=new Uint8Array(stringValue.length/2),i=0;i<stringValue.length/2;i++)value[i]=parseInt(stringValue.slice(2*i,2*i+2),16);return value}return null},_proto.hexadecimalIntegerAsNumber=function(attrName){var intValue=parseInt(this[attrName],16);return intValue>Number.MAX_SAFE_INTEGER?Infinity:intValue},_proto.decimalFloatingPoint=function(attrName){return parseFloat(this[attrName])},_proto.optionalFloat=function(attrName,defaultValue){var value=this[attrName];return value?parseFloat(value):defaultValue},_proto.enumeratedString=function(attrName){return this[attrName]},_proto.bool=function(attrName){return'YES'===this[attrName]},_proto.decimalResolution=function(attrName){var res=DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);return null===res?void 0:{width:parseInt(res[1],10),height:parseInt(res[2],10)}},AttrList.parseAttrList=function(input){var attrs={},quote='"',match;for(ATTR_LIST_REGEX.lastIndex=0;null!==(match=ATTR_LIST_REGEX.exec(input));){var value=match[2];0===value.indexOf(quote)&&value.lastIndexOf(quote)===value.length-1&&(value=value.slice(1,-1));var name=match[1].trim();attrs[name]=value}return attrs},_createClass(AttrList,[{key:'clientAttrs',get:function(){return Object.keys(this).filter(function(attr){return'X-'===attr.substring(0,2)})}}]),AttrList}(),DateRange=function(){function DateRange(dateRangeAttr,dateRangeWithSameId){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,dateRangeWithSameId){var previousAttr=dateRangeWithSameId.attr;for(var key in previousAttr)if(Object.prototype.hasOwnProperty.call(dateRangeAttr,key)&&dateRangeAttr[key]!==previousAttr[key]){logger.warn('DATERANGE tag attribute: "'+key+'" does not match for tags with ID: "'+dateRangeAttr.ID+'"'),this._badValueForSameId=key;break}dateRangeAttr=_extends(new AttrList({}),previousAttr,dateRangeAttr)}if(this.attr=dateRangeAttr,this._startDate=new Date(dateRangeAttr['START-DATE']),'END-DATE'in this.attr){var endDate=new Date(this.attr['END-DATE']);isFiniteNumber(endDate.getTime())&&(this._endDate=endDate)}}return _createClass(DateRange,[{key:'id',get:function(){return this.attr.ID}},{key:'class',get:function(){return this.attr.CLASS}},{key:'startDate',get:function(){return this._startDate}},{key:'endDate',get:function(){if(this._endDate)return this._endDate;var duration=this.duration;return null===duration?null:new Date(this._startDate.getTime()+1e3*duration)}},{key:'duration',get:function(){if('DURATION'in this.attr){var duration=this.attr.decimalFloatingPoint('DURATION');if(isFiniteNumber(duration))return duration}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:'plannedDuration',get:function(){return'PLANNED-DURATION'in this.attr?this.attr.decimalFloatingPoint('PLANNED-DURATION'):null}},{key:'endOnNext',get:function(){return this.attr.bool('END-ON-NEXT')}},{key:'isValid',get:function(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(this.startDate.getTime())&&(null===this.duration||0<=this.duration)&&(!this.endOnNext||!!this.class)}}]),DateRange}(),LoadStats=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}},ElementaryStreamTypes={AUDIO:'audio',VIDEO:'video',AUDIOVIDEO:'audiovideo'},BaseSegment=function(){function BaseSegment(baseurl){var _this$elementaryStrea;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=(_this$elementaryStrea={},_this$elementaryStrea[ElementaryStreamTypes.AUDIO]=null,_this$elementaryStrea[ElementaryStreamTypes.VIDEO]=null,_this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO]=null,_this$elementaryStrea),this.baseurl=baseurl}var _proto=BaseSegment.prototype;return _proto.setByteRange=function(value,previous){var params=value.split('@',2),start;
vendor: 5,555 bytes, line 1
1start=1===params.length?(null==previous?void 0:previous.byteRangeEndOffset)||0:parseInt(params[1]),this._byteRange=[start,parseInt(params[0])+start]},_createClass(BaseSegment,[{key:'byteRange',get:function(){return this._byteRange?this._byteRange:[]}},{key:'byteRangeStartOffset',get:function(){return this.byteRange[0]}},{key:'byteRangeEndOffset',get:function(){return this.byteRange[1]}},{key:'url',get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=urlToolkitExports.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||''},set:function(value){this._url=value}}]),BaseSegment}(),Fragment=function(_BaseSegment){function Fragment(type,baseurl){var _this;return _this=_BaseSegment.call(this,baseurl)||this,_this._decryptdata=null,_this.rawProgramDateTime=null,_this.programDateTime=null,_this.tagList=[],_this.duration=0,_this.sn=0,_this.levelkeys=void 0,_this.type=void 0,_this.loader=null,_this.keyLoader=null,_this.level=-1,_this.cc=0,_this.startPTS=void 0,_this.endPTS=void 0,_this.startDTS=void 0,_this.endDTS=void 0,_this.start=0,_this.deltaPTS=void 0,_this.maxStartPTS=void 0,_this.minEndPTS=void 0,_this.stats=new LoadStats,_this.data=void 0,_this.bitrateTest=!1,_this.title=null,_this.initSegment=null,_this.endList=void 0,_this.gap=void 0,_this.urlId=0,_this.type=type,_this}_inheritsLoose(Fragment,_BaseSegment);var _proto2=Fragment.prototype;return _proto2.setKeyFormat=function(keyFormat){if(this.levelkeys){var _key=this.levelkeys[keyFormat];_key&&!this._decryptdata&&(this._decryptdata=_key.getDecryptData(this.sn))}},_proto2.abortRequests=function(){var _this$loader,_this$keyLoader;null==(_this$loader=this.loader)?void 0:_this$loader.abort(),null==(_this$keyLoader=this.keyLoader)?void 0:_this$keyLoader.abort()},_proto2.setElementaryStreamInfo=function(type,startPTS,endPTS,startDTS,endDTS,partial){void 0===partial&&(partial=!1);var elementaryStreams=this.elementaryStreams,info=elementaryStreams[type];return info?void(info.startPTS=Math.min(info.startPTS,startPTS),info.endPTS=Math.max(info.endPTS,endPTS),info.startDTS=Math.min(info.startDTS,startDTS),info.endDTS=Math.max(info.endDTS,endDTS)):void(elementaryStreams[type]={startPTS:startPTS,endPTS:endPTS,startDTS:startDTS,endDTS:endDTS,partial:partial})},_proto2.clearElementaryStreamInfo=function(){var elementaryStreams=this.elementaryStreams;elementaryStreams[ElementaryStreamTypes.AUDIO]=null,elementaryStreams[ElementaryStreamTypes.VIDEO]=null,elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]=null},_createClass(Fragment,[{key:'decryptdata',get:function(){var levelkeys=this.levelkeys;if(!levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var _key2=this.levelkeys.identity;if(_key2)this._decryptdata=_key2.getDecryptData(this.sn);else{var keyFormats=Object.keys(this.levelkeys);if(1===keyFormats.length)return this._decryptdata=this.levelkeys[keyFormats[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:'end',get:function(){return this.start+this.duration}},{key:'endProgramDateTime',get:function(){if(null===this.programDateTime)return null;if(!isFiniteNumber(this.programDateTime))return null;var duration=isFiniteNumber(this.duration)?this.duration:0;return this.programDateTime+1e3*duration}},{key:'encrypted',get:function(){var _this$_decryptdata;if(null!=(_this$_decryptdata=this._decryptdata)&&_this$_decryptdata.encrypted)return!0;if(this.levelkeys){var keyFormats=Object.keys(this.levelkeys),len=keyFormats.length;if(1<len||1===len&&this.levelkeys[keyFormats[0]].encrypted)return!0}return!1}}]),Fragment}(BaseSegment),Part=function(_BaseSegment2){function Part(partAttrs,frag,baseurl,index,previous){var _this2;_this2=_BaseSegment2.call(this,baseurl)||this,_this2.fragOffset=0,_this2.duration=0,_this2.gap=!1,_this2.independent=!1,_this2.relurl=void 0,_this2.fragment=void 0,_this2.index=void 0,_this2.stats=new LoadStats,_this2.duration=partAttrs.decimalFloatingPoint('DURATION'),_this2.gap=partAttrs.bool('GAP'),_this2.independent=partAttrs.bool('INDEPENDENT'),_this2.relurl=partAttrs.enumeratedString('URI'),_this2.fragment=frag,_this2.index=index;var byteRange=partAttrs.enumeratedString('BYTERANGE');return byteRange&&_this2.setByteRange(byteRange,previous),previous&&(_this2.fragOffset=previous.fragOffset+previous.duration),_this2}return _inheritsLoose(Part,_BaseSegment2),_createClass(Part,[{key:'start',get:function(){return this.fragment.start+this.fragOffset}},{key:'end',get:function(){return this.start+this.duration}},{key:'loaded',get:function(){var elementaryStreams=this.elementaryStreams;return!!(elementaryStreams.audio||elementaryStreams.video||elementaryStreams.audiovideo)}}]),Part}(BaseSegment),LevelDetails=function(){function LevelDetails(baseUrl){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8='',this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.drift
1StartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=baseUrl}var _proto=LevelDetails.prototype;return _proto.reloaded=function(previous){if(!previous)return this.advanced=!0,void(this.updated=!0);var partSnDiff=this.lastPartSn-previous.lastPartSn,partIndexDiff=this.lastPartIndex-previous.lastPartIndex;this.updated=this.endSN!==previous.endSN||!!partIndexDiff||!!partSnDiff||!this.live,this.advanced=this.endSN>previous.endSN||0<partSnDiff||0==partSnDiff&&0<partIndexDiff,this.misses=this.updated||this.advanced?Math.floor(.6*previous.misses):previous.misses+1,this.availabilityDelay=previous.availabilityDelay},_createClass(LevelDetails,[{key:'hasProgramDateTime',get:function(){return!!this.fragments.length&&isFiniteNumber(this.fragments[this.fragments.length-1].programDateTime)}},{key:'levelTargetDuration',get:function(){return this.averagetargetduration||this.targetduration||10}},{key:'drift',get:function(){var runTime=this.driftEndTime-this.drift
1StartTime;if(0<runTime){var runDuration=this.driftEnd-this.driftStart;return 1e3*runDuration/runTime}return 1}},{key:'edge',get:function(){return this.partEnd||this.fragmentEnd}},{key:'partEnd',get:function(){var _this$partList;return null!=(_this$partList=this.partList)&&_this$partList.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:'fragmentEnd',get:function(){var _this$fragments;return null!=(_this$fragments=this.fragments)&&_this$fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:'age',get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:'lastPartIndex',get:function(){var _this$partList2;return null!=(_this$partList2=this.partList)&&_this$partList2.length?this.partList[this.partList.length-1].index:-1}},{key:'lastPartSn',get:function(){var _this$partList3;return null!=(_this$partList3=this.partList)&&_this$partList3.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),LevelDetails}(),optionalSelf='undefined'==typeof self?void 0:self,KeySystems={CLEARKEY:'org.w3.clearkey',FAIRPLAY:'com.apple.fps',PLAYREADY:'com.microsoft.playready',WIDEVINE:'com.widevine.alpha'},KeySystemFormats={CLEARKEY:'org.w3.clearkey',FAIRPLAY:'com.apple.streamingkeydelivery',PLAYREADY:'com.microsoft.playready',WIDEVINE:'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'},KeySystemIds={CENC:'1077efecc0b24d02ace33c1e52e2fb4b',CLEARKEY:'e2719d58a985b3c9781ab030af78d30e',FAIRPLAY:'94ce86fb07ff4f43adb893d2fa968ca2',PLAYREADY:'9a04f07998404286ab92e65be0885f95',WIDEVINE:'edef8ba979d64acea3c827dcd51d21ed'},requestMediaKeySystemAccess=function(_optionalSelf$navigat){return null!=optionalSelf&&null!=(_optionalSelf$navigat=optionalSelf.navigator)&&_optionalSelf$navigat.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}(),isHeader$2=function(data,offset){return!!(offset+10<=data.length&&73===data[offset]&&68===data[offset+1]&&51===data[offset+2]&&255>data[offset+3]&&255>data[offset+4]&&128>data[offset+6]&&128>data[offset+7]&&128>data[offset+8]&&128>data[offset+9])},isFooter=function(data,offset){return!!(offset+10<=data.length&&51===data[offset]&&68===data[offset+1]&&73===data[offset+2]&&255>data[offset+3]&&255>data[offset+4]&&128>data[offset+6]&&128>data[offset+7]&&128>data[offset+8]&&128>data[offset+9])},getID3Data=function(data,offset){for(var front=offset,length=0;isHeader$2(data,offset);){length+=10;var size=readSize(data,offset+6);length+=size,isFooter(data,offset+10)&&(length+=10),offset+=length}return 0<length?data.subarray(front,front+length):void 0},readSize=function(data,offset){var size=0;return size=(127&data[offset])<<21,size|=(127&data[offset+1])<<14,size|=(127&data[offset+2])<<7,size|=127&data[offset+3],size},canParse$2=function(data,offset){return isHeader$2(data,offset)&&readSize(data,offset+6)+10<=data.length-offset},getTimeStamp=function(data){for(var frames=getID3Frames(data),i=0,frame;i<frames.length;i++)if(frame=frames[i],isTimeStampFrame(frame))return readTimeStamp(frame)},isTimeStampFrame=function(frame){return frame&&'PRIV'===frame.key&&'com.apple.streaming.transportStreamTimestamp'===frame.info},getFrameData=function(data){var type=String.fromCharCode(data[0],data[1],data[2],data[3]),size=readSize(data,4),offset=10;return{type:type,size:size,data:data.subarray(offset,offset+size)}},getID3Frames=function(id3Data){for(var offset=0,frames=[],size;isHeader$2(id3Data,offset);){size=readSize(id3Data,offset+6),offset+=10;for(var end=offset+size;offset+8<end;){var frameData=getFrameData(id3Data.subarray(offset)),frame=decodeFrame(frameData);frame&&frames.push(frame),offset+=frameData.size+10}isFooter(id3Data,offset)&&(offset+=10)}return frames},decodeFrame=function(frame){return'PRIV'===frame.type?decodePrivFrame(frame):'W'===frame.type[0]?decodeURLFrame(frame):decodeTextFrame(frame)},decodePrivFrame=function(frame){if(!(2>frame.size)){var owner=utf8ArrayToStr(frame.data,!0),privateData=new Uint8Array(frame.data.subarray(owner.length+1));return{key:frame.type,info:owner,data:privateData.buffer}}},decodeTextFrame=function(frame){if(!(2>frame.size)){if('TXXX'===frame.type){var index=1,description=utf8ArrayToStr(frame.data.subarray(index),!0);index+=description.length+1;var value=utf8ArrayToStr(frame.data.subarray(index));return{key:frame.type,info:description,data:value}}var text=utf8ArrayToStr(frame.data.subarray(1));return{key:frame.type,data:text}}},decodeURLFrame=function(frame){if('WXXX'===frame.type){if(2>frame.size)return;var index=1,description=utf8ArrayToStr(frame.data.subarray(index),!0);index+=description.length+1;var value=utf8ArrayToStr(frame.data.subarray(index));return{key:frame.type,info:description,data:value}}var url=utf8ArrayToStr(frame.data);return{key:frame.type,data:url}},readTimeStamp=function(timeStampFrame){if(8===timeStampFrame.data.byteLength){var data=new Uint8Array(timeStampFrame.data),pts33Bit=1&data[3],timestamp=(data[4]<<23)+(data[5]<<15)+(data[6]<<7)+data[7];return timestamp/=45,pts33Bit&&(timestamp+=47721858.84),Math.round(timestamp)}},utf8ArrayToStr=function(array,exitOnNull){void 0===exitOnNull&&(exitOnNull=!1);var decoder=getTextDecoder();if(decoder){var decoded=decoder.decode(array);if(exitOnNull){var idx=decoded.indexOf('\0');return-1===idx?decoded:decoded.substring(0,idx)}return decoded.replace(/\0/g,'')}for(var len=array.length,out='',i=0,c,char2,char3;i<len;){if(c=array[i++],0===c&&exitOnNull)return out;if(0!==c&&3!==c)switch(c>>
14){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:out+=String.fromCharCode(c);break;case 12:case 13:char2=array[i++],out+=String.fromCharCode((31&c)<<6|63&char2);break;case 14:char2=array[i++],char3=array[i++],out+=String.fromCharCode((15&c)<<12|(63&char2)<<6|(63&char3)<<0);}}return out},Hex={hexDump:function(array){for(var str='',i=0,h;i<array.length;i++)h=array[i].toString(16),2>h.length&&(h='0'+h),str+=h;return str}},UINT32_MAX$1=Math.pow(2,32)-1,push=[].push,RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4},keyUriToKeyIdMap={},LevelKey=function(){function LevelKey(method,uri,format,formatversions,iv){void 0===formatversions&&(formatversions=[1]),void 0===iv&&(iv=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=method,this.uri=uri,this.keyFormat=format,this.keyFormatVersions=formatversions,this.iv=iv,this.encrypted=!!method&&'NONE'!==method,this.isCommonEncryption=this.encrypted&&'AES-128'!==method}LevelKey.clearKeyUriToKeyIdMap=function(){keyUriToKeyIdMap={}};var _proto=LevelKey.prototype;return _proto.isSupported=function(){if(this.method){if('AES-128'===this.method||'NONE'===this.method)return!0;if('identity'===this.keyFormat)return'SAMPLE-AES'===this.method;switch(this.keyFormat){case KeySystemFormats.FAIRPLAY:case KeySystemFormats.WIDEVINE:case KeySystemFormats.PLAYREADY:case KeySystemFormats.
1CLEARKEY:return-1!==['ISO-23001-7','SAMPLE-AES','SAMPLE-AES-CENC','SAMPLE-AES-CTR'].indexOf(this.method);}}return!1},_proto.getDecryptData=function(sn){if(!this.encrypted||!this.uri)return null;if('AES-128'===this.method&&this.uri&&!this.iv){'number'!=typeof sn&&('AES-128'===this.method&&!this.iv&&logger.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),sn=0);var iv=createInitializationVector(sn),decryptdata=new LevelKey(this.method,this.uri,'identity',this.keyFormatVersions,iv);return decryptdata}var keyBytes=convertDataUriToArrayBytes(this.uri);if(keyBytes)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:this.pssh=keyBytes,22<=keyBytes.length&&(this.keyId=keyBytes.subarray(keyBytes.length-22,keyBytes.length-6));break;case KeySystemFormats.PLAYREADY:{var PlayReadyKeySystemUUID=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(PlayReadyKeySystemUUID,null,keyBytes);var keyBytesUtf16=new Uint16Array(keyBytes.buffer,keyBytes.byteOffset,keyBytes.byteLength/2),keyByteStr=String.fromCharCode.apply(null,Array.from(keyBytesUtf16)),xmlKeyBytes=keyByteStr.substring(keyByteStr.indexOf('<'),keyByteStr.length),parser=new DOMParser,xmlDoc=parser.parseFromString(xmlKeyBytes,'text/xml'),keyData=xmlDoc.getElementsByTagName('KID')[0];if(keyData){var keyId=keyData.childNodes[0]?keyData.childNodes[0].nodeValue:keyData.getAttribute('VALUE');if(keyId){var keyIdArray=base64Decode(keyId).subarray(0,16);changeEndianness(keyIdArray),this.keyId=keyIdArray}}break}
1default:{var keydata=keyBytes.subarray(0,16);if(16!==keydata.length){var padded=new Uint8Array(16);padded.set(keydata,16-keydata.length),keydata=padded}this.keyId=keydata;break}}if(!this.keyId||16!==this.keyId.byteLength){var _keyId=keyUriToKeyIdMap[this.uri];if(!_keyId){var val=Object.keys(keyUriToKeyIdMap).length%Number.MAX_SAFE_INTEGER;_keyId=new Uint8Array(16);var dv=new DataView(_keyId.buffer,12,4);dv.setUint32(0,val),keyUriToKeyIdMap[this.uri]=_keyId}this.keyId=_keyId}return this},LevelKey}(),VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g,sampleEntryCodesISO={audio:{a3ds:1,'ac-3':.95,'ac-4':1,alac:.9,alaw:1,dra1:1,'dts+':1,'dts-':1,dtsc:1,dtse:1,dtsh:1,'ec-3':.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,'raw ':1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,'vc-1':1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}},CODEC_COMPATIBLE_NAMES={},AUDIO_CODEC_REGEXP=/flac|opus/i,MASTER_PLAYLIST_REGEX=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,IS_MEDIA_PLAYLIST=/^#EXT(?:INF|-X-TARGETDURATION):/m,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join('|'),'g'),LEVEL_PLAYLIST_REGEX_SLOW=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join('|')),M3U8Parser=function(){function M3U8Parser(){}return M3U8Parser.findGroup=function(groups,mediaGroupId){for(var i=0,group;i<groups.length;i++)if(group=groups[i],group.id===mediaGroupId)return group},M3U8Parser.resolve=function(url,baseUrl){return urlToolkitExports.buildAbsoluteURL(baseUrl,url,{alwaysNormalize:!0})},M3U8Parser.isMediaPlaylist=function(str){return IS_MEDIA_PLAYLIST.test(str)},M3U8Parser.parseMasterPlaylist=function(string,baseurl){var hasVariableRefs=hasVariableReferences(string),parsed={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hasVariableRefs},levelsWithKnownCodecs=[];MASTER_PLAYLIST_REGEX.lastIndex=0;for(var result;null!=(result=MASTER_PLAYLIST_REGEX.exec(string));)if(result[1]){var attrs=new AttrList(result[1]),_level$unknownCodecs;substituteVariablesInAttributes(parsed,attrs,['CODECS','SUPPLEMENTAL-CODECS','ALLOWED-CPC','PATHWAY-ID','STABLE-VARIANT-ID','AUDIO','VIDEO','SUBTITLES','CLOSED-CAPTIONS','NAME']);var uri=substituteVariables(parsed,result[2]),level={attrs:attrs,bitrate:attrs.decimalInteger('BANDWIDTH')||attrs.decimalInteger('AVERAGE-BANDWIDTH'),name:attrs.NAME,url:M3U8Parser.resolve(uri,baseurl)},resolution=attrs.decimalResolution('RESOLUTION');resolution&&(level.width=resolution.width,level.height=resolution.height),setCodecs(attrs.CODECS,level),null!=(_level$unknownCodecs=level.unknownCodecs)&&_level$unknownCodecs.length||levelsWithKnownCodecs.push(level),parsed.levels.push(level)}else if(result[3]){var tag=result[3],attributes=result[4];switch(tag){case'SESSION-DATA':{var sessionAttrs=new AttrList(attributes);substituteVariablesInAttributes(parsed,sessionAttrs,['DATA-ID','LANGUAGE','VALUE','URI']);var dataId=sessionAttrs['DATA-ID'];dataId&&(null===parsed.sessionData&&(parsed.sessionData={}),parsed.sessionData[dataId]=sessionAttrs);break}case'SESSION-KEY':{var sessionKey=parseKey(attributes,baseurl,parsed);sessionKey.encrypted&&sessionKey.isSupported()?(null===parsed.sessionKeys&&(parsed.sessionKeys=[]),parsed.sessionKeys.push(sessionKey)):logger.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+attributes+'"');break}case'DEFINE':{{var variableAttributes=new AttrList(attributes);substituteVariablesInAttributes(parsed,variableAttributes,['NAME','VALUE','QUERYPARAM']),addVariableDefinition(parsed,variableAttributes,baseurl)}break}case'CONTENT-STEERING':{var contentSteeringAttributes=new AttrList(attributes);substituteVariablesInAttributes(parsed,contentSteeringAttributes,['SERVER-URI','PATHWAY-ID']),parsed.contentSteering={uri:M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'],baseurl),pathwayId:contentSteeringAttributes['PATHWAY-ID']||'.'};break}case'START':{parsed.startTimeOffset=parseStartTimeOffset(attributes);break}}}var stripUnknownCodecLevels=0<levelsWithKnownCodecs.length&&levelsWithKnownCodecs.length<parsed.levels.length;return parsed.levels=stripUnknownCodecLevels?levelsWithKnownCodecs:parsed.levels,0===parsed.levels.length&&(parsed.playlistParsingError=new Error('no levels found in manifest')),parsed},M3U8Parser.parseMasterPlaylistMedia=function(string,baseurl,parsed){var results={},levels=parsed.levels,groupsByType={AUDIO:levels.map(function(level){return{id:level.attrs.AUDIO,audioCodec:level.audioCodec}}),SUBTITLES:levels.map(function(level){return{id:level.attrs.SUBTITLES,textCodec:level.textCodec}}),'CLOSED-CAPTIONS':[]},id=0,result;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(result=MASTER_PLAYLIST_MEDIA_REGEX.exec(string));){var attrs=new AttrList(result[1]),type=attrs.TYPE;if(type){var groups=groupsByType[type],medias=results[type]||[];results[type]=medias,substituteVariablesInAttributes(parsed,attrs,['URI','GROUP-ID','LANGUAGE','ASSOC-LANGUAGE','STABLE-RENDITION-ID','NAME','INSTREAM-ID','CHARACTERISTICS','CHANNELS']);var lang=attrs.LANGUAGE,assocLang=attrs['ASSOC-LANGUAGE'],channels=attrs.CHANNELS,characteristics=attrs.CHARACTERISTICS,instreamId=attrs['INSTREAM-ID'],media={attrs:attrs,bitrate:0,id:id++,groupId:attrs['GROUP-ID']||'',name:attrs.NAME||lang||'',type:type,default:attrs.bool('DEFAULT'),autoselect:attrs.bool('AUTOSELECT'),forced:attrs.bool('FORCED'),lang:lang,url:attrs.URI?M3U8Parser.resolve(attrs.URI,baseurl):''};if(assocLang&&(media.assocLang=assocLang),channels&&(media.channels=channels),characteristics&&(media.characteristics=characteristics),instreamId&&(media.instreamId=instreamId),null!=groups&&groups.length){var groupCodec=M3U8Parser.findGroup(groups,media.groupId)||groups[0];assignCodec(media,groupCodec,'audioCodec'),assignCodec(media,groupCodec,'textCodec')}medias.push(media)}}return results},M3U8Parser.parseLevelPlaylist=function(string,baseurl,id,type,levelUrlId,multivariantVariableList){var level=new LevelDetails(baseurl),fragments=level.fragments,currentInitSegment=null,currentSN=0,currentPart=0,totalduration=0,discontinuityCounter=0,prevFrag=null,frag=new Fragment(type,baseurl),firstPdtIndex=-1,
1createNextFrag=!1,nextByteRange=null,result,i,levelkeys;for(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0,level.m3u8=string,level.hasVariableRefs=hasVariableReferences(string);null!==(result=LEVEL_PLAYLIST_REGEX_FAST.exec(string));){createNextFrag&&(createNextFrag=!1,frag=new Fragment(type,baseurl),frag.start=totalduration,frag.sn=currentSN,frag.cc=discontinuityCounter,frag.level=id,currentInitSegment&&(frag.initSegment=currentInitSegment,frag.rawProgramDateTime=currentInitSegment.rawProgramDateTime,currentInitSegment.rawProgramDateTime=null,nextByteRange&&(frag.setByteRange(nextByteRange),nextByteRange=null)));var duration=result[1];if(duration){frag.duration=parseFloat(duration);var title=(' '+result[2]).slice(1);frag.title=title||null,frag.tagList.push(title?['INF',duration,title]:['INF',duration])}else if(result[3]){if(isFiniteNumber(frag.duration)){frag.start=totalduration,levelkeys&&setFragLevelKeys(frag,levelkeys,level),frag.sn=currentSN,frag.level=id,frag.cc=discontinuityCounter,fragments.push(frag);var uri=(' '+result[3]).slice(1);frag.relurl=substituteVariables(level,uri),assignProgramDateTime(frag,prevFrag),prevFrag=frag,totalduration+=frag.duration,currentSN++,currentPart=0,createNextFrag=!0}}else if(result[4]){var data=(' '+result[4]).slice(1);prevFrag?frag.setByteRange(data,prevFrag):frag.setByteRange(data)}else if(result[5])frag.rawProgramDateTime=(' '+result[5]).slice(1),frag.tagList.push(['PROGRAM-DATE-TIME',frag.rawProgramDateTime]),-1===firstPdtIndex&&(firstPdtIndex=fragments.length);else{if(result=result[0].match(LEVEL_PLAYLIST_REGEX_SLOW),!result){logger.warn('No matches on slow regex match for level playlist!');continue}for(i=1;i<result.length&&'undefined'==typeof result[i];i++);var tag=(' '+result[i]).slice(1),value1=(' '+result[i+1]).slice(1),value2=result[i+2]?(' '+result[i+2]).slice(1):'';switch(tag){case'PLAYLIST-TYPE':level.type=value1.toUpperCase();break;case'MEDIA-SEQUENCE':currentSN=level.startSN=parseInt(value1);break;case'SKIP':{var skipAttrs=new AttrList(value1);substituteVariablesInAttributes(level,skipAttrs,['RECENTLY-REMOVED-DATERANGES']);var skippedSegments=skipAttrs.decimalInteger('SKIPPED-SEGMENTS');if(isFiniteNumber(skippedSegments)){level.skippedSegments=skippedSegments;for(var _i=skippedSegments;_i--;)fragments.unshift(null);currentSN+=skippedSegments}var recentlyRemovedDateranges=skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');recentlyRemovedDateranges&&(level.recentlyRemovedDateranges=recentlyRemovedDateranges.split('\t'));break}case'TARGETDURATION':level.targetduration=Math.max(parseInt(value1),1);break;case'VERSION':level.version=parseInt(value1);break;case'INDEPENDENT-SEGMENTS':case'EXTM3U':break;case'ENDLIST':level.live=!1;break;case'#':(value1||value2)&&frag.tagList.push(value2?[value1,value2]:[value1]);break;case'DISCONTINUITY':discontinuityCounter++,frag.tagList.push(['DIS']);break;case'GAP':frag.gap=!0,frag.tagList.push([tag]);break;case'BITRATE':frag.tagList.push([tag,value1]);break;case'DATERANGE':{var dateRangeAttr=new AttrList(value1);substituteVariablesInAttributes(level,dateRangeAttr,['ID','CLASS','START-DATE','END-DATE','SCTE35-CMD','SCTE35-OUT','SCTE35-IN']),substituteVariablesInAttributes(level,dateRangeAttr,dateRangeAttr.clientAttrs);var dateRange=new DateRange(dateRangeAttr,level.dateRanges[dateRangeAttr.ID]);dateRange.isValid||level.skippedSegments?level.dateRanges[dateRange.id]=dateRange:logger.warn('Ignoring invalid DATERANGE tag: "'+value1+'"'),frag.tagList.push(['EXT-X-DATERANGE',value1]);break}case'DEFINE':{{var variableAttributes=new AttrList(value1);substituteVariablesInAttributes(level,variableAttributes,['NAME','VALUE','IMPORT','QUERYPARAM']),'IMPORT'in variableAttributes?importVariableDefinition(level,variableAttributes,multivariantVariableList):addVariableDefinition(level,variableAttributes,baseurl)}break}case'DISCONTINUITY-SEQUENCE':discontinuityCounter=parseInt(value1);break;case'KEY':{var levelKey=parseKey(value1,baseurl,level);if(levelKey.isSupported()){if('NONE'===levelKey.method){levelkeys=void 0;break}levelkeys||(levelkeys={}),levelkeys[levelKey.keyFormat]&&(levelkeys=_extends({},levelkeys)),levelkeys[levelKey.keyFormat]=levelKey}else logger.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+value1+'"');break}case'START':level.startTimeOffset=parseStartTimeOffset(value1);break;case'MAP':{var mapAttrs=new AttrList(value1);if(substituteVariablesInAttributes(level,mapAttrs,['BYTERANGE','URI']),frag.duration){var init=new Fragment(type,baseurl);setInitSegment(init,mapAttrs,id,levelkeys),currentInitSegment=init,frag.initSegment=currentInitSegment,currentInitSegment.rawProgramDateTime&&!frag.rawProgramDateTime&&(frag.rawProgramDateTime=currentInitSegment.rawProgramDateTime)}else{var end=frag.byteRangeEndOffset;if(end){var start=frag.byteRangeStartOffset;nextByteRange=end-start+'@'+start}else nextByteRange=null;setInitSegment(frag,mapAttrs,id,levelkeys),currentInitSegment=frag,createNextFrag=!0}break}case'SERVER-CONTROL':{var serverControlAttrs=new AttrList(value1);level.canBlockReload=serverControlAttrs.bool('CAN-BLOCK-RELOAD'),level.canSkipUntil=serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL',0),level.canSkipDateRanges=0<level.canSkipUntil&&serverControlAttrs.bool('CAN-SKIP-DATERANGES'),level.partHoldBack=serverControlAttrs.optionalFloat('PART-HOLD-BACK',0),level.holdBack=serverControlAttrs.optionalFloat('HOLD-BACK',0);break}case'PART-INF':{var partInfAttrs=new AttrList(value1);level.partTarget=partInfAttrs.decimalFloatingPoint('PART-TARGET');break}case'PART':{var partList=level.partList;partList||(partList=level.partList=[]);var previousFragmentPart=0<currentPart?partList[partList.length-1]:void 0,index=currentPart++,partAttrs=new AttrList(value1);substituteVariablesInAttributes(level,partAttrs,['BYTERANGE','URI']);var part=new Part(partAttrs,frag,baseurl,index,previousFragmentPart);partList.push(part),frag.duration+=part.duration;break}case'PRELOAD-HINT':{var preloadHintAttrs=new AttrList(value1);substituteVariablesInAttributes(level,preloadHintAttrs,['URI']),level.preloadHint=preloadHintAttrs;break}case'RENDITION-REPORT':{var renditionReportAttrs=new AttrList(value1);substituteVariablesInAttributes(level,renditionReportAttrs,['URI']),level.renditionReports=level.renditionReports||[],level.renditionReports.push(renditionReportAttrs);break}default:logger.warn('line parsed but not handled: '+result);}}}prevFrag&&!prevFrag.relurl?(fragments.pop(),totalduration-=prevFrag.duration,level.partList&&(level.fragmentHint=prevFrag)):level.partList&&(assignProgramDateTime(frag,prevFrag),frag.cc=discontinuityCounter,level.fragmentHint=frag,levelkeys&&setFragLevelKeys(frag,levelkeys,level));var fragmentLength=fragments.length,firstFragment=fragments[0],lastFragment=fragments[fragmentLength-1];if(totalduration+=level.skippedSegments*level.targetduration,0<totalduration&&fragmentLength&&lastFragment){level.averagetargetduration=totalduration/fragmentLength;var lastSn=lastFragment.sn;level.endSN='initSegment'===lastSn?0:lastSn,level.live||(lastFragment.endList=!0),firstFragment&&(level.startCC=firstFragment.cc)}else level.endSN=0,level.startCC=0;return level.fragmentHint&&(totalduration+=level.fragmentHint.duration),level.totalduration=totalduration,level.endCC=discontinuityCounter,0<firstPdtIndex&&backfillProgramDateTimes(fragments,firstPdtIndex),level},M3U8Parser}(),PlaylistContextType={MANIFEST:'manifest',LEVEL:'level',AUDIO_TRACK:'audioTrack',SUBTITLE_TRACK:'subtitleTrack'},PlaylistLevelType={MAIN:'main',AUDIO:'audio',SUBTITLE:'subtitle'},PlaylistLoader=function(){function PlaylistLoader(hls){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=hls,this.registerListeners()}var _proto=PlaylistLoader.prototype;return _proto.startLoad=function(){},_proto.stopLoad=function(){this.destroyInternalLoaders()}
1,_proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),hls.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),hls.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},_proto.createInternalLoader=function(context){var config=this.hls.config,PLoader=config.pLoader,Loader=config.loader,loader=new(PLoader||Loader)(config);return this.loaders[context.type]=loader,loader},_proto.getInternalLoader=function(context){return this.loaders[context.type]},_proto.resetInternalLoader=function(contextType){this.loaders[contextType]&&delete this.loaders[contextType]},_proto.destroyInternalLoaders=function(){for(var contextType in this.loaders){var loader=this.loaders[contextType];loader&&loader.destroy(),this.resetInternalLoader(contextType)}},_proto.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},_proto.onManifestLoading=function(event,data){var url=data.url;this.variableList=null,this.load({id:null,level:0,responseType:'text',type:PlaylistContextType.MANIFEST,url:url,deliveryDirectives:null})},_proto.onLevelLoading=function(event,data){var id=data.id,level=data.level,pathwayId=data.pathwayId,url=data.url,deliveryDirectives=data.deliveryDirectives;this.load({id:id,level:level,pathwayId:pathwayId,responseType:'text',type:PlaylistContextType.LEVEL,url:url,deliveryDirectives:deliveryDirectives})},_proto.onAudioTrackLoading=function(event,data){var id=data.id,groupId=data.groupId,url=data.url,deliveryDirectives=data.deliveryDirectives;this.load({id:id,groupId:groupId,level:null,responseType:'text',type:PlaylistContextType.AUDIO_TRACK,url:url,deliveryDirectives:deliveryDirectives})},_proto.onSubtitleTrackLoading=function(event,data){var id=data.id,groupId=data.groupId,url=data.url,deliveryDirectives=data.deliveryDirectives;this.load({id:id,groupId:groupId,level:null,responseType:'text',type:PlaylistContextType.SUBTITLE_TRACK,url:url,deliveryDirectives:deliveryDirectives})},_proto.load=function(context){var _this=this,config=this.hls.config,loader=this.getInternalLoader(context),_context$deliveryDire;if(loader){var loaderContext=loader.context;if(loaderContext&&loaderContext.url===context.url&&loaderContext.level===context.level)return void logger.trace('[playlist-loader]: playlist request ongoing');logger.log('[playlist-loader]: aborting previous loader for type: '+context.type),loader.abort()}var loadPolicy;if(loadPolicy=context.type===PlaylistContextType.MANIFEST?config.manifestLoadPolicy.default:_extends({},config.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),loader=this.createInternalLoader(context),isFiniteNumber(null==(_context$deliveryDire=context.deliveryDirectives)?void 0:_context$deliveryDire.part)){var levelDetails;if(context.type===PlaylistContextType.LEVEL&&null!==context.level?levelDetails=this.hls.levels[context.level].details:context.type===PlaylistContextType.AUDIO_TRACK&&null!==context.id?levelDetails=this.hls.audioTracks[context.id].details:context.type===PlaylistContextType.SUBTITLE_TRACK&&null!==context.id&&(levelDetails=this.hls.subtitleTracks[context.id].details),levelDetails){var partTarget=levelDetails.partTarget,targetDuration=levelDetails.targetduration;if(partTarget&&targetDuration){var maxLowLatencyPlaylistRefresh=1e3*Math.max(3*partTarget,.8*targetDuration);loadPolicy=_extends({},loadPolicy,{maxTimeToFirstByteMs:Math.min(maxLowLatencyPlaylistRefresh,loadPolicy.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(maxLowLatencyPlaylistRefresh,loadPolicy.maxTimeToFirstByteMs)})}}}var legacyRetryCompatibility=loadPolicy.errorRetry||loadPolicy.timeoutRetry||{},loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:legacyRetryCompatibility.maxNumRetry||0,retryDelay:legacyRetryCompatibility.retryDelayMs||0,maxRetryDelay:legacyRetryCompatibility.maxRetryDelayMs||0};loader.load(context,loaderConfig,{onSuccess:function(response,stats,context,networkDetails){var loader=_this.getInternalLoader(context);_this.resetInternalLoader(context.type);var string=response.data;return 0===string.indexOf('#EXTM3U')?void(stats.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(string)?_this.handleTrackOrLevelPlaylist(response,stats,context,networkDetails||null,loader):_this.handleMasterPlaylist(response,stats,context,networkDetails)):void _this.handleManifestParsingError(response,context,new Error('no EXTM3U delimiter'),networkDetails||null,stats)},onError:function(response,context,networkDetails,stats){_this.handleNetworkError(context,networkDetails,!1,response,stats)},onTimeout:function(stats,context,networkDetails){_this.handleNetworkError(context,networkDetails,!0,void 0,stats)}})},_proto.handleMasterPlaylist=function(response,stats,context,networkDetails){var hl
1s=this.hls,string=response.data,url=getResponseUrl(response,context),parsedResult=M3U8Parser.parseMasterPlaylist(string,url);if(parsedResult.playlistParsingError)return void this.handleManifestParsingError(response,context,parsedResult.playlistParsingError,networkDetails,stats);var contentSteering=parsedResult.contentSteering,levels=parsedResult.levels,sessionData=parsedResult.sessionData,sessionKeys=parsedResult.sessionKeys,startTimeOffset=parsedResult.startTimeOffset,variableList=parsedResult.variableList;this.variableList=variableList;var _M3U8Parser$parseMast=M3U8Parser.parseMasterPlaylistMedia(string,url,parsedResult),_M3U8Parser$parseMast2=_M3U8Parser$parseMast.AUDIO,audioTracks=void 0===_M3U8Parser$parseMast2?[]:_M3U8Parser$parseMast2,subtitles=_M3U8Parser$parseMast.SUBTITLES,captions=_M3U8Parser$parseMast['CLOSED-CAPTIONS'];if(audioTracks.length){var embeddedAudioFound=audioTracks.some(function(audioTrack){return!audioTrack.url});embeddedAudioFound||!levels[0].audioCodec||levels[0].attrs.AUDIO||(logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one'),audioTracks.unshift({type:'main',name:'main',groupId:'main',default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:''}))}hls.trigger(Events.MANIFEST_LOADED,{levels:levels,audioTracks:audioTracks,subtitles:subtitles,captions:captions,contentSteering:contentSteering,url:url,stats:stats,networkDetails:networkDetails,sessionData:sessionData,sessionKeys:sessionKeys,startTimeOffset:startTimeOffset,variableList:variableList})},_proto.handleTrackOrLevelPlaylist=function(response,stats,context,networkDetails,loader){var hls=this.hls,id=context.id,level=context.level,type=context.type,url=getResponseUrl(response,context),levelId=isFiniteNumber(level)?level:isFiniteNumber(id)?id:0,levelType=mapContextToLevelType(context),levelDetails=M3U8Parser.parseLevelPlaylist(response.data,url,levelId,levelType,0,this.variableList);if(type===PlaylistContextType.MANIFEST){var singleLevel={attrs:new AttrList({}),bitrate:0,details:levelDetails,name:'',url:url};hls.trigger(Events.MANIFEST_LOADED,{levels:[singleLevel],audioTracks:[],url:url,stats:stats,networkDetails:networkDetails,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}stats.parsing.end=performance.now(),context.levelDetails=levelDetails,this.handlePlaylistLoaded(levelDetails,response,stats,context,networkDetails,loader)},_proto.handleManifestParsingError=function(response,context,error,networkDetails,stats){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:context.type===PlaylistContextType.MANIFEST,url:response.url,err:error,error:error,reason:error.message,response:response,context:context,networkDetails:networkDetails,stats:stats})},_proto.handleNetworkError=function(context,networkDetails,timeout,response,stats){void 0===timeout&&(timeout=!1);var message='A network '+(timeout?'timeout':'error'+(response?' (status '+response.code+')':''))+' occurred while loading '+context.type;context.type===PlaylistContextType.LEVEL?message+=': '+context.level+' id: '+context.id:(context.type===PlaylistContextType.AUDIO_TRACK||context.type===PlaylistContextType.SUBTITLE_TRACK)&&(message+=' id: '+context.id+' group-id: "'+context.groupId+'"');var error=new Error(message);logger.warn('[playlist-loader]: '+message);var details=ErrorDetails.UNKNOWN,fatal=!1,loader=this.getInternalLoader(context);switch(context.type){case PlaylistContextType.MANIFEST:details=timeout?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,fatal=!0;break;case PlaylistContextType.LEVEL:details=timeout?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,fatal=!1;break;case PlaylistContextType.AUDIO_TRACK:details=timeout?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal=!1;break;case PlaylistContextType.SUBTITLE_TRACK:details=timeout?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,fatal=!1;}loader&&this.resetInternalLoader(context.type);
1var errorData={type:ErrorTypes.NETWORK_ERROR,details:details,fatal:fatal,url:context.url,loader:loader,context:context,error:error,networkDetails:networkDetails,stats:stats};if(response){var url=(null==networkDetails?void 0:networkDetails.url)||context.url;errorData.response=_objectSpread2({url:url,data:void 0},response)}this.hls.trigger(Events.ERROR,errorData)},_proto.handlePlaylistLoaded=function(levelDetails,response,stats,context,networkDetails,loader){var hls=this.hls,type=context.type,level=context.level,id=context.id,groupId=context.groupId,deliveryDirectives=context.deliveryDirectives,url=getResponseUrl(response,context),parent=mapContextToLevelType(context),levelIndex='number'==typeof context.level&&parent===PlaylistLevelType.MAIN?level:void 0;if(!levelDetails.fragments.length){var _error=new Error('No Segments found in Playlist');return void hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:url,error:_error,reason:_error.message,response:response,context:context,level:levelIndex,parent:parent,networkDetails:networkDetails,stats:stats})}levelDetails.targetduration||(levelDetails.playlistParsingError=new Error('Missing Target Duration'));var error=levelDetails.playlistParsingError;return error?void hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:url,error:error,reason:error.message,response:response,context:context,level:levelIndex,parent:parent,networkDetails:networkDetails,stats:stats}):void(levelDetails.live&&loader&&(loader.getCacheAge&&(levelDetails.ageHeader=loader.getCacheAge()||0),(!loader.getCacheAge||isNaN(levelDetails.ageHeader))&&(levelDetails.ageHeader=0)),type===PlaylistContextType.MANIFEST||type===PlaylistContextType.LEVEL?hls.trigger(Events.LEVEL_LOADED,{details:levelDetails,level:levelIndex||0,id:id||0,stats:stats,networkDetails:networkDetails,deliveryDirectives:deliveryDirectives}):type===PlaylistContextType.AUDIO_TRACK?hls.trigger(Events.AUDIO_TRACK_LOADED,{details:levelDetails,id:id||0,groupId:groupId||'',stats:stats,networkDetails:networkDetails,deliveryDirectives:deliveryDirectives}):type===PlaylistContextType.SUBTITLE_TRACK?hls.trigger(Events.SUBTITLE_TRACK_LOADED,{details:levelDetails,id:id||0,groupId:groupId||'',stats:stats,networkDetails:networkDetails,deliveryDirectives:deliveryDirectives}):void 0)},PlaylistLoader}(),MetadataSchema={audioId3:'org.id3',dateRange:'com.apple.quicktime.HLS',emsg:'https://aomedia.org/emsg/ID3'},MAX_CUE_ENDTIME=function(){var Cue=getCueClass();try{Cue&&new Cue(0,Number.POSITIVE_INFINITY,'')}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),ID3TrackController=function(){function ID3TrackController(hls){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=hls,this._registerListeners()}var _proto=ID3TrackController.prototype;return _proto.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null},_proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),hls.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),hls.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this)},_proto.onMediaAttached=function(event,data){this.media=data.media},_proto.onMediaDetaching=function(){this.id3Track&&(clearCurrentCues(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})},_proto.onManifestLoading=function(){this.dateRangeCuesAppended={}},_proto.createTrack=function(media){var track=this.getID3Track(media.textTracks);return track.mode='hidden',track},_proto.getID3Track=function(textTracks){if(this.media){for(var i=0,textTrack;i<textTracks.length;i++)if(textTrack=textTracks[i],'metadata'===textTrack.kind&&'id3'===textTrack.label)return sendAddTrackEvent(textTrack,this.media),textTrack;return this.media.addTextTrack('metadata','id3')}},_proto.onFragParsingMetadata=function(event,data){if(this.media){var _this$hls$config=this.hls.config,enableEmsgMetadataCues=_this$hls$config.enableEmsgMetadataCues,enableID3MetadataCues=_this$hls$config.enableID3MetadataCues;if(enableEmsgMetadataCues||enableID3MetadataCues){var samples=data.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var Cue=getCueClass();if(Cue)for(var i=0,type;i<samples.length;i++)if(type=samples[i].type,(type!==MetadataSchema.emsg||enableEmsgMetadataCues)&&enableID3MetadataCues){var frames=getID3Frames(samples[i].data);if(frames){var startTime=samples[i].pts,endTime=startTime+samples[i].duration;endTime>MAX_CUE_ENDTIME&&(endTime=MAX_CUE_ENDTIME);var timeDiff=endTime-startTime;0>=timeDiff&&(endTime=startTime+.25);for(var j=0,frame;j<frames.length;
1j++)if(frame=frames[j],!isTimeStampFrame(frame)){this.updateId3CueEnds(startTime,type);var cue=createCueWithDataFields(Cue,startTime,endTime,frame,type);cue&&this.id3Track.addCue(cue)}}}}}},_proto.updateId3CueEnds=function(startTime,type){var cues=null==(_this$id3Track=this.id3Track)?void 0:_this$id3Track.cues,_this$id3Track;if(cues)for(var i=cues.length,cue;i--;)cue=cues[i],cue.type===type&&cue.startTime<startTime&&cue.endTime===MAX_CUE_ENDTIME&&(cue.endTime=startTime)},_proto.onBufferFlushing=function(event,_ref){var startOffset=_ref.startOffset,endOffset=_ref.endOffset,type=_ref.type,id3Track=this.id3Track,hls=this.hls;if(hls){var _hls$config=hls.config,enableEmsgMetadataCues=_hls$config.enableEmsgMetadataCues,enableID3MetadataCues=_hls$config.enableID3MetadataCues;if(id3Track&&(enableEmsgMetadataCues||enableID3MetadataCues)){var predicate;predicate='audio'===type?function(cue){return cue.type===MetadataSchema.audioId3&&enableID3MetadataCues}:'video'===type?function(cue){return cue.type===MetadataSchema.emsg&&enableEmsgMetadataCues}:function(cue){return cue.type===MetadataSchema.audioId3&&enableID3MetadataCues||cue.type===MetadataSchema.emsg&&enableEmsgMetadataCues},removeCuesInRange(id3Track,startOffset,endOffset,predicate)}}},_proto.onLevelUpdated=function(event,_ref2){var _this=this,details=_ref2.details;if(this.media&&details.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var dateRangeCuesAppended=this.dateRangeCuesAppended,id3Track=this.id3Track,dateRanges=details.dateRanges,ids=Object.keys(dateRanges);if(id3Track)for(var idsToRemove=Object.keys(dateRangeCuesAppended).filter(function(id){return!ids.includes(id)}),_loop=function(){var id=idsToRemove[i];Object.keys(dateRangeCuesAppended[id].cues).forEach(function(key){id3Track.removeCue(dateRangeCuesAppended[id].cues[key])}),delete dateRangeCuesAppended[id]},i=idsToRemove.length;i--;)_loop();var lastFragment=details.fragments[details.fragments.length-1];if(0!==ids.length&&isFiniteNumber(null==lastFragment?void 0:lastFragment.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var dateTimeOffset=lastFragment.programDateTime/1e3-lastFragment.start,Cue=getCueClass(),_loop2=function(){var id=ids[_i],dateRange=dateRanges[id],startTime=dateRangeDateToTimelineSeconds(dateRange.startDate,dateTimeOffset),appendedDateRangeCues=dateRangeCuesAppended[id],cues=(null==appendedDateRangeCues?void 0:appendedDateRangeCues.cues)||{},durationKnown=(null==appendedDateRangeCues?void 0:appendedDateRangeCues.durationKnown)||!1,endTime=MAX_CUE_ENDTIME,endDate=dateRange.endDate;if(endDate)endTime=dateRangeDateToTimelineSeconds(endDate,dateTimeOffset),durationKnown=!0;else if(dateRange.endOnNext&&!durationKnown){var nextDateRangeWithSameClass=ids.reduce(function(candidateDateRange,id){if(id!==dateRange.id){var otherDateRange=dateRanges[id];if(otherDateRange.class===dateRange.class&&otherDateRange.startDate>dateRange.startDate&&(!candidateDateRange||dateRange.startDate<candidateDateRange.startDate))return otherDateRange}return candidateDateRange},null);nextDateRangeWithSameClass&&(endTime=dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate,dateTimeOffset),durationKnown=!0)}for(var attributes=Object.keys(dateRange.attr),j=0,key;j<attributes.length;j++)if(key=attributes[j],!!isDateRangeCueAttribute(key)){var cue=cues[key];if(cue)durationKnown&&!appendedDateRangeCues.durationKnown&&(cue.endTime=endTime);else if(Cue){var data=dateRange.attr[key];isSCTE35Attribute(key)&&(data=hexToArrayBuffer(data));var _cue=createCueWithDataFields(Cue,startTime,endTime,{key:key,data:data},MetadataSchema.dateRange);_cue&&(_cue.id=id,_this.id3Track.addCue(_cue),cues[key]=_cue)}}dateRangeCuesAppended[id]={cues:cues,dateRange:dateRange,durationKnown:durationKnown}},_i=0;_i<ids.length;_i++)_loop2()}}},ID3TrackController}(),LatencyController=function(){function LatencyController(hls){var _this=this;this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=function(){return _this.timeupdate()},this.hls=hls,this.config=hls.config,this.registerListeners()}var _proto=LatencyController.prototype;return _proto.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null},_proto.registerListeners=function(){this.hls.on(Events.MEDIA_ATTA
1CHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Events.ERROR,this.onError,this)},_proto.unregisterListeners=function(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Events.ERROR,this.onError,this)},_proto.onMediaAttached=function(event,data){this.media=data.media,this.media.addEventListener('timeupdate',this.timeupdateHandler)},_proto.onMediaDetaching=function(){this.media&&(this.media.removeEventListener('timeupdate',this.timeupdateHandler),this.media=null)},_proto.onManifestLoading=function(){this.levelDetails=null,this._latency=null,this.stallCount=0},_proto.onLevelUpdated=function(event,_ref){var details=_ref.details;this.levelDetails=details,details.advanced&&this.timeupdate(),!details.live&&this.media&&this.media.removeEventListener('timeupdate',this.timeupdateHandler)},_proto.onError=function(event,data){var _this$levelDetails;data.details!==ErrorDetails.BUFFER_STALLED_ERROR||(this.stallCount++,null!=(_this$levelDetails=this.levelDetails)&&_this$levelDetails.live&&logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency'))},_proto.timeupdate=function(){var media=this.media,levelDetails=this.levelDetails;if(media&&levelDetails){this.currentTime=media.currentTime;var latency=this.computeLatency();if(null!==latency){this._latency=latency;var _this$config=this.config,lowLatencyMode=_this$config.lowLatencyMode,maxLiveSyncPlaybackRate=_this$config.maxLiveSyncPlaybackRate;if(lowLatencyMode&&1!==maxLiveSyncPlaybackRate&&levelDetails.live){var targetLatency=this.targetLatency;if(null!==targetLatency){var distanceFromTarget=latency-targetLatency,liveMinLatencyDuration=Math.min(this.maxLatency,targetLatency+levelDetails.targetduration);if(distanceFromTarget<liveMinLatencyDuration&&.05<distanceFromTarget&&1<this.forwardBufferLength){var max=Math.min(2,Math.max(1,maxLiveSyncPlaybackRate)),rate=Math.round(20*(2/(1+Math.exp(-.75*distanceFromTarget-this.edgeStalled))))/20;media.playbackRate=Math.min(max,Math.max(1,rate))}else 1!==media.playbackRate&&0!==media.playbackRate&&(media.playbackRate=1)}}}}},_proto.estimateLiveEdge=function(){var levelDetails=this.levelDetails;return null===levelDetails?null:levelDetails.edge+levelDetails.age},_proto.computeLatency=function(){var liveEdge=this.estimateLiveEdge();return null===liveEdge?null:liveEdge-this.currentTime},_createClass(LatencyController,[{key:'latency',get:function(){return this._latency||0}},{key:'maxLatency',get:function(){var config=this.config,levelDetails=this.levelDetails;return void 0===config.liveMaxLatencyDuration?levelDetails?config.liveMaxLatencyDurationCount*levelDetails.targetduration:0:config.liveMaxLatencyDuration}},{key:'targetLatency',get:function(){var levelDetails=this.levelDetails;if(null===levelDetails)return null;var holdBack=levelDetails.holdBack,partHoldBack=levelDetails.partHoldBack,targetduration=levelDetails.targetduration,_this$config2=this.config,liveSyncDuration=_this$config2.liveSyncDuration,liveSyncDurationCount=_this$config2.liveSyncDurationCount,lowLatencyMode=_this$config2.lowLatencyMode,userConfig=this.hls.userConfig,targetLatency=lowLatencyMode?partHoldBack||holdBack:holdBack;(userConfig.liveSyncDuration||userConfig.liveSyncDurationCount||0===targetLatency)&&(targetLatency=void 0===liveSyncDuration?liveSyncDurationCount*targetduration:liveSyncDuration);return targetLatency+Math.min(this.stallCount*1,targetduration)}},{key:'liveSyncPosition',get:function(){var liveEdge=this.estimateLiveEdge(),targetLatency=this.targetLatency,levelDetails=this.levelDetails;if(null===liveEdge||null===targetLatency||null===levelDetails)return null;var edge=levelDetails.edge,syncPosition=liveEdge-targetLatency-this.edgeStalled,min=edge-levelDetails.totalduration,max=edge-(this.config.lowLatencyMode&&levelDetails.partTarget||levelDetails.targetduration);return Math.min(Math.max(min,syncPosition),max)}},{key:'drift',get:function(){var levelDetails=this.levelDetails;return null===levelDetails?1:levelDetails.drift}},{key:'edgeStalled',get:function(){var levelDetails=this.levelDetails;if(null===levelDetails)return 0;var maxLevelUpdateAge=3*(this.config.lowLatencyMode&&levelDetails.partTarget||levelDetails.targetduration);return Math.max(levelDetails.age-maxLevelUpdateAge,0)}},{key:'forwardBufferLength',get:function(){var media=this.media,levelDetails=this.levelDetails;
1if(!media||!levelDetails)return 0;var bufferedRanges=media.buffered.length;return(bufferedRanges?media.buffered.end(bufferedRanges-1):levelDetails.edge)-this.currentTime}}]),LatencyController}(),HdcpLevels=['NONE','TYPE-0','TYPE-1',null],VideoRangeValues=['SDR','PQ','HLG'],HlsSkip={No:'',Yes:'YES',v2:'v2'},HlsUrlParameters=function(){function HlsUrlParameters(msn,part,skip){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=msn,this.part=part,this.skip=skip}var _proto=HlsUrlParameters.prototype;return _proto.addDirectives=function(uri){var url=new self.URL(uri);return void 0!==this.msn&&url.searchParams.set('_HLS_msn',this.msn.toString()),void 0!==this.part&&url.searchParams.set('_HLS_part',this.part.toString()),this.skip&&url.searchParams.set('_HLS_skip',this.skip),url.href},HlsUrlParameters}(),Level=function(){function Level(data){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[data.url],this._attrs=[data.attrs],this.bitrate=data.bitrate,data.details&&(this.details=data.details),this.id=data.id||0,this.name=data.name,this.width=data.width||0,this.height=data.height||0,this.frameRate=data.attrs.optionalFloat('FRAME-RATE',0),this._avgBitrate=data.attrs.decimalInteger('AVERAGE-BANDWIDTH'),this.audioCodec=data.audioCodec,this.videoCodec=data.videoCodec,this.codecSet=[data.videoCodec,data.audioCodec].filter(function(c){return!!c}).map(function(s){return s.substring(0,4)}).join(','),this.addGroupId('audio',data.attrs.AUDIO),this.addGroupId('text',data.attrs.SUBTITLES)}var _proto2=Level.prototype;return _proto2.hasAudioGroup=function(groupId){return hasGroup(this._audioGroups,groupId)},_proto2.hasSubtitleGroup=function(groupId){return hasGroup(this._subtitleGroups,groupId)},_proto2.addGroupId=function(type,groupId){if(groupId)if('audio'===type){var audioGroups=this._audioGroups;audioGroups||(audioGroups=this._audioGroups=[]),-1===audioGroups.indexOf(groupId)&&audioGroups.push(groupId)}else if('text'===type){var subtitleGroups=this._subtitleGroups;subtitleGroups||(subtitleGroups=this._subtitleGroups=[]),-1===subtitleGroups.indexOf(groupId)&&subtitleGroups.push(groupId)}},_proto2.addFallback=function(){},_createClass(Level,[{key:'maxBitrate',get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:'averageBitrate',get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:'attrs',get:function(){return this._attrs[0]}},{key:'codecs',get:function(){return this.attrs.CODECS||''}},{key:'pathwayId',get:function(){return this.attrs['PATHWAY-ID']||'.'}},{key:'videoRange',get:function(){return this.attrs['VIDEO-RANGE']||'SDR'}},{key:'score',get:function(){return this.attrs.optionalFloat('SCORE',0)}},{key:'uri',get:function(){return this.url[0]||''}},{key:'audioGroups',get:function(){return this._audioGroups}},{key:'subtitleGroups',get:function(){return this._subtitleGroups}},{key:'urlId',get:function(){return 0},set:function(){}},{key:'audioGroupIds',get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:'textGroupIds',get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:'audioGroupId',get:function(){var _this$audioGroups;return null==(_this$audioGroups=this.audioGroups)?void 0:_this$audioGroups[0]}},{key:'textGroupId',get:function(){var _this$subtitleGroups;return null==(_this$subtitleGroups=this.subtitleGroups)?void 0:_this$subtitleGroups[0]}}]),Level}(),BinarySearch={search:function(list,comparisonFn){for(var minIndex=0,maxIndex=list.length-1,currentIndex=null,currentElement=null;minIndex<=maxIndex;){currentIndex=0|(minIndex+maxIndex)/2,currentElement=list[currentIndex];var comparisonResult=comparisonFn(currentElement);if(0<comparisonResult)minIndex=currentIndex+1;else if(0>comparisonResult)maxIndex=currentIndex-1;else return currentElement}return null}},NetworkErrorAction={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ErrorActionFlags={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4},ErrorController=function(){function ErrorController(hls){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=hls,this.log=logger.log.bind(logger,'[info]:'),this.warn=logger.warn.bind(logger,'[warning]:'),this.error=logger.error.bind(logger,'[error]:'),this.registerListeners()}
1var _proto=ErrorController.prototype;return _proto.registerListeners=function(){var hls=this.hls;hls.on(Events.ERROR,this.onError,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls&&(hls.off(Events.ERROR,this.onError,this),hls.off(Events.ERROR,this.onErrorOut,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this))},_proto.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},_proto.startLoad=function(){},_proto.stopLoad=function(){this.playlistError=0},_proto.getVariantLevelIndex=function(frag){return(null==frag?void 0:frag.type)===PlaylistLevelType.MAIN?frag.level:this.hls.loadLevel},_proto.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},_proto.onLevelUpdated=function(){this.playlistError=0},_proto.onError=function(event,data){var _data$frag,_data$level;if(!data.fatal){var hls=this.hls,context=data.context;switch(data.details){case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:return void(data.errorAction=this.getFragRetryOrSwitchAction(data));case ErrorDetails.FRAG_PARSING_ERROR:if(null!=(_data$frag=data.frag)&&_data$frag.gap)return void(data.errorAction={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None});case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_DECRYPT_ERROR:return data.errorAction=this.getFragRetryOrSwitchAction(data),void(data.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox);case ErrorDetails.LEVEL_EMPTY_ERROR:case ErrorDetails.LEVEL_PARSING_ERROR:{var levelIndex=data.parent===PlaylistLevelType.MAIN?data.level:hls.loadLevel,_data$context,_data$context$levelDe;data.details===ErrorDetails.LEVEL_EMPTY_ERROR&&null!=(_data$context=data.context)&&null!=(_data$context$levelDe=_data$context.levelDetails)&&_data$context$levelDe.live?data.errorAction=this.getPlaylistRetryOrSwitchAction(data,levelIndex):(data.levelRetry=!1,data.errorAction=this.getLevelSwitchAction(data,levelIndex))}return;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:return void('number'==typeof(null==context?void 0:context.level)&&(data.errorAction=this.getPlaylistRetryOrSwitchAction(data,context.level)));case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_LOAD_ERROR:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:if(context){var level=hls.levels[hls.loadLevel];if(level&&(context.type===PlaylistContextType.AUDIO_TRACK&&level.hasAudioGroup(context.groupId)||context.type===PlaylistContextType.SUBTITLE_TRACK&&level.hasSubtitleGroup(context.groupId)))return data.errorAction=this.getPlaylistRetryOrSwitchAction(data,hls.loadLevel),data.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox,void(data.errorAction.flags=ErrorActionFlags.MoveAllAlternatesMatchingHost)}return;case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{var _level=hls.levels[hls.loadLevel],restrictedHdcpLevel=null==_level?void 0:_level.attrs['HDCP-LEVEL'];restrictedHdcpLevel?data.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHDCP,hdcpLevel:restrictedHdcpLevel}:this.keySystemError(data)}return;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:return void(data.errorAction=this.getLevelSwitchAction(data,null==(_data$level=data.level)?hls.loadLevel:_data$level));case ErrorDetails.INTERNAL_EXCEPTION:case ErrorDetails.BUFFER_APPENDING_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:case ErrorDetails.LEVEL_SWITCH_ERROR:case ErrorDetails.BUFFER_STALLED_ERROR:case ErrorDetails.BUFFER_SEEK_OVER_HOLE:case ErrorDetails.BUFFER_NUDGE_ON_STALL:return void(data.errorAction={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None});}data.type===ErrorTypes.KEY_SYSTEM_ERROR&&this.keySystemError(data)}},_proto.keySystemError=function(data){var levelIndex=this.getVariantLevelIndex(data.frag);data.levelRetry=!1,data.errorAction=this.getLevelSwitchAction(data,levelIndex)},_proto.getPlaylistRetryOrSwitchAction=function(data,levelIndex){var hl
1s=this.hls,retryConfig=getRetryConfig(hls.config.playlistLoadPolicy,data),retryCount=this.playlistError++,retry=shouldRetry(retryConfig,retryCount,isTimeoutError(data),data.response);if(retry)return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:retryConfig,retryCount:retryCount};var errorAction=this.getLevelSwitchAction(data,levelIndex);return retryConfig&&(errorAction.retryConfig=retryConfig,errorAction.retryCount=retryCount),errorAction},_proto.getFragRetryOrSwitchAction=function(data){var hls=this.hls,variantLevelIndex=this.getVariantLevelIndex(data.frag),level=hls.levels[variantLevelIndex],_hls$config=hls.config,fragLoadPolicy=_hls$config.fragLoadPolicy,keyLoadPolicy=_hls$config.keyLoadPolicy,retryConfig=getRetryConfig(data.details.startsWith('key')?keyLoadPolicy:fragLoadPolicy,data),fragmentErrors=hls.levels.reduce(function(acc,level){return acc+level.fragmentError},0);if(level){data.details!==ErrorDetails.FRAG_GAP&&level.fragmentError++;var retry=shouldRetry(retryConfig,fragmentErrors,isTimeoutError(data),data.response);if(retry)return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:retryConfig,retryCount:fragmentErrors}}var errorAction=this.getLevelSwitchAction(data,variantLevelIndex);return retryConfig&&(errorAction.retryConfig=retryConfig,errorAction.retryCount=fragmentErrors),errorAction},_proto.getLevelSwitchAction=function(data,levelIndex){var hls=this.hls;(null===levelIndex||void 0===levelIndex)&&(levelIndex=hls.loadLevel);var level=this.hls.levels[levelIndex];if(level){var errorDetails=data.details,_data$frag2,_data$context2;level.loadError++,errorDetails===ErrorDetails.BUFFER_APPEND_ERROR&&level.fragmentError++;var nextLevel=-1,levels=hls.levels,loadLevel=hls.loadLevel,minAutoLevel=hls.minAutoLevel,maxAutoLevel=hls.maxAutoLevel;hls.autoLevelEnabled||(hls.loadLevel=-1);for(var fragErrorType=null==(_data$frag2=data.frag)?void 0:_data$frag2.type,isAudioCodecError=fragErrorType===PlaylistLevelType.AUDIO&&errorDetails===ErrorDetails.FRAG_PARSING_ERROR||'audio'===data.sourceBufferName&&(errorDetails===ErrorDetails.BUFFER_ADD_CODEC_ERROR||errorDetails===ErrorDetails.BUFFER_APPEND_ERROR),findAudioCodecAlternate=isAudioCodecError&&levels.some(function(_ref){var audioCodec=_ref.audioCodec;return level.audioCodec!==audioCodec}),isVideoCodecError='video'===data.sourceBufferName&&(errorDetails===ErrorDetails.BUFFER_ADD_CODEC_ERROR||errorDetails===ErrorDetails.BUFFER_APPEND_ERROR),findVideoCodecAlternate=isVideoCodecError&&levels.some(function(_ref2){var codecSet=_ref2.codecSet,audioCodec=_ref2.audioCodec;return level.codecSet!==codecSet&&level.audioCodec===audioCodec}),_ref3=null==(_data$context2=data.context)?{}:_data$context2,playlistErrorType=_ref3.type,playlistErrorGroupId=_ref3.groupId,_loop=function(){var candidate=(i+loadLevel)%levels.length;if(candidate!==loadLevel&&candidate>=minAutoLevel&&candidate<=maxAutoLevel&&0===levels[candidate].loadError){var levelCandidate=levels[candidate],_level$audioGroups,_level$subtitleGroups;if(errorDetails===ErrorDetails.FRAG_GAP&&fragErrorType===PlaylistLevelType.MAIN&&data.frag){var levelDetails=levels[candidate].details;if(levelDetails){var fragCandidate=findFragmentByPTS(data.frag,levelDetails.fragments,data.frag.start);if(null!=fragCandidate&&fragCandidate.gap)return 0}}else{if(playlistErrorType===PlaylistContextType.AUDIO_TRACK&&levelCandidate.hasAudioGroup(playlistErrorGroupId)||playlistErrorType===PlaylistContextType.SUBTITLE_TRACK&&levelCandidate.hasSubtitleGroup(playlistErrorGroupId))return 0;if(fragErrorType===PlaylistLevelType.AUDIO&&null!=(_level$audioGroups=level.audioGroups)&&_level$audioGroups.some(function(groupId){return levelCandidate.hasAudioGroup(groupId)})||fragErrorType===PlaylistLevelType.SUBTITLE&&null!=(_level$subtitleGroups=level.subtitleGroups)&&_level$subtitleGroups.some(function(groupId){return levelCandidate.hasSubtitleGroup(groupId)})||findAudioCodecAlternate&&level.audioCodec===levelCandidate.audioCodec||!findAudioCodecAlternate&&level.audioCodec!==levelCandidate.audioCodec||findVideoCodecAlternate&&level.codecSet===levelCandidate.codecSet)return 0}return nextLevel=candidate,1}},i=levels.length,_ret;i--&&(_ret=_loop(),0===_ret||1!==_ret););if(-1<nextLevel&&hls.loadLevel!==nextLevel)return data.levelRetry=!0,this.playlistError=0,{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.None,nextAutoLevel:nextLevel}}return{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHost}},_proto.onErrorOut=function(event,data){var _data$errorAction;switch(null==(_data$errorAction=data.errorAction)?void 0:_data$errorAction.action){case NetworkErrorAction.DoNothing:break;case NetworkErrorAction.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(data),data.errorAction.resolved||data.details===ErrorDetails.FRAG_GAP?/MediaSource readyState: ended/.test(data.error.message)&&(this.warn('MediaSource ended after "'+data.sourceBufferName+'" sourceBuffer append error. Attempting to re
1cover from media error.'),this.hls.recoverMediaError()):data.fatal=!0;}if(data.fatal)return void this.hls.stopLoad()},_proto.sendAlternateToPenaltyBox=function(data){var hls=this.hls,errorAction=data.errorAction;if(errorAction){var flags=errorAction.flags,hdcpLevel=errorAction.hdcpLevel,nextAutoLevel=errorAction.nextAutoLevel;flags===ErrorActionFlags.None?this.switchLevel(data,nextAutoLevel):flags===ErrorActionFlags.MoveAllAlternatesMatchingHDCP?(hdcpLevel&&(hls.maxHdcpLevel=HdcpLevels[HdcpLevels.indexOf(hdcpLevel)-1],errorAction.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+hls.maxHdcpLevel+'" or lower')):void 0,errorAction.resolved||this.switchLevel(data,nextAutoLevel)}},_proto.switchLevel=function(data,levelIndex){void 0!==levelIndex&&data.errorAction&&(this.warn('switching to level '+levelIndex+' after '+data.details),this.hls.nextAutoLevel=levelIndex,data.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},ErrorController}(),BasePlaylistController=function(){function BasePlaylistController(hls,logPrefix){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=logger.log.bind(logger,logPrefix+':'),this.warn=logger.warn.bind(logger,logPrefix+':'),this.hls=hls}var _proto=BasePlaylistController.prototype;return _proto.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},_proto.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},_proto.startLoad=function(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()},_proto.stopLoad=function(){this.canLoad=!1,this.clearTimer()},_proto.switchParams=function(playlistUri,previous,current){var renditionReports=null==previous?void 0:previous.renditionReports;if(renditionReports){for(var foundIndex=-1,i=0;i<renditionReports.length;i++){var attr=renditionReports[i],uri=void 0;try{uri=new self.URL(attr.URI,previous.url).href}catch(error){logger.warn('Could not construct new URL for Rendition Report: '+error),uri=attr.URI||''}if(uri===playlistUri){foundIndex=i;break}else uri===playlistUri.substring(0,uri.length)&&(foundIndex=i)}if(-1!==foundIndex){var _attr=renditionReports[foundIndex],msn=parseInt(_attr['LAST-MSN'])||(null==previous?void 0:previous.lastPartSn),part=parseInt(_attr['LAST-PART'])||(null==previous?void 0:previous.lastPartIndex);if(this.hls.config.lowLatencyMode){var currentGoal=Math.min(previous.age-previous.partTarget,previous.targetduration);0<=part&¤tGoal>previous.partTarget&&(part+=1)}var skip=current&&getSkipValue(current);return new HlsUrlParameters(msn,0<=part?part:void 0,skip)}}},_proto.loadPlaylist=function(){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())},_proto.shouldLoadPlaylist=function(playlist){return this.canLoad&&!!playlist&&!!playlist.url&&(!playlist.details||playlist.details.live)},_proto.shouldReloadPlaylist=function(playlist){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(playlist)},_proto.playlistLoaded=function(index,data,previousDetails){var _this=this,details=data.details,stats=data.stats,now=self.performance.now(),elapsed=stats.loading.first?Math.max(0,now-stats.loading.first):0;if(details.advancedDateTime=Date.now()-elapsed,details.live||null!=previousDetails&&previousDetails.live){if(details.reloaded(previousDetails),previousDetails&&this.log('live playlist '+index+' '+(details.advanced?'REFRESHED '+details.lastPartSn+'-'+details.lastPartIndex:details.updated?'UPDATED':'MISSED')),previousDetails&&0<details.fragments.length&&mergeDetails(previousDetails,details),!this.canLoad||!details.live)return;var msn=void 0,part=void 0,deliveryDirectives;if(details.canBlockReload&&details.endSN&&details.advanced){var lowLatencyMode=this.hls.config.lowLatencyMode,lastPartSn=details.lastPartSn,endSn=details.endSN,lastPartIndex=details.lastPartIndex,lastPart=lastPartSn===endSn,nextSnStartIndex=lowLatencyMode?0:lastPartIndex;-1!==lastPartIndex?(msn=lastPart?endSn+1:lastPartSn,part=lastPart?nextSnStartIndex:lastPartIndex+1):msn=endSn+1;
1var lastAdvanced=details.age,cdnAge=lastAdvanced+details.ageHeader,currentGoal=Math.min(cdnAge-details.partTarget,1.5*details.targetduration);if(0<currentGoal){if(previousDetails&¤tGoal>previousDetails.tuneInGoal)this.warn('CDN Tune-in goal increased from: '+previousDetails.tuneInGoal+' to: '+currentGoal+' with playlist age: '+details.age),currentGoal=0;else{var segments=Math.floor(currentGoal/details.targetduration);if(msn+=segments,void 0!==part){var parts=Math.round(currentGoal%details.targetduration/details.partTarget);part+=parts}this.log('CDN Tune-in age: '+details.ageHeader+'s last advanced '+lastAdvanced.toFixed(2)+'s goal: '+currentGoal+' skip sn '+segments+' to part '+part)}details.tuneInGoal=currentGoal}if(deliveryDirectives=this.getDeliveryDirectives(details,data.deliveryDirectives,msn,part),lowLatencyMode||!lastPart)return void this.loadPlaylist(deliveryDirectives)}else(details.canBlockReload||details.canSkipUntil)&&(deliveryDirectives=this.getDeliveryDirectives(details,data.deliveryDirectives,msn,part));var bufferInfo=this.hls.mainForwardBufferInfo,position=bufferInfo?bufferInfo.end-bufferInfo.len:0,distanceToLiveEdgeMs=1e3*(details.edge-position),reloadInterval=computeReloadInterval(details,distanceToLiveEdgeMs);details.updated&&now>this.requestScheduled+reloadInterval&&(this.requestScheduled=stats.loading.start),void 0!==msn&&details.canBlockReload?this.requestScheduled=stats.loading.first+reloadInterval-(1e3*details.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+reloadInterval<now?this.requestScheduled=now:0>=this.requestScheduled-now&&(this.requestScheduled+=reloadInterval);var estimatedTimeUntilUpdate=this.requestScheduled-now;estimatedTimeUntilUpdate=Math.max(0,estimatedTimeUntilUpdate),this.log('reload live playlist '+index+' in '+Math.round(estimatedTimeUntilUpdate)+' ms'),this.timer=self.setTimeout(function(){return _this.loadPlaylist(deliveryDirectives)},estimatedTimeUntilUpdate)}else this.clearTimer()},_proto.getDeliveryDirectives=function(details,previousDeliveryDirectives,msn,part){var skip=getSkipValue(details);return null!=previousDeliveryDirectives&&previousDeliveryDirectives.skip&&details.deltaUpdateFailed&&(msn=previousDeliveryDirectives.msn,part=previousDeliveryDirectives.part,skip=HlsSkip.No),new HlsUrlParameters(msn,part,skip)},_proto.checkRetry=function(errorEvent){var _this2=this,errorDetails=errorEvent.details,isTimeout=isTimeoutError(errorEvent),errorAction=errorEvent.errorAction,_ref=errorAction||{},action=_ref.action,_ref$retryCount=_ref.retryCount,retryCount=void 0===_ref$retryCount?0:_ref$retryCount,retryConfig=_ref.retryConfig,retry=!!errorAction&&!!retryConfig&&(action===NetworkErrorAction.RetryRequest||!errorAction.resolved&&action===NetworkErrorAction.SendAlternateToPenaltyBox);if(retry){var _errorEvent$context;if(this.requestScheduled=-1,retryCount>=retryConfig.maxNumRetry)return!1;if(isTimeout&&null!=(_errorEvent$context=errorEvent.context)&&_errorEvent$context.deliveryDirectives)this.warn('Retrying playlist loading '+(retryCount+1)+'/'+retryConfig.maxNumRetry+' after "'+errorDetails+'" without delivery-directives'),this.loadPlaylist();else{var delay=getRetryDelay(retryConfig,retryCount);this.timer=self.setTimeout(function(){return _this2.loadPlaylist()},delay),this.warn('Retrying playlist loading '+(retryCount+1)+'/'+retryConfig.maxNumRetry+' after "'+errorDetails+'" in '+delay+'ms')}errorEvent.levelRetry=!0,errorAction.resolved=!0}return retry},BasePlaylistController}(),EWMA=function(){function EWMA(halfLife,estimate,weight){void 0===estimate&&(estimate=0),void 0===weight&&(weight=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=halfLife,this.alpha_=halfLife?Math.exp(Math.log(.5)/halfLife):0,this.estimate_=estimate,this.totalWeight_=weight}var _proto=EWMA.prototype;return _proto.sample=function(weight,value){var adjAlpha=Math.pow(this.alpha_,weight);this.estimate_=value*(1-adjAlpha)+adjAlpha*this.estimate_,this.totalWeight_+=weight},_proto.getTotalWeight=function(){return this.totalWeight_},_proto.getEstimate=function(){if(this.alpha_){var zeroFactor=1-Math.pow(this.alpha_,this.totalWeight_);if(zeroFactor)return this.estimate_/zeroFactor}return this.estimate_},EWMA}(),EwmaBandWidthEstimator=function(){function EwmaBandWidthEstimator(slow,fast,defaultEstimate,defaultTTFB){void 0===defaultTTFB&&(defaultTTFB=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_
1=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=defaultEstimate,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(slow),this.fast_=new EWMA(fast),this.defaultTTFB_=defaultTTFB,this.ttfb_=new EWMA(slow)}var _proto=EwmaBandWidthEstimator.prototype;return _proto.update=function(slow,fast){var slow_=this.slow_,fast_=this.fast_,ttfb_=this.ttfb_;slow_.halfLife!==slow&&(this.slow_=new EWMA(slow,slow_.getEstimate(),slow_.getTotalWeight())),fast_.halfLife!==fast&&(this.fast_=new EWMA(fast,fast_.getEstimate(),fast_.getTotalWeight())),ttfb_.halfLife!==slow&&(this.ttfb_=new EWMA(slow,ttfb_.getEstimate(),ttfb_.getTotalWeight()))},_proto.sample=function(durationMs,numBytes){durationMs=Math.max(durationMs,this.minDelayMs_);var durationS=durationMs/1e3,bandwidthInBps=8*numBytes/durationS;this.fast_.sample(durationS,bandwidthInBps),this.slow_.sample(durationS,bandwidthInBps)},_proto.sampleTTFB=function(ttfb){var weight=Math.sqrt(2)*Math.exp(-Math.pow(ttfb/1e3,2)/2);this.ttfb_.sample(weight,Math.max(ttfb,5))},_proto.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},_proto.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},_proto.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},_proto.destroy=function(){},EwmaBandWidthEstimator}(),SUPPORTED_INFO_DEFAULT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},SUPPORTED_INFO_CACHE={},AbrController=function(){function AbrController(_hls){var _this=this;this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey='',this.audioTracksByGroup=null,this.co
1decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=function(){var frag=_this.fragCurrent,part=_this.partCurrent,hls=_this.hls,autoLevelEnabled=hls.autoLevelEnabled,media=hls.media;if(frag&&media){var now=performance.now(),stats=part?part.stats:frag.stats,duration=part?part.duration:frag.duration,timeLoading=now-stats.loading.start,minAutoLevel=hls.minAutoLevel;if(stats.aborted||stats.loaded&&stats.loaded===stats.total||frag.level<=minAutoLevel)return _this.clearTimer(),void(_this._nextAutoLevel=-1);if(autoLevelEnabled&&!media.paused&&media.playbackRate&&media.readyState){var bufferInfo=hls.mainForwardBufferInfo;if(null!==bufferInfo){var ttfbEstimate=_this.bwEstimator.getEstimateTTFB(),playbackRate=Math.abs(media.playbackRate);if(!(timeLoading<=Math.max(ttfbEstimate,1e3*(duration/(2*playbackRate))))){var bufferStarvationDelay=bufferInfo.len/playbackRate,ttfb=stats.loading.first?stats.loading.first-stats.loading.start:-1,loadedFirstByte=stats.loaded&&-1<ttfb,bwEstimate=_this.getBwEstimate(),levels=hls.levels,level=levels[frag.level],expectedLen=stats.total||Math.max(stats.loaded,Math.round(duration*level.averageBitrate/8)),timeStreaming=loadedFirstByte?timeLoading-ttfb:timeLoading;1>timeStreaming&&loadedFirstByte&&(timeStreaming=Math.min(timeLoading,8*stats.loaded/bwEstimate));var loadRate=loadedFirstByte?1e3*stats.loaded/timeStreaming:0,fragLoadedDelay=loadRate?(expectedLen-stats.loaded)/loadRate:8*expectedLen/bwEstimate+ttfbEstimate/1e3;if(!(fragLoadedDelay<=bufferStarvationDelay)){var bwe=loadRate?8*loadRate:bwEstimate,fragLevelNextLoadedDelay=Number.POSITIVE_INFINITY,nextLoadLevel;for(nextLoadLevel=frag.level-1;nextLoadLevel>minAutoLevel;nextLoadLevel--){var levelNextBitrate=levels[nextLoadLevel].maxBitrate;if(fragLevelNextLoadedDelay=_this.getTimeToLoadFrag(ttfbEstimate/1e3,bwe,duration*levelNextBitrate,!levels[nextLoadLevel].details),fragLevelNextLoadedDelay<bufferStarvationDelay)break}if(!(fragLevelNextLoadedDelay>=fragLoadedDelay)&&!(fragLevelNextLoadedDelay>10*duration)){hls.nextLoadLevel=hls.nextAutoLevel=nextLoadLevel,loadedFirstByte?_this.bwEstimator.sample(timeLoading-Math.min(ttfbEstimate,ttfb),stats.loaded):_this.bwEstimator.sampleTTFB(timeLoading);var nextLoadLevelBitrate=levels[nextLoadLevel].maxBitrate;_this.getBwEstimate()*_this.hls.config.abrBandWidthUpFactor>nextLoadLevelBitrate&&_this.resetEstimator(nextLoadLevelBitrate),_this.clearTimer(),logger.warn('[abr] Fragment '+frag.sn+(part?' part '+part.index:'')+' of level '+frag.level+' is loading too slowly;\n Time to underbuffer: '+bufferStarvationDelay.toFixed(3)+' s\n Estimated load time for current fragment: '+fragLoadedDelay.toFixed(3)+' s\n Estimated load time for down switch fragment: '+fragLevelNextLoadedDelay.toFixed(3)+' s\n TTFB estimate: '+(0|ttfb)+' ms\n Current BW estimate: '+(isFiniteNumber(bwEstimate)?0|bwEstimate:'Unknown')+' bps\n New BW estimate: '+(0|_this.getBwEstimate())+' bps\n Switching to level '+nextLoadLevel+' @ '+(0|nextLoadLevelBitrate)+' bps'),hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:frag,part:part,stats:stats})}}}}}}},this.hls=_hls,this.bwEstimator=this.initEstimator(),this.registerListeners()}var _proto=AbrController.prototype;return _proto.resetEstimator=function(abrEwmaDefaultEstimate){abrEwmaDefaultEstimate&&(logger.log('setting initial bwe to '+abrEwmaDefaultEstimate),this.hls.config.abrEwmaDefaultEstimate=abrEwmaDefaultEstimate),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},_proto.initEstimator=function(){var config=this.hls.config;return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD,config.abrEwmaFastVoD,config.abrEwmaDefaultEstimate)},_proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.FRAG_LOADING,this.onFragLoading,this),hls.on(Events.FRAG_LOADED,this.onFragLoaded,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),hls.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),hls.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.on(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),hls.on(Events.ERROR,this.onError,this)}
1,_proto.unregisterListeners=function(){var hls=this.hls;hls&&(hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.FRAG_LOADING,this.onFragLoading,this),hls.off(Events.FRAG_LOADED,this.onFragLoaded,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),hls.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),hls.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.off(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),hls.off(Events.ERROR,this.onError,this))},_proto.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},_proto.onManifestLoading=function(){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},_proto.onLevelsUpdated=function(){-1<this.lastLoadedFragLevel&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},_proto.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=''},_proto.onFragLoading=function(event,data){var frag=data.frag;if(!this.ignoreFragment(frag)){if(!frag.bitrateTest){var _data$part;this.fragCurrent=frag,this.partCurrent=null==(_data$part=data.part)?null:_data$part}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}},_proto.onLevelSwitching=function(){this.clearTimer()},_proto.onError=function(event,data){if(!data.fatal)switch(data.details){case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ErrorDetails.FRAG_LOAD_TIMEOUT:{var frag=data.frag,fragCurrent=this.fragCurrent,part=this.partCurrent;if(frag&&fragCurrent&&frag.sn===fragCurrent.sn&&frag.level===fragCurrent.level){var now=performance.now(),stats=part?part.stats:frag.stats,timeLoading=now-stats.loading.start,ttfb
1=stats.loading.first?stats.loading.first-stats.loading.start:-1,loadedFirstByte=stats.loaded&&-1<ttfb;if(loadedFirstByte){var ttfbEstimate=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(timeLoading-Math.min(ttfbEstimate,ttfb),stats.loaded)}else this.bwEstimator.sampleTTFB(timeLoading)}break}}},_proto.getTimeToLoadFrag=function(timeToFirstByteSec,bandwidth,fragSizeBits,isSwitch){var playlistLoadSec=isSwitch?this.lastLevelLoadSec:0;return timeToFirstByteSec+fragSizeBits/bandwidth+playlistLoadSec},_proto.onLevelLoaded=function(event,data){var config=this.hls.config,loading=data.stats.loading,timeLoadingMs=loading.end-loading.start;isFiniteNumber(timeLoadingMs)&&(this.lastLevelLoadSec=timeLoadingMs/1e3),data.details.live?this.bwEstimator.update(config.abrEwmaSlowLive,config.abrEwmaFastLive):this.bwEstimator.update(config.abrEwmaSlowVoD,config.abrEwmaFastVoD)},_proto.onFragLoaded=function(event,_ref){var frag=_ref.frag,part=_ref.part,stats=part?part.stats:frag.stats;if(frag.type===PlaylistLevelType.MAIN&&this.bwEstimator.sampleTTFB(stats.loading.first-stats.loading.start),!this.ignoreFragment(frag)){if(this.clearTimer(),frag.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var duration=part?part.duration:frag.duration,level=this.hls.levels[frag.level],loadedBytes=(level.loaded?level.loaded.bytes:0)+stats.loaded,loadedDuration=(level.loaded?level.loaded.duration:0)+duration;level.loaded={bytes:loadedBytes,duration:loadedDuration},level.realBitrate=Math.round(8*loadedBytes/loadedDuration)}if(frag.bitrateTest){var fragBufferedData={stats:stats,frag:frag,part:part,id:frag.type};this.onFragBuffered(Events.FRAG_BUFFERED,fragBufferedData),frag.bitrateTest=!1}else this.lastLoadedFragLevel=frag.level}},_proto.onFragBuffered=function(event,data){var frag=data.frag,part=data.part,stats=null!=part&&part.stats.loaded?part.stats:frag.stats;if(!stats.aborted&&!this.ignoreFragment(frag)){var processingMs=stats.parsing.end-stats.loading.start-Math.min(stats.loading.first-stats.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(processingMs,stats.loaded),stats.bwEstimate=this.getBwEstimate(),this.bitrateTestDelay=frag.bitrateTest?processingMs/1e3:0}},_proto.ignoreFragment=function(frag){return frag.type!==PlaylistLevelType.MAIN||'initSegment'===frag.sn},_proto.clearTimer=function(){-1<this.timer&&(self.clearInterval(this.timer),this.timer=-1)},_proto.getAutoLevelKey=function(){return this.getBwEstimate()+'_'+this.getStarvationDelay().toFixed(2)},_proto.getNextABRAutoLevel=function(){var fragCurrent=this.fragCurrent,partCurrent=this.partCurrent,hls=this.hls,maxAutoLevel=hls.maxAutoLevel,config=hls.config,minAutoLevel=hls.minAutoLevel,currentFragDuration=partCurrent?partCurrent.duration:fragCurrent?fragCurrent.duration:0,avgbw=this.getBwEstimate(),bufferStarvationDelay=this.getStarvationDelay(),bwFactor=config.abrBandWidthFactor,bwUpFactor=config.abrBandWidthUpFactor;if(bufferStarvationDelay){var _bestLevel=this.findBestLevel(avgbw,minAutoLevel,maxAutoLevel,bufferStarvationDelay,0,bwFactor,bwUpFactor);if(0<=_bestLevel)return _bestLevel}var maxStarvationDelay=currentFragDuration?Math.min(currentFragDuration,config.maxStarvationDelay):config.maxStarvationDelay;if(!bufferStarvationDelay){var bitrateTestDelay=this.bitrateTestDelay;if(bitrateTestDelay){var maxLoadingDelay=currentFragDuration?Math.min(currentFragDuration,config.maxLoadingDelay):config.maxLoadingDelay;maxStarvationDelay=maxLoadingDelay-bitrateTestDelay,logger.info('[abr] bitrate test took '+Math.round(1e3*bitrateTestDelay)+'ms, set first fragment max fetchDuration to '+Math.round(1e3*maxStarvationDelay)+' ms'),bwFactor=bwUpFactor=1}}var bestLevel=this.findBestLevel(avgbw,minAutoLevel,maxAutoLevel,bufferStarvationDelay,maxStarvationDelay,bwFactor,bwUpFactor);if(logger.info('[abr] '+(bufferStarvationDelay?'rebuffering expected':'buffer is empty')+', optimal quality level '+bestLevel),-1<bestLevel)return bestLevel;var minLevel=hls.levels[minAutoLevel],autoLevel=hls.levels[hls.loadLevel];return(null==minLevel?void 0:minLevel.bitrate)<(null==autoLevel?void 0:autoLevel.bitrate)?minAutoLevel:hls.loadLevel}
1,_proto.getStarvationDelay=function(){var hls=this.hls,media=hls.media;if(!media)return Infinity;var playbackRate=media&&0!==media.playbackRate?Math.abs(media.playbackRate):1,bufferInfo=hls.mainForwardBufferInfo;return(bufferInfo?bufferInfo.len:0)/playbackRate},_proto.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},_proto.findBestLevel=function(currentBw,minAutoLevel,maxAutoLevel,bufferStarvationDelay,maxStarvationDelay,bwFactor,bwUpFactor){var _this2=this,maxFetchDuration=bufferStarvationDelay+maxStarvationDelay,lastLoadedFragLevel=this.lastLoadedFragLevel,selectionBaseLevel=-1===lastLoadedFragLevel?this.hls.firstLevel:lastLoadedFragLevel,fragCurrent=this.fragCurrent,partCurrent=this.partCurrent,_this$hls=this.hls,levels=_this$hls.levels,allAudioTracks=_this$hls.allAudioTracks,loadLevel=_this$hls.loadLevel,config=_this$hls.config,_level$details;if(1===levels.length)return 0;var level=levels[selectionBaseLevel],live=!!(null!=level&&null!=(_level$details=level.details)&&_level$details.live),firstSelection=-1===loadLevel||-1===lastLoadedFragLevel,currentVideoRange='SDR',currentFrameRate=(null==level?void 0:level.frameRate)||0,audioPreference=config.audioPreference,videoPreference=config.videoPreference,audioTracksByGroup=this.audioTracksByGroup||(this.audioTracksByGroup=getAudioTracksByGroup(allAudioTracks)),currentCodecSet;if(firstSelection){if(-1!==this.firstSelection)return this.firstSelection;var codecTiers=this.codecTiers||(this.codecTiers=getCodecTiers(levels,audioTracksByGroup,minAutoLevel,maxAutoLevel)),startTier=getStartCodecTier(codecTiers,currentVideoRange,currentBw,audioPreference,videoPreference),codecSet=startTier.codecSet,videoRanges=startTier.videoRanges,minFramerate=startTier.minFramerate,minBitrate=startTier.minBitrate,preferHDR=startTier.preferHDR;currentCodecSet=codecSet,currentVideoRange=preferHDR?videoRanges[videoRanges.length-1]:videoRanges[0],currentFrameRate=minFramerate,currentBw=Math.max(currentBw,minBitrate),logger.log('[abr] picked start tier '+JSON.stringify(startTier))}else currentCodecSet=null==level?void 0:level.codecSet,currentVideoRange=null==level?void 0:level.videoRange;for(var currentFragDuration=partCurrent?partCurrent.duration:fragCurrent?fragCurrent.duration:0,ttfbEstimateSec=this.bwEstimator.getEstimateTTFB()/1e3,levelsSkipped=[],_loop=function(){var levelInfo=levels[i],upSwitch=i>selectionBaseLevel,_levelInfo$supportedR;if(!levelInfo)return 0;if(config.useMediaCapabilities&&!levelInfo.supportedResult&&!levelInfo.supportedPromise){var mediaCapabilities=navigator.mediaCapabilities;'function'==typeof(null==mediaCapabilities?void 0:mediaCapabilities.decodingInfo)&&requiresMediaCapabilitiesDecodingInfo(levelInfo,audioTracksByGroup,currentVideoRange,currentFrameRate,currentBw,audioPreference)?(levelInfo.supportedPromise=getMediaDecodingInfoPromise(levelInfo,audioTracksByGroup,mediaCapabilities),levelInfo.supportedPromise.then(function(decodingInfo){if(_this2.hls){levelInfo.supportedResult=decodingInfo;var levels=_this2.hls.levels,index=levels.indexOf(levelInfo);decodingInfo.error?logger.warn('[abr] MediaCapabilities decodingInfo error: "'+decodingInfo.error+'" for level '+index+' '+JSON.stringify(decodingInfo)):!decodingInfo.supported&&(logger.warn('[abr] Unsupported MediaCapabilities decodingInfo result for level '+index+' '+JSON.stringify(decodingInfo)),-1<index&&1<levels.length&&(logger.log('[abr] Removing unsupported level '+index),_this2.hls.removeLevel(index)))}})):levelInfo.supportedResult=SUPPORTED_INFO_DEFAULT}if(currentCodecSet&&levelInfo.codecSet!==currentCodecSet||currentVideoRange&&levelInfo.videoRange!==currentVideoRange||upSwitch&¤tFrameRate>levelInfo.frameRate||!upSwitch&&0<currentFrameRate&¤tFrameRate<levelInfo.frameRate||levelInfo.supportedResult&&!(null!=(_levelInfo$supportedR=levelInfo.supportedResult.decodingInfoResults)&&_levelInfo$supportedR[0].smooth))return levelsSkipped.push(i),0;var levelDetails=levelInfo.details,avgDuration=(partCurrent?null==levelDetails?void 0:levelDetails.partTarget:null==levelDetails?void 0:levelDetails.averagetargetduration)||currentFragDuration,adjustedbw;adjustedbw=upSwitch?bwUpFactor*currentBw:bwFactor*currentBw;var bitrate=currentFragDuration&&bufferStarvationDelay>=2*currentFragDuration&&0===maxStarvationDelay?levels[i].averageBitrate:levels[i].maxBitrate,fetchDuration=_this2.getTimeToLoadFrag(ttfbEstimateSec,adjustedbw,bitrate*avgDuration,void 0===levelDetails),canSwitchWithinTolerance=adjustedbw>=bitrate&&(i===lastLoadedFragLevel||0===levelInfo.loadError&&0===levelInfo.fragmentError)&&(fetchDuration<=ttfbEstimateSec||!isFiniteNumber(fetchDuration)||live&&!_this2.bitrateTestDelay||fetchDuration<maxFetchDuration);if(canSwitchWithinTolerance){var forcedAutoLevel=_this2.forcedAutoLevel;return i!==loadLevel&&(-1===forcedAutoLevel||forcedAutoLevel!==loadLevel)&&(levelsSkipped.length&&logger.trace('[abr] Ski
1pped level(s) '+levelsSkipped.join(',')+' of '+maxAutoLevel+' max with CODECS and VIDEO-RANGE:"'+levels[levelsSkipped[0]].codecs+'" '+levels[levelsSkipped[0]].videoRange+'; not compatible with "'+level.codecs+'" '+currentVideoRange),logger.info('[abr] switch candidate:'+selectionBaseLevel+'->'+i+' adjustedbw('+Math.round(adjustedbw)+')-bitrate='+Math.round(adjustedbw-bitrate)+' ttfb:'+ttfbEstimateSec.toFixed(1)+' avgDuration:'+avgDuration.toFixed(1)+' maxFetchDuration:'+maxFetchDuration.toFixed(1)+' fetchDuration:'+fetchDuration.toFixed(1)+' firstSelection:'+firstSelection+' codecSet:'+currentCodecSet+' videoRange:'+currentVideoRange+' hls.loadLevel:'+loadLevel)),firstSelection&&(_this2.firstSelection=i),{v:i}}},i=maxAutoLevel,_ret;i>=minAutoLevel;i--)if(_ret=_loop(),0!==_ret&&_ret)return _ret.v;return-1},_createClass(AbrController,[{key:'firstAutoLevel',get:function(){var _this$hls2=this.hls,maxAutoLevel=_this$hls2.maxAutoLevel,minAutoLevel=_this$hls2.minAutoLevel,bwEstimate=this.getBwEstimate(),maxStartDelay=this.hls.config.maxStarvationDelay,abrAutoLevel=this.findBestLevel(bwEstimate,minAutoLevel,maxAutoLevel,0,maxStartDelay,1,1);if(-1<abrAutoLevel)return abrAutoLevel;var firstLevel=this.hls.firstLevel,clamped=Math.min(Math.max(firstLevel,minAutoLevel),maxAutoLevel);return logger.warn('[abr] Could not find best starting auto level. Defaulting to first in playlist '+firstLevel+' clamped to '+clamped),clamped}},{key:'forcedAutoLevel',get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:'nextAutoLevel',get:function(){var forcedAutoLevel=this.forcedAutoLevel,bwEstimator=this.bwEstimator,useEstimate=bwEstimator.canEstimate(),loadedFirstFrag=-1<this.lastLoadedFragLevel;if(-1!==forcedAutoLevel&&(!useEstimate||!loadedFirstFrag||this.nextAutoLevelKey===this.getAutoLevelKey()))return forcedAutoLevel;var nextABRAutoLevel=useEstimate&&loadedFirstFrag?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==forcedAutoLevel){var levels=this.hls.levels;if(levels.length>Math.max(forcedAutoLevel,nextABRAutoLevel)&&levels[forcedAutoLevel].loadError<=levels[nextABRAutoLevel].loadError)return forcedAutoLevel}return this._nextAutoLevel=nextABRAutoLevel,this.nextAutoLevelKey=this.getAutoLevelKey(),nextABRAutoLevel},set:function(nextLevel){var _this$hls3=this.hls,maxAutoLevel=_this$hls3.maxAutoLevel,minAutoLevel=_this$hls3.minAutoLevel,value=Math.min(Math.max(nextLevel,minAutoLevel),maxAutoLevel);this._nextAutoLevel!==value&&(this.nextAutoLevelKey='',this._nextAutoLevel=value)}}]),AbrController}(),TaskLoop=function(){function TaskLoop(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var _proto=TaskLoop.prototype;return _proto.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},_proto.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},_proto.onHandlerDestroyed=function(){},_proto.hasInterval=function(){return!!this._tickInterval},_proto.hasNextTick=function(){return!!this._tickTimer},_proto.setInterval=function(millis){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,millis),!0)},_proto.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},_proto.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},_proto.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),1<this._tickCallCount&&this.tickImmediate(),this._tickCallCount=0)},_proto.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},_proto.doTick=function(){},TaskLoop}(),FragmentState={NOT_LOADED:'NOT_LOADED',APPENDING:'APPENDING',PARTIAL:'PARTIAL',OK:'OK'},FragmentTracker=function(){function FragmentTracker(hls){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=hls,this._registerListeners()}var _proto=FragmentTracker.prototype;
1return _proto._registerListeners=function(){var hls=this.hls;hls.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),hls.on(Events.FRAG_LOADED,this.onFragLoaded,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),hls.off(Events.FRAG_LOADED,this.onFragLoaded,this)},_proto.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},_proto.getAppendedFrag=function(position,levelType){var activeParts=this.activePartLists[levelType];if(activeParts)for(var i=activeParts.length,activePart,appendedPTS;i--&&(activePart=activeParts[i],!!activePart);)if(appendedPTS=activePart.end,activePart.start<=position&&null!==appendedPTS&&position<=appendedPTS)return activePart;return this.getBufferedFrag(position,levelType)},_proto.getBufferedFrag=function(position,levelType){for(var fragments=this.fragments,keys=Object.keys(fragments),i=keys.length,fragmentEntity;i--;)if(fragmentEntity=fragments[keys[i]],(null==fragmentEntity?void 0:fragmentEntity.body.type)===levelType&&fragmentEntity.buffered){var frag=fragmentEntity.body;if(frag.start<=position&&position<=frag.end)return frag}return null},_proto.detectEvictedFragments=function(elementaryStream,timeRange,playlistType,appendedPart){var _this=this;this.timeRanges&&(this.timeRanges[elementaryStream]=timeRange);var appendedPartSn=(null==appendedPart?void 0:appendedPart.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(key){var fragmentEntity=_this.fragments[key];if(fragmentEntity&&!(appendedPartSn>=fragmentEntity.body.sn)){if(!fragmentEntity.buffered&&!fragmentEntity.loaded)return void(fragmentEntity.body.type===playlistType&&_this.removeFragment(fragmentEntity.body));var esData=fragmentEntity.range[elementaryStream];esData&&esData.time.some(function(time){var isNotBuffered=!_this.isTimeBuffered(time.startPTS,time.endPTS,timeRange);return isNotBuffered&&_this.removeFragment(fragmentEntity.body),isNotBuffered})}})},_proto.detectPartialFragments=function(data){var _this2=this,timeRanges=this.timeRanges,frag=data.frag,part=data.part;if(timeRanges&&'initSegment'!==frag.sn){var fragKey=getFragmentKey(frag),fragmentEntity=this.fragments[fragKey];if(!(!fragmentEntity||fragmentEntity.buffered&&frag.gap)){var isFragHint=!frag.relurl;if(Object.keys(timeRanges).forEach(function(elementaryStream){var streamInfo=frag.elementaryStreams[elementaryStream];if(streamInfo){var timeRange=timeRanges[elementaryStream],partial=isFragHint||!0===streamInfo.partial;fragmentEntity.range[elementaryStream]=_this2.getBufferedTimes(frag,part,partial,timeRange)}}),fragmentEntity.loaded=null,Object.keys(fragmentEntity.range).length){fragmentEntity.buffered=!0;var endList=fragmentEntity.body.endList=frag.endList||fragmentEntity.body.endList;endList&&(this.endListFragments[fragmentEntity.body.type]=fragmentEntity),isPartial(fragmentEntity)||this.removeParts(frag.sn-1,frag.type)}else this.removeFragment(fragmentEntity.body)}}},_proto.removeParts=function(snToKeep,levelType){var activeParts=this.activePartLists[levelType];activeParts&&(this.activePartLists[levelType]=activeParts.filter(function(part){return part.fragment.sn>=snToKeep}))},_proto.fragBuffered=function(frag,force){var fragKey=getFragmentKey(frag),fragmentEntity=this.fragments[fragKey];!fragmentEntity&&force&&(fragmentEntity=this.fragments[fragKey]={body:frag,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},frag.gap&&(this.hasGaps=!0)),fragmentEntity&&(fragmentEntity.loaded=null,fragmentEntity.buffered=!0)},_proto.getBufferedTimes=function(fragment,part,partial,timeRange){for(var buffered={time:[],partial:partial},startPTS=fragment.start,endPTS=fragment.end,minEndPTS=fragment.minEndPTS||endPTS,maxStartPTS=fragment.maxStartPTS||startPTS,i=0;i<timeRange.length;i++){var startTime=timeRange.start(i)-this.bufferPadding,endTime=timeRange.end(i)+this.bufferPadding;if(maxStartPTS>=startTime&&minEndPTS<=endTime){buffered.time.push({startPTS:Math.max(startPTS,timeRange.start(i)),endPTS:Math.min(endPTS,timeRange.end(i))});break}else if(startPTS<endTime&&endPTS>startTime){var start=Math.max(startPTS,timeRange.start(i)),end=Math.min(endPTS,timeRange.end(i));end>start&&(buffered.partial=!0,buffered.time.push({startPTS:start,endPTS:end}))}else if(endPTS<=startTime)break}return buffered},_proto.getPartialFragment=function(time){var bestFragment=null,bestOverlap=0,bufferPadding=this.bufferPadding,fragments=this.fragments,timePadding,startTime,endTime;
1return Object.keys(fragments).forEach(function(key){var fragmentEntity=fragments[key];!fragmentEntity||isPartial(fragmentEntity)&&(startTime=fragmentEntity.body.start-bufferPadding,endTime=fragmentEntity.body.end+bufferPadding,time>=startTime&&time<=endTime&&(timePadding=Math.min(time-startTime,endTime-time),bestOverlap<=timePadding&&(bestFragment=fragmentEntity.body,bestOverlap=timePadding)))}),bestFragment},_proto.isEndListAppended=function(type){var lastFragmentEntity=this.endListFragments[type];return void 0!==lastFragmentEntity&&(lastFragmentEntity.buffered||isPartial(lastFragmentEntity))},_proto.getState=function(fragment){var fragKey=getFragmentKey(fragment),fragmentEntity=this.fragments[fragKey];return fragmentEntity?fragmentEntity.buffered?isPartial(fragmentEntity)?FragmentState.PARTIAL:FragmentState.OK:FragmentState.APPENDING:FragmentState.NOT_LOADED},_proto.isTimeBuffered=function(startPTS,endPTS,timeRange){for(var i=0,startTime,endTime;i<timeRange.length;i++){if(startTime=timeRange.start(i)-this.bufferPadding,endTime=timeRange.end(i)+this.bufferPadding,startPTS>=startTime&&endPTS<=endTime)return!0;if(endPTS<=startTime)return!1}return!1},_proto.onFragLoaded=function(event,data){var frag=data.frag,part=data.part;if(!('initSegment'===frag.sn||frag.bitrateTest)){var loaded=part?null:data,fragKey=getFragmentKey(frag);this.fragments[fragKey]={body:frag,appendedPTS:null,loaded:loaded,buffered:!1,range:Object.create(null)}}},_proto.onBufferAppended=function(event,data){var _this3=this,frag=data.frag,part=data.part,timeRanges=data.timeRanges;if('initSegment'!==frag.sn){var playlistType=frag.type;if(part){var activeParts=this.activePartLists[playlistType];activeParts||(this.activePartLists[playlistType]=activeParts=[]),activeParts.push(part)}this.timeRanges=timeRanges,Object.keys(timeRanges).forEach(function(elementaryStream){var timeRange=timeRanges[elementaryStream];_this3.detectEvictedFragments(elementaryStream,timeRange,playlistType,part)})}},_proto.onFragBuffered=function(event,data){this.detectPartialFragments(data)},_proto.hasFragment=function(fragment){var fragKey=getFragmentKey(fragment);return!!this.fragments[fragKey]},_proto.hasParts=function(type){var _this$activePartLists;return!!(null!=(_this$activePartLists=this.activePartLists[type])&&_this$activePartLists.length)},_proto.removeFragmentsInRange=function(start,end,playlistType,withGapOnly,unbufferedOnly){var _this4=this;withGapOnly&&!this.hasGaps||Object.keys(this.fragments).forEach(function(key){var fragmentEntity=_this4.fragments[key];if(fragmentEntity){var frag=fragmentEntity.body;frag.type!==playlistType||withGapOnly&&!frag.gap||frag.start<end&&frag.end>start&&(fragmentEntity.buffered||unbufferedOnly)&&_this4.removeFragment(frag)}})},_proto.removeFragment=function(fragment){var fragKey=getFragmentKey(fragment);fragment.stats.loaded=0,fragment.clearElementaryStreamInfo();var activeParts=this.activePartLists[fragment.type];if(activeParts){var snToRemove=fragment.sn;this.activePartLists[fragment.type]=activeParts.filter(function(part){return part.fragment.sn!==snToRemove})}delete this.fragments[fragKey],fragment.endList&&delete this.endListFragments[fragment.type]},_proto.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},FragmentTracker}(),noopBuffered={length:0,start:function(){return 0},end:function(){return 0}},BufferHelper=function(){function BufferHelper(){}return BufferHelper.isBuffered=function(media,position){try{if(media)for(var buffered=BufferHelper.getBuffered(media),i=0;i<buffered.length;i++)if(position>=buffered.start(i)&&position<=buffered.end(i))return!0}catch(error){}return!1},BufferHelper.bufferInfo=function(media,pos,maxHoleDuration){try{if(media){var vbuffered=BufferHelper.getBuffered(media),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){}return{len:0,start:pos,end:pos,nextStart:void 0}},BufferHelper.bufferedInfo=function(buffered,pos,maxHoleDuration){pos=Math.max(0,pos),buffered.sort(function(a,b){var diff=a.start-b.start;return diff?diff:b.end-a.end});var buffered2=[];
1if(maxHoleDuration){for(var i=0,buf2len;i<buffered.length;i++)if(buf2len=buffered2.length,buf2len){var buf2end=buffered2[buf2len-1].end;buffered[i].start-buf2end<maxHoleDuration?buffered[i].end>buf2end&&(buffered2[buf2len-1].end=buffered[i].end):buffered2.push(buffered[i])}else buffered2.push(buffered[i]);}else buffered2=buffered;for(var bufferLen=0,bufferStart=pos,bufferEnd=pos,_i=0,bufferStartNext;_i<buffered2.length;_i++){var start=buffered2[_i].start,end=buffered2[_i].end;if(pos+maxHoleDuration>=start&&pos<end)bufferStart=start,bufferEnd=end,bufferLen=bufferEnd-pos;else if(pos+maxHoleDuration<start){bufferStartNext=start;break}}return{len:bufferLen,start:bufferStart||0,end:bufferEnd||0,nextStart:bufferStartNext}},BufferHelper.getBuffered=function(media){try{return media.buffered}catch(e){return logger.log('failed to get media.buffered',e),noopBuffered}},BufferHelper}(),ChunkMetadata=function(level,sn,id,size,part,partial){void 0===size&&(size=0),void 0===part&&(part=-1),void 0===partial&&(partial=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=getNewPerformanceTiming(),this.buffering={audio:getNewPerformanceTiming(),video:getNewPerformanceTiming(),audiovideo:getNewPerformanceTiming()},this.level=level,this.sn=sn,this.id=id,this.size=size,this.part=part,this.partial=partial},MIN_CHUNK_SIZE=Math.pow(2,17),FragmentLoader=function(){function FragmentLoader(config){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=config}var _proto=FragmentLoader.prototype;return _proto.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},_proto.abort=function(){this.loader&&this.loader.abort()},_proto.load=function(frag,_onProgress){var _this=this,url=frag.url;if(!url)return Promise.reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:frag,error:new Error('Fragment does not have a '+(url?'part list':'url')),networkDetails:null}));this.abort();var config=this.config,FragmentILoader=config.fLoader,DefaultILoader=config.loader;return new Promise(function(resolve,reject){if(_this.loader&&_this.loader.destroy(),frag.gap){if(frag.tagList.some(function(tags){return'GAP'===tags[0]}))return void reject(createGapLoadError(frag));frag.gap=!1}var loader=_this.loader=frag.loader=FragmentILoader?new FragmentILoader(config):new DefaultILoader(config),loaderContext=createLoaderContext(frag),loadPolicy=getLoaderConfigWithoutReties(config.fragLoadPolicy.default),loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:'initSegment'===frag.sn?Infinity:MIN_CHUNK_SIZE};frag.stats=loader.stats,loader.load(loaderContext,loaderConfig,{onSuccess:function(response,stats,context,networkDetails){_this.resetLoader(frag,loader);var payload=response.data;context.resetIV&&frag.decryptdata&&(frag.decryptdata.iv=new Uint8Array(payload.slice(0,16)),payload=payload.slice(16)),resolve({frag:frag,part:null,payload:payload,networkDetails:networkDetails})},onError:function(response,context,networkDetails,stats){_this.resetLoader(frag,loader),reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:frag,response:_objectSpread2({url:url,data:void 0},response),error:new Error('HTTP Error '+response.code+' '+response.text),networkDetails:networkDetails,stats:stats}))},onAbort:function(stats,context,networkDetails){_this.resetLoader(frag,loader),reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:frag,error:new Error('Aborted'),networkDetails:networkDetails,stats:stats}))},onTimeout:function(stats,context,networkDetails){_this.resetLoader(frag,loader),reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:frag,error:new Error('Timeout after '+loaderConfig.timeout+'ms'),networkDetails:networkDetails,stats:stats}))},onProgress:function(stats,context,data,networkDetails){_onProgress&&_onProgress({frag:frag,part:null,payload:data,networkDetails:networkDetails})}})})},_proto.loadPart=function(frag,part,onProgress){var _this2=this;this.abort();
vendor: 5,161 bytes, line 1
1var config=this.config,FragmentILoader=config.fLoader,DefaultILoader=config.loader;return new Promise(function(resolve,reject){if(_this2.loader&&_this2.loader.destroy(),frag.gap||part.gap)return void reject(createGapLoadError(frag,part));var loader=_this2.loader=frag.loader=FragmentILoader?new FragmentILoader(config):new DefaultILoader(config),loaderContext=createLoaderContext(frag,part),loadPolicy=getLoaderConfigWithoutReties(config.fragLoadPolicy.default),loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:MIN_CHUNK_SIZE};part.stats=loader.stats,loader.load(loaderContext,loaderConfig,{onSuccess:function(response,stats,context,networkDetails){_this2.resetLoader(frag,loader),_this2.updateStatsFromPart(frag,part);var partLoadedData={frag:frag,part:part,payload:response.data,networkDetails:networkDetails};onProgress(partLoadedData),resolve(partLoadedData)},onError:function(response,context,networkDetails,stats){_this2.resetLoader(frag,loader),reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:frag,part:part,response:_objectSpread2({url:loaderContext.url,data:void 0},response),error:new Error('HTTP Error '+response.code+' '+response.text),networkDetails:networkDetails,stats:stats}))},onAbort:function(stats,context,networkDetails){frag.stats.aborted=part.stats.aborted,_this2.resetLoader(frag,loader),reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:frag,part:part,error:new Error('Aborted'),networkDetails:networkDetails,stats:stats}))},onTimeout:function(stats,context,networkDetails){_this2.resetLoader(frag,loader),reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:frag,part:part,error:new Error('Timeout after '+loaderConfig.timeout+'ms'),networkDetails:networkDetails,stats:stats}))}})})},_proto.updateStatsFromPart=function(frag,part){var fragStats=frag.stats,partStats=part.stats,partTotal=partStats.total;if(fragStats.loaded+=partStats.loaded,partTotal){var estTotalParts=Math.round(frag.duration/part.duration),estLoadedParts=Math.min(Math.round(fragStats.loaded/partTotal),estTotalParts),estRemainingBytes=(estTotalParts-estLoadedParts)*Math.round(fragStats.loaded/estLoadedParts);fragStats.total=fragStats.loaded+estRemainingBytes}else fragStats.total=Math.max(fragStats.loaded,fragStats.total);var fragLoading=fragStats.loading,partLoading=partStats.loading;fragLoading.start?fragLoading.first+=partLoading.first-partLoading.start:(fragLoading.start=partLoading.start,fragLoading.first=partLoading.first),fragLoading.end=partLoading.end},_proto.resetLoader=function(frag,loader){frag.loader=null,this.loader===loader&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),loader.destroy()},FragmentLoader}(),LoadError=function(_Error){function LoadError(data){var _this3;return _this3=_Error.call(this,data.error.message)||this,_this3.data=void 0,_this3.data=data,_this3}return _inheritsLoose(LoadError,_Error),LoadError}(_wrapNativeSuper(Error)),AESCrypto=function(){function AESCrypto(subtle,iv){this.subtle=void 0,this.aesIV=void 0,this.subtle=subtle,this.aesIV=iv}var _proto=AESCrypto.prototype;return _proto.decrypt=function(data,key){return this.subtle.decrypt({name:'AES-CBC',iv:this.aesIV},key,data)},AESCrypto}(),FastAESKey=function(){function FastAESKey(subtle,key){this.subtle=void 0,this.key=void 0,this.subtle=subtle,this.key=key}var _proto=FastAESKey.prototype;return _proto.expandKey=function(){return this.subtle.importKey('raw',this.key,{name:'AES-CBC'},!1,['encrypt','decrypt'])},FastAESKey}(),AESDecryptor=function(){function AESDecryptor(){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.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var _proto=AESDecryptor.prototype;return _proto.uint8ArrayToUint32Array_=function(arrayBuffer){for(var view=new DataView(arrayBuffer),newArray=new Uint32Array(4),i=0;4>i;i++)newArray[i]=view.getUint32(4*i);return newArray},_proto.initTable=function(){var sBox=this.sBox,invSBox=this.invSBox,subMix=this.subMix,subMix0=subMix[0],subMix1=subMix[1],subMix2=subMix[2],subMix3=subMix[3],invSubMix=this.invSubMix,invSubMix0=invSubMix[0],invSubMix1=invSubMix[1],invSubMix2=invSubMix[2],invSubMix3=invSubMix[3],d=new Uint32Array(256),x=0,xi=0,i=0;for(i=0;256>i;i++)d[i]=128>i?i<<1:283^i<<1;for(i=0;256>i;i++){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=99^(sx>>>8^255&sx),sBox[x]=sx,invSBox[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx;subMix0[x]=t<<24|t>>>8,subMix1[x]=t<<16|t>>>16,subMix2[x]=t<<8|t>>>24,subMix3[x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,invSubMix0[sx]=t<<24|t>>>8,invSubMix1[sx]=t<<16|t>>>16,invSubMix2[sx]=t<<8|t>>>24,invSubMix3[sx]=t,x?(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]]):x=xi=1}}
1,_proto.expandKey=function(keyBuffer){for(var key=this.uint8ArrayToUint32Array_(keyBuffer),sameKey=!0,offset=0;offset<key.length&&sameKey;)sameKey=key[offset]===this.key[offset],offset++;if(!sameKey){this.key=key;var keySize=this.keySize=key.length;if(4!==keySize&&6!==keySize&&8!==keySize)throw new Error('Invalid aes key size='+keySize);var ksRows=this.ksRows=4*(keySize+6+1),keySchedule=this.keySchedule=new Uint32Array(ksRows),invKeySchedule=this.invKeySchedule=new Uint32Array(ksRows),sbox=this.sBox,rcon=this.rcon,invSubMix=this.invSubMix,invSubMix0=invSubMix[0],invSubMix1=invSubMix[1],invSubMix2=invSubMix[2],invSubMix3=invSubMix[3],ksRow,invKsRow,prev,t;for(ksRow=0;ksRow<ksRows;ksRow++){if(ksRow<keySize){prev=keySchedule[ksRow]=key[ksRow];continue}t=prev,0==ksRow%keySize?(t=t<<8|t>>>24,t=sbox[t>>>24]<<24|sbox[255&t>>>16]<<16|sbox[255&t>>>8]<<8|sbox[255&t],t^=rcon[0|ksRow/keySize]<<24):6<keySize&&4==ksRow%keySize&&(t=sbox[t>>>24]<<24|sbox[255&t>>>16]<<16|sbox[255&t>>>8]<<8|sbox[255&t]),keySchedule[ksRow]=prev=(keySchedule[ksRow-keySize]^t)>>>0}for(invKsRow=0;invKsRow<ksRows;invKsRow++)ksRow=ksRows-invKsRow,t=3&invKsRow?keySchedule[ksRow]:keySchedule[ksRow-4],invKeySchedule[invKsRow]=4>invKsRow||4>=ksRow?t:invSubMix0[sbox[t>>>24]]^invSubMix1[sbox[255&t>>>16]]^invSubMix2[sbox[255&t>>>8]]^invSubMix3[sbox[255&t]],invKeySchedule[invKsRow]>>>=0}},_proto.networkToHostOrderSwap=function(word){return word<<24|(65280&word)<<8|(16711680&word)>>8|word>>>24},_proto.decrypt=function(inputArrayBuffer,offset,aesIV){for(var nRounds=this.keySize+6,invKeySchedule=this.invKeySchedule,invSBOX=this.invSBox,invSubMix=this.invSubMix,invSubMix0=invSubMix[0],invSubMix1=invSubMix[1],invSubMix2=invSubMix[2],invSubMix3=invSubMix[3],initVector=this.uint8ArrayToUint32Array_(aesIV),initVector0=initVector[0],initVector1=initVector[1],initVector2=initVector[2],initVector3=initVector[3],inputInt32=new Int32Array(inputArrayBuffer),outputInt32=new Int32Array(inputInt32.length),swapWord=this.networkToHostOrderSwap,t0,t1,t2,t3,s0,s1,s2,s3,inputWords0,inputWords1,inputWords2,inputWords3,ksRow,i;offset<inputInt32.length;){for(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,i=1;i<nRounds;i++)t0=invSubMix0[s0>>>24]^invSubMix1[255&s1>>16]^invSubMix2[255&s2>>8]^invSubMix3[255&s3]^invKeySchedule[ksRow],t1=invSubMix0[s1>>>24]^invSubMix1[255&s2>>16]^invSubMix2[255&s3>>8]^invSubMix3[255&s0]^invKeySchedule[ksRow+1],t2=invSubMix0[s2>>>24]^invSubMix1[255&s3>>16]^invSubMix2[255&s0>>8]^invSubMix3[255&s1]^invKeySchedule[ksRow+2],t3=invSubMix0[s3>>>24]^invSubMix1[255&s0>>16]^invSubMix2[255&s1>>8]^invSubMix3[255&s2]^invKeySchedule[ksRow+3],s0=t0,s1=t1,s2=t2,s3=t3,ksRow+=4;t0=invSBOX[s0>>>24]<<24^invSBOX[255&s1>>16]<<16^invSBOX[255&s2>>8]<<8^invSBOX[255&s3]^invKeySchedule[ksRow],t1=invSBOX[s1>>>24]<<24^invSBOX[255&s2>>16]<<16^invSBOX[255&s3>>8]<<8^invSBOX[255&s0]^invKeySchedule[ksRow+1],t2=invSBOX[s2>>>24]<<24^invSBOX[255&s3>>16]<<16^invSBOX[255&s0>>8]<<8^invSBOX[255&s1]^invKeySchedule[ksRow+2],t3=invSBOX[s3>>>24]<<24^invSBOX[255&s0>>16]<<16^invSBOX[255&s1>>8]<<8^invSBOX[255&s2]^invKeySchedule[ksRow+3],outputInt32[offset]=swapWord(t0^initVector0),outputInt32[offset+1]=swapWord(t3^initVector1),outputInt32[offset+2]=swapWord(t2^initVector2),outputInt32[offset+3]=swapWord(t1^initVector3),initVector0=inputWords0,initVector1=inputWords1,initVector2=inputWords2,initVector3=inputWords3,offset+=4}return outputInt32.buffer},AESDecryptor}(),Decrypter=function(){function Decrypter(config,_temp){var _ref=void 0===_temp?{}:_temp,_ref$removePKCS7Paddi=_ref.removePKCS7Padding,removePKCS7Padding=void 0===_ref$removePKCS7Paddi||_ref$removePKCS7Paddi;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=config.enableSoftw
vendor: 9,469 bytes, line 1
1areAES,this.removePKCS7Padding=removePKCS7Padding,removePKCS7Padding)try{var browserCrypto=self.crypto;browserCrypto&&(this.subtle=browserCrypto.subtle||browserCrypto.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var _proto=Decrypter.prototype;return _proto.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},_proto.isSync=function(){return this.useSoftware},_proto.flush=function(){var currentResult=this.currentResult,remainderData=this.remainderData;if(!currentResult||remainderData)return this.reset(),null;var data=new Uint8Array(currentResult);return this.reset(),this.removePKCS7Padding?removePadding(data):data},_proto.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},_proto.decrypt=function(data,key,iv){var _this=this;return this.useSoftware?new Promise(function(resolve,reject){_this.softwareDecrypt(new Uint8Array(data),key,iv);var decryptResult=_this.flush();decryptResult?resolve(decryptResult.buffer):reject(new Error('[softwareDecrypt] Failed to decrypt data'))}):this.webCryptoDecrypt(new Uint8Array(data),key,iv)},_proto.softwareDecrypt=function(data,key,iv){var currentIV=this.currentIV,currentResult=this.currentResult,remainderData=this.remainderData;this.logOnce('JS AES decrypt'),remainderData&&(data=appendUint8Array(remainderData,data),this.remainderData=null);var currentChunk=this.getValidChunk(data);if(!currentChunk.length)return null;currentIV&&(iv=currentIV);var softwareDecrypter=this.softwareDecrypter;softwareDecrypter||(softwareDecrypter=this.softwareDecrypter=new AESDecryptor),softwareDecrypter.expandKey(key);var result=currentResult;return this.currentResult=softwareDecrypter.decrypt(currentChunk.buffer,0,iv),this.currentIV=sliceUint8(currentChunk,-16).buffer,result?result:null},_proto.webCryptoDecrypt=function(data,key,iv){var _this2=this;if(this.key!==key||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(data,key,iv));this.key=key,this.fastAesKey=new FastAESKey(this.subtle,key)}return this.fastAesKey.expandKey().then(function(aesKey){if(!_this2.subtle)return Promise.reject(new Error('web crypto not initialized'));_this2.logOnce('WebCrypto AES decrypt');var crypto=new AESCrypto(_this2.subtle,new Uint8Array(iv));return crypto.decrypt(data.buffer,aesKey)}).catch(function(err){return logger.warn('[decrypter]: WebCrypto Error, disable WebCrypto API, '+err.name+': '+err.message),_this2.onWebCryptoError(data,key,iv)})},_proto.onWebCryptoError=function(data,key,iv){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(data,key,iv);var decryptResult=this.flush();if(decryptResult)return decryptResult.buffer;throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data')},_proto.getValidChunk=function(data){var currentChunk=data,splitPoint=data.length-data.length%16;return splitPoint!==data.length&&(currentChunk=sliceUint8(data,0,splitPoint),this.remainderData=sliceUint8(data,splitPoint)),currentChunk},_proto.logOnce=function(msg){this.logEnabled&&(logger.log('[decrypter]: '+msg),this.logEnabled=!1)},Decrypter}(),TimeRanges={toString:function(r){for(var log='',len=r.length,i=0;i<len;i++)log+='['+r.start(i).toFixed(3)+'-'+r.end(i).toFixed(3)+']';return log}},State={STOPPED:'STOPPED',IDLE:'IDLE',KEY_LOADING:'KEY_LOADING',FRAG_LOADING:'FRAG_LOADING',FRAG_LOADING_WAITING_RETRY:'FRAG_LOADING_WAITING_RETRY',WAITING_TRACK:'WAITING_TRACK',PARSING:'PARSING',PARSED:'PARSED',ENDED:'ENDED',ERROR:'ERROR',WAITING_INIT_PTS:'WAITING_INIT_PTS',WAITING_LEVEL:'WAITING_LEVEL'},BaseStreamController=function(_TaskLoop){function BaseStreamController(hls,fragmentTracker,keyLoader,logPrefix,playlistType){var _this;return _this=_TaskLoop.call(this)||this,_this.hls=void 0,_this.fragPrevious=null,_this.fragCurrent=null,_this.fragmentTracker=void 0,_this.transmuxer=null,_this._state=State.STOPPED,_this.playlistType=void 0,_this.media=null,_this.mediaBuffer=null,_this.config=void 0,_this.bitrateTest=!1,_this.lastCurrentTime=0,_this.nextLoadPosition=0,_this.startPosition=0,_this.startTimeOffset=null,_this.loadedmetadata=!1,_this.retryDate=0,_this.levels=null,_this.fragmentLoader=void 0,_this.keyLoader=void 0,_this.levelLastLoaded=null,_this.startFragRequested=!1,_this.decrypter=void 0,_this.initPTS=[],_this.onvseeking=null,_this.onvended=null,_this.logPrefix='',_this.log=void 0,_this.warn=void 0,_this.playlistType=playlistType,_this.logPrefix=logPrefix,_this.log=logger.log.bind(logger,logPrefix+':'),_this.warn=logger.warn.bind(logger,logPrefix+':'),_this.hls=hls,_this.fragmentLoader=new FragmentLoader(hls.config),_this.keyLoader=keyLoader,_this.fragmentTracker=fragmentTracker,_this.config=hls.config,_this.decrypter=new Decrypter(hls.config),hls.on(Events.MANIFEST_LOADED,_this.onManifestLoaded,_assertThisInitialized(_this)),_this}_inheritsLoose(BaseStreamController,_TaskLoop);var _proto=BaseStreamController.prototype;return _proto.doTick=function(){this.onTickEnd()},_proto.onTickEnd=function(){},_proto.startLoad=function(){},_proto.stopLoad=function(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var frag=this.fragCurrent;null!=frag&&frag.loader&&(frag.abortRequests(),this.fragmentTracker.removeFragment(frag)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=State.STOPPED},_proto._streamEnded=function(bufferInfo,levelDetails){if(levelDetails.live||bufferInfo.nextStart||!bufferInfo.end||!this.media)return!1;var partList=levelDetails.partList;if(null!=partList&&partList.length){var lastPart=partList[partList.length-1],lastPartBuffered=BufferHelper.isBuffered(this.media,lastPart.start+lastPart.duration/2);return lastPartBuffered}var playlistType=levelDetails.fragments[levelDetails.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(playlistType)},_proto.getLevelDetails=function(){if(this.levels&&null!==this.levelLastLoaded){var _this$levelLastLoaded;return null==(_this$levelLastLoaded=this.levelLastLoaded)?void 0:_this$levelLastLoaded.details}},_proto.onMediaAttached=function(event,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;this.levels&&config.autoStartLoad&&this.state===State.STOPPED&&this.startLoad(config.startPosition)},_proto.onMediaDetaching=function(){var media=this.media;null!=media&&media.ended&&(this.log('MSE detaching and video ended, reset startPosition'),this.startPosition=this.lastCurrentTime=0),media&&this.onvseeking&&this.onvended&&(media.removeEventListener('seeking',this.onvseeking),media.removeEventListener('ended',this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},_proto.onMediaSeeking=function(){var config=this.config,fragCurrent=this.fragCurrent,media=this.media,mediaBuffer=this.mediaBuffer,state=this.state,currentTime=media?media.currentTime:0,bufferInfo=BufferHelper.bufferInfo(mediaBuffer?mediaBuffer:media,currentTime,config.maxBufferHole);if(this.log('media seeking to '+(isFiniteNumber(currentTime)?currentTime.toFixed(3):currentTime)+', state: '+state),this.state===State.ENDED)this.resetLoadingState();else if(fragCurrent){var tolerance=config.maxFragLookUpTolerance,fragStartOffset=fragCurrent.start-tolerance,fragEndOffset=fragCurrent.start+fragCurrent.duration+tolerance;if(!bufferInfo.len||fragEndOffset<bufferInfo.start||fragStartOffset>bufferInfo.end){var pastFragment=currentTime>fragEndOffset;(currentTime<fragStartOffset||pastFragment)&&(pastFragment&&fragCurrent.loader&&(this.log('seeking outside of buffer while fragment load in progress, cancel fragment load'),fragCurrent.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}media&&(this.fragmentTracker.removeFragmentsInRange(currentTime,Infinity,this.playlistType,!0),this.lastCurrentTime=currentTime),this.loadedmetadata||bufferInfo.len||(this.nextLoadPosition=this.startPosition=currentTime),this.tickImmediate()},_proto.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},_proto.onManifestLoaded=function(event,data){this.startTimeOffset=data.startTimeOffset,this.initPTS=[]},_proto.onHandlerDestroying=function(){this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),_TaskLoop.prototype.onHandlerDestroying.call(this),this.hls=null},_proto.onHandlerDestroyed=function(){this.state=State.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,_TaskLoop.prototype.onHandlerDestroyed.call(this)},_proto.loadFragment=function(frag,level,targetBufferTime){this._loadFragForPlayback(frag,level,targetBufferTime)},_proto._loadFragForPlayback=function(frag,level,targetBufferTime){var _this2=this;this._doFragLoad(frag,level,targetBufferTime,function(data){return _this2.fragContextChanged(frag)?(_this2.warn('Fragment '+frag.sn+(data.part?' p: '+data.part.index:'')+' of level '+frag.level
1+' was dropped during download.'),void _this2.fragmentTracker.removeFragment(frag)):void(frag.stats.chunkCount++,_this2._handleFragmentLoadProgress(data))}).then(function(data){if(data){var state=_this2.state;return _this2.fragContextChanged(frag)?void(state!==State.FRAG_LOADING&&(_this2.fragCurrent||state!==State.PARSING)||(_this2.fragmentTracker.removeFragment(frag),_this2.state=State.IDLE)):void('payload'in data&&(_this2.log('Loaded fragment '+frag.sn+' of level '+frag.level),_this2.hls.trigger(Events.FRAG_LOADED,data)),_this2._handleFragmentLoadComplete(data))}}).catch(function(reason){_this2.state===State.STOPPED||_this2.state===State.ERROR||(_this2.warn('Frag error: '+((null==reason?void 0:reason.message)||reason)),_this2.resetFragmentLoading(frag))})},_proto.clearTrackerIfNeeded=function(frag){var fragmentTracker=this.fragmentTracker,fragState=fragmentTracker.getState(frag),_this$mediaBuffer;if(fragState===FragmentState.APPENDING){var playlistType=frag.type,bufferedInfo=this.getFwdBufferInfo(this.mediaBuffer,playlistType),minForwardBufferLength=Math.max(frag.duration,bufferedInfo?bufferedInfo.len:this.config.maxBufferLength),backtrackFragment=this.backtrackFragment,backtracked=backtrackFragment?frag.sn-backtrackFragment.sn:0;(1==backtracked||this.reduceMaxBufferLength(minForwardBufferLength,frag.duration))&&fragmentTracker.removeFragment(frag)}else 0===(null==(_this$mediaBuffer=this.mediaBuffer)?void 0:_this$mediaBuffer.buffered.length)?fragmentTracker.removeAllFragments():fragmentTracker.hasParts(frag.type)&&(fragmentTracker.detectPartialFragments({frag:frag,part:null,stats:frag.stats,id:frag.type}),fragmentTracker.getState(frag)===FragmentState.PARTIAL&&fragmentTracker.removeFragment(frag))},_proto.checkLiveUpdate=function(details){if(details.updated&&!details.live){var lastFragment=details.fragments[details.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:lastFragment,part:null,stats:lastFragment.stats,id:lastFragment.type})}details.fragments[0]||(details.deltaUpdateFailed=!0)},_proto.flushMainBuffer=function(startOffset,endOffset,type){if(void 0===type&&(type=null),!!(startOffset-endOffset)){var flushScope={startOffset:startOffset,endOffset:endOffset,type:type};this.hls.trigger(Events.BUFFER_FLUSHING,flushScope)}},_proto._loadInitSegment=function(frag,level){var _this3=this;this._doFragLoad(frag,level).then(function(data){if(!data||_this3.fragContextChanged(frag)||!_this3.levels)throw new Error('init load aborted');return data}).then(function(data){var hls=_this3.hls,payload=data.payload,decryptData=frag.decryptdata;if(payload&&0<payload.byteLength&&null!=decryptData&&decryptData.key&&decryptData.iv&&'AES-128'===decryptData.method){var startTime=self.performance.now();return _this3.decrypter.decrypt(new Uint8Array(payload),decryptData.key.buffer,decryptData.iv.buffer).catch(function(err){throw hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:err,reason:err.message,frag:frag}),err}).then(function(decryptedData){var endTime=self.performance.now();return hls.trigger(Events.FRAG_DECRYPTED,{frag:frag,payload:decryptedData,stats:{tstart:startTime,tdecrypt:endTime}}),data.payload=decryptedData,_this3.completeInitSegmentLoad(data)})}return _this3.completeInitSegmentLoad(data)}).catch(function(reason){_this3.state===State.STOPPED||_this3.state===State.ERROR||(_this3.warn(reason),_this3.resetFragmentLoading(frag))})},_proto.completeInitSegmentLoad=function(data){var levels=this.levels;if(!levels)throw new Error('init load aborted, missing levels');var stats=data.frag.stats;this.state=State.IDLE,data.frag.data=new Uint8Array(data.payload),stats.parsing.start=stats.buffering.start=self.performance.now(),stats.parsing.end=stats.buffering.end=self.performance.now(),this.tick()},_proto.fragContextChanged=function(frag){var fragCurrent=this.fragCurrent;return!frag||!fragCurrent||frag.sn!==fragCurrent.sn||frag.level!==fragCurrent.level},_proto.fragBufferedComplete=function(frag,part){var media=this.mediaBuffer?this.mediaBuffer:this.media,_frag$startPTS,_frag$endPTS,_this$fragCurrent,_this$fragPrevious;if(this.log('Buffered '+frag.type+' sn: '+frag.sn+(part?' part: '+part.index:'')+' of '+(this.playlistType===PlaylistLevelType.MAIN?'level':'track')+' '+frag.level
1+' (frag:['+(null==(_frag$startPTS=frag.startPTS)?NaN:_frag$startPTS).toFixed(3)+'-'+(null==(_frag$endPTS=frag.endPTS)?NaN:_frag$endPTS).toFixed(3)+'] > buffer:'+(media?TimeRanges.toString(BufferHelper.getBuffered(media)):'(detached)')+')'),'initSegment'!==frag.sn){var _this$levels;if(frag.type!==PlaylistLevelType.SUBTITLE){var el=frag.elementaryStreams;if(!Object.keys(el).some(function(type){return!!el[type]}))return void(this.state=State.IDLE)}var level=null==(_this$levels=this.levels)?void 0:_this$levels[frag.level];null!=level&&level.fragmentError&&(this.log('Resetting level fragment error count of '+level.fragmentError+' on frag buffered'),level.fragmentError=0)}this.state=State.IDLE,media&&(!this.loadedmetadata&&frag.type==PlaylistLevelType.MAIN&&media.buffered.length&&(null==(_this$fragCurrent=this.fragCurrent)?void 0:_this$fragCurrent.sn)===(null==(_this$fragPrevious=this.fragPrevious)?void 0:_this$fragPrevious.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},_proto.seekToStartPos=function(){},_proto._handleFragmentLoadComplete=function(fragLoadedEndData){var transmuxer=this.transmuxer;if(transmuxer){var frag=fragLoadedEndData.frag,part=fragLoadedEndData.part,partsLoaded=fragLoadedEndData.partsLoaded,complete=!partsLoaded||0===partsLoaded.length||partsLoaded.some(function(fragLoaded){return!fragLoaded}),chunkMeta=new ChunkMetadata(frag.level,frag.sn,frag.stats.chunkCount+1,0,part?part.index:-1,!complete);transmuxer.flush(chunkMeta)}},_proto._handleFragmentLoadProgress=function(){},_proto._doFragLoad=function(frag,level,targetBufferTime,progressCallback){var _this4=this,_frag$decryptdata;void 0===targetBufferTime&&(targetBufferTime=null);var details=null==level?void 0:level.details;if(!this.levels||!details)throw new Error('frag load aborted, missing level'+(details?'':' detail')+'s');var keyLoadingPromise=null;if(frag.encrypted&&!(null!=(_frag$decryptdata=frag.decryptdata)&&_frag$decryptdata.key)?(this.log('Loading key for '+frag.sn+' of ['+details.startSN+'-'+details.endSN+'], '+('[stream-controller]'===this.logPrefix?'level':'track')+' '+frag.level),this.state=State.KEY_LOADING,this.fragCurrent=frag,keyLoadingPromise=this.keyLoader.load(frag).then(function(keyLoadedData){if(!_this4.fragContextChanged(keyLoadedData.frag))return _this4.hls.trigger(Events.KEY_LOADED,keyLoadedData),_this4.state===State.KEY_LOADING&&(_this4.state=State.IDLE),keyLoadedData}),this.hls.trigger(Events.KEY_LOADING,{frag:frag}),null===this.fragCurrent&&(keyLoadingPromise=Promise.reject(new Error('frag load aborted, context changed in KEY_LOADING')))):!frag.encrypted&&details.encryptedFragments.length&&this.keyLoader.loadClear(frag,details.encryptedFragments),targetBufferTime=Math.max(frag.start,targetBufferTime||0),this.config.lowLatencyMode&&'initSegment'!==frag.sn){var partList=details.partList;if(partList&&progressCallback){targetBufferTime>frag.end&&details.fragmentHint&&(frag=details.fragmentHint);var partIndex=this.getNextPart(partList,frag,targetBufferTime);if(-1<partIndex){var part=partList[partIndex];this.log('Loading part sn: '+frag.sn+' p: '+part.index+' cc: '+frag.cc+' of playlist ['+details.startSN+'-'+details.endSN+'] parts [0-'+partIndex+'-'+(partList.length-1)+'] '+('[stream-controller]'===this.logPrefix?'level':'track')+': '+frag.level+', target: '+parseFloat(targetBufferTime.toFixed(3))),this.nextLoadPosition=part.start+part.duration,this.state=State.FRAG_LOADING;var _result;return _result=keyLoadingPromise?keyLoadingPromise.then(function(keyLoadedData){return!keyLoadedData||_this4.fragContextChanged(keyLoadedData.frag)?null:_this4.doFragPartsLoad(frag,part,level,progressCallback)}).catch(function(error){return _this4.handleFragLoadError(error)}):this.doFragPartsLoad(frag,part,level,progressCallback).catch(function(error){return _this4.handleFragLoadError(error)}),this.hls.trigger(Events.FRAG_LOADING,{frag:frag,part:part,targetBufferTime:targetBufferTime}),null===this.fragCurrent?Promise.reject(new Error('frag load aborted, context changed in FRAG_LOADING parts')):_result}if(!frag.url||this.loadedEndOfParts(partList,targetBufferTime))return Promise.resolve(null)}}this.log('Loading fragment '+frag.sn+' cc: '+frag.cc+' '+(detail
1s?'of ['+details.startSN+'-'+details.endSN+'] ':'')+('[stream-controller]'===this.logPrefix?'level':'track')+': '+frag.level+', target: '+parseFloat(targetBufferTime.toFixed(3))),isFiniteNumber(frag.sn)&&!this.bitrateTest&&(this.nextLoadPosition=frag.start+frag.duration),this.state=State.FRAG_LOADING;var dataOnProgress=this.config.progressive,result;return result=dataOnProgress&&keyLoadingPromise?keyLoadingPromise.then(function(keyLoadedData){return!keyLoadedData||_this4.fragContextChanged(null==keyLoadedData?void 0:keyLoadedData.frag)?null:_this4.fragmentLoader.load(frag,progressCallback)}).catch(function(error){return _this4.handleFragLoadError(error)}):Promise.all([this.fragmentLoader.load(frag,dataOnProgress?progressCallback:void 0),keyLoadingPromise]).then(function(_ref){var fragLoadedData=_ref[0];return!dataOnProgress&&fragLoadedData&&progressCallback&&progressCallback(fragLoadedData),fragLoadedData}).catch(function(error){return _this4.handleFragLoadError(error)}),this.hls.trigger(Events.FRAG_LOADING,{frag:frag,targetBufferTime:targetBufferTime}),null===this.fragCurrent?Promise.reject(new Error('frag load aborted, context changed in FRAG_LOADING')):result},_proto.doFragPartsLoad=function(frag,fromPart,level,progressCallback){var _this5=this;return new Promise(function(resolve,reject){var partsLoaded=[],initialPartList=null==(_level$details=level.details)?void 0:_level$details.partList,_level$details;(function loadPart(part){_this5.fragmentLoader.loadPart(frag,part,progressCallback).then(function(partLoadedData){partsLoaded[part.index]=partLoadedData;var loadedPart=partLoadedData.part;_this5.hls.trigger(Events.FRAG_LOADED,partLoadedData);var nextPart=getPartWith(level,frag.sn,part.index+1)||findPart(initialPartList,frag.sn,part.index+1);return nextPart?void loadPart(nextPart):resolve({frag:frag,part:loadedPart,partsLoaded:partsLoaded})}).catch(reject)})(fromPart)})},_proto.handleFragLoadError=function(error){if('data'in error){var data=error.data;error.data&&data.details===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(data.frag,data.part):this.hls.trigger(Events.ERROR,data)}else this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:error,error:error,fatal:!0});return null},_proto._handleTransmuxerFlush=function(chunkMeta){var context=this.getCurrentContext(chunkMeta);if(!context||this.state!==State.PARSING)return void(this.fragCurrent||this.state===State.STOPPED||this.state===State.ERROR||(this.state=State.IDLE));var frag=context.frag,part=context.part,level=context.level,now=self.performance.now();frag.stats.parsing.end=now,part&&(part.stats.parsing.end=now),this.updateLevelTiming(frag,part,level,chunkMeta.partial)},_proto.getCurrentContext=function(chunkMeta){var levels=this.levels,fragCurrent=this.fragCurrent,levelIndex=chunkMeta.level,sn=chunkMeta.sn,partIndex=chunkMeta.part;if(!(null!=levels&&levels[levelIndex]))return this.warn('Levels object was unset while buffering fragment '+sn+' of level '+levelIndex+'. The current chunk will not be buffered.'),null;var level=levels[levelIndex],part=-1<partIndex?getPartWith(level,sn,partIndex):null,frag=part?part.fragment:getFragmentWithSN(level,sn,fragCurrent);return frag?(fragCurrent&&fragCurrent!==frag&&(frag.stats=fragCurrent.stats),{frag:frag,part:part,level:level}):null},_proto.bufferFragmentData=function(data,frag,part,chunkMeta,noBacktracking){var _buffer;if(data&&this.state===State.PARSING){var data1=data.data1,data2=data.data2,buffer=data1;if(data1&&data2&&(buffer=appendUint8Array(data1,data2)),!!(null!=(_buffer=buffer)&&_buffer.length)){var segment={type:data.type,frag:frag,part:part,chunkMeta:chunkMeta,parent:frag.type,data:buffer};if(this.hls.trigger(Events.BUFFER_APPENDING,segment),data.dropped&&data.independent&&!part){if(noBacktracking)return;this.flushBufferGap(frag)}}}},_proto.flushBufferGap=function(frag){var media=this.media;if(media){if(!BufferHelper.isBuffered(media,media.currentTime))return void this.flushMainBuffer(0,frag.start);var currentTime=media.currentTime,bufferInfo=BufferHelper.bufferInfo(media,currentTime,0),fragDuration=frag.duration,segmentFraction=Math.min(2*this.config.maxFragLookUpTolerance,.25*fragDuration),start=Math.max(Math.min(frag.start-segmentFraction,bufferInfo.end-segmentFraction),currentTime+segmentFraction);frag.start-start>segmentFraction&&this.flushMainBuffer(start,frag.start)}},_proto.getFwdBufferInfo=function(bufferable,type){var pos=this.getLoadPosition();return isFiniteNumber(pos)?this.getFwdBufferInfoAtPos(bufferable,pos,type):null},_proto.getFwdBufferInfoAtPos=function(bufferable,pos,type){var maxBufferHole=this.config.maxBufferHole,bufferInfo=BufferHelper.bufferInfo(bufferable,pos,maxBufferHole);if(0===bufferInfo.len&&void 0!==bufferInfo.nextStart){var bufferedFragAtPos=this.fragmentTracker.getBufferedFrag(pos,type);if(bufferedFragAtPos&&bufferInfo.nextStart<bufferedFragAtPos.end)return BufferHelper.bufferInfo(bufferable,pos,Math.max(bufferInfo.nextStart,maxBufferHole))}return bufferInfo},_proto.getMaxBufferLength=function(levelBitrate){var config=this.config,maxBufLen;return maxBufLen=levelBitrate?Math.max(8*config.maxBufferSize/levelBitrate,config.maxBufferLength):config.maxBufferLength,Math.min(maxBufLen,config.max
1MaxBufferLength)},_proto.reduceMaxBufferLength=function(threshold,fragDuration){var config=this.config,minLength=Math.max(Math.min(threshold-fragDuration,config.maxBufferLength),fragDuration),reducedLength=Math.max(threshold-3*fragDuration,config.maxMaxBufferLength/2,minLength);return!!(reducedLength>=minLength)&&(config.maxMaxBufferLength=reducedLength,this.warn('Reduce max buffer length to '+reducedLength+'s'),!0)},_proto.getAppendedFrag=function(position){var fragOrPart=this.fragmentTracker.getAppendedFrag(position,PlaylistLevelType.MAIN);return fragOrPart&&'fragment'in fragOrPart?fragOrPart.fragment:fragOrPart},_proto.getNextFragment=function(pos,levelDetails){var fragments=levelDetails.fragments,fragLen=fragments.length;if(!fragLen)return null;var config=this.config,start=fragments[0].start,frag;if(levelDetails.live){var initialLiveManifestSize=config.initialLiveManifestSize;if(fragLen<initialLiveManifestSize)return this.warn('Not enough fragments to start playback (have: '+fragLen+', need: '+initialLiveManifestSize+')'),null;(levelDetails.PTSKnown||this.startFragRequested||-1!==this.startPosition)&&!(pos<start)||(frag=this.getInitialLiveFragment(levelDetails,fragments),this.startPosition=this.nextLoadPosition=frag?this.hls.liveSyncPosition||frag.start:pos)}else pos<=start&&(frag=fragments[0]);if(!frag){var end=config.lowLatencyMode?levelDetails.partEnd:levelDetails.fragmentEnd;frag=this.getFragmentAtPosition(pos,end,levelDetails)}return this.mapToInitFragWhenRequired(frag)},_proto.isLoopLoading=function(frag,targetBufferTime){var trackerState=this.fragmentTracker.getState(frag);return(trackerState===FragmentState.OK||trackerState===FragmentState.PARTIAL&&!!frag.gap)&&this.nextLoadPosition>targetBufferTime},_proto.getNextFragmentLoopLoading=function(frag,levelDetails,bufferInfo,playlistType,maxBufLen){var gapStart=frag.gap,nextFragment=this.getNextFragment(this.nextLoadPosition,levelDetails);if(null===nextFragment)return nextFragment;if(frag=nextFragment,gapStart&&frag&&!frag.gap&&bufferInfo.nextStart){var nextbufferInfo=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,bufferInfo.nextStart,playlistType);if(null!==nextbufferInfo&&bufferInfo.len+nextbufferInfo.len>=maxBufLen)return this.log('buffer full after gaps in "'+playlistType+'" playlist starting at sn: '+frag.sn),null}return frag},_proto.mapToInitFragWhenRequired=function(frag){return null==frag||!frag.initSegment||null!=frag&&frag.initSegment.data||this.bitrateTest?frag:frag.initSegment},_proto.getNextPart=function(partList,frag,targetBufferTime){for(var nextPart=-1,contiguous=!1,independentAttrOmitted=!0,i=0,len=partList.length,part,loaded;i<len&&(part=partList[i],independentAttrOmitted=independentAttrOmitted&&!part.independent,!(-1<nextPart&&targetBufferTime<part.start));i++)loaded=part.loaded,loaded?nextPart=-1:(contiguous||part.independent||independentAttrOmitted)&&part.fragment===frag&&(nextPart=i),contiguous=loaded;return nextPart},_proto.loadedEndOfParts=function(partList,targetBufferTime){var lastPart=partList[partList.length-1];return lastPart&&targetBufferTime>lastPart.start&&lastPart.loaded},_proto.getInitialLiveFragment=function(levelDetails,fragments){var fragPrevious=this.fragPrevious,frag=null;if(!fragPrevious){var liveStart=this.hls.liveSyncPosition;null!==liveStart&&(frag=this.getFragmentAtPosition(liveStart,this.bitrateTest?levelDetails.fragmentEnd:levelDetails.edge,levelDetails))}else if(levelDetails.hasProgramDateTime&&(this.log('Live playlist, switching playlist, load frag with same PDT: '+fragPrevious.programDateTime),frag=findFragmentByPDT(fragments,fragPrevious.endProgramDateTime,this.config.maxFragLookUpTolerance)),!frag){var targetSN=fragPrevious.sn+1;if(targetSN>=levelDetails.startSN&&targetSN<=levelDetails.endSN){var fragNext=fragments[targetSN-levelDetails.startSN];fragPrevious.cc===fragNext.cc&&(frag=fragNext,this.log('Live playlist, switching playlist, load frag with next SN: '+frag.sn))}frag||(frag=findFragWithCC(fragments,fragPrevious.cc),frag&&this.log('Live playlist, switching playlist, load frag with same CC: '+frag.sn))}return frag},_proto.getFragmentAtPosition=function(bufferEnd,end,levelDetails){var config=this.config,fragPrevious=this.fragPrevious,fragments=levelDetails.fragments,endSN=levelDetails.endSN,fragmentHint=levelDetails.fragmentHint,maxFragLookUpTolerance=config.maxFragLookUpTolerance,partList=levelDetails.partList,loadingParts=!!(config.lowLatencyMode&&null!=partList&&partList.length&&fragmentHint);loadingParts&&fragmentHint&&!this.bitrateTest&&(fragments=fragments.concat(fragmentHint),endSN=fragmentHint.sn);var frag;if(bufferEnd<end){var lookupTolerance=bufferEnd>end-maxFragLookUpTolerance?0:maxFragLookUpTolerance;frag=findFragmentByPTS(fragPrevious,fragments,bufferEnd,lookupTolerance)}else frag=fragments[fragments.length-1];if(frag){var curSNIdx=frag.sn-levelDetails.startSN,fragState=this.fragmentTracker.getState(frag);if((fragState===FragmentState.OK||fragState===FragmentState.PARTIAL&&frag.gap)&&(fragPrevious=frag),fragPrevious&&frag.sn===fragPrevious.sn&&(!loadingParts||partList[0].fragment.sn>frag.sn)){var sameLevel=fragPrevious&&frag.level===fragPrevious.level;if(sameLevel){var nextFrag=fragments[curSNIdx+1];frag=frag.sn<endSN&&this.fragmentTracker.getState(nextFrag)!==FragmentState.OK?nextFrag:null}}}return frag},_proto.synchronizeToLiveEdge=function(levelDetails){var config=this.config,media=this.media;if(media){var liveSyncPosition=this.hls.liveSyncPosition,currentTime=media.currentTime,start=levelDetails.fragments[0].start,end=levelDetails.edge,withinSlidingWindow=currentTime>=start-config.maxFragLookUpTolerance&¤tTime<=end;if(null!==liveSyncPosition&&media.duration>liveSyncPosition&&(currentTime<liveSyncPosition||!withinSlidingWindow)){var maxLatency=void 0===config.liveMaxLatencyDuration?config.liveMaxLatencyDurationCount*levelDetails.targetduration:config.liveMaxLatencyDuration;(!withinSlidingWindow&&4>media.readyState||currentTime<end-maxLatency)&&(!this.loadedmetadata&&(this.nextLoadPosition=liveSyncPosition),media.readyState&&(this.warn('Playback: '+currentTime.toFixed(3)+' is located too far from the end of live sliding playlist: '+end+', reset currentTime to : '+liveSyncPosition.toFixed(3)),media.currentTime=liveSyncPosition))}}},_proto.alignPlaylists=function(details,previousDetails,switchDetails){var length=detail
1s.fragments.length;if(!length)return this.warn('No fragments in live playlist'),0;var slidingStart=details.fragments[0].start,aligned=details.alignedSliding&&isFiniteNumber(slidingStart);if(!previousDetails||!aligned&&!slidingStart){var fragPrevious=this.fragPrevious;alignStream(fragPrevious,switchDetails,details);var alignedSlidingStart=details.fragments[0].start;return this.log('Live playlist sliding: '+alignedSlidingStart.toFixed(2)+' start-sn: '+(previousDetails?previousDetails.startSN:'na')+'->'+details.startSN+' prev-sn: '+(fragPrevious?fragPrevious.sn:'na')+' fragments: '+length),alignedSlidingStart}return slidingStart},_proto.waitForCdnTuneIn=function(details){return details.live&&details.canBlockReload&&details.partTarget&&details.tuneInGoal>Math.max(details.partHoldBack,details.partTarget*3)},_proto.setStartPosition=function(details,sliding){var startPosition=this.startPosition;if(startPosition<sliding&&(startPosition=-1),-1===startPosition||-1===this.lastCurrentTime){var offsetInMultivariantPlaylist=null!==this.startTimeOffset,startTimeOffset=offsetInMultivariantPlaylist?this.startTimeOffset:details.startTimeOffset;null!==startTimeOffset&&isFiniteNumber(startTimeOffset)?(startPosition=sliding+startTimeOffset,0>startTimeOffset&&(startPosition+=details.totalduration),startPosition=Math.min(Math.max(sliding,startPosition),sliding+details.totalduration),this.log('Start time offset '+startTimeOffset+' found in '+(offsetInMultivariantPlaylist?'multivariant':'media')+' playlist, adjust startPosition to '+startPosition),this.startPosition=startPosition):details.live?startPosition=this.hls.liveSyncPosition||sliding:this.startPosition=startPosition=0,this.lastCurrentTime=startPosition}this.nextLoadPosition=startPosition},_proto.getLoadPosition=function(){var media=this.media,pos=0;return this.loadedmetadata&&media?pos=media.currentTime:this.nextLoadPosition&&(pos=this.nextLoadPosition),pos},_proto.handleFragLoadAborted=function(frag,part){this.transmuxer&&'initSegment'!==frag.sn&&frag.stats.aborted&&(this.warn('Fragment '+frag.sn+(part?' part '+part.index:'')+' of level '+frag.level+' was aborted'),this.resetFragmentLoading(frag))},_proto.resetFragmentLoading=function(frag){this.fragCurrent&&(this.fragContextChanged(frag)||this.state===State.FRAG_LOADING_WAITING_RETRY)||(this.state=State.IDLE)},_proto.onFragmentOrKeyLoadError=function(filterType,data){if(data.chunkMeta&&!data.frag){var context=this.getCurrentContext(data.chunkMeta);context&&(data.frag=context.frag)}var frag=data.frag;if(frag&&frag.type===filterType&&this.levels){if(this.fragContextChanged(frag)){var _this$fragCurrent2;return void this.warn('Frag load error must match current frag to retry '+frag.url+' > '+(null==(_this$fragCurrent2=this.fragCurrent)?void 0:_this$fragCurrent2.url))}var gapTagEncountered=data.details===ErrorDetails.FRAG_GAP;gapTagEncountered&&this.fragmentTracker.fragBuffered(frag,!0);var errorAction=data.errorAction,_ref2=errorAction||{},action=_ref2.action,_ref2$retryCount=_ref2.retryCount,retryCount=void 0===_ref2$retryCount?0:_ref2$retryCount,retryConfig=_ref2.retryConfig;if(errorAction&&action===NetworkErrorAction.RetryRequest&&retryConfig){this.resetStartWhenNotLoaded(this.levelLastLoaded);var delay=getRetryDelay(retryConfig,retryCount);this.warn('Fragment '+frag.sn+' of '+filterType+' '+frag.level+' errored with '+data.details+', retrying loading '+(retryCount+1)+'/'+retryConfig.maxNumRetry+' in '+delay+'ms'),errorAction.resolved=!0,this.retryDate=self.performance.now()+delay,this.state=State.FRAG_LOADING_WAITING_RETRY}else if(!(retryConfig&&errorAction))this.state=(null==errorAction?void 0:errorAction.action)===NetworkErrorAction.SendAlternateToPenaltyBox?State.WAITING_LEVEL:State.ERROR;else if(this.resetFragmentErrors(filterType),retryCount<retryConfig.maxNumRetry)gapTagEncountered||action===NetworkErrorAction.RemoveAlternatePermanently||(errorAction.resolved=!0);else return void logger.warn(data.details+' reached or exceeded max retry ('+retryCount+')');this.tickImmediate()}},_proto.reduceLengthAndFlushBuffer=function(data){if(this.state===State.PARSING||this.state===State.PARSED){var frag=data.frag,playlistType=data.parent,bufferedInfo=this.getFwdBufferInfo(this.mediaBuffer,playlistType),buffered=bufferedInfo&&.5<bufferedInfo.len;buffered&&this.reduceMaxBufferLength(bufferedInfo.len,(null==frag?void 0:frag.duration)||10);var flushBuffer=!buffered;return flushBuffer&&this.warn('Buffer full error while media.currentTime is not buffered, flush '+playlistType+' buffer'),frag&&(this.fragmentTracker.removeFragment(frag),this.nextLoadPosition=frag.start),this.resetLoadingState(),flushBuffer}return!1},_proto.resetFragmentErrors=function(filterType){filterType===PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==State.STOPPED&&(this.state=State.IDLE)},_proto.afterBufferFlushed=function(media,bufferType,playlistType){if(media){var bufferedTimeRanges=BufferHelper.getBuffered(media);this.fragmentTracker.detectEvictedFragments(bufferType,bufferedTimeRanges,playlistType),this.state===State.ENDED&&this.resetLoadingState()}},_proto.resetLoadingState=function(){this.log('Reset loading state'),this.fragCurrent=null,this.fragPrevious=null,this.state=State.IDLE},_proto.resetStartWhenNotLoaded=function(level){if(!this.loadedmetadata){this.startFragRequested=!1;var details=level?level.details:null;null!=details&&details.live?(this.startPosition=-1,this.setStartPosition(details,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},_proto.resetWhenMissingContext=function(chunkMeta){this.warn('The loading context changed while buffering fragment '+chunkMeta.sn+' of level '+chunkMeta.level+'. This chunk will not be buffered.'),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},_proto.removeUnbufferedFrags=function(start){void 0===start&&(start=0),this.fragmentTracker.removeFragmentsInRange(start,Infinity,this.playlistType,!1,!0)},_proto.updateLevelTiming=function(frag,part,level,partial){var _this6=this,details=level.details,_this$transmuxer;
1if(!details)return void this.warn('level.details undefined');var parsed=Object.keys(frag.elementaryStreams).reduce(function(result,type){var info=frag.elementaryStreams[type];if(info){var parsedDuration=info.endPTS-info.startPTS;if(0>=parsedDuration)return _this6.warn('Could not parse fragment '+frag.sn+' '+type+' duration reliably ('+parsedDuration+')'),result||!1;var drift=partial?0:updateFragPTSDTS(details,frag,info.startPTS,info.endPTS,info.startDTS,info.endDTS);return _this6.hls.trigger(Events.LEVEL_PTS_UPDATED,{details:details,level:level,drift:drift,type:type,frag:frag,start:info.startPTS,end:info.endPTS}),!0}return result},!1);if(!parsed&&null===(null==(_this$transmuxer=this.transmuxer)?void 0:_this$transmuxer.error)){var error=new Error('Found no media in fragment '+frag.sn+' of level '+frag.level+' resetting transmuxer to fallback to playlist timing');if(0===level.fragmentError&&(level.fragmentError++,frag.gap=!0,this.fragmentTracker.removeFragment(frag),this.fragmentTracker.fragBuffered(frag,!0)),this.warn(error.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:error,frag:frag,reason:'Found no media in msn '+frag.sn+' of level "'+level.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=State.PARSED,this.hls.trigger(Events.FRAG_PARSED,{frag:frag,part:part})},_proto.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},_proto.recoverWorkerError=function(data){'demuxerWorker'===data.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},_createClass(BaseStreamController,[{key:'state',get:function(){return this._state},set:function(nextState){var previousState=this._state;previousState!==nextState&&(this._state=nextState,this.log(previousState+'->'+nextState))}}]),BaseStreamController}(TaskLoop),ChunkCache=function(){function ChunkCache(){this.chunks=[],this.dataLength=0}var _proto=ChunkCache.prototype;return _proto.push=function(chunk){this.chunks.push(chunk),this.dataLength+=chunk.length},_proto.flush=function(){var chunks=this.chunks,dataLength=this.dataLength,result;return chunks.length?(result=1===chunks.length?chunks[0]:concatUint8Arrays(chunks,dataLength),this.reset(),result):new Uint8Array(0)},_proto.reset=function(){this.chunks.length=0,this.dataLength=0},ChunkCache}(),BaseAudioDemuxer=function(){function BaseAudioDemuxer(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var _proto=BaseAudioDemuxer.prototype;return _proto.resetInitSegment=function(){this._id3Track={type:'id3',id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},_proto.resetTimeStamp=function(deaultTimestamp){this.initPTS=deaultTimestamp,this.resetContiguity()},_proto.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},_proto.canParse=function(){return!1},_proto.appendFrame=function(){},_proto.demux=function(data,timeOffset){this.cachedData&&(data=appendUint8Array(this.cachedData,data),this.cachedData=null);var id3Data=getID3Data(data,0),offset=id3Data?id3Data.length:0,track=this._audioTrack,id3Track=this._id3Track,timestamp=id3Data?getTimeStamp(id3Data):void 0,length=data.length,lastDataIndex;for((null===this.basePTS||0===this.frameIndex&&isFiniteNumber(timestamp))&&(this.basePTS=initPTSFn(timestamp,timeOffset,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),id3Data&&0<id3Data.length&&id3Track.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:id3Data,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});offset<length;){if(this.canParse(data,offset)){var frame=this.appendFrame(track,data,offset);frame?(this.frameIndex++,this.lastPTS=frame.sample.pts,offset+=frame.length,lastDataIndex=offset):offset=length}else canParse$2(data,offset)?(id3Data=getID3Data(data,offset),id3Track.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:id3Data,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),offset+=id3Data.length,lastDataIndex=offset):offset++;if(offset===length&&lastDataIndex!==length){var partialData=sliceUint8(data,lastDataIndex);
vendor: 4,427 bytes, line 1
1this.cachedData=this.cachedData?appendUint8Array(this.cachedData,partialData):partialData}}return{audioTrack:track,videoTrack:dummyTrack(),id3Track:id3Track,textTrack:dummyTrack()}},_proto.demuxSampleAes=function(){return Promise.reject(new Error('['+this+'] This demuxer does not support Sample-AES decryption'))},_proto.flush=function(){var cachedData=this.cachedData;return cachedData&&(this.cachedData=null,this.demux(cachedData,0)),{audioTrack:this._audioTrack,videoTrack:dummyTrack(),id3Track:this._id3Track,textTrack:dummyTrack()}},_proto.destroy=function(){},BaseAudioDemuxer}(),initPTSFn=function(timestamp,timeOffset,initPTS){if(isFiniteNumber(timestamp))return 90*timestamp;var init90kHz=initPTS?9e4*initPTS.baseTime/initPTS.timescale:0;return 9e4*timeOffset+init90kHz},chromeVersion$1=null,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],AACDemuxer=function(_BaseAudioDemuxer){function AACDemuxer(observer,config){var _this;return _this=_BaseAudioDemuxer.call(this)||this,_this.observer=void 0,_this.config=void 0,_this.observer=observer,_this.config=config,_this}_inheritsLoose(AACDemuxer,_BaseAudioDemuxer);var _proto=AACDemuxer.prototype;return _proto.resetInitSegment=function(initSegment,audioCodec,videoCodec,trackDuration){_BaseAudioDemuxer.prototype.resetInitSegment.call(this,initSegment,audioCodec,videoCodec,trackDuration),this._audioTrack={container:'audio/adts',type:'audio',id:2,pid:-1,sequenceNumber:0,segmentCodec:'aac',samples:[],manifestCodec:audioCodec,duration:trackDuration,inputTimeScale:9e4,dropped:0}},AACDemuxer.probe=function(data){if(!data)return!1;var id3Data=getID3Data(data,0),offset=(null==id3Data?void 0:id3Data.length)||0;if(probe(data,offset))return!1;for(var length=data.length;offset<length;offset++)if(probe$1(data,offset))return logger.log('ADTS sync word found !'),!0;return!1},_proto.canParse=function(data,offset){return canParse$1(data,offset)},_proto.appendFrame=function(track,data,offset){initTrackConfig(track,this.observer,data,offset,track.manifestCodec);var frame=appendFrame$1(track,data,offset,this.basePTS,this.frameIndex);if(frame&&0===frame.missing)return frame},AACDemuxer}(BaseAudioDemuxer),emsgSchemePattern=/\/emsg[-/]ID3/i,MP4Demuxer=function(){function MP4Demuxer(observer,config){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=config}var _proto=MP4Demuxer.prototype;return _proto.resetTimeStamp=function(){},_proto.resetInitSegment=function(initSegment,audioCodec,videoCodec,trackDuration){var videoTrack=this.videoTrack=dummyTrack('video',1),audioTrack=this.audioTrack=dummyTrack('audio',1),captionTrack=this.txtTrack=dummyTrack('text',1);if(this.id3Track=dummyTrack('id3',1),this.timeOffset=0,!!(null!=initSegment&&initSegment.byteLength)){var initData=parseInitSegment(initSegment);if(initData.video){var _initData$video=initData.video,id=_initData$video.id,timescale=_initData$video.timescale,codec=_initData$video.codec;videoTrack.id=id,videoTrack.timescale=captionTrack.timescale=timescale,videoTrack.codec=codec}if(initData.audio){var _initData$audio=initData.audio,_id=_initData$audio.id,_timescale=_initData$audio.timescale,_codec=_initData$audio.codec;audioTrack.id=_id,audioTrack.timescale=_timescale,audioTrack.codec=_codec}captionTrack.id=RemuxerTrackIdConfig.text,videoTrack.sampleDuration=0,videoTrack.duration=audioTrack.duration=trackDuration}},_proto.resetContiguity=function(){this.remainderData=null},MP4Demuxer.probe=function(data){return hasMoofData(data)},_proto.demux=function(data,timeOffset){this.timeOffset=timeOffset;var videoSamples=data,videoTrack=this.videoTrack,textTrack=this.txtTrack;if(this.config.progressive){this.remainderData&&(videoSamples=appendUint8Array(this.remainderData,data));var segmentedData=segmentValidRange(videoSamples);this.remainderData=segmentedData.remainder,videoTrack.samples=segmentedData.valid||new Uint8Array}else videoTrack.samples=videoSamples;var id3Track=this.extractID3Track(videoTrack,timeOffset);
1return textTrack.samples=parseSamples(timeOffset,videoTrack),{videoTrack:videoTrack,audioTrack:this.audioTrack,id3Track:id3Track,textTrack:this.txtTrack}},_proto.flush=function(){var timeOffset=this.timeOffset,videoTrack=this.videoTrack,textTrack=this.txtTrack;videoTrack.samples=this.remainderData||new Uint8Array,this.remainderData=null;var id3Track=this.extractID3Track(videoTrack,this.timeOffset);return textTrack.samples=parseSamples(timeOffset,videoTrack),{videoTrack:videoTrack,audioTrack:dummyTrack(),id3Track:id3Track,textTrack:dummyTrack()}},_proto.extractID3Track=function(videoTrack,timeOffset){var id3Track=this.id3Track;if(videoTrack.samples.length){var emsgs=findBox(videoTrack.samples,['emsg']);emsgs&&emsgs.forEach(function(data){var emsgInfo=parseEmsg(data);if(emsgSchemePattern.test(emsgInfo.schemeIdUri)){var pts=isFiniteNumber(emsgInfo.presentationTime)?emsgInfo.presentationTime/emsgInfo.timeScale:timeOffset+emsgInfo.presentationTimeDelta/emsgInfo.timeScale,duration=4294967295===emsgInfo.eventDuration?Number.POSITIVE_INFINITY:emsgInfo.eventDuration/emsgInfo.timeScale;.001>=duration&&(duration=Number.POSITIVE_INFINITY);var payload=emsgInfo.payload;id3Track.samples.push({data:payload,len:payload.byteLength,dts:pts,pts:pts,type:MetadataSchema.emsg,duration:duration})}})}return id3Track},_proto.demuxSampleAes=function(){return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'))},_proto.destroy=function(){},MP4Demuxer}(),getAudioBSID=function(data,offset){var bsid=0,numBits=5;offset+=numBits;for(var temp=new Uint32Array(1),mask=new Uint32Array(1),_byte=new Uint8Array(1);0<numBits;){_byte[0]=data[offset];var bits=Math.min(numBits,8),shift=8-bits;mask[0]=4278190080>>>24+shift<<shift,temp[0]=(_byte[0]&mask[0])>>shift,bsid=bsid?bsid<<bits|temp[0]:temp[0],offset+=1,numBits-=bits}return bsid},AC3Demuxer=function(_BaseAudioDemuxer){function AC3Demuxer(observer){var _this;return _this=_BaseAudioDemuxer.call(this)||this,_this.observer=void 0,_this.observer=observer,_this}_inheritsLoose(AC3Demuxer,_BaseAudioDemuxer);var _proto=AC3Demuxer.prototype;return _proto.resetInitSegment=function(initSegment,audioCodec,videoCodec,trackDuration){_BaseAudioDemuxer.prototype.resetInitSegment.call(this,initSegment,audioCodec,videoCodec,trackDuration),this._audioTrack={container:'audio/ac-3',type:'audio',id:2,pid:-1,sequenceNumber:0,segmentCodec:'ac3',samples:[],manifestCodec:audioCodec,duration:trackDuration,inputTimeScale:9e4,dropped:0}},_proto.canParse=function(data,offset){return offset+64<data.length},_proto.appendFrame=function(track,data,offset){var frameLength=_appendFrame(track,data,offset,this.basePTS,this.frameIndex);if(-1!==frameLength){var sample=track.samples[track.samples.length-1];return{sample:sample,length:frameLength,missing:0}}},AC3Demuxer.probe=function(data){if(!data)return!1;var id3Data=getID3Data(data,0);if(!id3Data)return!1;var offset=id3Data.length;return!!(11===data[offset]&&119===data[offset+1]&&void 0!==getTimeStamp(id3Data)&&16>getAudioBSID(data,offset))},AC3Demuxer}(BaseAudioDemuxer),BaseVideoParser=function(){function BaseVideoParser(){this.VideoSample=null}var _proto=BaseVideoParser.prototype;return _proto.createVideoSample=function(key,pts,dts,debug){return{key:key,frame:!1,pts:pts,dts:dts,units:[],debug:debug,length:0}},_proto.getLastNalUnit=function(samples){var VideoSample=this.VideoSample,_VideoSample,lastUnit;if(VideoSample&&0!==VideoSample.units.length||(VideoSample=samples[samples.length-1]),null!=(_VideoSample=VideoSample)&&_VideoSample.units){var units=VideoSample.units;lastUnit=units[units.length-1]}return lastUnit},_proto.pushAccessUnit=function(VideoSample,videoTrack){if(VideoSample.units.length&&VideoSample.frame){if(void 0===VideoSample.pts){var samples=videoTrack.samples,nbSamples=samples.length;if(nbSamples){var lastSample=samples[nbSamples-1];VideoSample.pts=lastSample.pts,VideoSample.dts=lastSample.dts}else return void videoTrack.dropped++}videoTrack.samples.push(VideoSample)}VideoSample.debug.length&&logger.log(VideoSample.pts+'/'+VideoSample.dts+':'+VideoSample.debug)},BaseVideoParser}(),ExpGolomb=function(){function ExpGolomb(data){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=data,this.bytesAvailable=data.byteLength,this.word=0,this.bitsAvailable=0}var _proto=ExpGolomb.prototype;return _proto.loadWord=function(){var data=this.data,bytesAvailable=this.bytesAvailable,position=data.byteLength-bytesAvailable,workingBytes=new Uint8Array(4),availableBytes=Math.min(4,bytesAvailable);if(0===availableBytes)throw new Error('no bytes available');workingBytes.set(data.subarray(position,position+availableBytes)),this.word=new DataView(workingBytes.buffer).getUint32(0),this.bitsAvailable=8*availableBytes,this.bytesAvailable-=availableBytes},_proto.skipBits=function(count){var skipBytes;count=Math.min(count,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>count?(this.word<<=count,this.bitsAvailable-=count):(count-=this.bitsAvailable,skipBytes=count>>3,count-=skipBytes<<3,this.bytesAvailable-=skipBytes,this.loadWord(),this.word<<=count,this.bitsAvailable-=count)},_proto.readBits=function(size){var bits=Math.min(this.bitsAvailable,size),valu=this.word>>>32-bits;if(32<size&&logger.error('Cannot read more than 32 bits at a time'),this.bitsAvailable-=bits,0<this.bitsAvailable)this.word<<=bits;else if(0<this.bytesAvailable)this.loadWord();else throw new Error('no bits available');return bits=size-bits,0<bits&&this.bitsAvailable?valu<<bits|this.readBits(bits):valu},_proto.skipLZ=function(){var leadingZeroCount;for(leadingZeroCount=0;leadingZeroCount<this.bitsAvailable;++leadingZeroCount)if(0!=(this.word&2147483648>>>leadingZeroCount))return this.word<<=leadingZeroCount,this.bitsAvailable-=leadingZeroCount,leadingZeroCount;return this.loadWord(),leadingZeroCount+this.skipLZ()},_proto.skipUEG=function(){this.skipBits(1+this.skipLZ())},_proto.skipEG=function(){this.skipBits(1+this.skipLZ())},_proto.readUEG=function(){var clz=this.skipLZ();return this.readBits(clz+1)-1},_proto.readEG=function(){var valu=this.readUEG();return 1&valu?1+valu>>>1:-1*(valu>>>1)},_proto.readBoolean=function(){return 1===this.readBits(1)},_proto.readUByte=function(){return this.readBits(8)},_proto.readUShort=function(){return this.readBits(16)},_proto.readUInt=function(){return this.readBits(32)},_proto.skipScalingList=function(count){for(var lastScale=8,nextScale=8,j=0,deltaScale;j<count;j++)0!=nextScale&&(deltaScale=this.readEG(),nextScale=(lastScale+deltaScale+256)%256),lastScale=0==nextScale?lastScale:nextScale},_proto.readSPS=function(){var frameCropLeftOffset=0,frameCropRightOffset=0,frameCropTopOffset=0,frameCropBottomOffset=0,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),numRefFramesInPicOrderCntCycle,scalingListCount,i;readUByte();var profileIdc=readUByte();if(readBits(5),skipBits(3),readUByte(),skipUEG(),100===profileIdc||110===profileIdc||122===profileIdc||244===profileIdc||44===profileIdc||83===profileIdc||86===profileIdc||118===profileIdc||128===profileIdc){var chromaFormatIdc=readUEG();if(3===chromaFormatIdc&&skipBits(1),skipUEG(),skipUEG(),skipBits(1),readBoolean())for(scalingListCount=3===chromaFormatIdc?12:8,i=0;i<scalingListCount;i++)readBoolean()&&(6>i?skipScalingList(16):skipScalingList(64))}skipUEG();var picOrderCntType=readUEG();if(0===picOrderCntType)readUEG();else if(1===picOrderCntType)for(skipBits(1),skipEG(),skipEG(),numRefFramesInPicOrderCntCycle=readUEG(),i=0;i<numRefFramesInPicOrderCntCycle;i++)skipEG();skipUEG(),skipBits(1);var picWidthInMbsMinus1=readUEG(),picHeightInMapUnitsMinus1=readUEG(),frameMbsOnlyFlag=readBits(1);0===frameMbsOnlyFlag&&skipBits(1),skipBits(1),readBoolean()&&(frameCropLeftOffset=readUEG(),frameCropRightOffset=readUEG(),frameCropTopOffset=readUEG(),frameCropBottomOffset=readUEG());var pixelRatio=[1,1];if(readBoolean()&&readBoolean()){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(16*(picWidthInMbsMinus1+1)-2*frameCropLeftOffset-2*frameCropRightOffset),height:16*((2-frameMbsOnlyFlag)*(picHeightInMapUnitsMinus1+1))-(frameMbsOnlyFlag?2:4)*(frameCropTopOffset+frameCropBottomOffset),pixelRatio:pixelRatio}},_proto.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},ExpGolomb}(),AvcVideoParser=function(_BaseVideoParser){function AvcVideoParser(){return _BaseVideoParser.apply(this,arguments)||this}_inheritsLoose(AvcVideoParser,_BaseVideoParser);var _proto=AvcVideoParser.prototype;return _proto.parseAVCPES=function(track,textTrack,pes,last,duration){var _this=this,units=this.parseAVCNALu(track,pes.data),VideoSample=this.VideoSample,spsfound=!1,push;pes.data=null,VideoSample&&units.length&&!track.audFound&&(this.pushAccessUnit(VideoSample,track),VideoSample=this.VideoSample=this.createVideoSample(!1,pes.pts,pes.dts,'')),units.forEac
1h(function(unit){var _VideoSample2;switch(unit.type){case 1:{var iskey=!1;push=!0;var data=unit.data;if(spsfound&&4<data.length){var sliceType=new ExpGolomb(data).readSliceType();(2===sliceType||4===sliceType||7===sliceType||9===sliceType)&&(iskey=!0)}if(iskey){var _VideoSample;null!=(_VideoSample=VideoSample)&&_VideoSample.frame&&!VideoSample.key&&(_this.pushAccessUnit(VideoSample,track),VideoSample=_this.VideoSample=null)}VideoSample||(VideoSample=_this.VideoSample=_this.createVideoSample(!0,pes.pts,pes.dts,'')),VideoSample.frame=!0,VideoSample.key=iskey;break}case 5:push=!0,null!=(_VideoSample2=VideoSample)&&_VideoSample2.frame&&!VideoSample.key&&(_this.pushAccessUnit(VideoSample,track),VideoSample=_this.VideoSample=null),VideoSample||(VideoSample=_this.VideoSample=_this.createVideoSample(!0,pes.pts,pes.dts,'')),VideoSample.key=!0,VideoSample.frame=!0;break;case 6:{push=!0,parseSEIMessageFromNALu(unit.data,1,pes.pts,textTrack.samples);break}case 7:{var _track$pixelRatio,_track$pixelRatio2;push=!0,spsfound=!0;var sps=unit.data,expGolombDecoder=new ExpGolomb(sps),config=expGolombDecoder.readSPS();if(!track.sps||track.width!==config.width||track.height!==config.height||(null==(_track$pixelRatio=track.pixelRatio)?void 0:_track$pixelRatio[0])!==config.pixelRatio[0]||(null==(_track$pixelRatio2=track.pixelRatio)?void 0:_track$pixelRatio2[1])!==config.pixelRatio[1]){track.width=config.width,track.height=config.height,track.pixelRatio=config.pixelRatio,track.sps=[sps],track.duration=duration;for(var codecarray=sps.subarray(1,4),codecstring='avc1.',i=0,h;3>i;i++)h=codecarray[i].toString(16),2>h.length&&(h='0'+h),codecstring+=h;track.codec=codecstring}break}case 8:push=!0,track.pps=[unit.data];break;case 9:push=!0,track.audFound=!0,VideoSample&&_this.pushAccessUnit(VideoSample,track),VideoSample=_this.VideoSample=_this.createVideoSample(!1,pes.pts,pes.dts,'');break;case 12:push=!0;break;default:push=!1,VideoSample&&(VideoSample.debug+='unknown NAL '+unit.type+' ');}if(VideoSample&&push){var _units=VideoSample.units;_units.push(unit)}}),last&&VideoSample&&(this.pushAccessUnit(VideoSample,track),this.VideoSample=null)},_proto.parseAVCNALu=function(track,array){var len=array.byteLength,state=track.naluState||0,lastState=state,units=[],i=0,lastUnitStart=-1,lastUnitType=0,value,overflow,unitType;for(-1===state&&(lastUnitStart=0,lastUnitType=31&array[0],state=0,i=1);i<len;){if(value=array[i++],!state){state=value?0:1;continue}if(1===state){state=value?0:2;continue}if(!value)state=3;else if(1===value){if(overflow=i-state-1,0<=lastUnitStart){var unit={data:array.subarray(lastUnitStart,overflow),type:lastUnitType};units.push(unit)}else{var lastUnit=this.getLastNalUnit(track.samples);lastUnit&&(lastState&&i<=4-lastState&&lastUnit.state&&(lastUnit.data=lastUnit.data.subarray(0,lastUnit.data.byteLength-lastState)),0<overflow&&(lastUnit.data=appendUint8Array(lastUnit.data,array.subarray(0,overflow)),lastUnit.state=0))}i<len?(unitType=31&array[i],lastUnitStart=i,lastUnitType=unitType,state=0):state=-1}else state=0}if(0<=lastUnitStart&&0<=state){var _unit={data:array.subarray(lastUnitStart,len),type:lastUnitType,state:state};units.push(_unit)}if(0===units.length){var _lastUnit=this.getLastNalUnit(track.samples);_lastUnit&&(_lastUnit.data=appendUint8Array(_lastUnit.data,array))}return track.naluState=state,units},AvcVideoParser}(BaseVideoParser),SampleAesDecrypter=function(){function SampleAesDecrypter(observer,config,keyData){this.keyData=void 0,this.decrypter=void 0,this.keyData=keyData,this.decrypter=new Decrypter(config,{removePKCS7Padding:!1})}var _proto=SampleAesDecrypter.prototype;return _proto.decryptBuffer=function(encryptedData){return this.decrypter.decrypt(encryptedData,this.keyData.key.buffer,this.keyData.iv.buffer)},_proto.decryptAacSample=function(samples,sampleIndex,callback){var _this=this,curUnit=samples[sampleIndex].unit;if(!(16>=curUnit.length)){var encryptedData=curUnit.subarray(16,curUnit.length-curUnit.length%16),encryptedBuffer=encryptedData.buffer.slice(encryptedData.byteOffset,encryptedData.byteOffset+encryptedData.length);this.decryptBuffer(encryptedBuffer).then(function(decryptedBuffer){var decryptedData=new Uint8Array(decryptedBuffer);curUnit.set(decryptedData,16),_this.decrypter.isSync()||_this.decryptAacSamples(samples,sampleIndex+1,callback)})}},_proto.decryptAacSamples=function(samples,sampleIndex,callback){for(;;sampleIndex++){if(sampleIndex>=samples.length)return void callback();if(!(32>samples[sampleIndex].unit.length)&&(this.decryptAacSample(samples,sampleIndex,callback),!this.decrypter.isSync()))return}},_proto.getAvcEncryptedData=function(decodedData){for(var encryptedDataLen=16*Math.floor((decodedData.length-48)/160)+16,encryptedData=new Int8Array(encryptedDataLen),outputPos=0,inputPos=32;inputPos<decodedData.length-16;inputPos+=160,outputPos+=16)encryptedData.set(decodedData.subarray(inputPos,inputPos+16),outputPos);return encryptedData},_proto.getAvcDecryptedUnit=function(decodedData,decryptedData){for(var uint8DecryptedData=new Uint8Array(decryptedData),inputPos=0,outputPos=32;outputPos<decodedData.length-16;outputPos+=160,inputPos+=16)decodedData.set(uint8DecryptedData.subarray(inputPos,inputPos+16),outputPos);return decodedData},_proto.decryptAvcSample=function(samples,sampleIndex,unitIndex,callback,curUnit){var _this2=this,decodedData=discardEPB(curUnit.data),encryptedData=this.getAvcEncryptedData(decodedData);this.decryptBuffer(encryptedData.buffer).then(function(decryptedBuffer){curUnit.data=_this2.getAvcDecryptedUnit(decodedData,decryptedBuffer),_this2.decrypter.isSync()||_this2.decryptAvcSamples(samples,sampleIndex,unitIndex+1,callback)})},_proto.decryptAvcSamples=function(samples,sampleIndex,unitIndex,callback){if(samples instanceof Uint8Array)throw new Error('Cannot decrypt samples of type Uint8Array');for(;;sampleIndex++,unitIndex=0){if(sampleIndex>=samples.length)return void callback();for(var curUnits=samples[sampleIndex].units;;unitIndex++){if(unitIndex>=curUnits.length)break;var curUnit=curUnits[unitIndex];if(!(48>=curUnit.data.length||1!==curUnit.type&&5!==curUnit.type)&&(this.decryptAvcSample(samples,sampleIndex,unitIndex,callback,curUnit),!this.decrypter.isSync()))return}}},SampleAesDecrypter}(),PACKET_LENGTH=188,TSDemuxer=function(){function TSDemuxer(observer,config,typeSupp
1orted){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=observer,this.config=config,this.typeSupported=typeSupported,this.videoParser=new AvcVideoParser}TSDemuxer.probe=function(data){var syncOffset=TSDemuxer.syncOffset(data);return 0<syncOffset&&logger.warn('MPEG2-TS detected but first sync word found @ offset '+syncOffset),-1!==syncOffset},TSDemuxer.syncOffset=function(data){for(var length=data.length,scanwindow=Math.min(5*PACKET_LENGTH,length-PACKET_LENGTH)+1,i=0;i<scanwindow;){for(var foundPat=!1,packetStart=-1,tsPackets=0,j=i;j<length;j+=PACKET_LENGTH)if(71!==data[j]||length-j!==PACKET_LENGTH&&71!==data[j+PACKET_LENGTH]){if(tsPackets)return-1;break}else if(tsPackets++,-1===packetStart&&(packetStart=j,0!==packetStart&&(scanwindow=Math.min(packetStart+99*PACKET_LENGTH,data.length-PACKET_LENGTH)+1)),foundPat||(foundPat=0===parsePID(data,j)),foundPat&&1<tsPackets&&(0===packetStart&&2<tsPackets||j+PACKET_LENGTH>scanwindow))return packetStart;i++}return-1},TSDemuxer.createTrack=function(type,duration){return{container:'video'===type||'audio'===type?'video/mp2t':void 0,type:type,id:RemuxerTrackIdConfig[type],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:'audio'===type?duration:void 0}};var _proto=TSDemuxer.prototype;return _proto.resetInitSegment=function(initSegment,audioCodec,videoCodec,trackDuration){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack('video'),this._audioTrack=TSDemuxer.createTrack('audio',trackDuration),this._id3Track=TSDemuxer.createTrack('id3'),this._txtTrack=TSDemuxer.createTrack('text'),this._audioTrack.segmentCodec='aac',this.aacOverFlow=null,this.remainderData=null,this.audioCodec=audioCodec,this.videoCodec=videoCodec,this._duration=trackDuration},_proto.resetTimeStamp=function(){},_proto.resetContiguity=function(){var _audioTrack=this._audioTrack,_videoTrack=this._videoTrack,_id3Track=this._id3Track;_audioTrack&&(_audioTrack.pesData=null),_videoTrack&&(_videoTrack.pesData=null),_id3Track&&(_id3Track.pesData=null),this.aacOverFlow=null,this.remainderData=null},_proto.demux=function(data,timeOffset,isSampleAes,flush){void 0===isSampleAes&&(isSampleAes=!1),void 0===flush&&(flush=!1),isSampleAes||(this.sampleAes=null);var videoTrack=this._videoTrack,audioTrack=this._audioTrack,id3Track=this._id3Track,textTrack=this._txtTrack,videoPid=videoTrack.pid,videoData=videoTrack.pesData,audioPid=audioTrack.pid,id3Pid=id3Track.pid,audioData=audioTrack.pesData,id3Data=id3Track.pesData,unknownPID=null,pmtParsed=this.pmtParsed,pmtId=this._pmtId,len=data.length,pes;if(this.remainderData&&(data=appendUint8Array(this.remainderData,data),len=data.length,this.remainderData=null),len<PACKET_LENGTH&&!flush)return this.remainderData=data,{audioTrack:audioTrack,videoTrack:videoTrack,id3Track:id3Track,textTrack:textTrack};var syncOffset=Math.max(0,TSDemuxer.syncOffset(data));len-=(len-syncOffset)%PACKET_LENGTH,len<data.byteLength&&!flush&&(this.remainderData=new Uint8Array(data.buffer,len,data.buffer.byteLength-len));for(var tsPacketErrors=0,start=syncOffset;start<len;start+=PACKET_LENGTH)if(71===data[start]){var stt=!!(64&data[start+1]),pid=parsePID(data,start),atf=(48&data[start+3])>>4,offset=void 0;if(!(1<atf))offset=start+4;else if(offset=start+5+data[start+4],offset===start+PACKET_LENGTH)continue;switch(pid){case videoPid:stt&&(videoData&&(pes=parsePES(videoData))&&this.videoParser.parseAVCPES(videoTrack,textTrack,pes,!1,this._duration),videoData={data:[],size:0}),videoData&&(videoData.data.push(data.subarray(offset,start+PACKET_LENGTH)),videoData.size+=start+PACKET_LENGTH-offset);break;case audioPid:if(stt){if(audioData&&(pes=parsePES(audioData)))switch(audioTrack.segmentCodec){case'aac':this.parseAACPES(audioTrack,pes);break;case'mp3':this.parseMPEGPES(audioTrack,pes);break;case'ac3':this.parseAC3PES(audioTrack,pes);}audioData={data:[],size:0}}audioData&&(audioData.data.push(data.subarray(offset,start+PACKET_LENGTH)),audioData.size+=start+PACKET_LENGTH-offset);break;case id3Pid:stt&&(id3Data&&(pes=parsePES(id3Data))&&this.parseID3PES(id3Track,pes),id3Data={data:[],size:0}),id3Data&&(id3Data.data.push(data.subarray(offset,start+PACKET_LENGTH)),id3Data.size+=start+PACKET_LENGTH-offset);break;case 0:stt&&(offset+=data[offset]+1),pmtId=this._pmtId=parsePAT(data,offset);break;case pmtId:{stt&&(offset+=data[offset]+1);
1var parsedPIDs=parsePMT(data,offset,this.typeSupported,isSampleAes,this.observer);videoPid=parsedPIDs.videoPid,0<videoPid&&(videoTrack.pid=videoPid,videoTrack.segmentCodec=parsedPIDs.segmentVideoCodec),audioPid=parsedPIDs.audioPid,0<audioPid&&(audioTrack.pid=audioPid,audioTrack.segmentCodec=parsedPIDs.segmentAudioCodec),id3Pid=parsedPIDs.id3Pid,0<id3Pid&&(id3Track.pid=id3Pid),null===unknownPID||pmtParsed||(logger.warn('MPEG-TS PMT found at '+start+' after unknown PID \''+unknownPID+'\'. Backtracking to sync byte @'+syncOffset+' to parse all TS packets.'),unknownPID=null,start=syncOffset-188),pmtParsed=this.pmtParsed=!0;break}case 17:case 8191:break;default:unknownPID=pid;}}else tsPacketErrors++;0<tsPacketErrors&&emitParsingError(this.observer,new Error('Found '+tsPacketErrors+' TS packet/s that do not start with 0x47')),videoTrack.pesData=videoData,audioTrack.pesData=audioData,id3Track.pesData=id3Data;var demuxResult={audioTrack:audioTrack,videoTrack:videoTrack,id3Track:id3Track,textTrack:textTrack};return flush&&this.extractRemainingSamples(demuxResult),demuxResult},_proto.flush=function(){var remainderData=this.remainderData;this.remainderData=null;var result;return result=remainderData?this.demux(remainderData,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(result),this.sampleAes?this.decrypt(result,this.sampleAes):result},_proto.extractRemainingSamples=function(demuxResult){var audioTrack=demuxResult.audioTrack,videoTrack=demuxResult.videoTrack,id3Track=demuxResult.id3Track,textTrack=demuxResult.textTrack,videoData=videoTrack.pesData,audioData=audioTrack.pesData,id3Data=id3Track.pesData,pes;if(videoData&&(pes=parsePES(videoData))?(this.videoParser.parseAVCPES(videoTrack,textTrack,pes,!0,this._duration),videoTrack.pesData=null):videoTrack.pesData=videoData,audioData&&(pes=parsePES(audioData))){switch(audioTrack.segmentCodec){case'aac':this.parseAACPES(audioTrack,pes);break;case'mp3':this.parseMPEGPES(audioTrack,pes);break;case'ac3':this.parseAC3PES(audioTrack,pes);}audioTrack.pesData=null}else null!=audioData&&audioData.size&&logger.log('last AAC PES packet truncated,might overlap between fragments'),audioTrack.pesData=audioData;id3Data&&(pes=parsePES(id3Data))?(this.parseID3PES(id3Track,pes),id3Track.pesData=null):id3Track.pesData=id3Data},_proto.demuxSampleAes=function(data,keyData,timeOffset){var demuxResult=this.demux(data,timeOffset,!0,!this.config.progressive),sampleAes=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,keyData);return this.decrypt(demuxResult,sampleAes)},_proto.decrypt=function(demuxResult,sampleAes){return new Promise(function(resolve){var audioTrack=demuxResult.audioTrack,videoTrack=demuxResult.videoTrack;audioTrack.samples&&'aac'===audioTrack.segmentCodec?sampleAes.decryptAacSamples(audioTrack.samples,0,function(){videoTrack.samples?sampleAes.decryptAvcSamples(videoTrack.samples,0,0,function(){resolve(demuxResult)}):resolve(demuxResult)}):videoTrack.samples&&sampleAes.decryptAvcSamples(videoTrack.samples,0,0,function(){resolve(demuxResult)})})},_proto.destroy=function(){this._duration=0},_proto.parseAACPES=function(track,pes){var startOffset=0,aacOverFlow=this.aacOverFlow,data=pes.data;if(aacOverFlow){this.aacOverFlow=null;var frameMissingBytes=aacOverFlow.missing,sampleLength=aacOverFlow.sample.unit.byteLength;if(-1===frameMissingBytes)data=appendUint8Array(aacOverFlow.sample.unit,data);else{aacOverFlow.sample.unit.set(data.subarray(0,frameMissingBytes),sampleLength-frameMissingBytes),track.samples.push(aacOverFlow.sample),startOffset=aacOverFlow.missing}}var offset,len;for(offset=startOffset,len=data.length;offset<len-1&&!isHeader$1(data,offset);offset++);if(offset!==startOffset){var recoverable=offset<len-1,reason;if(reason=recoverable?'AAC PES did not start with ADTS header,offset:'+offset:'No ADTS header found in AAC PES',emitParsingError(this.observer,new Error(reason),recoverable),!recoverable)return}initTrackConfig(track,this.observer,data,offset,this.audioCodec);var pts;if(void 0!==pes.pts)pts=pes.pts;else if(aacOverFlow){var frameDuration=getFrameDuration(track.samplerate);pts=aacOverFlow.sample.pts+frameDuration}else return void logger.warn('[tsdemuxer]: AAC PES unknown PTS');for(var frameIndex=0,frame;offset<len;)if(frame=appendFrame$1(track,data,offset,pts,frameIndex),offset+=frame.length,!frame.missing)for(frameIndex++;offset<len-1&&!isHeader$1(data,offset);offset++);else{this.aacOverFlow=frame;break}},_proto.parseMPEGPES=function(track,pes){var data=pes.data,length=data.length,frameIndex=0,offset=0,pts=pes.pts;if(void 0===pts)return void logger.warn('[tsdemuxer]: MPEG PES unknown PTS');for(;offset<length;)if(isHeader(data,offset)){var frame=appendFrame(track,data,offset,pts,frameIndex);if(frame)offset+=frame.length,frameIndex++;else break}else offset++},_proto.parseAC3PES=function(track,pes){{var data=pes.data,pts=pes.pts;if(void 0===pts)return void logger.warn('[tsdemuxer]: AC3 PES unknown PTS');for(var length=data.length,frameIndex=0,offset=0,parsed;offset<length&&0<(parsed=_appendFrame(track,data,offset,pts,frameIndex++));)offset+=parsed}},_proto.parseID3PES=function(id3Track,pes){if(void 0===pes.pts)return void logger.warn('[tsdemuxer]: ID3 PES unknown PTS');var id3Sample=_extends({},pes,{type:this._videoTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});id3Track.samples.push(id3Sample)},TSDemuxer}(),MP3Demuxer=function(_BaseAudioDemuxer){function MP3Demuxer(){return _BaseAudioDemuxer.apply(this,arguments)||this}_inheritsLoose(MP3Demuxer,_BaseAudioDemuxer);var _proto=MP3Demuxer.prototype;return _proto.resetInitSegment=function(initSegment,audioCodec,videoCodec,trackDuration){_BaseAudioDemuxer.prototype.resetInitSegment.call(this,initSegment,audioCodec,videoCodec,trackDuration),this._audioTrack={container:'audio/mpeg',type:'audio',id:2,pid:-1,sequenceNumber:0,segmentCodec:'mp3',samples:[],manifestCodec:audioCodec,duration:trackDuration,inputTimeScale:9e4,dropped:0}},MP3Demuxer.probe=function(data){if(!data)return!1;var id3Data=getID3Data(data,0),offset=(null==id3Data?void 0:id3Data.length)||0;if(id3Data&&11===data[offset]&&119===data[offset+1]&&void 0!==getTimeStamp(id3Data)&&16>=getAudioBSID(data,offset))return!1;for(var length=data.length;offset<length;offset++)if(probe(data,offset))return logger.log('MPEG Audio sync word found !'),!0;return!1},_proto.canParse=function(data,offset){return canParse(data,offset)},_proto.appendFrame=function(track,data,offset){return null===this.basePTS?void 0:appendFrame(track,data,offset,this.basePTS,this.frameIndex)},MP3Demuxer}(BaseAudioDemuxer),AAC=function(){function AAC(){}return AAC.getSilentFrame=function(codec,channelCount){switch(codec){case'mp4a.40.2':if(1===channelCount)return new Uint8Array([0,200,0,128,35,128]);if(2===channelCount)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===channelCount)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===channelCount)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===channelCount)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===channelCount)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===channelCount)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===channelCount)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===channelCount)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]);}},AAC}(),UINT32_MAX=Math.pow(2,32)-1,MP4=function(){function MP4(){}return MP4.init=function(){MP4.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],'.mp3':[],dac3:[],'ac-3':[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};for(var i in MP4.types)MP4.types.hasOwnProperty(i)&&(MP4.types[i]=[i.charCo
1deAt(0),i.charCodeAt(1),i.charCodeAt(2),i.charCodeAt(3)]);var videoHdlr=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]),audioHdlr=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]);MP4.HDLR_TYPES={video:videoHdlr,audio:audioHdlr};var dref=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),stco=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=stco,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var majorBrand=new Uint8Array([105,115,111,109]),avc1Brand=new Uint8Array([97,118,99,49]),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(type){for(var size=8,_len=arguments.length,payload=Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)payload[_key-1]=arguments[_key];for(var i=payload.length,len=i;i--;)size+=payload[i].byteLength;var result=new Uint8Array(size);for(result[0]=255&size>>24,result[1]=255&size>>16,result[2]=255&size>>8,result[3]=255&size,result.set(type,4),(i=0,size=8);i<len;i++)result.set(payload[i],size),size+=payload[i].byteLength;return result},MP4.hdlr=function(type){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[type])},MP4.mdat=function(data){return MP4.box(MP4.types.mdat,data)},MP4.mdhd=function(timescale,duration){duration*=timescale;var upperWordDuration=Math.floor(duration/(UINT32_MAX+1)),lowerWordDuration=Math.floor(duration%(UINT32_MAX+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,255×cale>>24,255×cale>>16,255×cale>>8,255×cale,upperWordDuration>>24,255&upperWordDuration>>16,255&upperWordDuration>>8,255&upperWordDuration,lowerWordDuration>>24,255&lowerWordDuration>>16,255&lowerWordDuration>>8,255&lowerWordDuration,85,196,0,0]))},MP4.mdia=function(track){return MP4.box(MP4.types.mdia,MP4.mdhd(track.timescale,track.duration),MP4.hdlr(track.type),MP4.minf(track))},MP4.mfhd=function(sequenceNumber){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,sequenceNumber>>24,255&sequenceNumber>>16,255&sequenceNumber>>8,255&sequenceNumber]))},MP4.minf=function(track){return'audio'===track.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(track)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(track))},MP4.moof=function(sn,baseMediaDecodeTime,track){return MP4.box(MP4.types.moof,MP4.mfhd(sn),MP4.traf(track,baseMediaDecodeTime))},MP4.moov=function(tracks){for(var i=tracks.length,boxes=[];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(tracks){for(var i=tracks.length,boxes=[];i--;)boxes[i]=MP4.trex(tracks[i]);return MP4.box.apply(null,[MP4.types.mvex].concat(boxes))},MP4.mvhd=function(timescale,duration){duration*=timescale;var upperWordDuration=Math.floor(duration/(UINT32_MAX+1)),lowerWordDuration=Math.floor(duration%(UINT32_MAX+1)),bytes=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,255×cale>>24,255×cale>>16,255×cale>>8,255×cale,upperWordDuration>>24,255&upperWordDuration>>16,255&upperWordDuration>>8,255&upperWordDuration,lowerWordDuration>>24,255&lowerWordDuration>>16,255&lowerWordDuration>>8,255&lowerWordDuration,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 MP4.box(MP4.types.mvhd,bytes)},MP4.sdtp=function(track){var samples=track.samples||[],bytes=new Uint8Array(4+samples.length),i,flags;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(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(track){var sps=[],pps=[],i,data,len;for(i=0;i<track.sps.length;i++)data=track.sps[i],len=data.byteLength,sps.push(255&len>>>8),sps.push(255&len),sps=sps.concat(Array.prototype.slice.call(data));for(i=0;i<track.pps.length;i++)data=track.pps[i],len=data.byteLength,pps.push(255&len>>>8),pps.push(255&len),pps=pps.concat(Array.prototype.slice.call(data));var avcc=MP4.box(MP4.types.avcC,new Uint8Array([1,sps[3],sps[4],sps[5],255,224|track.sps.length].concat(sps).c
1oncat([track.pps.length]).concat(pps))),width=track.width,height=track.height,hSpacing=track.pixelRatio[0],vSpacing=track.pixelRatio[1];return MP4.box(MP4.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,255&width>>8,255&width,255&height>>8,255&height,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]),avcc,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([hSpacing>>24,255&hSpacing>>16,255&hSpacing>>8,255&hSpacing,vSpacing>>24,255&vSpacing>>16,255&vSpacing>>8,255&vSpacing])))},MP4.esds=function(track){var configlen=track.config.length;return new Uint8Array([0,0,0,0,3,23+configlen,0,1,0,4,15+configlen,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([configlen]).concat(track.config).concat([6,1,2]))},MP4.audioStsd=function(track){var samplerate=track.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,track.channelCount,0,16,0,0,0,0,255&samplerate>>8,255&samplerate,0,0])},MP4.mp4a=function(track){return MP4.box(MP4.types.mp4a,MP4.audioStsd(track),MP4.box(MP4.types.esds,MP4.esds(track)))},MP4.mp3=function(track){return MP4.box(MP4.types['.mp3'],MP4.audioStsd(track))},MP4.ac3=function(track){return MP4.box(MP4.types['ac-3'],MP4.audioStsd(track),MP4.box(MP4.types.dac3,track.config))},MP4.stsd=function(track){return'audio'===track.type?'mp3'===track.segmentCodec&&'mp3'===track.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(track)):'ac3'===track.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.ac3(track)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(track)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(track))},MP4.tkhd=function(track){var id=track.id,duration=track.duration*track.timescale,width=track.width,height=track.height,upperWordDuration=Math.floor(duration/(UINT32_MAX+1)),lowerWordDuration=Math.floor(duration%(UINT32_MAX+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,255&id>>24,255&id>>16,255&id>>8,255&id,0,0,0,0,upperWordDuration>>24,255&upperWordDuration>>16,255&upperWordDuration>>8,255&upperWordDuration,lowerWordDuration>>24,255&lowerWordDuration>>16,255&lowerWordDuration>>8,255&lowerWordDuration,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,255&width>>8,255&width,0,0,255&height>>8,255&height,0,0]))},MP4.traf=function(track,baseMediaDecodeTime){var sampleDependencyTable=MP4.sdtp(track),id=track.id,upperWordBaseMediaDecodeTime=Math.floor(baseMediaDecodeTime/(UINT32_MAX+1)),lowerWordBaseMediaDecodeTime=Math.floor(baseMediaDecodeTime%(UINT32_MAX+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,id>>24,255&id>>16,255&id>>8,255&id])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,upperWordBaseMediaDecodeTime>>24,255&upperWordBaseMediaDecodeTime>>16,255&upperWordBaseMediaDecodeTime>>8,255&upperWordBaseMediaDecodeTime,lowerWordBaseMediaDecodeTime>>24,255&lowerWordBaseMediaDecodeTime>>16,255&lowerWordBaseMediaDecodeTime>>8,255&lowerWordBaseMediaDecodeTime])),MP4.trun(track,sampleDependencyTable.length+16+20+8+16+8+8),sampleDependencyTable)},MP4.trak=function(track){return track.duration=track.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(track),MP4.mdia(track))},MP4.trex=function(track){var id=track.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,id>>24,255&id>>16,255&id>>8,255&id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},MP4.trun=function(track,offset){var samples=track.samples||[],len=samples.length,arraylen=12+16*len,array=new Uint8Array(arraylen),i,sample,duration,size,flags,cts;for(offset+=8+arraylen,array.set(['video'===track.type?1:0,0,15,1,255&len>>>24,255&len>>>16,255&len>>>8,255&len,255&offset>>>24,255&offset>>>16,255&offset>>>8,255&offset],0),i=0;i<len;i++)sample=samples[i],duration=sample.duration,size=sample.size,flags=sample.flags,cts=sample.cts,array.set([255&duration>>>24,255&duration>>>16,255&duration>>>8,255&duration,255&size>>>24,255&size>>>16,255&size>>>8,255&size,flags.isLeading<<2|flags.dependsOn,flags.isDependedOn<<6|flags.hasRedundancy<<4|flags.paddingValue<<1|flags.isNonSync,61440&flags.degradPrio,15&flags.degradPrio,255&cts>>>24,255&cts>>>16,255&cts>>>8,255&cts],12+16*i);return MP4.box(MP4.types.trun,array)},MP4.initSegment=function(tracks){MP4.types||MP4.init();var movie=MP4.moov(tracks),result=appendUint8Array(MP4.FTYP,movie);return result},MP4}(),decoder;MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;var MPEG_TS_CLOCK_FREQ_HZ=9e4,AAC_SAMPLES_PER_FRAME=1024,chromeVersion=null,safariWebkitVersion=null,MP4Remuxer=function(){function MP4Remuxer(observer,config,typeSupp
1orted){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=observer,this.config=config,this.typeSupported=typeSupported,this.ISGenerated=!1,null===chromeVersion){var userAgent=navigator.userAgent||'',result=userAgent.match(/Chrome\/(\d+)/i);chromeVersion=result?parseInt(result[1]):0}if(null===safariWebkitVersion){var _result=navigator.userAgent.match(/Safari\/(\d+)/i);safariWebkitVersion=_result?parseInt(_result[1]):0}}var _proto=MP4Remuxer.prototype;return _proto.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},_proto.resetTimeStamp=function(defaultTimeStamp){logger.log('[mp4-remuxer]: initPTS & initDTS reset'),this._initPTS=this._initDTS=defaultTimeStamp},_proto.resetNextTimestamp=function(){logger.log('[mp4-remuxer]: reset next timestamp'),this.isVideoContiguous=!1,this.isAudioContiguous=!1},_proto.resetInitSegment=function(){logger.log('[mp4-remuxer]: ISGenerated flag reset'),this.ISGenerated=!1,this.videoTrackConfig=void 0},_proto.getVideoStartPts=function(videoSamples){var rolloverDetected=!1,startPTS=videoSamples.reduce(function(minPTS,sample){var delta=sample.pts-minPTS;return-4294967296>delta?(rolloverDetected=!0,normalizePts(minPTS,sample.pts)):0<delta?minPTS:sample.pts},videoSamples[0].pts);return rolloverDetected&&logger.debug('PTS rollover detected'),startPTS},_proto.remux=function(audioTrack,videoTrack,id3Track,textTrack,timeOffset,accurateTimeOffset,flush,playlistType){var audioTimeOffset=timeOffset,videoTimeOffset=timeOffset,hasAudio=-1<audioTrack.pid,hasVideo=-1<videoTrack.pid,length=videoTrack.samples.length,enoughAudioSamples=0<audioTrack.samples.length,enoughVideoSamples=flush&&0<length||1<length,canRemuxAvc=(!hasAudio||enoughAudioSamples)&&(!hasVideo||enoughVideoSamples)||this.ISGenerated||flush,video,audio,initSegment,text,id3,independent;if(canRemuxAvc){if(this.ISGenerated){var config=this.videoTrackConfig,_videoTrack$pixelRati,_config$pixelRatio,_videoTrack$pixelRati2,_config$pixelRatio2;config&&(videoTrack.width!==config.width||videoTrack.height!==config.height||(null==(_videoTrack$pixelRati=videoTrack.pixelRatio)?void 0:_videoTrack$pixelRati[0])!==(null==(_config$pixelRatio=config.pixelRatio)?void 0:_config$pixelRatio[0])||(null==(_videoTrack$pixelRati2=videoTrack.pixelRatio)?void 0:_videoTrack$pixelRati2[1])!==(null==(_config$pixelRatio2=config.pixelRatio)?void 0:_config$pixelRatio2[1]))&&this.resetInitSegment()}else initSegment=this.generateIS(audioTrack,videoTrack,timeOffset,accurateTimeOffset);var isVideoContiguous=this.isVideoContiguous,firstKeyFrameIndex=-1,firstKeyFramePTS;if(enoughVideoSamples&&(firstKeyFrameIndex=findKeyframeIndex(videoTrack.samples),!isVideoContiguous&&this.config.forceKeyFrameOnDiscontinuity))if(independent=!0,0<firstKeyFrameIndex){logger.warn('[mp4-remuxer]: Dropped '+firstKeyFrameIndex+' out of '+length+' video samples due to a missing keyframe');var startPTS=this.getVideoStartPts(videoTrack.samples);videoTrack.samples=videoTrack.samples.slice(firstKeyFrameIndex),videoTrack.dropped+=firstKe
1yFrameIndex,videoTimeOffset+=(videoTrack.samples[0].pts-startPTS)/videoTrack.inputTimeScale,firstKeyFramePTS=videoTimeOffset}else-1===firstKeyFrameIndex&&(logger.warn('[mp4-remuxer]: No keyframe found out of '+length+' video samples'),independent=!1);if(this.ISGenerated){if(enoughAudioSamples&&enoughVideoSamples){var _startPTS=this.getVideoStartPts(videoTrack.samples),tsDelta=normalizePts(audioTrack.samples[0].pts,_startPTS)-_startPTS,audiovideoTimestampDelta=tsDelta/videoTrack.inputTimeScale;audioTimeOffset+=Math.max(0,audiovideoTimestampDelta),videoTimeOffset+=Math.max(0,-audiovideoTimestampDelta)}if(!enoughAudioSamples)enoughVideoSamples&&(video=this.remuxVideo(videoTrack,videoTimeOffset,isVideoContiguous,0));else if(audioTrack.samplerate||(logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected'),initSegment=this.generateIS(audioTrack,videoTrack,timeOffset,accurateTimeOffset)),audio=this.remuxAudio(audioTrack,audioTimeOffset,this.isAudioContiguous,accurateTimeOffset,hasVideo||enoughVideoSamples||playlistType===PlaylistLevelType.AUDIO?videoTimeOffset:void 0),enoughVideoSamples){var audioTrackLength=audio?audio.endPTS-audio.startPTS:0;videoTrack.inputTimeScale||(logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected'),initSegment=this.generateIS(audioTrack,videoTrack,timeOffset,accurateTimeOffset)),video=this.remuxVideo(videoTrack,videoTimeOffset,isVideoContiguous,audioTrackLength)}video&&(video.firstKeyFrame=firstKeyFrameIndex,video.independent=-1!==firstKeyFrameIndex,video.firstKeyFramePTS=firstKeyFramePTS)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(id3Track.samples.length&&(id3=flushTextTrackMetadataCueSamples(id3Track,timeOffset,this._initPTS,this._initDTS)),textTrack.samples.length&&(text=flushTextTrackUserdataCueSamples(textTrack,timeOffset,this._initPTS))),{audio:audio,video:video,initSegment:initSegment,independent:independent,text:text,id3:id3}},_proto.generateIS=function(audioTrack,videoTrack,timeOffset,accurateTimeOffset){var audioSamples=audioTrack.samples,videoSamples=videoTrack.samples,typeSupported=this.typeSupported,tracks={},_initPTS=this._initPTS,computePTSDTS=!_initPTS||accurateTimeOffset,container='audio/mp4',initPTS,initDTS,timescale;if(computePTSDTS&&(initPTS=initDTS=Infinity),audioTrack.config&&audioSamples.length){switch(audioTrack.timescale=audioTrack.samplerate,audioTrack.segmentCodec){case'mp3':typeSupported.mpeg?(container='audio/mpeg',audioTrack.codec=''):typeSupported.mp3&&(audioTrack.codec='mp3');break;case'ac3':audioTrack.codec='ac-3';}tracks.audio={id:'audio',container:container,codec:audioTrack.codec,initSegment:'mp3'===audioTrack.segmentCodec&&typeSupported.mpeg?new Uint8Array(0):MP4.initSegment([audioTrack]),metadata:{channelCount:audioTrack.channelCount}},computePTSDTS&&(timescale=audioTrack.inputTimeScale,_initPTS&×cale===_initPTS.timescale?computePTSDTS=!1:initPTS=initDTS=audioSamples[0].pts-Math.round(timescale*timeOffset))}if(videoTrack.sps&&videoTrack.pps&&videoSamples.length){if(videoTrack.timescale=videoTrack.inputTimeScale,tracks.video={id:'main',container:'video/mp4',codec:videoTrack.codec,initSegment:MP4.initSegment([videoTrack]),metadata:{width:videoTrack.width,height:videoTrack.height}},computePTSDTS)if(timescale=videoTrack.inputTimeScale,!_initPTS||timescale!==_initPTS.timescale){var startPTS=this.getVideoStartPts(videoSamples),startOffset=Math.round(timescale*timeOffset);initDTS=Math.min(initDTS,normalizePts(videoSamples[0].dts,startPTS)-startOffset),initPTS=Math.min(initPTS,startPTS-startOffset)}else computePTSDTS=!1;this.videoTrackConfig={width:videoTrack.width,height:videoTrack.height,pixelRatio:videoTrack.pixelRatio}}return Object.keys(tracks).length?(this.ISGenerated=!0,computePTSDTS?(this._initPTS={baseTime:initPTS,timescale:timescale},this._initDTS={baseTime:initDTS,timescale:timescale}):initPTS=timescale=void 0,{tracks:tracks,initPTS:initPTS,timescale:timescale}):void 0},_proto.remuxVideo=function(track,timeOffset,contiguous,audioTrackLength){var timeScale=track.inputTimeScale,inputSamples=track.samples,outputSamples=[],nbSamples=inputSamples.length,initPTS=this._initPTS,nextAvcDts=this.nextAvcDts,offset=8,mp4SampleDuration=this.videoSampleDuration,minPTS=Number.POSITIVE_INFINITY,maxPTS=Number.NEGATIVE_INFINITY,sortSamples=!1,firstDTS,lastDTS;
1if(!contiguous||null===nextAvcDts){var pts=timeOffset*timeScale,cts=inputSamples[0].pts-normalizePts(inputSamples[0].dts,inputSamples[0].pts);chromeVersion&&null!==nextAvcDts&&15e3>Math.abs(pts-cts-nextAvcDts)?contiguous=!0:nextAvcDts=pts-cts}for(var initTime=initPTS.baseTime*timeScale/initPTS.timescale,i=0,sample;i<nbSamples;i++)sample=inputSamples[i],sample.pts=normalizePts(sample.pts-initTime,nextAvcDts),sample.dts=normalizePts(sample.dts-initTime,nextAvcDts),sample.dts<inputSamples[0<i?i-1:i].dts&&(sortSamples=!0);sortSamples&&inputSamples.sort(function(a,b){var deltadts=a.dts-b.dts,deltapts=a.pts-b.pts;return deltadts||deltapts}),firstDTS=inputSamples[0].dts,lastDTS=inputSamples[inputSamples.length-1].dts;var inputDuration=lastDTS-firstDTS,averageSampleDuration=inputDuration?Math.round(inputDuration/(nbSamples-1)):mp4SampleDuration||track.inputTimeScale/30;if(contiguous){var delta=firstDTS-nextAvcDts,foundHole=delta>averageSampleDuration,foundOverlap=-1>delta;if((foundHole||foundOverlap)&&(foundHole?logger.warn('AVC: '+toMsFromMpegTsClock(delta,!0)+' ms ('+delta+'dts) hole between fragments detected at '+timeOffset.toFixed(3)):logger.warn('AVC: '+toMsFromMpegTsClock(-delta,!0)+' ms ('+delta+'dts) overlapping between fragments detected at '+timeOffset.toFixed(3)),!foundOverlap||nextAvcDts>=inputSamples[0].pts||chromeVersion)){firstDTS=nextAvcDts;var firstPTS=inputSamples[0].pts-delta;if(foundHole)inputSamples[0].dts=firstDTS,inputSamples[0].pts=firstPTS;else for(var _i=0;_i<inputSamples.length&&!(inputSamples[_i].dts>firstPTS);_i++)inputSamples[_i].dts-=delta,inputSamples[_i].pts-=delta;logger.log('Video: Initial PTS/DTS adjusted: '+toMsFromMpegTsClock(firstPTS,!0)+'/'+toMsFromMpegTsClock(firstDTS,!0)+', delta: '+toMsFromMpegTsClock(delta,!0)+' ms')}}firstDTS=Math.max(0,firstDTS);for(var nbNalu=0,naluLen=0,dtsStep=firstDTS,_i2=0;_i2<nbSamples;_i2++){for(var _sample=inputSamples[_i2],units=_sample.units,nbUnits=u
1nits.length,sampleLen=0,j=0;j<nbUnits;j++)sampleLen+=units[j].data.length;naluLen+=sampleLen,nbNalu+=nbUnits,_sample.length=sampleLen,_sample.dts<dtsStep?(_sample.dts=dtsStep,dtsStep+=0|averageSampleDuration/4||1):dtsStep=_sample.dts,minPTS=Math.min(_sample.pts,minPTS),maxPTS=Math.max(_sample.pts,maxPTS)}lastDTS=inputSamples[nbSamples-1].dts;var mdatSize=naluLen+4*nbNalu+8,mdat;try{mdat=new Uint8Array(mdatSize)}catch(err){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:err,bytes:mdatSize,reason:'fail allocating video mdat '+mdatSize})}var view=new DataView(mdat.buffer);view.setUint32(0,mdatSize),mdat.set(MP4.types.mdat,4);for(var stretchedLastFrame=!1,minDtsDelta=Number.POSITIVE_INFINITY,minPtsDelta=Number.POSITIVE_INFINITY,maxDtsDelta=Number.NEGATIVE_INFINITY,maxPtsDelta=Number.NEGATIVE_INFINITY,_i3=0;_i3<nbSamples;_i3++){for(var _VideoSample=inputSamples[_i3],VideoSampleUnits=_VideoSample.units,mp4SampleLength=0,_j=0,_nbUnits=VideoSampleUnits.length;_j<_nbUnits;_j++){var unit=VideoSampleUnits[_j],unitData=unit.data,unitDataLen=unit.data.byteLength;view.setUint32(offset,unitDataLen),offset+=4,mdat.set(unitData,offset),offset+=unitDataLen,mp4SampleLength+=4+unitDataLen}var ptsDelta=void 0;if(_i3<nbSamples-1)mp4SampleDuration=inputSamples[_i3+1].dts-_VideoSample.dts,ptsDelta=inputSamples[_i3+1].pts-_VideoSample.pts;else{var config=this.config,lastFrameDuration=0<_i3?_VideoSample.dts-inputSamples[_i3-1].dts:averageSampleDuration;if(ptsDelta=0<_i3?_VideoSample.pts-inputSamples[_i3-1].pts:averageSampleDuration,config.stretchShortVideoTrack&&null!==this.nextAudioPts){var gapTolerance=Math.floor(config.maxBufferHole*timeScale),deltaToFrameEnd=(audioTrackLength?minPTS+audioTrackLength*timeScale:this.nextAudioPts)-_VideoSample.pts;deltaToFrameEnd>gapTolerance?(mp4SampleDuration=deltaToFrameEnd-lastFrameDuration,0>mp4SampleDuration?mp4SampleDuration=lastFrameDuration:stretchedLastFrame=!0,logger.log('[mp4-remuxer]: It is approximately '+deltaToFrameEnd/90+' ms to the next segment; using duration '+mp4SampleDuration/90+' ms for the last video frame.')):mp4SampleDuration=lastFrameDuration}else mp4SampleDuration=lastFrameDuration}var compositionTimeOffset=Math.round(_VideoSample.pts-_VideoSample.dts);minDtsDelta=Math.min(minDtsDelta,mp4SampleDuration),maxDtsDelta=Math.max(maxDtsDelta,mp4SampleDuration),minPtsDelta=Math.min(minPtsDelta,ptsDelta),maxPtsDelta=Math.max(maxPtsDelta,ptsDelta),outputSamples.push(new Mp4Sample(_VideoSample.key,mp4SampleDuration,mp4SampleLength,compositionTimeOffset))}if(outputSamples.length)if(chromeVersion){if(70>chromeVersion){var flags=outputSamples[0].flags;flags.dependsOn=2,flags.isNonSync=0}}else if(safariWebkitVersion&&maxPtsDelta-minPtsDelta<maxDtsDelta-minDtsDelta&&.025>averageSampleDuration/maxDtsDelta&&0===outputSamples[0].cts){logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');for(var dts=firstDTS,_i4=0,len=outputSamples.length;_i4<len;_i4++){var nextDts=dts+outputSamples[_i4].duration,_pts=dts+outputSamples[_i4].cts;if(_i4<len-1){var nextPts=nextDts+outputSamples[_i4+1].cts;outputSamples[_i4].duration=nextPts-_pts}else outputSamples[_i4].duration=_i4?outputSamples[_i4-1].duration:averageSampleDuration;outputSamples[_i4].cts=0,dts=nextDts}}mp4SampleDuration=stretchedLastFrame||!mp4SampleDuration?averageSampleDuration:mp4SampleDuration,this.nextAvcDts=nextAvcDts=lastDTS+mp4SampleDuration,this.videoSampleDuration=mp4SampleDuration,this.isVideoContiguous=!0;var moof=MP4.moof(track.sequenceNumber++,firstDTS,_extends({},track,{samples:outputSamples})),data={data1:moof,data2:mdat,startPTS:minPTS/timeScale,endPTS:(maxPTS+mp4SampleDuration)/timeScale,startDTS:firstDTS/timeScale,endDTS:nextAvcDts/timeScale,type:'video',hasAudio:!1,hasVideo:!0,nb:outputSamples.length,dropped:track.dropped};return track.samples=[],track.dropped=0,data},_proto.getSamplesPerFrame=function(track){switch(track.segmentCodec){case'mp3':return 1152;case'ac3':return 1536;default:return AAC_SAMPLES_PER_FRAME;}},_proto.remuxAudio=function(track,timeOffset,contiguous,accurateTimeOff
1set,videoTimeOffset){var inputTimeScale=track.inputTimeScale,mp4timeScale=track.samplerate?track.samplerate:inputTimeScale,scaleFactor=inputTimeScale/mp4timeScale,mp4SampleDuration=this.getSamplesPerFrame(track),inputSampleDuration=mp4SampleDuration*scaleFactor,initPTS=this._initPTS,rawMPEG='mp3'===track.segmentCodec&&this.typeSupported.mpeg,outputSamples=[],alignedWithVideo=void 0!==videoTimeOffset,inputSamples=track.samples,offset=rawMPEG?0:8,nextAudioPts=this.nextAudioPts||-1,timeOffsetMpegTS=timeOffset*inputTimeScale,initTime=initPTS.baseTime*inputTimeScale/initPTS.timescale;if(this.isAudioContiguous=contiguous=contiguous||inputSamples.length&&0<nextAudioPts&&(accurateTimeOffset&&9e3>Math.abs(timeOffsetMpegTS-nextAudioPts)||Math.abs(normalizePts(inputSamples[0].pts-initTime,timeOffsetMpegTS)-nextAudioPts)<20*inputSampleDuration),inputSamples.forEach(function(sample){sample.pts=normalizePts(sample.pts-initTime,timeOffsetMpegTS)}),!contiguous||0>nextAudioPts){if(inputSamples=inputSamples.filter(function(sample){return 0<=sample.pts}),!inputSamples.length)return;nextAudioPts=0===videoTimeOffset?0:accurateTimeOffset&&!alignedWithVideo?Math.max(0,timeOffsetMpegTS):inputSamples[0].pts}if('aac'===track.segmentCodec)for(var maxAudioFramesDrift=this.config.maxAudioFramesDrift,i=0,nextPts=nextAudioPts;i<inputSamples.length;i++){var sample=inputSamples[i],pts=sample.pts,delta=pts-nextPts,duration=Math.abs(1e3*delta/inputTimeScale);if(delta<=-maxAudioFramesDrift*inputSampleDuration&&alignedWithVideo)0===i&&(logger.warn('Audio frame @ '+(pts/inputTimeScale).toFixed(3)+'s overlaps nextAudioPts by '+Math.round(1e3*delta/inputTimeScale)+' ms.'),this.nextAudioPts=nextAudioPts=nextPts=pts);else if(delta>=maxAudioFramesDrift*inputSampleDuration&&duration<10000&&alignedWithVideo){var missing=Math.round(delta/inputSampleDuration);nextPts=pts-missing*inputSampleDuration,0>nextPts&&(missing--,nextPts+=inputSampleDuration),0===i&&(this.nextAudioPts=nextAudioPts=nextPts),logger.warn('[mp4-remuxer]: Injecting '+missing+' audio frame @ '+(nextPts/inputTimeScale).toFixed(3)+'s due to '+Math.round(1e3*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);fillFrame||(logger.log('[mp4-remuxer]: 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}),nextPts+=inputSampleDuration,i++}}sample.pts=nextPts,nextPts+=inputSampleDuration}for(var firstPTS=null,lastPTS=null,mdatSize=0,sampleLength=inputSamples.length,mdat;sampleLength--;)mdatSize+=inputSamples[sampleLength].unit.byteLength;for(var _j2=0,_nbSamples=inputSamples.length;_j2<_nbSamples;_j2++){var audioSample=inputSamples[_j2],unit=audioSample.unit,_pts2=audioSample.pts;if(null!==lastPTS){var prevSample=outputSamples[_j2-1];prevSample.duration=Math.round((_pts2-lastPTS)/scaleFactor)}else if(contiguous&&'aac'===track.segmentCodec&&(_pts2=nextAudioPts),firstPTS=_pts2,0<mdatSize){mdatSize+=offset;try{mdat=new Uint8Array(mdatSize)}catch(err){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:err,bytes:mdatSize,reason:'fail allocating audio mdat '+mdatSize})}if(!rawMPEG){var view=new DataView(mdat.buffer);view.setUint32(0,mdatSize),mdat.set(MP4.types.mdat,4)}}else return;mdat.set(unit,offset);var unitLen=unit.byteLength;offset+=unitLen,outputSamples.push(new Mp4Sample(!0,mp4SampleDuration,unitLen,0)),lastPTS=_pts2}var nbSamples=outputSamples.length;if(nbSamples){var lastSample=outputSamples[outputSamples.length-1];this.nextAudioPts=nextAudioPts=lastPTS+scaleFactor*lastSample.duration;var moof=rawMPEG?new Uint8Array(0):MP4.moof(track.sequenceNumber++,firstPTS/scaleFactor,_extends({},track,{samples:outputSamples}));track.samples=[];var start=firstPTS/inputTimeScale,end=nextAudioPts/inputTimeScale,audioData={data1:moof,data2:mdat,startPTS:start,endPTS:end,startDTS:start,endDTS:end,type:'audio',hasAudio:!0,hasVideo:!1,nb:nbSamples};return this.isAudioContiguous=!0,audioData}},_proto.remuxEmptyAudio=function(track,timeOffset,contiguous,videoData){var inputTimeScale=track.inputTimeScale,mp4timeScale=track.samplerate?track.samplerate:inputTimeScale,nextAudioPts=this.nextAudioPts,initDTS=this._initDTS,init90kHz=9e4*initDTS.baseTime/initDTS.timescale,startDTS=(null===nextAudioPts?videoData.startDTS*inputTimeScale:nextAudioPts)+init90kHz,endDTS=videoData.endDTS*inputTimeScale+init90kHz,frameDuration=inputTimeScale/mp4timeScale*AAC_SAMPLES_PER_FRAME,nbSamples=Math.ceil((endDT
1S-startDTS)/frameDuration),silentFrame=AAC.getSilentFrame(track.manifestCodec||track.codec,track.channelCount);if(logger.warn('[mp4-remuxer]: remux empty Audio'),!silentFrame)return void logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');for(var samples=[],i=0,stamp;i<nbSamples;i++)stamp=startDTS+i*frameDuration,samples.push({unit:silentFrame,pts:stamp,dts:stamp});return track.samples=samples,this.remuxAudio(track,timeOffset,contiguous,!1)},MP4Remuxer}(),Mp4Sample=function(isKeyframe,duration,size,cts){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=duration,this.size=size,this.cts=cts,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:isKeyframe?2:1,isNonSync:isKeyframe?0:1}},PassThroughRemuxer=function(){function PassThroughRemuxer(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}var _proto=PassThroughRemuxer.prototype;return _proto.destroy=function(){},_proto.resetTimeStamp=function(defaultInitPTS){this.initPTS=defaultInitPTS,this.lastEndTime=null},_proto.resetNextTimestamp=function(){this.lastEndTime=null},_proto.resetInitSegment=function(initSegment,audioCodec,videoCodec,decryptdata){this.audioCodec=audioCodec,this.videoCodec=videoCodec,this.generateInitSegment(patchEncyptionData(initSegment,decryptdata)),this.emitInitSegment=!0},_proto.generateInitSegment=function(initSegment){var audioCodec=this.audioCodec,videoCodec=this.videoCodec;if(!(null!=initSegment&&initSegment.byteLength))return this.initTracks=void 0,void(this.initData=void 0);var initData=this.initData=parseInitSegment(initSegment);initData.audio&&(audioCodec=getParsedTrackCodec(initData.audio,ElementaryStreamTypes.AUDIO)),initData.video&&(videoCodec=getParsedTrackCodec(initData.video,ElementaryStreamTypes.VIDEO));var tracks={};initData.audio&&initData.video?tracks.audiovideo={container:'video/mp4',codec:audioCodec+','+videoCodec,initSegment:initSegment,id:'main'}:initData.audio?tracks.audio={container:'audio/mp4',codec:audioCodec,initSegment:initSegment,id:'audio'}:initData.video?tracks.video={container:'video/mp4',codec:videoCodec,initSegment:initSegment,id:'main'}:logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.'),this.initTracks=tracks},_proto.remux=function(audioTrack,videoTrack,id3Track,textTrack,timeOffset,accurateTimeOffset){var initPTS=this.initPTS,lastEndTime=this.lastEndTime,result={audio:void 0,video:void 0,text:textTrack,id3:id3Track,initSegment:void 0},_initData,_initData2;isFiniteNumber(lastEndTime)||(lastEndTime=this.lastEndTime=timeOffset||0);var data=videoTrack.samples;if(!(null!=data&&data.length))return result;var initSegment={initPTS:void 0,timescale:1},initData=this.initData;if(null!=(_initData=initData)&&_initData.length||(this.generateInitSegment(data),initData=this.initData),!(null!=(_initData2=initData)&&_initData2.length))return logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.'),result;this.emitInitSegment&&(initSegment.tracks=this.initTracks,this.emitInitSegment=!1);var duration=getDuration(data,initData),startDTS=getStartDTS(initData,data),decodeTime=null===startDTS?timeOffset:startDTS;(isInvalidInitPts(initPTS,decodeTime,timeOffset,duration)||initSegment.timescale!==initPTS.timescale&&accurateTimeOffset)&&(initSegment.initPTS=decodeTime-timeOffset,initPTS&&1===initPTS.timescale&&logger.warn('Adjusting initPTS by '+(initSegment.initPTS-initPTS.baseTime)),this.initPTS=initPTS={baseTime:initSegment.initPTS,timescale:1});var startTime=audioTrack?decodeTime-initPTS.baseTime/initPTS.timescale:lastEndTime,endTime=startTime+duration;offsetStartDTS(initData,data,initPTS.baseTime/initPTS.timescale),0<duration?this.lastEndTime=endTime:(logger.warn('Duration parsed from mp4 should be greater than zero'),this.resetNextTimestamp());var hasAudio=!!initData.audio,hasVideo=!!initData.video,type='';hasAudio&&(type+='audio'),hasVideo&&(type+='video');var track={data1:data,startPTS:startTime,startDTS:startTime,endPTS:endTime,endDTS:endTime,type:type,hasAudio:hasAudio,hasVideo:hasVideo,nb:1,dropped:0};return result.audio='audio'===track.type?track:void 0,result.video='audio'===track.type?void 0:track,result.initSegment=initSegment,result.id3=flushTextTrackMetadataCueSamples(id3Track,timeOffset,initPTS,initPTS),textTrack.samples.length&&(result.text=flushTextTrackUserdataCueSamples(textTrack,timeOffset,initPTS)),result},PassThroughRemuxer}(),now;try{now=self.performance.now.bind(self.performance)}catch(err){logger.debug('Unable to use Performance API on this environment'),now=null==optionalSelf?void 0:optionalSelf.Date.now}var muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:TSDemuxer,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:MP3Demuxer,remux:MP4Remuxer}];muxConfig.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});
1var Transmuxer=function(){function Transmuxer(observer,typeSupported,config,vendor,id){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=observer,this.typeSupported=typeSupported,this.config=config,this.vendor=vendor,this.id=id}var _proto=Transmuxer.prototype;return _proto.configure=function(transmuxConfig){this.transmuxConfig=transmuxConfig,this.decrypter&&this.decrypter.reset()},_proto.push=function(data,decryptdata,chunkMeta,state){var _this=this,stats=chunkMeta.transmuxing;stats.executeStart=now();var uintData=new Uint8Array(data),currentTransmuxState=this.currentTransmuxState,transmuxConfig=this.transmuxConfig;state&&(this.currentTransmuxState=state);var _ref=state||currentTransmuxState,contiguous=_ref.contiguous,discontinuity=_ref.discontinuity,trackSwitch=_ref.trackSwitch,accurateTimeOffset=_ref.accurateTimeOffset,timeOffset=_ref.timeOffset,initSegmentChange=_ref.initSegmentChange,audioCodec=transmuxConfig.audioCodec,videoCodec=transmuxConfig.videoCodec,defaultInitPts=transmuxConfig.defaultInitPts,duration=transmuxConfig.duration,initSegmentData=transmuxConfig.initSegmentData,keyData=getEncryptionType(uintData,decryptdata);if(keyData&&'AES-128'===keyData.method){var decrypter=this.getDecrypter();if(decrypter.isSync()){var decryptedData=decrypter.softwareDecrypt(uintData,keyData.key.buffer,keyData.iv.buffer),loadingParts=-1<chunkMeta.part;if(loadingParts&&(decryptedData=decrypter.flush()),!decryptedData)return stats.executeEnd=now(),emptyResult(chunkMeta);uintData=new Uint8Array(decryptedData)}else return this.decryptionPromise=decrypter.webCryptoDecrypt(uintData,keyData.key.buffer,keyData.iv.buffer).then(function(decryptedData){var result=_this.push(decryptedData,null,chunkMeta);return _this.decryptionPromise=null,result}),this.decryptionPromise}var resetMuxers=this.needsProbing(discontinuity,trackSwitch);if(resetMuxers){var error=this.configureTransmuxer(uintData);if(error)return logger.warn('[transmuxer] '+error.message),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:error,reason:error.message}),stats.executeEnd=now(),emptyResult(chunkMeta)}(discontinuity||trackSwitch||initSegmentChange||resetMuxers)&&this.resetInitSegment(initSegmentData,audioCodec,videoCodec,duration,decryptdata),(discontinuity||initSegmentChange||resetMuxers)&&this.resetInitialTimestamp(defaultInitPts),contiguous||this.resetContiguity();var result=this.transmux(uintData,keyData,timeOffset,accurateTimeOffset,chunkMeta),currentState=this.currentTransmuxState;return currentState.contiguous=!0,currentState.discontinuity=!1,currentState.trackSwitch=!1,stats.executeEnd=now(),result},_proto.flush=function(chunkMeta){var _this2=this,stats=chunkMeta.transmuxing;stats.executeStart=now();var decrypter=this.decrypter,currentTransmuxState=this.currentTransmuxState,decryptionPromise=this.decryptionPromise;if(decryptionPromise)return decryptionPromise.then(function(){return _this2.flush(chunkMeta)});var transmuxResults=[],timeOffset=currentTransmuxState.timeOffset;if(decrypter){var decryptedData=decrypter.flush();decryptedData&&transmuxResults.push(this.push(decryptedData,null,chunkMeta))}var demuxer=this.demuxer,remuxer=this.remuxer;if(!demuxer||!remuxer)return stats.executeEnd=now(),[emptyResult(chunkMeta)];var demuxResultOrPromise=demuxer.flush(timeOffset);return isPromise(demuxResultOrPromise)?demuxResultOrPromise.then(function(demuxResult){return _this2.flushRemux(transmuxResults,demuxResult,chunkMeta),transmuxResults}):(this.flushRemux(transmuxResults,demuxResultOrPromise,chunkMeta),transmuxResults)},_proto.flushRemux=function(transmuxResults,demuxResult,chunkMeta){var audioTrack=demuxResult.audioTrack,videoTrack=demuxResult.videoTrack,id3Track=demuxResult.id3Track,textTrack=demuxResult.textTrack,_this$currentTransmux=this.currentTransmuxState,accurateTimeOff
1set=_this$currentTransmux.accurateTimeOffset,timeOffset=_this$currentTransmux.timeOffset;logger.log('[transmuxer.ts]: Flushed fragment '+chunkMeta.sn+(-1<chunkMeta.part?' p: '+chunkMeta.part:'')+' of level '+chunkMeta.level);var remuxResult=this.remuxer.remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset,accurateTimeOffset,!0,this.id);transmuxResults.push({remuxResult:remuxResult,chunkMeta:chunkMeta}),chunkMeta.transmuxing.executeEnd=now()},_proto.resetInitialTimestamp=function(defaultInitPts){var demuxer=this.demuxer,remuxer=this.remuxer;demuxer&&remuxer&&(demuxer.resetTimeStamp(defaultInitPts),remuxer.resetTimeStamp(defaultInitPts))},_proto.resetContiguity=function(){var demuxer=this.demuxer,remuxer=this.remuxer;demuxer&&remuxer&&(demuxer.resetContiguity(),remuxer.resetNextTimestamp())},_proto.resetInitSegment=function(initSegmentData,audioCodec,videoCodec,trackDuration,decryptdata){var demuxer=this.demuxer,remuxer=this.remuxer;demuxer&&remuxer&&(demuxer.resetInitSegment(initSegmentData,audioCodec,videoCodec,trackDuration),remuxer.resetInitSegment(initSegmentData,audioCodec,videoCodec,decryptdata))},_proto.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},_proto.transmux=function(data,keyData,timeOffset,accurateTimeOffset,chunkMeta){var result;return result=keyData&&'SAMPLE-AES'===keyData.method?this.transmuxSampleAes(data,keyData,timeOffset,accurateTimeOffset,chunkMeta):this.transmuxUnencrypted(data,timeOffset,accurateTimeOffset,chunkMeta),result},_proto.transmuxUnencrypted=function(data,timeOffset,accurateTimeOffset,chunkMeta){var _demux=this.demuxer.demux(data,timeOffset,!1,!this.config.progressive),audioTrack=_demux.audioTrack,videoTrack=_demux.videoTrack,id3Track=_demux.id3Track,textTrack=_demux.textTrack,remuxResult=this.remuxer.remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset,accurateTimeOffset,!1,this.id);return{remuxResult:remuxResult,chunkMeta:chunkMeta}},_proto.transmuxSampleAes=function(data,decryptData,timeOffset,accurateTimeOffset,chunkMeta){var _this3=this;return this.demuxer.demuxSampleAes(data,decryptData,timeOffset).then(function(demuxResult){var remuxResult=_this3.remuxer.remux(demuxResult.audioTrack,demuxResult.videoTrack,demuxResult.id3Track,demuxResult.textTrack,timeOffset,accurateTimeOffset,!1,_this3.id);return{remuxResult:remuxResult,chunkMeta:chunkMeta}})},_proto.configureTransmuxer=function(data){for(var config=this.config,observer=this.observer,typeSupported=this.typeSupported,vendor=this.vendor,i=0,len=muxConfig.length,mux;i<len;i++){var _muxConfig$i$demux;if(null!=(_muxConfig$i$demux=muxConfig[i].demux)&&_muxConfig$i$demux.probe(data)){mux=muxConfig[i];break}}if(!mux)return new Error('Failed to find demuxer by probing fragment data');var demuxer=this.demuxer,remuxer=this.remuxer,Remuxer=mux.remux,Demuxer=mux.demux;remuxer&&remuxer instanceof Remuxer||(this.remuxer=new Remuxer(observer,config,typeSupported,vendor)),demuxer&&demuxer instanceof Demuxer||(this.demuxer=new Demuxer(observer,config,typeSupported),this.probe=Demuxer.probe)},_proto.needsProbing=function(discontinuity,trackSwitch){return!this.demuxer||!this.remuxer||discontinuity||trackSwitch},_proto.getDecrypter=function(){var decrypter=this.decrypter;return decrypter||(decrypter=this.decrypter=new Decrypter(this.config)),decrypter},Transmuxer}(),emptyResult=function(chunkMeta){return{remuxResult:{},chunkMeta:chunkMeta}},TransmuxConfig=function(audioCodec,videoCodec,initSegmentData,duration,defaultInitPts){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=audioCodec,this.videoCodec=videoCodec,this.initSegmentData=initSegmentData,this.duration=duration,this.defaultInitPts=defaultInitPts||null},TransmuxState=function(discontinuity,contiguous,accurateTimeOffset,trackSwitch,timeOffset,initSegmentChange){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=discontinuity,this.contiguous=contiguous,this.accurateTimeOff
1set=accurateTimeOffset,this.trackSwitch=trackSwitch,this.timeOffset=timeOffset,this.initSegmentChange=initSegmentChange},eventemitter3={exports:{}};(function(module){function Events(){}function EE(fn,context,once){this.fn=fn,this.context=context,this.once=once||!1}function addListener(emitter,event,fn,context,once){if('function'!=typeof fn)throw new TypeError('The listener must be a function');var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;return emitter._events[evt]?emitter._events[evt].fn?emitter._events[evt]=[emitter._events[evt],listener]:emitter._events[evt].push(listener):(emitter._events[evt]=listener,emitter._eventsCount++),emitter}function clearEvent(emitter,evt){0==--emitter._eventsCount?emitter._events=new Events:delete emitter._events[evt]}function EventEmitter(){this._events=new Events,this._eventsCount=0}var has=Object.prototype.hasOwnProperty,prefix='~';Object.create&&(Events.prototype=Object.create(null),!new Events().__proto__&&(prefix=!1)),EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(0===this._eventsCount)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names},EventEmitter.prototype.listeners=function(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=Array(l);i<l;i++)ee[i]=handlers[i].fn;return ee},EventEmitter.prototype.listenerCount=function(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];return listeners?listeners.fn?1:listeners.length:0},EventEmitter.prototype.emit=function(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a1),!0;case 3:return listeners.fn.call(listeners.context,a1,a2),!0;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),!0;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),!0;}for(i=1,args=Array(len-1);i<len;i++)args[i-1]=arguments[i];listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++)switch(listeners[i].once&&this.removeListener(event,listeners[i].fn,void 0,!0),len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=Array(len-1);j<len;j++)args[j-1]=arguments[j];listeners[i].fn.apply(listeners[i].context,args);}}return!0},EventEmitter.prototype.on=function(event,fn,context){return addListener(this,event,fn,context,!1)},EventEmitter.prototype.once=function(event,fn,context){return addListener(this,event,fn,context,!0)},EventEmitter.prototype.removeListener=function(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn)return clearEvent(this,evt),this;var listeners=this._events[evt];if(listeners.fn)listeners.fn!==fn||once&&!listeners.once||context&&listeners.context!==context||clearEvent(this,evt);else{for(var i=0,events=[],length=listeners.length;i<length;i++)(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context)&&events.push(listeners[i]);events.length?this._events[evt]=1===events.length?events[0]:events:clearEvent(this,evt)}return this},EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&clearEvent(this,evt)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=prefix,EventEmitter.EventEmitter=EventEmitter,module.exports=EventEmitter})(eventemitter3);var eventemitter3Exports=eventemitter3.exports,EventEmitter=function(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x}(eventemitter3Exports);'undefined'!=typeof __IN_WORKER__&&__IN_WORKER__&&function(self){var observer=new EventEmitter,forwardMessage=function(ev,data){self.postMessage({event:ev,data:data})};observer.on(Events.FRAG_DECRYPTED,forwardMessage),observer.on(Events.ERROR,forwardMessage);var forwardWorkerLogs=function(){var _loop=function(logFn){logger[logFn]=function(message){forwardMessage('workerLog',{logType:logFn,message:message})}};for(var logFn in logger)_loop(logFn)};self.addEventListener('message',function(ev){var data=ev.data;switch(data.cmd){case'init':{var config=JSON.parse(data.config);
1self.transmuxer=new Transmuxer(observer,data.typeSupported,config,'',data.id),enableLogs(config.debug,data.id),forwardWorkerLogs(),forwardMessage('init',null);break}case'configure':{self.transmuxer.configure(data.config);break}case'demux':{var transmuxResult=self.transmuxer.push(data.data,data.decryptdata,data.chunkMeta,data.state);isPromise(transmuxResult)?(self.transmuxer.async=!0,transmuxResult.then(function(data){emitTransmuxComplete(self,data)}).catch(function(error){forwardMessage(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:data.chunkMeta,fatal:!1,error:error,err:error,reason:'transmuxer-worker push error'})})):(self.transmuxer.async=!1,emitTransmuxComplete(self,transmuxResult));break}case'flush':{var id=data.chunkMeta,_transmuxResult=self.transmuxer.flush(id),asyncFlush=isPromise(_transmuxResult);asyncFlush||self.transmuxer.async?(!isPromise(_transmuxResult)&&(_transmuxResult=Promise.resolve(_transmuxResult)),_transmuxResult.then(function(results){handleFlushResult(self,results,id)}).catch(function(error){forwardMessage(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:data.chunkMeta,fatal:!1,error:error,err:error,reason:'transmuxer-worker flush error'})})):handleFlushResult(self,_transmuxResult,id);break}}})}(self);var TransmuxerInterface=function(){function TransmuxerInterface(hls,id,onTransmuxComplete,onFlush){var _this=this;this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;var config=hls.config;this.hls=hls,this.id=id,this.useWorker=!!config.enableWorker,this.onTransmuxComplete=onTransmuxComplete,this.onFlush=onFlush;var forwardMessage=function(ev,data){data=data||{},data.frag=_this.frag,data.id=_this.id,ev===Events.ERROR&&(_this.error=data.error),_this.hls.trigger(ev,data)};this.observer=new EventEmitter,this.observer.on(Events.FRAG_DECRYPTED,forwardMessage),this.observer.on(Events.ERROR,forwardMessage);var MediaSource=getMediaSource(config.preferManagedMediaSource)||{isTypeSupported:function(){return!1}},m2tsTypeSupported={mpeg:MediaSource.isTypeSupported('audio/mpeg'),mp3:MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&'undefined'!=typeof Worker){var canCreateWorker=config.workerPath||hasUMDWorker();if(canCreateWorker){try{config.workerPath?(logger.log('loading Web Worker '+config.workerPath+' for "'+id+'"'),this.workerContext=loadWorker(config.workerPath)):(logger.log('injecting Web Worker for "'+id+'"'),this.workerContext=injectWorker()),this.onwmsg=function(event){return _this.onWorkerMessage(event)};var worker=this.workerContext.worker;worker.addEventListener('message',this.onwmsg),worker.onerror=function(event){var error=new Error(event.message+' ('+event.filename+':'+event.lineno+')');config.enableWorker=!1,logger.warn('Error in "'+id+'" Web Worker, fallback to inline'),_this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:'demuxerWorker',error:error})},worker.postMessage({cmd:'init',typeSupported:m2tsTypeSupported,vendor:'',id:id,config:JSON.stringify(config)})}catch(err){logger.warn('Error setting up "'+id+'" Web Worker, fallback to inline',err),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,m2tsTypeSupported,config,'',id)}return}}this.transmuxer=new Transmuxer(this.observer,m2tsTypeSupported,config,'',id)}var _proto=TransmuxerInterface.prototype;return _proto.resetWorker=function(){if(this.workerContext){var _this$workerContext=this.workerContext,worker=_this$workerContext.worker,objectURL=_this$workerContext.objectURL;objectURL&&self.URL.revokeObjectURL(objectURL),worker.removeEventListener('message',this.onwmsg),worker.onerror=null,worker.terminate(),this.workerContext=null}},_proto.destroy=function(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{var transmuxer=this.transmuxer;transmuxer&&(transmuxer.destroy(),this.transmuxer=null)}var observer=this.observer;observer&&observer.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null},_proto.push=function(data,initSegmentData,audioCodec,videoCodec,frag,part,duration,accurateTimeOff
1set,chunkMeta,defaultInitPTS){var _this2=this,_frag$initSegment,_lastFrag$initSegment;chunkMeta.transmuxing.start=self.performance.now();var transmuxer=this.transmuxer,timeOffset=part?part.start:frag.start,decryptdata=frag.decryptdata,lastFrag=this.frag,discontinuity=!(lastFrag&&frag.cc===lastFrag.cc),trackSwitch=!(lastFrag&&chunkMeta.level===lastFrag.level),snDiff=lastFrag?chunkMeta.sn-lastFrag.sn:-1,partDiff=this.part?chunkMeta.part-this.part.index:-1,progressive=0===snDiff&&1<chunkMeta.id&&chunkMeta.id===(null==lastFrag?void 0:lastFrag.stats.chunkCount),contiguous=!trackSwitch&&(1===snDiff||0===snDiff&&(1===partDiff||progressive&&0>=partDiff)),now=self.performance.now();(trackSwitch||snDiff||0===frag.stats.parsing.start)&&(frag.stats.parsing.start=now),part&&(partDiff||!contiguous)&&(part.stats.parsing.start=now);var initSegmentChange=!(lastFrag&&(null==(_frag$initSegment=frag.initSegment)?void 0:_frag$initSegment.url)===(null==(_lastFrag$initSegment=lastFrag.initSegment)?void 0:_lastFrag$initSegment.url)),state=new TransmuxState(discontinuity,contiguous,accurateTimeOffset,trackSwitch,timeOffset,initSegmentChange);if(!contiguous||discontinuity||initSegmentChange){logger.log('[transmuxer-interface, '+frag.type+']: Starting new transmux session for sn: '+chunkMeta.sn+' p: '+chunkMeta.part+' level: '+chunkMeta.level+' id: '+chunkMeta.id+'\n discontinuity: '+discontinuity+'\n trackSwitch: '+trackSwitch+'\n contiguous: '+contiguous+'\n accurateTimeOffset: '+accurateTimeOffset+'\n timeOffset: '+timeOffset+'\n initSegmentChange: '+initSegmentChange);var config=new TransmuxConfig(audioCodec,videoCodec,initSegmentData,duration,defaultInitPTS);this.configureTransmuxer(config)}if(this.frag=frag,this.part=part,this.workerContext)this.workerContext.worker.postMessage({cmd:'demux',data:data,decryptdata:decryptdata,chunkMeta:chunkMeta,state:state},data instanceof ArrayBuffer?[data]:[]);else if(transmuxer){var _transmuxResult=transmuxer.push(data,decryptdata,chunkMeta,state);isPromise(_transmuxResult)?(transmuxer.async=!0,_transmuxResult.then(function(data){_this2.handleTransmuxComplete(data)}).catch(function(error){_this2.transmuxerError(error,chunkMeta,'transmuxer-interface push error')})):(transmuxer.async=!1,this.handleTransmuxComplete(_transmuxResult))}},_proto.flush=function(chunkMeta){var _this3=this;chunkMeta.transmuxing.start=self.performance.now();var transmuxer=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:'flush',chunkMeta:chunkMeta});else if(transmuxer){var _transmuxResult2=transmuxer.flush(chunkMeta),asyncFlush=isPromise(_transmuxResult2);asyncFlush||transmuxer.async?(!isPromise(_transmuxResult2)&&(_transmuxResult2=Promise.resolve(_transmuxResult2)),_transmuxResult2.then(function(data){_this3.handleFlushResult(data,chunkMeta)}).catch(function(error){_this3.transmuxerError(error,chunkMeta,'transmuxer-interface flush error')})):this.handleFlushResult(_transmuxResult2,chunkMeta)}},_proto.transmuxerError=function(error,chunkMeta,reason){this.hls&&(this.error=error,this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:chunkMeta,frag:this.frag||void 0,fatal:!1,error:error,err:error,reason:reason}))},_proto.handleFlushResult=function(results,chunkMeta){var _this4=this;results.forEach(function(result){_this4.handleTransmuxComplete(result)}),this.onFlush(chunkMeta)},_proto.onWorkerMessage=function(event){var data=event.data;if(!(null!=data&&data.event))return void logger.warn('worker message received with no '+(data?'event name':'data'));var hls=this.hls;if(this.hls)switch(data.event){case'init':{var objectURL=null==(_this$workerContext2=this.workerContext)?void 0:_this$workerContext2.objectURL,_this$workerContext2;objectURL&&self.URL.revokeObjectURL(objectURL);break}case'transmuxComplete':{this.handleTransmuxComplete(data.data);break}case'flush':{this.onFlush(data.data);break}case'workerLog':logger[data.data.logType]&&logger[data.data.logType](data.data.message);break;default:{data.data=data.data||{},data.data.frag=this.frag,data.data.id=this.id,hls.trigger(data.event,data.data);break}}},_proto.configureTransmuxer=function(config){var transmuxer=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:'configure',config:config}):transmuxer&&transmuxer.configure(config)}
1,_proto.handleTransmuxComplete=function(result){result.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(result)},TransmuxerInterface}(),TICK_INTERVAL$2=100,AudioStreamController=function(_BaseStreamController){function AudioStreamController(hls,fragmentTracker,keyLoader){var _this;return _this=_BaseStreamController.call(this,hls,fragmentTracker,keyLoader,'[audio-stream-controller]',PlaylistLevelType.AUDIO)||this,_this.videoBuffer=null,_this.videoTrackCC=-1,_this.waitingVideoCC=-1,_this.bufferedTrack=null,_this.switchingTrack=null,_this.trackId=-1,_this.waitingData=null,_this.mainDetails=null,_this.flushing=!1,_this.bufferFlushed=!1,_this.cachedTrackLoadedData=null,_this._registerListeners(),_this}_inheritsLoose(AudioStreamController,_BaseStreamController);var _proto=AudioStreamController.prototype;return _proto.onHandlerDestroying=function(){this._unregisterListeners(),_BaseStreamController.prototype.onHandlerDestroying.call(this),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null},_proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.on(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),hls.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),hls.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),hls.on(Events.ERROR,this.onError,this),hls.on(Events.BUFFER_RESET,this.onBufferReset,this),hls.on(Events.BUFFER_CREATED,this.onBufferCreated,this),hls.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),hls.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.off(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),hls.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),hls.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),hls.off(Events.ERROR,this.onError,this),hls.off(Events.BUFFER_RESET,this.onBufferReset,this),hls.off(Events.BUFFER_CREATED,this.onBufferCreated,this),hls.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),hls.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto.onInitPtsFound=function(event,_ref){var frag=_ref.frag,id=_ref.id,initPTS=_ref.initPTS,timescale=_ref.timescale;if('main'===id){var cc=frag.cc;this.initPTS[frag.cc]={baseTime:initPTS,timescale:timescale},this.log('InitPTS for cc: '+cc+' found from main: '+initPTS),this.videoTrackCC=cc,this.state===State.WAITING_INIT_PTS&&this.tick()}},_proto.startLoad=function(startPosition){if(!this.levels)return this.startPosition=startPosition,void(this.state=State.STOPPED);var lastCurrentTime=this.lastCurrentTime;this.stopLoad(),this.setInterval(TICK_INTERVAL$2),0<lastCurrentTime&&-1===startPosition?(this.log('Override startPosition with lastCurrentTime @'+lastCurrentTime.toFixed(3)),startPosition=lastCurrentTime,this.state=State.IDLE):(this.loadedmetadata=!1,this.state=State.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=startPosition,this.tick()},_proto.doTick=function(){switch(this.state){case State.IDLE:this.doTickIdle();break;case State.WAITING_TRACK:{var levels=this.levels,trackId=this.trackId,details=null==levels||null==(_levels$trackId=levels[trackId])?void 0:_levels$trackId.details,_levels$trackId;if(details){if(this.waitForCdnTuneIn(details))break;this.state=State.WAITING_INIT_PTS}break}case State.FRAG_LOADING_WAITING_RETRY:{var now=performance.now(),retryDate=this.retryDate,_this$media;if(!retryDate||now>=retryDate||null!=(_this$media=this.media)&&_this$media.seeking){var _levels=this.levels,_trackId=this.trackId;this.log('RetryDate reached, switch back to IDLE state'),this.resetStartWhenNotLoaded((null==_levels?void 0:_levels[_trackId])||null),this.state=State.IDLE}break}case State.WAITING_INIT_PTS:{var waitingData=this.waitingData;if(waitingData){var frag=waitingData.frag,part=waitingData.part,cache=waitingData.cache,complete=waitingData.complete;if(void 0!==this.initPTS[frag.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=State.FRAG_LOADING;var payload=cache.flush(),data={frag:frag,part:part,payload:payload,networkDetails:null};this._handleFragmentLoadProgress(data),complete&&_BaseStreamController.prototype._handleFragmentLoadComplete.call(this,data)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log('Waiting fragment cc ('+frag.cc+') cancelled because video is at cc '+this.videoTrackCC),this.clearWaitingFragment();else{var pos=this.getLoadPosition(),bufferInfo=BufferHelper.bufferInfo(this.mediaBuffer,pos,this.config.maxBufferHole),waitingFragmentAtPosition=fragmentWithinToleranceTest(bufferInfo.end,this.config.maxFragLookUpTolerance,frag);0>waitingFragmentAtPosition&&(this.log('Waiting fragment cc ('+frag.cc+') @ '+frag.start+' cancelled because another fragment at '+bufferInfo.end+' is needed'),this.clearWaitingFragment())}}else this.state=State.IDLE}}this.onTickEnd()},_proto.clearWaitingFragment=function(){var waitingData=this.waitingData;waitingData&&(this.fragmentTracker.removeFragment(waitingData.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=State.IDLE)},_proto.resetLoadingState=function(){this.clearWaitingFragment(),_BaseStreamController.prototype.resetLoadingState.call(this)},_proto.onTickEnd=function(){var media=this.media;null!=media&&media.readyState&&(this.lastCurrentTime=media.currentTime)}
1,_proto.doTickIdle=function(){var hls=this.hls,levels=this.levels,media=this.media,trackId=this.trackId,config=hls.config;if((media||!this.startFragRequested&&config.startFragPrefetch)&&null!=levels&&levels[trackId]){var levelInfo=levels[trackId],trackDetails=levelInfo.details;if(!trackDetails||trackDetails.live&&this.levelLastLoaded!==levelInfo||this.waitForCdnTuneIn(trackDetails))return void(this.state=State.WAITING_TRACK);var bufferable=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&bufferable&&(this.bufferFlushed=!1,this.afterBufferFlushed(bufferable,ElementaryStreamTypes.AUDIO,PlaylistLevelType.AUDIO));var bufferInfo=this.getFwdBufferInfo(bufferable,PlaylistLevelType.AUDIO);if(null!==bufferInfo){var bufferedTrack=this.bufferedTrack,switchingTrack=this.switchingTrack;if(!switchingTrack&&this._streamEnded(bufferInfo,trackDetails))return hls.trigger(Events.BUFFER_EOS,{type:'audio'}),void(this.state=State.ENDED);var mainBufferInfo=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,PlaylistLevelType.MAIN),bufferLen=bufferInfo.len,maxBufLen=this.getMaxBufferLength(null==mainBufferInfo?void 0:mainBufferInfo.len),fragments=trackDetails.fragments,start=fragments[0].start,targetBufferTime=this.flushing?this.getLoadPosition():bufferInfo.end;if(switchingTrack&&media){var pos=this.getLoadPosition();bufferedTrack&&!mediaAttributesIdentical(switchingTrack.attrs,bufferedTrack.attrs)&&(targetBufferTime=pos),trackDetails.PTSKnown&&pos<start&&(bufferInfo.end>start||bufferInfo.nextStart)&&(this.log('Alt audio track ahead of main track, seek to start of alt audio track'),media.currentTime=start+.05)}if(!(bufferLen>=maxBufLen&&!switchingTrack&&targetBufferTime<fragments[fragments.length-1].start)){var frag=this.getNextFragment(targetBufferTime,trackDetails),atGap=!1;if(frag&&this.isLoopLoading(frag,targetBufferTime)&&(atGap=!!frag.gap,frag=this.getNextFragmentLoopLoading(frag,trackDetails,bufferInfo,PlaylistLevelType.MAIN,maxBufLen)),!frag)return void(this.bufferFlushed=!0);var atBufferSyncLimit=mainBufferInfo&&frag.start>mainBufferInfo.end+trackDetails.targetduration;if(atBufferSyncLimit||!(null!=mainBufferInfo&&mainBufferInfo.len)&&bufferInfo.len){var mainFrag=this.getAppendedFrag(frag.start,PlaylistLevelType.MAIN);if(null===mainFrag)return;if(atGap||(atGap=!!mainFrag.gap||!!atBufferSyncLimit&&0===mainBufferInfo.len),atBufferSyncLimit&&!atGap||atGap&&bufferInfo.nextStart&&bufferInfo.nextStart<mainFrag.end)return}this.loadFragment(frag,levelInfo,targetBufferTime)}}}},_proto.getMaxBufferLength=function(mainBufferLength){var maxConfigBuffer=_BaseStreamController.prototype.getMaxBufferLength.call(this);return mainBufferLength?Math.min(Math.max(maxConfigBuffer,mainBufferLength),this.config.maxMaxBufferLength):maxConfigBuffer},_proto.onMediaDetaching=function(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,_BaseStreamController.prototype.onMediaDetaching.call(this)},_proto.onAudioTracksUpdated=function(event,_ref2){var audioTracks=_ref2.audioTracks;this.resetTransmuxer(),this.levels=audioTracks.map(function(mediaPlaylist){return new Level(mediaPlaylist)})},_proto.onAudioTrackSwitching=function(event,data){var altAudio=!!data.url;this.trackId=data.id;var fragCurrent=this.fragCurrent;fragCurrent&&(fragCurrent.abortRequests(),this.removeUnbufferedFrags(fragCurrent.start)),this.resetLoadingState(),altAudio?this.setInterval(TICK_INTERVAL$2):this.resetTransmuxer(),altAudio?(this.switchingTrack=data,this.state=State.IDLE,this.flushAudioIfNeeded(data)):(this.switchingTrack=null,this.bufferedTrack=data,this.state=State.STOPPED),this.tick()},_proto.onManifestLoading=function(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1},_proto.onLevelLoaded=function(event,data){this.mainDetails=data.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(Events.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)},_proto.onAudioTrackLoaded=function(event,data){var _track$details;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=data);var levels=this.levels,newDetails=data.details,trackId=data.id;if(!levels)return void this.warn('Audio tracks were reset while loading level '+trackId);this.log('Audio track '+trackId+' loaded ['+newDetails.startSN+','+newDetails.endSN+']'+(newDetails.lastPartSn?'[part-'+newDetails.lastPartSn+'-'+newDetails.lastPartIndex+']':'')+',duration:'+newDetails.totalduration);var track=levels[trackId],sliding=0;if(newDetails.live||null!=(_track$details=track.details)&&_track$details.live){this.checkLiveUpdate(newDetails);var mainDetails=this.mainDetails;if(newDetails.deltaUpdateFailed||!mainDetails)return;if(!track.details&&newDetails.hasProgramDateTime&&mainDetails.hasProgramDateTime)alignMediaPlaylistByPDT(newDetails,mainDetails),sliding=newDetails.fragments[0].start;else{var _this$levelLastLoaded;sliding=this.alignPlaylists(newDetails,track.details,null==(_this$levelLastLoaded=this.levelLastLoaded)?void 0:_this$levelLastLoaded.details)}}track.details=newDetails,this.levelLastLoaded=track,this.startFragRequested||!this.mainDetails&&newDetails.live||this.setStartPosition(this.mainDetails||newDetails,sliding),this.state!==State.WAITING_TRACK||this.waitForCdnTuneIn(newDetails)||(this.state=State.IDLE),this.tick()},_proto._handleFragmentLoadProgress=function(data){var frag=data.frag,part=data.part,payload=data.payload,config=this.config,trackId=this.trackId,levels=this.levels,_frag$initSegment;if(!levels)return void this.warn('Audio tracks were reset while fragment load was in progress. Fragment '+frag.sn+' of level '+frag.level
1+' will not be buffered');var track=levels[trackId];if(!track)return void this.warn('Audio track is undefined on fragment load progress');var details=track.details;if(!details)return this.warn('Audio track details undefined on fragment load progress'),void this.removeUnbufferedFrags(frag.start);var audioCodec=config.defaultAudioCodec||track.audioCodec||'mp4a.40.2',transmuxer=this.transmuxer;transmuxer||(transmuxer=this.transmuxer=new TransmuxerInterface(this.hls,PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var initPTS=this.initPTS[frag.cc],initSegmentData=null==(_frag$initSegment=frag.initSegment)?void 0:_frag$initSegment.data;if(void 0!==initPTS){var partIndex=part?part.index:-1,chunkMeta=new ChunkMetadata(frag.level,frag.sn,frag.stats.chunkCount,payload.byteLength,partIndex,-1!==partIndex);transmuxer.push(payload,initSegmentData,audioCodec,'',frag,part,details.totalduration,!1,chunkMeta,initPTS)}else{this.log('Unknown video PTS for cc '+frag.cc+', waiting for video PTS before demuxing audio frag '+frag.sn+' of ['+details.startSN+' ,'+details.endSN+'],track '+trackId);var _this$waitingData=this.waitingData=this.waitingData||{frag:frag,part:part,cache:new ChunkCache,complete:!1},cache=_this$waitingData.cache;cache.push(new Uint8Array(payload)),this.waitingVideoCC=this.videoTrackCC,this.state=State.WAITING_INIT_PTS}},_proto._handleFragmentLoadComplete=function(fragLoadedData){return this.waitingData?void(this.waitingData.complete=!0):void _BaseStreamController.prototype._handleFragmentLoadComplete.call(this,fragLoadedData)},_proto.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},_proto.onBufferCreated=function(event,data){var audioTrack=data.tracks.audio;audioTrack&&(this.mediaBuffer=audioTrack.buffer||null),data.tracks.video&&(this.videoBuffer=data.tracks.video.buffer||null)},_proto.onFragBuffered=function(event,data){var frag=data.frag,part=data.part;if(frag.type!==PlaylistLevelType.AUDIO){if(!this.loadedmetadata&&frag.type===PlaylistLevelType.MAIN){var bufferable=this.videoBuffer||this.media;if(bufferable){var bufferedTimeRanges=BufferHelper.getBuffered(bufferable);bufferedTimeRanges.length&&(this.loadedmetadata=!0)}}return}if(this.fragContextChanged(frag))return void this.warn('Fragment '+frag.sn+(part?' p: '+part.index:'')+' of level '+frag.level+' finished buffering, but was aborted. state: '+this.state+', audioSwitch: '+(this.switchingTrack?this.switchingTrack.name:'false'));if('initSegment'!==frag.sn){this.fragPrevious=frag;var track=this.switchingTrack;track&&(this.bufferedTrack=track,this.switchingTrack=null,this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},track)))}this.fragBufferedComplete(frag,part)},_proto.onError=function(event,data){var _data$context;if(data.fatal)return void(this.state=State.ERROR);switch(data.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO,data);break;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:data.levelRetry||this.state!==State.WAITING_TRACK||(null==(_data$context=data.context)?void 0:_data$context.type)!==PlaylistContextType.AUDIO_TRACK||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:if(!data.parent||'audio'!==data.parent)return;if(data.details===ErrorDetails.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(data)&&(this.bufferedTrack=null,_BaseStreamController.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,'audio'));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(data);}},_proto.onBufferFlushing=function(event,_ref3){var type=_ref3.type;type!==ElementaryStreamTypes.VIDEO&&(this.flushing=!0)},_proto.onBufferFlushed=function(event,_ref4){var type=_ref4.type;if(type!==ElementaryStreamTypes.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===State.ENDED&&(this.state=State.IDLE);var mediaBuffer=this.mediaBuffer||this.media;mediaBuffer&&(this.afterBufferFlushed(mediaBuffer,type,PlaylistLevelType.AUDIO),this.tick())}},_proto._handleTransmuxComplete=function(transmuxResult){var id='audio',hls=this.hls,remuxResult=transmuxResult.remuxResult,chunkMeta=transmuxResult.chunkMeta,context=this.getCurrentContext(c
vendor: 4,346 bytes, line 1
1hunkMeta),_id3$samples;if(!context)return void this.resetWhenMissingContext(chunkMeta);var frag=context.frag,part=context.part,level=context.level,details=level.details,audio=remuxResult.audio,text=remuxResult.text,id3=remuxResult.id3,initSegment=remuxResult.initSegment;if(this.fragContextChanged(frag)||!details)return void this.fragmentTracker.removeFragment(frag);if(this.state=State.PARSING,this.switchingTrack&&audio&&this.completeAudioSwitch(this.switchingTrack),null!=initSegment&&initSegment.tracks){var mapFragment=frag.initSegment||frag;this._bufferInitSegment(level,initSegment.tracks,mapFragment,chunkMeta),hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:mapFragment,id:id,tracks:initSegment.tracks})}if(audio){var startPTS=audio.startPTS,endPTS=audio.endPTS,startDTS=audio.startDTS,endDTS=audio.endDTS;part&&(part.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:startPTS,endPTS:endPTS,startDTS:startDTS,endDTS:endDTS}),frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,startPTS,endPTS,startDTS,endDTS),this.bufferFragmentData(audio,frag,part,chunkMeta)}if(null!=id3&&null!=(_id3$samples=id3.samples)&&_id3$samples.length){var emittedID3=_extends({id:id,frag:frag,details:details},id3);hls.trigger(Events.FRAG_PARSING_METADATA,emittedID3)}if(text){var emittedText=_extends({id:id,frag:frag,details:details},text);hls.trigger(Events.FRAG_PARSING_USERDATA,emittedText)}},_proto._bufferInitSegment=function(currentLevel,tracks,frag,chunkMeta){if(this.state===State.PARSING){tracks.video&&delete tracks.video;var track=tracks.audio;if(track){track.id='audio';var variantAudioCodecs=currentLevel.audioCodec;this.log('Init audio buffer, container:'+track.container+', codecs[level/parsed]=['+variantAudioCodecs+'/'+track.codec+']'),variantAudioCodecs&&1===variantAudioCodecs.split(',').length&&(track.levelCodec=variantAudioCodecs),this.hls.trigger(Events.BUFFER_CODECS,tracks);var initSegment=track.initSegment;if(null!=initSegment&&initSegment.byteLength){var segment={type:'audio',frag:frag,part:null,chunkMeta:chunkMeta,parent:frag.type,data:initSegment};this.hls.trigger(Events.BUFFER_APPENDING,segment)}this.tickImmediate()}}},_proto.loadFragment=function(frag,track,targetBufferTime){var fragState=this.fragmentTracker.getState(frag);if(this.fragCurrent=frag,this.switchingTrack||fragState===FragmentState.NOT_LOADED||fragState===FragmentState.PARTIAL){var _track$details2;if('initSegment'===frag.sn)this._loadInitSegment(frag,track);else if(null!=(_track$details2=track.details)&&_track$details2.live&&!this.initPTS[frag.cc]){this.log('Waiting for video PTS in continuity counter '+frag.cc+' of live stream before loading audio fragment '+frag.sn+' of level '+this.trackId),this.state=State.WAITING_INIT_PTS;var mainDetails=this.mainDetails;mainDetails&&mainDetails.fragments[0].start!==track.details.fragments[0].start&&alignMediaPlaylistByPDT(track.details,mainDetails)}else this.startFragRequested=!0,_BaseStreamController.prototype.loadFragment.call(this,frag,track,targetBufferTime)}else this.clearTrackerIfNeeded(frag)},_proto.flushAudioIfNeeded=function(switchingTrack){var media=this.media,bufferedTrack=this.bufferedTrack,bufferedAttributes=null==bufferedTrack?void 0:bufferedTrack.attrs,switchAttributes=switchingTrack.attrs;media&&bufferedAttributes&&(bufferedAttributes.CHANNELS!==switchAttributes.CHANNELS||bufferedTrack.name!==switchingTrack.name||bufferedTrack.lang!==switchingTrack.lang)&&(this.log('Switching audio track : flushing all audio'),_BaseStreamController.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,'audio'),this.bufferedTrack=null)},_proto.completeAudioSwitch=function(switchingTrack){var hls=this.hls;this.flushAudioIfNeeded(switchingTrack),this.bufferedTrack=switchingTrack,this.switchingTrack=null,hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},switchingTrack))},AudioStreamController}(BaseStreamController),AudioTrackController=function(_BasePlaylistControll){function AudioTrackController(hls){var _this;return _this=_BasePlaylistControll.call(this,hls,'[audio-track-controller]')||this,_this.tracks=[],_this.groupIds=null,_this.tracksInGroup=[],_this.trackId=-1,_this.currentTrack=null,_this.selectDefaultTrack=!0,_this.registerListeners(),_this}_inheritsLoose(AudioTrackController,_BasePlaylistControll);var _proto=AudioTrackController.prototype;
1return _proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.on(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),hls.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),hls.on(Events.ERROR,this.onError,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.off(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),hls.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),hls.off(Events.ERROR,this.onError,this)},_proto.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,_BasePlaylistControll.prototype.destroy.call(this)},_proto.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},_proto.onManifestParsed=function(event,data){this.tracks=data.audioTracks||[]},_proto.onAudioTrackLoaded=function(event,data){var id=data.id,groupId=data.groupId,details=data.details,trackInActiveGroup=this.tracksInGroup[id];if(!trackInActiveGroup||trackInActiveGroup.groupId!==groupId)return void this.warn('Audio track with id:'+id+' and group:'+groupId+' not found in active group '+(null==trackInActiveGroup?void 0:trackInActiveGroup.groupId));var curDetails=trackInActiveGroup.details;trackInActiveGroup.details=data.details,this.log('Audio track '+id+' "'+trackInActiveGroup.name+'" lang:'+trackInActiveGroup.lang+' group:'+groupId+' loaded ['+details.startSN+'-'+details.endSN+']'),id===this.trackId&&this.playlistLoaded(id,data,curDetails)},_proto.onLevelLoading=function(event,data){this.switchLevel(data.level)},_proto.onLevelSwitching=function(event,data){this.switchLevel(data.level)},_proto.switchLevel=function(levelIndex){var levelInfo=this.hls.levels[levelIndex];if(levelInfo){var audioGroups=levelInfo.audioGroups||null,currentGroups=this.groupIds,currentTrack=this.currentTrack;if(!audioGroups||(null==currentGroups?void 0:currentGroups.length)!==(null==audioGroups?void 0:audioGroups.length)||null!=audioGroups&&audioGroups.some(function(groupId){return-1===(null==currentGroups?void 0:currentGroups.indexOf(groupId))})){this.groupIds=audioGroups,this.trackId=-1,this.currentTrack=null;var audioTracks=this.tracks.filter(function(track){return!audioGroups||-1!==audioGroups.indexOf(track.groupId)});if(audioTracks.length)this.selectDefaultTrack&&!audioTracks.some(function(track){return track.default})&&(this.selectDefaultTrack=!1),audioTracks.forEach(function(track,i){track.id=i});else if(!currentTrack&&!this.tracksInGroup.length)return;this.tracksInGroup=audioTracks;var audioPreference=this.hls.config.audioPreference;if(!currentTrack&&audioPreference){var groupIndex=findMatchingOption(audioPreference,audioTracks,audioMatchPredicate);if(-1<groupIndex)currentTrack=audioTracks[groupIndex];else{var allIndex=findMatchingOption(audioPreference,this.tracks);currentTrack=this.tracks[allIndex]}}var trackId=this.findTrackId(currentTrack);-1===trackId&¤tTrack&&(trackId=this.findTrackId(null));this.log('Updating audio tracks, '+audioTracks.length+' track(s) found in group(s): '+(null==audioGroups?void 0:audioGroups.join(','))),this.hls.trigger(Events.AUDIO_TRACKS_UPDATED,{audioTracks:audioTracks});var selectedTrackId=this.trackId;if(-1!==trackId&&-1===selectedTrackId)this.setAudioTrack(trackId);else if(audioTracks.length&&-1===selectedTrackId){var error=new Error('No audio track selected for current audio group-ID(s): '+(null==(_this$groupIds=this.groupIds)?void 0:_this$groupIds.join(','))+' track count: '+audioTracks.length),_this$groupIds;this.warn(error.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:error})}}else this.shouldReloadPlaylist(currentTrack)&&this.setAudioTrack(this.trackId)}},_proto.onError=function(event,data){!data.fatal&&data.context&&(data.context.type!==PlaylistContextType.AUDIO_TRACK||data.context.
1id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(data.context.groupId)||(this.requestScheduled=-1,this.checkRetry(data)))},_proto.setAudioOption=function(audioOption){var hls=this.hls;if(hls.config.audioPreference=audioOption,audioOption){var allAudioTracks=this.allAudioTracks;if(this.selectDefaultTrack=!1,allAudioTracks.length){var currentTrack=this.currentTrack;if(currentTrack&&matchesOption(audioOption,currentTrack,audioMatchPredicate))return currentTrack;var groupIndex=findMatchingOption(audioOption,this.tracksInGroup,audioMatchPredicate);if(-1<groupIndex){var track=this.tracksInGroup[groupIndex];return this.setAudioTrack(groupIndex),track}if(currentTrack){var searchIndex=hls.loadLevel;-1===searchIndex&&(searchIndex=hls.firstAutoLevel);var switchIndex=findClosestLevelWithAudioGroup(audioOption,hls.levels,allAudioTracks,searchIndex,audioMatchPredicate);if(-1===switchIndex)return null;hls.nextLoadLevel=switchIndex}if(audioOption.channels||audioOption.audioCodec){var withoutCodecAndChannelsMatch=findMatchingOption(audioOption,allAudioTracks);if(-1<withoutCodecAndChannelsMatch)return allAudioTracks[withoutCodecAndChannelsMatch]}}}return null},_proto.setAudioTrack=function(newId){var tracks=this.tracksInGroup;if(0>newId||newId>=tracks.length)return void this.warn('Invalid audio track id: '+newId);this.clearTimer(),this.selectDefaultTrack=!1;var lastTrack=this.currentTrack,track=tracks[newId],trackLoaded=track.details&&!track.details.live;if(!(newId===this.trackId&&track===lastTrack&&trackLoaded)&&(this.log('Switching to audio-track '+newId+' "'+track.name+'" lang:'+track.lang+' group:'+track.groupId+' channels:'+track.channels),this.trackId=newId,this.currentTrack=track,this.hls.trigger(Events.AUDIO_TRACK_SWITCHING,_objectSpread2({},track)),!trackLoaded)){var hlsUrlParameters=this.switchParams(track.url,null==lastTrack?void 0:lastTrack.details,track.details);this.loadPlaylist(hlsUrlParameters)}},_proto.findTrackId=function(currentTrack){for(var audioTracks=this.tracksInGroup,i=0,track;i<audioTracks.length;i++)if((track=audioTracks[i],!this.selectDefaultTrack||track.default)&&(!currentTrack||matchesOption(currentTrack,track,audioMatchPredicate)))return i;if(currentTrack){for(var name=currentTrack.name,lang=currentTrack.lang,assocLang=currentTrack.assocLang,characteristics=currentTrack.characteristics,audioCodec=currentTrack.audioCodec,channels=currentTrack.channels,_i=0,_track;_i<audioTracks.length;_i++)if(_track=audioTracks[_i],matchesOption({name:name,lang:lang,assocLang:assocLang,characteristics:characteristics,audioCodec:audioCodec,channels:channels},_track,audioMatchPredicate))return _i;for(var _i2=0,_track2;_i2<audioTracks.length;_i2++)if(_track2=audioTracks[_i2],mediaAttributesIdentical(currentTrack.attrs,_track2.attrs,['LANGUAGE','ASSOC-LANGUAGE','CHARACTERISTICS']))return _i2;for(var _i3=0,_track3;_i3<audioTracks.length;_i3++)if(_track3=audioTracks[_i3],mediaAttributesIdentical(currentTrack.attrs,_track3.attrs,['LANGUAGE']))return _i3}return-1},_proto.loadPlaylist=function(hlsUrlParameters){var audioTrack=this.currentTrack;if(this.shouldLoadPlaylist(audioTrack)&&audioTrack){_BasePlaylistControll.prototype.loadPlaylist.call(this);var id=audioTrack.id,groupId=audioTrack.groupId,url=audioTrack.url;if(hlsUrlParameters)try{url=hlsUrlParameters.addDirectives(url)}catch(error){this.warn('Could not construct new URL with HLS Delivery Directives: '+error)}this.log('loading audio-track playlist '+id+' "'+audioTrack.name+'" lang:'+audioTrack.lang+' group:'+groupId),this.clearTimer(),this.hls.trigger(Events.AUDIO_TRACK_LOADING,{url:url,id:id,groupId:groupId,deliveryDirectives:hlsUrlParameters||null})}},_createClass(AudioTrackController,[{key:'allAudioTracks',get:function(){return this.tracks}},{key:'audioTracks',get:function(){return this.tracksInGroup}},{key:'audioTrack',get:function(){return this.trackId},set:function(newId){this.selectDefaultTrack=!1,this.setAudioTrack(newId)}}]),AudioTrackController}(BasePlaylistController),TICK_INTERVAL$1=500,SubtitleStreamController=function(_BaseStreamController){function Subt
1itleStreamController(hls,fragmentTracker,keyLoader){var _this;return _this=_BaseStreamController.call(this,hls,fragmentTracker,keyLoader,'[subtitle-stream-controller]',PlaylistLevelType.SUBTITLE)||this,_this.currentTrackId=-1,_this.tracksBuffered=[],_this.mainDetails=null,_this._registerListeners(),_this}_inheritsLoose(SubtitleStreamController,_BaseStreamController);var _proto=SubtitleStreamController.prototype;return _proto.onHandlerDestroying=function(){this._unregisterListeners(),_BaseStreamController.prototype.onHandlerDestroying.call(this),this.mainDetails=null},_proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.on(Events.ERROR,this.onError,this),hls.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),hls.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),hls.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),hls.on(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),hls.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.off(Events.ERROR,this.onError,this),hls.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),hls.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),hls.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),hls.off(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),hls.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto.startLoad=function(startPosition){this.stopLoad(),this.state=State.IDLE,this.setInterval(TICK_INTERVAL$1),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=startPosition,this.tick()},_proto.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()},_proto.onMediaDetaching=function(){this.tracksBuffered=[],_BaseStreamController.prototype.onMediaDetaching.call(this)},_proto.onLevelLoaded=function(event,data){this.mainDetails=data.details},_proto.onSubtitleFragProcessed=function(event,data){var frag=data.frag,success=data.success;if(this.fragPrevious=frag,this.state=State.IDLE,!!success){var buffered=this.tracksBuffered[this.currentTrackId];if(buffered){for(var fragStart=frag.start,i=0,timeRange;i<buffered.length;i++)if(fragStart>=buffered[i].start&&fragStart<=buffered[i].end){timeRange=buffered[i];break}var fragEnd=frag.start+frag.duration;timeRange?timeRange.end=fragEnd:(timeRange={start:fragStart,end:fragEnd},buffered.push(timeRange)),this.fragmentTracker.fragBuffered(frag),this.fragBufferedComplete(frag,null)}}},_proto.onBufferFlushing=function(event,data){var startOffset=data.startOffset,endOffset=data.endOffset;if(0===startOffset&&endOffset!==Number.POSITIVE_INFINITY){var endOffsetSubtitles=endOffset-1;if(0>=endOffsetSubtitles)return;data.endOffsetSubtitles=Math.max(0,endOffsetSubtitles),this.tracksBuffered.forEach(function(buffered){for(var i=0;i<buffered.length;){if(buffered[i].end<=endOffsetSubtitles){buffered.shift();continue}else if(buffered[i].start<endOffsetSubtitles)buffered[i].start=endOffsetSubtitles;else break;i++}}),this.fragmentTracker.removeFragmentsInRange(startOffset,endOffsetSubtitles,PlaylistLevelType.SUBTITLE)}},_proto.onFragBuffered=function(event,data){if(!this.loadedmetadata&&data.frag.type===PlaylistLevelType.MAIN){var _this$media;null!=(_this$media=this.media)&&_this$media.buffered.length&&(this.loadedmetadata=!0)}},_proto.onError=function(event,data){var frag=data.frag;(null==frag?void 0:frag.type)===PlaylistLevelType.SUBTITLE&&(data.details===ErrorDetails.FRAG_GAP&&this.fragmentTracker.fragBuffered(frag,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==State.STOPPED&&(this.state=State.IDLE))}
1,_proto.onSubtitleTracksUpdated=function(event,_ref){var _this2=this,subtitleTracks=_ref.subtitleTracks;return this.levels&&subtitleOptionsIdentical(this.levels,subtitleTracks)?void(this.levels=subtitleTracks.map(function(mediaPlaylist){return new Level(mediaPlaylist)})):void(this.tracksBuffered=[],this.levels=subtitleTracks.map(function(mediaPlaylist){var level=new Level(mediaPlaylist);return _this2.tracksBuffered[level.id]=[],level}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)},_proto.onSubtitleTrackSwitch=function(event,data){var _this$levels;if(this.currentTrackId=data.id,!(null!=(_this$levels=this.levels)&&_this$levels.length)||-1===this.currentTrackId)return void this.clearInterval();var currentTrack=this.levels[this.currentTrackId];this.mediaBuffer=null!=currentTrack&¤tTrack.details?this.mediaBufferTimeRanges:null,currentTrack&&this.setInterval(TICK_INTERVAL$1)},_proto.onSubtitleTrackLoaded=function(event,data){var currentTrackId=this.currentTrackId,levels=this.levels,newDetails=data.details,trackId=data.id,_track$details;if(!levels)return void this.warn('Subtitle tracks were reset while loading level '+trackId);var track=levels[trackId];if(!(trackId>=levels.length)&&track){this.log('Subtitle track '+trackId+' loaded ['+newDetails.startSN+','+newDetails.endSN+']'+(newDetails.lastPartSn?'[part-'+newDetails.lastPartSn+'-'+newDetails.lastPartIndex+']':'')+',duration:'+newDetails.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var sliding=0;if(newDetails.live||null!=(_track$details=track.details)&&_track$details.live){var mainDetails=this.mainDetails;if(newDetails.deltaUpdateFailed||!mainDetails)return;var mainSlidingStartFragment=mainDetails.fragments[0];if(!track.details)newDetails.hasProgramDateTime&&mainDetails.hasProgramDateTime?(alignMediaPlaylistByPDT(newDetails,mainDetails),sliding=newDetails.fragments[0].start):mainSlidingStartFragment&&(sliding=mainSlidingStartFragment.start,addSliding(newDetails,sliding));else{var _this$levelLastLoaded;sliding=this.alignPlaylists(newDetails,track.details,null==(_this$levelLastLoaded=this.levelLastLoaded)?void 0:_this$levelLastLoaded.details),0===sliding&&mainSlidingStartFragment&&(sliding=mainSlidingStartFragment.start,addSliding(newDetails,sliding))}}if((track.details=newDetails,this.levelLastLoaded=track,trackId===currentTrackId)&&(this.startFragRequested||!this.mainDetails&&newDetails.live||this.setStartPosition(this.mainDetails||newDetails,sliding),this.tick(),newDetails.live&&!this.fragCurrent&&this.media&&this.state===State.IDLE)){var foundFrag=findFragmentByPTS(null,newDetails.fragments,this.media.currentTime,0);foundFrag||(this.warn('Subtitle playlist not aligned with playback'),track.details=void 0)}}},_proto._handleFragmentLoadComplete=function(fragLoadedData){var _this3=this,frag=fragLoadedData.frag,payload=fragLoadedData.payload,decryptData=frag.decryptdata,hls=this.hls;if(!this.fragContextChanged(frag)&&payload&&0<payload.byteLength&&null!=decryptData&&decryptData.key&&decryptData.iv&&'AES-128'===decryptData.method){var startTime=performance.now();this.decrypter.decrypt(new Uint8Array(payload),decryptData.key.buffer,decryptData.iv.buffer).catch(function(err){throw hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:err,reason:err.message,frag:frag}),err}).then(function(decryptedData){var endTime=performance.now();hls.trigger(Events.FRAG_DECRYPTED,{frag:frag,payload:decryptedData,stats:{tstart:startTime,tdecrypt:endTime}})}).catch(function(err){_this3.warn(err.name+': '+err.message),_this3.state=State.IDLE})}},_proto.doTick=function(){if(!this.media)return void(this.state=State.IDLE);if(this.state===State.IDLE){var currentTrackId=this.currentTrackId,levels=this.levels,track=null==levels?void 0:levels[currentTrackId];if(!track||!levels.length||!track.details)return;var config=this.config,currentTime=this.getLoadPosition(),bufferedInfo=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],currentTime,config.maxBufferHole),targetBufferTime=bufferedInfo.end,bufferLen=bufferedInfo.len,mainBufferInfo=this.getFwdBufferInfo(this.media,PlaylistLevelType.MAIN),trackDetail
1s=track.details,maxBufLen=this.getMaxBufferLength(null==mainBufferInfo?void 0:mainBufferInfo.len)+trackDetails.levelTargetDuration;if(bufferLen>maxBufLen)return;var fragments=trackDetails.fragments,fragLen=fragments.length,end=trackDetails.edge,foundFrag=null,fragPrevious=this.fragPrevious;if(targetBufferTime<end){var tolerance=config.maxFragLookUpTolerance,lookupTolerance=targetBufferTime>end-tolerance?0:tolerance;foundFrag=findFragmentByPTS(fragPrevious,fragments,Math.max(fragments[0].start,targetBufferTime),lookupTolerance),!foundFrag&&fragPrevious&&fragPrevious.start<fragments[0].start&&(foundFrag=fragments[0])}else foundFrag=fragments[fragLen-1];if(!foundFrag)return;if(foundFrag=this.mapToInitFragWhenRequired(foundFrag),'initSegment'!==foundFrag.sn){var curSNIdx=foundFrag.sn-trackDetails.startSN,prevFrag=fragments[curSNIdx-1];prevFrag&&prevFrag.cc===foundFrag.cc&&this.fragmentTracker.getState(prevFrag)===FragmentState.NOT_LOADED&&(foundFrag=prevFrag)}this.fragmentTracker.getState(foundFrag)===FragmentState.NOT_LOADED&&this.loadFragment(foundFrag,track,targetBufferTime)}},_proto.getMaxBufferLength=function(mainBufferLength){var maxConfigBuffer=_BaseStreamController.prototype.getMaxBufferLength.call(this);return mainBufferLength?Math.max(maxConfigBuffer,mainBufferLength):maxConfigBuffer},_proto.loadFragment=function(frag,level,targetBufferTime){this.fragCurrent=frag,'initSegment'===frag.sn?this._loadInitSegment(frag,level):(this.startFragRequested=!0,_BaseStreamController.prototype.loadFragment.call(this,frag,level,targetBufferTime))},_createClass(SubtitleStreamController,[{key:'mediaBufferTimeRanges',get:function(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}]),SubtitleStreamController}(BaseStreamController),BufferableInstance=function(timeranges){this.buffered=void 0;var getRange=function(name,index,length){if(index>>>=0,index>length-1)throw new DOMException('Failed to execute \''+name+'\' on \'TimeRanges\': The index provided ('+index+') is greater than the maximum bound ('+length+')');return timeranges[index][name]};this.buffered={get length(){return timeranges.length},end:function(index){return getRange('end',index,timeranges.length)},start:function(index){return getRange('start',index,timeranges.length)}}},SubtitleTrackController=function(_BasePlaylistControll){function SubtitleTrackController(hls){var _this;return _this=_BasePlaylistControll.call(this,hls,'[subtitle-track-controller]')||this,_this.media=null,_this.tracks=[],_this.groupIds=null,_this.tracksInGroup=[],_this.trackId=-1,_this.currentTrack=null,_this.selectDefaultTrack=!0,_this.queuedDefaultTrack=-1,_this.asyncPollTrackChange=function(){return _this.pollTrackChange(0)},_this.useTextTrackPolling=!1,_this.subtitlePollingInterval=-1,_this._subtitleDisplay=!0,_this.onTextTracksChanged=function(){if(_this.useTextTrackPolling||self.clearInterval(_this.subtitlePollingInterval),_this.media&&_this.hls.config.renderTextTracksNatively){for(var textTrack=null,tracks=filterSubtitleTracks(_this.media.textTracks),i=0;i<tracks.length;i++)if('hidden'===tracks[i].mode)textTrack=tracks[i];else if('showing'===tracks[i].mode){textTrack=tracks[i];break}var trackId=_this.findTrackForTextTrack(textTrack);_this.subtitleTrack!==trackId&&_this.setSubtitleTrack(trackId)}},_this.registerListeners(),_this}_inheritsLoose(SubtitleTrackController,_BasePlaylistControll);var _proto=SubtitleTrackController.prototype;return _proto.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,_BasePlaylistControll.prototype.destroy.call(this)},_proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.on(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),hls.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),hls.on(Events.ERROR,this.onError,this)}
1,_proto.unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.off(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),hls.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),hls.off(Events.ERROR,this.onError,this)},_proto.onMediaAttached=function(event,data){this.media=data.media,this.media&&(-1<this.queuedDefaultTrack&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&'onchange'in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener('change',this.asyncPollTrackChange))},_proto.pollTrackChange=function(timeout){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,timeout)},_proto.onMediaDetaching=function(){if(this.media){self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener('change',this.asyncPollTrackChange),-1<this.trackId&&(this.queuedDefaultTrack=this.trackId);var textTracks=filterSubtitleTracks(this.media.textTracks);textTracks.forEach(function(track){clearCurrentCues(track)}),this.subtitleTrack=-1,this.media=null}},_proto.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},_proto.onManifestParsed=function(event,data){this.tracks=data.subtitleTracks},_proto.onSubtitleTrackLoaded=function(event,data){var id=data.id,groupId=data.groupId,details=data.details,trackInActiveGroup=this.tracksInGroup[id];if(!trackInActiveGroup||trackInActiveGroup.groupId!==groupId)return void this.warn('Subtitle track with id:'+id+' and group:'+groupId+' not found in active group '+(null==trackInActiveGroup?void 0:trackInActiveGroup.groupId));var curDetails=trackInActiveGroup.details;trackInActiveGroup.details=data.details,this.log('Subtitle track '+id+' "'+trackInActiveGroup.name+'" lang:'+trackInActiveGroup.lang+' group:'+groupId+' loaded ['+details.startSN+'-'+details.endSN+']'),id===this.trackId&&this.playlistLoaded(id,data,curDetails)},_proto.onLevelLoading=function(event,data){this.switchLevel(data.level)},_proto.onLevelSwitching=function(event,data){this.switchLevel(data.level)},_proto.switchLevel=function(levelIndex){var levelInfo=this.hls.levels[levelIndex];if(levelInfo){var subtitleGroups=levelInfo.subtitleGroups||null,currentGroups=this.groupIds,currentTrack=this.currentTrack;if(!subtitleGroups||(null==currentGroups?void 0:currentGroups.length)!==(null==subtitleGroups?void 0:subtitleGroups.length)||null!=subtitleGroups&&subtitleGroups.some(function(groupId){return-1===(null==currentGroups?void 0:currentGroups.indexOf(groupId))})){this.groupIds=subtitleGroups,this.trackId=-1,this.currentTrack=null;var subtitleTracks=this.tracks.filter(function(track){return!subtitleGroups||-1!==subtitleGroups.indexOf(track.groupId)});if(subtitleTracks.length)this.selectDefaultTrack&&!subtitleTracks.some(function(track){return track.default})&&(this.selectDefaultTrack=!1),subtitleTracks.forEach(function(track,i){track.id=i});else if(!currentTrack&&!this.tracksInGroup.length)return;this.tracksInGroup=subtitleTracks;var subtitlePreference=this.hls.config.subtitlePreference;if(!currentTrack&&subtitlePreference){this.selectDefaultTrack=!1;var groupIndex=findMatchingOption(subtitlePreference,subtitleTracks);if(-1<groupIndex)currentTrack=subtitleTracks[groupIndex];else{var allIndex=findMatchingOption(subtitlePreference,this.tracks);currentTrack=this.tracks[allIndex]}}var trackId=this.findTrackId(currentTrack);-1===trackId&¤tTrack&&(trackId=this.findTrackId(null));this.log('Updating subtitle tracks, '+subtitleTracks.length+' track(s) found in "'+(null==subtitleGroups?void 0:subtitleGroups.join(','))+'" group-id'),this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:subtitleTracks}),-1!==trackId&&-1===this.trackId&&this.setSubtitleTrack(trackId)}else this.shouldReloadPlaylist(currentTrack)&&this.setSubtitleTrack(this.trackId)}},_proto.findTrackId=function(currentTrack){for(var tracks=this.tracksInGroup,selectDefault=this.selectDefaultTrack,i=0,track;i<tracks.length;i++)if((track=tracks[i],(!selectDefault||track.default)&&(selectDefault||currentTrack))&&(!currentTrack||matchesOption(track,currentTrack)))return i;if(currentTrack){for(var _i=0,_track;_i<tracks.length;_i++)if(_track=tracks[_i],mediaAttributesIdentical(currentTrack.attrs,_track.attrs,['LANGUAGE','ASSOC-LANGUAGE','CHARACTERISTICS']))return _i;for(var _i2=0,_track2;_i2<tracks.length;_i2++)if(_track2=tracks[_i2],mediaAttributesIdentical(currentTrack.attrs,_track2.attrs,['LANGUAGE']))return _i2}return-1},_proto.findTrackForTextTrack=function(textTrack){if(textTrack)for(var tracks=this.tracksInGroup,i=0,track;i<tracks.length;i++)if(track=tracks[i],subtitleTrackMatchesTextTrack(track,textTrack))return i;return-1},_proto.onError=function(event,data){!data.fatal&&data.context&&(data.context.type!==PlaylistContextType.SUBTITLE_TRACK||data.context.
1id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(data.context.groupId)||this.checkRetry(data))},_proto.setSubtitleOption=function(subtitleOption){if(this.hls.config.subtitlePreference=subtitleOption,subtitleOption){var allSubtitleTracks=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,allSubtitleTracks.length){var currentTrack=this.currentTrack;if(currentTrack&&matchesOption(subtitleOption,currentTrack))return currentTrack;var groupIndex=findMatchingOption(subtitleOption,this.tracksInGroup);if(-1<groupIndex){var track=this.tracksInGroup[groupIndex];return this.setSubtitleTrack(groupIndex),track}if(currentTrack)return null;var allIndex=findMatchingOption(subtitleOption,allSubtitleTracks);if(-1<allIndex)return allSubtitleTracks[allIndex]}}return null},_proto.loadPlaylist=function(hlsUrlParameters){_BasePlaylistControll.prototype.loadPlaylist.call(this);var currentTrack=this.currentTrack;if(this.shouldLoadPlaylist(currentTrack)&¤tTrack){var id=currentTrack.id,groupId=currentTrack.groupId,url=currentTrack.url;if(hlsUrlParameters)try{url=hlsUrlParameters.addDirectives(url)}catch(error){this.warn('Could not construct new URL with HLS Delivery Directives: '+error)}this.log('Loading subtitle playlist for id '+id),this.hls.trigger(Events.SUBTITLE_TRACK_LOADING,{url:url,id:id,groupId:groupId,deliveryDirectives:hlsUrlParameters||null})}},_proto.toggleTrackModes=function(){var media=this.media;if(media){var textTracks=filterSubtitleTracks(media.textTracks),currentTrack=this.currentTrack,nextTrack;if(currentTrack&&(nextTrack=textTracks.filter(function(textTrack){return subtitleTrackMatchesTextTrack(currentTrack,textTrack)})[0],!nextTrack&&this.warn('Unable to find subtitle TextTrack with name "'+currentTrack.name+'" and language "'+currentTrack.lang+'"')),[].slice.call(textTracks).forEac
1h(function(track){'disabled'!==track.mode&&track!==nextTrack&&(track.mode='disabled')}),nextTrack){var mode=this.subtitleDisplay?'showing':'hidden';nextTrack.mode!==mode&&(nextTrack.mode=mode)}}},_proto.setSubtitleTrack=function(newId){var tracks=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=newId);if(-1>newId||newId>=tracks.length||!isFiniteNumber(newId))return void this.warn('Invalid subtitle track id: '+newId);this.clearTimer(),this.selectDefaultTrack=!1;var lastTrack=this.currentTrack,track=tracks[newId]||null;if(this.trackId=newId,this.currentTrack=track,this.toggleTrackModes(),!track)return void this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:newId});var trackLoaded=!!track.details&&!track.details.live;if(!(newId===this.trackId&&track===lastTrack&&trackLoaded)){this.log('Switching to subtitle-track '+newId+(track?' "'+track.name+'" lang:'+track.lang+' group:'+track.groupId:''));var id=track.id,_track$groupId=track.groupId,groupId=void 0===_track$groupId?'':_track$groupId,name=track.name,type=track.type,url=track.url;this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:id,groupId:groupId,name:name,type:type,url:url});var hlsUrlParameters=this.switchParams(track.url,null==lastTrack?void 0:lastTrack.details,track.details);this.loadPlaylist(hlsUrlParameters)}},_createClass(SubtitleTrackController,[{key:'subtitleDisplay',get:function(){return this._subtitleDisplay},set:function(value){this._subtitleDisplay=value,-1<this.trackId&&this.toggleTrackModes()}},{key:'allSubtitleTracks',get:function(){return this.tracks}},{key:'subtitleTracks',get:function(){return this.tracksInGroup}},{key:'subtitleTrack',get:function(){return this.trackId},set:function(newId){this.selectDefaultTrack=!1,this.setSubtitleTrack(newId)}}]),SubtitleTrackController}(BasePlaylistController),BufferOperationQueue=function(){function BufferOperationQueue(sourceBufferReference){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=sourceBufferReference}var _proto=BufferOperationQueue.prototype;return _proto.append=function(operation,type,pending){var queue=this.queues[type];queue.push(operation),1!==queue.length||pending||this.executeNext(type)},_proto.insertAbort=function(operation,type){var queue=this.queues[type];queue.unshift(operation),this.executeNext(type)},_proto.appendBlocker=function(type){var promise=new Promise(function(resolve){execute=resolve}),operation={execute:execute,onStart:function(){},onComplete:function(){},onError:function(){}},execute;return this.append(operation,type),promise},_proto.executeNext=function(type){var queue=this.queues[type];if(queue.length){var operation=queue[0];try{operation.execute()}catch(error){logger.warn('[buffer-operation-queue]: Exception executing "'+type+'" SourceBuffer operation: '+error),operation.onError(error);var sb=this.buffers[type];null!=sb&&sb.updating||this.shiftAndExecuteNext(type)}}},_proto.shiftAndExecuteNext=function(type){this.queues[type].shift(),this.executeNext(type)},_proto.current=function(type){return this.queues[type][0]},BufferOperationQueue}(),VIDEO_CODEC_PROFILE_REPLACE=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,BufferController=function(){function BufferController(hls){var _this=this;this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=function(){_this.hls&&_this.hls.pauseBuffering()},this._onStartStreaming=function(){_this.hls&&_this.hls.resumeBuffering()},this._onMediaSourceOpen=function(){var media=_this.media,mediaSource=_this.mediaSource;_this.log('Media source opened'),media&&(media.removeEventListener('emptied',_this._onMediaEmptied),_this.updateMediaElementDuration(),_this.hls.trigger(Events.MEDIA_ATTACHED,{media:media,mediaSource:mediaSource})),mediaSource&&mediaSource.removeEventListener('sourceopen',_this._onMediaSourceOpen),_this.checkPendingTracks()},this._onMediaSourceClose=function(){_this.log('Media source closed')},this._onMediaSourceEnded=function(){_this.log('Media source ended')},this._onMediaEmptied=function(){var mediaSrc=_this.mediaSrc,_objectUrl=_this._objectUrl;mediaSrc!==_objectUrl&&logger.error('Media element src was set while attaching MediaSource ('+_objectUrl+' > '+mediaSrc+')')},this.hls=hls;var logPrefix='[buffer-controller]';this.appendSource=isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource)),this.log=logger.log.bind(logger,logPrefix),this.warn=logger.warn.bind(logger,logPrefix),this.error=logger.error.bind(logger,logPrefix),this._initSourceBuffer(),this.registerListeners()}var _proto=BufferController.prototype;return _proto.hasSourceTypes=function(){return 0<this.getSourceBufferTypes().length||0<Object.keys(this.pendingTracks).length},_proto.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}
vendor: 4,386 bytes, line 1
1,_proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.on(Events.BUFFER_RESET,this.onBufferReset,this),hls.on(Events.BUFFER_APPENDING,this.onBufferAppending,this),hls.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),hls.on(Events.BUFFER_EOS,this.onBufferEos,this),hls.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),hls.on(Events.FRAG_PARSED,this.onFragParsed,this),hls.on(Events.FRAG_CHANGED,this.onFragChanged,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.off(Events.BUFFER_RESET,this.onBufferReset,this),hls.off(Events.BUFFER_APPENDING,this.onBufferAppending,this),hls.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),hls.off(Events.BUFFER_EOS,this.onBufferEos,this),hls.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),hls.off(Events.FRAG_PARSED,this.onFragParsed,this),hls.off(Events.FRAG_CHANGED,this.onFragChanged,this)},_proto._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null},_proto.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},_proto.onManifestParsed=function(event,data){var codecEvents=2;(!data.audio||data.video)&&data.altAudio&&!0||(codecEvents=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=codecEvents,this.log(this.bufferCodecEventsExpected+' bufferCodec event(s) expected')},_proto.onMediaAttaching=function(event,data){var media=this.media=data.media,MediaSource=getMediaSource(this.appendSource);if(media&&MediaSource){var ms=this.mediaSource=new MediaSource,_ms$constructor;this.log('created media source: '+(null==(_ms$constructor=ms.constructor)?void 0:_ms$constructor.name)),ms.addEventListener('sourceopen',this._onMediaSourceOpen),ms.addEventListener('sourceended',this._onMediaSourceEnded),ms.addEventListener('sourceclose',this._onMediaSourceClose),this.appendSource&&(ms.addEventListener('startstreaming',this._onStartStreaming),ms.addEventListener('endstreaming',this._onEndStreaming));var objectUrl=this._objectUrl=self.URL.createObjectURL(ms);if(this.appendSource)try{media.removeAttribute('src');var MMS=self.ManagedMediaSource;media.disableRemotePlayback=media.disableRemotePlayback||MMS&&ms instanceof MMS,removeSourceChildren(media),addSource(media,objectUrl),media.load()}catch(error){media.src=objectUrl}else media.src=objectUrl;media.addEventListener('emptied',this._onMediaEmptied)}},_proto.onMediaDetaching=function(){var media=this.media,mediaSource=this.mediaSource,_objectUrl=this._objectUrl;if(mediaSource){if(this.log('media source detaching'),'open'===mediaSource.readyState)try{mediaSource.endOfStream()}catch(err){this.warn('onMediaDetaching: '+err.message+' while calling endOfStream')}this.onBufferReset(),mediaSource.removeEventListener('sourceopen',this._onMediaSourceOpen),mediaSource.removeEventListener('sourceended',this._onMediaSourceEnded),mediaSource.removeEventListener('sourceclose',this._onMediaSourceClose),this.appendSource&&(mediaSource.removeEventListener('startstreaming',this._onStartStreaming),mediaSource.removeEventListener('endstreaming',this._onEndStreaming)),media&&(media.removeEventListener('emptied',this._onMediaEmptied),_objectUrl&&self.URL.revokeObjectURL(_objectUrl),this.mediaSrc===_objectUrl?(media.removeAttribute('src'),this.appendSource&&removeSourceChildren(media),media.load()):this.warn('media|source.src was changed by a third party - skip cleanup')),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(Events.MEDIA_DETACHED,void 0)},_proto.onBufferReset=function(){var _this2=this;
1this.getSourceBufferTypes().forEach(function(type){_this2.resetBuffer(type)}),this._initSourceBuffer()},_proto.resetBuffer=function(type){var sb=this.sourceBuffer[type];try{if(sb){var _this$mediaSource;this.removeBufferListeners(type),this.sourceBuffer[type]=void 0,null!=(_this$mediaSource=this.mediaSource)&&_this$mediaSource.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(sb)}}catch(err){this.warn('onBufferReset '+type,err)}},_proto.onBufferCodecs=function(event,data){var _this3=this,sourceBufferCount=this.getSourceBufferTypes().length,trackNames=Object.keys(data);if(trackNames.forEach(function(trackName){if(sourceBufferCount){var track=_this3.tracks[trackName];if(track&&'function'==typeof track.buffer.changeType){var _data$trackName=data[trackName],id=_data$trackName.id,codec=_data$trackName.codec,levelCodec=_data$trackName.levelCodec,container=_data$trackName.container,metadata=_data$trackName.metadata,currentCodecFull=pickMostCompleteCodecName(track.codec,track.levelCodec),currentCodec=null==currentCodecFull?void 0:currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE,'$1'),trackCodec=pickMostCompleteCodecName(codec,levelCodec),nextCodec=null==(_trackCodec=trackCodec)?void 0:_trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE,'$1'),_trackCodec;if(trackCodec&¤tCodec!==nextCodec){'audio'===trackName.slice(0,5)&&(trackCodec=getCodecCompatibleName(trackCodec,_this3.appendSource));var mimeType=container+';codecs='+trackCodec;_this3.appendChangeType(trackName,mimeType),_this3.log('switching codec '+currentCodecFull+' to '+trackCodec),_this3.tracks[trackName]={buffer:track.buffer,codec:codec,container:container,levelCodec:levelCodec,metadata:metadata,id:id}}}}else _this3.pendingTracks[trackName]=data[trackName]}),!sourceBufferCount){var bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==bufferCodecEventsExpected&&(this.log(bufferCodecEventsExpected+' bufferCodec event(s) expected '+trackNames.join(',')),this.bufferCodecEventsExpected=bufferCodecEventsExpected),this.mediaSource&&'open'===this.mediaSource.readyState&&this.checkPendingTracks()}},_proto.appendChangeType=function(type,mimeType){var _this4=this,operationQueue=this.operationQueue;operationQueue.append({execute:function(){var sb=_this4.sourceBuffer[type];sb&&(_this4.log('changing '+type+' sourceBuffer type to '+mimeType),sb.changeType(mimeType)),operationQueue.shiftAndExecuteNext(type)},onStart:function(){},onComplete:function(){},onError:function(error){_this4.warn('Failed to change '+type+' SourceBuffer type',error)}},type,!!this.pendingTracks[type])},_proto.onBufferAppending=function(event,eventData){var _this5=this,hls=this.hls,operationQueue=this.operationQueue,tracks=this.tracks,data=eventData.data,type=eventData.type,frag=eventData.frag,part=eventData.part,chunkMeta=eventData.chunkMeta,chunkStats=chunkMeta.buffering[type],bufferAppendingStart=self.performance.now();chunkStats.start=bufferAppendingStart;var fragBuffering=frag.stats.buffering,partBuffering=part?part.stats.buffering:null;0===fragBuffering.start&&(fragBuffering.start=bufferAppendingStart),partBuffering&&0===partBuffering.start&&(partBuffering.start=bufferAppendingStart);var audioTrack=tracks.audio,checkTimestampOffset=!1;'audio'===type&&'audio/mpeg'===(null==audioTrack?void 0:audioTrack.container)&&(checkTimestampOffset=!this.lastMpegAudioChunk||1===chunkMeta.id||this.lastMpegAudioChunk.sn!==chunkMeta.sn,this.lastMpegAudioChunk=chunkMeta);var fragStart=frag.start;operationQueue.append({execute:function(){if(chunkStats.executeStart=self.performance.now(),checkTimestampOffset){var sb=_this5.sourceBuffer[type];if(sb){var delta=fragStart-sb.timestampOffset;.1<=Math.abs(delta)&&(_this5.log('Updating audio SourceBuffer timestampOffset to '+fragStart+' (delta: '+delta+') sn: '+frag.sn+')'),sb.timestampOffset=fragStart)}}_this5.appendExecutor(data,type)},onStart:function(){},onComplete:function(){var end=self.performance.now();chunkStats.executeEnd=chunkStats.end=end,0===fragBuffering.first&&(fragBuffering.first=end),partBuffering&&0===partBuffer
1ing.first&&(partBuffering.first=end);var sourceBuffer=_this5.sourceBuffer,timeRanges={};for(var _type in sourceBuffer)timeRanges[_type]=BufferHelper.getBuffered(sourceBuffer[_type]);_this5.appendErrors[type]=0,'audio'===type||'video'===type?_this5.appendErrors.audiovideo=0:(_this5.appendErrors.audio=0,_this5.appendErrors.video=0),_this5.hls.trigger(Events.BUFFER_APPENDED,{type:type,frag:frag,part:part,chunkMeta:chunkMeta,parent:frag.type,timeRanges:timeRanges})},onError:function(error){var event={type:ErrorTypes.MEDIA_ERROR,parent:frag.type,details:ErrorDetails.BUFFER_APPEND_ERROR,sourceBufferName:type,frag:frag,part:part,chunkMeta:chunkMeta,error:error,err:error,fatal:!1};if(error.code===DOMException.QUOTA_EXCEEDED_ERR)event.details=ErrorDetails.BUFFER_FULL_ERROR;else{var appendErrorCount=++_this5.appendErrors[type];event.details=ErrorDetails.BUFFER_APPEND_ERROR,_this5.warn('Failed '+appendErrorCount+'/'+hls.config.appendErrorMaxRetry+' times to append segment in "'+type+'" sourceBuffer'),appendErrorCount>=hls.config.appendErrorMaxRetry&&(event.fatal=!0)}hls.trigger(Events.ERROR,event)}},type,!!this.pendingTracks[type])},_proto.onBufferFlushing=function(event,data){var _this6=this,operationQueue=this.operationQueue,flushOperation=function(type){return{execute:_this6.removeExecutor.bind(_this6,type,data.startOffset,data.endOffset),onStart:function(){},onComplete:function(){_this6.hls.trigger(Events.BUFFER_FLUSHED,{type:type})},onError:function(error){_this6.warn('Failed to remove from '+type+' SourceBuffer',error)}}};data.type?operationQueue.append(flushOperation(data.type),data.type):this.getSourceBufferTypes().forEach(function(type){operationQueue.append(flushOperation(type),type)})},_proto.onFragParsed=function(event,data){var _this7=this,frag=data.frag,part=data.part,buffersAppendedTo=[],elementaryStreams=part?part.elementaryStreams:frag.elementaryStreams;elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]?buffersAppendedTo.push('audiovideo'):(elementaryStreams[ElementaryStreamTypes.AUDIO]&&buffersAppendedTo.push('audio'),elementaryStreams[ElementaryStreamTypes.VIDEO]&&buffersAppendedTo.push('video'));var onUnblocked=function(){var now=self.performance.now();frag.stats.buffering.end=now,part&&(part.stats.buffering.end=now);var stats=part?part.stats:frag.stats;_this7.hls.trigger(Events.FRAG_BUFFERED,{frag:frag,part:part,stats:stats,id:frag.type})};0===buffersAppendedTo.length&&this.warn('Fragments must have at least one ElementaryStreamType set. type: '+frag.type+' level: '+frag.level+' sn: '+frag.sn),this.blockBuffers(onUnblocked,buffersAppendedTo)},_proto.onFragChanged=function(){this.trimBuffers()},_proto.onBufferEos=function(event,data){var _this8=this,ended=this.getSourceBufferTypes().reduce(function(acc,type){var sb=_this8.sourceBuffer[type];return sb&&(!data.type||data.type===type)&&(sb.ending=!0,!sb.ended&&(sb.ended=!0,_this8.log(type+' sourceBuffer now EOS'))),acc&&(!sb||sb.ended)},!0);ended&&(this.log('Queueing mediaSource.endOfStream()'),this.blockBuffers(function(){_this8.getSourceBufferTypes().forEach(function(type){var sb=_this8.sourceBuffer[type];sb&&(sb.ending=!1)});var mediaSource=_this8.mediaSource;return mediaSource&&'open'===mediaSource.readyState?void(_this8.log('Calling mediaSource.endOfStream()'),mediaSource.endOfStream()):void(mediaSource&&_this8.log('Could not call mediaSource.endOfStream(). mediaSource.readyState: '+mediaSource.readyState))}))},_proto.onLevelUpdated=function(event,_ref){var details=_ref.details;details.fragments.length&&(this.details=details,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},_proto.trimBuffers=function(){var hls=this.hls,details=this.details,media=this.media;if(media&&null!==details){var sourceBufferTypes=this.getSourceBufferTypes();if(sourceBufferTypes.length){var config=hls.config,currentTime=media.currentTime,targetDuration=details.levelTargetDuration,backBufferLength=details.live&&null!==config.liveBackBufferLength?config.liveBackBufferLength:config.backBufferLength;if(isFiniteNumber(backBufferLength)&&0<backBufferLength){var maxBackBufferLength=Math.max(backBufferLength,targetDuration),targetBackBufferPosition=Math.floor(currentTime/targetDuration)*targetDuration-maxBackBufferLength;this.flushBackBuffer(currentTime,targetDuration,targetBackBufferPosition)}if(isFiniteNumber(config.frontBufferFlushThreshold)&&0<config.frontBufferFlushThreshold){var frontBufferLength=Math.max(config.maxBufferLength,
1config.frontBufferFlushThreshold),maxFrontBufferLength=Math.max(frontBufferLength,targetDuration),targetFrontBufferPosition=Math.floor(currentTime/targetDuration)*targetDuration+maxFrontBufferLength;this.flushFrontBuffer(currentTime,targetDuration,targetFrontBufferPosition)}}}},_proto.flushBackBuffer=function(currentTime,targetDuration,targetBackBufferPosition){var _this9=this,details=this.details,sourceBuffer=this.sourceBuffer,sourceBufferTypes=this.getSourceBufferTypes();sourceBufferTypes.forEach(function(type){var sb=sourceBuffer[type];if(sb){var buffered=BufferHelper.getBuffered(sb);if(0<buffered.length&&targetBackBufferPosition>buffered.start(0)){if(_this9.hls.trigger(Events.BACK_BUFFER_REACHED,{bufferEnd:targetBackBufferPosition}),null!=details&&details.live)_this9.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:targetBackBufferPosition});else if(sb.ended&&buffered.end(buffered.length-1)-currentTime<2*targetDuration)return void _this9.log('Cannot flush '+type+' back buffer while SourceBuffer is in ended state');_this9.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:targetBackBufferPosition,type:type})}}})},_proto.flushFrontBuffer=function(currentTime,targetDuration,targetFrontBufferPosition){var _this10=this,sourceBuffer=this.sourceBuffer,sourceBufferTypes=this.getSourceBufferTypes();sourceBufferTypes.forEach(function(type){var sb=sourceBuffer[type];if(sb){var buffered=BufferHelper.getBuffered(sb),numBufferedRanges=buffered.length;if(2>numBufferedRanges)return;var bufferStart=buffered.start(numBufferedRanges-1),bufferEnd=buffered.end(numBufferedRanges-1);if(targetFrontBufferPosition>bufferStart||currentTime>=bufferStart&¤tTime<=bufferEnd)return;if(sb.ended&¤tTime-bufferEnd<2*targetDuration)return void _this10.log('Cannot flush '+type+' front buffer while SourceBuffer is in ended state');_this10.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:bufferStart,endOffset:Infinity,type:type})}})},_proto.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&'open'===this.mediaSource.readyState){var details=this.details,hls=this.hls,media=this.media,mediaSource=this.mediaSource,levelDuration=details.fragments[0].start+details.totalduration,mediaDuration=media.duration,msDuration=isFiniteNumber(mediaSource.duration)?mediaSource.duration:0;details.live&&hls.config.liveDurationInfinity?(mediaSource.duration=Infinity,this.updateSeekableRange(details)):(levelDuration>msDuration&&levelDuration>mediaDuration||!isFiniteNumber(mediaDuration))&&(this.log('Updating Media Source duration to '+levelDuration.toFixed(3)),mediaSource.duration=levelDuration)}},_proto.updateSeekableRange=function(levelDetails){var mediaSource=this.mediaSource,fragments=levelDetails.fragments,len=fragments.length;if(len&&levelDetails.live&&null!=mediaSource&&mediaSource.setLiveSeekableRange){var start=Math.max(0,fragments[0].start),end=Math.max(start,start+levelDetails.totalduration);this.log('Media Source duration is set to '+mediaSource.duration+'. Setting seekable range to '+start+'-'+end+'.'),mediaSource.setLiveSeekableRange(start,end)}},_proto.checkPendingTracks=function(){var bufferCodecEventsExpected=this.bufferCodecEventsExpected,operationQueue=this.operationQueue,pendingTracks=this.pendingTracks,pendingTracksCount=Object.keys(pendingTracks).length;if(pendingTracksCount&&(!bufferCodecEventsExpected||2===pendingTracksCount||'audiovideo'in pendingTracks)){this.createSourceBuffers(pendingTracks),this.pendingTracks={};var buffers=this.getSourceBufferTypes();if(buffers.length)this.hls.trigger(Events.BUFFER_CREATED,{tracks:this.tracks}),buffers.forEach(function(type){operationQueue.executeNext(type)});else{var error=new Error('could not create source buffer for media codec(s)');this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:error,reason:error.message})}}},_proto.createSourceBuffers=function(tracks){var _this11=this,sourceBuffer=this.sourceBuffer,mediaSource=this.mediaSource;if(!mediaSource)throw Error('createSourceBuffers called when mediaSource was null');var _loop=function(trackName){if(!sourceBuffer[trackName]){var track=tracks[trackName],_track$levelCodec;if(!track)throw Error('source buffer exists for track '+trackName+', however track does not');var codec=-1===(null==(_track$levelCodec=track.levelCodec)?void 0:_track$levelCodec.indexOf(','))?track.levelCodec:track.codec;codec&&'audio'===trackName.slice(0,5)&&(codec=getCodecCompatibleName(codec,_this11.appendSource));var mimeType=track.container+';codecs='+codec;_this11.log('creating sourceBuffer('+mimeType+')');try{var sb=sourceBuffer[trackName]=mediaSource.addSourceBuffer(mimeType),sbName=trackName;_this11.addBufferListener(sbName,'updatestart',_this11._onSBUpdateStart),_this11.addBufferListener(sbName,'updateend',_this11._onSBUpdateEnd),_this11.addBufferListener(sbName,'error',_this11._onSBUpdateError),_this11.appendSource&&_this11.addBufferListener(sbName,'bufferedchange',function(type,event){var removedRanges=event.removedRanges;null!=removedRanges&&removedRanges.length&&_this11.hls.trigger(Events.BUFFER_FLUSHED,{type:trackName})}),_this11.tracks[trackName]={buffer:sb,codec:codec,container:track.container,levelCodec:track.levelCodec,metadata:track.metadata,id:track.id}}catch(err){_this11.error('error while trying to add sourceBuffer: '+err.message),_this11.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:err,sourceBufferName:trackName,mimeType:mimeType})}}};for(var trackName in tracks)_loop(trackName)},_proto._onSBUpdateStart=function(type){var operationQueue=this.operationQueue,operation=operationQueue.current(type);operation.onStart()},_proto._onSBUpdateEnd=function(type){var _this$mediaSource2;if('closed'===(null==(_this$mediaSource2=this.mediaSource)?void 0:_this$mediaSource2.readyState))return void this.resetBuffer(type);var operationQueue=this.operationQueue,operation=operationQueue.current(type);operation.onComplete(),operationQueue.shiftAndExecuteNext(type)},_proto._onSBUpdateError=function(type,event){var error=new Error(type+' SourceBuffer error. MediaSource readyState: '+(null==(_this$mediaSource3=this.mediaSource)?void 0:_this$mediaSource3.readyState)),_this$mediaSource3;this.error(''+error,event),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,sourceBufferName:type,error:error,fatal:!1});var operation=this.operationQueue.current(type);operation&&operation.onError(error)},_proto.removeExecutor=function(type,startOffset,endOffset){var media=this.media,mediaSource=this.mediaSource,operationQueue=this.operationQueue,sourceBuffer=this.sourceBuffer,sb=sourceBuffer[type];
1if(!media||!mediaSource||!sb)return this.warn('Attempting to remove from the '+type+' SourceBuffer, but it does not exist'),void operationQueue.shiftAndExecuteNext(type);var mediaDuration=isFiniteNumber(media.duration)?media.duration:Infinity,msDuration=isFiniteNumber(mediaSource.duration)?mediaSource.duration:Infinity,removeStart=Math.max(0,startOffset),removeEnd=Math.min(endOffset,mediaDuration,msDuration);removeEnd>removeStart&&(!sb.ending||sb.ended)?(sb.ended=!1,this.log('Removing ['+removeStart+','+removeEnd+'] from the '+type+' SourceBuffer'),sb.remove(removeStart,removeEnd)):operationQueue.shiftAndExecuteNext(type)},_proto.appendExecutor=function(data,type){var sb=this.sourceBuffer[type];if(!sb){if(!this.pendingTracks[type])throw new Error('Attempting to append to the '+type+' SourceBuffer, but it does not exist');return}sb.ended=!1,sb.appendBuffer(data)},_proto.blockBuffers=function(onUnblocked,buffers){var _this12=this;if(void 0===buffers&&(buffers=this.getSourceBufferTypes()),!buffers.length)return this.log('Blocking operation requested, but no SourceBuffers exist'),void Promise.resolve().then(onUnblocked);var operationQueue=this.operationQueue,blockingOperations=buffers.map(function(type){return operationQueue.appendBlocker(type)});Promise.all(blockingOperations).then(function(){onUnblocked(),buffers.forEach(function(type){var sb=_this12.sourceBuffer[type];null!=sb&&sb.updating||operationQueue.shiftAndExecuteNext(type)})})},_proto.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},_proto.addBufferListener=function(type,event,fn){var buffer=this.sourceBuffer[type];if(buffer){var listener=fn.bind(this,type);this.listeners[type].push({event:event,listener:listener}),buffer.addEventListener(event,listener)}},_proto.removeBufferListeners=function(type){var buffer=this.sourceBuffer[type];buffer&&this.listeners[type].forEach(function(l){buffer.removeEventListener(l.event,l.listener)})},_createClass(BufferController,[{key:'mediaSrc',get:function(){var media=(null==(_this$media=this.media)||null==(_this$media$querySele=_this$media.querySelector)?void 0:_this$media$querySele.call(_this$media,'source'))||this.media,_this$media,_this$media$querySele;return null==media?void 0:media.src}}]),BufferController}(),specialCea608CharsCodes={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},getCharForByte=function(_byte){return String.fromCharCode(specialCea608CharsCodes[_byte]||_byte)},NR_ROWS=15,NR_COLS=100,rowsLowCh1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rowsHighCh1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rowsLowCh2={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rowsHighCh2={25:2,26:4,29:6,30:8,31:10,27:13,28:15},backgroundColors=['white','green','blue','cyan','red','yellow','magenta','black','transparent'],CaptionsLogger=function(){function CaptionsLogger(){this.time=null,this.verboseLevel=0}var _proto=CaptionsLogger.prototype;return _proto.log=function(severity,msg){if(this.verboseLevel>=severity){var m='function'==typeof msg?msg():msg;logger.log(this.time+' ['+severity+'] '+m)}},CaptionsLogger}(),numArrayToHexArray=function(numArray){for(var hexArray=[],j=0;j<numArray.length;j++)hexArray.push(numArray[j].toString(16));return hexArray},PenState=function(){function PenState(){this.foreground='white',this.underline=!1,this.italics=!1,this.background='black',this.flash=!1}var _proto2=PenState.prototype;return _proto2.reset=function(){this.foreground='white',this.underline=!1,this.italics=!1,this.background='black',this.flash=!1},_proto2.setStyles=function(styles){for(var attribs=['foreground','underline','italics','background','flash'],i=0,style;i<attribs.length;i++)style=attribs[i],styles.hasOwnProperty(style)&&(this[style]=styles[style])},_proto2.isDefault=function(){return'white'===this.foreground&&!this.underline&&!this.italics&&'black'===this.background&&!this.flash},_proto2.equals=function(other){return this.foreground===other.foreground&&this.underline===other.underline&&this.italics===other.italics&&this.background===other.background&&this.flash===other.flash},_proto2.copy=function(newPenState){this.foreground=newPenState.foreground,this.underline=newPenState.underline,this.italics=newPenState.italics,this.background=newPenState.background,this.flash=newPenState.flash},_proto2.toString=function(){return'color='+this.foreground+', underline='+this.underline+', italics='+this.italics+', background='+this.background+', flash='+this.flash},PenState}(),StyledUnicodeChar=function(){function StyledUnicodeChar(){this.uchar=' ',this.penState=new PenState}var _proto3=StyledUnicodeChar.prototype;return _proto3.reset=function(){this.uchar=' ',this.penState.reset()},_proto3.setChar=function(uchar,newPenState){this.uchar=uchar,this.penState.copy(newPenState)},_proto3.setPenState=function(newPenState){this.penState.copy(newPenState)},_proto3.equals=function(other){return this.uchar===other.uchar&&this.penState.equals(other.penState)},_proto3.copy=function(newChar){this.uchar=newChar.uchar,this.penState.copy(newChar.penState)},_proto3.isEmpty=function(){return' '===this.uchar&&this.penState.isDefault()},StyledUnicodeChar}(),Row=function(){function Row(logger){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(var i=0;i<NR_COLS;i++)this.chars.push(new StyledUnicodeChar);this.logger=logger}var _proto4=Row.prototype;return _proto4.equals=function(other){for(var i=0;i<NR_COLS;i++)if(!this.chars[i].equals(other.chars[i]))return!1;return!0},_proto4.copy=function(other){for(var i=0;i<NR_COLS;i++)this.chars[i].copy(other.chars[i])},_proto4.isEmpty=function(){for(var empty=!0,i=0;i<NR_COLS;i++)if(!this.chars[i].isEmpty()){empty=!1;break}return empty},_proto4.setCursor=function(absPos){this.pos!==absPos&&(this.pos=absPos),0>this.pos?(this.logger.log(3,'Negative cursor position '+this.pos),this.pos=0):this.pos>NR_COLS&&(this.logger.log(3,'Too large cursor position '+this.pos),this.pos=NR_COLS)},_proto4.moveCursor=function(relPos){var newPos=this.pos+relPos;if(1<relPos)for(var i=this.pos+1;i<newPos+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(newPos)},_proto4.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(' ',this.currPenState)},_proto4.insertChar=function(_byte2){var _this=this;144<=_byte2&&this.backSpace();var _char=getCharForByte(_byte2);return this.pos>=NR_COLS?void this.logger.log(0,function(){return'Cannot insert '+_byte2.toString(16)+' ('+_char+') at position '+_this.pos+'. Skipping it!'}):void(this.chars[this.pos].setChar(_char,this.currPenState),this.moveCursor(1))},_proto4.clearFromPos=function(startPos){var i;for(i=startPos;i<NR_COLS;i++)this.chars[i].reset()},_proto4.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},_proto4.clearToEndOfRow=function(){this.clearFromPos(this.pos)},_proto4.getTextString=function(){for(var chars=[],empty=!0,i=0,_char2;i<NR_COLS;i++)_char2=this.chars[i].uchar,' '!==_char2&&(empty=!1),chars.push(_char2);return empty?'':chars.join('')},_proto4.setPenStyles=function(styles){this.currPenState.setStyles(styles);var currChar=this.chars[this.pos];currChar.setPenState(this.currPenState)},Row}(),CaptionScreen=function(){function CaptionScreen(logger){this.rows=[],this.currRow=NR_ROWS-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var i=0;i<NR_ROWS;i++)this.rows.push(new Row(logger));this.logger=logger}var _proto5=CaptionScreen.prototype;return _proto5.reset=function(){for(var i=0;i<NR_ROWS;i++)this.rows[i].clear();this.currRow=NR_ROWS-1},_proto5.equals=function(other){for(var equal=!0,i=0;i<NR_ROWS;i++)if(!this.rows[i].equals(other.rows[i])){equal=!1;break}return equal},_proto5.copy=function(other){for(var i=0;i<NR_ROWS;i++)this.rows[i].copy(other.rows[i])},_proto5.isEmpty=function(){for(var empty=!0,i=0;i<NR_ROWS;i++)if(!this.rows[i].isEmpty()){empty=!1;break}return empty},_proto5.backSpace=function(){var row=this.rows[this.currRow];row.backSpace()},_proto5.clearToEndOfRow=function(){var row=this.rows[this.currRow];row.clearToEndOfRow()},_proto5.insertChar=function(_char3){var row=this.rows[this.currRow];row.insertChar(_char3)},_proto5.setPen=function(styles){var row=this.rows[this.currRow];row.setPenStyles(styles)},_proto5.moveCursor=function(relPos){var row=this.rows[this.currRow];row.moveCursor(relPos)},_proto5.setCursor=function(absPos){this.logger.log(2,'setCursor: '+absPos);var row=this.rows[this.currRow];row.setCursor(absPos)},_proto5.setPAC=function(pacData){this.logger.log(2,function(){return'pacData = '+JSON.stringify(pacData)});var newRow=pacData.row-1;if(this.nrRollUpRows&&newRow<this.nrRollUpRows-1&&(newRow=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==newRow){for(var i=0;i<NR_ROWS;i++)this.rows[i].clear();var topRowIndex=this.currRow+1-this.nrRollUpRows,lastOutputScreen=this.lastOutputScreen;if(lastOutputScreen){var prevLineTime=lastOutputScreen.rows[topRowIndex].cueStartTime,time=this.logger.time;if(null!==prevLineTime&&null!==time&&prevLineTime<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(null!==pacData.indent){var indent=pacData.indent,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:!1};this.setPen(styles)},_proto5.setBkgData=function(bkgData){this.logger.log(2,function(){return'bkgData = '+JSON.stringify(bkgData)}),this.backSpace(),this.setPen(bkgData),this.insertChar(32)},_proto5.setRollUpRows=function(nrRows){this.nrRollUpRows=nrRows},_proto5.rollUp=function(){var _this2=this;if(null===this.nrRollUpRows)return void this.logger.log(3,'roll_up but nrRollUpRows not set yet');this.logger.log(1,function(){return _this2.getDisplayText()});var topRowIndex=this.currRow+1-this.nrRollUpRows,topRow=this.rows.splice(topRowIndex,1)[0];topRow.clear(),this.rows.splice(this.currRow,0,topRow),this.logger.log(2,'Rolling up')},_proto5.getDisplayText=function(asOneRow){asOneRow=asOneRow||!1;for(var displayText=[],text='',rowNr=-1,i=0,rowText;i<NR_ROWS;i++)rowText=this.rows[i].getTextString(),rowText&&(rowNr=i+1,asOneRow?displayText.push('Row '+rowNr+': \''+rowText
1+'\''):displayText.push(rowText.trim()));return 0<displayText.length&&(asOneRow?text='['+displayText.join(' | ')+']':text=displayText.join('\n')),text},_proto5.getTextAndFormat=function(){return this.rows},CaptionScreen}(),Cea608Channel=function(){function Cea608Channel(channelNumber,outputFilter,logger){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=channelNumber,this.outputFilter=outputFilter,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(logger),this.nonDisplayedMemory=new CaptionScreen(logger),this.lastOutputScreen=new CaptionScreen(logger),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=logger}var _proto6=Cea608Channel.prototype;return _proto6.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},_proto6.getHandler=function(){return this.outputFilter},_proto6.setHandler=function(newHandler){this.outputFilter=newHandler},_proto6.setPAC=function(pacData){this.writeScreen.setPAC(pacData)},_proto6.setBkgData=function(bkgData){this.writeScreen.setBkgData(bkgData)},_proto6.setMode=function(newMode){newMode===this.mode||(this.mode=newMode,this.logger.log(2,function(){return'MODE='+newMode}),'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=newMode)},_proto6.insertChars=function(chars){for(var _this3=this,i=0;i<chars.length;i++)this.writeScreen.insertChar(chars[i]);var screen=this.writeScreen===this.displayedMemory?'DISP':'NON_DISP';this.logger.log(2,function(){return screen+': '+_this3.writeScreen.getDisplayText(!0)}),('MODE_PAINT-ON'===this.mode||'MODE_ROLL-UP'===this.mode)&&(this.logger.log(1,function(){return'DISPLAYED: '+_this3.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())},_proto6.ccRCL=function(){this.logger.log(2,'RCL - Resume Caption Loading'),this.setMode('MODE_POP-ON')},_proto6.ccBS=function(){this.logger.log(2,'BS - BackSpace'),'MODE_TEXT'===this.mode||(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},_proto6.ccAOF=function(){},_proto6.ccAON=function(){},_proto6.ccDER=function(){this.logger.log(2,'DER- Delete to End of Row'),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},_proto6.ccRU=function(nrRows){this.logger.log(2,'RU('+nrRows+') - Roll Up'),this.writeScreen=this.displayedMemory,this.setMode('MODE_ROLL-UP'),this.writeScreen.setRollUpRows(nrRows)},_proto6.ccFON=function(){this.logger.log(2,'FON - Flash On'),this.writeScreen.setPen({flash:!0})},_proto6.ccRDC=function(){this.logger.log(2,'RDC - Resume Direct Captioning'),this.setMode('MODE_PAINT-ON')},_proto6.ccTR=function(){this.logger.log(2,'TR'),this.setMode('MODE_TEXT')},_proto6.ccRTD=function(){this.logger.log(2,'RTD'),this.setMode('MODE_TEXT')},_proto6.ccEDM=function(){this.logger.log(2,'EDM - Erase Displayed Memory'),this.displayedMemory.reset(),this.outputDataUpdate(!0)},_proto6.ccCR=function(){this.logger.log(2,'CR - Carriage Return'),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},_proto6.ccENM=function(){this.logger.log(2,'ENM - Erase Non-displayed Memory'),this.nonDisplayedMemory.reset()},_proto6.ccEOC=function(){var _this4=this;if(this.logger.log(2,'EOC - End Of Caption'),'MODE_POP-ON'===this.mode){var tmp=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=tmp,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return'DISP: '+_this4.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)},_proto6.ccTO=function(nrCols){this.logger.log(2,'TO('+nrCols+') - Tab Offset'),this.writeScreen.moveCursor(nrCols)},_proto6.ccMIDROW=function(secondByte){var styles={flash:!1,underline:1==secondByte
1%2,italics:46<=secondByte};if(!styles.italics){var colorIndex=Math.floor(secondByte/2)-16;styles.foreground=['white','green','blue','cyan','red','yellow','magenta'][colorIndex]}else styles.foreground='white';this.logger.log(2,'MIDROW: '+JSON.stringify(styles)),this.writeScreen.setPen(styles)},_proto6.outputDataUpdate=function(dispatch){void 0===dispatch&&(dispatch=!1);var time=this.logger.time;null===time||this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?!this.displayedMemory.equals(this.lastOutputScreen)&&(this.outputFilter.newCue(this.cueStartTime,time,this.lastOutputScreen),dispatch&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:time):this.cueStartTime=time,this.lastOutputScreen.copy(this.displayedMemory))},_proto6.cueSplitAtTime=function(t){this.outputFilter&&!this.displayedMemory.isEmpty()&&(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t)},Cea608Channel}(),Cea608Parser=function(){function Cea608Parser(field,out1,out2){this.channels=void 0,this.currentChannel=0,this.cmdHistory=createCmdHistory(),this.logger=void 0;var logger=this.logger=new CaptionsLogger;this.channels=[null,new Cea608Channel(field,out1,logger),new Cea608Channel(field+1,out2,logger)]}var _proto7=Cea608Parser.prototype;return _proto7.getHandler=function(channel){return this.channels[channel].getHandler()},_proto7.setHandler=function(channel,newHandler){this.channels[channel].setHandler(newHandler)},_proto7.addData=function(time,byteList){var _this5=this;this.logger.time=time;for(var _loop=function(i){var a=127&byteList[i],b=127&byteList[i+1],cmdFound=!1,charsFound=null;if(0==a&&0==b)return 0;_this5.logger.log(3,function(){return'['+numArrayToHexArray([byteList[i],byteList[i+1]])+'] -> ('+numArrayToHexArray([a,b])+')'});var cmdHistory=_this5.cmdHistory;if(16<=a&&31>=a){if(hasCmdRepeated(a,b,cmdHistory))return setLastCmd(null,null,cmdHistory),_this5.logger.log(3,function(){return'Repeated command ('+numArrayToHexArray([a,b])+') is dropped'}),0;setLastCmd(a,b,_this5.cmdHistory),cmdFound=_this5.parseCmd(a,b),cmdFound||(cmdFound=_this5.parseMidrow(a,b)),cmdFound||(cmdFound=_this5.parsePAC(a,b)),cmdFound||(cmdFound=_this5.parseBackgroundAttributes(a,b))}else setLastCmd(null,null,cmdHistory);if(!cmdFound&&(charsFound=_this5.parseChars(a,b),charsFound)){var currChNr=_this5.currentChannel;if(currChNr&&0<currChNr){var channel=_this5.channels[currChNr];channel.insertChars(charsFound)}else _this5.logger.log(2,'No channel found yet. TEXT-MODE?')}cmdFound||charsFound||_this5.logger.log(2,function(){return'Couldn\'t parse cleaned data '+numArrayToHexArray([a,b])+' orig: '+numArrayToHexArray([byteList[i],byteList[i+1]])})},i=0,_ret;i<byteList.length;i+=2)_ret=_loop(i),0===_ret},_proto7.parseCmd=function(a,b){if(!((20===a||28===a||21===a||29===a)&&32<=b&&47>=b||(23===a||31===a)&&33<=b&&35>=b))return!1;var chNr=20===a||21===a||23===a?1:2,channel=this.channels[chNr];return 20===a||21===a||28===a||29===a?32===b?channel.ccRCL():33===b?channel.ccBS():34===b?channel.ccAOF():35===b?channel.ccAON():36===b?channel.ccDER():37===b?channel.ccRU(2):38===b?channel.ccRU(3):39===b?channel.ccRU(4):40===b?channel.ccFON():41===b?channel.ccRDC():42===b?channel.ccTR():43===b?channel.ccRTD():44===b?channel.ccEDM():45===b?channel.ccCR():46===b?channel.ccENM():47==b&&channel.ccEOC():channel.ccTO(b-32),this.currentChannel=chNr,!0},_proto7.parseMidrow=function(a,b){var chNr=0;if((17===a||25===a)&&32<=b&&47>=b){if(chNr=17===a?1:2,chNr!==this.currentChannel)return this.logger.log(0,'Mismatch channel in midrow parsing'),!1;var channel=this.channels[chNr];return!!channel&&(channel.ccMIDROW(b),this.logger.log(3,function(){return'MIDROW ('+numArrayToHexArray([a,b])+')'}),!0)}return!1},_proto7.parsePAC=function(a,b){var row;if(!((17<=a&&23>=a||25<=a&&31>=a)&&64<=b&&127>=b||(16===a||24===a)&&64<=b&&95>=b))return!1;var chNr=23>=a?1:2;row=64<=b&&95>=b?1==chNr?rowsLowCh1[a]:rowsLowCh2[a]:1==chNr?rowsHighCh1[a]:rowsHighCh2[a];var channel=this.channels[chNr];return!!channel&&(channel.setPAC(this.interpretPAC(row,b)),this.currentChannel=chNr,!0)},_proto7.interpretPAC=function(row,_byte3){var pacData={color:null,italics:!1,indent:null,underline:!1,row:row},pacIndex;return pacIndex=95<_byte3?_byte3-96:_byte3-64,pacData.underline=1==(1&pacIndex),13>=pacIndex?pacData.color=['white','green','blue','cyan','red','yellow','magenta','white'][Math.floor(pacIndex/2)]:15>=pacIndex?(pacData.italics=!0,pacData.color='white'):pacData.indent=4*Math.floor((pacIndex-16)/2),pacData}
1,_proto7.parseChars=function(a,b){var charCodes=null,charCode1=null,channelNr;if(25<=a?(channelNr=2,charCode1=a-8):(channelNr=1,charCode1=a),17<=charCode1&&19>=charCode1){var oneCode;oneCode=17===charCode1?b+80:18===charCode1?b+112:b+144,this.logger.log(2,function(){return'Special char \''+getCharForByte(oneCode)+'\' in channel '+channelNr}),charCodes=[oneCode]}else 32<=a&&127>=a&&(charCodes=0===b?[a]:[a,b]);return charCodes&&this.logger.log(3,function(){return'Char codes = '+numArrayToHexArray(charCodes).join(',')}),charCodes},_proto7.parseBackgroundAttributes=function(a,b){if(!((16===a||24===a)&&32<=b&&47>=b||(23===a||31===a)&&45<=b&&47>=b))return!1;var bkgData={},index;16===a||24===a?(index=Math.floor((b-32)/2),bkgData.background=backgroundColors[index],1==b%2&&(bkgData.background+='_semi')):45===b?bkgData.background='transparent':(bkgData.foreground='black',47==b&&(bkgData.underline=!0));var chNr=23>=a?1:2,channel=this.channels[chNr];return channel.setBkgData(bkgData),!0},_proto7.reset=function(){for(var i=0,channel;i<Object.keys(this.channels).length;i++)channel=this.channels[i],channel&&channel.reset();setLastCmd(null,null,this.cmdHistory)},_proto7.cueSplitAtTime=function(t){for(var i=0,channel;i<this.channels.length;i++)channel=this.channels[i],channel&&channel.cueSplitAtTime(t)},Cea608Parser}(),OutputFilter=function(){function OutputFilter(timelineController,trackName){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=timelineController,this.trackName=trackName}var _proto=OutputFilter.prototype;return _proto.dispatchCue=function(){null===this.startTime||(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},_proto.newCue=function(startTime,endTime,screen){(null===this.startTime||this.startTime>startTime)&&(this.startTime=startTime),this.endTime=endTime,this.screen=screen,this.timelineController.createCaptionsTrack(this.trackName)},_proto.reset=function(){this.cueRanges=[],this.startTime=null},OutputFilter}(),VTTCue=function(){function isAllowedValue(allowed,value){if('string'!=typeof value)return!1;if(!Array.isArray(allowed))return!1;var lcValue=value.toLowerCase();return!!~allowed.indexOf(lcValue)&&lcValue}function findDirectionSetting(value){return isAllowedValue(AllowedDirections,value)}function findAlignSetting(value){return isAllowedValue(AllowedAlignments,value)}function extend(obj){for(var _len=arguments.length,rest=Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)rest[_key-1]=arguments[_key];for(var i=1,cobj;i<arguments.length;i++)for(var p in cobj=arguments[i],cobj)obj[p]=cobj[p];return obj}function VTTCue(startTime,endTime,text){var cue=this,baseObj={enumerable:!0};cue.hasBeenReset=!1;var _id='',_pauseOnExit=!1,_startTime=startTime,_endTime=endTime,_text=text,_region=null,_vertical='',_snapToLines=!0,_line='auto',_lineAlign='start',_position=50,_positionAlign='middle',_size=50,_align='middle';Object.defineProperty(cue,'id',extend({},baseObj,{get:function(){return _id},set:function(value){_id=''+value}})),Object.defineProperty(cue,'pauseOnExit',extend({},baseObj,{get:function(){return _pauseOnExit},set:function(value){_pauseOnExit=!!value}})),Object.defineProperty(cue,'startTime',extend({},baseObj,{get:function(){return _startTime},set:function(value){if('number'!=typeof value)throw new TypeError('Start time must be set to a number.');_startTime=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'endTime',extend({},baseObj,{get:function(){return _endTime},set:function(value){if('number'!=typeof value)throw new TypeError('End time must be set to a number.');_endTime=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'text',extend({},baseObj,{get:function(){return _text},set:function(value){_text=''+value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'region',extend({},baseObj,{get:function(){return _region},set:function(value){_region=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'vertical',extend({},baseObj,{get:function(){return _vertical},set:function(value){var setting=findDirectionSetting(value);if(!1===setting)throw new SyntaxError('An invalid or illegal string was specified.');
1_vertical=setting,this.hasBeenReset=!0}})),Object.defineProperty(cue,'snapToLines',extend({},baseObj,{get:function(){return _snapToLines},set:function(value){_snapToLines=!!value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'line',extend({},baseObj,{get:function(){return _line},set:function(value){if('number'!=typeof value&&'auto'!==value)throw new SyntaxError('An invalid number or illegal string was specified.');_line=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'lineAlign',extend({},baseObj,{get:function(){return _lineAlign},set:function(value){var setting=findAlignSetting(value);if(!setting)throw new SyntaxError('An invalid or illegal string was specified.');_lineAlign=setting,this.hasBeenReset=!0}})),Object.defineProperty(cue,'position',extend({},baseObj,{get:function(){return _position},set:function(value){if(0>value||100<value)throw new Error('Position must be between 0 and 100.');_position=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'positionAlign',extend({},baseObj,{get:function(){return _positionAlign},set:function(value){var setting=findAlignSetting(value);if(!setting)throw new SyntaxError('An invalid or illegal string was specified.');_positionAlign=setting,this.hasBeenReset=!0}})),Object.defineProperty(cue,'size',extend({},baseObj,{get:function(){return _size},set:function(value){if(0>value||100<value)throw new Error('Size must be between 0 and 100.');_size=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,'align',extend({},baseObj,{get:function(){return _align},set:function(value){var setting=findAlignSetting(value);if(!setting)throw new SyntaxError('An invalid or illegal string was specified.');_align=setting,this.hasBeenReset=!0}})),cue.displayState=void 0}if(null!=optionalSelf&&optionalSelf.VTTCue)return self.VTTCue;var AllowedDirections=['','lr','rl'],AllowedAlignments=['start','middle','end','left','right'];return VTTCue.prototype.getCueAsHTML=function(){var WebVTT=self.WebVTT;return WebVTT.convertCueToDOMTree(self,this.text)},VTTCue}(),StringDecoder=function(){function StringDecoder(){}var _proto=StringDecoder.prototype;return _proto.decode=function(data){if(!data)return'';if('string'!=typeof data)throw new Error('Error - expected string data.');return decodeURIComponent(encodeURIComponent(data))},StringDecoder}(),Settings=function(){function Settings(){this.values=Object.create(null)}var _proto2=Settings.prototype;return _proto2.set=function(k,v){this.get(k)||''===v||(this.values[k]=v)},_proto2.get=function(k,dflt,defaultKey){return defaultKey?this.has(k)?this.values[k]:dflt[defaultKey]:this.has(k)?this.values[k]:dflt},_proto2.has=function(k){return k in this.values},_proto2.alt=function(k,v,a){for(var n=0;n<a.length;++n)if(v===a[n]){this.set(k,v);break}},_proto2.integer=function(k,v){/^-?\d+$/.test(v)&&this.set(k,parseInt(v,10))},_proto2.percent=function(k,v){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(v)){var percent=parseFloat(v);if(0<=percent&&100>=percent)return this.set(k,percent),!0}return!1},Settings}(),defaults=new VTTCue(0,0,''),center='middle'===defaults.align?'middle':'center',VTTParser=function(){function VTTParser(){this.state='INITIAL',this.buffer='',this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var _proto3=VTTParser.prototype;return _proto3.parse=function(data){function collectNextLine(){var buffer=_this.buffer,pos=0;for(buffer=fixLineBreaks(buffer);pos<buffer.length&&'\r'!==buffer[pos]&&'\n'!==buffer[pos];)++pos;var line=buffer.slice(0,pos);return'\r'===buffer[pos]&&++pos,'\n'===buffer[pos]&&++pos,_this.buffer=buffer.slice(pos),line}function parseHeader(input){parseOptions(input,function(){},/:/)}var _this=this;data&&(_this.buffer+=_this.decoder.decode(data,{stream:!0}));try{var line='';if('INITIAL'===_this.state){if(!/\r\n|\n/.test(_this.buffer))return this;line=collectNextLine();var m=line.match(/^(ïûÿ)?WEBVTT([ \t].*)?$/);if(!(null!=m&&m[0]))throw new Error('Malformed WebVTT signature.');_this.state='HEADER'}for(var alreadyCollectedLine=!1;_this.buffer;){if(!/\r\n|\n/.test(_this.buffer))return this;switch(alreadyCollectedLine?alreadyCollectedLine=!1:line=collectNextLine(),_this.state){case'HEADER':/:/.test(line)?parseHeader(line):!line&&(_this.state='ID');continue;case'NOTE':line||(_this.state='ID');continue;case'ID':if(/^NOTE($|[ \t])/.test(line)){_this.state='NOTE';break}if(!line)continue;if(_this.cue=new VTTCue(0,0,''),_this.state='CUE',-1===line.indexOf('-->')){_this.cue.id=line;continue}case'CUE':if(!_this.cue){_this.state='BADCUE';continue}try{parseCue(line,_this.cue,_this.regionList)}catch(e){_this.cue=null,_this.state='BADCUE';continue}_this.state='CUETEXT';continue;case'CUETEXT':{var hasSubstring=-1!==line.indexOf('-->');if(!line||hasSubstring&&(alreadyCollectedLine=!0)){_this.oncue&&_this.cue&&_this.oncue
1(_this.cue),_this.cue=null,_this.state='ID';continue}if(null===_this.cue)continue;_this.cue.text&&(_this.cue.text+='\n'),_this.cue.text+=line}continue;case'BADCUE':line||(_this.state='ID');}}}catch(e){'CUETEXT'===_this.state&&_this.cue&&_this.oncue&&_this.oncue(_this.cue),_this.cue=null,_this.state='INITIAL'===_this.state?'BADWEBVTT':'BADCUE'}return this},_proto3.flush=function(){var _this=this;try{if((_this.cue||'HEADER'===_this.state)&&(_this.buffer+='\n\n',_this.parse()),'INITIAL'===_this.state||'BADWEBVTT'===_this.state)throw new Error('Malformed WebVTT signature.')}catch(e){_this.onparsingerror&&_this.onparsingerror(e)}return _this.onflush&&_this.onflush(),this},VTTParser}(),LINEBREAKS=/\r\n|\n\r|\n|\r/g,startsWith=function(inputString,searchString,position){return void 0===position&&(position=0),inputString.slice(position,position+searchString.length)===searchString},cueString2millis=function(timeString){var ts=parseInt(timeString.slice(-3)),secs=parseInt(timeString.slice(-6,-4)),mins=parseInt(timeString.slice(-9,-7)),hours=9<timeString.length?parseInt(timeString.substring(0,timeString.indexOf(':'))):0;if(!isFiniteNumber(ts)||!isFiniteNumber(secs)||!isFiniteNumber(mins)||!isFiniteNumber(hours))throw Error('Malformed X-TIMESTAMP-MAP: Local:'+timeString);return ts+=1e3*secs,ts+=60000*mins,ts+=3600000*hours,ts},hash=function(text){for(var hash=5381,i=text.length;i;)hash=33*hash^text.charCodeAt(--i);return(hash>>>0).toString()},calculateOffset=function(vttCCs,cc,presentationTime){var currCC=vttCCs[cc],prevCC=vttCCs[currCC.prevCC];if(!prevCC||!prevCC.new&&currCC.new)return vttCCs.ccOffset=vttCCs.presentationOffset=currCC.start,void(currCC.new=!1);for(;null!=(_prevCC=prevCC)&&_prevCC.new;){var _prevCC;vttCCs.ccOffset+=currCC.start-prevCC.start,currCC.new=!1,currCC=prevCC,prevCC=vttCCs[currCC.prevCC]}vttCCs.presentationOffset=presentationTime},IMSC1_CODEC='stpp.ttml.im1t',HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:'start',center:'center',right:'end',start:'start',end:'end'},TimelineController=function(){function TimelineController(hls){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=hls,this.config=hls.config,this.Cues=hls.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),hls.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),hls.on(Events.FRAG_LOADING,this.onFragLoading,this),hls.on(Events.FRAG_LOADED,this.onFragLoaded,this),hls.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),hls.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),hls.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),hls.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),hls.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}var _proto=TimelineController.prototype;return _proto.destroy=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),hls.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUp
1dated,this),hls.off(Events.FRAG_LOADING,this.onFragLoading,this),hls.off(Events.FRAG_LOADED,this.onFragLoaded,this),hls.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),hls.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),hls.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),hls.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),hls.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0},_proto.initCea608Parsers=function(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){var channel1=new OutputFilter(this,'textTrack1'),channel2=new OutputFilter(this,'textTrack2'),channel3=new OutputFilter(this,'textTrack3'),channel4=new OutputFilter(this,'textTrack4');this.cea608Parser1=new Cea608Parser(1,channel1,channel2),this.cea608Parser2=new Cea608Parser(3,channel3,channel4)}},_proto.addCues=function(trackName,startTime,endTime,screen,cueRanges){for(var merged=!1,i=cueRanges.length;i--;){var cueRange=cueRanges[i],overlap=intersection(cueRange[0],cueRange[1],startTime,endTime);if(0<=overlap&&(cueRange[0]=Math.min(cueRange[0],startTime),cueRange[1]=Math.max(cueRange[1],endTime),merged=!0,.5<overlap/(endTime-startTime)))return}if(merged||cueRanges.push([startTime,endTime]),this.config.renderTextTracksNatively){var track=this.captionsTracks[trackName];this.Cues.newCue(track,startTime,endTime,screen)}else{var cues=this.Cues.newCue(null,startTime,endTime,screen);this.hls.trigger(Events.CUES_PARSED,{type:'captions',cues:cues,track:trackName})}},_proto.onInitPtsFound=function(event,_ref){var _this=this,frag=_ref.frag,id=_ref.id,initPTS=_ref.initPTS,timescale=_ref.timescale,unparsedVttFrags=this.unparsedVttFrags;'main'===id&&(this.initPTS[frag.cc]={baseTime:initPTS,timescale:timescale}),unparsedVttFrags.length&&(this.unparsedVttFrags=[],unparsedVttFrags.forEach(function(frag){_this.onFragLoaded(Events.FRAG_LOADED,frag)}))},_proto.getExistingTrack=function(label,language){var media=this.media;if(media)for(var i=0,textTrack;i<media.textTracks.length;i++)if(textTrack=media.textTracks[i],canReuseVttTextTrack(textTrack,{name:label,lang:language,attrs:{}}))return textTrack;return null},_proto.createCaptionsTrack=function(trackName){this.config.renderTextTracksNatively?this.createNativeTrack(trackName):this.createNonNativeTrack(trackName)},_proto.createNativeTrack=function(trackName){if(!this.captionsTracks[trackName]){var captionsProperties=this.captionsProperties,captionsTracks=this.captionsTracks,media=this.media,_captionsProperties$t=captionsProperties[trackName],label=_captionsProperties$t.label,languageCode=_captionsProperties$t.languageCode,existingTrack=this.getExistingTrack(label,languageCode);if(!existingTrack){var textTrack=this.createTextTrack('captions',label,languageCode);textTrack&&(textTrack[trackName]=!0,captionsTracks[trackName]=textTrack)}else captionsTracks[trackName]=existingTrack,clearCurrentCues(captionsTracks[trackName]),sendAddTrackEvent(captionsTracks[trackName],media)}},_proto.createNonNativeTrack=function(trackName){if(!this.nonNativeCaptionsTracks[trackName]){var trackProperties=this.captionsProperties[trackName];if(trackProperties){var label=trackProperties.label,track={_id:trackName,label:label,kind:'captions',default:!!trackProperties.media&&!!trackProperties.media.default,closedCaptions:trackProperties.media};this.nonNativeCaptionsTracks[trackName]=track,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[track]})}}},_proto.createTextTrack=function(kind,label,lang){var media=this.media;return media?media.addTextTrack(kind,label,lang):void 0},_proto.onMediaAttaching=function(event,data){this.media=data.media,this._cleanTracks()},_proto.onMediaDetaching=function(){var captionsTracks=this.captionsTracks;
1Object.keys(captionsTracks).forEach(function(trackName){clearCurrentCues(captionsTracks[trackName]),delete captionsTracks[trackName]}),this.nonNativeCaptionsTracks={}},_proto.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},_proto._cleanTracks=function(){var media=this.media;if(media){var textTracks=media.textTracks;if(textTracks)for(var i=0;i<textTracks.length;i++)clearCurrentCues(textTracks[i])}},_proto.onSubtitleTracksUpdated=function(event,data){var _this2=this,tracks=data.subtitleTracks||[],hasIMSC1=tracks.some(function(track){return track.textCodec===IMSC1_CODEC});if(this.config.enableWebVTT||hasIMSC1&&this.config.enableIMSC1){var listIsIdentical=subtitleOptionsIdentical(this.tracks,tracks);if(listIsIdentical)return void(this.tracks=tracks);if(this.textTracks=[],this.tracks=tracks,this.config.renderTextTracksNatively){var media=this.media,inUseTracks=media?filterSubtitleTracks(media.textTracks):null;if(this.tracks.forEach(function(track){var textTrack;if(inUseTracks){for(var inUseTrack=null,i=0;i<inUseTracks.length;i++)if(inUseTracks[i]&&canReuseVttTextTrack(inUseTracks[i],track)){inUseTrack=inUseTracks[i],inUseTracks[i]=null;break}inUseTrack&&(textTrack=inUseTrack)}if(textTrack)clearCurrentCues(textTrack);else{var textTrackKind=captionsOrSubtitlesFromCharacteristics(track);textTrack=_this2.createTextTrack(textTrackKind,track.name,track.lang),textTrack&&(textTrack.mode='disabled')}textTrack&&_this2.textTracks.push(textTrack)}),null!=inUseTracks&&inUseTracks.length){var unusedTextTracks=inUseTracks.filter(function(t){return null!==t}).map(function(t){return t.label});unusedTextTracks.length&&logger.warn('Media element contains unused subtitle tracks: '+unusedTextTracks.join(', ')+'. Replace media element for each source to clear TextTracks and captions menu.')}}else if(this.tracks.length){var tracksList=this.tracks.map(function(track){return{label:track.name,kind:track.type.toLowerCase(),default:track.default,subtitleTrack:track}});this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:tracksList})}}},_proto.onManifestLoaded=function(event,data){var _this3=this;this.config.enableCEA708Captions&&data.captions&&data.captions.forEach(function(captionsTrack){var instreamIdMatch=/(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);if(instreamIdMatch){var trackName='textTrack'+instreamIdMatch[1],trackProperties=_this3.captionsProperties[trackName];trackProperties&&(trackProperties.label=captionsTrack.name,captionsTrack.lang&&(trackProperties.languageCode=captionsTrack.lang),trackProperties.media=captionsTrack)}})},_proto.closedCaptionsForLevel=function(frag){var level=this.hls.levels[frag.level];return null==level?void 0:level.attrs['CLOSED-CAPTIONS']},_proto.onFragLoading=function(event,data){if(this.enabled&&data.frag.type===PlaylistLevelType.MAIN){var cea608Parser1=this.cea608Parser1,cea608Parser2=this.cea608Parser2,lastSn=this.lastSn,_data$frag=data.frag,cc=_data$frag.cc,sn=_data$frag.sn,partIndex=null==(_data$part$index=null==(_data$part=data.part)?void 0:_data$part.index)?-1:_data$part$index,_data$part$index,_data$part;cea608Parser1&&cea608Parser2&&(sn!==lastSn+1||sn===lastSn&&partIndex!==this.lastPartIndex+1||cc!==this.lastCc)&&(cea608Parser1.reset(),cea608Parser2.reset()),this.lastCc=cc,this.lastSn=sn,this.lastPartIndex=partIndex}},_proto.onFragLoaded=function(event,data){var frag=data.frag,payload=data.payload;if(frag.type===PlaylistLevelType.SUBTITLE)if(payload.byteLength){var decryptData=frag.decryptdata,decrypted='stats'in data;if(null==decryptData||!decryptData.encrypted||decrypted){var trackPlaylistMedia=this.tracks[frag.level],vttCCs=this.vttCCs;vttCCs[frag.cc]||(vttCCs[frag.cc]={start:frag.start,prevCC:this.prevCC,new:!0},this.prevCC=frag.cc),trackPlaylistMedia&&trackPlaylistMedia.textCodec===IMSC1_CODEC?this._parseIMSC1(frag,payload):this._parseVTTs(data)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:frag,error:new Error('Empty subt
1itle payload')})},_proto._parseIMSC1=function(frag,payload){var _this4=this,hls=this.hls;parseIMSC1(payload,this.initPTS[frag.cc],function(cues){_this4._appendCues(cues,frag.level),hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:frag})},function(error){logger.log('Failed to parse IMSC1: '+error),hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:frag,error:error})})},_proto._parseVTTs=function(data){var _this5=this,frag=data.frag,payload=data.payload,initPTS=this.initPTS,unparsedVttFrags=this.unparsedVttFrags,maxAvCC=initPTS.length-1,_frag$initSegment;if(!initPTS[frag.cc]&&-1==maxAvCC)return void unparsedVttFrags.push(data);var hls=this.hls,payloadWebVTT=null!=(_frag$initSegment=frag.initSegment)&&_frag$initSegment.data?appendUint8Array(frag.initSegment.data,new Uint8Array(payload)):payload;parseWebVTT(payloadWebVTT,this.initPTS[frag.cc],this.vttCCs,frag.cc,frag.start,function(cues){_this5._appendCues(cues,frag.level),hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:frag})},function(error){var missingInitPTS='Missing initPTS for VTT MPEGTS'===error.message;missingInitPTS?unparsedVttFrags.push(data):_this5._fallbackToIMSC1(frag,payload),logger.log('Failed to parse VTT cue: '+error),missingInitPTS&&maxAvCC>frag.cc||hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:frag,error:error})})},_proto._fallbackToIMSC1=function(frag,payload){var _this6=this,trackPlaylistMedia=this.tracks[frag.level];trackPlaylistMedia.textCodec||parseIMSC1(payload,this.initPTS[frag.cc],function(){trackPlaylistMedia.textCodec=IMSC1_CODEC,_this6._parseIMSC1(frag,payload)},function(){trackPlaylistMedia.textCodec='wvtt'})},_proto._appendCues=function(cues,fragLevel){var hls=this.hls;if(this.config.renderTextTracksNatively){var textTrack=this.textTracks[fragLevel];if(!textTrack||'disabled'===textTrack.mode)return;cues.forEach(function(cue){return addCueToTrack(textTrack,cue)})}else{var currentTrack=this.tracks[fragLevel];if(!currentTrack)return;var track=currentTrack.default?'default':'subtitles'+fragLevel;hls.trigger(Events.CUES_PARSED,{type:'subtitles',cues:cues,track:track})}},_proto.onFragDecrypted=function(event,data){var frag=data.frag;frag.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,data)},_proto.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},_proto.onFragParsingUserdata=function(event,data){this.initCea608Parsers();var cea608Parser1=this.cea608Parser1,cea608Parser2=this.cea608Parser2;if(this.enabled&&cea608Parser1&&cea608Parser2){var frag=data.frag,samples=data.samples;if(frag.type!==PlaylistLevelType.MAIN||'NONE'!==this.closedCaptionsForLevel(frag))for(var i=0,ccBytes;i<samples.length;i++)if(ccBytes=samples[i].bytes,ccBytes){var ccdatas=this.extractCea608Data(ccBytes);cea608Parser1.addData(samples[i].pts,ccdatas[0]),cea608Parser2.addData(samples[i].pts,ccdatas[1])}}},_proto.onBufferFlushing=function(event,_ref2){var startOffset=_ref2.startOffset,endOffset=_ref2.endOffset,endOffsetSubtitles=_ref2.endOffsetSubtitles,type=_ref2.type,media=this.media;if(media&&!(media.currentTime<endOffset)){if(!type||'video'===type){var captionsTracks=this.captionsTracks;
1Object.keys(captionsTracks).forEach(function(trackName){return removeCuesInRange(captionsTracks[trackName],startOffset,endOffset)})}if(this.config.renderTextTracksNatively&&0===startOffset&&void 0!==endOffsetSubtitles){var textTracks=this.textTracks;Object.keys(textTracks).forEach(function(trackName){return removeCuesInRange(textTracks[trackName],startOffset,endOffsetSubtitles)})}}},_proto.extractCea608Data=function(byteArray){for(var actualCCBytes=[[],[]],count=31&byteArray[0],position=2,j=0;j<count;j++){var tmpByte=byteArray[position++],ccbyte1=127&byteArray[position++],ccbyte2=127&byteArray[position++];if(0!=ccbyte1||0!=ccbyte2){if(0!=(4&tmpByte)){var ccType=3&tmpByte;(0==ccType||1==ccType)&&(actualCCBytes[ccType].push(ccbyte1),actualCCBytes[ccType].push(ccbyte2))}}}return actualCCBytes},TimelineController}(),CapLevelController=function(){function CapLevelController(hls){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=hls,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var _proto=CapLevelController.prototype;return _proto.setStreamController=function(streamController){this.streamController=streamController},_proto.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},_proto.registerListeners=function(){var hls=this.hls;hls.on(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),hls.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)},_proto.unregisterListener=function(){var hls=this.hls;hls.off(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),hls.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)},_proto.onFpsDropLevelCapping=function(event,data){var level=this.hls.levels[data.droppedLevel];this.isLevelAllowed(level)&&this.restrictedLevels.push({bitrate:level.bitrate,height:level.height,width:level.width})},_proto.onMediaAttaching=function(event,data){this.media=data.media instanceof HTMLVideoElement?data.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},_proto.onManifestParsed=function(event,data){var hls=this.hls;this.restrictedLevels=[],this.firstLevel=data.firstLevel,hls.config.capLevelToPlayerSize&&data.video&&this.startCapping()},_proto.onLevelsUpdated=function(){this.timer&&isFiniteNumber(this.autoLevelCapping)&&this.detectPlayerSize()},_proto.onBufferCodecs=function(event,data){var hls=this.hls;hls.config.capLevelToPlayerSize&&data.video&&this.startCapping()},_proto.onMediaDetaching=function(){this.stopCapping()},_proto.detectPlayerSize=function(){if(this.media){if(0>=this.mediaHeight||0>=this.mediaWidth)return void(this.clientRect=null);var levels=this.hls.levels;if(levels.length){var hls=this.hls,maxLevel=this.getMaxLevel(levels.length-1);maxLevel!==this.autoLevelCapping&&logger.log('Setting autoLevelCapping to '+maxLevel+': '+levels[maxLevel].height+'p@'+levels[maxLevel].bitrate+' for media '+this.mediaWidth+'x'+this.mediaHeight),hls.autoLevelCapping=maxLevel,hls.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=hls.autoLevelCapping}}},_proto.getMaxLevel=function(capLevelIndex){var _this=this,levels=this.hls.levels;if(!levels.length)return-1;var validLevels=levels.filter(function(level,index){return _this.isLevelAllowed(level)&&index<=capLevelIndex});return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(validLevels,this.mediaWidth,this.mediaHeight)},_proto.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},_proto.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},_proto.getDimensions=function(){if(this.clientRect)return this.clientRect;var media=this.media,boundsRect={width:0,height:0};if(media){var clientRect=media.getBoundingClientRect();boundsRect.width=clientRect.width,boundsRect.height=clientRect.height,boundsRect.width||boundsRect.height||(boundsRect.width=clientRect.right-clientRect.left||media.width||0,boundsRect.height=clientRect.bottom-clientRect.top||media.height||0)}return this.clientRect=boundsRect,boundsRect},_proto.isLevelAllowed=function(level){var restrictedLevels=this.restrictedLevels;return!restrictedLevels.some(function(restrictedLevel){return level.bitrate===restrictedLevel.bitrate&&level.width===restrictedLevel.width&&level.height===restrictedLevel.height})},CapLevelController.getMaxLevelByMediaSize=function(levels,width,height){if(!(null!=levels&&levels.length))return-1;for(var atGreatestBandwidth=function(curLevel,nextLevel){return!nextLevel||curLevel.width!==nextLevel.width||curLevel.height!==nextLevel.height},maxLevelIndex=levels.length-1,squareSize=Math.max(width,height),i=0,level;i<levels.length;i+=1)if(level=levels[i],(level.width>=squareSize||level.height>=squareSize)&&atGreatestBandwidth(level,levels[i+1])){maxLevelIndex=i;break}return maxLevelIndex},_createClass(CapLevelController,[{key:'mediaWidth',get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:'mediaHeight',get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:'contentScaleFactor',get:function(){var pixelRatio=1;if(!this.hls.config.ignoreDevicePixelRatio)try{pixelRatio=self.devicePixelRatio}catch(e){}return pixelRatio}}]),CapLevelController}(),FPSController=function(){function FPSController(hls){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=hls,this.registerListeners()}var _proto=FPSController.prototype;return _proto.setStreamController=function(streamController){this.streamController=streamController},_proto.registerListeners=function(){this.hls.on(Events.MEDIA_ATTA
1CHING,this.onMediaAttaching,this)},_proto.unregisterListeners=function(){this.hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this)},_proto.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},_proto.onMediaAttaching=function(event,data){var config=this.hls.config;if(config.capLevelOnFPSDrop){var media=data.media instanceof self.HTMLVideoElement?data.media:null;this.media=media,media&&'function'==typeof media.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),config.fpsDroppedMonitoringPeriod)}},_proto.checkFPS=function(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,hls=this.hls;if(hls.trigger(Events.FPS_DROP,{currentDropped:currentDropped,currentDecoded:currentDecoded,totalDroppedFrames:droppedFrames}),0<1e3*currentDropped/currentPeriod&¤tDropped>hls.config.fpsDroppedMonitoringThreshold*currentDecoded){var currentLevel=hls.currentLevel;logger.warn('drop FPS ratio greater than max allowed value for currentLevel: '+currentLevel),0<currentLevel&&(-1===hls.autoLevelCapping||hls.autoLevelCapping>=currentLevel)&&(--currentLevel,hls.trigger(Events.FPS_DROP_LEVEL_CAPPING,{level:currentLevel,droppedLevel:hls.currentLevel}),hls.autoLevelCapping=currentLevel,this.streamController.nextLevelSwitch())}}this.lastTime=currentTime,this.lastDroppedFrames=droppedFrames,this.lastDecodedFrames=decodedFrames}},_proto.checkFPSInterval=function(){var video=this.media;if(video)if(this.isVideoPlaybackQualityAvailable){var videoPlaybackQuality=video.getVideoPlaybackQuality();this.checkFPS(video,videoPlaybackQuality.totalVideoFrames,videoPlaybackQuality.droppedVideoFrames)}else this.checkFPS(video,video.webkitDecodedFrameCount,video.webkitDroppedFrameCount)},FPSController}(),LOGGER_PREFIX='[eme]',EMEController=function(){function EMEController(hls){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=logger.debug.bind(logger,LOGGER_PREFIX),this.log=logger.log.bind(logger,LOGGER_PREFIX),this.warn=logger.warn.bind(logger,LOGGER_PREFIX),this.error=logger.error.bind(logger,LOGGER_PREFIX),this.hls=hls,this.config=hls.config,this.registerListeners()}var _proto=EMEController.prototype;return _proto.destroy=function(){this.unregisterListeners(),this.onMediaDetached();var config=this.config;config.requestMediaKeySystemAccessFunc=null,config.licenseXhrSetup=config.licenseResponseCallback=void 0,config.drmSystems=config.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null},_proto.registerListeners=function(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this)},_proto.unregisterListeners=function(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this)},_proto.getLicenseServerUrl=function(keySystem){var _this$config=this.config,drmSystems=_this$config.drmSystems,widevineLicenseUrl=_this$config.widevineLicenseUrl,keySystemConfiguration=drmSystems[keySystem];if(keySystemConfiguration)return keySystemConfiguration.licenseUrl;if(keySystem===KeySystems.WIDEVINE&&widevineLicenseUrl)return widevineLicenseUrl;throw new Error('no license server URL configured for key-system "'+keySystem+'"')},_proto.getServerCertificateUrl=function(keySystem){var drmSystems=this.config.drmSystems,keySystemConfiguration=drmSystems[keySystem];return keySystemConfiguration?keySystemConfiguration.serverCertificateUrl:void this.log('No Server Certificate in config.drmSystems["'+keySystem+'"]')},_proto.attemptKeySystemAccess=function(keySystemsToAttempt){var _this=this,levels=this.hls.levels,uniqueCodec=function(value,i,a){return!!value&&a.indexOf(value)===i},audioCodecs=levels.map(function(level){return level.audioCodec}
1).filter(uniqueCodec),videoCodecs=levels.map(function(level){return level.videoCodec}).filter(uniqueCodec);return 0===audioCodecs.length+videoCodecs.length&&videoCodecs.push('avc1.42e01e'),new Promise(function(resolve,reject){(function attempt(keySystems){var keySystem=keySystems.shift();_this.getMediaKeysPromise(keySystem,audioCodecs,videoCodecs).then(function(mediaKeys){return resolve({keySystem:keySystem,mediaKeys:mediaKeys})}).catch(function(error){keySystems.length?attempt(keySystems):error instanceof EMEKeyError?reject(error):reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_ACCESS,error:error,fatal:!0},error.message))})})(keySystemsToAttempt)})},_proto.requestMediaKeySystemAccess=function(keySystem,supportedConfigurations){var requestMediaKeySystemAccessFunc=this.config.requestMediaKeySystemAccessFunc;if('function'!=typeof requestMediaKeySystemAccessFunc){var errMessage='Configured requestMediaKeySystemAccess is not a function '+requestMediaKeySystemAccessFunc;return null===requestMediaKeySystemAccess&&'http:'===self.location.protocol&&(errMessage='navigator.requestMediaKeySystemAccess is not available over insecure protocol '+location.protocol),Promise.reject(new Error(errMessage))}return requestMediaKeySystemAccessFunc(keySystem,supportedConfigurations)},_proto.getMediaKeysPromise=function(keySystem,audioCodecs,videoCodecs){var _this2=this,mediaKeySystemConfigs=getSupportedMediaKeySystemConfigurations(keySystem,audioCodecs,videoCodecs,this.config.drmSystemOptions),keySystemAccessPromises=this.keySystemAccessPromises[keySystem],keySystemAccess=null==keySystemAccessPromises?void 0:keySystemAccessPromises.keySystemAccess;if(!keySystemAccess){this.log('Requesting encrypted media "'+keySystem+'" key-system access with config: '+JSON.stringify(mediaKeySystemConfigs)),keySystemAccess=this.requestMediaKeySystemAccess(keySystem,mediaKeySystemConfigs);var _keySystemAccessPromises=this.keySystemAccessPromises[keySystem]={keySystemAccess:keySystemAccess};return keySystemAccess.catch(function(error){_this2.log('Failed to obtain access to key-system "'+keySystem+'": '+error)}),keySystemAccess.then(function(mediaKeySystemAccess){_this2.log('Access for key-system "'+mediaKeySystemAccess.keySystem+'" obtained');var certificateRequest=_this2.fetchServerCertificate(keySystem);return _this2.log('Create media-keys for "'+keySystem+'"'),_keySystemAccessPromises.mediaKeys=mediaKeySystemAccess.createMediaKeys().then(function(mediaKeys){return _this2.log('Media-keys created for "'+keySystem+'"'),certificateRequest.then(function(certificate){return certificate?_this2.setMediaKeysServerCertificate(mediaKeys,keySystem,certificate):mediaKeys})}),_keySystemAccessPromises.mediaKeys.catch(function(error){_this2.error('Failed to create media-keys for "'+keySystem+'"}: '+error)}),_keySystemAccessPromises.mediaKeys})}return keySystemAccess.then(function(){return keySystemAccessPromises.mediaKeys})},_proto.createMediaKeySessionContext=function(_ref){var decryptdata=_ref.decryptdata,keySystem=_ref.keySystem,mediaKeys=_ref.mediaKeys;this.log('Creating key-system session "'+keySystem+'" keyId: '+Hex.hexDump(decryptdata.keyId||[]));var mediaKeysSession=mediaKeys.createSession(),mediaKeySessionContext={decryptdata:decryptdata,keySystem:keySystem,mediaKeys:mediaKeys,mediaKeysSession:mediaKeysSession,keyStatus:'status-pending'};return this.mediaKeySessions.push(mediaKeySessionContext),mediaKeySessionContext},_proto.renewKeySession=function(mediaKeySessionContext){var decryptdata=mediaKeySessionContext.decryptdata;if(decryptdata.pssh){var keySessionContext=this.createMediaKeySessionContext(mediaKeySessionContext),_keyId=this.getKeyIdString(decryptdata);this.keyIdToKeySessionPromise[_keyId]=this.generateRequestWithPreferredKeySession(keySessionContext,'cenc',decryptdata.pssh,'expired')}else this.warn('Could not renew expired session. Missing pssh initData.');this.removeSession(mediaKeySessionContext)},_proto.getKeyIdString=function(decryptdata){if(!decryptdata)throw new Error('Could not read keyId of undefined decryptdata');if(null===decryptdata.keyId)throw new Error('keyId is null');return Hex.hexDump(decryptdata.keyId)},_proto.updateKeySession=function(mediaKeySessionContext,data){var keySession=mediaKeySessionContext.mediaKeysSession,_mediaKeySessionConte;return this.log('Updating key-session "'+keySession.sessionId+'" for keyID '+Hex.hexDump((null==(_mediaKeySessionConte=mediaKeySessionContext.decryptdata)?void 0:_mediaKeySessionConte.keyId)||[])+'\n } (data length: '+(data?data.byteLength:data)+')'),keySession.update(data)},_proto.selectKeySystemFormat=function(frag){var keyFormats=Object.keys(frag.levelkeys||{});return this.keyFormatPromise||(this.log('Selecting key-system from fragment (sn: '+frag.sn+' '+frag.type+': '+frag.level
1+') key formats '+keyFormats.join(', ')),this.keyFormatPromise=this.getKeyFormatPromise(keyFormats)),this.keyFormatPromise},_proto.getKeyFormatPromise=function(keyFormats){var _this3=this;return new Promise(function(resolve,reject){var keySystemsInConfig=getKeySystemsForConfig(_this3.config),keySystemsToAttempt=keyFormats.map(keySystemFormatToKeySystemDomain).filter(function(value){return!!value&&-1!==keySystemsInConfig.indexOf(value)});return _this3.getKeySystemSelectionPromise(keySystemsToAttempt).then(function(_ref2){var keySystem=_ref2.keySystem,keySystemFormat=keySystemDomainToKeySystemFormat(keySystem);keySystemFormat?resolve(keySystemFormat):reject(new Error('Unable to find format for key-system "'+keySystem+'"'))}).catch(reject)})},_proto.loadKey=function(data){var _this4=this,decryptdata=data.keyInfo.decryptdata,keyId=this.getKeyIdString(decryptdata),keyDetails='(keyId: '+keyId+' format: "'+decryptdata.keyFormat+'" method: '+decryptdata.method+' uri: '+decryptdata.uri+')';this.log('Starting session for key '+keyDetails);var keySessionContextPromise=this.keyIdToKeySessionPromise[keyId];return keySessionContextPromise||(keySessionContextPromise=this.keyIdToKeySessionPromise[keyId]=this.getKeySystemForKeyPromise(decryptdata).then(function(_ref3){var keySystem=_ref3.keySystem,mediaKeys=_ref3.mediaKeys;return _this4.throwIfDestroyed(),_this4.log('Handle encrypted media sn: '+data.frag.sn+' '+data.frag.type+': '+data.frag.level+' using key '+keyDetails),_this4.attemptSetMediaKeys(keySystem,mediaKeys).then(function(){_this4.throwIfDestroyed();var keySessionContext=_this4.createMediaKeySessionContext({keySystem:keySystem,mediaKeys:mediaKeys,decryptdata:decryptdata});return _this4.generateRequestWithPreferredKeySession(keySessionContext,'cenc',decryptdata.pssh,'playlist-key')})}),keySessionContextPromise.catch(function(error){return _this4.handleError(error)})),keySessionContextPromise},_proto.throwIfDestroyed=function(){if(!this.hls)throw new Error('invalid state')},_proto.handleError=function(error){this.hls&&(this.error(error.message),error instanceof EMEKeyError?this.hls.trigger(Events.ERROR,error.data):this.hls.trigger(Events.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,error:error,fatal:!0}))},_proto.getKeySystemForKeyPromise=function(decryptdata){var keyId=this.getKeyIdString(decryptdata),mediaKeySessionContext=this.keyIdToKeySessionPromise[keyId];if(!mediaKeySessionContext){var keySystem=keySystemFormatToKeySystemDomain(decryptdata.keyFormat),keySystemsToAttempt=keySystem?[keySystem]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(keySystemsToAttempt)}return mediaKeySessionContext},_proto.getKeySystemSelectionPromise=function(keySystemsToAttempt){if(keySystemsToAttempt.length||(keySystemsToAttempt=getKeySystemsForConfig(this.config)),0===keySystemsToAttempt.length)throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},'Missing key-system license configuration options '+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(keySystemsToAttempt)},_proto._onMediaEncrypted=function(event){var _this5=this,initDataType=event.initDataType,initData=event.initData,logMessage='"'+event.type+'" event: init data type: "'+initDataType+'"';if(this.debug(logMessage),null!==initData){var keyId,keySystemDomain;if('sinf'===initDataType&&this.config.drmSystems[KeySystems.FAIRPLAY]){var json=bin2str(new Uint8Array(initData));try{var sinf=base64Decode(JSON.parse(json).sinf),tenc=parseSinf(new Uint8Array(sinf));if(!tenc)throw new Error('\'schm\' box missing or not cbcs/cenc with schi > tenc');keyId=tenc.subarray(8,24),keySystemDomain=KeySystems.FAIRPLAY}catch(error){return void this.warn(logMessage+' Failed to parse sinf: '+error)}}else{var psshResults=parseMultiPssh(initData),psshInfo=psshResults.filter(function(pssh){return pssh.systemId===KeySystemIds.WIDEVINE})[0];if(!psshInfo)return void(0===psshResults.length||psshResults.some(function(pssh){return!pssh.systemId})?this.warn(logMessage+' contains incomplete or invalid pssh data'):this.log('ignoring '+logMessage+' for '+psshResults.map(function(pssh){return keySystemIdToKeySystemDomain(pssh.systemId)}).join(',')+' pssh data in favor of playlist keys'));if(keySystemDomain=keySystemIdToKeySystemDomain(psshInfo.systemId),0===psshInfo.version&&psshInfo.data){var offset=psshInfo.data.length-22;keyId=psshInfo.data.subarray(offset,offset+16)}}if(keySystemDomain&&keyId){for(var keyIdHex=Hex.hexDump(keyId),keyIdToKeySessionPromise=this.keyIdToKeySessionPromise,mediaKeySessions=this.mediaKeySessions,keySessionContextPromise=keyIdToKeySessionPromise[keyIdHex],_loop=function(){var keyContext=mediaKeySessions[i],decryptdata=keyContext.decryptdata;if(!decryptdata.keyId)return 0;var oldKeyIdHex=Hex.hexDump(decryptdata.keyId);if(keyIdHex===oldKeyIdHex||-1!==decryptdata.uri.replace(/-/g,'').indexOf(keyIdHex))return(keySessionContextPromise=keyIdToKeySessionPromise[oldKeyIdHex],decryptdata.pssh)?1:(delete keyIdToKeySessionPromise[oldKeyIdHex],decryptdata.pssh=new Uint8Array(initData),decryptdata.keyId=keyId,keySessionContextPromise=keyIdToKeySessionPromise[keyIdHex]=keySessionContextPromise.then(function(){return _this5.generateRequestWithPreferredKeySession(keyContext,initDataType,initData,'encrypted-event-key-match')}),1)},i=0,_ret;i<mediaKeySessions.length&&(_ret=_loop(),0===_ret||1!==_ret);i++);keySessionContextPromise||(keySessionContextPromise=keyIdToKeySessionPromise[keyIdHex]=this.getKeySystemSelectionPromise([keySystemDomain]).then(function(_ref4){var keySystem=_ref4.keySystem,mediaKeys=_ref4.mediaKeys,_keySystemToKeySystem;_this5.throwIfDestroyed();var decryptdata=new LevelKey('ISO-23001-7',keyIdHex,null==(_keySystemToKeySystem=keySystemDomainToKeySystemFormat(keySystem))?'':_keySystemToKeySystem);return decryptdata.pssh=new Uint8Array(initData),decryptdata.keyId=keyId,_this5.attemptSetMediaKeys(keySystem,mediaKeys).then(function(){_this5.throwIfDestroyed();var keySessionContext=_this5.createMediaKeySessionContext({decryptdata:decryptdata,keySystem:keySystem,mediaKeys:mediaKeys});return _this5.generateRequestWithPreferredKeySession(keySessionContext,initDataType,initData,'encrypted-event-no-match')})})),keySessionContextPromise.catch(function(error){return _this5.handleError(error)})}}},_proto._onWaitingForKey=function(event){this.log('"'+event.type+'" event')},_proto.attemptSetMediaKeys=function(keySystem,mediaKeys){var _this6=this,queue=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+keySystem+'"');var setMediaKeysPromise=Promise.all(queue).then(function(){if(!_this6.media)throw new Error('Attempted to set mediaKeys without media element attached');return _this6.media.setMediaKeys(mediaKeys)});return this.setMediaKeysQueue.push(setMediaKeysPromise),setMediaKeysPromise.then(function(){_this6.log('Media-keys set for "'+keySystem+'"'),queue.push(setMediaKeysPromise),_this6.setMediaKeysQueue=_this6.setMediaKeysQueue.filter(function(p){return-1===queue.indexOf(p)})})},_proto.generateRequestWithPreferredKeySession=function(context,initDataType,initData,reason){var _this7=this,generateRequestFilter=null==(_this$config$drmSyste=this.config.drmSystems)||null==(_this$config$drmSyste2=_this$config$drmSyste[context.keySystem])?void 0:_this$config$drmSyste2.generateRequest,_this$config$drmSyste,_this$config$drmSyste2;if(generateRequestFilter)try{var mappedInitData=generateRequestFilter.call(this.hls,initDataType,initData,context);if(!mappedInitData)throw new Error('Invalid response from configured generateRequest filter');initDataType=mappedInitData.initDataType,initData=context.decryptdata.pssh=mappedInitData.initData?new Uint8Array(mappedInitData.initData):null}catch(error){var _this$hls;if(this.warn(error.message),null!=(_this$hls=this.hls)&&_this$hls.config.debug)throw error}if(null===initData)return this.log('Skipping key-session request for "'+reason+'" (no initData)'),Promise.resolve(context);var keyId=this.getKeyIdString(context.decryptdata);this.log('Generating key-session request for "'+reason+'": '+keyId+' (init data type: '+initDataType+' length: '+(initData?initData.byteLength:null)+')');var licenseStatus=new EventEmitter,onmessage=context._onmessage=function(event){var keySession=context.mediaKeysSession;if(!keySession)return void licenseStatus.emit('error',new Error('invalid state'));var messageType=event.messageType,message=event.message;_this7.log('"'+messageType+'" message event for session "'+keySession.sessionId+'" message size: '+message.byteLength),'license-request'===messageType||'license-renewal'===messageType?_this7.renewLicense(context,message).cat
1ch(function(error){_this7.handleError(error),licenseStatus.emit('error',error)}):'license-release'===messageType?context.keySystem===KeySystems.FAIRPLAY&&(_this7.updateKeySession(context,strToUtf8array('acknowledged')),_this7.removeSession(context)):_this7.warn('unhandled media key message type "'+messageType+'"')},onkeystatuseschange=context._onkeystatuseschange=function(){var keySession=context.mediaKeysSession;if(!keySession)return void licenseStatus.emit('error',new Error('invalid state'));_this7.onKeyStatusChange(context);var keyStatus=context.keyStatus;licenseStatus.emit('keyStatus',keyStatus),'expired'===keyStatus&&(_this7.warn(context.keySystem+' expired for key '+keyId),_this7.renewKeySession(context))};context.mediaKeysSession.addEventListener('message',onmessage),context.mediaKeysSession.addEventListener('keystatuseschange',onkeystatuseschange);var keyUsablePromise=new Promise(function(resolve,reject){licenseStatus.on('error',reject),licenseStatus.on('keyStatus',function(keyStatus){keyStatus.startsWith('usable')?resolve():'output-restricted'===keyStatus?reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},'HDCP level output restricted')):'internal-error'===keyStatus?reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'+keyStatus+'"')):'expired'===keyStatus?reject(new Error('key expired while generating request')):_this7.warn('unhandled key status change "'+keyStatus+'"')})});return context.mediaKeysSession.generateRequest(initDataType,initData).then(function(){var _context$mediaKeysSes;_this7.log('Request generated for key-session "'+(null==(_context$mediaKeysSes=context.mediaKeysSession)?void 0:_context$mediaKeysSes.sessionId)+'" keyId: '+keyId)}).catch(function(error){throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_SESSION,error:error,fatal:!1},'Error generating key-session request: '+error)}).then(function(){return keyUsablePromise}).catch(function(error){throw licenseStatus.removeAllListeners(),_this7.removeSession(context),error}).then(function(){return licenseStatus.removeAllListeners(),context})},_proto.onKeyStatusChange=function(mediaKeySessionContext){var _this8=this;mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach(function(status,keyId){_this8.log('key status change "'+status+'" for keyStatuses keyId: '+Hex.hexDump('buffer'in keyId?new Uint8Array(keyId.buffer,keyId.byteOffset,keyId.byteLength):new Uint8Array(keyId))+' session keyId: '+Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId||[]))+' uri: '+mediaKeySessionContext.decryptdata.uri),mediaKeySessionContext.keyStatus=status})},_proto.fetchServerCertificate=function(keySystem){var config=this.config,Loader=config.loader,certLoader=new Loader(config),url=this.getServerCertificateUrl(keySystem);return url?(this.log('Fetching server certificate for "'+keySystem+'"'),new Promise(function(resolve,reject){var loaderContext={responseType:'arraybuffer',url:url},loadPolicy=config.certLoadPolicy.default,loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};certLoader.load(loaderContext,loaderConfig,{onSuccess:function(response){resolve(response.data)},onError:function(response,contex,networkDetails){reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:networkDetails,response:_objectSpread2({url:loaderContext.url,data:void 0},response)},'"'+keySystem+'" certificate request failed ('+url+'). Status: '+response.code+' ('+response.text+')'))},onTimeout:function(stats,context,networkDetails){reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:networkDetails,response:{url:loaderContext.url,data:void 0}},'"'+keySystem+'" certificate request timed out ('+url+')'))},onAbort:function(){reject(new Error('aborted'))}})})):Promise.resolve()},_proto.setMediaKeysServerCertificate=function(mediaKeys,keySystem,cert){var _this9=this;return new Promise(function(resolve,reject){mediaKeys.setServerCertificate(cert).then(function(success){_this9.log('setServerCertificate '+(success?'success':'not supported by CDM')+' ('+(null==cert?void 0:cert.byteLength)+') on "'+keySystem+'"'),resolve(mediaKeys)}).catch(function(error){reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:error,fatal:!0},error.message))})})},_proto.renewLicense=function(context,keyMessage){var _this10=this;return this.requestLicense(context,new Uint8Array(keyMessage)).then(function(data){return _this10.updateKeySession(context,new Uint8Array(data)).catch(function(error){throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:error,fatal:!0},error.message)})})},_proto.unpackPlayReadyKeyMessage=function(xhr,licenseChallenge){var xmlString=String.fromCharCode.apply(null,new Uint16Array(licenseChallenge.buffer));if(!xmlString.includes('PlayReadyKeyMessage'))return xhr.setRequestHeader('Content-Type','text/xml; charset=utf-8'),licenseChallenge;
1var keyMessageXml=new DOMParser().parseFromString(xmlString,'application/xml'),headers=keyMessageXml.querySelectorAll('HttpHeader');if(0<headers.length)for(var i=0,len=headers.length,header;i<len;i++){var _header$querySelector,_header$querySelector2;header=headers[i];var name=null==(_header$querySelector=header.querySelector('name'))?void 0:_header$querySelector.textContent,_value=null==(_header$querySelector2=header.querySelector('value'))?void 0:_header$querySelector2.textContent;name&&_value&&xhr.setRequestHeader(name,_value)}var challengeElement=keyMessageXml.querySelector('Challenge'),challengeText=null==challengeElement?void 0:challengeElement.textContent;if(!challengeText)throw new Error('Cannot find <Challenge> in key message');return strToUtf8array(atob(challengeText))},_proto.setupLicenseXHR=function(xhr,url,keysListItem,licenseChallenge){var _this11=this,licenseXhrSetup=this.config.licenseXhrSetup;return licenseXhrSetup?Promise.resolve().then(function(){if(!keysListItem.decryptdata)throw new Error('Key removed');return licenseXhrSetup.call(_this11.hls,xhr,url,keysListItem,licenseChallenge)}).catch(function(error){if(!keysListItem.decryptdata)throw error;return xhr.open('POST',url,!0),licenseXhrSetup.call(_this11.hls,xhr,url,keysListItem,licenseChallenge)}).then(function(licenseXhrSetupResult){xhr.readyState||xhr.open('POST',url,!0);var finalLicenseChallenge=licenseXhrSetupResult?licenseXhrSetupResult:licenseChallenge;return{xhr:xhr,licenseChallenge:finalLicenseChallenge}}):(xhr.open('POST',url,!0),Promise.resolve({xhr:xhr,licenseChallenge:licenseChallenge}))},_proto.requestLicense=function(keySessionContext,licenseChallenge){var _this12=this,keyLoadPolicy=this.config.keyLoadPolicy.default;return new Promise(function(resolve,reject){var url=_this12.getLicenseServerUrl(keySessionContext.keySystem);_this12.log('Sending license request to URL: '+url);var xhr=new XMLHttpRequest;xhr.responseType='arraybuffer',xhr.onreadystatechange=function(){if(!_this12.hls||!keySessionContext.mediaKeysSession)return reject(new Error('invalid state'));if(4===xhr.readyState)if(200===xhr.status){_this12._requestLicenseFailureCount=0;var data=xhr.response;_this12.log('License received '+(data instanceof ArrayBuffer?data.byteLength:data));var licenseResponseCallback=_this12.config.licenseResponseCallback;if(licenseResponseCallback)try{data=licenseResponseCallback.call(_this12.hls,xhr,url,keySessionContext)}catch(error){_this12.error(error)}resolve(data)}else{var retryConfig=keyLoadPolicy.errorRetry,maxNumRetry=retryConfig?retryConfig.maxNumRetry:0;if(_this12._requestLicenseFailureCount++,_this12._requestLicenseFailureCount>maxNumRetry||400<=xhr.status&&500>xhr.status)reject(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:xhr,response:{url:url,data:void 0,code:xhr.status,text:xhr.statusText}},'License Request XHR failed ('+url+'). Status: '+xhr.status+' ('+xhr.statusText+')'));else{var attemptsLeft=maxNumRetry-_this12._requestLicenseFailureCount+1;_this12.warn('Retrying license request, '+attemptsLeft+' attempts left'),_this12.requestLicense(keySessionContext,licenseChallenge).then(resolve,reject)}}},keySessionContext.licenseXhr&&keySessionContext.licenseXhr.readyState!==XMLHttpRequest.DONE&&keySessionContext.licenseXhr.abort(),keySessionContext.licenseXhr=xhr,_this12.setupLicenseXHR(xhr,url,keySessionContext,licenseChallenge).then(function(_ref5){var xhr=_ref5.xhr,licenseChallenge=_ref5.licenseChallenge;keySessionContext.keySystem==KeySystems.PLAYREADY&&(licenseChallenge=_this12.unpackPlayReadyKeyMessage(xhr,licenseChallenge)),xhr.send(licenseChallenge)})})},_proto.onMediaAttached=function(event,data){if(this.config.emeEnabled){var media=data.media;this.media=media,media.addEventListener('encrypted',this.onMediaEncrypted),media.addEventListener('waitingforkey',this.onWaitingForKey)}},_proto.onMediaDetached=function(){var _this13=this,media=this.media,mediaKeysList=this.mediaKeySessions;media&&(media.removeEventListener('encrypted',this.onMediaEncrypted),media.removeEventListener('waitingforkey',this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();var keySessionCount=mediaKeysList.length;EMEController.CDMCleanupPromise=Promise.all(mediaKeysList.map(function(mediaKeySessionContext){return _this13.removeSession(mediaKeySessionContext)}
1).concat(null==media?void 0:media.setMediaKeys(null).catch(function(error){_this13.log('Could not clear media keys: '+error)}))).then(function(){keySessionCount&&(_this13.log('finished closing key sessions and clearing media keys'),mediaKeysList.length=0)}).catch(function(error){_this13.log('Could not close sessions and clear media keys: '+error)})},_proto.onManifestLoading=function(){this.keyFormatPromise=null},_proto.onManifestLoaded=function(event,_ref6){var sessionKeys=_ref6.sessionKeys;if(sessionKeys&&this.config.emeEnabled&&!this.keyFormatPromise){var keyFormats=sessionKeys.reduce(function(formats,sessionKey){return-1===formats.indexOf(sessionKey.keyFormat)&&formats.push(sessionKey.keyFormat),formats},[]);this.log('Selecting key-system from session-keys '+keyFormats.join(', ')),this.keyFormatPromise=this.getKeyFormatPromise(keyFormats)}},_proto.removeSession=function(mediaKeySessionContext){var _this14=this,mediaKeysSession=mediaKeySessionContext.mediaKeysSession,licenseXhr=mediaKeySessionContext.licenseXhr;if(mediaKeysSession){this.log('Remove licenses and keys and close session '+mediaKeysSession.sessionId),mediaKeySessionContext._onmessage&&(mediaKeysSession.removeEventListener('message',mediaKeySessionContext._onmessage),mediaKeySessionContext._onmessage=void 0),mediaKeySessionContext._onkeystatuseschange&&(mediaKeysSession.removeEventListener('keystatuseschange',mediaKeySessionContext._onkeystatuseschange),mediaKeySessionContext._onkeystatuseschange=void 0),licenseXhr&&licenseXhr.readyState!==XMLHttpRequest.DONE&&licenseXhr.abort(),mediaKeySessionContext.mediaKeysSession=mediaKeySessionContext.decryptdata=mediaKeySessionContext.licenseXhr=void 0;var index=this.mediaKeySessions.indexOf(mediaKeySessionContext);return-1<index&&this.mediaKeySessions.splice(index,1),mediaKeysSession.remove().catch(function(error){_this14.log('Could not remove session: '+error)}).then(function(){return mediaKeysSession.close()}).catch(function(error){_this14.log('Could not close session: '+error)})}},EMEController}();EMEController.CDMCleanupPromise=void 0;var EMEKeyError=function(_Error){function EMEKeyError(data,message){var _this15;return _this15=_Error.call(this,message)||this,_this15.data=void 0,data.error||(data.error=new Error(message)),_this15.data=data,data.err=data.error,_this15}return _inheritsLoose(EMEKeyError,_Error),EMEKeyError}(_wrapNativeSuper(Error)),CmObjectType;(function(CmObjectType){CmObjectType.MANIFEST='m',CmObjectType.AUDIO='a',CmObjectType.VIDEO='v',CmObjectType.MUXED='av',CmObjectType.INIT='i',CmObjectType.CAPTION='c',CmObjectType.TIMED_TEXT='tt',CmObjectType.KEY='k',CmObjectType.OTHER='o'})(CmObjectType||(CmObjectType={}));var CmStreamingFormat;(function(CmStreamingFormat){CmStreamingFormat.DASH='d',CmStreamingFormat.HLS='h',CmStreamingFormat.SMOOTH='s',CmStreamingFormat.OTHER='o'})(CmStreamingFormat||(CmStreamingFormat={}));var CmcdHeaderField;(function(CmcdHeaderField){CmcdHeaderField.OBJECT='CMCD-Object',CmcdHeaderField.REQUEST='CMCD-Request',CmcdHeaderField.SESSION='CMCD-Session',CmcdHeaderField.STATUS='CMCD-Status'})(CmcdHeaderField||(CmcdHeaderField={}));var CmcdHeaderMap=(_CmcdHeaderMap={},_CmcdHeaderMap[CmcdHeaderField.OBJECT]=['br','d','ot','tb'],_CmcdHeaderMap[CmcdHeaderField.REQUEST]=['bl','dl','mtp','nor','nrr','su'],_CmcdHeaderMap[CmcdHeaderField.SESSION]=['cid','pr','sf','sid','st','v'],_CmcdHeaderMap[CmcdHeaderField.STATUS]=['bs','rtp'],_CmcdHeaderMap),SfItem=function SfItem(value,params){this.value=void 0,this.params=void 0,Array.isArray(value)&&(value=value.map(function(v){return v instanceof SfItem?v:new SfItem(v)})),this.value=value,this.params=params},SfToken=function(description){this.description=void 0,this.description=description},DICT='Dict',BARE_ITEM='Bare Item',BOOLEAN='Boolean',BYTES='Byte Sequence',DECIMAL='Decimal',INTEGER='Integer',STRING_REGEX=/[\x00-\x1f\x7f]+/,TOKEN='Token',KEY='Key',STRING='String',isTokenField=function(key){return'ot'===key||'sf'===key||'st'===key},isValid=function(value){return'number'==typeof value?isFiniteNumber(value):null!=value&&''!==value&&!1!==value},toRounded=function(value){return Math.round(value)},toHundred=function(value){return 100*toRounded(value/100)},CmcdFormatters={br:toRounded,d:toRounded,bl:toHundred,dl:toHundred,mtp:toHundred,nor:function(value,options){return null!=options&&options.baseUrl&&(value=urlToRelativePath(value,options.baseUrl)),encodeURIComponent(value)},rtp:toHundred,tb:toRounded},CMCD_PARAM='CMCD',REGEX=/CMCD=[^&#]+/,CMCDController=function(){function CMCDController(hls){var _this=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){_this.initialized&&(_this.starved=!0),_this.buffering=!0},this.onPlaying=function(){_this.initialized||(_this.initialized=!0),_this.buffering=!1},this.applyPlaylistData=function(context){try{_this.apply(context,{ot:CmObjectType.MANIFEST,su:!_this.initialized})}catch(error){logger.warn('Could not generate manifest CMCD data.',error)}},this.applyFragmentData=function(context){try{var fragment=context.frag,level=_this.hls.levels[fragment.level],ot=_this.getObjectType(fragment),data={d:1e3*fragment.duration,ot:ot};(ot===CmObjectType.VIDEO||ot===CmObjectType.AUDIO||ot==CmObjectType.MUXED)&&(data.br=level.bitrate/1e3,data.tb=_this.getTopBandwidth(ot)/1e3,data.bl=_this.getBufferLength(ot)),_this.apply(context,data)}catch(error){logger.warn('Could not generate segment CMCD data.',error)}},this.hls=hls;var config=this.config=hls.config,cmcd=config.cmcd;null!=cmcd&&(config.pLoader=this.createPlaylistLoader(),config.fLoa
1der=this.createFragmentLoader(),this.sid=cmcd.sessionId||uuid(),this.cid=cmcd.contentId,this.useHeaders=!0===cmcd.useHeaders,this.includeKeys=cmcd.includeKeys,this.registerListeners())}var _proto=CMCDController.prototype;return _proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),hls.on(Events.BUFFER_CREATED,this.onBufferCreated,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),hls.off(Events.BUFFER_CREATED,this.onBufferCreated,this)},_proto.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null},_proto.onMediaAttached=function(event,data){this.media=data.media,this.media.addEventListener('waiting',this.onWaiting),this.media.addEventListener('playing',this.onPlaying)},_proto.onMediaDetached=function(){this.media&&(this.media.removeEventListener('waiting',this.onWaiting),this.media.removeEventListener('playing',this.onPlaying),this.media=null)},_proto.onBufferCreated=function(event,data){var _data$tracks$audio,_data$tracks$video;this.audioBuffer=null==(_data$tracks$audio=data.tracks.audio)?void 0:_data$tracks$audio.buffer,this.videoBuffer=null==(_data$tracks$video=data.tracks.video)?void 0:_data$tracks$video.buffer},_proto.createData=function(){var _this$media;return{v:1,sf:CmStreamingFormat.HLS,sid:this.sid,cid:this.cid,pr:null==(_this$media=this.media)?void 0:_this$media.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},_proto.apply=function(context,data){void 0===data&&(data={}),_extends(data,this.createData());var isVideo=data.ot===CmObjectType.INIT||data.ot===CmObjectType.VIDEO||data.ot===CmObjectType.MUXED;this.starved&&isVideo&&(data.bs=!0,data.su=!0,this.starved=!1),null==data.su&&(data.su=this.buffering);var includeKeys=this.includeKeys;includeKeys&&(data=Object.keys(data).reduce(function(acc,key){return includeKeys.includes(key)&&(acc[key]=data[key]),acc},{})),this.useHeaders?(!context.headers&&(context.headers={}),appendCmcdHeaders(context.headers,data)):context.url=appendCmcdQuery(context.url,data)},_proto.getObjectType=function(fragment){var type=fragment.type;return'subtitle'===type?CmObjectType.TIMED_TEXT:'initSegment'===fragment.sn?CmObjectType.INIT:'audio'===type?CmObjectType.AUDIO:'main'===type?this.hls.audioTracks.length?CmObjectType.VIDEO:CmObjectType.MUXED:void 0},_proto.getTopBandwidth=function(type){var bitrate=0,hls=this.hls,levels;if(type===CmObjectType.AUDIO)levels=hls.audioTracks;else{var max=hls.maxAutoLevel,len=-1<max?max+1:hls.levels.length;levels=hls.levels.slice(0,len)}for(var _iterator=_createForOfIteratorHelperLoose(levels),_step,level;!(_step=_iterator()).done;)level=_step.value,level.bitrate>bitrate&&(bitrate=level.bitrate);return 0<bitrate?bitrate:NaN},_proto.getBufferLength=function(type){var media=this.hls.media,buffer=type===CmObjectType.AUDIO?this.audioBuffer:this.videoBuffer;if(!buffer||!media)return NaN;var info=BufferHelper.bufferInfo(buffer,media.currentTime,this.config.maxBufferHole);return 1e3*info.len},_proto.createPlaylistLoader=function(){var pLoader=this.config.pLoader,apply=this.applyPlaylistData,Ctor=pLoader||this.config.loader;return function(){function CmcdPlaylistLoader(config){this.loader=void 0,this.loader=new Ctor(config)}var _proto2=CmcdPlaylistLoader.prototype;return _proto2.destroy=function(){this.loader.destroy()},_proto2.abort=function(){this.loader.abort()},_proto2.load=function(context,config,callbacks){apply(context),this.loader.load(context,config,callbacks)},_createClass(CmcdPlaylistLoader,[{key:'stats',get:function(){return this.loader.stats}},{key:'context',get:function(){return this.loader.context}}]),CmcdPlaylistLoader}()},_proto.createFragmentLoader=function(){var fLoader=this.config.fLoader,apply=this.applyFragmentData,Ctor=fLoader||this.config.loader;return function(){function CmcdFragmentLoader(config){this.loader=void 0,this.loader=new Ctor(config)}
1var _proto3=CmcdFragmentLoader.prototype;return _proto3.destroy=function(){this.loader.destroy()},_proto3.abort=function(){this.loader.abort()},_proto3.load=function(context,config,callbacks){apply(context),this.loader.load(context,config,callbacks)},_createClass(CmcdFragmentLoader,[{key:'stats',get:function(){return this.loader.stats}},{key:'context',get:function(){return this.loader.context}}]),CmcdFragmentLoader}()},CMCDController}(),ContentSteeringController=function(){function ContentSteeringController(hls){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId='.',this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=hls,this.log=logger.log.bind(logger,'[content-steering]:'),this.registerListeners()}var _proto=ContentSteeringController.prototype;return _proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),hls.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.on(Events.ERROR,this.onError,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls&&(hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),hls.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.off(Events.ERROR,this.onError,this))},_proto.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var ttl=1e3*this.timeToLoad-(performance.now()-this.updated);if(0<ttl)return void this.scheduleRefresh(this.uri,ttl)}this.loadSteeringManifest(this.uri)}},_proto.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},_proto.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},_proto.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},_proto.removeLevel=function(levelToRemove){var levels=this.levels;levels&&(this.levels=levels.filter(function(level){return level!==levelToRemove}))},_proto.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId='.',this.levels=this.audioTracks=this.subtitleTracks=null},_proto.onManifestLoaded=function(event,data){var contentSteering=data.contentSteering;null===contentSteering||(this.pathwayId=contentSteering.pathwayId,this.uri=contentSteering.uri,this.started&&this.startLoad())},_proto.onManifestParsed=function(event,data){this.audioTracks=data.audioTracks,this.subtitleTracks=data.subtitleTracks},_proto.onError=function(event,data){var errorAction=data.errorAction;if((null==errorAction?void 0:errorAction.action)===NetworkErrorAction.SendAlternateToPenaltyBox&&errorAction.flags===ErrorActionFlags.MoveAllAlternatesMatchingHost){var levels=this.levels,pathwayPriority=this.pathwayPriority,errorPathway=this.pathwayId;if(data.context){var _data$context=data.context,groupId=_data$context.groupId,_pathwayId=_data$context.pathwayId,type=_data$context.type;groupId&&levels?errorPathway=this.getPathwayForGroupId(groupId,type,errorPathway):_pathwayId&&(errorPathway=_pathwayId)}errorPathway in this.penalizedPathways||(this.penalizedPathways[errorPathway]=performance.now()),!pathwayPriority&&levels&&(pathwayPriority=levels.reduce(function(pathways,level){return-1===pathways.indexOf(level.pathwayId)&&pathways.push(level.pathwayId),pathways},[])),pathwayPriority&&1<pathwayPriority.length&&(this.updatePathwayPriority(pathwayPriority),errorAction.resolved=this.pathwayId!==errorPathway),errorAction.resolved||logger.warn('Could not resolve '+data.details+' ("'+data.error.message+'") with content-steering for Pathway: '+errorPathway+' levels: '+(levels?levels.length:levels)+' priorities: '+JSON.stringify(pathwayPriority)+' penalized: '+JSON.stringify(this.penalizedPathways))}},_proto.filterParsedLevels=function(levels){this.levels=levels;var pathwayLevels=this.getLevelsForPathway(this.pathwayId);if(0===pathwayLevels.length){var _pathwayId2=levels[0].pathwayId;this.log('No levels found in Pathway '+this.pathwayId+'. Setting initial Pathway to "'+_pathwayId2+'"'),pathwayLevels=this.getLevelsForPathway(_pathwayId2),this.pathwayId=_pathwayId2}return pathwayLevels.length!==levels.length&&this.log('Found '+pathwayLevels.length+'/'+levels.length+' levels in Pathway "'+this.pathwayId+'"'),pathwayLevels},_proto.getLevelsForPathway=function(pathwayId){return null===this.levels?[]:this.levels.filter(function(level){return pathwayId===level.pathwayId})},_proto.updatePathwayPriority=function(pathwayPriority){this.pathwayPriority=pathwayPriority;var penalizedPathways=this.penalizedPathways,now=performance.now(),levels;
1Object.keys(penalizedPathways).forEach(function(pathwayId){now-penalizedPathways[pathwayId]>3e5&&delete penalizedPathways[pathwayId]});for(var i=0,_pathwayId3;i<pathwayPriority.length;i++)if(_pathwayId3=pathwayPriority[i],!(_pathwayId3 in penalizedPathways)){if(_pathwayId3===this.pathwayId)return;var selectedIndex=this.hls.nextLoadLevel,selectedLevel=this.hls.levels[selectedIndex];if(levels=this.getLevelsForPathway(_pathwayId3),0<levels.length){this.log('Setting Pathway to "'+_pathwayId3+'"'),this.pathwayId=_pathwayId3,reassignFragmentLevelIndexes(levels),this.hls.trigger(Events.LEVELS_UPDATED,{levels:levels});var levelAfterChange=this.hls.levels[selectedIndex];selectedLevel&&levelAfterChange&&this.levels&&(levelAfterChange.attrs['STABLE-VARIANT-ID']!==selectedLevel.attrs['STABLE-VARIANT-ID']&&levelAfterChange.bitrate!==selectedLevel.bitrate&&this.log('Unstable Pathways change from bitrate '+selectedLevel.bitrate+' to '+levelAfterChange.bitrate),this.hls.nextLoadLevel=selectedIndex);break}}},_proto.getPathwayForGroupId=function(groupId,type,defaultPathway){for(var levels=this.getLevelsForPathway(defaultPathway).concat(this.levels||[]),i=0;i<levels.length;i++)if(type===PlaylistContextType.AUDIO_TRACK&&levels[i].hasAudioGroup(groupId)||type===PlaylistContextType.SUBTITLE_TRACK&&levels[i].hasSubtitleGroup(groupId))return levels[i].pathwayId;return defaultPathway},_proto.clonePathways=function(pathwayClones){var _this=this,levels=this.levels;if(levels){var audioGroupCloneMap={},subtitleGroupCloneMap={};pathwayClones.forEach(function(pathwayClone){var cloneId=pathwayClone.ID,baseId=pathwayClone['BASE-ID'],uriReplacement=pathwayClone['URI-REPLACEMENT'];if(!levels.some(function(level){return level.pathwayId===cloneId})){var clonedVariants=_this.getLevelsForPathway(baseId).map(function(baseLevel){var attributes=new AttrList(baseLevel.attrs);attributes['PATHWAY-ID']=cloneId;var clonedAudioGroupId=attributes.AUDIO&&attributes.AUDIO+'_clone_'+cloneId,clonedSubtitleGroupId=attributes.SUBTITLES&&attributes.SUBTITLES+'_clone_'+cloneId;clonedAudioGroupId&&(audioGroupCloneMap[attributes.AUDIO]=clonedAudioGroupId,attributes.AUDIO=clonedAudioGroupId),clonedSubtitleGroupId&&(subtitleGroupCloneMap[attributes.SUBTITLES]=clonedSubtitleGroupId,attributes.SUBTITLES=clonedSubtitleGroupId);var url=performUriReplacement(baseLevel.uri,attributes['STABLE-VARIANT-ID'],'PER-VARIANT-URIS',uriReplacement),clonedLevel=new Level({attrs:attributes,audioCodec:baseLevel.audioCodec,bitrate:baseLevel.bitrate,height:baseLevel.height,name:baseLevel.name,url:url,videoCodec:baseLevel.videoCodec,width:baseLevel.width});if(baseLevel.audioGroups)for(var i=1;i<baseLevel.audioGroups.length;i++)clonedLevel.addGroupId('audio',baseLevel.audioGroups[i]+'_clone_'+cloneId);if(baseLevel.subtitleGroups)for(var _i=1;_i<baseLevel.subtitleGroups.length;_i++)clonedLevel.addGroupId('text',baseLevel.subtitleGroups[_i]+'_clone_'+cloneId);return clonedLevel});levels.push.apply(levels,clonedVariants),cloneRenditionGroups(_this.audioTracks,audioGroupCloneMap,uriReplacement,cloneId),cloneRenditionGroups(_this.subtitleTracks,subtitleGroupCloneMap,uriReplacement,cloneId)}})}},_proto.loadSteeringManifest=function(uri){var _this2=this,config=this.hls.config,Loader=config.loader;this.loader&&this.loader.destroy(),this.loader=new Loader(config);var url;try{url=new self.URL(uri)}catch(error){return this.enabled=!1,void this.log('Failed to parse Steering Manifest URI: '+uri)}if('data:'!==url.protocol){var throughput=0|(this.hls.bandwidthEstimate||config.abrEwmaDefaultEstimate);url.searchParams.set('_HLS_pathway',this.pathwayId),url.searchParams.set('_HLS_throughput',''+throughput)}var context={responseType:'json',url:url.href},loadPolicy=config.steeringManifestLoadPolicy.default,legacyRetryCompatibility=loadPolicy.errorRetry||loadPolicy.timeoutRetry||{},loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:legacyRetryCompatibility.maxNumRetry||0,retryDelay:legacyRetryCompatibility.retryDelayMs||0,maxRetryDelay:legacyRetryCompatibility.maxRetryDelayMs||0};this.log('Requesting steering manifest: '+url),this.loader.load(context,loaderConfig,{onSuccess:function(response,stats,context){_this2.log('Loaded steering manifest: "'+url+'"');var steeringData=response.data;if(1!==steeringData.VERSION)return void _this2.log('Steering VERSION '+steeringData.VERSION+' not supported!');_this2.updated=performance.now(),_this2.timeToLoad=steeringData.TTL;var reloadUri=steeringData['RELOAD-URI'],pathwayClones=steeringData['PATHWAY-CLONES'],pathwayPriority=steeringData['PATHWAY-PRIORITY'];if(reloadUri)try{_this2.uri=new self.URL(reloadUri,url).href}catch(error){return _this2.enabled=!1,void _this2.log('Failed to parse Steering Manifest RELOAD-URI: '+reloadUri)}_this2.scheduleRefresh(_this2.uri||context.url),pathwayClones&&_this2.clonePathways(pathwayClones);var loadedSteeringData={steeringManifest:steeringData,url:url.toString()};_this2.hls.trigger(Events.STEERING_MANIFEST_LOADED,loadedSteeringData),pathwayPriority&&_this2.updatePathwayPriority(pathwayPriority)},onError:function(error,context){if(_this2.log('Error loading steering manifest: '+error.code+' '+error.text+' ('+context.url+')'),_this2.stopLoad(),410===error.code)return _this2.enabled=!1,void _this2.log('Steering manifest '+context.url+' no longer available');var ttl=1e3*_this2.timeToLoad;if(429===error.code){var loader=_this2.loader;if('function'==typeof(null==loader?void 0:loader.getResponseHeader)){var retryAfter=loader.getResponseHeader('Retry-After');retryAfter&&(ttl=1e3*parseFloat(retryAfter))}return void _this2.log('Steering manifest '+context.url+' rate limited')}_this2.scheduleRefresh(_this2.uri||context.url,ttl)},onTimeout:function(stats,context){_this2.log('Timeout loading steering manifest ('+context.url+')'),_this2.scheduleRefresh(_this2.uri||context.url)}})},_proto.scheduleRefresh=function(uri,ttlMs){var _this3=this;void 0===ttlMs&&(ttlMs=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var media=null==(_this3$hls=_this3.hls)?void 0:_this3$hls.media,_this3$hls;return media&&!media.ended?void _this3.loadSteeringManifest(uri):void _this3.scheduleRefresh(uri,1e3*_this3.timeToLoad)},ttlMs)},ContentSteeringController}(),AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im,XhrLoader=function(){function XhrLoader(config){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=config?config.xhrSetup||null:null,this.stats=new LoadStats,this.retryDelay=0}
vendor: 9,093 bytes, line 1
1var _proto=XhrLoader.prototype;return _proto.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},_proto.abortInternal=function(){var loader=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),loader&&(loader.onreadystatechange=null,loader.onprogress=null,4!==loader.readyState&&(this.stats.aborted=!0,loader.abort()))},_proto.abort=function(){var _this$callbacks;this.abortInternal(),null!=(_this$callbacks=this.callbacks)&&_this$callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},_proto.load=function(context,config,callbacks){if(this.stats.loading.start)throw new Error('Loader can only be used once.');this.stats.loading.start=self.performance.now(),this.context=context,this.config=config,this.callbacks=callbacks,this.loadInternal()},_proto.loadInternal=function(){var _this=this,config=this.config,context=this.context;if(config&&context){var xhr=this.loader=new self.XMLHttpRequest,stats=this.stats;stats.loading.first=0,stats.loaded=0,stats.aborted=!1;var xhrSetup=this.xhrSetup;xhrSetup?Promise.resolve().then(function(){return _this.loader!==xhr||_this.stats.aborted?void 0:xhrSetup(xhr,context.url)}).catch(function(){if(!(_this.loader!==xhr||_this.stats.aborted))return xhr.open('GET',context.url,!0),xhrSetup(xhr,context.url)}).then(function(){_this.loader!==xhr||_this.stats.aborted||_this.openAndSendXhr(xhr,context,config)}).catch(function(error){_this.callbacks.onError({code:xhr.status,text:error.message},context,xhr,stats)}):this.openAndSendXhr(xhr,context,config)}},_proto.openAndSendXhr=function(xhr,context,config){xhr.readyState||xhr.open('GET',context.url,!0);var headers=context.headers,_config$loadPolicy=config.loadPolicy,maxTimeToFirstByteMs=_config$loadPolicy.maxTimeToFirstByteMs,maxLoadTimeMs=_config$loadPolicy.maxLoadTimeMs;if(headers)for(var header in headers)xhr.setRequestHeader(header,headers[header]);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,self.clearTimeout(this.requestTimeout),config.timeout=maxTimeToFirstByteMs&&isFiniteNumber(maxTimeToFirstByteMs)?maxTimeToFirstByteMs:maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),config.timeout),xhr.send()},_proto.readystatechange=function(){var context=this.context,xhr=this.loader,stats=this.stats;if(context&&xhr){var readyState=xhr.readyState,config=this.config;if(!stats.aborted&&2<=readyState&&(0===stats.loading.first&&(stats.loading.first=Math.max(self.performance.now(),stats.loading.start),config.timeout!==config.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),config.timeout=config.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),config.loadPolicy.maxLoadTimeMs-(stats.loading.first-stats.loading.start)))),4===readyState)){self.clearTimeout(this.requestTimeout),xhr.onreadystatechange=null,xhr.onprogress=null;var _status=xhr.status,useResponse='text'!==xhr.responseType;if(200<=_status&&300>_status&&(useResponse&&xhr.response||null!==xhr.responseText)){stats.loading.end=Math.max(self.performance.now(),stats.loading.first);var data=useResponse?xhr.response:xhr.responseText,len='arraybuffer'===xhr.responseType?data.byteLength:data.length;if(stats.loaded=stats.total=len,stats.bwEstimate=8e3*stats.total/(stats.loading.end-stats.loading.first),!this.callbacks)return;var onProgress=this.callbacks.onProgress;if(onProgress&&onProgress(stats,context,data,xhr),!this.callbacks)return;var response={url:xhr.responseURL,data:data,code:_status};this.callbacks.onSuccess(response,stats,context,xhr)}else{var retryConfig=config.loadPolicy.errorRetry,retryCount=stats.retry,_response={url:context.url,data:void 0,code:_status};shouldRetry(retryConfig,retryCount,!1,_response)?this.retry(retryConfig):(logger.error(_status+' while loading '+context.url),this.callbacks.onError({code:_status,text:xhr.statusText},context,xhr,stats))}}}},_proto.loadtimeout=function(){if(this.config){var retryConfig=this.config.loadPolicy.timeoutRetry,retryCount=this.stats.retry;if(shouldRetry(retryConfig,retryCount,!0))this.retry(retryConfig);else{var _this$context;logger.warn('timeout while loading '+(null==(_this$context=this.context)?void 0:_this$context.url));var callbacks=this.callbacks;callbacks&&(this.abortInternal(),callbacks.onTimeout(this.stats,this.context,this.loader))}}},_proto.retry=function(retryConfig){var context=this.context,stats=this.stats;this.retryDelay=getRetryDelay(retryConfig,stats.retry),stats.retry++,logger.warn((status?'HTTP Status '+status:'Timeout')+' while loading '+(null==context?void 0:context.url)+', retrying '+stats.retry+'/'+retryConfig.maxNumRetry+' in '+this.retryDelay+'ms'),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},_proto.loadprogress=function(event){var stats=this.stats;stats.loaded=event.loaded,event.lengthComputable&&(stats.total=event.total)},_proto.getCacheAge=function(){var result=null;if(this.loader&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){var ageHeader=this.loader.getResponseHeader('age');result=ageHeader?parseFloat(ageHeader):null}return result},_proto.getResponseHeader=function(name){return this.loader&&new RegExp('^'+name+':\\s*[\\d.]+\\s*$','im').test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(name):null},XhrLoader}(),BYTERANGE=/(\d+)-(\d+)\/(\d+)/,FetchLoader=function(){function FetchLoader(config){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=config.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}var _proto=FetchLoader.prototype;return _proto.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},_proto.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},_proto.abort=function(){var _this$callbacks;this.abortInternal(),null!=(_this$callbacks=this.callbacks)&&_this$callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},_proto.load=function(context,config,callbacks){var _this=this,stats=this.stats;if(stats.loading.start)throw new Error('Loader can only be used once.');stats.loading.start=self.performance.now();var initParams=getRequestParameters(context,this.controller.signal),onProgress=callbacks.onProgress,isArrayBuffer='arraybuffer'===context.responseType,LENGTH=isArrayBuffer?'byteLength':'length',_config$loadPolicy=config.loadPolicy,maxTimeToFirstByteMs=_config$loadPolicy.maxTimeToFirstByteMs,maxLoadTimeMs=_config$loadPolicy.maxLoadTimeMs;this.context=context,this.config=config,this.callbacks=callbacks,this.request=this.fetchSetup(context,initParams),self.clearTimeout(this.requestTimeout),config.timeout=maxTimeToFirstByteMs&&isFiniteNumber(maxTimeToFirstByteMs)?maxTimeToFirstByteMs:maxLoadTimeMs,this.requestTimeout=self.setTimeout(function(){_this.abortInternal(),callbacks.onTimeout(stats,context,_this.response)},config.timeout),self.fetch(this.request).then(function(response){_this.response=_this.loader=response;var first=Math.max(self.performance.now(),stats.loading.start);if(self.clearTimeout(_this.requestTimeout),config.timeout=maxLoadTimeMs,_this.requestTimeout=self.setTimeout(function(){_this.abortInternal(),callbacks.onTimeout(stats,context,_this.response)},maxLoadTimeMs-(first-stats.loading.start)),!response.ok){var status=response.status,statusText=response.statusText;throw new FetchError(statusText||'fetch, bad network response',status,response)}return stats.loading.first=first,stats.total=getContentLength(response.headers)||stats.total,onProgress&&isFiniteNumber(config.highWaterMark)?_this.loadProgressively(response,stats,context,config.highWaterMark,onProgress):isArrayBuffer?response.arrayBuffer():'json'===context.responseType?response.json():response.text()}).then(function(responseData){var response=_this.response;if(!response)throw new Error('loader destroyed');self.clearTimeout(_this.requestTimeout),stats.loading.end=Math.max(self.performance.now(),stats.loading.first);var total=responseData[LENGTH];total&&(stats.loaded=stats.total=total);var loaderResponse={url:response.url,data:responseData,code:response.status};onProgress&&!isFiniteNumber(config.highWaterMark)&&onProgress(stats,context,responseData,response),callbacks.onSuccess(loaderResponse,stats,context,response)}).catch(function(error){if(self.clearTimeout(_this.requestTimeout),!stats.aborted){var code=error?error.code||0:0,text=error?error.message:null;callbacks.onError({code:code,text:text}
1,context,error?error.details:null,stats)}})},_proto.getCacheAge=function(){var result=null;if(this.response){var ageHeader=this.response.headers.get('age');result=ageHeader?parseFloat(ageHeader):null}return result},_proto.getResponseHeader=function(name){return this.response?this.response.headers.get(name):null},_proto.loadProgressively=function(response,stats,context,highWaterMark,onProgress){void 0===highWaterMark&&(highWaterMark=0);var chunkCache=new ChunkCache,reader=response.body.getReader();return function pump(){return reader.read().then(function(data){if(data.done)return chunkCache.dataLength&&onProgress(stats,context,chunkCache.flush(),response),Promise.resolve(new ArrayBuffer(0));var chunk=data.value,len=chunk.length;return stats.loaded+=len,len<highWaterMark||chunkCache.dataLength?(chunkCache.push(chunk),chunkCache.dataLength>=highWaterMark&&onProgress(stats,context,chunkCache.flush(),response)):onProgress(stats,context,chunk,response),pump()}).catch(function(){return Promise.reject()})}()},FetchLoader}(),FetchError=function(_Error){function FetchError(message,code,details){var _this2;return _this2=_Error.call(this,message)||this,_this2.code=void 0,_this2.details=void 0,_this2.code=code,_this2.details=details,_this2}return _inheritsLoose(FetchError,_Error),FetchError}(_wrapNativeSuper(Error)),WHITESPACE_CHAR=/\s/,Cues={newCue:function(track,startTime,endTime,captionScreen){for(var result=[],Cue=self.VTTCue||self.TextTrackCue,r=0,row,cue,indenting,indent,text;r<captionScreen.rows.length;r++)if(row=captionScreen.rows[r],indenting=!0,indent=0,text='',!row.isEmpty()){for(var c=0,_track$cues;c<row.chars.length;c++)WHITESPACE_CHAR.test(row.chars[c].uchar)&&indenting?indent++:(text+=row.chars[c].uchar,indenting=!1);row.cueStartTime=startTime,startTime===endTime&&(endTime+=1e-4),16<=indent?indent--:indent++;var cueText=fixLineBreaks(text.trim()),id=generateCueId(startTime,endTime,cueText);null!=track&&null!=(_track$cues=track.cues)&&_track$cues.getCueById(id)||(cue=new Cue(startTime,endTime,cueText),cue.id=id,cue.line=r+1,cue.align='left',cue.position=10+Math.min(80,10*Math.floor(8*indent/32)),result.push(cue))}return track&&result.length&&(result.sort(function(cueA,cueB){return'auto'===cueA.line||'auto'===cueB.line?0:8<cueA.line&&8<cueB.line?cueB.line-cueA.line:cueA.line-cueB.line}),result.forEach(function(cue){return addCueToTrack(track,cue)})),result}},hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:Infinity,frontBufferFlushThreshold:Infinity,maxBufferSize:60000000,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:Infinity,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:requestMediaKeySystemAccess,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,cert
1LoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:'linear'},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:'linear'}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:Infinity,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},function(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:'English',captionsTextTrack1LanguageCode:'en',captionsTextTrack2Label:'Spanish',captionsTextTrack2LanguageCode:'es',captionsTextTrack3Label:'Unknown CC',captionsTextTrack3LanguageCode:'',captionsTextTrack4Label:'Unknown CC',captionsTextTrack4LanguageCode:'',renderTextTracksNatively:!0}}()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController}),LevelController=function(_BasePlaylistControll){function LevelController(hls,contentSteeringController){var _this;return _this=_BasePlaylistControll.call(this,hls,'[level-controller]')||this,_this._levels=[],_this._firstLevel=-1,_this._maxAutoLevel=-1,_this._startLevel=void 0,_this.currentLevel=null,_this.currentLevelIndex=-1,_this.manualLevelIndex=-1,_this.steering=void 0,_this.onParsedComplete=void 0,_this.steering=contentSteeringController,_this._registerListeners(),_this}_inheritsLoose(LevelController,_BasePlaylistControll);var _proto=LevelController.prototype;return _proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),hls.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),hls.on(Events.ERROR,this.onError,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),hls.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),hls.off(Events.ERROR,this.onError,this)},_proto.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),_BasePlaylistControll.prototype.destroy.call(this)},_proto.stopLoad=function(){var levels=this._levels;levels.forEach(function(level){level.loadError=0,level.fragmentError=0}),_BasePlaylistControll.prototype.stopLoad.call(this)},_proto.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},_proto.onManifestLoading=function(){this.resetLevels()},_proto.onManifestLoaded=function(event,data){var preferManagedMediaSource=this.hls.config.preferManagedMediaSource,levels=[],redundantSet={},generatePathwaySet={},resolutionFound=!1,videoCodecFound=!1,audioCodecFound=!1;
1data.levels.forEach(function(levelParsed){var attributes=levelParsed.attrs,audioCodec=levelParsed.audioCodec,videoCodec=levelParsed.videoCodec,_audioCodec,_videoCodec;-1!==(null==(_audioCodec=audioCodec)?void 0:_audioCodec.indexOf('mp4a.40.34'))&&(chromeOrFirefox||(chromeOrFirefox=/chrome|firefox/i.test(navigator.userAgent)),chromeOrFirefox&&(levelParsed.audioCodec=audioCodec=void 0)),audioCodec&&(levelParsed.audioCodec=audioCodec=getCodecCompatibleName(audioCodec,preferManagedMediaSource)),0===(null==(_videoCodec=videoCodec)?void 0:_videoCodec.indexOf('avc1'))&&(videoCodec=levelParsed.videoCodec=convertAVC1ToAVCOTI(videoCodec));var width=levelParsed.width,height=levelParsed.height,unknownCodecs=levelParsed.unknownCodecs;if(resolutionFound||(resolutionFound=!!(width&&height)),videoCodecFound||(videoCodecFound=!!videoCodec),audioCodecFound||(audioCodecFound=!!audioCodec),!(null!=unknownCodecs&&unknownCodecs.length||audioCodec&&!areCodecsMediaSourceSupported(audioCodec,'audio',preferManagedMediaSource)||videoCodec&&!areCodecsMediaSourceSupported(videoCodec,'video',preferManagedMediaSource))){var CODECS=attributes.CODECS,FRAMERATE=attributes['FRAME-RATE'],HDCP=attributes['HDCP-LEVEL'],PATHWAY=attributes['PATHWAY-ID'],RESOLUTION=attributes.RESOLUTION,VIDEO_RANGE=attributes['VIDEO-RANGE'],levelKey=''+((PATHWAY||'.')+'-')+levelParsed.bitrate+'-'+RESOLUTION+'-'+FRAMERATE+'-'+CODECS+'-'+VIDEO_RANGE+'-'+HDCP;if(!redundantSet[levelKey]){var level=new Level(levelParsed);redundantSet[levelKey]=level,generatePathwaySet[levelKey]=1,levels.push(level)}else if(redundantSet[levelKey].uri!==levelParsed.url&&!levelParsed.attrs['PATHWAY-ID']){var pathwayCount=generatePathwaySet[levelKey]+=1;levelParsed.attrs['PATHWAY-ID']=Array(pathwayCount+1).join('.');var _level=new Level(levelParsed);redundantSet[levelKey]=_level,levels.push(_level)}else redundantSet[levelKey].addGroupId('audio',attributes.AUDIO),redundantSet[levelKey].addGroupId('text',attributes.SUBTITLES)}}),this.filterAndSortMediaOptions(levels,data,resolutionFound,videoCodecFound,audioCodecFound)},_proto.filterAndSortMediaOptions=function(filteredLevels,data,resolutionFound,videoCodecFound,audioCodecFound){var _this2=this,audioTracks=[],subtitleTracks=[],levels=filteredLevels;if((resolutionFound||videoCodecFound)&&audioCodecFound&&(levels=levels.filter(function(_ref){var videoCodec=_ref.videoCodec,videoRange=_ref.videoRange,width=_ref.width,height=_ref.height;return(!!videoCodec||!!(width&&height))&&isVideoRange(videoRange)})),0===levels.length)return void Promise.resolve().then(function(){if(_this2.hls){data.levels.length&&_this2.warn('One or more CODECS in variant not supported: '+JSON.stringify(data.levels[0].attrs));var error=new Error('no level with compatible codecs found in manifest');_this2.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:data.url,error:error,reason:error.message})}});if(data.audioTracks){var preferManagedMediaSource=this.hls.config.preferManagedMediaSource;audioTracks=data.audioTracks.filter(function(track){return!track.audioCodec||areCodecsMediaSourceSupported(track.audioCodec,'audio',preferManagedMediaSource)}),assignTrackIdsByGroup(audioTracks)}data.subtitles&&(subtitleTracks=data.subtitles,assignTrackIdsByGroup(subtitleTracks));var unsortedLevels=levels.slice(0);levels.sort(function(a,b){if(a.attrs['HDCP-LEVEL']!==b.attrs['HDCP-LEVEL'])return(a.attrs['HDCP-LEVEL']||'')>(b.attrs['HDCP-LEVEL']||'')?1:-1;if(resolutionFound&&a.height!==b.height)return a.height-b.height;if(a.frameRate!==b.frameRate)return a.frameRate-b.frameRate;if(a.videoRange!==b.videoRange)return VideoRangeValues.indexOf(a.videoRange)-VideoRangeValues.indexOf(b.videoRange);if(a.videoCodec!==b.videoCodec){var valueA=videoCodecPreferenceValue(a.videoCodec),valueB=videoCodecPreferenceValue(b.videoCodec);if(valueA!==valueB)return valueB-valueA}if(a.uri===b.uri&&a.codecSet!==b.codecSet){var _valueA=codecsSetSelectionPreferenceValue(a.codecSet),_valueB=codecsSetSelectionPreferenceValue(b.codecSet);if(_valueA!==_valueB)return _valueB-_valueA}return a.averageBitrate===b.averageBitrate?0:a.averageBitrate-b.averageBitrate});var firstLevelInPlaylist=unsortedLevels[0];if(this.steering&&(levels=this.steering.filterParsedLevels(levels),levels.length!==unsortedLevels.length))for(var i=0;i<unsortedLevels.length;i++)if(unsortedLevels[i].pathwayId===levels[0].pathwayId){firstLevelInPlaylist=unsortedLevels[i];break}this._levels=levels;for(var _i=0;_i<levels.length;_i++)if(levels[_i]===firstLevelInPlaylist){var _this$hls$userConfig;this._firstLevel=_i;var firstLevelBitrate=firstLevelInPlaylist.bitrate,bandwidthEstimate=this.hls.bandwidthEstimate;if(this.log('manifest loaded, '+levels.length+' level(s) found, first bitrate: '+firstLevelBitrate),void 0===(null==(_this$hls$userConfig=this.hls.userConfig)?void 0:_this$hls$userConfig.abrEwmaDefaultEstimate)){var startingBwEstimate=Math.min(firstLevelBitrate,this.hls.config.abrEwmaDefaultEstimateMax);startingBwEstimate>bandwidthEstimate&&bandwidthEstimate===hlsDefaultConfig.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=startingBwEstimate)}break}var edata={levels:levels,audioTracks:audioTracks,subtitleTracks:subtitleTracks,sessionData:data.sessionData,sessionKeys:data.sessionKeys,firstLevel:this._firstLevel,stats:data.stats,audio:audioCodecFound,video:videoCodecFound,altAudio:!(audioCodecFound&&!videoCodecFound)&&audioTracks.some(function(t){return!!t.url})};this.hls.trigger(Events.MANIFEST_PARSED,edata),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)},_proto.onError=function(event,data){data.fatal||!data.context||data.context.type===PlaylistContextType.LEVEL&&data.context.level===this.level&&this.checkRetry(data)},_proto.onFragBuffered=function(event,_ref2){var frag=_ref2.frag;if(void 0!==frag&&frag.type===PlaylistLevelType.MAIN){var el=frag.elementaryStreams;if(!Object.keys(el).some(function(type){return!!el[type]}))return;var level=this._levels[frag.level];null!=level&&level.loadError&&(this.log('Resetting level error count of '+level.loadError+' on frag buffered'),level.loadError=0)}},_proto.onLevelLoaded=function(event,data){var level=data.level,details=data.details,curLevel=this._levels[level],_data$deliveryDirecti2;if(!curLevel){var _data$deliveryDirecti;return this.warn('Invalid level index '+level),void(null!=(_data$deliveryDirecti=data.deliveryDirectives)&&_data$deliveryDirecti.skip&&(details.deltaUpdateFailed=!0))}level===this.currentLevelIndex?(0===curLevel.fragmentError&&(curLevel.loadError=0),this.playlistLoaded(level,data,curLevel.details)):null!=(_data$deliveryDirecti2=data.deliveryDirectives)&&_data$deliveryDirecti2.skip&&(details.deltaUpdateFailed=!0)},_proto.loadPlaylist=function(hlsUrlParameters){_BasePlaylistControll.prototype.loadPlaylist.call(this);var currentLevelIndex=this.currentLevelIndex,currentLevel=this.currentLevel;if(currentLevel&&this.shouldLoadPlaylist(currentLevel)){var url=currentLevel.uri;if(hlsUrlParameters)try{url=hlsUrlParameters.addDirectives(url)}catch(error){this.warn('Could not construct new URL with HLS Delivery Directives: '+error)}var pathwayId=currentLevel.attrs['PATHWAY-ID'];this.log('Loading level index '+currentLevelIndex+(void 0===(null==hlsUrlParameters?void 0:hlsUrlParameters.msn)?'':' at sn '+hlsUrlParameters.msn+' part '+hlsUrlParameters.part)+' with'+(pathwayId?' Pathway '+pathwayId:'')+' '+url),this.clearTimer(),this.hls.trigger(Events.LEVEL_LOADING,{url:url,level:currentLevelIndex,pathwayId:currentLevel.attrs['PATHWAY-ID'],id:0,deliveryDirectives:hlsUrlParameters||null})}},_proto.removeLevel=function(levelIndex){var _this3=this,levels=this._levels.filter(function(level,index){return index!==levelIndex||(_this3.steering&&_this3.steering.removeLevel(level),level===_this3.currentLevel&&(_this3.currentLevel=null,_this3.currentLevelIndex=-1,level.details&&level.details.fragments.forEac
1h(function(f){return f.level=-1})),!1)}),_this$currentLevel;reassignFragmentLevelIndexes(levels),this._levels=levels,-1<this.currentLevelIndex&&null!=(_this$currentLevel=this.currentLevel)&&_this$currentLevel.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(Events.LEVELS_UPDATED,{levels:levels})},_proto.onLevelsUpdated=function(event,_ref3){var levels=_ref3.levels;this._levels=levels},_proto.checkMaxAutoUpdated=function(){var _this$hls=this.hls,autoLevelCapping=_this$hls.autoLevelCapping,maxAutoLevel=_this$hls.maxAutoLevel,maxHdcpLevel=_this$hls.maxHdcpLevel;this._maxAutoLevel!==maxAutoLevel&&(this._maxAutoLevel=maxAutoLevel,this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:autoLevelCapping,levels:this.levels,maxAutoLevel:maxAutoLevel,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:maxHdcpLevel}))},_createClass(LevelController,[{key:'levels',get:function(){return 0===this._levels.length?null:this._levels}},{key:'level',get:function(){return this.currentLevelIndex},set:function(newLevel){var levels=this._levels;if(0!==levels.length){if(0>newLevel||newLevel>=levels.length){var error=new Error('invalid level idx'),fatal=0>newLevel;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:newLevel,fatal:fatal,error:error,reason:error.message}),fatal)return;newLevel=Math.min(newLevel,levels.length-1)}var lastLevelIndex=this.currentLevelIndex,lastLevel=this.currentLevel,lastPathwayId=lastLevel?lastLevel.attrs['PATHWAY-ID']:void 0,level=levels[newLevel],pathwayId=level.attrs['PATHWAY-ID'];if(this.currentLevelIndex=newLevel,this.currentLevel=level,!(lastLevelIndex===newLevel&&level.details&&lastLevel&&lastPathwayId===pathwayId)){this.log('Switching to level '+newLevel+' ('+(level.height?level.height+'p ':'')+(level.videoRange?level.videoRange+' ':'')+(level.codecSet?level.codecSet+' ':'')+'@'+level.bitrate+')'+(pathwayId?' with Pathway '+pathwayId:'')+' from level '+lastLevelIndex+(lastPathwayId?' with Pathway '+lastPathwayId:''));var levelSwitchingData={level:newLevel,attrs:level.attrs,details:level.details,bitrate:level.bitrate,averageBitrate:level.averageBitrate,maxBitrate:level.maxBitrate,realBitrate:level.realBitrate,width:level.width,height:level.height,codecSet:level.codecSet,audioCodec:level.audioCodec,videoCodec:level.videoCodec,audioGroups:level.audioGroups,subtitleGroups:level.subtitleGroups,loaded:level.loaded,loadError:level.loadError,fragmentError:level.fragmentError,name:level.name,id:level.id,uri:level.uri,url:level.url,urlId:0,audioGroupIds:level.audioGroupIds,textGroupIds:level.textGroupIds};this.hls.trigger(Events.LEVEL_SWITCHING,levelSwitchingData);var levelDetails=level.details;if(!levelDetails||levelDetails.live){var hlsUrlParameters=this.switchParams(level.uri,null==lastLevel?void 0:lastLevel.details,levelDetails);this.loadPlaylist(hlsUrlParameters)}}}}},{key:'manualLevel',get:function(){return this.manualLevelIndex},set:function(newLevel){this.manualLevelIndex=newLevel,void 0===this._startLevel&&(this._startLevel=newLevel),-1!==newLevel&&(this.level=newLevel)}},{key:'firstLevel',get:function(){return this._firstLevel},set:function(newLevel){this._firstLevel=newLevel}},{key:'startLevel',get:function(){if(void 0===this._startLevel){var configStartLevel=this.hls.config.startLevel;return void 0===configStartLevel?this.hls.firstAutoLevel:configStartLevel}return this._startLevel},set:function(newLevel){this._startLevel=newLevel}},{key:'nextLoadLevel',get:function(){return-1===this.manualLevelIndex?this.hls.nextAutoLevel:this.manualLevelIndex},set:function(nextLevel){this.level=nextLevel,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=nextLevel)}}]),LevelController}(BasePlaylistController),KeyLoader=function(){function KeyLoader(config){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=config}var _proto=KeyLoader.prototype;return _proto.abort=function(type){for(var uri in this.keyUriToKeyInfo){var loader=this.keyUriToKeyInfo[uri].loader;if(loader){var _loader$context;if(type&&type!==(null==(_loader$context=loader.context)?void 0:_loader$context.frag.type))return;loader.abort()}}},_proto.detach=function(){for(var uri in this.keyUriToKeyInfo){var keyInfo=this.keyUriToKeyInfo[uri];(keyInfo.mediaKeySessionContext||keyInfo.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[uri]}},_proto.destroy=function(){for(var uri in this.detach(),this.keyUriToKeyInfo){var loader=this.keyUriToKeyInfo[uri].loader;loader&&loader.destroy()}this.keyUriToKeyInfo={}},_proto.createKeyLoadError=function(frag,details,error,networkDetails,response){return void 0===detail
1s&&(details=ErrorDetails.KEY_LOAD_ERROR),new LoadError({type:ErrorTypes.NETWORK_ERROR,details:details,fatal:!1,frag:frag,response:response,error:error,networkDetails:networkDetails})},_proto.loadClear=function(loadingFrag,encryptedFragments){var _this=this;if(this.emeController&&this.config.emeEnabled)for(var sn=loadingFrag.sn,cc=loadingFrag.cc,_loop=function(){var frag=encryptedFragments[i];if(cc<=frag.cc&&('initSegment'===sn||'initSegment'===frag.sn||sn<frag.sn))return _this.emeController.selectKeySystemFormat(frag).then(function(keySystemFormat){frag.setKeyFormat(keySystemFormat)}),1},i=0;i<encryptedFragments.length&&!_loop();i++);},_proto.load=function(frag){var _this2=this;return!frag.decryptdata&&frag.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(frag).then(function(keySystemFormat){return _this2.loadInternal(frag,keySystemFormat)}):this.loadInternal(frag)},_proto.loadInternal=function(frag,keySystemFormat){var _keyInfo,_keyInfo2;keySystemFormat&&frag.setKeyFormat(keySystemFormat);var decryptdata=frag.decryptdata;if(!decryptdata){var error=new Error(keySystemFormat?'Expected frag.decryptdata to be defined after setting format '+keySystemFormat:'Missing decryption data on fragment in onKeyLoading');return Promise.reject(this.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,error))}var uri=decryptdata.uri;if(!uri)return Promise.reject(this.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+uri+'"')));var keyInfo=this.keyUriToKeyInfo[uri];if(null!=(_keyInfo=keyInfo)&&_keyInfo.decryptdata.key)return decryptdata.key=keyInfo.decryptdata.key,Promise.resolve({frag:frag,keyInfo:keyInfo});if(null!=(_keyInfo2=keyInfo)&&_keyInfo2.keyLoadPromise){var _keyInfo$mediaKeySess;switch(null==(_keyInfo$mediaKeySess=keyInfo.mediaKeySessionContext)?void 0:_keyInfo$mediaKeySess.keyStatus){case void 0:case'status-pending':case'usable':case'usable-in-future':return keyInfo.keyLoadPromise.then(function(keyLoadedData){return decryptdata.key=keyLoadedData.keyInfo.decryptdata.key,{frag:frag,keyInfo:keyInfo}});}}switch(keyInfo=this.keyUriToKeyInfo[uri]={decryptdata:decryptdata,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},decryptdata.method){case'ISO-23001-7':case'SAMPLE-AES':case'SAMPLE-AES-CENC':case'SAMPLE-AES-CTR':return'identity'===decryptdata.keyFormat?this.loadKeyHTTP(keyInfo,frag):this.loadKeyEME(keyInfo,frag);case'AES-128':return this.loadKeyHTTP(keyInfo,frag);default:return Promise.reject(this.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+decryptdata.method+'"')));}},_proto.loadKeyEME=function(keyInfo,frag){var keyLoadedData={frag:frag,keyInfo:keyInfo};if(this.emeController&&this.config.emeEnabled){var keySessionContextPromise=this.emeController.loadKey(keyLoadedData);if(keySessionContextPromise)return(keyInfo.keyLoadPromise=keySessionContextPromise.then(function(keySessionContext){return keyInfo.mediaKeySessionContext=keySessionContext,keyLoadedData})).catch(function(error){throw keyInfo.keyLoadPromise=null,error})}return Promise.resolve(keyLoadedData)},_proto.loadKeyHTTP=function(keyInfo,frag){var _this3=this,config=this.config,Loader=config.loader,keyLoader=new Loader(config);return frag.keyLoader=keyInfo.loader=keyLoader,keyInfo.keyLoadPromise=new Promise(function(resolve,reject){var loaderContext={keyInfo:keyInfo,frag:frag,responseType:'arraybuffer',url:keyInfo.decryptdata.uri},loadPolicy=config.keyLoadPolicy.default,loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};keyLoader.load(loaderContext,loaderConfig,{onSuccess:function(response,stats,context,networkDetails){var frag=context.frag,keyInfo=context.keyInfo,uri=context.url;return frag.decryptdata&&keyInfo===_this3.keyUriToKeyInfo[uri]?void(keyInfo.decryptdata.key=frag.decryptdata.key=new Uint8Array(response.data),frag.keyLoader=null,keyInfo.loader=null,resolve({frag:frag,keyInfo:keyInfo})):reject(_this3.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error('after key load, decryptdata unset or changed'),networkDetails))},onError:function(response,context,networkDetails){_this3.resetLoader(context),reject(_this3.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error('HTTP Error '+response.code+' loading key '+response.text),networkDetails,_objectSpread2
1({url:loaderContext.url,data:void 0},response)))},onTimeout:function(stats,context,networkDetails){_this3.resetLoader(context),reject(_this3.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_TIMEOUT,new Error('key loading timed out'),networkDetails))},onAbort:function(stats,context,networkDetails){_this3.resetLoader(context),reject(_this3.createKeyLoadError(frag,ErrorDetails.INTERNAL_ABORTED,new Error('key loading aborted'),networkDetails))}})})},_proto.resetLoader=function(context){var frag=context.frag,keyInfo=context.keyInfo,uri=context.url,loader=keyInfo.loader;frag.keyLoader===loader&&(frag.keyLoader=null,keyInfo.loader=null),delete this.keyUriToKeyInfo[uri],loader&&loader.destroy()},KeyLoader}(),MAX_START_GAP_JUMP=2,GapController=function(){function GapController(config,media,fragmentTracker,hls){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=config,this.media=media,this.fragmentTracker=fragmentTracker,this.hls=hls}var _proto=GapController.prototype;return _proto.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},_proto.poll=function(lastCurrentTime,activeFrag){var config=this.config,media=this.media,stalled=this.stalled;if(null!==media){var currentTime=media.currentTime,seeking=media.seeking,seeked=this.seeking&&!seeking,beginSeek=!this.seeking&&seeking;if(this.seeking=seeking,currentTime!==lastCurrentTime){if(this.moved=!0,seeking||(this.nudgeRetry=0),null!==stalled){if(this.stallReported){var _stalledDuration=self.performance.now()-stalled;logger.warn('playback not stuck anymore @'+currentTime+', after '+Math.round(_stalledDuration)+'ms'),this.stallReported=!1}this.stalled=null}return}if(beginSeek||seeked)return void(this.stalled=null);if(media.paused&&!seeking||media.ended||0===media.playbackRate||!BufferHelper.getBuffered(media).length)return void(this.nudgeRetry=0);var bufferInfo=BufferHelper.bufferInfo(media,currentTime,0),nextStart=bufferInfo.nextStart||0;if(seeking){var hasEnoughBuffer=bufferInfo.len>MAX_START_GAP_JUMP,noBufferGap=!nextStart||activeFrag&&activeFrag.start<=currentTime||nextStart-currentTime>MAX_START_GAP_JUMP&&!this.fragmentTracker.getPartialFragment(currentTime);if(hasEnoughBuffer||noBufferGap)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var isBuffered=0<bufferInfo.len,_level$details;if(!isBuffered&&!nextStart)return;var startJump=Math.max(nextStart,bufferInfo.start||0)-currentTime,level=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,isLive=null==level||null==(_level$details=level.details)?void 0:_level$details.live,maxStartGapJump=isLive?2*level.details.targetduration:MAX_START_GAP_JUMP,partialOrGap=this.fragmentTracker.getPartialFragment(currentTime);if(0<startJump&&(startJump<=maxStartGapJump||partialOrGap))return void(media.paused||this._trySkipBufferHole(partialOrGap))}var tnow=self.performance.now();if(null===stalled)return void(this.stalled=tnow);var stalledDuration=tnow-stalled;if(!(!seeking&&stalledDuration>=250&&(this._reportStall(bufferInfo),!this.media))){var bufferedWithHoles=BufferHelper.bufferInfo(media,currentTime,config.maxBufferHole);this._tryFixBufferStall(bufferedWithHoles,stalledDuration)}}},_proto._tryFixBufferStall=function(bufferInfo,stalledDurationMs){var config=this.config,fragmentTracker=this.fragmentTracker,media=this.media;if(null!==media){var currentTime=media.currentTime,partial=fragmentTracker.getPartialFragment(currentTime);if(partial){var targetTime=this._trySkipBufferHole(partial);if(targetTime||!this.media)return}(bufferInfo.len>config.maxBufferHole||bufferInfo.nextStart&&bufferInfo.nextStart-currentTime<config.maxBufferHole)&&stalledDurationMs>1e3*config.highBufferWatchdogPeriod&&(logger.warn('Trying to nudge playhead over buffer-hole'),this.stalled=null,this._tryNudgeBuffer())}},_proto._reportStall=function(bufferInfo){var hls=this.hls,media=this.media,stallReported=this.stallReported;if(!stallReported&&media){this.stallReported=!0;var error=new Error('Playback stalling at @'+media.currentTime+' due to low buffer ('+JSON.stringify(bufferInfo)+')');logger.warn(error.message),hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:error,buffer:bufferInfo.len})}},_proto._trySkipBufferHole=function(partial){var config=this.config,hls=this.hls,media=this.media;if(null===media)return 0;var currentTime=media.currentTime,bufferInfo=BufferHelper.bufferInfo(media,currentTime,0),startTime=currentTime<bufferInfo.start?bufferInfo.start:bufferInfo.nextStart;if(startTime){var bufferStarved=bufferInfo.len<=config.maxBufferHole,waiting=0<bufferInfo.len&&1>bufferInfo.len&&3>media.readyState,gapLength=startTime-currentTime;if(0<gapLength&&(bufferStarved||waiting)){if(gapLength>config.maxBufferHole){var fragmentTracker=this.fragmentTracker,startGap=!1;if(0===currentTime){var startFrag=fragmentTracker.getAppendedFrag(0,PlaylistLevelType.MAIN);startFrag&&startTime<startFrag.end&&(startGap=!0)}if(!startGap){var startProvisioned=partial||fragmentTracker.getAppendedFrag(currentTime,PlaylistLevelType.MAIN);if(startProvisioned){for(var moreToLoad=!1,pos=startProvisioned.end,provisioned;pos<startTime;)if(provisioned=fragmentTracker.getPartialFragment(pos),provisioned)pos+=provisioned.duration;else{moreToLoad=!0;break}if(moreToLoad)return 0}}}var targetTime=Math.max(startTime+.05,currentTime+.1);if(logger.warn('skipping hole, adjusting currentTime from '+currentTime+' to '+targetTime),this.moved=!0,this.stalled=null,media.currentTime=targetTime,partial&&!partial.ga
vendor: 4,495 bytes, line 1
1p){var error=new Error('fragment loaded with buffer holes, seeking from '+currentTime+' to '+targetTime);hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:error,reason:error.message,frag:partial})}return targetTime}}return 0},_proto._tryNudgeBuffer=function(){var config=this.config,hls=this.hls,media=this.media,nudgeRetry=this.nudgeRetry;if(null!==media){var currentTime=media.currentTime;if(this.nudgeRetry++,nudgeRetry<config.nudgeMaxRetry){var targetTime=currentTime+(nudgeRetry+1)*config.nudgeOffset,error=new Error('Nudging \'currentTime\' from '+currentTime+' to '+targetTime);logger.warn(error.message),media.currentTime=targetTime,hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:error,fatal:!1})}else{var _error=new Error('Playhead still not moving while enough data buffered @'+currentTime+' after '+config.nudgeMaxRetry+' nudges');logger.error(_error.message),hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:_error,fatal:!0})}}},GapController}(),StreamController=function(_BaseStreamController){function StreamController(hls,fragmentTracker,keyLoader){var _this;return _this=_BaseStreamController.call(this,hls,fragmentTracker,keyLoader,'[stream-controller]',PlaylistLevelType.MAIN)||this,_this.audioCodecSwap=!1,_this.gapController=null,_this.level=-1,_this._forceStartLoad=!1,_this.altAudio=!1,_this.audioOnly=!1,_this.fragPlaying=null,_this.onvplaying=null,_this.onvseeked=null,_this.fragLastKbps=0,_this.couldBacktrack=!1,_this.backtrackFragment=null,_this.audioCodecSwitch=!1,_this.videoBuffer=null,_this._registerListeners(),_this}_inheritsLoose(StreamController,_BaseStreamController);var _proto=StreamController.prototype;return _proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.on(Events.LEVEL_LOADING,this.onLevelLoading,this),hls.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),hls.on(Events.ERROR,this.onError,this),hls.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),hls.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),hls.on(Events.BUFFER_CREATED,this.onBufferCreated,this),hls.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),hls.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),hls.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),hls.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),hls.off(Events.ERROR,this.onError,this),hls.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),hls.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),hls.off(Events.BUFFER_CREATED,this.onBufferCreated,this),hls.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),hls.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto.onHandlerDestroying=function(){this._unregisterListeners(),_BaseStreamController.prototype.onHandlerDestroying.call(this)},_proto.startLoad=function(startPosition){if(this.levels){var lastCurrentTime=this.lastCurrentTime,hls=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var startLevel=hls.startLevel;-1===startLevel&&(hls.config.testBandwidth&&1<this.levels.length?(startLevel=0,this.bitrateTest=!0):startLevel=hls.firstAutoLevel),hls.nextLoadLevel=startLevel,this.level=hls.loadLevel,this.loadedmetadata=!1}0<lastCurrentTime&&-1===startPosition&&(this.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=!0,this.state=State.STOPPED},_proto.stopLoad=function(){this._forceStartLoad=!1,_BaseStreamController.prototype.stopLoad.c
1all(this)},_proto.doTick=function(){switch(this.state){case State.WAITING_LEVEL:{var levels=this.levels,level=this.level,currentLevel=null==levels?void 0:levels[level],details=null==currentLevel?void 0:currentLevel.details;if(details&&(!details.live||this.levelLastLoaded===currentLevel)){if(this.waitForCdnTuneIn(details))break;this.state=State.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:{var now=self.performance.now(),retryDate=this.retryDate,_this$media;if(!retryDate||now>=retryDate||null!=(_this$media=this.media)&&_this$media.seeking){var _levels=this.levels,_level=this.level,_currentLevel=null==_levels?void 0:_levels[_level];this.resetStartWhenNotLoaded(_currentLevel||null),this.state=State.IDLE}}}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()},_proto.onTickEnd=function(){_BaseStreamController.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},_proto.doTickIdle=function(){var hls=this.hls,levelLastLoaded=this.levelLastLoaded,levels=this.levels,media=this.media;if(null!==levelLastLoaded&&(media||!this.startFragRequested&&hls.config.startFragPrefetch)&&!(this.altAudio&&this.audioOnly)){var level=hls.nextLoadLevel;if(null!=levels&&levels[level]){var levelInfo=levels[level],bufferInfo=this.getMainFwdBufferInfo();if(null!==bufferInfo){var lastDetails=this.getLevelDetails();if(lastDetails&&this._streamEnded(bufferInfo,lastDetails)){var data={};return this.altAudio&&(data.type='video'),this.hls.trigger(Events.BUFFER_EOS,data),void(this.state=State.ENDED)}hls.loadLevel!==level&&-1===hls.manualLevel&&this.log('Adapting to level '+level+' from level '+this.level),this.level=hls.nextLoadLevel=level;var levelDetails=levelInfo.details;if(!levelDetails||this.state===State.WAITING_LEVEL||levelDetails.live&&this.levelLastLoaded!==levelInfo)return this.level=level,void(this.state=State.WAITING_LEVEL);var bufferLen=bufferInfo.len,maxBufLen=this.getMaxBufferLength(levelInfo.maxBitrate);if(!(bufferLen>=maxBufLen)){this.backtrackFragment&&this.backtrackFragment.start>bufferInfo.end&&(this.backtrackFragment=null);var targetBufferTime=this.backtrackFragment?this.backtrackFragment.start:bufferInfo.end,frag=this.getNextFragment(targetBufferTime,levelDetails);if(this.couldBacktrack&&!this.fragPrevious&&frag&&'initSegment'!==frag.sn&&this.fragmentTracker.getState(frag)!==FragmentState.OK){var backtrackSn=(null==(_this$backtrackFragme=this.backtrackFragment)?frag:_this$backtrackFragme).sn,fragIdx=backtrackSn-levelDetails.startSN,backtrackFrag=levelDetails.fragments[fragIdx-1],_this$backtrackFragme;backtrackFrag&&frag.cc===backtrackFrag.cc&&(frag=backtrackFrag,this.fragmentTracker.removeFragment(backtrackFrag))}else this.backtrackFragment&&bufferInfo.len&&(this.backtrackFragment=null);if(frag&&this.isLoopLoading(frag,targetBufferTime)){var gapStart=frag.gap;if(!gapStart){var type=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,mediaBuffer=(type===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;mediaBuffer&&this.afterBufferFlushed(mediaBuffer,type,PlaylistLevelType.MAIN)}frag=this.getNextFragmentLoopLoading(frag,levelDetails,bufferInfo,PlaylistLevelType.MAIN,maxBufLen)}frag&&(frag.initSegment&&!frag.initSegment.data&&!this.bitrateTest&&(frag=frag.initSegment),this.loadFragment(frag,levelInfo,targetBufferTime))}}}}},_proto.loadFragment=function(frag,level,targetBufferTime){var fragState=this.fragmentTracker.getState(frag);this.fragCurrent=frag,fragState===FragmentState.NOT_LOADED||fragState===FragmentState.PARTIAL?'initSegment'===frag.sn?this._loadInitSegment(frag,level):this.bitrateTest?(this.log('Fragment '+frag.sn+' of level '+frag.level+' is being downloaded to test bitrate and will not be buffered'),this._loadBitrateTestFrag(frag,level)):(this.startFragRequested=!0,_BaseStreamController.prototype.loadFragment.call(this,frag,level,targetBufferTime)):this.clearTrackerIfNeeded(frag)},_proto.getBufferedFrag=function(position){return this.fragmentTracker.getBufferedFrag(position,PlaylistLevelType.MAIN)},_proto.followingBufferedFrag=function(frag){return frag?this.getBufferedFrag(frag.end+.5):null},_proto.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},_proto.nextLevelSwitch=function(){var levels=this.levels,media=this.media;if(null!=media&&media.readyState){var fragPlayingCurrent=this.getAppendedFrag(media.currentTime),fetchdelay;fragPlayingCurrent&&1<fragPlayingCurrent.start&&this.flushMainBuffer(0,fragPlayingCurrent.start-1);var levelDetails=this.getLevelDetails();if(null!=levelDetails&&levelDetails.live){var bufferInfo=this.getMainFwdBufferInfo();if(!bufferInfo||bufferInfo.len<2*levelDetails.targetduration)return}if(!media.paused&&levels){var nextLevelId=this.hls.nextLoadLevel,nextLevel=levels[nextLevelId],fragLastKbps=this.fragLastKbps;fetchdelay=fragLastKbps&&this.fragCurrent?this.fragCurrent.duration*nextLevel.maxBitrate/(1e3*fragLastKbps)+1:0}else fetchdelay=0;var bufferedFrag=this.getBufferedFrag(media.currentTime+fetchdelay);if(bufferedFrag){var nextBufferedFrag=this.followingBufferedFrag(bufferedFrag);if(nextBufferedFrag){this.abortCurrentFrag();var maxStart=nextBufferedFrag.maxStartPTS?nextBufferedFrag.maxStartPTS:nextBufferedFrag.start,fragDuration=nextBufferedFrag.duration,startPts=Math.max(bufferedFrag.end,maxStart+Math.min(Math.max(fragDuration-this.config.maxFragLookUpTolerance,fragDuration*(this.couldBacktrack?.5:.125)),fragDuration*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(startPts,Number.POSITIVE_INFINITY)}}}},_proto.abortCurrentFrag=function(){var fragCurrent=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,fragCurrent&&(fragCurrent.abortRequests(),this.fragmentTracker.removeFragment(fragCurrent)),this.state){case State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE;}this.nextLoadPosition=this.getLoadPosition()},_proto.flushMainBuffer=function(startOffset,endOffset){_BaseStreamController.prototype.flushMainBuffer.call(this,startOffset,endOffset,this.altAudio?'video':null)},_proto.onMediaAttached=function(event,data){_BaseStreamController.prototype.onMediaAttached.call(this,event,data);var media=data.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),media.addEventListener('playing',this.onvplaying),media.addEventListener('seeked',this.onvseeked),this.gapController=new GapController(this.config,media,this.fragmentTracker,this.hls)},_proto.onMediaDetaching=function(){var media=this.media;media&&this.onvplaying&&this.onvseeked&&(media.removeEventListener('playing',this.onvplaying),media.removeEventListener('seeked',this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),_BaseStreamController.prototype.onMediaDetaching.call(this)},_proto.onMediaPlaying=function(){this.tick()},_proto.onMediaSeeked=function(){var media=this.media,currentTime=media?media.currentTime:null;isFiniteNumber(currentTime)&&this.log('Media seeked to '+currentTime.toFixed(3));var bufferInfo=this.getMainFwdBufferInfo();return null===bufferInfo||0===bufferInfo.len?void this.warn('Main forward buffer length on "seeked" event '+(bufferInfo?bufferInfo.len:'empty')+')'):void this.tick()},_proto.onManifestLoading=function(){this.log('Trigger BUFFER_RESET'),this.hls.trigger(Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1},_proto.onManifestParsed=function(event,data){var aac=!1,heaac=!1;
1data.levels.forEach(function(level){var codec=level.audioCodec;codec&&(aac=aac||-1!==codec.indexOf('mp4a.40.2'),heaac=heaac||-1!==codec.indexOf('mp4a.40.5'))}),this.audioCodecSwitch=aac&&heaac&&!changeTypeSupported(),this.audioCodecSwitch&&this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'),this.levels=data.levels,this.startFragRequested=!1},_proto.onLevelLoading=function(event,data){var levels=this.levels;if(levels&&this.state===State.IDLE){var level=levels[data.level];(!level.details||level.details.live&&this.levelLastLoaded!==level||this.waitForCdnTuneIn(level.details))&&(this.state=State.WAITING_LEVEL)}},_proto.onLevelLoaded=function(event,data){var levels=this.levels,newLevelId=data.level,newDetails=data.details,duration=newDetails.totalduration,_curLevel$details;if(!levels)return void this.warn('Levels were reset while loading level '+newLevelId);this.log('Level '+newLevelId+' loaded ['+newDetails.startSN+','+newDetails.endSN+']'+(newDetails.lastPartSn?'[part-'+newDetails.lastPartSn+'-'+newDetails.lastPartIndex+']':'')+', cc ['+newDetails.startCC+', '+newDetails.endCC+'] duration:'+duration);var curLevel=levels[newLevelId],fragCurrent=this.fragCurrent;fragCurrent&&(this.state===State.FRAG_LOADING||this.state===State.FRAG_LOADING_WAITING_RETRY)&&fragCurrent.level!==data.level&&fragCurrent.loader&&this.abortCurrentFrag();var sliding=0;if(newDetails.live||null!=(_curLevel$details=curLevel.details)&&_curLevel$details.live){var _this$levelLastLoaded;if(this.checkLiveUpdate(newDetails),newDetails.deltaUpdateFailed)return;sliding=this.alignPlaylists(newDetails,curLevel.details,null==(_this$levelLastLoaded=this.levelLastLoaded)?void 0:_this$levelLastLoaded.details)}if(curLevel.details=newDetails,this.levelLastLoaded=curLevel,this.hls.trigger(Events.LEVEL_UPDATED,{details:newDetails,level:newLevelId}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(newDetails))return;this.state=State.IDLE}this.startFragRequested?newDetails.live&&this.synchronizeToLiveEdge(newDetails):this.setStartPosition(newDetails,sliding),this.tick()},_proto._handleFragmentLoadProgress=function(data){var frag=data.frag,part=data.part,payload=data.payload,levels=this.levels,_frag$initSegment;if(!levels)return void this.warn('Levels were reset while fragment load was in progress. Fragment '+frag.sn+' of level '+frag.level+' will not be buffered');var currentLevel=levels[frag.level],details=currentLevel.details;
1if(!details)return this.warn('Dropping fragment '+frag.sn+' of level '+frag.level+' after level details were reset'),void this.fragmentTracker.removeFragment(frag);var videoCodec=currentLevel.videoCodec,accurateTimeOffset=details.PTSKnown||!details.live,initSegmentData=null==(_frag$initSegment=frag.initSegment)?void 0:_frag$initSegment.data,audioCodec=this._getAudioCodec(currentLevel),transmuxer=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),partIndex=part?part.index:-1,chunkMeta=new ChunkMetadata(frag.level,frag.sn,frag.stats.chunkCount,payload.byteLength,partIndex,-1!==partIndex),initPTS=this.initPTS[frag.cc];transmuxer.push(payload,initSegmentData,audioCodec,videoCodec,frag,part,details.totalduration,accurateTimeOffset,chunkMeta,initPTS)},_proto.onAudioTrackSwitching=function(event,data){var fromAltAudio=this.altAudio,altAudio=!!data.url;if(!altAudio){if(this.mediaBuffer!==this.media){this.log('Switching on main audio, use media.buffered to schedule main fragment loading'),this.mediaBuffer=this.media;var fragCurrent=this.fragCurrent;fragCurrent&&(this.log('Switching to main audio track, cancel main fragment load'),fragCurrent.abortRequests(),this.fragmentTracker.removeFragment(fragCurrent)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var hls=this.hls;fromAltAudio&&(hls.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),hls.trigger(Events.AUDIO_TRACK_SWITCHED,data)}},_proto.onAudioTrackSwitched=function(event,data){var trackId=data.id,altAudio=!!this.hls.audioTracks[trackId].url;if(altAudio){var videoBuffer=this.videoBuffer;videoBuffer&&this.mediaBuffer!==videoBuffer&&(this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading'),this.mediaBuffer=videoBuffer)}this.altAudio=altAudio,this.tick()},_proto.onBufferCreated=function(event,data){var tracks=data.tracks,alternate=!1,mediaTrack,name;for(var type in tracks){var track=tracks[type];if('main'!==track.id)alternate=!0;else if(name=type,mediaTrack=track,'video'==type){var videoTrack=tracks[type];videoTrack&&(this.videoBuffer=videoTrack.buffer)}}alternate&&mediaTrack?(this.log('Alternate track found, use '+name+'.buffered to schedule main fragment loading'),this.mediaBuffer=mediaTrack.buffer):this.mediaBuffer=this.media},_proto.onFragBuffered=function(event,data){var frag=data.frag,part=data.part;if(!(frag&&frag.type!==PlaylistLevelType.MAIN)){if(this.fragContextChanged(frag))return this.warn('Fragment '+frag.sn+(part?' p: '+part.index:'')+' of level '+frag.level+' finished buffering, but was aborted. state: '+this.state),void(this.state===State.PARSED&&(this.state=State.IDLE));var stats=part?part.stats:frag.stats;this.fragLastKbps=Math.round(8*stats.total/(stats.buffering.end-stats.loading.first)),'initSegment'!==frag.sn&&(this.fragPrevious=frag),this.fragBufferedComplete(frag,part)}},_proto.onError=function(event,data){var _data$context;if(data.fatal)return void(this.state=State.ERROR);switch(data.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,data);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:data.levelRetry||this.state!==State.WAITING_LEVEL||(null==(_data$context=data.context)?void 0:_data$context.type)!==PlaylistContextType.LEVEL||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:if(!data.parent||'main'!==data.parent)return;if(data.details===ErrorDetails.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(data)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(data);}},_proto.checkBuffer=function(){var media=this.media,gapController=this.gapController;if(media&&gapController&&media.readyState){if(this.loadedmetadata||!BufferHelper.getBuffered(media).length){var activeFrag=this.state===State.IDLE?null:this.fragCurrent;gapController.poll(this.lastCurrentTime,activeFrag)}this.lastCurrentTime=media.currentTime}},_proto.onFragLoadEmergencyAborted=function(){this.state=State.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},_proto.onBufferFlushed=function(event,_ref){var type=_ref.type;if(type!==ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){var mediaBuffer=(type===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(mediaBuffer,type,PlaylistLevelType.MAIN),this.tick()}},_proto.onLevelsUpdated=function(event,data){-1<this.level&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=data.levels},_proto.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},_proto.seekToStartPos=function(){var media=this.media;if(media){var currentTime=media.currentTime,startPosition=this.startPosition;if(0<=startPosition&¤tTime<startPosition){if(media.seeking)return void this.log('could not seek to '+startPosition+', already seeking at '+currentTime);var buffered=BufferHelper.getBuffered(media),bufferStart=buffered.length?buffered.start(0):0,delta=bufferStart-startPosition;0<delta&&(delta<this.config.maxBufferHole||delta<this.config.maxFragLookUpTolerance)&&(this.log('adjusting start position by '+delta+' to match buffer start'),startPosition+=delta,this.startPosition=startPosition),this.log('seek to target start position '+startPosition+' from current time '+currentTime),media.currentTime=startPosition}}},_proto._getAudioCodec=function(currentLevel){var audioCodec=this.config.defaultAudioCodec||currentLevel.audioCodec;return this.audioCodecSwap&&audioCodec&&(this.log('Swapping audio codec'),audioCodec=-1===audioCodec.indexOf('mp4a.40.5')?'mp4a.40.5':'mp4a.40.2'),audioCodec},_proto._loadBitrateTestFrag=function(frag,level){var _this2=this;frag.bitrateTest=!0,this._doFragLoad(frag,level).then(function(data){var hl
1s=_this2.hls;if(data&&!_this2.fragContextChanged(frag)){level.fragmentError=0,_this2.state=State.IDLE,_this2.startFragRequested=!1,_this2.bitrateTest=!1;var stats=frag.stats;stats.parsing.start=stats.parsing.end=stats.buffering.start=stats.buffering.end=self.performance.now(),hls.trigger(Events.FRAG_LOADED,data),frag.bitrateTest=!1}})},_proto._handleTransmuxComplete=function(transmuxResult){var id='main',hls=this.hls,remuxResult=transmuxResult.remuxResult,chunkMeta=transmuxResult.chunkMeta,context=this.getCurrentContext(chunkMeta),_id3$samples;if(!context)return void this.resetWhenMissingContext(chunkMeta);var frag=context.frag,part=context.part,level=context.level,video=remuxResult.video,text=remuxResult.text,id3=remuxResult.id3,initSegment=remuxResult.initSegment,details=level.details,audio=this.altAudio?void 0:remuxResult.audio;if(this.fragContextChanged(frag))return void this.fragmentTracker.removeFragment(frag);if(this.state=State.PARSING,initSegment){if(null!=initSegment&&initSegment.tracks){var mapFragment=frag.initSegment||frag;this._bufferInitSegment(level,initSegment.tracks,mapFragment,chunkMeta),hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:mapFragment,id:id,tracks:initSegment.tracks})}var initPTS=initSegment.initPTS,timescale=initSegment.timescale;isFiniteNumber(initPTS)&&(this.initPTS[frag.cc]={baseTime:initPTS,timescale:timescale},hls.trigger(Events.INIT_PTS_FOUND,{frag:frag,id:id,initPTS:initPTS,timescale:timescale}))}if(video&&details&&'initSegment'!==frag.sn){var prevFrag=details.fragments[frag.sn-1-details.startSN],isFirstFragment=frag.sn===detail
vendor: 19,055 bytes, line 1
1s.startSN,isFirstInDiscontinuity=!prevFrag||frag.cc>prevFrag.cc;if(!1!==remuxResult.independent){var startPTS=video.startPTS,endPTS=video.endPTS,startDTS=video.startDTS,endDTS=video.endDTS;if(part)part.elementaryStreams[video.type]={startPTS:startPTS,endPTS:endPTS,startDTS:startDTS,endDTS:endDTS};else if(video.firstKeyFrame&&video.independent&&1===chunkMeta.id&&!isFirstInDiscontinuity&&(this.couldBacktrack=!0),video.dropped&&video.independent){var bufferInfo=this.getMainFwdBufferInfo(),targetBufferTime=(bufferInfo?bufferInfo.end:this.getLoadPosition())+this.config.maxBufferHole,startTime=video.firstKeyFramePTS?video.firstKeyFramePTS:startPTS;if(!isFirstFragment&&targetBufferTime<startTime-this.config.maxBufferHole&&!isFirstInDiscontinuity)return void this.backtrack(frag);isFirstInDiscontinuity&&(frag.gap=!0),frag.setElementaryStreamInfo(video.type,frag.start,endPTS,frag.start,endDTS,!0)}else isFirstFragment&&startPTS>MAX_START_GAP_JUMP&&(frag.gap=!0);frag.setElementaryStreamInfo(video.type,startPTS,endPTS,startDTS,endDTS),this.backtrackFragment&&(this.backtrackFragment=frag),this.bufferFragmentData(video,frag,part,chunkMeta,isFirstFragment||isFirstInDiscontinuity)}else if(isFirstFragment||isFirstInDiscontinuity)frag.gap=!0;else return void this.backtrack(frag)}if(audio){var _startPTS=audio.startPTS,_endPTS=audio.endPTS,_startDTS=audio.startDTS,_endDTS=audio.endDTS;part&&(part.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:_startPTS,endPTS:_endPTS,startDTS:_startDTS,endDTS:_endDTS}),frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,_startPTS,_endPTS,_startDTS,_endDTS),this.bufferFragmentData(audio,frag,part,chunkMeta)}if(details&&null!=id3&&null!=(_id3$samples=id3.samples)&&_id3$samples.length){var emittedID3={id:id,frag:frag,details:details,samples:id3.samples};hls.trigger(Events.FRAG_PARSING_METADATA,emittedID3)}if(details&&text){var emittedText={id:id,frag:frag,details:details,samples:text.samples};hls.trigger(Events.FRAG_PARSING_USERDATA,emittedText)}},_proto._bufferInitSegment=function(currentLevel,tracks,frag,chunkMeta){var _this3=this;if(this.state===State.PARSING){this.audioOnly=!!tracks.audio&&!tracks.video,this.altAudio&&!this.audioOnly&&delete tracks.audio;var audio=tracks.audio,video=tracks.video,audiovideo=tracks.audiovideo;if(audio){var audioCodec=currentLevel.audioCodec,ua=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){audioCodec&&(-1===audioCodec.indexOf('mp4a.40.5')?audioCodec='mp4a.40.5':audioCodec='mp4a.40.2');var audioMetadata=audio.metadata;audioMetadata&&'channelCount'in audioMetadata&&1!==(audioMetadata.channelCount||1)&&-1===ua.indexOf('firefox')&&(audioCodec='mp4a.40.5')}audioCodec&&-1!==audioCodec.indexOf('mp4a.40.5')&&-1!==ua.indexOf('android')&&'audio/mpeg'!==audio.container&&(audioCodec='mp4a.40.2',this.log('Android: force audio codec to '+audioCodec)),currentLevel.audioCodec&¤tLevel.audioCodec!==audioCodec&&this.log('Swapping manifest audio codec "'+currentLevel.audioCodec+'" for "'+audioCodec+'"'),audio.levelCodec=audioCodec,audio.id='main',this.log('Init audio buffer, container:'+audio.container+', codecs[selected/level/parsed]=['+(audioCodec||'')+'/'+(currentLevel.audioCodec||'')+'/'+audio.codec+']')}video&&(video.levelCodec=currentLevel.videoCodec,video.id='main',this.log('Init video buffer, container:'+video.container+', codecs[level/parsed]=['+(currentLevel.videoCodec||'')+'/'+video.codec+']')),audiovideo&&this.log('Init audiovideo buffer, container:'+audiovideo.container+', codecs[level/parsed]=['+currentLevel.codecs+'/'+audiovideo.codec+']'),this.hls.trigger(Events.BUFFER_CODECS,tracks),Object.keys(tracks).forEach(function(trackName){var track=tracks[trackName],initSegment=track.initSegment;null!=initSegment&&initSegment.byteLength&&_this3.hls.trigger(Events.BUFFER_APPENDING,{type:trackName,data:initSegment,frag:frag,part:null,chunkMeta:chunkMeta,parent:frag.type})}),this.tickImmediate()}},_proto.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,PlaylistLevelType.MAIN)},_proto.backtrack=function(frag){this.couldBacktrack=!0,this.backtrackFragment=frag,this.resetTransmuxer(),this.flushBufferGap(frag),this.fragmentTracker.removeFragment(frag),this.fragPrevious=null,this.nextLoadPosition=frag.start,this.state=State.IDLE},_proto.checkFragmentChanged=function(){var video=this.media,fragPlayingCurrent=null;if(video&&1<video.readyState&&!1===video.seeking){var currentTime=video.currentTime;if(BufferHelper.isBuffered(video,currentTime)?fragPlayingCurrent=this.getAppendedFrag(currentTime):BufferHelper.isBuffered(video,currentTime+.1)&&(fragPlayingCurrent=this.getAppendedFrag(currentTime+.1)),fragPlayingCurrent){this.backtrackFragment=null;var fragPlaying=this.fragPlaying,fragCurrentLevel=fragPlayingCurrent.level;fragPlaying&&fragPlayingCurrent.sn===fragPlaying.sn&&fragPlaying.level===fragCurrentLevel||(this.fragPlaying=fragPlayingCurrent,this.hls.trigger(Events.FRAG_CHANGED,{frag:fragPlayingCurrent}),(!fragPlaying||fragPlaying.level!==fragCurrentLevel)&&this.hls.trigger(Events.LEVEL_SWITCHED,{level:fragCurrentLevel}))}}},_createClass(StreamController,[{key:'nextLevel',get:function(){var frag=this.nextBufferedFrag;return frag?frag.level:-1}},{key:'currentFrag',get:function(){var media=this.media;return media?this.fragPlaying||this.getAppendedFrag(media.currentTime):null}},{key:'currentProgramDateTime',get:function(){var media=this.media;if(media){var currentTime=media.currentTime,frag=this.currentFrag;if(frag&&isFiniteNumber(currentTime)&&isFiniteNumber(frag.programDateTime)){var epocMs=frag.programDateTime+1e3*(currentTime-frag.start);return new Date(epocMs)}}return null}},{key:'currentLevel',get:function(){var frag=this.currentFrag;return frag?frag.level:-1}},{key:'nextBufferedFrag',get:function(){var frag=this.currentFrag;return frag?this.followingBufferedFrag(frag):null}},{key:'forceStartLoad',get:function(){return this._forceStartLoad}}]),StreamController}(BaseStreamController),Hls=function(){function Hls(userConfig){void 0===userConfig&&(userConfig={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new EventEmitter,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,enableLogs(userConfig.debug||!1,'Hls instance');var config=this.config=mergeConfig(Hls.DefaultConfig,userConfig);this.userConfig=userConfig,config.progressive&&enableStreamingMode(config);var ConfigAbrController=config.abrController,ConfigBufferController=config.bufferController,ConfigCapLevelController=config.capLevelController,ConfigErrorController=config.errorController,ConfigFpsController=config.fpsController,errorController=new ConfigErrorController(this),abrController=this.abrController=new ConfigAbrController(this),bufferController=this.bufferController=new ConfigBufferController(this),capLevelController=this.capLevelController=new ConfigCapLevelController(this),fpsController=new ConfigFpsController(this),playListLoader=new PlaylistLoader(this),id3TrackController=new ID3TrackController(this),ConfigContentSteeringController=config.contentSteeringController,contentSteering=ConfigContentSteeringController?new ConfigContentSteeringController(this):null,levelController=this.levelController=new LevelController(this,contentSteering),fragmentTracker=new FragmentTracker(this),keyLoader=new KeyLoader(this.config),streamController=this.streamController=new StreamController(this,fragmentTracker,keyLoader);capLevelController.setStreamController(streamController),fpsController.setStreamController(streamController);var networkControllers=[playListLoader,levelController,streamController];contentSteering&&networkControllers.splice(1,0,contentSteering),this.networkControllers=networkControllers;var coreComponents=[abrController,bufferController,capLevelController,fpsController,id3TrackController,fragmentTracker];this.audioTrackController=this.createController(config.audioTrackController,networkControllers);var AudioStreamControllerClass=config.audioStreamController;AudioStreamControllerClass&&networkControllers.push(new AudioStreamControllerClass(this,fragmentTracker,keyLoader)),this.subtitleTrackController=this.createController(config.subtitleTrackController,networkControllers);var SubtitleStreamControllerClass=config.subtitleStreamController;SubtitleStreamControllerClass&&networkControllers.push(new SubtitleStreamControllerClass(this,fragmentTracker,keyLoader)),this.createController(config.timelineController,coreComponents),keyLoader.emeController=this.emeController=this.createController(config.emeController,coreComponents),this.cmcdController=this.createController(config.cmcdController,coreComponents),this.latencyController=this.createController(LatencyController,coreComponents),this.coreComponents=coreComponents,networkControllers.push(errorController);var onErrorOut=errorController.onErrorOut;'function'==typeof onErrorOut&&this.on(Events.ERROR,onErrorOut,errorController)}Hls.isMSESupported=function(){return isMSESupported()},Hls.isSupported=function(){return isSupported()},Hls.getMediaSource=function(){return getMediaSource()};var _proto=Hls.prototype;return _proto.createController=function(ControllerClass,components){if(ControllerClass){var controllerInstance=new ControllerClass(this);return components&&components.push(controllerInstance),controllerInstance}return null},_proto.on=function(event,listener,context){void 0===context&&(context=this),this._emitter.on(event,listener,context)},_proto.once=function(event,listener,context){void 0===context&&(context=this),this._emitter.once(event,listener,context)},_proto.removeAllListeners=function(event){this._emitter.removeAllListeners(event)},_proto.off=function(event,listener,context,once){void 0===context&&(context=this),this._emitter.off(event,listener,context,once)},_proto.listeners=function(event){return this._emitter.listeners(event)},_proto.emit=function(event,name,eventObject){return this._emitter.emit(event,name,eventObject)},_proto.trigger=function(event,eventObject){if(this.config.debug)return this.emit(event,event,eventObject);try{return this.emit(event,event,eventObject)}catch(error){if(logger.error('An internal error happened while handling event '+event+'. Error message: "'+error.message+'". Here is a stacktrace:',error),!this.triggeringException){this.triggeringException=!0;var fatal=event===Events.ERROR;this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:fatal,event:event,error:error}),this.triggeringException=!1}}return!1},_proto.listenerCount=function(event){return this._emitter.listenerCount(event)},_proto.destroy=function(){logger.log('destroy'),this.trigger(Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(function(component){return component.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(component){return component.destroy()}),this.coreComponents.length=0;var config=this.config;config.xhrSetup=config.fetchSetup=void 0,this.userConfig=null},_proto.attachMedia=function(media){logger.log('attachMedia'),this._media=media,this.trigger(Events.MEDIA_ATTACHING,{media:media})},_proto.detachMedia=function(){logger.log('detachMedia'),this.trigger(Events.MEDIA_DETACHING,void 0),this._media=null},_proto.loadSource=function(url){this.stopLoad();var media=this.media,loadedSource=this.url,loadingSource=this.url=urlToolkitExports.buildAbsoluteURL(self.location.href,url,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,logger.log('loadSource:'+loadingSource),media&&loadedSource&&(loadedSource!==loadingSource||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(media)),this.trigger(Events.MANIFEST_LOADING,{url:url})},_proto.startLoad=function(startPosition){void 0===startPosition&&(startPosition=-1),logger.log('startLoad('+startPosition+')'),this.started=!0,this.networkControllers.forEach(function(controller){controller.startLoad(startPosition)})},_proto.stopLoad=function(){logger.log('stopLoad'),this.started=!1,this.networkControllers.forEach(function(controller){controller.stopLoad()})},_proto.resumeBuffering=function(){this.started&&this.networkControllers.forEach(function(controller){'fragmentLoader'in controller&&controller.startLoad(-1)})},_proto.pauseBuffering=function(){this.networkControllers.forEach(function(controller){'fragmentLoader'in controller&&controller.stopLoad()})},_proto.swapAudioCodec=function(){logger.log('swapAudioCodec'),this.streamController.swapAudioCodec()},_proto.recoverMediaError=function(){logger.log('recoverMediaError');var media=this._media;this.detachMedia(),media&&this.attachMedia(media)},_proto.removeLevel=function(levelIndex){this.levelController.removeLevel(levelIndex)},_proto.setAudioOption=function(audioOption){var _this$audioTrackContr;return null==(_this$audioTrackContr=this.audioTrackController)?void 0:_this$audioTrackContr.setAudioOption(audioOption)},_proto.setSubtitleOption=function(subtitleOption){var _this$subtitleTrackCo;return null==(_this$subtitleTrackCo=this.subtitleTrackController)?void 0:_this$subtitleTrackCo.setSubtitleOption(subtitleOption),null},_createClass(Hls,[{key:'levels',get:function(){var levels=this.levelController.levels;return levels?levels:[]}},{key:'currentLevel',get:function(){return this.streamController.currentLevel},set:function(newLevel){logger.log('set currentLevel:'+newLevel),this.levelController.manualLevel=newLevel,this.streamController.immediateLevelSwitch()}},{key:'nextLevel',get:function(){return this.streamController.nextLevel},set:function(newLevel){logger.log('set nextLevel:'+newLevel),this.levelController.manualLevel=newLevel,this.streamController.nextLevelSwitch()}},{key:'loadLevel',get:function(){return this.levelController.level},set:function(newLevel){logger.log('set loadLevel:'+newLevel),this.levelController.manualLevel=newLevel}},{key:'nextLoadLevel',get:function(){return this.levelController.nextLoadLevel},set:function(level){this.levelController.nextLoadLevel=level}},{key:'firstLevel',get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(newLevel){logger.log('set firstLevel:'+newLevel),this.levelController.firstLevel=newLevel}},{key:'startLevel',get:function(){var startLevel=this.levelController.startLevel;return-1===startLevel&&-1<this.abrController.forcedAutoLevel?this.abrController.forcedAutoLevel:startLevel},set:function(newLevel){logger.log('set startLevel:'+newLevel),-1!==newLevel&&(newLevel=Math.max(newLevel,this.minAutoLevel)),this.levelController.startLevel=newLevel}},{key:'capLevelToPlayerSize',get:function(){return this.config.capLevelToPlayerSize},set:function(shouldStartCapping){var newCapLevelToPlayerSize=!!shouldStartCapping;newCapLevelToPlayerSize!==this.config.capLevelToPlayerSize&&(newCapLevelToPlayerSize?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=newCapLevelToPlayerSize)}},{key:'autoLevelCapping',get:function(){return this._autoLevelCapping},set:function(newLevel){this._autoLevelCapping!==newLevel&&(logger.log('set autoLevelCapping:'+newLevel),this._autoLevelCapping=newLevel,this.levelController.checkMaxAutoUpdated())}},{key:'bandwidthEstimate',get:function(){var bwEstimator=this.abrController.bwEstimator;return bwEstimator?bwEstimator.getEstimate():NaN},set:function(abrEwmaDefaultEstimate){this.abrController.resetEstimator(abrEwmaDefaultEstimate)}},{key:'ttfbEstimate',get:function(){var bwEstimator=this.abrController.bwEstimator;return bwEstimator?bwEstimator.getEstimateTTFB():NaN}},{key:'maxHdcpLevel',get:function(){return this._maxHdcpLevel},set:function(value){isHdcpLevel(value)&&this._maxHdcpLevel!==value&&(this._maxHdcpLevel=value,this.levelController.checkMaxAutoUpdated())}},{key:'autoLevelEnabled',get:function(){return-1===this.levelController.manualLevel}},{key:'manualLevel',get:function(){return this.levelController.manualLevel}},{key:'minAutoLevel',get:function(){var levels=this.levels,minAutoBitrate=this.config.minAutoBitrate;if(!levels)return 0;for(var len=levels.length,i=0;i<len;i++)if(levels[i].maxBitrate>=minAutoBitrate)return i;return 0}},{key:'maxAutoLevel',get:function(){var levels=this.levels,autoLevelCapping=this.autoLevelCapping,maxHdcpLevel=this.maxHdcpLevel,maxAutoLevel;if(maxAutoLevel=-1===autoLevelCapping&&null!=levels&&levels.length?levels.length-1:autoLevelCapping,maxHdcpLevel)for(var i=maxAutoLevel,hdcpLevel;i--;)if(hdcpLevel=levels[i].attrs['HDCP-LEVEL'],hdcpLevel&&hdcpLevel<=maxHdcpLevel)return i;return maxAutoLevel}},{key:'firstAutoLevel',get:function(){return this.abrController.firstAutoLevel}},{key:'nextAutoLevel',get:function(){return this.abrController.nextAutoLevel},set:function(nextLevel){this.abrController.nextAutoLevel=nextLevel}},{key:'playingDate',get:function(){return this.streamController.currentProgramDateTime}},{key:'mainForwardBufferInfo',get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:'allAudioTracks',get:function(){var audioTrackController=this.audioTrackController;return audioTrackController?audioTrackController.allAudioTracks:[]}},{key:'audioTracks',get:function(){var audioTrackController=this.audioTrackController;return audioTrackController?audioTrackController.audioTracks:[]}},{key:'audioTrack',get:function(){var audioTrackController=this.audioTrackController;return audioTrackController?audioTrackController.audioTrack:-1},set:function(audioTrackId){var audioTrackController=this.audioTrackController;audioTrackController&&(audioTrackController.audioTrack=audioTrackId)}},{key:'allSubtitleTracks',get:function(){var subtitleTrackController=this.subtitleTrackController;return subtitleTrackController?subtitleTrackController.allSubtitleTracks:[]}},{key:'subtitleTracks',get:function(){var subtitleTrackController=this.subtitleTrackController;return subtitleTrackController?subtitleTrackController.subtitleTracks:[]}},{key:'subtitleTrack',get:function(){var subtitleTrackController=this.subtitleTrackController;return subtitleTrackController?subtitleTrackController.subtitleTrack:-1},set:function(subtitleTrackId){var subtitleTrackController=this.subtitleTrackController;subtitleTrackController&&(subtitleTrackController.subtitleTrack=subtitleTrackId)}},{key:'media',get:function(){return this._media}},{key:'subtitleDisplay',get:function(){var subtitleTrackController=this.subtitleTrackController;return!!subtitleTrackController&&subtitleTrackController.subtitleDisplay}
1,set:function(value){var subtitleTrackController=this.subtitleTrackController;subtitleTrackController&&(subtitleTrackController.subtitleDisplay=value)}},{key:'lowLatencyMode',get:function(){return this.config.lowLatencyMode},set:function(mode){this.config.lowLatencyMode=mode}},{key:'liveSyncPosition',get:function(){return this.latencyController.liveSyncPosition}},{key:'latency',get:function(){return this.latencyController.latency}},{key:'maxLatency',get:function(){return this.latencyController.maxLatency}},{key:'targetLatency',get:function(){return this.latencyController.targetLatency}},{key:'drift',get:function(){return this.latencyController.drift}},{key:'forceStartLoad',get:function(){return this.streamController.forceStartLoad}}],[{key:'version',get:function(){return'1.5.17'}},{key:'Events',get:function(){return Events}},{key:'ErrorTypes',get:function(){return ErrorTypes}},{key:'ErrorDetails',get:function(){return ErrorDetails}},{key:'DefaultConfig',get:function(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig},set:function(defaultConfig){Hls.defaultConfig=defaultConfig}}]),Hls}(),_CmcdHeaderMap,chromeOrFirefox;return Hls.defaultConfig=void 0,Hls})})(!1)},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return{HLS_TRACK_ID:'hlsTrackId',HLS_SEGMENT_ID:'hlsSegmentId'}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return{CUE_TITLE:'cueTitle',ARTIST_NAME:'artistName',ALBUM_NAME:'albumName',PROGRAM_ID:'trackID',CUE_TIME_DURATION:'cueTimeDuration',CUE_TIME_START:'cueTimeStart',TRACK_ID:'trackID',NOW_PLAYING_URL:'nowplayingURL',TRACK_COVER_URL:'coverURL'}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){module.exports={AUDIO:'Audio',VIDEO:'Video'}},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3),__webpack_require__(2),__webpack_require__(109),__webpack_require__(108)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on,lang,adQuartile,adModuleEvents){var adModule=declare([adModuleEvents],{constructor:function(target,config){void 0,this.target=target,this.config=config,this.adQuartile=new adQuartile,this._defaultSequence=-1,this._adsTrackingProgress=[],this._destroyAdToggle=!1},init:function(){void 0,this._destroyAdlisteners(),this.onAdPlaybackStatusListener=this.target.on('ad-playback-status',lang.hitch(this,this._onAdPlaybackStatus)),this.inherited(arguments)},destroyAd:function(){void 0,this.html5OnDemand&&('function'==typeof this.html5OnDemand.skip&&(this._destroyAdToggle=!0,this.html5OnDemand.skip()),this.html5OnDemand=null)},skipAd:function(){void 0,this.html5OnDemand&&('function'==typeof this.html5OnDemand.skip&&this.html5OnDemand.skip(),this.html5OnDemand=null)},initAdListeners:function(html5OnDemand){void 0,this.html5OnDemand=html5OnDemand,this.html5OnDemand.initHTMLElementsStyle(this.html5OnDemand.videoNode),this.playbackOnDemandStatushandler=this.html5OnDemand.setPlaybackStatusHandler(lang.hitch(this,this._onAdPlaybackStatus)),this.clickTrackingElementClickedHandler=this.html5OnDemand.setClickTrackingElementClickedHandler(lang.hitch(this,this._onClickTrackingElementClicked)),this.adPlaybackCompleteHandler=this.target.on('ad-playback-complete',lang.hitch(this,this._destroyAdlisteners)),this.adPlaybackDestroyHandler=this.target.on('ad-playback-destroy',lang.hitch(this,this._destroyAdlisteners)),this.adPlaybackErrorHandler=this.target.on('ad-playback-error',lang.hitch(this,this._destroyAdlisteners))},getVastInlineAd:function(){return null},_onAdPlaybackStatus:function(e){if(this.html5Node=e.html5Node,'MEDIA_STARTED'==e.code).5>
1=this.html5Node.currentTime&&this.emit(this.AD_MODULE_PLAYBACK_START,{id:this.playerNode,type:e.adServerType,error:!1});else if('MEDIA_TIME_UPDATE'==e.code){var currentTime=Math.round(this.html5Node.currentTime),duration=Math.round(this.html5Node.duration);this._checkVideoPlaybackQuartile(this._getTimePercent(currentTime,duration)),this.emit(this.AD_MODULE_COUNTDOWN,{countDown:duration-currentTime})}else('MEDIA_ENDED'==e.code||'MEDIA_ERROR'==e.code)&&(this.html5OnDemand.stop(),this._destroyAdToggle?this.emit(this.AD_MODULE_PLAYBACK_DESTROY):this.emit(this.AD_MODULE_PLAYBACK_COMPLETE,{id:this.playerNode,type:e.adServerType,error:!1}),this._destroyAdToggle=!1,this._adsTrackingProgress=[],this.onAdPlaybackStatusListener.remove())},_onClickTrackingElementClicked:function(e){void 0,this.emit(this.AD_MODULE_CLICK_TRACKING,e)},_getTimePercent:function(currentTime,duration){return 0==duration?0:(currentTime/duration).toFixed(2)},_checkVideoPlaybackQuartile:function(timeAsPercent){var playbackQuartile=Math.floor(4*timeAsPercent);void 0!=this._adsTrackingProgress[playbackQuartile]||(this._adsTrackingProgress[playbackQuartile]=!0,this.emit(this.AD_MODULE_QUARTILE,{id:this.playerNode,adQuartile:this.adQuartile.getQuartileByIndex(playbackQuartile),error:!1}))},_destroyAdlisteners:function(){void 0,this.playbackOnDemandStatushandler&&this.playbackOnDemandStatushandler.remove(),this.clickTrackingElementClickedHandler&&this.clickTrackingElementClickedHandler.remove(),this.adPlaybackCompleteHandler&&this.adPlaybackCompleteHandler.remove(),this.adPlaybackErrorHandler&&this.adPlaybackErrorHandler.remove(),this.onAdPlaybackStatusListener&&this.onAdPlaybackStatusListener.remove(),this.adPlaybackDestroyHandler&&this.adPlaybackDestroyHandler.remove()}});return adModule}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var VASTAd=declare([],{constructor:function(id){void 0,this.id=id,this.inlineAd=null,this.wrapperAd=null}});return VASTAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastCompanionAd=declare([],{constructor:function(){void 0,this.id=null,this.width=null,this.height=null,this.expandedWidth=null,this.expandedHeight=null,this.resourceType=null,this.creativeType=null,this.url=null,this.co
1de=null,this.clickThroughURL=null,this.altText=null,this.adParameters=null,this.creativeView=null}});return vastCompanionAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var VASTDocument=declare([],{constructor:function(){void 0,this.vastAd=null}});return VASTDocument}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastMediaFile=declare([],{DELIVERY_STREAMING:'streaming',DELIVERY_PROGRESSIVE:'progressive',constructor:function(){void 0,this.url=null,this.id=null,this.delivery=null,this.bitrate=null,this.width=null,this.height=null,this.type=null,this.scalable=!1,this.maintainAspectRatio=!1,this.apiFramework=null,this.minBitrate=null,this.maxBitrate=null,this.co
1dec=null}});return vastMediaFile}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastResourceType=declare([],{IFRAME:'iframe',HTML:'html',STATIC:'static',SCRIPT:'script',OTHER:'other',constructor:function(value){void 0,this.name=value}});return vastResourceType}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastTrackingEvent=declare([],{constructor:function(){void 0,this.urls=[],this.type=null},addUrls:function(array){for(var arrayLength=array.length,i=0;i<arrayLength;i++)this.urls.push(array[i])}});return vastTrackingEvent}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastVideoClick=declare([],{constructor:function(){void 0,this.clickThrough=null,this.clickTrackings=[],this.customClicks=[]}});return vastVideoClick}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var VASTWrapperAd=declare([],{constructor:function(){void 0,this.vastAdTagURL=null,this.impression=null,this.impressions=[],this.error=null,this.trackingEvents=null,this.creatives=[],this.videoClicks=null},getLinearTrackingEvents:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),null==this._getLinearElement(sequence)?this.trackingEvents:this._getLinearElement(sequence).trackingEvents},_getLinearElement:function(sequence){var sequence=sequence;sequence==void 0&&(sequence=-1);for(var collectionLength=this.creatives.length,i=0;i<collectionLength;i++)if(null!=this.creatives[i].linearElement){if(-1==sequence)return this.creatives[i].linearElement;if(this.creatives[i].sequence==sequence)return this.creatives[i].linearElement}},getLinearVideoClick:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),null==this._getLinearElement(sequence)?this.videoClicks:this._getLinearElement(sequence).videoClick}});return VASTWrapperAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return{ID:'id',NODEKIND_ELEMENT:'element',INLINE:'InLine',WRAPPER:'Wrapper',AD_SYSTEM:'AdSystem',AD_TITLE:'AdTitle',DESCRIPTION:'Description',ERROR:'Error',IMPRESSION:'Impression',TRACKING_EVENTS:'TrackingEvents',COMPANION_ADS:'CompanionAds',COMPANION_CLICK_THROUGH:'CompanionClickThrough',LINEAR:'Linear',NON_LINEAR_ADS:'NonLinearAds',NON_LINEAR:'NonLinear',NON_LINEAR_CLICK_THROUGH:'NonLinearClickThrough',TRACKING:'Tracking',EVENT:'event',DURATION:'Duration',AD_ID:'AdID',MEDIA_FILES:'MediaFiles',MEDIA_FILE:'MediaFile',VIDEO_CLICKS:'VideoClicks',CLICK_THROUGH:'ClickThrough',CLICK_TRACKING:'ClickTracking',CUSTOM_CLICK:'CustomClick',COMPANION:'Companion',ALT_TEXT:'AltText',AD_PARAMETERS:'AdParameters',BITRATE:'bitrate',MIN_BITRATE:'minBitrate',MAX_BITRATE:'maxBitrate',CODEC:'codec',DELIVERY:'delivery',TYPE:'type',WIDTH:'width',HEIGHT:'height',EXPANDED_WIDTH:'expandedWidth',EXPANDED_HEIGHT:'expandedHeight',CREATIVE_TYPE:'creativeType',SEQUENCE:'sequence',SCALABLE:'scalable',MAINTAIN_ASPECT_RATIO:'maintainAspectRatio',API_FRAMEWORK:'apiFramework',IFRAME_RESOURCE:'IFrameResource',HTML_RESOURCE:'HTMLResource',STATIC_RESOURCE:'StaticResource',CREATIVE_VIEW:'creativeView',MIN_SUGGESTED_DURATION:'minSuggestedDuration',EXPIRES:'Expires',CATEGORY:'C
1ategory',SURVEY:'Survey',ADVERTISER:'Advertiser',AUDIO_INTERACTIONS:'AudioInteractions',LOGO_TILE:'logoTile',LOGO_TITLE:'logoTitle',LOGO_ARTIST:'logoArtist',LOGO_URL:'logoURL'}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var xmlParser=__webpack_require__(15),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastParser=declare([],{constructor:function(target){void 0,this.target=target},getTagValue:function(xmldata,tagName){return 0==xmldata.getElementsByTagName(tagName).length?null:xmlParser.textContent(xmldata.getElementsByTagName(tagName)[0])},getDataAsArray:function(xmldata,tagName,nodeName){if(0==xmldata.getElementsByTagName(tagName).length)return null;for(var data=xmldata.getElementsByTagName(tagName)[0].childNodes,array=[],i=0;i<data.length;i++)data[i].nodeName==nodeName&&array.push(xmlParser.textContent(data[i]));return array},trim:function(value){return void 0==value?null:value.replace(/^\s+|\s+$/g,'')}});return vastParser}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(2)],__WEBPACK_AMD_DEFINE_RESULT__=function(lang){var backstop={};return{objectToQuery:function(map){var enc=encodeURIComponent,pairs=[];for(var name in map){var value=map[name];if(value!=backstop[name]){var assign=enc(name)+'=';if(lang.isArray(value))for(var i=0,l=value.length;i<l;++i)pairs.push(assign+enc(value[i]));else pairs.push(assign+enc(value))}}return pairs.join('&')},queryToObject:function(str){for(var dec=decodeURIComponent,qp=str.split('&'),ret={},i=0,l=qp.length,name,val,item;i<l;++i)if(item=qp[i],item.length){var s=item.indexOf('=');0>s?(name=dec(item),val=''):(name=dec(item.slice(0,s)),val=dec(item.slice(s+1))),'string'==typeof ret[name]&&(ret[name]=[ret[name]]),lang.isArray(ret[name])?ret[name].push(val):ret[name]=val}return ret}}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[exports,__webpack_require__(37),__webpack_require__(28),__webpack_require__(26),__webpack_require__(55),__webpack_require__(6),__webpack_require__(2),__webpack_require__(29)],__WEBPACK_AMD_DEFINE_RESULT__=function(exports,RequestError,CancelError,Deferred,ioQuery,array,lang,Promise){function okHandler(response){return freeze(response)}function dataHandler(response){return response.data||response.text}exports.deepCopy=function(target,source){for(var name in source){var tval=target[name],sval=source[name];tval!==sval&&(tval&&'object'==typeof tval&&sval&&'object'==typeof sval?exports.deepCopy(tval,sval):target[name]=sval)}return target},exports.deepCreate=function(source,properties){properties=properties||{};var target=lang.delegate(source),name,value;for(name in source)value=source[name],value&&'object'==typeof value&&(target[name]=exports.deepCreate(value,properties[name]));return exports.deepCopy(target,properties)};var freeze=Object.freeze||function(obj){return obj};exports.deferred=function(response,cancel,isValid,isReady,handleResponse,last){var def=new Deferred(function(reason){return cancel&&cancel(def,response),reason&&(reason instanceof RequestError||reason instanceof CancelError)?reason:new CancelError('Request canceled',response)});def.response=response,def.isValid=isValid,def.isReady=isReady,def.handleResponse=handleResponse;var responsePromise=def.then(okHandler).otherwise(function(error){throw error.response=response,error});exports.notify&&responsePromise.then(lang.hitch(exports.notify,'emit','load'),lang.hitch(exports.notify,'emit','error'));var dataPromise=responsePromise.then(dataHandler),promise=new Promise;for(var prop in dataPromise)dataPromise.hasOwnProperty(prop)&&(promise[prop]=dataPromise[prop]);return promise.response=responsePromise,freeze(promise),last&&def.then(function(response){last.call(def,response)},function(error){last.call(def,response,error)}),def.promise=promise,def.then=promise.then,def},exports.addCommonMethods=function(provider,methods){array.forEach(methods||['GET','POST','PUT','DELETE'],function(method){provider[('DELETE'===method?'DEL':method).toLowerCase()]=function(url,options){return options=lang.delegate(options||{}),options.method=method,provider(url,options)}})},exports.parseArgs=function(url,options,skipData){var data=options.data,query=options.query;return data&&!skipData&&'object'==typeof data&&(options.data=ioQuery.objectToQuery(data)),query?('object'==typeof query&&(query=ioQuery.objectToQuery(query)),options.preventCache&&(query+=(query?'&':'')+'request.preventCache='+ +new Date)):options.preventCache&&(query='request.preventCache='+ +new Date),url&&query&&(url+=(~url.indexOf('?')?'&':'?')+query),{url:url,options:options,getHeader:function(){return null}}},exports.checkStatus=function(stat){return stat=stat||0,200<=stat&&300>stat||304===stat||1223===stat||!stat}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(37),__webpack_require__(94),__webpack_require__(93),__webpack_require__(56),__webpack_require__(4)],__WEBPACK_AMD_DEFINE_RESULT__=function(RequestError,watch,handlers,util,has){function handleResponse(response,error){var _xhr=response.xhr;if(response.status=response.xhr.status,response.text=_xhr.responseText,'xml'===response.options.handleAs&&(response.data=_xhr.responseXML),!error)try{handlers(response)}catch(e){error=e}error?this.reject(error):util.checkStatus(_xhr.status)?this.resolve(response):(error=new RequestError('Unable to load '+response.url+' status: '+_x
1hr.status,response),this.reject(error))}function getHeader(headerName){return this.xhr.getResponseHeader(headerName)}function xhr(url,options,returnDeferred){var response=util.parseArgs(url,util.deepCreate(defaultOptions,options),has('native-formdata')&&options&&options.data&&options.data instanceof FormData);url=response.url,options=response.options;var last=function(){remover&&remover()},dfd=util.deferred(response,cancel,isValid,isReady,handleResponse,last),_xhr=response.xhr=xhr._create(),remover;if(!_xhr)return dfd.cancel(new RequestError('XHR was not created')),returnDeferred?dfd:dfd.promise;response.getHeader=getHeader,addListeners&&(remover=addListeners(_xhr,dfd,response));var data=options.data,async=!options.sync,method=options.method;try{_xhr.open(method,url,async,options.user||void 0,options.password||void 0),options.withCredentials&&(_xhr.withCredentials=options.withCredentials);var headers=options.headers,contentType='application/x-www-form-urlencoded';if(headers)for(var hdr in headers)'content-type'===hdr.toLowerCase()?contentType=headers[hdr]:headers[hdr]&&_xhr.setRequestHeader(hdr,headers[hdr]);contentType&&!1!==contentType&&_xhr.setRequestHeader('Content-Type',contentType),headers&&'X-Requested-With'in headers||_xhr.setRequestHeader('X-Requested-With','XMLHttpRequest'),util.notify&&util.notify.emit('send',response,dfd.promise.cancel),_xhr.send(data)}catch(e){dfd.reject(e)}return watch(dfd),_xhr=null,returnDeferred?dfd:dfd.promise}has.add('native-xhr',function(){return'undefined'!=typeof XMLHttpRequest}),has.add('dojo-force-activex-xhr',function(){return has('activex')&&!document.addEventListener&&'file:'===window.location.protocol}),has.add('native-xhr2',function(){if(has('native-xhr')){var x=new XMLHttpRequest;return'undefined'!=typeof x.addEventListener&&('undefined'==typeof opera||'undefined'!=typeof x.upload)}}),has.add('native-formdata',function(){return'function'==typeof FormData});var isValid,isReady,addListeners,cancel;has('native-xhr2')?(isValid=function(){return!this.isFulfilled()},cancel=function(dfd,response){response.xhr.abort()},addListeners=function(_xhr,dfd,response){function onLoad(){dfd.handleResponse(response)}function onError(evt){var _xhr=evt.target,error=new RequestError('Unable to load '+response.url+' status: '+_xhr.status,response);dfd.handleResponse(response,error)}function onProgress(evt){evt.lengthComputable&&(response.loaded=evt.loaded,response.total=evt.total,dfd.progress(response))}return _xhr.addEventListener('load',onLoad,!1),_xhr.addEventListener('error',onError,!1),_xhr.addEventListener('progress',onProgress,!1),function(){_xhr.removeEventListener('load',onLoad,!1),_xhr.removeEventListener('error',onError,!1),_xhr.removeEventListener('progress',onProgress,!1),_xhr=null}}):(isValid=function(response){return response.xhr.readyState},isReady=function(response){return 4===response.xhr.readyState},cancel=function(dfd,response){var xhr=response.xhr,_at=typeof xhr.abort;('function'==_at||'object'==_at||'unknown'==_at)&&xhr.abort()});var defaultOptions={data:null,query:null,sync:!1,method:'GET'};if(xhr._create=function(){throw new Error('XMLHTTP not available')},has('native-xhr')&&!has('dojo-force-activex-xhr'))xhr._create=function(){return new XMLHttpRequest};else if(has('activex'))try{new ActiveXObject('Msxml2.XMLHTTP'),xhr._create=function(){return new ActiveXObject('Msxml2.XMLHTTP')}}catch(e){try{new ActiveXObject('Microsoft.XMLHTTP'),xhr._create=function(){return new ActiveXObject('Microsoft.XMLHTTP')}}catch(e){}}return util.addCommonMethods(xhr),xhr}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4),__webpack_require__(30)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,require){'use strict';var testDiv=document.createElement('div');has.add('dom-qsa2.1',!!testDiv.querySelectorAll),has.add('dom-qsa3',function(){try{return testDiv.innerHTML='<p class=\'TEST\'></p>',1==testDiv.querySelectorAll('.TEST:empty').length}catch(e){}});var acme='./acme',lite='./lite',fullEngine;return{load:function(id,parentRequire,loaded){var req=require;if(id='default'==id?has('config-selectorEngine')||'css3':id,id='css2'==id||'lite'==id?lite:'css2.1'==id?has('dom-qsa2.1')?lite:acme:'css3'==id?has('dom-qsa3')?lite:acme:'acme'==id?acme:(req=parentRequire)&&id,'?'==id.charAt(id.length-1)){id=id.substring(0,id.length-1)}return has('dom-compliant-qsa')||fullEngine?loaded(fullEngine):void req([id],function(engine){'./lite'!=id&&(fullEngine=engine),loaded(engine)})}}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){module.exports=void 0},function(module){module.exports={'gettingStationInformation':'Getting station information...','paused':'Paused','onAir':'On Air','disconnected':'Disconnected','streamUnavailable':'Stream unavailable','buffering':'Buffering','connecting':'Live stream connection in progress...','reconnecting':'Live stream connection in progress...','seekfailed':'Seek failed','seekinvalidtime':'Impossible to seek due to invali
1d time','ended':'Ended','pause':'Paused','play':'Playing','stop':'Stopped','error':'Error','streamGeoBlocked':'Sorry, this content is not available in your area','stationNotFound':'Station not found','flashPluginOutOfDate':'Your Flash plugin version detected is out of date. Minimum version required is: 10.2.0','browserNotSupported':'Your browser does not support HTML5 feature','embedFailed':'The embed failed!','playbackNotAllowed':'Playback of media in the current context or situation is not allowed','tritonListenLink':'The OnDemand player cannot be used with Triton listen links'}},function(module){function defaultSetTimout(){throw new Error('setTimeout has not been defined')}function defaultClearTimeout(){throw new Error('clearTimeout has not been defined')}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}var process=module.exports={},cachedSetTimeout,cachedClearTimeout;(function(){try{cachedSetTimeout='function'==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout='function'==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}})();var queue=[],draining=!1,queueIndex=-1,currentQueue;process.nextTick=function(fun){var args=Array(arguments.length-1);if(1<arguments.length)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title='browser',process.browser=!0,process.env={},process.argv=[],process.version='',process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(){return[]},process.binding=function(){throw new Error('process.binding is not supported')},process.cwd=function(){return'/'},process.chdir=function(){throw new Error('process.chdir is not supported')},process.umask=function(){return 0}},function(module){var swfobject=function(){function f(){if(!J){try{var Z=j.getElementsByTagName('body')[0].appendChild(C('span'));Z.parentNode.removeChild(Z)}catch(aa){return}J=!0;for(var X=U.length,Y=0;Y<X;Y++)U[Y]()}}function K(X){J?X():U[U.length]=X}function s(Y){if(typeof O.addEventListener!=D)O.addEventListener('load',Y,!1);else if(typeof j.addEventListener!=D)j.addEventListener('load',Y,!1);else if(typeof O.attachEvent!=D)i(O,'onload',Y);else if('function'==typeof O.onload){var X=O.onload;O.onload=function(){X(),Y()}}else O.onload=Y}function h(){T?V():H()}function V(){var X=j.getElementsByTagName('body')[0],aa=C(r);aa.setAttribute('type',q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable('$version');ab&&(ab=ab.split(' ')[1].split(','),M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)])}else if(10>Y)return Y++,void setTimeout(arguments.callee,10);X.removeChild(aa),Z=null,H()})()}else H()}function H(){var ag=o.length;if(0<ag)for(var af=0;af<ag;af++){var Y=o[af].id,ab=o[af].callbackFn,aa={success:!1,id:Y};if(0<M.pv[0]){var ae=c(Y);if(ae)if(F(o[af].swfVersion)&&!(M.wk&&312>
1M.wk))w(Y,!0),ab&&(aa.success=!0,aa.ref=z(Y),ab(aa));else if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall,ai.width=ae.getAttribute('width')||'0',ai.height=ae.getAttribute('height')||'0',ae.getAttribute('class')&&(ai.styleclass=ae.getAttribute('class')),ae.getAttribute('align')&&(ai.align=ae.getAttribute('align'));for(var ah={},X=ae.getElementsByTagName('param'),ac=X.length,ad=0;ad<ac;ad++)'movie'!=X[ad].getAttribute('name').toLowerCase()&&(ah[X[ad].getAttribute('name')]=X[ad].getAttribute('value'));P(ai,ah,Y,ab)}else p(ae),ab&&ab(aa)}else if(w(Y,!0),ab){var Z=z(Y);Z&&typeof Z.SetVariable!=D&&(aa.success=!0,aa.ref=Z),ab(aa)}}}function z(aa){var X=null,Y=c(aa);if(Y&&'OBJECT'==Y.nodeName)if(typeof Y.SetVariable!=D)X=Y;else{var Z=Y.getElementsByTagName(r)[0];Z&&(X=Z)}return X}function A(){return!a&&F('6.0.65')&&(M.win||M.mac)&&!(M.wk&&312>M.wk)}function P(aa,ab,X,Z){a=!0,E=Z||null,B={success:!1,id:X};var ae=c(X);if(ae){'OBJECT'==ae.nodeName?(l=g(ae),Q=null):(l=ae,Q=X),aa.id=R,(typeof aa.width==D||!/%$/.test(aa.width)&&310>parseInt(aa.width,10))&&(aa.width='310'),(typeof aa.height==D||!/%$/.test(aa.height)&&137>parseInt(aa.height,10))&&(aa.height='137'),j.title=j.title.slice(0,47)+' - Flash Player Installation';var ad=M.ie&&M.win?['Active'].concat('').join('X'):'PlugIn',ac='MMredirectURL='+O.location.toString().replace(/&/g,'%26')+'&MMplayerType='+ad+'&MMdoctitle='+j.title;if(typeof ab.flashvars==D?ab.flashvars=ac:ab.flashvars+='&'+ac,M.ie&&M.win&&4!=ae.readyState){var Y=C('div');X+='SWFObjectNew',Y.setAttribute('id',X),ae.parentNode.insertBefore(Y,ae),ae.style.display='none',function(){4==ae.readyState?ae.parentNode.removeChild(ae):setTimeout(arguments.callee,10)}()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&4!=Y.readyState){var X=C('div');Y.parentNode.insertBefore(X,Y),X.parentNode.replaceChild(g(Y),X),Y.style.display='none',function(){4==Y.readyState?Y.parentNode.removeChild(Y):setTimeout(arguments.callee,10)}()}else Y.parentNode.replaceChild(g(Y),Y)}function g(ab){var aa=C('div');if(M.win&&M.ie)aa.innerHTML=ab.innerHTML;else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad)for(var X=ad.length,Z=0;Z<X;Z++)(1!=ad[Z].nodeType||'PARAM'!=ad[Z].nodeName)&&8!=ad[Z].nodeType&&aa.appendChild(ad[Z].cloneNode(!0))}}return aa}function u(ai,ag,Y){var aa=c(Y),X;if(M.wk&&312>M.wk)return X;if(aa)if(typeof ai.id==D&&(ai.id=Y),M.ie&&M.win){var ah='';for(var ae in ai)ai[ae]!=Object.prototype[ae]&&('data'==ae.toLowerCase()?ag.movie=ai[ae]:'styleclass'==ae.toLowerCase()?ah+=' class="'+ai[ae]+'"':'classid'!=ae.toLowerCase()&&(ah+=' '+ae+'="'+ai[ae]+'"'));var af='';for(var ad in ag)ag[ad]!=Object.prototype[ad]&&(af+='<param name="'+ad+'" value="'+ag[ad]+'" />');aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+'>'+af+'</object>',N[N.length]=ai.id,X=c(ai.id)}else{var Z=C(r);for(var ac in Z.setAttribute('type',q),ai)ai[ac]!=Object.prototype[ac]&&('styleclass'==ac.toLowerCase()?Z.setAttribute('class',ai[ac]):'classid'!=ac.toLowerCase()&&Z.setAttribute(ac,ai[ac]));for(var ab in ag)ag[ab]!=Object.prototype[ab]&&'movie'!=ab.toLowerCase()&&e(Z,ab,ag[ab]);aa.parentNode.replaceChild(Z,aa),X=Z}return X}function e(Z,X,Y){var aa=C('param');aa.setAttribute('name',X),aa.setAttribute('value',Y),Z.appendChild(aa)}function y(Y){var X=c(Y);X&&'OBJECT'==X.nodeName&&(M.ie&&M.win?(X.style.display='none',function(){4==X.readyState?b(Y):setTimeout(arguments.callee,10)}()):X.parentNode.removeChild(X))}function b(Z){var Y=c(Z);if(Y){for(var X in Y)'function'==typeof Y[X]&&(Y[X]=null);Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y),I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split('.');return X[0]=parseInt(X[0],10),X[1]=parseInt(X[1],10)||0,X[2]=parseInt(X[2],10)||0,!!(Y[0]>X[0]||Y[0]==X[0]&&Y[1]>X[1]||Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2])}function v(ac,Y,ad,ab){if(!(M.ie&&M.mac)){var aa=j.getElementsByTagName('head')[0];if(aa){var X=ad&&'string'==typeof ad?ad:'screen';if(ab&&(n=null,G=null),!n||G!=X){var Z=C('style');Z.setAttribute('type','text/css'),Z.setAttribute('media',X),n=aa.appendChild(Z),M.ie&&M.win&&typeof j.styleSheets!=D&&0<j.styleSheets.length&&(n=j.styleSheets[j.styleSheets.length-1]),G=X}M.ie&&M.win?n&&typeof n.addRule==r&&n.addRule(ac,Y):n&&typeof j.createTextNode!=D&&n.appendChild(j.createTextNode(ac+' {'+Y+'}'))}}}function w(Z,X){if(m){var Y=X?'visible':'hidden';J&&c(Z)?c(Z).style.visibility=Y:v('#'+Z,'visibility:'+Y)}}function L(Y){var Z=/[\\\"<>\.;]/,X=null!=Z.exec(Y);return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var D='undefined',r='object',S='Shockwave Flash',q='application/x-shockwave-flash',R='SWFObjectExprInst',x='onreadystatechange',O=window,j=document,t=navigator,T=!1,U=[h],o=[],N=[],I=[],J=!1,a=!1,m=!0,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=!!/webkit/.test(ah)&&parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,'$1')),X=!1,ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r)ab=t.plugins[S].description,ab&&(typeof t.mimeTypes==D||!t.mimeTypes[q]||t.mimeTypes[q].enabledPlugin)&&(T=!0,X=!1,ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,'$1'),ag[0]=parseInt(ab.replace(/^(.*)\..*$/,'$1'),10),ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,'$1'),10),ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,'$1'),10):0);else if(typeof O[['Active'].concat('Object').join('X')]!=D)try{var ad=new window[['Active'].concat('Object').join('X')]('ShockwaveFlash.ShockwaveFlash');
1ad&&(ab=ad.GetVariable('$version'),ab&&(X=!0,ab=ab.split(' ')[1].split(','),ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]))}catch(Z){}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){M.w3&&((typeof j.readyState!=D&&'complete'==j.readyState||typeof j.readyState==D&&(j.getElementsByTagName('body')[0]||j.body))&&f(),!J&&(typeof j.addEventListener!=D&&j.addEventListener('DOMContentLoaded',f,!1),M.ie&&M.win&&(j.attachEvent(x,function(){'complete'==j.readyState&&(j.detachEvent(x,arguments.callee),f())}),O==top&&function(){if(!J){try{j.documentElement.doScroll('left')}catch(X){return void setTimeout(arguments.callee,0)}f()}}()),M.wk&&function(){return J?void 0:/loaded|complete/.test(j.readyState)?void f():void setTimeout(arguments.callee,0)}(),s(f)))}(),d=function(){M.ie&&M.win&&window.attachEvent('onunload',function(){for(var ac=I.length,ab=0;ab<ac;ab++)I[ab][0].detachEvent(I[ab][1],I[ab][2]);for(var Z=N.length,aa=0;aa<Z;aa++)y(N[aa]);for(var Y in M)M[Y]=null;for(var X in M=null,swfobject)swfobject[X]=null;swfobject=null})}(),l,Q,E,B,n,G;return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab,Y.swfVersion=X,Y.expressInstall=aa,Y.callbackFn=Z,o[o.length]=Y,w(ab,!1)}else Z&&Z({success:!1,id:ab})},getObjectById:function(X){if(M.w3)return z(X)},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:!1,id:ah};M.w3&&!(M.wk&&312>M.wk)&&ab&&ah&&ae&&ag&&Y?(w(ah,!1),K(function(){ae+='',ag+='';var aj={};if(af&&typeof af==r)for(var al in af)aj[al]=af[al];aj.data=ab,aj.width=ae,aj.height=ag;var am={};if(ad&&typeof ad==r)for(var ak in ad)am[ak]=ad[ak];if(Z&&typeof Z==r)for(var ai in Z)typeof am.flashvars==D?am.flashvars=ai+'='+Z[ai]:am.flashvars+='&'+ai+'='+Z[ai];if(F(Y)){var an=u(aj,am,ah);aj.id==ah&&w(ah,!0),X.success=!0,X.ref=an}else{if(aa&&A())return aj.data=aa,void P(aj,am,ah,ac);w(ah,!0)}ac&&ac(X)})):ac&&ac(X)},switchOffAutoHideShow:function(){m=!1},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){return M.w3?u(Z,Y,X):void 0},showExpressInstall:function(Z,aa,X,Y){M.w3&&A()&&P(Z,aa,X,Y)},removeSWF:function(X){M.w3&&y(X)},createCSS:function(aa,Z,Y,X){M.w3&&v(aa,Z,Y,X)},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)&&(Z=Z.split('?')[1]),null==aa)return L(Z);for(var Y=Z.split('&'),X=0;X<Y.length;X++)if(Y[X].substring(0,Y[X].indexOf('='))==aa)return L(Y[X].substring(Y[X].indexOf('=')+1))}return''},expressInstallCallback:function(){if(a){var X=c(R);X&&l&&(X.parentNode.replaceChild(l,X),Q&&(w(Q,!0),M.ie&&M.win&&(l.style.display='block')),E&&E(B)),a=!1}}}}();module.exports=swfobject},function(module,exports,__webpack_require__){var LocationHelper=__webpack_require__(24),PROTOCOL=LocationHelper.getProtocol(),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var tritonRunSpot4Helper=declare([],{ENDPOINT:PROTOCOL+'//runspot4.tritondigital.com/RunSpotV4.svc/GetVASTAd?&StationID={sid}&MediaFormat={mediaformat}&RecordImpressionOnCall={recordimpressiononcall}&AdMinimumDuration={adminimumduration}&AdMaximumDuration={admaximumduration}&AdLevelPlacement={adlevelplacement}&AdCategory={adcategory}',mediaAdBlankFiles:['blank.flv','9483.mp3'],getVastUri:function(apiBaseUrl,sid,mediaformat,adlevelplacement,recordimpressiononcall,adminimumduration,admaximumduration,adcategory){var mediaformat=void 0==mediaformat?'21':mediaformat,adlevelplacement=void 0==adlevelplacement?'1':adlevelplacement,recordimpressiononcall=void 0!=recordimpressiononcall&&recordimpressiononcall,adminimumduration=void 0==adminimumduration?'0':adminimumduration,admaximumduration=void 0==admaximumduration?'900':admaximumduration,adcategory=void 0==adcategory?'1':adcategory,requestUri=void 0==apiBaseUrl?this.ENDPOINT:apiBaseUrl;return requestUri=requestUri.replace('{sid}',sid),requestUri=requestUri.replace('{mediaformat}',parseInt(mediaformat)),requestUri=requestUri.replace('{adlevelplacement}',parseInt(adlevelplacement)),requestUri=requestUri.replace('{recordimpressiononcall}',recordimpressiononcall),requestUri=requestUri.replace('{adminimumduration}',parseInt(adminimumduration)),requestUri=requestUri.replace('{admaximumduration}',parseInt(admaximumduration)),requestUri=requestUri.replace('{adcategory}',parseInt(adcategory)),requestUri}});return tritonRunSpot4Helper}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){module.exports={LIVE_STREAMING:'liveStreaming',CLOUD_STREAMING:'cloudStreaming'}},function(module,exports,__webpack_require__){var xmlParser=__webpack_require__(15),Platform=__webpack_require__(14),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(12),__webpack_require__(42),__webpack_require__(33),__webpack_require__(9),__webpack_require__(16)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,coreModule,TrackCuePoint,BreakCuePoint,XhrProvider,Deferred){var module=declare([coreModule],{cuePointMap:{timestamp:'timestamp',type:'type',cue_title:TrackCuePoint.CUE_TITLE,track_artist_name:TrackCuePoint.ARTIST_NAME,track_album_name:TrackCuePoint.ALBUM_NAME,program_id:TrackCuePoint.PROGRAM_ID,cue_time_duration:TrackCuePoint.CUE_TIME_DURATION,cue_time_start:TrackCuePoint.CUE_TIME_START,track_id:TrackCuePoint.TRACK_ID,track_nowplaying_url:TrackCuePoint.NOW_PLAYING_URL,track_cover_url:TrackCuePoint.TRACK_COVER_URL,ad_id:BreakCuePoint.AD_ID,ad_type:BreakCuePoint.AD_TYPE,cue_title:BreakCuePoint.CUE_TITLE,cue_time_duration:BreakCuePoint.CUE_TIME_DURATION,ad_url:BreakCuePoint.AD_URL},constructor:function(config){void 0,this.inherited(arguments),this.platform=new Platform(config.platformId)}
1,start:function(){void 0,this.emit('module-ready',{id:'NowPlayingApi',module:this})},load:function(data){var deferred=new Deferred,requestArgs=this._getRequestArgs(data.hd?data.mount+'AAC':data.mount,data.numberToFetch,data.eventType||'track',data.mode),xhrProv=new XhrProvider;return xhrProv.request(this.platform.endpoint.nowPlayingHistory,{mount:data.mount,mode:data.mode||'songHistory',deferred:deferred},requestArgs,lang.hitch(this,this._onLoadComplete),lang.hitch(this,this._onLoadError)),deferred},_onLoadError:function(requestData){return this.emit('nowplaying-api-error',{mount:requestData.mount,error:requestData.error}),requestData.deferred.reject({mount:requestData.mount,error:requestData.error})},_onLoadComplete:function(requestData,data){void 0,data=data.getElementsByTagName('nowplaying-info');for(var list=[],i=0,cuePoint,npInfoAttr,propName,propValue,type,timestamp;i<data.length;i++){type=data[i].getAttribute('type'),timestamp=data[i].getAttribute('timestamp'),npInfoAttr=data[i].childNodes,cuePoint={parameters:{}},cuePoint[this.cuePointMap.type]=type,cuePoint[this.cuePointMap.timestamp]=parseInt(timestamp);for(var j=0;j<npInfoAttr.length;j++)propName=npInfoAttr[j].getAttribute('name'),propValue=xmlParser.textContent(npInfoAttr[j]),void 0!=this.cuePointMap[propName]&&(cuePoint[this.cuePointMap[propName]]=propValue),cuePoint.parameters[propName]=propValue;list.push(cuePoint)}0<list.length&&list[0].cueTimeStart?list=list.sort(function(a,b){return a.cueTimeStart-b.cueTimeStart}).reverse():0<list.length&&!list[0].cueTimeStart&&(list=list.sort(function(a,b){return a.timestamp-b.timestamp}).reverse()),this._emitNotificationByMode(requestData.mount,requestData.mode,list),requestData.deferred.resolve({mount:requestData.mount,list:list})},_emitNotificationByMode:function(mount,mode,list){switch(mode){case'songHistory':this._emitSongHistoryNotification(mount,list);break;case'nowPlaying':this._emitNowPlayingNotification(mount,list);break;default:}},_emitSongHistoryNotification:function(mount,list){0<list.length?this.emit('list-loaded',{mount:mount,list:list}):this.emit('list-empty',{mount:mount})},_emitNowPlayingNotification:function(mount,list){0<list.length?this.emit('cue-point',{mount:mount,cuePoint:list[0]}):this.emit('cue-point-empty',{mount:mount})},_getRequestArgs:function(mount,numberToFetch,eventType,mode){return{handleAs:'xml',preventCache:!0,headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'},query:{mountName:mount,numberToFetch:'nowPlaying'==mode?1:numberToFetch,eventType:eventType}}}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var MediaElement=__webpack_require__(25),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__,__webpack_require__(16),__webpack_require__(3),__webpack_require__(11),__webpack_require__(8),__webpack_require__(32),__webpack_require__(111),__webpack_require__(9),__webpack_require__(128),__webpack_require__(130),__webpack_require__(129),__webpack_require__(34)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,require,Deferred,on,domConstruct,dom,AdServerType,TritonAdPlatformHelper,XhrProvider,ImaSdkModule,VASTAdModule,MediaAdModule,GAEventRequest){var adManager=declare([],{AD_PLAYBACK_START:'ad-playback-start',AD_PLAYBACK_COMPLETE:'ad-playback-complete',AD_PLAYBACK_DESTROY:'ad-playback-destroy',AD_PLAYBACK_ERROR:'ad-playback-error',AD_COUNTDOWN:'ad-countdown',AD_QUARTILE:'ad-quartile',VAST_COMPANIONS_READY:'vast-companions-ready',VAST_COMPANIONS_VPAID:'vast-companions-vpaid',AD_BLOCKER_DETECTED:'ad-blocker-detected',STREAMING_GUIDE_VERSION:'1.5.1',constructor:function(tech,techType,target,config){void 0,this.target=target,this.config=config,this.playerNode=dom.byId(this.config.playerId,document),this.tech=tech,this.techType=techType,this.adServerType=null,this.adModules=[],this.currentAdModule=null,this.xhrProv=new XhrProvider,config.adBlockerDetected||(this.imaSdkModule=new ImaSdkModule(target,config),this.VASTAdModule=new VASTAdModule(target,config),this.mediaAdModule=new MediaAdModule(target,config)),this.inherited(arguments),this._adPrerollTime=0,this._adPrerollTimeIntervall=null,this._adParser=null,this._adSource=null,this._adFormat=null,on(this.target,'ad-playback-start',lang.hitch(this,this._onAdPlaybackStart)),on(this.target,'ad-playback-error',lang.hitch(this,this._onAdPlaybackError))},playAd:function(adServerType,config){var self=this;if(this.adServerType=adServerType,!0!==config.adBreak&&MediaElement.init(),this.config.adBlockerDetected)return void(!0!=config.adBreak&&this.target.emit(this.AD_BLOCKER_DETECTED,{data:{message:'playAd function has been disabled because Ad Blocker is activated'}}));if(self._adPrerollTime=0,this._adPrerollTimeIntervall=setInterval(function(){self._adPrerollTime+=10},10),this.destroyAd(!1),adServerType==AdServerType.TRITON_AD_PLATFORM&&(adServerType=AdServerType.VAST_AD,config=this._convertTAPConfigToVast(config)),config.url&&(config.url=this._generateUrl(config)),null==config.url&&void 0==config.mediaUrl&&void 0==config.rawXML&&void 0==config.sid)return void this.target.emit(this.AD_PLAYBACK_ERROR,{data:{type:null,error:!0}});switch(config.url?(config.fallbackToVastPlugin=-1<config.url.toLowerCase().indexOf('daast')||-1<config.url.toLowerCase().indexOf('/ondemand/ars')||-1<config.url.toLowerCase().indexOf('s3'),this._adFormat=-1<config.url.toLowerCase().indexOf('daast')?'DAAST':'VAST',this._adSource=-1<config.url.toLowerCase().indexOf('daast')?'TAP':config.sid?'CM3':'Others'):config.rawXML&&(config.fallbackToVastPlugin=-1<config.rawXML.toLowerCase().indexOf('daast'),this._adFormat=-1<config.rawXML.toLowerCase().indexOf('daast')?'DAAST':'VAST',this._adSource=-1<config.rawXML.toLowerCase().indexOf('daast')?'TAP':config.sid?'CM3':'Others'),this.tech.prepare('adModule'),adServerType){case AdServerType.VAST_AD:config.adBreak||config.fallbackToVastPlugin?(this._initAdModule(this.VASTAdModule,config),this._adParser='VASTModule'):(this._initAdModule(this.imaSdkModule,config),this._adParser='IMA');break;case AdServerType.MEDIA_AD:this._initAdModule(this.mediaAdModule,config),this._adParser='Direct';break;default:this.target.emit(this.AD_PLAYBACK_COMPLETE,{data:{type:null,error:!1}});}}
1,skipAd:function(){return'Flash'==this.techType?void this.tech.skipAd():void(this.currentAdModule&&this.currentAdModule.skipAd())},destroyAd:function(shouldRemoveAdsRef){return'Flash'==this.techType?void this.tech.destroyAd(shouldRemoveAdsRef):void(this.currentAdModule&&this.currentAdModule.destroyAd(shouldRemoveAdsRef))},reloadSyncBanner:function(){return'Flash'==this.techType?void this.tech.reloadSyncBanner():void(this.currentAdModule&&(this.adServerType==AdServerType.VAST_AD||this.adServerType==AdServerType.TRITON_AD_PLATFORM)&&this.currentAdModule.reloadSyncBanner())},_initAdModule:function(module,adConfig){void 0,this._removeListeners(),this.currentAdModule=module,this._mediaAdReadyHandler=on(this.target,this.currentAdModule.AD_MODULE_MEDIA_READY,lang.hitch(this,this._onMediaAdReady)),this._mediaAdEmptyHandler=on(this.target,this.currentAdModule.AD_MODULE_MEDIA_EMPTY,lang.hitch(this,this._onMediaAdEmpty)),this._adCountdownHandler=on(this.target,this.currentAdModule.AD_MODULE_COUNTDOWN,lang.hitch(this,this._onAdModuleCountdown)),this._adModulePlaybackStartHandler=on(this.target,this.currentAdModule.AD_MODULE_PLAYBACK_START,lang.hitch(this,this._onAdModulePlaybackStart)),this._adModulePlaybackCompleteHandler=on(this.target,this.currentAdModule.AD_MODULE_PLAYBACK_COMPLETE,lang.hitch(this,this._onAdModulePlaybackComplete)),this._adModulePlaybackDestroyHandler=on(this.target,this.currentAdModule.AD_MODULE_PLAYBACK_DESTROY,lang.hitch(this,this._onAdModulePlaybackDestroy)),this._adModulePlaybackErrorHandler=on(this.target,this.currentAdModule.AD_MODULE_PLAYBACK_ERROR,lang.hitch(this,this._onAdModulePlaybackError)),this._adModuleQuartileHandler=on(this.target,this.currentAdModule.AD_MODULE_QUARTILE,lang.hitch(this,this._onAdModuleQuartile)),this._adModuleCompanionsHandler=on(this.target,this.currentAdModule.AD_MODULE_COMPANIONS,lang.hitch(this,this._onAdModuleCompanions)),this._adModuleClickTrackingHandler=on(this.target,this.currentAdModule.AD_MODULE_CLICK_TRACKING,lang.hitch(this,this._onAdModuleClickTracking)),this._adModuleVastEmptyHandler=on(this.target,this.currentAdModule.AD_MODULE_VAST_EMPTY,lang.hitch(this,this._onAdError)),this._adModuleVastErrorHandler=on(this.target,this.currentAdModule.AD_MODULE_VAST_ERROR,lang.hitch(this,this._onAdError)),this.currentAdModule.init(adConfig),this.currentAdModule.initAdListeners(this.tech.html5OnDemand)},_onAdPlaybackStart:function(e){var gaDimensions={};gaDimensions[GAEventRequest.DIM_AD_SOURCE]=this._adSource,gaDimensions[GAEventRequest.DIM_AD_FORMAT]=this._adFormat,gaDimensions[GAEventRequest.DIM_AD_PARSER]=this._adParser?this._adParser:e.data&&e.data.playerData&&e.data.playerData.adParser?e.data.playerData.adParser:'';var gaMetrics={};gaMetrics[GAEventRequest.METRIC_CONNECTION_TIME]=this._adPrerollTime,GAEventRequest.requestGA(GAEventRequest.CATEGORY_AD,GAEventRequest.ACTION_PREROLL,GAEventRequest.LABEL_SUCCESS,gaDimensions,gaMetrics),clearInterval(this._adPrerollTimeIntervall)},_onAdPlaybackError:function(e){var gaDimensions={};gaDimensions[GAEventRequest.DIM_AD_SOURCE]=this._adSource,gaDimensions[GAEventRequest.DIM_AD_FORMAT]=this._adFormat,gaDimensions[GAEventRequest.DIM_AD_PARSER]=this._adParser?this._adParser:e.data&&e.data.playerData&&e.data.playerData.adParser?e.data.playerData.adParser:'';var gaMetrics={};gaMetrics[GAEventRequest.METRIC_CONNECTION_TIME]=this._adPrerollTime,GAEventRequest.requestGA(GAEventRequest.CATEGORY_AD,GAEventRequest.ACTION_PREROLL,GAEventRequest.LABEL_ERROR,gaDimensions,gaMetrics),clearInterval(this._adPrerollTimeIntervall)},_onAdModuleCompanions:function(e){void 0,this.currentAdModule.emit(this.VAST_COMPANIONS_READY,e.data)},_onAdModulePlaybackStart:function(e){void 0,this._callImpressions(),this.currentAdModule.emit(this.AD_PLAYBACK_START,{type:e.data.type})},_onAdModulePlaybackComplete:function(e){void 0,this._removeListeners(),this.currentAdModule.emit(this.AD_PLAYBACK_COMPLETE,{type:e.data.type})},_onAdModulePlaybackDestroy:function(){void 0,this._removeListeners(),this.currentAdModule.emit(this.AD_PLAYBACK_DESTROY)},_onAdModulePlaybackError:function(e){void 0,this._removeListeners(),this.currentAdModule.emit(this.AD_PLAYBACK_ERROR,{type:e.data.type})},_onAdModuleCountdown:function(e){void 0,void 0,this.currentAdModule.emit(this.AD_COUNTDOWN,{countDown:e.data.countDown})},_onAdModuleClickTracking:function(e){if(null!=e&&void 0!=e.data){var clickThrough=void 0==e.data.clickThrough?null:e.data.clickThrough,clickTrackings=void 0==e.data.clickTrackings?null:e.data.clickTrackings,pattern=/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/,isWebUrl=pattern.test(clickThrough);if(null!=clickThrough&&!0==isWebUrl&&window.open(clickThrough),clickTrackings)for(var clickTrackingsLength=clickTrackings.length,i=0;i<clickTrackingsLength;i++)this.xhrProv.request(clickTrackings[i],null,{method:'GET',handleAs:'text',headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}})}},_onAdModuleQuartile:function(e){if(this.currentAdModule.getVastInlineAd())for(var trackingEvents=this.currentAdModule.getVastInlineAd().getLinearTrackingEvents(this.currentAdModule._defaultSequence),trackingEventsLength=trackingEvents.length,i=0;i<trackingEventsLength;i++)if(trackingEvents[i].type==e.adQuartile)for(var urls=trackingEvents[i].urls,urlsLength=urls.length,j=0;j<urlsLength;j++)this.xhrProv.request(urls[j],null,{method:'GET',handleAs:'text',headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}})},_onMediaAdReady:function(e){var data=e.data,mediaFile=this._getSupportedMediaFile(data);null==mediaFile?this.target.emit(this.AD_PLAYBACK_ERROR,{data:{type:data.adServerType,error:!1}}):this.tech.html5OnDemand.playAd({adServerType:data.adServerType,mediaUrl:mediaFile.url,mediaFormat:mediaFile.format,clickThrough:data.clickThrough,clickTrackings:data.clickTrackings})},_onMediaAdEmpty:function(e){var data=e.data;this._removeListeners(),this.currentAdModule.emit(this.AD_PLAYBACK_COMPLETE,{type:data.adServerType,error:!1})},_onAdError:function(e){var data=e.data;this._removeListeners(),this.currentAdModule.emit(this.AD_PLAYBACK_ERROR,{type:data.adServerType,error:!1})},_removeListeners:function(){void 0,this._mediaAdReadyHandler&&this._mediaAdReadyHandler.remove(),this._mediaAdEmptyHandler&&this._mediaAdEmptyHandler.remove(),this._adCountdownHandler&&this._adCountdownHandler.remove(),this._adModulePlaybackStartHandler&&this._adModulePlaybackStartHandler.remove(),this._adModulePlaybackCompleteHandler&&this._adModulePlaybackCompleteHandler.remove(),this._adModulePlaybackErrorHandler&&this._adModulePlaybackErrorHandler.remove(),this._adModuleQuartileHandler&&this._adModuleQuartileHandler.remove(),this._adModuleClickTrackingHandler&&this._adModuleClickTrackingHandler.remove(),this._adModuleVastEmptyHandler&&this._adModuleVastEmptyHandler.remove(),this._adModuleVastErrorHandler&&this._adModuleVastErrorHandler.remove(),this._adModuleVastProcessCompleteHandler&&this._adModuleVastProcessCompleteHandler.remove(),this._adModuleCompanionsHandler&&this._adModuleCompanionsHandler.remove(),this._adModulePlaybackDestroyHandler&&this._adModulePlaybackDestroyHandler.remove()},_callImpressions:function(){if(this.currentAdModule.getVastInlineAd()){var impressions=this.currentAdModule.getVastInlineAd().impressions;
1if(impressions){var impressionsLength=impressions.length;if(0==impressionsLength)return;for(var i=0;i<impressionsLength;i++)this.xhrProv.request(impressions[i],null,{method:'GET',handleAs:'text',headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}})}}},_getAdModuleById:function(Module,moduleId){var adModulesLength=this.adModules.length;if(0==adModulesLength){var newModule=new Module(this.target,this.config);return this.adModules.push({moduleId:moduleId,module:newModule}),newModule}for(var i=0;i<adModulesLength;i++)if(this.adModules[i].moduleId==moduleId)return this.adModules[i].module;var newModule=new Module(this.target,this.config);return this.adModules.push({moduleId:moduleId,module:newModule}),newModule},_getSupportedMediaFile:function(data){if(null==data)return null;switch(data.adServerType){case AdServerType.VAST_AD:case AdServerType.MEDIA_AD:if(null==data.mediaFiles||0==data.mediaFiles.length)return null;for(var mediaFiles=data.mediaFiles,mediaFilesLength=mediaFiles.length,i=0,j;i<mediaFilesLength;i++){if(j=this._isTypeSupported('video','video/mp4;'),('audio/aac'==mediaFiles[i].type||'aac'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('audio','audio/aac;'))return{url:mediaFiles[i].url,format:'audio'};if(('audio/mp4'==mediaFiles[i].type||'m4a'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('audio','audio/mp4;'))return{url:mediaFiles[i].url,format:'audio'};if(('audio/mpeg'==mediaFiles[i].type||'mp3'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('audio','audio/mpeg;'))return{url:mediaFiles[i].url,format:'audio'};if(('audio/wav'==mediaFiles[i].type||'wav'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('audio','audio/wav;'))return{url:mediaFiles[i].url,format:'audio'};if(('audio/ogg'==mediaFiles[i].type||'oga'==mediaFiles[i].url.split('.').pop()||'ogg'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('audio','audio/ogg;'))return{url:mediaFiles[i].url,format:'audio'};if('audio/webm'==mediaFiles[i].type&&this._isTypeSupported('audio','audio/webm;'))return{url:mediaFiles[i].url,format:'audio'};if(('video/mp4'==mediaFiles[i].type||'mp4'==mediaFiles[i].url.split('.').pop()||'m4v'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('video','video/mp4;'))return{url:mediaFiles[i].url,format:'video'};if(('video/ogg'==mediaFiles[i].type||'ogv'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('video','video/ogg;'))return{url:mediaFiles[i].url,format:'video'};if(('video/webm'==mediaFiles[i].type||'webm'==mediaFiles[i].url.split('.').pop())&&this._isTypeSupported('video','video/webm;'))return{url:mediaFiles[i].url,format:'video'}}return null;break;default:return null;}},_isTypeSupported:function(format,mimetype){var html5CheckerNode=dom.byId('tdplayer_od_videonode',document);return!!html5CheckerNode.canPlayType&&html5CheckerNode.canPlayType(mimetype)},_convertTAPConfigToVast:function(adConfig){var tritonAdPlatformHelper=new TritonAdPlatformHelper;return adConfig.url=tritonAdPlatformHelper.getVastUri(adConfig),adConfig},_generateUrl:function(adConfig){if(adConfig!=void 0&&adConfig.url!=void 0){if(-1<adConfig.url.indexOf('/ondemand/ars')&&void 0!=adConfig.trackingParameters){var delimiter;void 0!=adConfig.trackingParameters.tdsdk&&(delimiter=-1<adConfig.url.indexOf('?')?'&':'?',adConfig.url+=delimiter+'tdsdk='+adConfig.trackingParameters.tdsdk),void 0!=adConfig.trackingParameters.position&&void 0!=adConfig.trackingParameters.position.coords.latitude&&void 0!=adConfig.trackingParameters.position.coords&&void 0!=adConfig.trackingParameters.position.coords.longitude&&(delimiter=-1<adConfig.url.indexOf('?')?'&':'?',adConfig.url+=delimiter+'lat='+parseFloat(adConfig.trackingParameters.position.coords.latitude.toFixed(1))+'&long='+parseFloat(adConfig.trackingParameters.position.coords.longitude.toFixed(1))),void 0!=adConfig.trackingParameters.banners&&(delimiter=-1<adConfig.url.indexOf('?')?'&':'?',adConfig.url+=delimiter+'banners='+adConfig.trackingParameters.banners);var cloneTrackingParams=lang.clone(adConfig.trackingParameters);for(var key in delete cloneTrackingParams.tdsdk,delete cloneTrackingParams.position,delete cloneTrackingParams.banners,delete cloneTrackingParams.pname,delete cloneTrackingParams.pversion,cloneTrackingParams)delimiter=-1<adConfig.url.indexOf('?')?'&':'?',adConfig.url+=delimiter+key+'='+encodeURIComponent(cloneTrackingParams[key]);return adConfig.url+=delimiter+'version='+this.STREAMING_GUIDE_VERSION,adConfig.url}return adConfig.url}}});return adManager}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vast2Creative=declare([],{constructor:function(){void 0,this.id=null,this.adID=null,this.sequence=null,this.linearElement=null,this.companionAds=[],this.nonLinearAds=[]}});return vast2Creative}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vast2InlineAd=declare([],{constructor:function(){void 0,this.creatives=[],this.inherited(arguments)},addWrapperLinearTrackingEvents:function(value){var linearElement=this._getLinearElement();
1null!=linearElement&&(linearElement.trackingEvents=linearElement.trackingEvents.concat(value))},addWrapperLinearVideoClickTracking:function(value){var linearElement=this._getLinearElement();null!=linearElement&&null!=linearElement.videoClick&&(linearElement.videoClick.clickTrackings=linearElement.videoClick.clickTrackings.concat(value))},addImpressions:function(value){null!=value&&(this.impressions=this.impressions.concat(value))},addCustomClicks:function(value){var linearElement=this._getLinearElement();null!=linearElement&&null!=linearElement.videoClick&&(linearElement.videoClick.customClicks=linearElement.videoClick.customClicks.concat(value))},getLinearTrackingEvents:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),null==this._getLinearElement()?null:this._getLinearElement().trackingEvents},getCompanionAdUrl:function(width,height,vastResourceType,sequence){var companionAds=this.getCompanionAds(sequence);if(null==companionAds)return null;for(var dimensionFit=!1,arrayLength=companionAds.length,i=0;i<arrayLength;i++)if(dimensionFit=companionAds[i].width==width&&companionAds[i].height==height,!0!=dimensionFit){if(null==vastResourceType)return companionAds[i];if(companionAd.resourceType==vastResourceType)return companionAds[i]}return null},getCompanionAds:function(sequence){var sequence=sequence;sequence==void 0&&(sequence=-1);for(var collectionLength=this.creatives.length,i=0;i<collectionLength;i++)if(0<this.creatives[i].companionAds.length){if(-1==sequence)return this.creatives[i].companionAds;if(this.creatives[i].sequence==sequence)return this.creatives[i].companionAds}},getLinearMediaFiles:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),null==this._getLinearElement(sequence)?null:this._getLinearElement(sequence).mediaFiles},getLinearMediaFileByIndex:function(index,sequence){var sequence=sequence;void 0==sequence&&(sequence=-1);var index=index;return void 0==index&&(index=0),null==this._getLinearElement(sequence).mediaFiles[index]?null:this._getLinearElement(sequence).mediaFiles[index]},getLinearVideoClick:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),null==this._getLinearElement(sequence).videoClick?null:this._getLinearElement(sequence).videoClick},getNonLinearAds:function(sequence){var sequence=sequence;sequence==void 0&&(sequence=-1);for(var collectionLength=this.creatives.length,j=0;j<collectionLength;j++)if(0<this.creatives[j].nonLinearAds.length){if(-1==sequence)return this.creatives[j].nonLinearAds;if(this.creatives[j].sequence==sequence)return this.creatives[j].nonLinearAds}},getLinearDuration:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),null==this._getLinearElement(sequence).duration?null:this._getLinearElement(sequence).duration},_getLinearElement:function(sequence){var sequence=sequence;sequence==void 0&&(sequence=-1);for(var collectionLength=this.creatives.length,i=0;i<collectionLength;i++)if(null!=this.creatives[i].linearElement){if(-1==sequence)return this.creatives[i].linearElement;if(this.creatives[i].sequence==sequence)return this.creatives[i].linearElement}}});return vast2InlineAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastLinearElement=declare([],{constructor:function(){void 0,this.duration=null,this.trackingEvents=[],this.videoClick=null,this.mediaFiles=[]}});return vastLinearElement}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastNonLinearAd=declare([],{constructor:function(){void 0,this.id=null,this.width=0,this.height=0,this.expandedWidth=0,this.expandedHeight=0,this.resourceType=null,this.creativeType=null,this.url=null,this.co
1de=null,this.clickThroughURL=null,this.adParameters=null,this.scalable=!1,this.maintainAspectRatio=!1,this.apiFramework=null,this.minSuggestedDuration=null}});return vastNonLinearAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var i18n=__webpack_require__(19),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var errorCode=declare([],{constructor:function(){var e=i18n.getLocalization();this.flashModuleMap={flashPluginOutOfDate:{code:100,message:e.flashPluginOutOfDate}},this.html5ModuleMap={browserNotSupported:{code:101,message:e.browserNotSupported},tritonListenLink:{code:102,message:e.tritonListenLink}}}});return errorCode}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(4),__webpack_require__(3),__webpack_require__(8),__webpack_require__(12),__webpack_require__(18),__webpack_require__(55),__webpack_require__(34),__webpack_require__(9)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,has,on,dom,coreModule,topic,ioQuery,GAEventRequest,XhrProvider){var module=declare([coreModule],{TIME_OUT_MESSAGE_DELAY:3e4,constructor:function(config,target,type){void 0,this.type=type,this.volume=1,this.xhrProv=new XhrProvider,this.params=null,this.connection=null,this._track=null,this._currentLiveApiParams=null,this.isLiveStream=!1,this.lowActivated=!1,this.playAdCalled=!1,this.mount=null,this.station=null,this.__resetBackOff(),this.config=config,config&&config.playerId&&(this.playerNode=dom.byId(config.playerId,document)),config&&config.mount&&(this.mount=config.mount),config&&config.station&&(this.station=config.station),this.hls=!(config.hls!=void 0)||config.hls,this.audioAdaptive=config.audioAdaptive!=void 0&&config.audioAdaptive,this.__initSbmConfig(config),this._playConnectionTime=0,this._playConnectionTimeIntervall=null,this.isReconnect=!1},start:function(){void 0,on(this.target,'stream-start',lang.hitch(this,this.__onStreamStart)),on(this.target,'stream-stop',lang.hitch(this,this.__onStreamStop)),on(this.target,'stream-fail',lang.hitch(this,this.__onStreamFailed)),on(this.target,'media-playback-started',lang.hitch(this,this._onMediaPlaybackStarted)),on(this.target,'media-playback-error',lang.hitch(this,this._onMediaPlaybackError)),on(this.target,'ad-break-cue-point',lang.hitch(this,this.__onAdBreakCuePoint))},play:function(params){if(this.isReconnect=!1,null!=params)return this.params=params,void 0!=params.file&&''!=params.file?(this.isLiveStream=!1,this.__extractOmnyParameters(params),void this.__playMedia(params)):void(this._currentLiveApiParams=params,this.connectionIterator?(this.isLiveStream=!0,this.__connect(this.connectionIterator.current())):void 0)},changePlayBackRate:function(rate){this.changeHtml5PlayBackRate(rate)},setConnectionIterator:function(connectionIterator){this.connectionIterator=connectionIterator},currentConnection:function(){return this.connection},currentTrack:function(){return this._track},setCurrentTrack:function(track){this._track=track},_onMediaPlaybackStarted:function(){GAEventRequest.requestGA(GAEventRequest.CATEGORY_ON_DEMAND,GAEventRequest.ACTION_PLAY,GAEventRequest.LABEL_SUCCESS)},_onMediaPlaybackError:function(){GAEventRequest.requestGA(GAEventRequest.CATEGORY_ON_DEMAND,GAEventRequest.ACTION_PLAY,GAEventRequest.LABEL_ERROR)},__onStreamStart:function(){void 0,this.__resetBackOff(),this._currentLiveApiParams&&0<this._currentLiveApiParams.connectionTimeOut&&(void 0,this.connectionTimeOutTimer=setInterval(lang.hitch(this,this.__onTimeOutAlert),6e4*this._currentLiveApiParams.connectionTimeOut));var gaDimensions={};this.connection&&(gaDimensions[GAEventRequest.DIM_MEDIA_TYPE]=this.connection.type,gaDimensions[GAEventRequest.DIM_MOUNT]=this.connection.mount?this.connection.mount:'',gaDimensions[GAEventRequest.DIM_STATION]=this._currentLiveApiParams.station?this._currentLiveApiParams.station:'',gaDimensions[GAEventRequest.DIM_HLS]=this.hls,gaDimensions[GAEventRequest.DIM_AUDIO_ADAPTIVE]=this.audioAdaptive);({})[GAEventRequest.METRIC_CONNECTION_TIME]=this._playConnectionTime,GAEventRequest.requestGA(GAEventRequest.CATEGORY_STREAMING,GAEventRequest.ACTION_PLAY,GAEventRequest.LABEL_SUCCESS)},__onStreamStop:function(){void 0,this.breakTimer&&clearInterval(this.breakTimer),this.connectionTimeOutTimer&&clearInterval(this.connectionTimeOutTimer)},__onStreamFailed:function(){void 0,this.__reconnect()},__onStreamUnmute:function(){this.connectionIterator&&this.__reconnect()},__reconnect:function(){if(this.isReconnect=!0,!!this.connectionIterator)if(this.connectionIterator.hasLooped()){var delay=Math.min(this.backOffDelay<<this.backOffRetry++,6e4);if(6e4<=delay){var gaDimensions={};gaDimensions[GAEventRequest.DIM_MOUNT]=this.connection.mount?this.connection.mount:'',gaDimensions[GAEventRequest.DIM_STATION]=this._currentLiveApiParams.station?this._currentLiveApiParams.station:'',GAEventRequest.requestGA(GAEventRequest.CATEGORY_STREAMING,GAEventRequest.ACTION_CONNECTION,GAEventRequest.LABEL_UNAVAILABLE,gaDimensions)}this.backOffTimer=setTimeout(lang.hitch(this,this.__onBackOffTimeOut),delay)}else this.__connect(this.connectionIterator.next())},__onBackOffTimeOut:function(){void 0,this.connectionIterator.reset(),this.__connect(this.connectionIterator.next())},__resetBackOff:function(){void 0,this.backOffRetry=0,this.backOffDelay=4e3*Math.random()+1e3,this.backOffTimer&&clearTimeout(this.backOffTimer)},__playMedia:function(params){null==params||(!0==this.config.adStitcher&¶ms.trackingParameters&&(params.file+=(-1==params.file.indexOf('?')?'?':'&')+ioQuery.objectToQuery(params.trackingParameters).replace(/\./g,'%2E')),void 0,this.playMedia({url:params.file,omnyOrganizationId:params.omnyOrganizationId,omnyClipId:params.omnyClipId,omnySessionId:params.omnySessionId,enableOmnyAnalytics:params.enableOmnyAnalytics}))},__connect:function(connection){if(null!=connection){var self=this;this.connection=connection,null!=this.connection&&(this.mount=this.connection.mount?this.connection.mount:null),null!=this._currentLiveApiParams&&(this.station=this._currentLiveApiParams.station?this._currentLiveApiParams.station:null);var params=this._currentLiveApiParams.trackingParameters||{};this.lowActivated&&this.connection.isAudioAdaptive&&(params.utags='low-bw');var mimeType=this.connection.mimeType,streamUrl=this.connection.url;if(0<Object.keys(params).length){let sanitisedParams=this._sanitiseDistParam(streamUrl,JSON.parse(JSON.stringify(this._currentLiveApiParams.trackingParameters)));streamUrl=streamUrl+'?'+ioQuery.objectToQuery(sanitisedParams)+'&burst-time=15'}else streamUrl+='?burst-time=15';
1this.emit('stream-select'),this._playConnectionTime=0,this._playConnectionTimeIntervall||(this._playConnectionTimeIntervall=setInterval(function(){self._playConnectionTime+=10},10)),this.playStream({url:streamUrl,mimeType:mimeType,format:this.connection.format,timeShift:this._currentLiveApiParams.timeShift,forceTimeShift:this._currentLiveApiParams.forceTimeShift,uuidEnabled:this.connection.uuidEnabled,sendPageUrl:this.connection.sendPageUrl,hasVideo:this.connection.hasVideo,type:this.connection.type,mount:this.connection.mount,sbmConfig:this.__getSbmData(),isHLS:this.connection.isHLS,isHLSTS:this.connection.isHLSTS,wcmStationId:this.connection.wcmStationId,listenerTrackingURL:this.connection.listenerTrackingURL,isReconnect:this.isReconnect,mrHost:this.connection.mrHost,isProgram:this._currentLiveApiParams.isProgram,timeshiftOffset:this._currentLiveApiParams.offset,timeshiftEnabled:this._currentLiveApiParams.timeshiftEnabled})}},__getSbmData:function(){return null!=this._sbmConfig&&this._sbmConfig.active&&null!=this.connection.metadata&&null!=this.connection.metadata.sseSideband?(this._sbmConfig.info=this.connection.metadata.sseSideband,this._sbmConfig):this._sbmConfig},__onAdBreakCuePoint:function(e){void 0,void 0;var adBreakData=e.data.adBreakData;this.breakTimer&&clearInterval(this.breakTimer),0<adBreakData.duration&&this.__initBreakTimer(adBreakData.duration)},__initBreakTimer:function(duration){void 0,this.breakTimer=setInterval(lang.hitch(this,this.__onBreakTimerComplete),duration)},__onBreakTimerComplete:function(){void 0,this.breakTimer&&clearInterval(this.breakTimer),this.emit('ad-break-cue-point-complete')},__initSbmConfig:function(config){this._sbmConfig=config.sbm&&!config.sbm.active?{active:!1,aSyncCuePointFallback:void 0==config.sbm.aSyncCuePointFallback||config.sbm.aSyncCuePointFallback}:config.sbm&&config.sbm.active?{active:!0,aSyncCuePointFallback:void 0==config.sbm.aSyncCuePointFallback||config.sbm.aSyncCuePointFallback}:'Html5'==this.type?{active:!0,aSyncCuePointFallback:!0}:null},prepare:function(module){void 0,'adModule'===module&&(this.playAdCalled=!0)},playStream:function(){},pause:function(){void 0,!0==this.isLiveStream?this.pauseStream():this.pauseMedia(),GAEventRequest.requestGA(GAEventRequest.CATEGORY_DEFAULT,GAEventRequest.ACTION_PAUSE,GAEventRequest.LABEL_SUCCESS,this.getDefaultGADimensions())},stop:function(){void 0,this.isLiveStream?(this.__resetBackOff(),this.stopStream()):this.stopMedia(),GAEventRequest.requestGA(GAEventRequest.CATEGORY_DEFAULT,GAEventRequest.ACTION_STOP,GAEventRequest.LABEL_SUCCESS,this.getDefaultGADimensions())},resume:function(){void 0,!0==this.isLiveStream?this.resumeStream():this.resumeMedia(),GAEventRequest.requestGA(GAEventRequest.CATEGORY_DEFAULT,GAEventRequest.ACTION_RESUME,GAEventRequest.LABEL_SUCCESS,this.getDefaultGADimensions())},seek:function(seekOffset){void 0,!0==this.isLiveStream?this.seekStream(seekOffset):this.seekMedia(seekOffset)},seekLive:function(){},restartConnectionTimeOut:function(){void 0,this.connectionTimeOutTimer&&clearInterval(this.connectionTimeOutTimer),0<this._currentLiveApiParams.connectionTimeOut&&(this.connectionTimeOutTimer=setInterval(lang.hitch(this,this.__onTimeOutAlert),6e4*this._currentLiveApiParams.connectionTimeOut))},setVolume:function(volumePercent){void 0,this.volume=volumePercent},getVolume:function(){return this.volume},mute:function(){void 0,!0==this.isLiveStream?this.muteStream():this.muteMedia(),GAEventRequest.requestGA(GAEventRequest.CATEGORY_DEFAULT,GAEventRequest.ACTION_MUTE,GAEventRequest.LABEL_SUCCESS,this.getDefaultGADimensions())},unMute:function(){void 0,!0==this.isLiveStream?this.unMuteStream():this.unMuteMedia(),GAEventRequest.requestGA(GAEventRequest.CATEGORY_DEFAULT,GAEventRequest.ACTION_UNMUTE,GAEventRequest.LABEL_SUCCESS,this.getDefaultGADimensions())},playAd:function(){void 0,this.playAdCalled=!0},skipAd:function(){},destroyAd:function(){},reloadSyncBanner:function(){},__onTimeOutAlert:function(){void 0,this.connectionTimeOutTimer&&clearInterval(this.connectionTimeOutTimer),this.connectionTimeOutTimer=setInterval(lang.hitch(this,this.__onTimeOutReached),this.TIME_OUT_MESSAGE_DELAY),this.emit
1('timeout-alert')},__onTimeOutReached:function(){void 0,this.connectionTimeOutTimer&&clearInterval(this.connectionTimeOutTimer),this.stopStream(),this.emit('timeout-reach')},_callWhiteOps:function(params,mount){try{params.st=this._createUUID(),di=window.location.hostname,ui='1234',ti=params.st,md='3',de='2',sr='tritondigital.com',pp=123456,c1=mount,c2=params.tdsdk,this.xhrProv.request('https://s.update.tritondigital.com/2/163927/analytics.gif?dt=1639271602866005506000&di='+di+'&pp='+pp+'&sr='+sr+'&ti='+ti+'&cb='+new Date().getTime()+'&c1='+c1+'&c2='+c2+'&md='+md,null,{method:'GET',handleAs:'text',headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}})}catch(e){log.error('Could not log IVT')}},_createUUID:function(){for(var s=[],hexDigits='0123456789abcdef',i=0;36>i;i++)s[i]=hexDigits.substr(Math.floor(16*Math.random()),1);s[14]='4',s[19]=hexDigits.substr(8|3&s[19],1),s[8]=s[13]=s[18]=s[23]='-';var uuid=s.join('');return uuid},__extractOmnyParameters:function(params){if(null!=params&&(void 0==params.omnyOrganizationId||void 0==params.omnyClipId)&¶ms.enableOmnyAnalytics&&-1<params.file.indexOf('omny.fm')){var urlParts=params.file.split('/');params.omnySessionId=this._createUUID(),params.omnyOrganizationId=urlParts[5],params.omnyClipId=urlParts[7]}},getDefaultGADimensions:function(){var gaDimensions={};return null!=this.mount&&(gaDimensions[GAEventRequest.DIM_MOUNT]=this.mount),null!=this.station&&(gaDimensions[GAEventRequest.DIM_STATION]=this.station),gaDimensions},_sanitiseDistParam:function(streamUrl,params){let isTimeshift=-1<streamUrl.indexOf('/HLSRW/')||-1<streamUrl.indexOf('/CLOUD/');return isTimeshift&¶ms['dist-timeshift']?(params.dist=params['dist-timeshift'],delete params['dist-timeshift']):!isTimeshift&¶ms['dist-timeshift']&&delete params['dist-timeshift'],params}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var i18n=__webpack_require__(19),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(3),__webpack_require__(13),__webpack_require__(11),__webpack_require__(20),__webpack_require__(27),__webpack_require__(4),__webpack_require__(74),__webpack_require__(141)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,on,Evented,domConstruct,domAttr,domStyle,has,Html5Player,ConsumptionAnalytics){var html5OnDemand=declare([Evented],{constructor:function(node){void 0,this.playerNode=node,this.html5Player=new Html5Player,this.html5Player.on('html5-playback-status',lang.hitch(this,this.__onHTML5PlayerStatus)),this.html5OnDemandNode=this.__createHTML5Elements(),this._playbackStatusCallback=null,this._clickTrackingElementClickedCallback=null,this._adServerType=null,this._clickThrough=null,this._clickTrackings=null,this.onVideoNodeClickHandler=on(this.html5OnDemandNode,'click',lang.hitch(this,this.__onVideoNodeClick)),this.onVideoNodeTouchHandler=on(this.html5OnDemandNode,'touchstart',lang.hitch(this,this.__onVideoNodeClick)),this.consumptionAnalytics=null},play:function(config){this._adServerType=null,this.initConsumptionAnalytics(config),this.html5Player.play({url:config.mediaUrl,type:config.mediaFormat,mediaNode:this.audioNode,isLive:!1})},playAd:function(config){this.__initHtml5AdPlayer(this.videoNode),this._clickThrough=config.clickThrough,this._clickTrackings=config.clickTrackings,this._adServerType=config.adServerType,this.html5Player.play({url:config.mediaUrl,type:config.mediaFormat,mediaNode:this.videoNode,isLive:!1})},skip:function(){void 0==this.html5Player||(this.html5Player.skip(),this.__resetHTML5ElementsStyle(this.mediaNode))},stop:function(){void 0==this.html5Player||this.html5Player.stop()},pause:function(){void 0==this.html5Player||this.html5Player.pause()},resume:function(){void 0==this.html5Player||this.html5Player.resume()},seek:function(seekOffset){void 0==this.html5Player||this.html5Player.seek(seekOffset)},setVolume:function(volumePercent){null==this.html5Player||this.html5Player.setVolume(volumePercent)},mute:function(){null==this.html5Player||this.html5Player.mute()}
1,unMute:function(){null==this.html5Player||this.html5Player.unMute()},changePlayBackRate:function(rate){null==this.html5Player||this.html5Player.changePlayBackRate(rate)},initMediaTag:function(){this.audioNode||(this.audioNode=this.__createMediaTag('audio')),this.videoNode||(this.videoNode=this.__createMediaTag('video'))},setPlaybackStatusHandler:function(callback){this._playbackStatusCallback=callback},setClickTrackingElementClickedHandler:function(callback){this._clickTrackingElementClickedCallback=callback},clean:function(){null!=this.audioNode&&(has('ie11')?(domConstruct.destroy(this.audioNode),this.audioNode=null):(domAttr.has(this.audioNode,'src')&&domAttr.remove(this.audioNode,'src'),'function'==typeof this.audioNode.webkitExitFullScreen&&this.audioNode.webkitExitFullScreen())),null!=this.videoNode&&(has('ie11')?(domConstruct.destroy(this.videoNode),this.videoNode=null):(domAttr.has(this.videoNode,'src')&&domAttr.remove(this.videoNode,'src'),'function'==typeof window.document.exitFullscreen&&window.document.fullscreen&&window.document.exitFullscreen(),this.__resetHTML5ElementsStyle(this.videoNode))),this.__createHTML5Elements()},__onHTML5PlayerStatus:function(e){void 0,e.adServerType=this._adServerType,this.__emitPlaybackStatus(e)},__emitPlaybackStatus:function(e){if(null!=this._playbackStatusCallback){var statusMessages=i18n.getLocalization();if(statusMessages==void 0)return;this._adServerType||'canPlayThrough'!=e.type||(e.type='play');var msg=this.statusMap[e.type];msg&&(statusMsg=statusMessages[msg.status]?statusMessages[msg.status]:msg.status,codeMsg=statusMessages[msg.code]?statusMessages[msg.code]:msg.code,this._playbackStatusCallback({type:statusMsg,code:codeMsg,html5Node:e.mediaNode,adServerType:e.adServerType}))}},__createHTML5Elements:function(){if(null==this.html5OnDemandNode){var onDemandNode=domConstruct.create('div',{id:'tdplayer_ondemand'},this.playerNode,'first');return onDemandNode}},__createMediaTag:function(mediaTagType){if(mediaTagType){var node=domConstruct.create(mediaTagType,{id:'tdplayer_od_'+mediaTagType+'node',type:mediaTagType},this.html5OnDemandNode,'first');domAttr.set(node,'height','0%'),domAttr.set(node,'width','0%'),domAttr.set(node,'x-webkit-airplay','allow');var sourceNode=domConstruct.create('source',{id:'tdplayer_od'+mediaTagType+'source'},node,'first');domAttr.set(sourceNode,'src',''),domAttr.set(node,'playsinline','');try{node.play().catch(function(){}),node.pause()}catch(err){}return node}},__initHtml5AdPlayer:function(node){this.initHTMLElementsStyle(node),this.isVideoClicked=!1},__resetHTML5ElementsStyle:function(node){node&&(domStyle.set(node,'width','0px'),domStyle.set(node,'height','0px'),domStyle.set(node,'display','none'))},initHTMLElementsStyle:function(node){node&&(domStyle.set(node,'width','100%'),domStyle.set(node,'height','100%'),domStyle.set(node,'display','block'),domStyle.set(this.html5OnDemandNode,'width','100%'),domStyle.set(this.html5OnDemandNode,'height','100%'),domStyle.set(this.html5OnDemandNode,'background-color','#000000'),domStyle.set(this.html5OnDemandNode,'display','block'))},__onVideoNodeClick:function(e){null==this._clickThrough||('touchstart'==e.type&&this.onVideoNodeClickHandler.remove(),this._clickTrackingElementClickedCallback({clickThrough:this._clickThrough,clickTrackings:this._clickTrackings}))},initConsumptionAnalytics:function(config){config.enableOmnyAnalytics&&config.omnyOrganizationId!=void 0&&config.omnyClipId!=void 0&&(this.consumptionAnalytics=new ConsumptionAnalytics(this.html5Player),this.consumptionAnalytics.init(config.omnyOrganizationId,config.omnyClipId,config.omnySessionId))},statusMap:{canPlay:{status:'buffering',code:'MEDIA_BUFFERING'},canPlayThrough:{status:'buffering',code:'MEDIA_BUFFERING'},dataLoading:{status:'buffering',code:'MEDIA_BUFFERING'},emptied:{status:'buffering',code:'MEDIA_BUFFERING'},ended:{status:'ended',code:'MEDIA_ENDED'},error:{status:'error',code:'MEDIA_ERROR'},loadStart:{status:'buffering',code:'MEDIA_BUFFERING'},pause:{status:'pause',code:'MEDIA_PAUSED'},play:{status:'play',code:'MEDIA_STARTED'},stalled:{status:'stop',code:'MEDIA_STOPPED'},stop:{status:'stop',code:'MEDIA_STOPPED'},suspend:{status:'buffering',code:'MEDIA_BUFFERING'},waiting:{status:'buffering',code:'MEDIA_BUFFERING'},timeupdate:{status:'timeupdate',code:'MEDIA_TIME_UPDATE'},playbackNotAllowed:{status:'playbackNotAllowed',code:'PLAY_NOT_ALLOWED'}}});return html5OnDemand}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var OsPlatform=__webpack_require__(21),Hls=__webpack_require__(40),PlaybackState=__webpack_require__(22),MediaElement=__webpack_require__(25),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3),__webpack_require__(13),__webpack_require__(6),__webpack_require__(2),__webpack_require__(20),__webpack_require__(91),__webpack_require__(4)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on,Evented,array,lang,domAttr,query,has){var html5Player=declare([Evented],{MAX_CONNECTION_LATENCY:5e3,constructor:function(){void 0,this.inherited(arguments),this.mediaNode=null,this.audioSource=null,this.isStopped=!0,this.isPaused=!0,this.listeners=[],this.volume=1,this._onCanPlayHandler=lang.hitch(this,this._onCanPlay),this._onCanPlayThroughHandler=lang.hitch(this,this._onCanPlayThrough),this._onLoadDataHandler=lang.hitch(this,this._onLoadData),this._onLoadStartHandler=lang.hitch(this,this._onLoadStart),this._onWaitingHandler=lang.hitch(this,this._onWaiting),this._onEmptiedHandler=lang.hitch(this,this._onEmptied),this._onAbortHandler=lang.hitch(this,this._onAbort),this._onErrorHandler=lang.hitch(this,this._onError),this._onLoadedMetadataHandler=lang.hitch(this,this._onLoadedmetadata),this._onTimeUpdateHandler=lang.hitch(this,this._onTimeupdate),this._onEndedHandler=lang.hitch(this,this._onEnded),this._onPlayHandler=lang.hitch(this,this._onPlay),this._onPauseHandler=lang.hitch(this,this._onPause),this._onProgressHandler=lang.hitch(this,this._onProgress),this._onStalledHandler=lang.hitch(this,this._onStalled),this._onSuspendHandler=lang.hitch(this,this._onSuspend)},play:function(params){params&&(this.isStopped||this.isPaused)&&(this.params=params,this.mediaNode=params.mediaNode,this.isStopped=!1,this.isPaused=!1,this._loadMedia(params))},stop:function(){this.isStopped=!0,this.isPaused=!1;void 0==this.mediaNode||(this.mediaNode.pause(),this._emptyMediaNode())},skip:function(){this.isStopped=!0,this.isPaused=!1;
1void 0==this.mediaNode||(this.emit('html5-playback-status',{type:PlaybackState.ENDED}),this.mediaNode.pause())},pause:function(){this.isPaused=!0;void 0==this.mediaNode||this.mediaNode.pause()},resume:function(){var context=this;this.isPaused=!1;void 0==this.mediaNode||this.mediaNode.paused&&this.mediaNode.play().catch(function(e){'NotAllowedError'===e.name&&context.emit('html5-playback-status',{type:PlaybackState.PLAY_NOT_ALLOWED,mediaNode:this.audioNode})})},seek:function(seekOffset){void 0==this.mediaNode||(this.mediaNode.currentTime=seekOffset,this.isPaused&&this.resume())},setVolume:function(volumePercent){void 0==this.mediaNode||(void 0,this.volume=volumePercent,this.mediaNode.volume=volumePercent,this.mediaNode.muted&&0<volumePercent&&(this.mediaNode.muted=!1))},mute:function(){void 0==this.mediaNode||(this.mediaNode.muted=!0)},unMute:function(){void 0==this.mediaNode||(this.mediaNode.muted=!1)},_loadMedia:function(params){this.mediaNode.src=params.url,this._initMediaListeners(params.isLive),this.mediaNode.load()},changePlayBackRate:function(rate){void 0==this.mediaNode||(this.mediaNode.playbackRate=rate)},_emptyMediaNode:function(){this.mediaNode.src='',this.mediaNode.load()},_removeMediaSource:function(){domAttr.has(this.audioSource,'src')&&domAttr.remove(this.audioSource,'src'),domAttr.has(this.mediaNode,'src')&&domAttr.remove(this.mediaNode,'src')},_onLoadData:function(){var context=this;this.isStopped||this.isPaused||(has('mozilla')&&this.mediaNode&&this.mediaNode.paused&&this.mediaNode.play().catch(function(e){'NotAllowedError'===e.name&&context.emit('html5-playback-status',{type:PlaybackState.PLAY_NOT_ALLOWED,mediaNode:this.audioNode})}),this.emit('html5-playback-status',{type:PlaybackState.DATA_LOADING,mediaNode:this.mediaNode}))},_onCanPlay:function(){var context=this;this.isStopped||this.isPaused||(this.emit('html5-playback-status',{type:PlaybackState.CAN_PLAY,mediaNode:this.mediaNode}),this.mediaNode&&this.mediaNode.paused&&this.mediaNode.play().catch(function(e){'NotAllowedError'===e.name&&context.emit('html5-playback-status',{type:PlaybackState.PLAY_NOT_ALLOWED,mediaNode:this.audioNode})}))},_onCanPlayThrough:function(){var context=this;this.isStopped||this.isPaused||(this.emit('html5-playback-status',{type:PlaybackState.CAN_PLAY_THROUGH,mediaNode:this.mediaNode}),this.mediaNode&&this.mediaNode.paused&&this.mediaNode.play().catch(function(e){'NotAllowedError'===e.name&&context.emit('html5-playback-status',{type:PlaybackState.PLAY_NOT_ALLOWED,mediaNode:this.audioNode})}))},_onWaiting:function(){this.isStopped||this.isPaused||this.emit('html5-playback-status',{type:PlaybackState.WAITING,mediaNode:this.mediaNode})},_onEmptied:function(){this.isStopped||this.isPaused||this.emit('html5-playback-status',{type:PlaybackState.EMPTIED,mediaNode:this.mediaNode})},_onAbort:function(){this.isStopped||this.isPaused||this.emit('html5-playback-status',{type:PlaybackState.ABORT,mediaNode:this.mediaNode})},_onError:function(){return this._removeMediaListeners(),this.isStopped||this.isPaused?void this.emit('html5-playback-status',{type:PlaybackState.STOP,mediaNode:this.mediaNode}):void this.emit('html5-playback-status',{type:3==this.mediaNode.readyState?PlaybackState.STOP:PlaybackState.ERROR,mediaNode:this.mediaNode})},_onLoadedmetadata:function(){this.isStopped||this.isPaused||this.emit('html5-playback-status',{type:PlaybackState.EMPTIED,mediaNode:this.mediaNode})},_onTimeupdate:function(){this.isStopped||this.isPaused||(this.mediaNode.currentTime.toFixed(1)==this.mediaNode.duration.toFixed(1)?(this.isStopped=!0,this.emit('html5-playback-status',{type:PlaybackState.ENDED,mediaNode:this.mediaNode})):this.emit('html5-playback-status',{type:PlaybackState.TIME_UPDATE,mediaNode:this.mediaNode}))},_onLoadStart:function(){this.isStopped||this.isPaused||this.emit('html5-playback-status',{type:PlaybackState.LOAD_START,mediaNode:this.mediaNode})},_onEnded:function(){this.isStopped||(this._removeMediaListeners(),this.emit('html5-playback-status',{type:PlaybackState.ENDED,mediaNode:this.mediaNode}))},_onPlay:function(){this.emit('html5-playback-status',{type:PlaybackState.PLAY,mediaNode:this.mediaNode})}
1,_onPause:function(){this.isStopped?this.emit('html5-playback-status',{type:PlaybackState.STOP,mediaNode:this.mediaNode}):this.emit('html5-playback-status',{type:PlaybackState.PAUSE,mediaNode:this.mediaNode})},_initMediaListeners:function(isLive){this._errorHandler=on(this.mediaNode,'error',this._onErrorHandler),this._loadDataHandler=on(this.mediaNode,'loadeddata',this._onLoadDataHandler),this._loadStartHandler=on(this.mediaNode,'loadstart',this._onLoadStartHandler),this._canPlayHandler=on(this.mediaNode,'canplay',this._onCanPlayHandler),this._canPlayThroughHandler=on(this.mediaNode,'canplaythrough',this._onCanPlayThroughHandler),this._waitingHandler=on(this.mediaNode,'waiting',this._onWaitingHandler),this._emptiedHandler=on(this.mediaNode,'emptied',this._onEmptiedHandler),this._abortHandler=on(this.mediaNode,'abort',this._onAbortHandler),this._endedHandler=on(this.mediaNode,'ended',this._onEndedHandler),this._playHandler=on(this.mediaNode,'play',this._onPlayHandler),this._pauseHandler=on(this.mediaNode,'pause',this._onPauseHandler),this._loadedMetadataHandler=on(this.mediaNode,'loadedmetadata',this._onLoadedMetadataHandler),this._timeUpdateHandler=isLive?null:on(this.mediaNode,'timeupdate',this._onTimeUpdateHandler)},_removeMediaListeners:function(){this.params.mediaNode.src='',this._errorHandler.remove(),this._loadDataHandler.remove(),this._loadStartHandler.remove(),this._canPlayHandler.remove(),this._canPlayThroughHandler.remove(),this._waitingHandler.remove(),this._emptiedHandler.remove(),this._abortHandler.remove(),this._endedHandler.remove(),this._playHandler.remove(),this._pauseHandler.remove(),this._loadedMetadataHandler.remove(),this._timeUpdateHandler&&this._timeUpdateHandler.remove()}});return html5Player}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){function _filterByTag(mountPoints,tags,excludeUntagged){return'string'==typeof tags&&(tags=[tags]),_.isUndefined(excludeUntagged)&&(excludeUntagged=!1),mountPoints.filter(function(mountPoint){return!(_.isEmpty(mountPoint.tags)&&excludeUntagged)||_.some(tags,function(tag){return-1!==mountPoint.tags.indexOf(tag)})})}function _sortMountpoints(mountPoints){return _.sortBy(mountPoints,function(m){return m.mediaFormat.isAudioAdaptive?0:1},function(m){return m.mediaFormat.audioTracks[0].isAAC?0:1})}function _sortMountpointsByBitrate(mountPoints){var mountPointsByCodec=_.groupBy(mountPoints,function(mountPoint){var codec;return codec=mountPoint.mediaFormat.isAudioAdaptive?'audioAdaptive':mountPoint.mediaFormat.audioTracks[0].isAAC?'aac':'mp3',codec}),codecs=_.keys(mountPointsByCodec);return _.flatMap(codecs,function(codec){var mountPointsOfCodec=mountPointsByCodec[codec];return _.orderBy(mountPointsOfCodec,'bitRate','desc')})}function _excludeTransport(mountPoints,transportExcluded){return _.isArray(transportExcluded)||(transportExcluded=[transportExcluded]),_.forEach(mountPoints,function(mountpoint){var transports=mountpoint.transports.filter(function(transport){return!_.some(transportExcluded,function(transportToExclude){return transportToExclude.transport===transport.transport&&-1<mountpoint.mediaFormat.audioTracks[0].codec.indexOf(transportToExclude.codec)})});mountpoint.transports=transports}),mountPoints.filter(function(mountPoint){return!_.isEmpty(mountPoint.transports)})}function _excludeAudioAdaptive(mountPoints){return _.filter(mountPoints,function(mountPoint){return!mountPoint.mediaFormat.isAudioAdaptive})}function _excludeHLS(mountPoints){return _excludeTransport(mountPoints,[{transport:'hls',codec:'aac'},{transport:'hlsts',codec:'aac'}])}function _forceHls(mountPoints,isHlsts){return _excludeTransport(mountPoints,[{transport:isHlsts?'hls':'hlsts',codec:'aac'},{transport:'http',codec:'aac'},{transport:'http',codec:'mp3'}])}function _sortTransport(mountPoints,transportPriorities){var transportPrioritiesFunctions=_.map(transportPriorities,function(transportPriority){return function(transport){return transport.transport===transportPriority?0:1}});return _.forEach(mountPoints,function(mountPoint){var transports=mountPoint.transports,sortedTransports=_.sortBy(trans
1ports,transportPrioritiesFunctions);mountPoint.transports=sortedTransports}),mountPoints}function _filterByTimeshift(mountPoints,includeMount){return mountPoints=includeMount?mountPoints.filter(mount=>_.some(mount.transports,function(transport){return!0===transport.timeshift})):mountPoints.filter(mount=>!_.some(mount.transports,function(transport){return!0===transport.timeshift})),mountPoints}function _filterByPlatform(mountPoints,platform,techType){if('flash'==techType.toLowerCase())mountPoints=_excludeAudioAdaptive(mountPoints),mountPoints=_excludeTransport(mountPoints,[{transport:'hlsts',codec:'aac'},{transport:'hls',codec:'aac'}]);else switch(platform.os.family){case'iOS':mountPoints=_excludeTransport(mountPoints,{transport:'hlsts',codec:'aac'}),'Chrome Mobile'===platform.name&&(mountPoints=_excludeTransport(mountPoints,[{transport:'hls',codec:'aac'}])),mountPoints=_sortTransport(mountPoints,['hls','http']);break;case'Android':mountPoints=_sortTransport(mountPoints,['hlsts','http']);break;default:switch(platform.name){case'Safari':mountPoints=_excludeTransport(mountPoints,{transport:'hlsts',codec:'aac'}),mountPoints=_sortTransport(mountPoints,['hls','http']);break;case'IE':mountPoints='11.0'===platform.version&&7<parseInt(platform.os.version)?_excludeTransport(mountPoints,[{transport:'http',codec:'aac'},{transport:'hlsts',codec:'aac'}]):_excludeTransport(mountPoints,[{transport:'hls',codec:'aac'},{transport:'http',codec:'aac'},{transport:'hlsts',codec:'aac'}]),mountPoints=_sortTransport(mountPoints,['hls','http']);break;case'Microsoft Edge':mountPoints=_excludeTransport(mountPoints,[{transport:'hlsts',codec:'aac'}]),mountPoints=_sortTransport(mountPoints,['hls','http']);break;default:mountPoints=_excludeTransport(mountPoints,[{transport:'hlsts',codec:'aac'},{transport:'hls',codec:'aac'}]),mountPoints=_sortTransport(mountPoints,['hls','http']);}}return mountPoints}const{times}=__webpack_require__(7);var _=__webpack_require__(7);module.exports={filterMountPoints:function(mountPoints,platform,techType,tags,excludeUntagged,removeHLS,removeAudioAdaptive,forceHls,forceHlsts,timeshift){return!removeHLS||forceHls||forceHlsts||(mountPoints=_excludeHLS(mountPoints)),removeAudioAdaptive&&(mountPoints=_excludeAudioAdaptive(mountPoints)),mountPoints=_filterByTag(mountPoints,tags,excludeUntagged),mountPoints=forceHls?_forceHls(mountPoints):forceHlsts?_forceHls(mountPoints,!0):_filterByPlatform(mountPoints,platform,techType),timeshift?mountPoints=_filterByTimeshift(mountPoints,!0):1<mountPoints.length&&(mountPoints=_filterByTimeshift(mountPoints,!1)),mountPoints=_sortMountpointsByBitrate(mountPoints),mountPoints=_sortMountpoints(mountPoints),mountPoints},filterByTag:_filterByTag,sortMountpoints:_sortMountpoints}},function(module){module.exports=function(data){this.name=null,function(context,data){context.name=data?data:null}(this,data)}},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(6),__webpack_require__(2),__webpack_require__(9),__webpack_require__(35),__webpack_require__(79),__webpack_require__(78),__webpack_require__(3)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,array,lang,XhrProvider,Inpe,Track,Picture,on){var album=declare([Inpe],{constructor:function(){void 0,this.albumData=null,this.inherited(arguments)},getArtists:function(){return this.albumData.artists},getArtistId:function(){return this.getArtists()[0].id},getDuration:function(){return this.albumData.duration},getGenres:function(){for(var genres=[],i=0;i<this.albumData.genres.length;i++)genres.push(this.albumData.genres[i].name);return genres},getTitle:function(){return null==this.albumData?this.data.title:this.albumData.title},getLabel:function(){return this.data.label},getReleaseDate:function(){return null==this.albumData?this.data.release:this.albumData.release},getReview:function(){return this.albumData.review},getReviewAuthor:function(){return this.albumData.reviewAuthor},getBuyUrl:function(){return null==this.albumData?this.data.buyURL:this.albumData.buyURL},getRating:function(){return null==this.albumData?this.data.rating:this.albumData.rating},getCoverArtOriginal:function(){var cover=null==this.albumData?this.data.cover:this.albumData.cover;return null!=cover||void 0!=cover?{url:cover.originalSourceUrl,width:cover.width,height:cover.height,id:cover.id}:null},getCoverArtPicture:function(){return this.coverArtPicture},fetchCoverArtPicture:function(){if(this.coverArtPicture)return void this.notify('cover-complete',this.coverArtPicture);var pictureItem=null==this.albumData?this.data.cover:this.albumData.cover;return null==pictureItem?void this.notify('cover-complete'):void(pictureItem.albumId=this.id,this.coverArtPicture=new Picture
1(pictureItem,this.platformId),this.coverArtPicture.successCallback&&this.coverArtPicture.successCallback.remove(),this.coverArtPicture.errorCallback&&this.coverArtPicture.errorCallback.remove(),this.coverArtPicture.successCallback=on(this.coverArtPicture,'picture-complete',lang.hitch(this,this._onCoverArtPictureComplete)),this.coverArtPicture.errorCallback=on(this.coverArtPicture,'picture-error',lang.hitch(this,this._onCoverArtPictureComplete)),this.coverArtPicture.fetchData())},_onCoverArtPictureComplete:function(){this.notify('cover-complete',this.coverArtPicture)},getTracks:function(){if(null==this.tracks){this.tracks=[];var track;array.forEach(this.albumData.tracks,function(item){track=new Track(item,this.platformId),this.tracks.push(track)},this)}return this.tracks},getTrackById:function(trackId){var itemIndex=-1;return array.forEach(this.getTracks(),function(item,index){item.id==trackId&&(itemIndex=index)},this),-1<itemIndex?this.getTracks()[itemIndex]:null},fetchData:function(isDynamicCall){if(isDynamicCall=void 0!=isDynamicCall&&isDynamicCall,isDynamicCall&&(this.url=this.getDynamicAlbumUrl(this.id)),null==this.url)return void this.notify('album-error',{albumId:this.id});if(!1==this.alreadyFetched){var xhrProv=new XhrProvider;xhrProv.request(this.url,{albumId:this.id,isDynamicCall:isDynamicCall},this.getRequestArgs(),lang.hitch(this,this._onLoadComplete),lang.hitch(this,this._onLoadError))}else this.notify('album-complete',{albumId:this.id})},fetchTrackByIds:function(trackIds){void 0,'string'==typeof trackIds&&(trackIds=[trackIds]),this.tracksQueue=lang.clone(trackIds);for(var i=0,track;i<trackIds.length;i++)track=this.getTrackById(trackIds[i]),track.successCallback&&track.successCallback.remove(),track.errorCallback&&track.errorCallback.remove(),track.successCallback=on(track,'track-complete',lang.hitch(this,this._onTrackComplete)),track.errorCallback=on(track,'track-error',lang.hitch(this,this._onTrackComplete)),track.fetchData()},_onLoadError:function(requestData){void 0,!1==requestData.isDynamicCall?this.fetchData(!0):this.notify('album-error',{albumId:requestData.albumId})},_onLoadComplete:function(requestData,data){void 0,this.albumData=data.album,this.alreadyFetched=!0,this.notify('album-complete',{albumId:requestData.albumId})},_onTrackComplete:function(requestData){void 0,this._removeTrackFromQueue(requestData.trackId),0==this.tracksQueue.length&&this.notify('track-complete',this.tracks)},_removeTrackFromQueue:function(trackId){var spliceStartIndex=-1;array.forEach(this.tracksQueue,function(itemId,index){itemId==trackId&&(spliceStartIndex=index)},this),-1<spliceStartIndex&&this.tracksQueue.splice(spliceStartIndex,1)}});return album}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(9),__webpack_require__(35)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,XhrProvider,Inpe){var picture=declare([Inpe],{constructor:function(data){void 0,this.pictureData=null,this.albumId=data.albumId?data.albumId:null,this.artistId=data.artistId?data.artistId:null,this.inherited(arguments)},getOriginalSourceUrl:function(){return this.data.originalSourceUrl},getOriginalWidth:function(){return this.data.width},getOriginalHeight:function(){return this.data.height},getFiles:function(){return null!=this.pictureData&&this.pictureData.files!=void 0&&0<this.pictureData.files.length?this.pictureData.files:null},fetchData:function(isDynamicCall){if(isDynamicCall=void 0!=isDynamicCall&&isDynamicCall,isDynamicCall?null==this.albumId?this.url=this.getDynamicArtistPictureUrl(this.artistId,this.id):this.url=this.getDynamicAlbumPictureUrl(this.albumId,this.id):null==this.albumId?this.url+=-1==this.url.indexOf('?')?'?rewrite_id='+this.artistId:'&':this.url+=-1==this.url.indexOf('?')?'?rewrite_id='+this.albumId:'&',!1==this.alreadyFetched){var xhrProv=new XhrProvider;xhrProv.request(this.url,{pictureId:this.id,isDynamicCall:isDynamicCall},this.getRequestArgs(),lang.hitch(this,this._onLoadComplete),lang.hitch(this,this._onLoadError))}else this.notify('picture-complete',{pictureId:this.id})},_onLoadError:function(requestData){void 0,!1==requestData.isDynamicCall?this.fetchData(!0):this.notify('picture-error',{pictureId:requestData.pictureId})},_onLoadComplete:function(requestData,data){void 0,this.pictureData=data.picture,this.alreadyFetched=!0,this.notify('picture-complete',{pictureId:requestData.pictureId})}});return picture}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(9),__webpack_require__(35)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,XhrProvider,Inpe){var track=declare([Inpe],{constructor:function(){void 0,this.trackData=null,this.inherited(arguments)},getBuyUrl:function(){return null==this.trackData?this.data.buyURL:this.trackData.buyURL},getDuration:function(){return this.data.duration},getSampleUrl:function(){return null==this.trackData?this.data.sampleURL:this.trackData.sampleURL},getTitle:function(){return null==this.trackData?this.data.title:this.trackData.title},getArtists:function(){return this.trackData.artists},getReview:function(){return this.trackData.review},getReviewAuthor:function(){return this.trackData.reviewAuthor},getDisc:function(){return this.data.disc},fetchData:function(isDynamicCall){if(isDynamicCall=void 0!=isDynamicCall&&isDynamicCall,isDynamicCall&&(this.url=this.getDynamicTrackUrl(this.id
1)),!1==this.alreadyFetched){var xhrProv=new XhrProvider;xhrProv.request(this.url,{trackId:this.id,isDynamicCall:isDynamicCall},this.getRequestArgs(),lang.hitch(this,this._onLoadComplete),lang.hitch(this,this._onLoadError))}else this.notify('track-complete',{trackId:this.id})},_onLoadError:function(requestData){void 0,!1==requestData.isDynamicCall?this.fetchData(!0):this.notify('track-error',{trackId:requestData.trackId})},_onLoadComplete:function(requestData,data){void 0,this.trackData=data.track,this.alreadyFetched=!0,this.notify('track-complete',{trackId:requestData.trackId})}});return track}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4),__webpack_require__(30)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,require){var result={};if(has('dojo-config-api')){var src=require.rawConfig,p;for(p in src)result[p]=src[p]}else{var adviseHas=function(featureSet,prefix,booting){for(p in featureSet)'has'!=p&&has.add(prefix+p,featureSet[p],0,booting)};result=has('dojo-loader')?require.rawConfig:this.dojoConfig||this.djConfig||{},adviseHas(result,'config',1),adviseHas(result.has,'',1)}return result.locale||(result.locale=(navigator.language||navigator.userLanguage).toLowerCase()),result}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(3),__webpack_require__(18),__webpack_require__(36),__webpack_require__(82),__webpack_require__(90),__webpack_require__(83),__webpack_require__(2),__webpack_require__(89)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,on,hub,aspect,eventModule,mouse,has,lang){function connect_(obj,event,context,method,dontFix){return(method=lang.hitch(context,method),!obj||!(obj.addEventListener||obj.attachEvent))?aspect.after(obj||dojo.global,event,method,!0):('string'==typeof event&&'on'==event.substring(0,2)&&(event=event.substring(2)),obj||(obj=dojo.global),(dontFix||('keypress'===event?event=keypress:'mouseenter'===event?event=mouse.enter:'mouseleave'===event?event=mouse.leave:void 0),on(obj,event,method,dontFix)))}function setKeyChar(evt){evt.keyChar=evt.charCode?String.fromCharCode(evt.charCode):'',evt.charOrCode=evt.keyChar||evt.keyCode}has.add('events-keypress-typed',function(){var testKeyEvent={charCode:0};try{testKeyEvent=document.createEvent('KeyboardEvent'),(testKeyEvent.initKeyboardEvent||testKeyEvent.initKeyEvent).call(testKeyEvent,'keypress',!0,!0,null,!1,!1,!1,!1,9,3)}catch(e){}return 0==testKeyEvent.charCode&&!has('opera')});var _punctMap={106:42,111:47,186:59,187:43,188:44,189:45,190:46,191:47,192:96,219:91,220:92,221:93,222:39,229:113},evtCopyKey=has('mac')?'metaKey':'ctrlKey',_synthesizeEvent=function(evt,props){var faux=lang.mixin({},evt,props);return setKeyChar(faux),faux.preventDefault=function(){evt.preventDefault()},faux.stopPropagation=function(){evt.stopPropagation()},faux},keypress;if(has('events-keypress-typed')){var _trySetKeyCode=function(e,code){try{return e.keyCode=code}catch(e){return 0}};keypress=function(object,listener){var keydownSignal=on(object,'keydown',function(evt){var k=evt.keyCode,unprintable=13!=k&&32!=k&&(27!=k||!has('ie'))&&(48>k||90<k)&&(96>k||111<k)&&(186>k||192<k)&&(219>k||222<k)&&229!=k;if(unprintable||evt.ctrlKey){var c=unprintable?0:k;if(evt.ctrlKey){if(3==k||13==k)return listener.call(evt.currentTarget,evt);95<c&&106>c?c-=48:!evt.shiftKey&&65<=c&&90>=c?c+=32:c=_punctMap[c]||c}var faux=_synthesizeEvent(evt,{type:'keypress',faux:!0,charCode:c});listener.call(evt.currentTarget,faux),has('ie')&&_trySetKeyCode(evt,faux.keyCode)}}),keypressSignal=on(object,'keypress',function(evt){var c=evt.charCode;return c=32<=c?c:0,evt=_synthesizeEvent(evt,{charCode:c,faux:!0}),listener.call(this,evt)});return{remove:function(){keydownSignal.remove(),keypressSignal.remove()}}}}else keypress=has('opera')?function(object,listener){return on(object,'keypress',function(evt){var c=evt.which;return 3==c&&(c=99),c=32>c&&!evt.shiftKey?0:c,evt.ctrlKey&&!evt.shiftKey&&65<=c&&90>
1=c&&(c+=32),listener.call(this,_synthesizeEvent(evt,{charCode:c}))})}:function(object,listener){return on(object,'keypress',function(evt){return setKeyChar(evt),listener.call(this,evt)})};var connect={_keypress:keypress,connect:function(){var a=arguments,args=[],i=0;args.push('string'==typeof a[0]?null:a[i++],a[i++]);var a1=a[i+1];args.push('string'==typeof a1||'function'==typeof a1?a[i++]:null,a[i++]);for(var l=a.length;i<l;i++)args.push(a[i]);return connect_.apply(this,args)},disconnect:function(handle){handle&&handle.remove()},subscribe:function(topic,context,method){return hub.subscribe(topic,lang.hitch(context,method))},publish:function(topic,args){return hub.publish.apply(hub,[topic].concat(args))},connectPublisher:function(topic,obj,event){var pf=function(){connect.publish(topic,arguments)};return event?connect.connect(obj,event,pf):connect.connect(obj,pf)},isCopyKey:function(e){return e[evtCopyKey]}};return connect.unsubscribe=connect.disconnect,has('extend-dojo')&&lang.mixin(dojo,connect),connect}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(3),__webpack_require__(4),__webpack_require__(85)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,on,has,dom){if(on._fixEvent){var fixEvent=on._fixEvent;on._fixEvent=function(evt,se){return evt=fixEvent(evt,se),evt&&dom.normalizeEvent(evt),evt}}var ret={fix:function(evt,sender){return on._fixEvent?on._fixEvent(evt,sender):evt},stop:function(evt){has('dom-addeventlistener')||evt&&evt.preventDefault?(evt.preventDefault(),evt.stopPropagation()):(evt=evt||window.event,evt.cancelBubble=!0,on._preventDefault.call(evt))}};return has('extend-dojo')&&(dojo.fixEvent=ret.fix,dojo.stopEvent=ret.stop),ret}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(2),__webpack_require__(10)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,lang,has){return has('host-browser')?(dojo._name='browser',lang.mixin(dojo,{isBrowser:!0,isFF:has('ff'),isIE:has('ie'),isKhtml:has('khtml'),isWebKit:has('webkit'),isMozilla:has('mozilla'),isMoz:has('mozilla'),isOpera:has('opera'),isSafari:has('safari'),isChrome:has('chrome'),isMac:has('mac'),isIos:has('ios'),isAndroid:has('android'),isWii:has('wii'),isQuirks:has('quirks'),isAir:has('air')}),has):has}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(92)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,regexp){return dojo.cookie=function(name,value,props){var c=document.cookie,ret;if(1==arguments.length){var matches=c.match(new RegExp('(?:^|; )'+regexp.escapeString(name)+'=([^;]*)'));ret=matches?decodeURIComponent(matches[1]):void 0}else{props=props||{};var exp=props.expires;if('number'==typeof exp){var d=new Date;d.setTime(d.getTime()+1e3*(60*(60*(24*exp)))),exp=props.expires=d}exp&&exp.toUTCString&&(props.expires=exp.toUTCString()),value=encodeURIComponent(value);var updatedCookie=name+'='+value,propName;for(propName in props){updatedCookie+='; '+propName;var propValue=props[propName];!0!==propValue&&(updatedCookie+='='+propValue)}document.cookie=updatedCookie}return ret},dojo.cookie.isSupported=function(){return'cookieEnabled'in navigator||(this('__djCookieTest__','CookiesAllowed'),navigator.cookieEnabled='CookiesAllowed'==this('__djCookieTest__'),navigator.cookieEnabled&&this('__djCookieTest__','',{expires:-1})),navigator.cookieEnabled},dojo.cookie}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(10),__webpack_require__(17),__webpack_require__(8),__webpack_require__(27)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,win,dom,style){function setBox(node,l,t,w,h,u){u=u||'px';var s=node.style;
1isNaN(l)||(s.left=l+u),isNaN(t)||(s.top=t+u),0<=w&&(s.width=w+u),0<=h&&(s.height=h+u)}function isButtonTag(node){return'button'==node.tagName.toLowerCase()||'input'==node.tagName.toLowerCase()&&'button'==(node.getAttribute('type')||'').toLowerCase()}function usesBorderBox(node){return'border-box'==geom.boxModel||'table'==node.tagName.toLowerCase()||isButtonTag(node)}var geom={};geom.boxModel='content-box',has('ie')&&(geom.boxModel='BackCompat'==document.compatMode?'border-box':'content-box'),geom.getPadExtents=function(node,computedStyle){node=dom.byId(node);var s=computedStyle||style.getComputedStyle(node),px=style.toPixelValue,l=px(node,s.paddingLeft),t=px(node,s.paddingTop),r=px(node,s.paddingRight),b=px(node,s.paddingBottom);return{l:l,t:t,r:r,b:b,w:l+r,h:t+b}};var none='none';geom.getBorderExtents=function(node,computedStyle){node=dom.byId(node);var px=style.toPixelValue,s=computedStyle||style.getComputedStyle(node),l=s.borderLeftStyle==none?0:px(node,s.borderLeftWidth),t=s.borderTopStyle==none?0:px(node,s.borderTopWidth),r=s.borderRightStyle==none?0:px(node,s.borderRightWidth),b=s.borderBottomStyle==none?0:px(node,s.borderBottomWidth);return{l:l,t:t,r:r,b:b,w:l+r,h:t+b}},geom.getPadBorderExtents=function(node,computedStyle){node=dom.byId(node);var s=computedStyle||style.getComputedStyle(node),p=geom.getPadExtents(node,s),b=geom.getBorderExtents(node,s);return{l:p.l+b.l,t:p.t+b.t,r:p.r+b.r,b:p.b+b.b,w:p.w+b.w,h:p.h+b.h}},geom.getMarginExtents=function(node,computedStyle){node=dom.byId(node);var s=computedStyle||style.getComputedStyle(node),px=style.toPixelValue,l=px(node,s.marginLeft),t=px(node,s.marginTop),r=px(node,s.marginRight),b=px(node,s.marginBottom);return{l:l,t:t,r:r,b:b,w:l+r,h:t+b}},geom.getMarginBox=function(node,computedStyle){node=dom.byId(node);var s=computedStyle||style.getComputedStyle(node),me=geom.getMarginExtents(node,s),l=node.offsetLeft-me.l,t=node.offsetTop-me.t,p=node.parentNode,px=style.toPixelValue,pcs;if(has('mozilla')){var sl=parseFloat(s.left),st=parseFloat(s.top);isNaN(sl)||isNaN(st)?p&&p.style&&(pcs=style.getComputedStyle(p),'visible'!=pcs.overflow&&(l+=pcs.borderLeftStyle==none?0:px(node,pcs.borderLeftWidth),t+=pcs.borderTopStyle==none?0:px(node,pcs.borderTopWidth))):(l=sl,t=st)}else(has('opera')||8==has('ie')&&!has('quirks'))&&p&&(pcs=style.getComputedStyle(p),l-=pcs.borderLeftStyle==none?0:px(node,pcs.borderLeftWidth),t-=pcs.borderTopStyle==none?0:px(node,pcs.borderTopWidth));return{l:l,t:t,w:node.offsetWidth+me.w,h:node.offsetHeight+me.h}},geom.getContentBox=function(node,computedStyle){node=dom.byId(node);var s=computedStyle||style.getComputedStyle(node),w=node.clientWidth,pe=geom.getPadExtents(node,s),be=geom.getBorderExtents(node,s),h;return w?(h=node.clientHeight,be.w=be.h=0):(w=node.offsetWidth,h=node.offsetHeight),has('opera')&&(pe.l+=be.l,pe.t+=be.t),{l:pe.l,t:pe.t,w:w-pe.w-be.w,h:h-pe.h-be.h}},geom.setContentSize=function(node,box,computedStyle){node=dom.byId(node);var w=box.w,h=box.h;if(usesBorderBox(node)){var pb=geom.getPadBorderExtents(node,computedStyle);0<=w&&(w+=pb.w),0<=h&&(h+=pb.h)}setBox(node,NaN,NaN,w,h)};var nilExtents={l:0,t:0,w:0,h:0};return geom.setMarginBox=function(node,box,computedStyle){node=dom.byId(node);var s=computedStyle||style.getComputedStyle(node),w=box.w,h=box.h,pb=usesBorderBox(node)?nilExtents:geom.getPadBorderExtents(node,s),mb=geom.getMarginExtents(node,s);if(has('webkit')&&isButtonTag(node)){var ns=node.style;0<=w&&!ns.width&&(ns.width='4px'),0<=h&&!ns.height&&(ns.height='4px')}0<=w&&(w=Math.max(w-pb.w-mb.w,0)),0<=h&&(h=Math.max(h-pb.h-mb.h,0)),setBox(node,box.l,box.t,w,h)},geom.isBodyLtr=function(doc){return doc=doc||win.doc,'ltr'==(win.body(doc).dir||doc.documentElement.dir||'ltr').toLowerCase()},geom.docScroll=function(doc){doc=doc||win.doc;var node=win.doc.parentWindow||win.doc.defaultView;return'pageXOffset'in node?{x:node.pageXOffset,y:node.pageYOffset}:(node=has('quirks')?win.body(doc):doc.documentElement)&&{x:geom.fixIeBiDiScrollLeft(node.scrollLeft||0,doc),y:node.scrollTop||0}},has('ie')&&(geom.getIeDocumentElementOffset=function(doc){doc=doc||win.doc;var de=doc.documentElement;if(8>has('ie')){var r=de.getBoundingClientRect(),l=r.left,t=r.top;return 7>has('ie')&&(l+=de.clientLeft,t+=de.clientTop),{x:0>l?0:l,y:0>t?0:t}}return{x:0,y:0}}),geom.fixIeBiDiScrollLeft=function(scrollLeft,doc){doc=doc||win.doc;var ie=has('ie');if(ie&&!geom.isBodyLtr(doc)){var qk=has('quirks'),de=qk?win.body(doc):doc.documentElement,pwin=win.global;return 6==ie&&!qk&&pwin.frameElement&&de.scrollHeight>de.clientHeight&&(scrollLeft+=de.clientLeft),8>ie||qk?scrollLeft+de.clientWidth-de.scrollWidth:-scrollLeft}return scrollLeft},geom.position=function(node,includeScroll){node=dom.byId(node);var db=win.body(node.ownerDocument),ret=node.getBoundingClientRect();if(ret={x:ret.left,y:ret.top,w:ret.right-ret.left,h:ret.bottom-ret.top},9>has('ie')){var offset=geom.getIeDocumentElementOffset(node.ownerDocument);ret.x-=offset.x+(has('quirks')?db.clientLeft+db.offsetLeft:0),ret.y-=offset.y+(has('quirks')?db.clientTop+db.offsetTop:0)}if(includeScroll){var scroll=geom.docScroll(node.ownerDocument);ret.x+=scroll.x,ret.y+=scroll.y}return ret},geom.getMarginSize=function(node,computedStyle){node=dom.byId(node);var me=geom.getMarginExtents(node,computedStyle||style.getComputedStyle(node)),size=node.getBoundingClientRect();return{w:size.right-size.left+me.w,h:size.bottom-size.top+me.h}},geom.normalizeEvent=function(event){if('layerX'in event||(event.layerX=event.offsetX,event.layerY=event.offsetY),!has('dom-addeventlistener')){var se=event.target,doc=se&&se.ownerDocument||document,docBody=has('quirks')?doc.body:doc.documentElement,offset=geom.getIeDocumentElementOffset(doc);
1event.pageX=event.clientX+geom.fixIeBiDiScrollLeft(docBody.scrollLeft||0,doc)-offset.x,event.pageY=event.clientY+(docBody.scrollTop||0)-offset.y}},geom}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[exports,__webpack_require__(5),__webpack_require__(10),__webpack_require__(2),__webpack_require__(8),__webpack_require__(27),__webpack_require__(11),__webpack_require__(81)],__WEBPACK_AMD_DEFINE_RESULT__=function(exports,dojo,has,lang,dom,style,ctr,conn){var _evtHdlrMap={},_ctr=0,_attrId=dojo._scopeName+'attrid';exports.names={class:'className',for:'htmlFor',tabindex:'tabIndex',readonly:'readOnly',colspan:'colSpan',frameborder:'frameBorder',rowspan:'rowSpan',valuetype:'valueType'},exports.get=function(node,name){node=dom.byId(node);var lc=name.toLowerCase(),propName=exports.names[lc]||name;return node[propName]},exports.set=function(node,name,value){node=dom.byId(node);var l=arguments.length;if(2==l&&'string'!=typeof name){for(var x in name)exports.set(node,x,name[x]);return node}var lc=name.toLowerCase(),propName=exports.names[lc]||name;if('style'==propName&&'string'!=typeof value)return style.set(node,value),node;if('innerHTML'==propName)return has('ie')&&node.tagName.toLowerCase()in{col:1,colgroup:1,table:1,tbody:1,tfoot:1,thead:1,tr:1,title:1}?(ctr.empty(node),node.appendChild(ctr.toDom(value,node.ownerDocument))):node[propName]=value,node;if(lang.isFunction(value)){var attrId=node[_attrId];attrId||(attrId=_ctr++,node[_attrId]=attrId),_evtHdlrMap[attrId]||(_evtHdlrMap[attrId]={});var h=_evtHdlrMap[attrId][propName];if(h)conn.disconnect(h);else try{delete node[propName]}catch(e){}return value?_evtHdlrMap[attrId][propName]=conn.connect(node,propName,value):node[propName]=null,node}return node[propName]=value,node}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(38),__webpack_require__(37)],__WEBPACK_AMD_DEFINE_RESULT__=function(create,RequestError){return create('RequestTimeoutError',null,RequestError,{dojoType:'timeout'})}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4)],__WEBPACK_AMD_DEFINE_RESULT__=function(has){'use strict';var hasJSON='undefined'!=typeof JSON;if(has.add('json-parse',hasJSON),has.add('json-stringify',hasJSON&&'{"a":1}'==JSON.stringify({a:0},function(k,v){return v||1})),has('json-stringify'))return JSON;var escapeString=function(str){return('"'+str.replace(/(["\\])/g,'\\$1')+'"').replace(/[\f]/g,'\\f').replace(/[\b]/g,'\\b').replace(/[\n]/g,'\\n').replace(/[\t]/g,'\\t').replace(/[\r]/g,'\\r')};return{parse:has('json-parse')?JSON.parse:function(str,strict){if(strict&&!/^([\s\[\{]*(?:"(?:\\.|[^"])*"|-?\d[\d\.]*(?:[Ee][+-]?\d+)?|null|true|false|)[\s\]\}]*(?:,|:|$))+$/.test(str))throw new SyntaxError('Invalid characters in JSON');return eval('('+str+')')},stringify:function(value,replacer,spacer){function stringify(it,indent,key){replacer&&(it=replacer(key,it));var objtype=typeof it,val;if('number'==objtype)return isFinite(it)?it+'':'null';if('boolean'==objtype)return it+'';if(null===it)return'null';if('string'==typeof it)return escapeString(it);if('function'==objtype||'undefined'==objtype)return undef;if('function'==typeof it.toJSON)return stringify(it.toJSON(key),indent,key);if(it instanceof Date)return'"{FullYear}-{Month+}-{Date}T{Hours}:{Minutes}:{Seconds}Z"'.replace(/\{(\w+)(\+)?\}/g,function(t,prop,plus){var num=it['getUTC'+prop]()+(plus?1:0);return 10>num?'0'+num:num});if(it.valueOf()!==it)return stringify(it.valueOf(),indent,key);var nextIndent=spacer?indent+spacer:'',sep=spacer?' ':'',newLine=spacer?'\n':'';if(it instanceof Array){var itl=it.length,res=[];for(key=0;key<itl;key++){var obj=it[key];val=stringify(obj,nextIndent,key),'string'!=typeof val&&(val='null'),res.push(newLine+nextIndent+val)}return'['+res.join(',')+newLine+indent+']'}var output=[];for(key in it){var keyStr;if(it.hasOwnProperty(key)){if('number'==typeof key)keyStr='"'+key+'"';else if('string'==typeof key)keyStr=escapeString(key);else continue;if(val=stringify(it[key],nextIndent,key),'string'!=typeof val)continue;output.push(newLine+nextIndent+keyStr+':'+sep+val)}}return'{'+output.join(',')+newLine+indent+'}'}var undef;return'string'==typeof replacer&&(spacer=replacer,replacer=null),stringify(value,'','')}}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(10)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,has){return dojo.keys={BACKSPACE:8,TAB:9,CLEAR:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,META:has('webkit')?91:224,PAUSE:19,CAPS_LOCK:20,ESCAPE:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT_ARROW:37,UP_ARROW:38,RIGHT_ARROW:39,DOWN_ARROW:40,INSERT:45,DELETE:46,HELP:47,LEFT_WINDOW:91,RIGHT_WINDOW:92,SELECT:93,NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_MULTIPLY:106,NUMPAD_PLUS:107,NUMPAD_ENTER:108,NUMPAD_MINUS:109,NUMPAD_PERIOD:110,NUMPAD_DIVIDE:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,NUM_LOCK:144,SCROLL_LOCK:145,UP_DPAD:175,DOWN_DPAD:176,LEFT_DPAD:177,RIGHT_DPAD:178,copyKey:has('mac')&&!has('air')?has('safari')?91:224:17}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(3),__webpack_require__(4),__webpack_require__(8),__webpack_require__(17)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,on,has,dom,win){function eventHandler(type,selectHandler){var handler=function(node,listener){return on(node,type,function(evt){return selectHandler?selectHandler(evt,listener):dom.isDescendant(evt.relatedTarget,node)?void 0:listener.call(this,evt)})};return handler.bubble=function(select){return eventHandler(type,function(evt,listener){var target=select(evt.target),relatedTarget=evt.relatedTarget;if(target&&target!=(relatedTarget&&1==relatedTarget.nodeType&&select(relatedTarget)))return listener.call(target,evt)}
1)},handler}has.add('dom-quirks',win.doc&&'BackCompat'==win.doc.compatMode),has.add('events-mouseenter',win.doc&&'onmouseenter'in win.doc.createElement('div')),has.add('events-mousewheel',win.doc&&'onmousewheel'in win.doc);var mouseButtons;mouseButtons=has('dom-quirks')&&has('ie')||!has('dom-addeventlistener')?{LEFT:1,MIDDLE:4,RIGHT:2,isButton:function(e,button){return e.button&button},isLeft:function(e){return 1&e.button},isMiddle:function(e){return 4&e.button},isRight:function(e){return 2&e.button}}:{LEFT:0,MIDDLE:1,RIGHT:2,isButton:function(e,button){return e.button==button},isLeft:function(e){return 0==e.button},isMiddle:function(e){return 1==e.button},isRight:function(e){return 2==e.button}},dojo.mouseButtons=mouseButtons;var wheel;return wheel=has('events-mousewheel')?'mousewheel':function(node,listener){return on(node,'DOMMouseScroll',function(evt){evt.wheelDelta=-evt.detail,listener.call(this,evt)})},{_eventHandler:eventHandler,enter:eventHandler('mouseover'),leave:eventHandler('mouseout'),wheel:wheel,isLeft:mouseButtons.isLeft,isMiddle:mouseButtons.isMiddle,isRight:mouseButtons.isRight}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(4),__webpack_require__(8),__webpack_require__(3),__webpack_require__(6),__webpack_require__(2),__webpack_require__(58),__webpack_require__(95)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,has,dom,on,array,lang,loader,defaultEngine){'use strict';function queryForEngine(engine,NodeList){var query=function(query,root){if('string'==typeof root&&(root=dom.byId(root),!root))return new NodeList([]);var results='string'==typeof query?engine(query,root):query?query.end&&query.on?query:[query]:[];return results.end&&results.on?results:new NodeList(results)};if(query.matches=engine.match||function(node,selector,root){return 0<query.filter([node],selector,root).length},query.filter=engine.filter||function(nodes,selector,root){return query(selector,root).filter(function(node){return-1<array.indexOf(nodes,node)})},'function'!=typeof engine){var search=engine.search;engine=function(selector,root){return search(root||document,selector)}}return query}has.add('array-extensible',function(){return 1==lang.delegate([],{length:1}).length&&!has('bug-for-in-skips-shadowed')});var ap=Array.prototype,aps=ap.slice,apc=ap.concat,forEach=array.forEach,loopBody=function(f,a,o){return a=[0].concat(aps.call(a,0)),o=o||dojo.global,function(node){return a[0]=node,f.apply(o,a)}},NodeList=function(array){var isNew=this instanceof nl&&has('array-extensible');'number'==typeof array&&(array=Array(array));var nodeArray=array&&'length'in array?array:arguments;if(isNew||!nodeArray.sort){for(var target=isNew?this:[],l=target.length=nodeArray.length,i=0;i<l;i++)target[i]=nodeArray[i];if(isNew)return target;nodeArray=target}return lang._mixin(nodeArray,nlp),nodeArray._NodeListCtor=function(array){return nl(array)},nodeArray},nl=NodeList,nlp=nl.prototype=has('array-extensible')?[]:{};nl._wrap=nlp._wrap=function(a,parent,NodeListCtor){var nodeList=new(NodeListCtor||this._NodeListCtor||nl)(a);return parent?nodeList._stash(parent):nodeList},nl._adaptAsMap=function(f,o){return function(){return this.map(loopBody(f,arguments,o))}},nl._adaptAsForEach=function(f,o){return function(){return this.forEach(loopBody(f,arguments,o)),this}},nl._adaptAsFilter=function(f,o){return function(){return this.filter(loopBody(f,arguments,o))}},nl._adaptWithCondition=function(f,g,o){return function(){var a=arguments,body=loopBody(f,a,o);return g.call(o||dojo.global,a)?this.map(body):(this.forEach(body),this)}},forEach(['slice','splice'],function(name){var f=ap[name];nlp[name]=function(){return this._wrap(f.apply(this,arguments),'slice'==name?this:null)}}),forEach(['indexOf','lastIndexOf','every','some'],function(name){var f=array[name];nlp[name]=function(){return f.apply(dojo,[this].concat(aps.call(arguments,0)))}}),lang.extend(NodeList,{constructor:nl,_NodeListCtor:nl,toString:function(){return this.join(',')},_stash:function(parent){return this._parent=parent,this},on:function(eventName,listener){var handles=this.map(function(node){return on(node,eventName,listener)});return handles.remove=function(){for(var i=0;i<handles.length;i++)handles[i].remove()},handles},end:function(){return this._parent?this._parent:new this._NodeListCtor(0)},concat:function(){var t=aps.call(this,0),m=array.map(arguments,function(a){return aps.call(a,0)});return this._wrap(apc.apply(t,m),this)},map:function(func,obj){return this._wrap(array.map(this,func,obj),this)}
1,forEach:function(callback,thisObj){return forEach(this,callback,thisObj),this},filter:function(filter){var a=arguments,items=this,start=0;if('string'==typeof filter){if(items=query._filterResult(this,a[0]),1==a.length)return items._stash(this);start=1}return this._wrap(array.filter(items,a[start],a[start+1]),this)},instantiate:function(declaredClass,properties){var c=lang.isFunction(declaredClass)?declaredClass:lang.getObject(declaredClass);return properties=properties||{},this.forEach(function(node){new c(properties,node)})},at:function(){var t=new this._NodeListCtor(0);return forEach(arguments,function(i){0>i&&(i=this.length+i),this[i]&&t.push(this[i])},this),t._stash(this)}});var query=queryForEngine(defaultEngine,NodeList);return dojo.query=queryForEngine(defaultEngine,function(array){return NodeList(array)}),query.load=function(id,parentRequire,loaded){loader.load(id,parentRequire,function(engine){loaded(queryForEngine(engine,NodeList))})},dojo._filterQueryResult=query._filterResult=function(nodes,selector,root){return new NodeList(query.filter(nodes,selector,root))},dojo.NodeList=query.NodeList=NodeList,query}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(5),__webpack_require__(2)],__WEBPACK_AMD_DEFINE_RESULT__=function(dojo,lang){var regexp={};return lang.setObject('dojo.regexp',regexp),regexp.escapeString=function(str,except){return str.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,function(ch){return except&&-1!=except.indexOf(ch)?ch:'\\'+ch})},regexp.buildGroupRE=function(arr,re,nonCapture){if(!(arr instanceof Array))return re(arr);for(var b=[],i=0;i<arr.length;i++)b.push(re(arr[i]));return regexp.group(b.join('|'),nonCapture)},regexp.group=function(expression,nonCapture){return'('+(nonCapture?'?:':'')+expression+')'},regexp}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(88),__webpack_require__(5),__webpack_require__(6),__webpack_require__(4),__webpack_require__(58)],__WEBPACK_AMD_DEFINE_RESULT__=function(JSON,kernel,array,has){function handle(response){var handler=handlers[response.options.handleAs];return response.data=handler?handler(response):response.data||response.text,response}has.add('activex','undefined'!=typeof ActiveXObject),has.add('dom-parser',function(global){return'DOMParser'in global});var handleXML;if(has('activex')){var dp=['Msxml2.DOMDocument.6.0','Msxml2.DOMDocument.4.0','MSXML2.DOMDocument.3.0','MSXML.DOMDocument'];handleXML=function(response){var result=response.data;if(result&&has('dom-qsa2.1')&&!result.querySelectorAll&&has('dom-parser')&&(result=new DOMParser().parseFromString(response.text,'application/xml')),!result||!result.documentElement){var text=response.text;array.some(dp,function(p){try{var dom=new ActiveXObject(p);dom.async=!1,dom.loadXML(text),result=dom}catch(e){return!1}return!0})}return result}}var handlers={javascript:function(response){return kernel.eval(response.text||'')},json:function(response){return JSON.parse(response.text||null)},xml:handleXML};return handle.register=function(name,handler){handlers[name]=handler},handle}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(56),__webpack_require__(87),__webpack_require__(28),__webpack_require__(6),__webpack_require__(17),__webpack_require__(59)],__WEBPACK_AMD_DEFINE_RESULT__=function(util,RequestTimeoutError,CancelError,array,win,on){function watchInFlight(){for(var now=+new Date,i=0,dfd;i<_inFlight.length&&(dfd=_inFlight[i]);i++){var response=dfd.response,options=response.options;dfd.isCanceled&&dfd.isCanceled()||dfd.isValid&&!dfd.isValid(response)?(_inFlight.splice(i--,1),watch._onAction&&watch._onAction()):dfd.isReady&&dfd.isReady(response)?(_inFlight.splice(i--,1),dfd.handleResponse(response),watch._onAction&&watch._onAction()):dfd.startTime&&dfd.startTime+(options.timeout||0)<now&&(_inFlight.splice(i--,1),dfd.cancel(new RequestTimeoutError('Timeout exceeded',response)),watch._onAction&&watch._onAction())}watch._onInFlight&&watch._onInFlight(dfd),_inFlight.length||(clearInterval(_inFlightIntvl),_inFlightIntvl=null)}function watch(dfd){dfd.response.options.timeout&&(dfd.startTime=+new Date),dfd.isFulfilled()||(_inFlight.push(dfd),!_inFlightIntvl&&(_inFlightIntvl=setInterval(watchInFlight,50)),dfd.response.options.sync&&watchInFlight())}var _inFlightIntvl=null,_inFlight=[];return watch.cancelAll=function(){try{array.forEach(_inFlight,function(dfd){try{dfd.cancel(new CancelError('All requests canceled.'))}catch(e){}})}catch(e){}},win&&on&&win.doc.attachEvent&&on(win.global,'unload',function(){watch.cancelAll()}),watch}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(4),__webpack_require__(5)],__WEBPACK_AMD_DEFINE_RESULT__=function(has,dojo){'use strict';var testDiv=document.createElement('div'),matchesSelector=testDiv.matchesSelector||testDiv.webkitMatchesSelector||testDiv.mozMatchesSelector||testDiv.msMatchesSelector||testDiv.oMatchesSelector,querySelectorAll=testDiv.querySelectorAll,unionSplit=/([^\s,](?:"(?:\\.|[^"])+"|'(?:\\.|[^'])+'|[^,])*)/g;has.add('dom-matches-selector',!!matchesSelector),has.add('dom-qsa',!!querySelectorAll);var liteEngine=function(selector,root){if(combine&&-1<selector.indexOf(','))return combine(selector,root);var doc=root?root.ownerDocument||root:dojo.doc||document,match=(querySelectorAll?/^([\w]*)#([\w\-]+$)|^(\.)([\w\-\*]+$)|^(\w+$)/:/^([\w]*)#([\w\-]+)(?:\s+(.*))?$|(?:^|(>|.+\s+))([\w\-\*]+)(\S*$)/).exec(selector);
1if(root=root||doc,match){if(match[2]){var found=dojo.byId?dojo.byId(match[2],doc):doc.getElementById(match[2]);if(!found||match[1]&&match[1]!=found.tagName.toLowerCase())return[];if(root!=doc)for(var parent=found;parent!=root;)if(parent=parent.parentNode,!parent)return[];return match[3]?liteEngine(match[3],found):[found]}if(match[3]&&root.getElementsByClassName)return root.getElementsByClassName(match[4]);var found;if(match[5])if(found=root.getElementsByTagName(match[5]),match[4]||match[6])selector=(match[4]||'')+match[6];else return found}if(querySelectorAll)return 1===root.nodeType&&'object'!==root.nodeName.toLowerCase()?useRoot(root,selector,root.querySelectorAll):root.querySelectorAll(selector);found||(found=root.getElementsByTagName('*'));for(var results=[],i=0,l=found.length,node;i<l;i++)node=found[i],1==node.nodeType&&jsMatchesSelector(node,selector,root)&&results.push(node);return results},useRoot=function(context,query,method){var oldContext=context,old=context.getAttribute('id'),nid=old||'__dojo__',hasParent=context.parentNode,relativeHierarchySelector=/^\s*[+~]/.test(query);if(relativeHierarchySelector&&!hasParent)return[];old?nid=nid.replace(/'/g,'\\$&'):context.setAttribute('id',nid),relativeHierarchySelector&&hasParent&&(context=context.parentNode);for(var selectors=query.match(unionSplit),i=0;i<selectors.length;i++)selectors[i]='[id=\''+nid+'\'] '+selectors[i];query=selectors.join(',');try{return method.call(context,query)}finally{old||oldContext.removeAttribute('id')}};if(!has('dom-matches-selector'))var jsMatchesSelector=function(){function attr(name,value,type){var firstChar=value.charAt(0);('"'==firstChar||'\''==firstChar)&&(value=value.slice(1,-1)),value=value.replace(/\\/g,'');var comparator=attrComparators[type||''];return function(node){var attrValue=node.getAttribute(name);return attrValue&&comparator(attrValue,value)}}function ancestor(matcher){return function(node,root){for(;(node=node.parentNode)!=root;)if(matcher(node,root))return!0}}function parent(matcher){return function(node,root){return node=node.parentNode,matcher?node!=root&&matcher(node,root):node==root}}function and(matcher,next){return matcher?function(node,root){return next(node)&&matcher(node,root)}:next}var caseFix='div'==testDiv.tagName?'toLowerCase':'toUpperCase',selectorTypes={'':function(tagName){return tagName=tagName[caseFix](),function(node){return node.tagName==tagName}},'.':function(className){return function(node){return-1<node.className.indexOf(className)&&-1<(' '+node.className+' ').indexOf(' '+className+' ')}},'#':function(id){return function(node){return node.id==id}}},attrComparators={'^=':function(attrValue,value){return 0==attrValue.indexOf(value)},'*=':function(attrValue,value){return-1<attrValue.indexOf(value)},'$=':function(attrValue,value){return attrValue.substring(attrValue.length-value.length,attrValue.length)==value},'~=':function(attrValue,value){return-1<(' '+attrValue+' ').indexOf(' '+value+' ')},'|=':function(attrValue,value){return 0==(attrValue+'-').indexOf(value+'-')},'=':function(attrValue,value){return attrValue==value},'':function(){return!0}},cache={};return function(node,selector,root){var matcher=cache[selector];if(!matcher){if(selector.replace(/(?:\s*([> ])\s*)|(#|\.)?((?:\\.|[\w-])+)|\[\s*([\w-]+)\s*(.?=)?\s*("(?:\\.|[^"])+"|'(?:\\.|[^'])+'|(?:\\.|[^\]])*)\s*\]/g,function(t,combinator,type,value,attrName,attrType,attrValue){return value?matcher=and(matcher,selectorTypes[type||''](value.replace(/\\/g,''))):combinator?matcher=(' '==combinator?ancestor:parent)(matcher):attrName&&(matcher=and(matcher,attr(attrName,attrValue,attrType))),''}))throw new Error('Syntax error in query');if(!matcher)return!0;cache[selector]=matcher}return matcher(node,root)}}();if(!has('dom-qsa'))var combine=function(selector,root){for(var selectors=selector.match(unionSplit),indexed=[],i=0;i<selectors.length;i++){selector=new String(selectors[i].replace(/\s*$/,'')),selector.indexOf=escape;for(var results=liteEngine(selector,root),j=0,l=results.length,node;j<l;j++)node=results[j],indexed[node.sourceIndex]=node}var totalResults=[];for(i in indexed)totalResults.push(indexed[i]);return totalResults};return liteEngine.match=matchesSelector?function(node,selector,root){return root&&9
1!=root.nodeType?useRoot(root,selector,function(query){return matchesSelector.call(node,query)}):matchesSelector.call(node,selector)}:jsMatchesSelector,liteEngine}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(26),__webpack_require__(29)],__WEBPACK_AMD_DEFINE_RESULT__=function(Deferred,Promise){'use strict';return function(valueOrPromise,callback,errback,progback){var receivedPromise=valueOrPromise&&'function'==typeof valueOrPromise.then,nativePromise=receivedPromise&&valueOrPromise instanceof Promise;if(!receivedPromise)return 1<arguments.length?callback?callback(valueOrPromise):valueOrPromise:new Deferred().resolve(valueOrPromise);if(!nativePromise){var deferred=new Deferred(valueOrPromise.cancel);valueOrPromise.then(deferred.resolve,deferred.reject,deferred.progress),valueOrPromise=deferred.promise}return callback||errback||progback?valueOrPromise.then(callback,errback,progback):valueOrPromise}}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return'function'==typeof arg}function isNumber(arg){return'number'==typeof arg}function isObject(arg){return'object'==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError('n must be a positive number');return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),'error'===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))if(er=arguments[1],er instanceof Error)throw er;else{var err=new Error('Uncaught, unspecified "error" event. ('+er+')');throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args);}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i<len;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError('listener must be a function');return this._events||(this._events={}),this._events.newListener&&this.emit('newListener',type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&0<m&&this._events[type].length>m&&(this._events[type].warned=!0,void 0)),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError('listener must be a function');var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit
1('removeListener',type,listener);else if(isObject(list)){for(i=length;0<i--;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit('removeListener',type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)'removeListener'!==key&&this.removeAllListeners(key);return this.removeAllListeners('removeListener'),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[],ret},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},function(module,exports){(function(){var StateMachine={VERSION:'2.4.0',Result:{SUCCEEDED:1,NOTRANSITION:2,CANCELLED:3,PENDING:4},Error:{INVALID_TRANSITION:100,PENDING_TRANSITION:200,INVALID_CALLBACK:300},WILDCARD:'*',ASYNC:'async',create:function(cfg,target){var initial='string'==typeof cfg.initial?{state:cfg.initial}:cfg.initial,terminal=cfg.terminal||cfg.final,fsm=target||cfg.target||{},events=cfg.events||[],callbacks=cfg.callbacks||{},map={},transitions={},add=function(e){var from=Array.isArray(e.from)?e.from:e.from?[e.from]:[StateMachine.WILDCARD];map[e.name]=map[e.name]||{};for(var n=0;n<from.length;n++)transitions[from[n]]=transitions[from[n]]||[],transitions[from[n]].push(e.name),map[e.name][from[n]]=e.to||from[n];e.to&&(transitions[e.to]=transitions[e.to]||[])};initial&&(initial.event=initial.event||'startup',add({name:initial.event,from:'none',to:initial.state}));for(var n=0;n<events.length;n++)add(events[n]);for(var name in map)map.hasOwnProperty(name)&&(fsm[name]=StateMachine.buildEvent(name,map[name]));for(var name in callbacks)callbacks.hasOwnProperty(name)&&(fsm[name]=callbacks[name]);return fsm.current='none',fsm.is=function(state){return Array.isArray(state)?0<=state.indexOf(this.current):this.current===state},fsm.can=function(event){return!this.transition&&void 0!==map[event]&&(map[event].hasOwnProperty(this.current)||map[event].hasOwnProperty(StateMachine.WILDCARD))},fsm.cannot=function(event){return!this.can(event)},fsm.transitions=function(){return(transitions[this.current]||[]).concat(transitions[StateMachine.WILDCARD]||[])},fsm.isFinished=function(){return this.is(terminal)},fsm.error=cfg.error||function(name,from,to,args,error,msg,e){throw e||msg},fsm.states=function(){return Object.keys(transitions).sort()},initial&&!initial.defer&&fsm[initial.event](),fsm},doCallback:function(fsm,func,name,from,to,args){if(func)try{return func.apply(fsm,[name,from,to].concat(args))}catch(e){return fsm.error(name,from,to,args,StateMachine.Error.INVALID_CALLBACK,'an exception occurred in a caller-provided callback function',e)}},beforeAnyEvent:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm.onbeforeevent,name,from,to,args)},afterAnyEvent:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm.onafterevent||fsm.onevent,name,from,to,args)},leaveAnyState:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm.onleavestate,name,from,to,args)},enterAnyState:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm.onenterstate||fsm.onstate,name,from,to,args)},changeState:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm.onchangestate,name,from,to,args)},beforeThisEvent:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm['onbefore'+name],name,from,to,args)},afterThisEvent:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm['onafter'+name]||fsm['on'+name],name,from,to,args)},leaveThisState:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm['onleave'+from],name,from,to,args)},enterThisState:function(fsm,name,from,to,args){return StateMachine.doCallback(fsm,fsm['onenter'+to]||fsm['on'+to],name,from,to,args)},beforeEvent:function(fsm,name,from,to,args){if(!1===StateMachine.beforeThisEvent(fsm,name,from,to,args)||!1===StateMachine.beforeAnyEvent(fsm,name,from,to,args))return!1},afterEvent:function(fsm,name,from,to,args){StateMachine.afterThisEvent(fsm,name,from,to,args),StateMachine.afterAnyEvent(fsm,name,from,to,args)},leaveState:function(fsm,name,from,to,args){var specific=StateMachine.leaveThisState(fsm,name,from,to,args),general=StateMachine.leaveAnyState(fsm,name,from,to,args);
1if(!1===specific||!1===general)return!1;return StateMachine.ASYNC===specific||StateMachine.ASYNC===general?StateMachine.ASYNC:void 0},enterState:function(fsm,name,from,to,args){StateMachine.enterThisState(fsm,name,from,to,args),StateMachine.enterAnyState(fsm,name,from,to,args)},buildEvent:function(name,map){return function(){var from=this.current,to=map[from]||(map[StateMachine.WILDCARD]==StateMachine.WILDCARD?from:map[StateMachine.WILDCARD])||from,args=Array.prototype.slice.call(arguments);if(this.transition)return this.error(name,from,to,args,StateMachine.Error.PENDING_TRANSITION,'event '+name+' inappropriate because previous transition did not complete');if(this.cannot(name))return this.error(name,from,to,args,StateMachine.Error.INVALID_TRANSITION,'event '+name+' inappropriate in current state '+this.current);if(!1===StateMachine.beforeEvent(this,name,from,to,args))return StateMachine.Result.CANCELLED;if(from===to)return StateMachine.afterEvent(this,name,from,to,args),StateMachine.Result.NOTRANSITION;var fsm=this;this.transition=function(){return fsm.transition=null,fsm.current=to,StateMachine.enterState(fsm,name,from,to,args),StateMachine.changeState(fsm,name,from,to,args),StateMachine.afterEvent(fsm,name,from,to,args),StateMachine.Result.SUCCEEDED},this.transition.cancel=function(){fsm.transition=null,StateMachine.afterEvent(fsm,name,from,to,args)};var leave=StateMachine.leaveState(this,name,from,to,args);return!1===leave?(this.transition=null,StateMachine.Result.CANCELLED):StateMachine.ASYNC===leave?StateMachine.Result.PENDING:this.transition?this.transition():void 0}}};'undefined'!=typeof module&&module.exports&&(exports=module.exports=StateMachine),exports.StateMachine=StateMachine})()},function(module){module.exports={'gettingStationInformation':'Obteniendo informaci\xF3n de la estaci\xF3n...','paused':'Pausado','onAir':'En el aire','disconnected':'Desconectado','streamUnavailable':'Transmisi\xF3n no disponible','buffering':'Buffering','connecting':'Conexi\xF3n de transmisi\xF3n en vivo en progreso...','reconnecting':'Conexi\xF3n de transmisi\xF3n en vivo en progreso...','seekfailed':'Operaci\xF3n imposible','seekinvalidtime':'Operaci\xF3n imposible: tiempo no v\xE1lido','ended':'Terminado','pause':'Pausado','play':'En vivo','stop':'Desconectado','error':'Erro','streamGeoBlocked':'Lo sentimos, este contenido no est\xE1 disponible en su \xE1rea','stationNotFound':'No se encontr\xF3 la estaci\xF3n','flashPluginOutOfDate':'Su versi\xF3n Flash plugin detectada es obsoleta. La versi\xF3n m\xEDnima requerida es: 10.2.0','browserNotSupported':'Su navegador no es compatible con la funci\xF3n HTML5','playbackNotAllowed':'No se permite la reproducci\xF3n de medios en el contexto o situaci\xF3n actual','tritonListenLink':'El reproductor OnDemand no se puede usar con enlaces de escucha Triton'}},function(module){module.exports={'gettingStationInformation':'Chargement des informations de la station...','paused':'En pause','onAir':'En ondes','disconnected':'D\xE9connect\xE9','streamUnavailable':'Flux indisponible','buffering':'Mise en m\xE9moire tampon','connecting':'Connexion en cours...','reconnecting':'Connexion en cours...','seekfailed':'Op\xE9ration impossible','seekinvalidtime':'Op\xE9ration impossible : temps invalide','ended':'Termin\xE9','pause':'En pause','play':'En lecture','stop':'D\xE9connect\xE9','error':'Erreur','streamGeoBlocked':'D\xE9sol\xE9, ce flux n\'est pas disponible dans votre r\xE9gion','stationNotFound':'Station inexistante','flashPluginOutOfDate':'La version de votre plugin Flash est obsol\xE8te. La version minimale requise est: 10.2.0','browserNotSupported':'Votre navigateur ne supporte pas HTML5','playbackNotAllowed':'La lecture de contenu multim\xE9dia dans le contexte ou la situation actuels n\'est pas autoris\xE9e','tritonListenLink':'Le lecteur OnDemand ne peut pas \xEAtre utilis\xE9 avec les liens d\'\xE9coute Triton'}},function(module){module.exports={'gettingStationInformation':'Obtendo informa\xE7\xF5es da esta\xE7\xE3o...','paused':'Em Pausa','onAir':'No Ar','disconnected':'Desconectado','streamUnavailable':'Streaming n\xE3o dispon\xEDvel','buffering':'Em Buffer','connecting':'Conex\xE3o com stream ao vivo em andamento...','reconnecting':'Conex\xE3o com stream ao vivo em andamento...','seekfailed':'Opera\xE7\xE3o imposs\xEDvel','seekinvalidtime':'Opera\xE7\xE3o imposs\xEDvel: hora inv\xE1lida','ended':'Terminou','pause':'Pausa','play':'Tocando','stop':'Interrompido','error':'Erro','streamGeoBlocked':'Infelizmente, este conte\xFAdo n\xE3o est\xE1 dispon\xEDvel na sua \xE1rea','stationNotFound':'Esta\xE7\xE3o n\xE3o encontrada','flashPluginOutOfDate':'A vers\xE3o detectada do seu plug
1-in Flash est\xE1 desatualizada. A vers\xE3o m\xEDnima necess\xE1ria \xE9: 10.2.0','browserNotSupported':'Seu navegador n\xE3o oferece suporte para o recurso HTML5','playbackNotAllowed':'A reprodu\xE7\xE3o de m\xEDdia no contexto ou situa\xE7\xE3o atual n\xE3o \xE9 permitida','tritonListenLink':'O OnDemand player n\xE3o pode ser usado com links de escuta do Triton'}},function(module,exports,__webpack_require__){(function(process,setImmediate){(function(definition){'use strict';if('function'==typeof bootstrap)bootstrap('promise',definition);else{module.exports=definition()}})(function(){'use strict';function uncurryThis(f){return function(){return call.apply(f,arguments)}}function isObject(value){return value===Object(value)}function isStopIteration(exception){return'[object StopIteration]'===object_toString(exception)||exception instanceof QReturnValue}function makeStackTraceLong(error,promise){if(hasStacks&&promise.stack&&'object'==typeof error&&null!==error&&error.stack){for(var stacks=[],p=promise;!!p;p=p.source)p.stack&&(!error.__minimumStackCounter__||error.__minimumStackCounter__>p.stackCounter)&&(object_defineProperty(error,'__minimumStackCounter__',{value:p.stackCounter,configurable:!0}),stacks.unshift(p.stack));stacks.unshift(error.stack);var concatedStacks=stacks.join('\n'+STACK_JUMP_SEPARATOR+'\n'),stack=filterStackString(concatedStacks);object_defineProperty(error,'stack',{value:stack,configurable:!0})}}function filterStackString(stackString){for(var lines=stackString.split('\n'),desiredLines=[],i=0,line;i<lines.length;++i)line=lines[i],isInternalFrame(line)||isNodeFrame(line)||!line||desiredLines.push(line);return desiredLines.join('\n')}function isNodeFrame(stackLine){return-1!==stackLine.indexOf('(module.js:')||-1!==stackLine.indexOf('(node.js:')}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1)return[attempt1[1],+attempt1[2]];var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2)return[attempt2[1],+attempt2[2]];var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);if(attempt3)return[attempt3[1],+attempt3[2]]}function isInternalFrame(stackLine){var fileNameAndLineNumber=getFileNameAndLineNumber(stackLine);if(!fileNameAndLineNumber)return!1;var fileName=fileNameAndLineNumber[0],lineNumber=fileNameAndLineNumber[1];return fileName===qFileName&&lineNumber>=qStartingLine&&lineNumber<=qEndingLine}function captureLine(){if(hasStacks)try{throw new Error}catch(e){var lines=e.stack.split('\n'),firstLine=0<lines[0].indexOf('@')?lines[1]:lines[2],fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);return fileNameAndLineNumber?(qFileName=fileNameAndLineNumber[0],fileNameAndLineNumber[1]):void 0}}function Q(value){return value instanceof Promise?value:isPromiseAlike(value)?coerce(value):fulfill(value)}function defer(){function become(newPromise){resolvedPromise=newPromise,Q.longStackSupport&&hasStacks&&(promise.source=newPromise),array_reduce(messages,function(undefined,message){Q.nextTick(function(){newPromise.promiseDispatch.apply(newPromise,message)})},void 0),messages=void 0,progressListeners=void 0}var messages=[],progressListeners=[],deferred=object_create(defer.prototype),promise=object_create(Promise.prototype),resolvedPromise;if(promise.promiseDispatch=function(resolve,op,operands){var args=array_slice(arguments);messages?(messages.push(args),'when'===op&&operands[1]&&progressListeners.push(operands[1])):Q.nextTick(function(){resolvedPromise.promiseDispatch.apply(resolvedPromise,args)})},promise.valueOf=function(){if(messages)return promise;var nearerValue=nearer(resolvedPromise);return isPromise(nearerValue)&&(resolvedPromise=nearerValue),nearerValue},promise.inspect=function(){return resolvedPromise?resolvedPromise.inspect():{state:'pending'}},Q.longStackSupport&&hasStacks)try{throw new Error}catch(e){promise.stack=e.stack.substring(e.stack.indexOf('\n')+1),promise.stackCounter=longStackCounter++}return deferred.promise=promise,deferred.resolve=function(value){resolvedPromise||become(Q(value))},deferred.fulfill=function(value){resolvedPromise||become(fulfill(value))},deferred.reject=function(reason){resolvedPromise||become(reject(reason))},deferred.notify=function(progress){resolvedPromise||array_reduce(progressListeners,function(undefined,progressListener){Q.nextTick(function(){progressListener(progress)})},void 0)},deferred}function promise(resolver){if('function'!=typeof resolver)throw new TypeError('resolver must be a function.');var deferred=defer();try{resolver(deferred.resolve,deferred.reject,deferred.notify)}catch(reason){deferred.reject(reason)}return deferred.promise}function race(answerPs){return promise(function(resolve,reject){for(var i=0,len=answerPs.length;i<len;i++)Q(answerPs[i]).then(resolve,reject)})}function Promise(descriptor,fallback,inspect){void 0===fallback&&(fallback=function(op){return reject(new Error('Promise does not support operation: '+op))}),void 0===inspect&&(inspect=function(){return{state:'unknown'}});var promise=object_create(Promise.prototype);
1if(promise.promiseDispatch=function(resolve,op,args){var result;try{result=descriptor[op]?descriptor[op].apply(promise,args):fallback.call(promise,op,args)}catch(exception){result=reject(exception)}resolve&&resolve(result)},promise.inspect=inspect,inspect){var inspected=inspect();'rejected'===inspected.state&&(promise.exception=inspected.reason),promise.valueOf=function(){var inspected=inspect();return'pending'===inspected.state||'rejected'===inspected.state?promise:inspected.value}}return promise}function when(value,fulfilled,rejected,progressed){return Q(value).then(fulfilled,rejected,progressed)}function nearer(value){if(isPromise(value)){var inspected=value.inspect();if('fulfilled'===inspected.state)return inspected.value}return value}function isPromise(object){return object instanceof Promise}function isPromiseAlike(object){return isObject(object)&&'function'==typeof object.then}function resetUnhandledRejections(){unhandledReasons.length=0,unhandledRejections.length=0,trackUnhandledRejections||(trackUnhandledRejections=!0)}function trackRejection(promise,reason){trackUnhandledRejections&&('object'==typeof process&&'function'==typeof process.emit&&Q.nextTick.runAfter(function(){-1!==array_indexOf(unhandledRejections,promise)&&(process.emit('unhandledRejection',reason,promise),reportedUnhandledRejections.push(promise))}),unhandledRejections.push(promise),reason&&'undefined'!=typeof reason.stack?unhandledReasons.push(reason.stack):unhandledReasons.push('(no stack) '+reason))}function untrackRejection(promise){if(trackUnhandledRejections){var at=array_indexOf(unhandledRejections,promise);-1!==at&&('object'==typeof process&&'function'==typeof process.emit&&Q.nextTick.runAfter(function(){var atReport=array_indexOf(reportedUnhandledRejections,promise);-1!==atReport&&(process.emit('rejectionHandled',unhandledReasons[at],promise),reportedUnhandledRejections.splice(atReport,1))}),unhandledRejections.splice(at,1),unhandledReasons.splice(at,1))}}function reject(reason){var rejection=Promise({'when':function(rejected){return rejected&&untrackRejection(this),rejected?rejected(reason):this}},function(){return this},function(){return{state:'rejected',reason:reason}});return trackRejection(rejection,reason),rejection}function fulfill(value){return Promise({'when':function(){return value},'get':function(name){return value[name]},'set':function(name,rhs){value[name]=rhs},'delete':function(name){delete value[name]},'post':function(name,args){return null===name||void 0===name?value.apply(void 0,args):value[name].apply(value,args)},'apply':function(thisp,args){return value.apply(thisp,args)},'keys':function(){return object_keys(value)}},void 0,function(){return{state:'fulfilled',value:value}})}function coerce(promise){var deferred=defer();return Q.nextTick(function(){try{promise.then(deferred.resolve,deferred.reject,deferred.notify)}catch(exception){deferred.reject(exception)}}),deferred.promise}function spread(value,fulfilled,rejected){return Q(value).spread(fulfilled,rejected)}function _return(value){throw new QReturnValue(value)}function dispatch(object,op,args){return Q(object).dispatch(op,args)}function all(promises){return when(promises,function(promises){var pendingCount=0,deferred=defer();return array_reduce(promises,function(undefined,promise,index){var snapshot;isPromise(promise)&&'fulfilled'===(snapshot=promise.inspect()).state?promises[index]=snapshot.value:(++pendingCount,when(promise,function(value){promises[index]=value,0==--pendingCount&&deferred.resolve(promises)},deferred.reject,function(progress){deferred.notify({index:index,value:progress})}))},void 0),0==pendingCount&&deferred.resolve(promises),deferred.promise})}function any(promises){if(0===promises.length)return Q.resolve();var deferred=Q.defer(),pendingCount=0;return array_reduce(promises,function(prev,current,index){function onRejected(err){if(pendingCount--,0==pendingCount){var rejection=err||new Error(''+err);rejection.message='Q can\'t get fulfillment value from any promise, all promises were rejected. Last error message: '+rejection.message,deferred.reject(rejection)}}var promise=promises[index];pendingCount++,when(promise,function(result){deferred.resolve(result)},onRejected,function(progress){deferred.notify({index:index,value:progress})})},void 0),deferred.promise}function allResolved(promises){return when(promises,function(promises){return promises=array_map(promises,Q),when(all(array_map(promises,function(promise){return when(promise,noop,noop)})),function(){return promises})})}var hasStacks=!1;try{throw new Error}catch(e){hasStacks=!!e.stack}var qStartingLine=captureLine(),noop=function(){},nextTick=function(){function flush(){for(var task,domain;head.next;)head=head.next,task=head.task,head.task=void 0,domain=head.domain,domain&&(head.domain=void 0,domain.enter()),runSingle(task,domain);for(;laterQueue.length;)task=laterQueue.pop(),runSingle(task);flushing=!1}function runSingle(task,domain){try{task()}catch(e){if(isNodeJS)throw domain&&domain.exit(),setTimeout(flush,0),domain&&domain.enter(),e;else setTimeout(function(){throw e},0)}domain&&domain.exit()}var head={task:void 0,next:null},tail=head,flushing=!1,requestTick=void 0,isNodeJS=!1,laterQueue=[];
1if(nextTick=function(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null},flushing||(flushing=!0,requestTick())},'object'==typeof process&&'[object process]'===process.toString()&&process.nextTick)isNodeJS=!0,requestTick=function(){process.nextTick(flush)};else if('function'==typeof setImmediate)requestTick='undefined'==typeof window?function(){setImmediate(flush)}:setImmediate.bind(window,flush);else if('undefined'!=typeof MessageChannel){var channel=new MessageChannel;channel.port1.onmessage=function(){requestTick=requestPortTick,channel.port1.onmessage=flush,flush()};var requestPortTick=function(){channel.port2.postMessage(0)};requestTick=function(){setTimeout(flush,0),requestPortTick()}}else requestTick=function(){setTimeout(flush,0)};return nextTick.runAfter=function(task){laterQueue.push(task),flushing||(flushing=!0,requestTick())},nextTick}(),call=Function.call,array_slice=uncurryThis(Array.prototype.slice),array_reduce=uncurryThis(Array.prototype.reduce||function(callback,basis){var index=0,length=this.length;if(1===arguments.length)do{if(index in this){basis=this[index++];break}if(++index>=length)throw new TypeError}while(1);for(;index<length;index++)index in this&&(basis=callback(basis,this[index],index));return basis}),array_indexOf=uncurryThis(Array.prototype.indexOf||function(value){for(var i=0;i<this.length;i++)if(this[i]===value)return i;return-1}),array_map=uncurryThis(Array.prototype.map||function(callback,thisp){var self=this,collect=[];return array_reduce(self,function(undefined,value,index){collect.push(callback.call(thisp,value,index,self))},void 0),collect}),object_create=Object.create||function(prototype){function Type(){}return Type.prototype=prototype,new Type},object_defineProperty=Object.defineProperty||function(obj,prop,descriptor){return obj[prop]=descriptor.value,obj},object_hasOwnProperty=uncurryThis(Object.prototype.hasOwnProperty),object_keys=Object.keys||function(object){var keys=[];for(var key in object)object_hasOwnProperty(object,key)&&keys.push(key);return keys},object_toString=uncurryThis(Object.prototype.toString),qFileName,QReturnValue;QReturnValue='undefined'==typeof ReturnValue?function(value){this.value=value}:ReturnValue;var STACK_JUMP_SEPARATOR='From previous event:';Q.resolve=Q,Q.nextTick=nextTick,Q.longStackSupport=!1;var longStackCounter=1;'object'==typeof process&&process&&process.env&&process.env.Q_DEBUG&&(Q.longStackSupport=!0),Q.defer=defer,defer.prototype.makeNodeResolver=function(){var self=this;return function(error,value){error?self.reject(error):2<arguments.length?self.resolve(array_slice(arguments,1)):self.resolve(value)}},Q.Promise=promise,Q.promise=promise,promise.race=race,promise.all=all,promise.reject=reject,promise.resolve=Q,Q.passByCopy=function(object){return object},Promise.prototype.passByCopy=function(){return this},Q.join=function(x,y){return Q(x).join(y)},Promise.prototype.join=function(that){return Q([this,that]).spread(function(x,y){if(x===y)return x;throw new Error('Q can\'t join: not the same: '+x+' '+y)})},Q.race=race,Promise.prototype.race=function(){return this.then(Q.race)},Q.makePromise=Promise,Promise.prototype.toString=function(){return'[object Promise]'},Promise.prototype.then=function(fulfilled,rejected,progressed){function _fulfilled(value){try{return'function'==typeof fulfilled?fulfilled(value):value}catch(exception){return reject(exception)}}function _rejected(exception){if('function'==typeof rejected){makeStackTraceLong(exception,self);try{return rejected(exception)}catch(newException){return reject(newException)}}return reject(exception)}function _progressed(value){return'function'==typeof progressed?progressed(value):value}var self=this,deferred=defer(),done=!1;return Q.nextTick(function(){self.promiseDispatch(function(value){done||(done=!0,deferred.resolve(_fulfilled(value)))},'when',[function(exception){done||(done=!0,deferred.resolve(_rejected(exception)))}])}),self.promiseDispatch(void 0,'when',[void 0,function(value){var threw=!1,newValue;try{newValue=_progressed(value)}
1catch(e){if(threw=!0,Q.onerror)Q.onerror(e);else throw e}threw||deferred.notify(newValue)}]),deferred.promise},Q.tap=function(promise,callback){return Q(promise).tap(callback)},Promise.prototype.tap=function(callback){return callback=Q(callback),this.then(function(value){return callback.fcall(value).thenResolve(value)})},Q.when=when,Promise.prototype.thenResolve=function(value){return this.then(function(){return value})},Q.thenResolve=function(promise,value){return Q(promise).thenResolve(value)},Promise.prototype.thenReject=function(reason){return this.then(function(){throw reason})},Q.thenReject=function(promise,reason){return Q(promise).thenReject(reason)},Q.nearer=nearer,Q.isPromise=isPromise,Q.isPromiseAlike=isPromiseAlike,Q.isPending=function(object){return isPromise(object)&&'pending'===object.inspect().state},Promise.prototype.isPending=function(){return'pending'===this.inspect().state},Q.isFulfilled=function(object){return!isPromise(object)||'fulfilled'===object.inspect().state},Promise.prototype.isFulfilled=function(){return'fulfilled'===this.inspect().state},Q.isRejected=function(object){return isPromise(object)&&'rejected'===object.inspect().state},Promise.prototype.isRejected=function(){return'rejected'===this.inspect().state};var unhandledReasons=[],unhandledRejections=[],reportedUnhandledRejections=[],trackUnhandledRejections=!0;Q.resetUnhandledRejections=resetUnhandledRejections,Q.getUnhandledReasons=function(){return unhandledReasons.slice()},Q.stopUnhandledRejectionTracking=function(){resetUnhandledRejections(),trackUnhandledRejections=!1},resetUnhandledRejections(),Q.reject=reject,Q.fulfill=fulfill,Q.master=function(object){return Promise({'isDef':function(){}},function(op,args){return dispatch(object,op,args)},function(){return Q(object).inspect()})},Q.spread=spread,Promise.prototype.spread=function(fulfilled,rejected){return this.all().then(function(array){return fulfilled.apply(void 0,array)},rejected)},Q.async=function(makeGenerator){return function(){function continuer(verb,arg){var result;if('undefined'==typeof StopIteration){try{result=generator[verb](arg)}catch(exception){return reject(exception)}return result.done?Q(result.value):when(result.value,callback,errback)}try{result=generator[verb](arg)}catch(exception){return isStopIteration(exception)?Q(exception.value):reject(exception)}return when(result,callback,errback)}var generator=makeGenerator.apply(this,arguments),callback=continuer.bind(continuer,'next'),errback=continuer.bind(continuer,'throw');return callback()}},Q.spawn=function(makeGenerator){Q.done(Q.async(makeGenerator)())},Q['return']=_return,Q.promised=function(callback){return function(){return spread([this,all(arguments)],function(self,args){return callback.apply(self,args)})}},Q.dispatch=dispatch,Promise.prototype.dispatch=function(op,args){var self=this,deferred=defer();return Q.nextTick(function(){self.promiseDispatch(deferred.resolve,op,args)}),deferred.promise},Q.get=function(object,key){return Q(object).dispatch('get',[key])},Promise.prototype.get=function(key){return this.dispatch('get',[key])},Q.set=function(object,key,value){return Q(object).dispatch('set',[key,value])},Promise.prototype.set=function(key,value){return this.dispatch('set',[key,value])},Q.del=Q['delete']=function(object,key){return Q(object).dispatch('delete',[key])},Promise.prototype.del=Promise.prototype['delete']=function(key){return this.dispatch('delete',[key])},Q.mapply=Q.post=function(object,name,args){return Q(object).dispatch('post',[name,args])},Promise.prototype.mapply=Promise.prototype.post=function(name,args){return this.dispatch('post',[name,args])},Q.send=Q.mcall=Q.invoke=function(object,name){return Q(object).dispatch('post',[name,array_slice(arguments,2)])},Promise.prototype.send=Promise.prototype.mcall=Promise.prototype.invoke=function(name){return this.dispatch('post',[name,array_slice(arguments,1)])},Q.fapply=function(object,args){return Q(object).dispatch('apply',[void 0,args])},Promise.prototype.fapply=function(args){return this.dispatch('apply',[void 0,args])},Q['try']=Q.fcall=function(object){return Q(object).dispatch('apply',[void 0,array_slice(arguments,1
1)])},Promise.prototype.fcall=function(){return this.dispatch('apply',[void 0,array_slice(arguments)])},Q.fbind=function(object){var promise=Q(object),args=array_slice(arguments,1);return function(){return promise.dispatch('apply',[this,args.concat(array_slice(arguments))])}},Promise.prototype.fbind=function(){var promise=this,args=array_slice(arguments);return function(){return promise.dispatch('apply',[this,args.concat(array_slice(arguments))])}},Q.keys=function(object){return Q(object).dispatch('keys',[])},Promise.prototype.keys=function(){return this.dispatch('keys',[])},Q.all=all,Promise.prototype.all=function(){return all(this)},Q.any=any,Promise.prototype.any=function(){return any(this)},Q.allResolved=function(callback){return function(){return'undefined'!=typeof console&&!0&&void 0,callback.apply(callback,arguments)}}(allResolved,'allResolved','allSettled'),Promise.prototype.allResolved=function(){return allResolved(this)},Q.allSettled=function(promises){return Q(promises).allSettled()},Promise.prototype.allSettled=function(){return this.then(function(promises){return all(array_map(promises,function(promise){function regardless(){return promise.inspect()}return promise=Q(promise),promise.then(regardless,regardless)}))})},Q.fail=Q['catch']=function(object,rejected){return Q(object).then(void 0,rejected)},Promise.prototype.fail=Promise.prototype['catch']=function(rejected){return this.then(void 0,rejected)},Q.progress=function(object,progressed){return Q(object).then(void 0,void 0,progressed)},Promise.prototype.progress=function(progressed){return this.then(void 0,void 0,progressed)},Q.fin=Q['finally']=function(object,callback){return Q(object)['finally'](callback)},Promise.prototype.fin=Promise.prototype['finally']=function(callback){if(!callback||'function'!=typeof callback.apply)throw new Error('Q can\'t apply finally callback');return callback=Q(callback),this.then(function(value){return callback.fcall().then(function(){return value})},function(reason){return callback.fcall().then(function(){throw reason})})},Q.done=function(object,fulfilled,rejected,progress){return Q(object).done(fulfilled,rejected,progress)},Promise.prototype.done=function(fulfilled,rejected,progress){var onUnhandledError=function(error){Q.nextTick(function(){if(makeStackTraceLong(error,promise),Q.onerror)Q.onerror(error);else throw error})},promise=fulfilled||rejected||progress?this.then(fulfilled,rejected,progress):this;'object'==typeof process&&process&&process.domain&&(onUnhandledError=process.domain.bind(onUnhandledError)),promise.then(void 0,onUnhandledError)},Q.timeout=function(object,ms,error){return Q(object).timeout(ms,error)},Promise.prototype.timeout=function(ms,error){var deferred=defer(),timeoutId=setTimeout(function(){error&&'string'!=typeof error||(error=new Error(error||'Timed out after '+ms+' ms'),error.code='ETIMEDOUT'),deferred.reject(error)},ms);return this.then(function(value){clearTimeout(timeoutId),deferred.resolve(value)},function(exception){clearTimeout(timeoutId),deferred.reject(exception)},deferred.notify),deferred.promise},Q.delay=function(object,timeout){return void 0===timeout&&(timeout=object,object=void 0),Q(object).delay(timeout)},Promise.prototype.delay=function(timeout){return this.then(function(value){var deferred=defer();return setTimeout(function(){deferred.resolve(value)},timeout),deferred.promise})},Q.nfapply=function(callback,args){return Q(callback).nfapply(args)},Promise.prototype.nfapply=function(args){var deferred=defer(),nodeArgs=array_slice(args);return nodeArgs.push(deferred.makeNodeResolver()),this.fapply(nodeArgs).fail(deferred.reject),deferred.promise},Q.nfcall=function(callback){var args=array_slice(arguments,1);return Q(callback).nfapply(args)},Promise.prototype.nfcall=function(){var nodeArgs=array_slice(arguments),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.fapply(nodeArgs).fail(deferred.reject),deferred.promise},Q.nfbind=Q.denodeify=function(callback){if(callback===void 0)throw new Error('Q can\'t wrap an undefined function');
1var baseArgs=array_slice(arguments,1);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(callback).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nfbind=Promise.prototype.denodeify=function(){var args=array_slice(arguments);return args.unshift(this),Q.denodeify.apply(void 0,args)},Q.nbind=function(callback,thisp){var baseArgs=array_slice(arguments,2);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(function(){return callback.apply(thisp,arguments)}).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nbind=function(){var args=array_slice(arguments,0);return args.unshift(this),Q.nbind.apply(void 0,args)},Q.nmapply=Q.npost=function(object,name,args){return Q(object).npost(name,args)},Promise.prototype.nmapply=Promise.prototype.npost=function(name,args){var nodeArgs=array_slice(args||[]),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.dispatch('post',[name,nodeArgs]).fail(deferred.reject),deferred.promise},Q.nsend=Q.nmcall=Q.ninvoke=function(object,name){var nodeArgs=array_slice(arguments,2),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(object).dispatch('post',[name,nodeArgs]).fail(deferred.reject),deferred.promise},Promise.prototype.nsend=Promise.prototype.nmcall=Promise.prototype.ninvoke=function(name){var nodeArgs=array_slice(arguments,1),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.dispatch('post',[name,nodeArgs]).fail(deferred.reject),deferred.promise},Q.nodeify=function(object,nodeback){return Q(object).nodeify(nodeback)},Promise.prototype.nodeify=function(nodeback){return nodeback?void this.then(function(value){Q.nextTick(function(){nodeback(null,value)})},function(error){Q.nextTick(function(){nodeback(error)})}):this},Q.noConflict=function(){throw new Error('Q.noConflict only works when Q is used as a global')};var qEndingLine=captureLine();return Q})}).call(exports,__webpack_require__(61),__webpack_require__(105).setImmediate)},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__;(function(name,definition){'undefined'!=typeof module&&module.exports?module.exports=definition():(__WEBPACK_AMD_DEFINE_FACTORY__=definition,__WEBPACK_AMD_DEFINE_RESULT__='function'==typeof __WEBPACK_AMD_DEFINE_FACTORY__?__WEBPACK_AMD_DEFINE_FACTORY__.call(exports,__webpack_require__,exports,module):__WEBPACK_AMD_DEFINE_FACTORY__,!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__)))})('$script',function(){function every(ar,fn){for(var i=0,j=ar.length;i<j;++i)if(!fn(ar[i]))return f;return 1}function each(ar,fn){every(ar,function(el){return fn(el),1})}function $script(paths,idOrDone,optDone){function loopFn(item){return item.call?item():list[item]}function callback(){if(! --queue)for(var dset in list[id]=1,done&&done(),delay)every(dset.split('|'),loopFn)&&!each(delay[dset],loopFn)&&(delay[dset]=[])}paths=paths[push]?paths:[paths];var idOrDoneIsDone=idOrDone&&idOrDone.call,done=idOrDoneIsDone?idOrDone:optDone,id=idOrDoneIsDone?paths.join(''):idOrDone,queue=paths.length;return setTimeout(function(){each(paths,function loading(path,force){return null===path?callback():(force||/^https?:\/\//.test(path)||!scriptpath||(path=-1===path.indexOf('.js')?scriptpath+path+'.js':scriptpath+p
1ath),scripts[path]?(id&&(ids[id]=1),2==scripts[path]?callback():setTimeout(function(){loading(path,!0)},0)):void(scripts[path]=1,id&&(ids[id]=1),create(path,callback)))})},0),$script}function create(path,fn){var el=doc.createElement('script'),loaded;el.onload=el.onerror=el[onreadystatechange]=function(){el[readyState]&&!/^c|loade/.test(el[readyState])||loaded||(el.onload=el[onreadystatechange]=null,loaded=1,scripts[path]=2,fn())},el.async=1,el.src=urlArgs?path+(-1===path.indexOf('?')?'?':'&')+urlArgs:path,head.insertBefore(el,head.lastChild)}var doc=document,head=doc.getElementsByTagName('head')[0],f=!1,push='push',readyState='readyState',onreadystatechange='onreadystatechange',list={},ids={},delay={},scripts={},scriptpath,urlArgs;return $script.get=create,$script.order=function(scripts,id,done){(function callback(s){s=scripts.shift(),scripts.length?$script(s,callback):$script(s,id,done)})()},$script.path=function(p){scriptpath=p},$script.urlArgs=function(str){urlArgs=str},$script.ready=function(deps,ready,req){deps=deps[push]?deps:[deps];var missing=[];return!each(deps,function(dep){list[dep]||missing[push](dep)})&&every(deps,function(dep){return list[dep]})?ready():!function(key){delay[key]=delay[key]||[],delay[key][push](ready),req&&req(missing)}(deps.join('|')),$script},$script.done=function(idOrDone){$script([null],idOrDone)},$script})},function(module,exports,__webpack_require__){(function(global,process){(function(global){'use strict';function setImmediate(callback){'function'!=typeof callback&&(callback=new Function(''+callback));for(var args=Array(arguments.length-1),i=0;i<args.length;i++)args[i]=arguments[i+1];var task={callback:callback,args:args};return tasksByHandle[nextHandle]=task,registerImmediate(nextHandle),nextHandle++}function clearImmediate(handle){delete tasksByHandle[handle]}function run(task){var callback=task.callback,args=task.args;switch(args.length){case 0:callback();break;case 1:callback(args[0]);break;case 2:callback(args[0],args[1]);break;case 3:callback(args[0],args[1],args[2]);break;default:callback.apply(void 0,args);}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(runIfPresent,0,handle);else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{run(task)}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function installNextTickImplementation(){registerImmediate=function(handle){process.nextTick(function(){runIfPresent(handle)})}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage('','*'),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix='setImmediate$'+Math.random()+'$',onGlobalMessage=function(event){event.source===global&&'string'==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener('message',onGlobalMessage,!1):global.attachEvent('onmessage',onGlobalMessage),registerImmediate=function(handle){global.postMessage(messagePrefix+handle,'*')}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},registerImmediate=function(handle){channel.port2.postMessage(handle)}}function installReadyStateChangeImplementation(){var html=doc.documentElement;registerImmediate=function(handle){var script=doc.createElement('script');script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script)}}function installSetTimeoutImplementation(){registerImmediate=function(handle){setTimeout(runIfPresent,0,handle)}}if(!global.setImmediate){var nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global),registerImmediate;attachTo=attachTo&&attachTo.setTimeout?attachTo:global,'[object process]'==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.Me
1ssageChannel?installMessageChannelImplementation():doc&&'onreadystatechange'in doc.createElement('script')?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}})('undefined'==typeof self?'undefined'==typeof global?this:global:self)}).call(exports,function(){return this}(),__webpack_require__(61))},function(module,exports,__webpack_require__){(function(global){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var scope='undefined'!=typeof global&&global||'undefined'!=typeof self&&self||window,apply=Function.prototype.apply;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,scope,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,scope,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout&&timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(scope,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;0<=msecs&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},__webpack_require__(104),exports.setImmediate='undefined'!=typeof self&&self.setImmediate||'undefined'!=typeof global&&global.setImmediate||this&&this.setImmediate,exports.clearImmediate='undefined'!=typeof self&&self.clearImmediate||'undefined'!=typeof global&&global.clearImmediate||this&&this.clearImmediate}).call(exports,function(){return this}())},function(module,exports){(function(global){(function(global,factory){factory(exports)})(this,function(exports){'use strict';function isDataView(obj){return obj&&DataView.prototype.isPrototypeOf(obj)}function normalizeName(name){if('string'!=typeof name&&(name+=''),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name)||''===name)throw new TypeError('Invalid character in header field name: "'+name+'"');return name.toLowerCase()}function normalizeValue(value){return'string'!=typeof value&&(value+=''),value}function iteratorFor(items){var iterator={next:function(){var value=items.shift();return{done:void 0===value,value:value}}};return support.iterable&&(iterator[Symbol.iterator]=function(){return iterator}),iterator}function Headers(headers){this.map={},headers instanceof Headers?headers.forEach(function(value,name){this.append(name,value)},this):Array.isArray(headers)?headers.forEach(function(header){if(2!=header.length)throw new TypeError('Headers constructor: expected name/value pair to be length 2, found'+header.length);this.append(header[0],header[1])},this):headers&&Object.getOwnPropertyNames(headers).forEach(function(name){this.append(name,headers[name])},this)}function consumed(body){return body._noBody?void 0:body.bodyUsed?Promise.reject(new TypeError('Already read')):void(body.bodyUsed=!0)}function fileReaderReady(reader){return new Promise(function(resolve,reject){reader.onload=function(){resolve(reader.result)},reader.onerror=function(){reject(reader.error)}})}function readBlobAsArrayBuffer(blob){var reader=new FileReader,promise=fileReaderReady(reader);return reader.readAsArrayBuffer(blob),promise}function readBlobAsText(blob){var reader=new FileReader,promise=fileReaderReady(reader),match=/charset=([A-Za-z0-9_-]+)/.exec(blob.type),encoding=match?match[1]:'utf-8';return reader.readAsText(blob,encoding),promise}function readArrayBufferAsText(buf){for(var view=new Uint8Array(buf),chars=Array(view.length),i=0;i<view.length;i++)chars[i]=String.fromCharCode(view[i]);return chars.join('')}function bufferClone(buf){if(buf.slice)return buf.slice(0);var view=new Uint8Array(buf.byteLength);return view.set(new Uint8Array(buf)),view.buffer}function Body(){return this.bodyUsed=!1,this._initBody=function(body){this.bodyUsed=this.bodyUsed,this._bodyInit=body,body?'string'==typeof body?this._bodyText=body:support.blob&&Blob.prototype.isPrototypeOf(body)?this._bodyBlob=body:support.formData&&FormData.prototype.isPrototypeOf(body)?this._bodyFormData=body:support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)?this._bodyText=body.toString():support.arrayBuffer&&support.blob&&isDataView(body)?(this._bodyArrayBuffer=bufferClone(body.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):support.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(body)||isArrayBufferView(body))?this._bodyArrayBuffer=bufferClone(body):this._bodyText=body=Object.prototype.toString.call(body):(this._noBody=!0,this._bodyText=''),this.headers.get('content-type')||('string'==typeof body?this.headers.set('content-type','text/plain;charset=UTF-8'):this._bodyBlob&&this._bodyBlob.type?this.headers.set('content-type',this._bodyBlob.type):support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)&&this.headers.set('content-type','application/x-www-form-urlencoded;charset=UTF-8'))},support.blob&&(this.blob=function(){var rejected=consumed(this);if(rejected)return rejected;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error('could not read FormData body as blob');else return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var isConsumed=consumed(this);return isConsumed?isConsumed:ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer)}if(support.blob)return this.blob().then(readBlobAsArrayBuffer);throw new Error('could not read as ArrayBuffer')},this.text=function(){var rejected=consumed(this);if(rejected)return rejected;if(this._bodyBlob)return readBlobAsText(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error('could not read FormData body as text');else return Promise.resolve(this._bodyText)},support.formData&&(this.formData=function(){return this.text().then(decode)}),this.json=function(){return this.text().then(JSON.parse)},this}
vendor: 4,409 bytes, line 1
1function normalizeMethod(method){var upcased=method.toUpperCase();return-1<methods.indexOf(upcased)?upcased:method}function Request(input,options){if(!(this instanceof Request))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');options=options||{};var body=options.body;if(input instanceof Request){if(input.bodyUsed)throw new TypeError('Already read');this.url=input.url,this.credentials=input.credentials,options.headers||(this.headers=new Headers(input.headers)),this.method=input.method,this.mode=input.mode,this.signal=input.signal,body||null==input._bodyInit||(body=input._bodyInit,input.bodyUsed=!0)}else this.url=input+'';if(this.credentials=options.credentials||this.credentials||'same-origin',(options.headers||!this.headers)&&(this.headers=new Headers(options.headers)),this.method=normalizeMethod(options.method||this.method||'GET'),this.mode=options.mode||this.mode||null,this.signal=options.signal||this.signal||function(){if('AbortController'in g){var ctrl=new AbortController;return ctrl.signal}}(),this.referrer=null,('GET'===this.method||'HEAD'===this.method)&&body)throw new TypeError('Body not allowed for GET or HEAD requests');if(this._initBody(body),('GET'===this.method||'HEAD'===this.method)&&('no-store'===options.cache||'no-cache'===options.cache)){var reParamSearch=/([?&])_=[^&]*/;if(reParamSearch.test(this.url))this.url=this.url.replace(reParamSearch,'$1_='+new Date().getTime());else{var reQueryString=/\?/;this.url+=(reQueryString.test(this.url)?'&':'?')+'_='+new Date().getTime()}}}function decode(body){var form=new FormData;return body.trim().split('&').forEach(function(bytes){if(bytes){var split=bytes.split('='),name=split.shift().replace(/\+/g,' '),value=split.join('=').replace(/\+/g,' ');form.append(decodeURIComponent(name),decodeURIComponent(value))}}),form}function parseHeaders(rawHeaders){var headers=new Headers,preProcessedHeaders=rawHeaders.replace(/\r?\n[\t ]+/g,' ');return preProcessedHeaders.split('\r').map(function(header){return 0===header.indexOf('\n')?header.substr(1,header.length):header}).forEach(function(line){var parts=line.split(':'),key=parts.shift().trim();if(key){var value=parts.join(':').trim();try{headers.append(key,value)}catch(error){}}}),headers}function Response(bodyInit,options){if(!(this instanceof Response))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(options||(options={}),this.type='default',this.status=void 0===options.status?200:options.status,200>this.status||599<this.status)throw new RangeError('Failed to construct \'Response\': The status provided (0) is outside the range [200, 599].');this.ok=200<=this.status&&300>this.status,this.statusText=void 0===options.statusText?'':''+options.statusText,this.headers=new Headers(options.headers),this.url=options.url||'',this._initBody(bodyInit)}function fetch(input,init){return new Promise(function(resolve,reject){function abortXhr(){xhr.abort()}var request=new Request(input,init);if(request.signal&&request.signal.aborted)return reject(new exports.DOMException('Aborted','AbortError'));var xhr=new XMLHttpRequest;if(xhr.onload=function(){var options={statusText:xhr.statusText,headers:parseHeaders(xhr.getAllResponseHeaders()||'')};options.status=0===request.url.indexOf('file://')&&(200>xhr.status||599<xhr.status)?200:xhr.status,options.url='responseURL'in xhr?xhr.responseURL:options.headers.get('X-Request-URL');var body='response'in xhr?xhr.response:xhr.responseText;setTimeout(function(){resolve(new Response(body,options))},0)},xhr.onerror=function(){setTimeout(function(){reject(new TypeError('Network request failed'))},0)},xhr.ontimeout=function(){setTimeout(function(){reject(new TypeError('Network request timed out'))},0)},xhr.onabort=function(){setTimeout(function(){reject(new exports.DOMException('Aborted','AbortError'))},0)},xhr.open(request.method,function(url){try{return''===url&&g.location.href?g.location.href:url}catch(e){return url}}(request.url),!0),'include'===request.credentials?xhr.withCredentials=!0:'omit'===request.credentials&&(xhr.withCredentials=!1),'responseType'in xhr&&(support.blob?xhr.responseType='blob':support.arrayBuffer&&(xhr.responseType='arraybuffer')),init&&'object'==typeof init.headers&&!(init.headers instanceof Headers||g.Headers&&init.headers instanceof g.Headers)){var names=[];
1Object.getOwnPropertyNames(init.headers).forEach(function(name){names.push(normalizeName(name)),xhr.setRequestHeader(name,normalizeValue(init.headers[name]))}),request.headers.forEach(function(value,name){-1===names.indexOf(name)&&xhr.setRequestHeader(name,value)})}else request.headers.forEach(function(value,name){xhr.setRequestHeader(name,value)});request.signal&&(request.signal.addEventListener('abort',abortXhr),xhr.onreadystatechange=function(){4===xhr.readyState&&request.signal.removeEventListener('abort',abortXhr)}),xhr.send('undefined'==typeof request._bodyInit?null:request._bodyInit)})}var g='undefined'!=typeof globalThis&&globalThis||'undefined'!=typeof self&&self||'undefined'!=typeof global&&global||{},support={searchParams:'URLSearchParams'in g,iterable:'Symbol'in g&&'iterator'in Symbol,blob:'FileReader'in g&&'Blob'in g&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:'FormData'in g,arrayBuffer:'ArrayBuffer'in g};if(support.arrayBuffer)var viewClasses=['[object Int8Array]','[object Uint8Array]','[object Uint8ClampedArray]','[object Int16Array]','[object Uint16Array]','[object Int32Array]','[object Uint32Array]','[object Float32Array]','[object Float64Array]'],isArrayBufferView=ArrayBuffer.isView||function(obj){return obj&&-1<viewClasses.indexOf(Object.prototype.toString.call(obj))};Headers.prototype.append=function(name,value){name=normalizeName(name),value=normalizeValue(value);var oldValue=this.map[name];this.map[name]=oldValue?oldValue+', '+value:value},Headers.prototype['delete']=function(name){delete this.map[normalizeName(name)]},Headers.prototype.get=function(name){return name=normalizeName(name),this.has(name)?this.map[name]:null},Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name))},Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=normalizeValue(value)},Headers.prototype.forEach=function(callback,thisArg){for(var name in this.map)this.map.hasOwnProperty(name)&&callback.call(thisArg,this.map[name],name,this)},Headers.prototype.keys=function(){var items=[];return this.forEach(function(value,name){items.push(name)}),iteratorFor(items)},Headers.prototype.values=function(){var items=[];return this.forEach(function(value){items.push(value)}),iteratorFor(items)},Headers.prototype.entries=function(){var items=[];return this.forEach(function(value,name){items.push([name,value])}),iteratorFor(items)},support.iterable&&(Headers.prototype[Symbol.iterator]=Headers.prototype.entries);var methods=['CONNECT','DELETE','GET','HEAD','OPTIONS','PATCH','POST','PUT','TRACE'];Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var response=new Response(null,{status:200,statusText:''});return response.ok=!1,response.status=0,response.type='error',response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(-1===redirectStatuses.indexOf(status))throw new RangeError('Invalid status code');return new Response(null,{status:status,headers:{location:url}})},exports.DOMException=g.DOMException;try{new exports.DOMException}catch(err){exports.DOMException=function(message,name){this.message=message,this.name=name;var error=Error(message);this.stack=error.stack},exports.DOMException.prototype=Object.create(Error.prototype),exports.DOMException.prototype.constructor=exports.DOMException}fetch.polyfill=!0,g.fetch||(g.fetch=fetch,g.Headers=Headers,g.Request=Request,g.Response=Response),exports.Headers=Headers,exports.Request=Request,exports.Response=Response,exports.fetch=fetch,Object.defineProperty(exports,'__esModule',{value:!0})})}).call(exports,function(){return this}())},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(12),__webpack_require__(6),__webpack_require__(1),__webpack_require__(16),__webpack_require__(2),__webpack_require__(3),__webpack_require__(137),__webpack_require__(114),__webpack_require__(34),__webpack_require__(125),__webpack_require__(122),__webpack_require__(65),__webpack_require__(123),__webpack_require__(124),__webpack_require__(126),__webpack_require__(127)],__WEBPACK_AMD_DEFINE_RESULT__=function(coreModule,array,declare,Deferred,lang,on,UserRegPlayerMediator,GoogleIma,GAEventRequest,SyncBanners,MediaPlayer,NowPlayingApi,Npe,PlayerWebAdmin,TargetSpot,UserRegistration){var moduleManager=declare([coreModule],{constructor:function(){void 0,this.coreModules=[],this.modulesQueue=this.config&&this.config.coreModules?lang.clone(this.config.coreModules):[],this.moduleReadyHandler=on(this.target,'module-ready',lang.hitch(this,this._onModuleComplete)),this.moduleErrorHandler=on(this.target,'module-error',lang.hitch(this,this._onModuleComplete)),this.inherited(arguments),this.analyticsLoadTime=0,this.hasLoadModuleError=!1},loadModules:function(){var self=this;if(0!=this.modulesQueue.length){this.analyticsLoadTimeInterval=setInterval(function(){self.analyticsLoadTime+=10},10);for(var i=0;i<this.config.coreModules.length;i++)this.loadModule(this.config.coreModules[i].id,this._getModuleConfigById(this.config.coreModules[i].id))}}
1,loadModule:function(moduleId,moduleConfig){var moduleInstance=null;switch(moduleId){case'SyncBanners':moduleInstance=SyncBanners;break;case'MediaPlayer':moduleInstance=MediaPlayer;break;case'Npe':moduleInstance=Npe;break;case'NowPlayingApi':moduleInstance=NowPlayingApi;break;case'PlayerWebAdmin':moduleInstance=PlayerWebAdmin;break;case'TargetSpot':moduleInstance=TargetSpot;break;case'UserRegistration':moduleInstance=UserRegistration;default:}moduleInstance&&this._instanciateCurrentModule(moduleInstance,moduleId,moduleConfig)},getModuleById:function(moduleId){var module=null;return array.forEach(this.coreModules,function(item){item.id==moduleId&&(module=item.module)},this),module},_instanciateCurrentModule:function(Module,moduleId,moduleConfig){var module=new Module(moduleConfig,this.target);this.coreModules.push({id:moduleId,module:module}),module.start()},_removeCurrentModuleFromQueue:function(currentModuleId){var spliceStartIndex=-1;array.forEach(this.modulesQueue,function(item,index){item.id==currentModuleId&&(spliceStartIndex=index)},this),-1<spliceStartIndex&&this.modulesQueue.splice(spliceStartIndex,1)},_onModuleComplete:function(e){void 0,this._removeCurrentModuleFromQueue(e.data.id);var self=this,dimensions,metrics;if(0==this.modulesQueue.length){if(this.moduleReadyHandler.remove(),this.moduleErrorHandler.remove(),this.getModuleById('UserRegistration')&&this.getModuleById('MediaPlayer'))new UserRegPlayerMediator(lang.hitch(this,this.getModuleById),this.target);var mediaPlayerModule=this.getModuleById('MediaPlayer'),sendAnalyticsInit=function(label){mediaPlayerModule&&(dimensions={},dimensions[GAEventRequest.DIM_HLS]=!!mediaPlayerModule&&mediaPlayerModule.hls,dimensions[GAEventRequest.DIM_SBM]=!(mediaPlayerModule.config.sbm&&mediaPlayerModule.config.sbm.active)||mediaPlayerModule.config.sbm.active,dimensions[GAEventRequest.DIM_TECH]=mediaPlayerModule.tech.type,dimensions[GAEventRequest.DIM_ADBLOCK]=self.config.adBlockerDetected,dimensions[GAEventRequest.DIM_AUDIO_ADAPTIVE]=mediaPlayerModule.audioAdaptive,dimensions[GAEventRequest.DIM_IDSYNC]=!!mediaPlayerModule.config.idSync,metrics={}
1,metrics[GAEventRequest.METRIC_LOAD_TIME]=self.analyticsLoadTime,GAEventRequest.requestGA(GAEventRequest.CATEGORY_INIT,GAEventRequest.ACTION_CONFIG,label,dimensions,metrics)),clearInterval(self.analyticsLoadTimeInterval)};if(void 0!=mediaPlayerModule&&'Html5'==mediaPlayerModule.tech.type&&!this.config.adBlockerDetected){var imaHelper=new GoogleIma,imaDeferred=imaHelper.init();imaDeferred.then(function(){self.emit('player-ready'),this.hasLoadModuleError?sendAnalyticsInit(GAEventRequest.LABEL_ERROR):sendAnalyticsInit(GAEventRequest.LABEL_SUCCESS)},function(){self.emit('player-ready'),this.hasLoadModuleError?sendAnalyticsInit(GAEventRequest.LABEL_ERROR):sendAnalyticsInit(GAEventRequest.LABEL_SUCCESS)})}else this.emit('player-ready'),mediaPlayerModule&&!this.hasLoadModuleError?sendAnalyticsInit(GAEventRequest.LABEL_SUCCESS):sendAnalyticsInit(GAEventRequest.LABEL_ERROR);this.config.adBlockerDetected&&this.emit('ad-blocker-detected',{message:'Ad Blocker is activated'})}},_getModuleConfigById:function(moduleId){var moduleConfig={};return this.config&&this.config.coreModules&&array.forEach(this.config.coreModules,function(item){item.id==moduleId&&(moduleConfig=item)}
1,this),moduleConfig}});return moduleManager}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on){var AdModuleEvents=declare([],{AD_MODULE_PLAYBACK_START:'ad-module-playback-start',AD_MODULE_PLAYBACK_COMPLETE:'ad-module-playback-complete',AD_MODULE_PLAYBACK_DESTROY:'ad-module-playback-destroy',AD_MODULE_PLAYBACK_ERROR:'ad-module-playback-error',AD_MODULE_COUNTDOWN:'ad-module-countdown',AD_MODULE_MEDIA_READY:'ad-module-media-ready',AD_MODULE_MEDIA_EMPTY:'ad-module-media-empty',AD_MODULE_QUARTILE:'ad-module-quartile',AD_MODULE_COMPANIONS:'ad-module-companions',AD_MODULE_CLICK_TRACKING:'ad-module-click-tracking',AD_MODULE_VAST_ERROR:'ad-module-vast-error',AD_MODULE_VAST_EMPTY:'ad-module-vast-empty',AD_MODULE_VAST_PROCESS_COMPLETE:'ad-module-vast-process-complete',emit:function(eventName,data,targetNode){targetNode&&this.config.playerId!=targetNode.id||(void 0,on.emit(this.target,eventName,{data:data,bubbles:!0,cancelable:!0}))}});return AdModuleEvents}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var adQuartile=declare([],{quartileMap:['start','firstQuartile','midpoint','thirdQuartile','complete'],constructor:function(){},getQuartileByIndex:function(index){return this.quartileMap[index]},isValidType:function(type){for(var j=0;j<this.length();j++)if(this.quartileMap[j]==type)return!0;return!1},length:function(){return this.quartileMap.length}});return adQuartile}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return['970x250','120x60','300x600','728x90','970x100','300x250','88x31','300x1050','970x90','180x150','320x480','300x50','320x50','300x300','970x66','160x600']}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var LocationHelper=__webpack_require__(24),PROTOCOL=LocationHelper.getProtocol(),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var tritonAdPlatformHelper=declare([],{ENDPOINT:PROTOCOL+'//{host}/ondemand/ars?type={type}',getVastUri:function(config){if(void 0==config.host||void 0==config.type||void 0==config.stationName&&void 0==config.stationId)return null;var requestUri=this.ENDPOINT;return requestUri=requestUri.replace('{host}',config.host),requestUri=requestUri.replace('{type}',config.type),void 0!=config.format&&(requestUri=requestUri+'&fmt='+config.format),void 0==config.stationName?void 0!=config.stationId&&(requestUri=requestUri+'&stid='+parseInt(config.stationId)):requestUri=requestUri+'&stn='+config.stationName,void 0!=config.maxAds&&(requestUri=requestUri+'&Max_ads='+parseInt(config.maxAds)),void 0!=config.assetType&&(requestUri=requestUri+'&at='+config.assetType),void 0!=config.minFileSize&&(requestUri=requestUri+'&minsz='+parseInt(config.minFileSize)),void 0!=config.maxFileSize&&(requestUri=requestUri+'&maxsz='+parseInt(config.maxFileSize)),void 0!=config.fileFormat&&(requestUri=requestUri+'&cntnr='+config.fileFormat),void 0!=config.minDuration&&(requestUri=requestUri+'&mindur='+parseInt(config.minDuration)),void 0!=config.maxDuration&&(requestUri=requestUri+'&maxdur='+parseInt(config.maxDuration)),void 0!=config.minBitrate&&(requestUri=requestUri+'&minbr='+parseInt(config.minBitrate)),void 0!=config.maxBitrate&&(requestUri=requestUri+'&maxbr='+parseInt(config.maxBitrate)),void 0!=config.minWidth&&(requestUri=requestUri+'&minw='+parseInt(config.minWidth)),void 0!=config.maxWidth&&(requestUri=requestUri+'&maxw='+parseInt(config.maxWidth)),void 0!=config.minHeight&&(requestUri=requestUri+'&minh='+parseInt(config.minHeight)),void 0!=config.maxHeight&&(requestUri=requestUri+'&maxh='+parseInt(config.maxHeight)),void 0!=config.audioCodec&&(requestUri=requestUri+'&acodec='+config.audioCodec),void 0!=config.audioMinChannels&&(requestUri=requestUri+'&minach='+parseInt(config.audioMinChannels)),void 0!=config.audioMaxChannels&&(requestUri=requestUri+'&maxach='+parseInt(config.audioMaxChannels)),void 0!=config.audioSampleRates&&(requestUri=requestUri+'&asr='+config.audioSampleRates),void 0!=config.videoCodec&&(requestUri=requestUri+'&vcodec='+config.videoCodec),void 0!=config.videoAspectRatio&&(requestUri=requestUri+'&vaspect='+config.videoAspectRatio),void 0!=config.minFrameRate&&(requestUri=requestUri+'&minfps='+parseFloat(config.minFrameRate)),void 0!=config.maxFrameRate&&(requestUri=requestUri+'&maxfps='+parseFloat(config.maxFrameRate)),void 0!=config.excludedCategories&&(requestUri=requestUri+'&iab-categories-to-exclude='+config.excludedCategories),requestUri}});return tritonAdPlatformHelper}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var OsPlatform=__webpack_require__(21),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var debug=!0,FabUtils=function(){var self=this,options={};this.errors={throwError:function(name,method,type){throw'Argument "'+name+'" of method "'+method+'" is not an "'+type+'"'},isObject:function(value,name,method){('object'!=typeof value||!0===Array.isArray(value)||null===value)&&this.throwError(name,method,'object')},isArray:function(value,name,method){!1===Array.isArray(value)&&this.throwError(name,method,'array')},isFunction:function(value,name,method){'function'!=typeof value&&this.throwError(name,method,'function')},isString:function(value,name,method){'string'!=typeof value&&this.throwError(name,method,'string')},isBoolean:function(value,name,method){'boolean'!=typeof value&&this.throwError(name,method,'boolean')}},this.options={set:function(optionsList){for(var key in self.errors.isObject(optionsList,'optionsList','options.set'),optionsList)options[key]=optionsList[key],self.debug.log('options.set','Set "'+key+'" to "'+optionsList[key]+'"');return self},get:function(key){return options[key]}},this.debug={set:function(isEnable){return debug=isEnable,self.debug.log('debug.set','Set debug to "'+debug+'"'),self},isEnable:function(){return debug},log:function(method,message){!0===debug&&(self.errors.isString(method,'method','debug.log'),self.errors.isString(message,'message','debug.log'),void 0)}},this.versionToInt=function(version){for(var versionInt='',i=0,block;3>i;i++)block=version[i]||0,1===(''+block).length&&(block='0'+block),versionInt+=block;return parseInt(versionInt)}},FabPlugin=function(){FabUtils.apply(this);var callbackDetected=null,callbackUndetected=null;this.setDetected=function(callback){return callbackDetected=callback,this},this.callDetected=function(){return null!==callbackDetected&&(callbackDetected(),callbackDetected=null,!0)},this.setUndetected=function(callback){return callbackUndetected=callback,this},this.callUndetected=function(){return null!==callbackUndetected&&(callbackUndetected(),callbackUndetected=null,!0)}}
1,Fab=function(){FabUtils.apply(this),this.options.set({timeout:200});var self=this,version=[4,0,0,'beta',3],events={},pluginsClass={};this.getVersion=function(toInt){return!0===toInt?void this.versionToInt(version):version},this.addEvent=function(name,callback){return this.errors.isString(name,'name','addEvent'),this.errors.isFunction(callback,'callback','addEvent'),void 0===events[name]&&(events[name]=[]),events[name].push(callback),this.debug.log('set','Event "'+name+'" added'),this},this.on=function(detected,callback){return this.errors.isBoolean(detected,'detected','on'),this.errors.isFunction(callback,'callback','on'),this.addEvent(!0===detected?'detected':'undetected',callback)},this.onDetected=function(callback){return this.errors.isFunction(callback,'callback','onDetected'),this.addEvent('detected',callback)},this.onNotDetected=function(callback){return this.errors.isFunction(callback,'callback','onNotDetected'),this.addEvent('undetected',callback)};var dispatchEvent=function(name){var eventsList=events[name];if(!0===self.debug.isEnable()){var eventsNumber=void 0===eventsList?0:eventsList.length;self.debug.log('dispatchEvent','Starts dispatch of events "'+name+'" (0/'+eventsNumber+')')}return void 0!==eventsList&&eventsList.forEach(function(theEvent,i){!0===self.debug.isEnable()&&self.debug.log('dispatchEvent','Dispatch event "'+name+'" ('+(parseInt(i)+1)+'/'+eventsNumber+')'),theEvent()}),this};this.check=function(pluginsList,optionsList){!1==pluginsList instanceof Array&&void 0===optionsList&&(optionsList=pluginsList,pluginsList=void 0),void 0===pluginsList&&(pluginsList=Object.keys(pluginsClass)),void 0===optionsList&&(optionsList={}),this.errors.isArray(pluginsList,'pluginsList','check'),this.errors.isObject(optionsList,'optionsList','check'),this.debug.log('check','Starting check');var plugins={},pluginsLength=pluginsList.length,pluginsEndLength=0,end=function(pluginName,detected,force){if(pluginsEndLength++,self.debug.log('check',(!0===detected?'Positive':'Negative')+'" check of plugin "'+pluginName+'"'),!0===force||!0===detected||pluginsEndLength===pluginsLength){for(var name in clearTimeout(timeout),plugins)plugins[name].instance.stop();dispatchEvent(!0===detected?'detected':'undetected')}};if(this.debug.log('check','Starting loading plugins (0/'+pluginsLength+') ('+pluginsList.join()+')'),0===pluginsLength)return end('#NoPlugin',!1,!0),this;for(var name in pluginsList.forEach(function(name,i){self.debug.log('check','Load plugin "'+name+'" ('+(parseInt(i)+1)+'/'+pluginsLength+')');var plugin=plugins[name]={name:name,instance:new pluginsClass[name],detected:null};void 0!==optionsList[name]&&plugin.instance.options.set(optionsList[name]),function(end,plugin){plugin.instance.setDetected(function(){plugin.detected=!0,end(plugin.name,!0)}).setUndetected(function(){plugin.detected=!1,end(plugin.name,!1)})}(end,plugin)}),plugins)plugins[name].instance.start();var timeout=setTimeout(function(){end('#Timeout',!1,!0)},this.options.get('timeout'));return this},this.registerPlugin=function(pluginClass){if(this.errors.isFunction(pluginClass,'pluginClass','registerPlugin'),this.errors.isString(pluginClass.pluginName,'pluginClass.pluginName','registerPlugin'),this.errors.isArray(pluginClass.versionMin,'pluginClass.versionMin','registerPlugin'),3!==pluginClass.versionMin.length&&this.errors.throwError('pluginClass.versionMin','registerPlugin','array with 3 values'),void 0===pluginsClass[pluginClass.pluginName]){if(this.versionToInt(version)>=this.versionToInt(pluginClass.versionMin))return pluginsClass[pluginClass.pluginName]=pluginClass,this.debug.log('registerPlugin','Plugin "'+pluginClass.pluginName+'" registered'),!0;throw'The plugin "'+pluginClass.pluginName+'" ('+pluginClass.versionMin.join('.')+') is too recent for this version of '+'BlockAdBlock'+' ('+version.join('.')+')'}else throw'The plugin "'+pluginClass.pluginName+'" is already registered';return!1},'iOS'===OsPlatform.os.family?this.registerPlugin(FabPluginHttp):this.registerPlugin(FabPluginHtml)};Fab.getPluginClass=function(){return FabPlugin};var FabPluginHtml=function(){Fab.getPluginClass().apply(this,arguments),this.options.set({loopTime:50,baitElement:null,baitClass:'pub_300x250 pub_300x250m pub_728x90 text-ad textAd text_ad text_ads text-ads text-ad-links adBanner',baitStyle:'width:1px!important;height:1px!important;position:absolute!important;left:-10000px!important;top:-1000px!important;',baitParent:null});var data={};this.start=function(){var self=this;if(null===this.options.get('baitElement')){data.bait=this.createBait({class:this.options.get('baitClass'),style:this.options.get('baitStyle')});var baitParent=this.options.get('baitParent');null===baitParent?window.document.body.appendChild(data.bait):baitParent.appendChild(data.bait)}else data.bait=this.options.get('baitElement');var check=function(){!0===self.checkBait(data.bait,!0)&&self.callDetected()};return data.loopTimeout=setTimeout(check,1),data.loopInterval=setInterval(check,this.options.get('loopTime')),this},this.stop=function(){clearInterval(data.loopTimeout),clearInterval(data.loopInterval);var baitParent=this.options.get('baitParent');return null===baitParent?window.document.body.removeChild(data.bait):baitParent.removeChild(data.bait),this},this.createBait=function(options){var bait=window.document.createElement('div');return bait.setAttribute('class',options.class),bait.setAttribute('style',options.style),bait.offsetParent,bait.offsetHeight,bait.offsetLeft,bait.offsetTop,bait.offsetWidth,bait.clientHeight,bait.clientWidth,bait},this.checkBait=function(bait,checkBody){var detected=!1;if(!0===checkBody&&null!==window.document.body.getAttribute('abp')||null===bait.offsetParent||0==bait.offsetHeight||0==bait.offsetLeft||0==bait.offsetTop||0==bait.offsetWidth||0==bait.clientHeight||0==bait.clientWidth)detected=!0;else{var baitComputedStyle=window.getComputedStyle(bait);('none'==baitComputedStyle.getPropertyValue('display')||'hidden'==bait
1ComputedStyle.getPropertyValue('visibility'))&&(detected=!0)}return detected}};FabPluginHtml.pluginName='html',FabPluginHtml.version=[1,0,0],FabPluginHtml.versionMin=[4,0,0];var FabPluginHttp=function(){Fab.getPluginClass().apply(this,arguments),this.options.set({baitMode:'ajax',baitUrl:'https://sdk.listenlive.co/ad/banner/_adsense_/_adserver/_adview_.ad.json?adzone=top&adsize=300x250&advid={RANDOM}'});var data={};this.start=function(){var self=this;data.end=!1;var baitUrl=this.options.get('baitUrl').replace(/\{RANDOM\}/g,function(){return parseInt(1e8*Math.random())});return this._urlCheck(baitUrl,this.options.get('baitMode'),function(){!1!==data.end||(data.end=!0,self.callDetected())},function(){!1!==data.end||(data.end=!0,self.callUndetected())}),this},this.stop=function(){return data.end=!0,this},this._urlCheck=function(url,mode,cbDetected,cbUndetected){var endSend=!1,end=function(detected){!1!==endSend||(endSend=!0,!0===detected?cbDetected():cbUndetected())};if('ajax'===mode){var readyStates=[!1,!1,!1,!1],status=null,respond=function(responseForce){if(responseForce!==void 0)end(responseForce);else{if(0===status)return void end(!0);for(var i=0;4>i;i++)if(!1===readyStates[i]&&404!=status)return void end(!0);end(!1)}},xmlHttp=new XMLHttpRequest;xmlHttp.onreadystatechange=function(){readyStates[xmlHttp.readyState-1]=!0;try{status=xmlHttp.status}catch(e){}4===xmlHttp.readyState&&respond()};try{xmlHttp.open('GET',url,!0),xmlHttp.send()}catch(e){'2153644038'==e.result&&respond(!0)}}else if('import'===mode){var element=document.createElement('script');element.src=url,element.onerror=function(){end(!0),window.document.body.removeChild(element)},element.onload=function(){end(!1),window.document.body.removeChild(element)},window.document.body.appendChild(element)}else end(!1)}};FabPluginHttp.pluginName='http',FabPluginHtml.version=[1,0,0],FabPluginHttp.versionMin=[4,0,0];var blockadblock=declare([],{constructor:function(){this.fab=new Fab}});return blockadblock}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;(function(swfobject){__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(3),__webpack_require__(13),__webpack_require__(6),__webpack_require__(8),__webpack_require__(11),__webpack_require__(39),__webpack_require__(9)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,on,Evented,array,dom,domConstruct){var fetch=__webpack_require__(106),companions=window.TdCompanions=declare([Evented],{JS_BANNER_URL:'https://player.tritondigital.com/tpl/default/jsbanner.php',constructor:function(){void 0,this.listeners=[]},loadCompanionIframe:function(containerId,adSpotUrl,width,height){var container=dom.byId(containerId,document);domConstruct.empty(container),domConstruct.create('iframe',{src:adSpotUrl,width:width,height:height,scrolling:'no',frameborder:0,marginheight:0,marginwidth:0,allowtransparency:!0,style:{margin:0,padding:0}},container)},loadCompanionStatic:function(containerId,adSpotUrl,width,height,clickThroughURL,altText,adSpotType){altText=altText||'',adSpotType=adSpotType||'';var container=dom.byId(containerId,document);domConstruct.empty(container);var extFile=adSpotUrl.substring(adSpotUrl.lastIndexOf('.')+1).toLowerCase();if('application/x-shockwave-flash'==adSpotType||'swf'==extFile){if(0<!swfobject.getFlashPlayerVersion().major)return void this.emit('companion-load-error',{containerId:containerId,adSpotUrl:adSpotUrl});adSpotUrl=adSpotUrl+(-1<adSpotUrl.indexOf('?')?'&':'?')+'cb_'+new Date().getTime(),void 0;var flashArgs={expressInstall:!0,path:adSpotUrl,width:width,height:height,allowScriptAccess:'always',allowfullscreen:!0,allowNetworking:'all',minimumVersion:'10.2.0',vars:{clickTAG:encodeURIComponent(clickThroughURL)},params:{scale:'showall',wmode:'opaque',allowScriptAccess:'always',allowNetworking:'all'}},flashContentId='td_flash_companions';domConstruct.create('div',{id:flashContentId},container),swfobject.embedSWF(adSpotUrl,flashContentId,width,height,'10.2.0',!1,{clickTAG:encodeURIComponent(clickThroughURL)},{scale:'showall',wmode:'opaque',allowScriptAccess:'always',allowNetworking:'all'},!1,!1)}else{var imgHtml='';clickThroughURL!=void 0&&(imgHtml='<a href="'+clickThroughURL+'" target="_blank">'),imgHtml+='<img src="'+adSpotUrl+'" width="'+width+'" height="'+height+'" title="'+altText+'" border="0"/>',clickThroughURL!=void 0&&(imgHtml+='</a>'),container.innerHTML=imgHtml}},loadVASTCompanionAd:function(containerId,vastCompanionAd){if(vastCompanionAd.content)return void(dom.byId(containerId,document).innerHTML=vastCompanionAd.content);switch(vastCompanionAd.resourceType.name){case'html':-1<vastCompanionAd.code.indexOf('<script>')&&-1<vastCompanionAd.code.indexOf('document.write')?dom.byId(containerId,document).innerHTML=vastCompanionAd.code:-1<vastCompanionAd.code.indexOf('document.write')?(vastCompanionAd.resourceType.name='iframe',vastCompanionAd.url=this.JS_BANNER_URL+'?code='+encodeURIComponent(vastCompanionAd.code),this.loadVASTCompanionAd(containerId,vastCompanionAd)):dom.byId(containerId,document).innerHTML=vastCompanionAd.code;break;case'iframe':this.loadCompanionIframe(containerId,vastCompanionAd.url,vastCompanionAd.width,vastCompanionAd.height);break;case'static':'text/javascript'==vastCompanionAd.creativeType?(vastCompanionAd.resourceType.name='iframe',vastCompanionAd.url=this.JS_BANNER_URL+'?url='+encodeURIComponent(vastCompanionAd.url),this.loadVASTCompanionAd(containerId,vastCompanionAd)):this.loadCompanionStatic(containerId,vastCompanionAd.url,vastCompanionAd.width,vastCompanionAd.height,vastCompanionAd.clickThroughURL,vastCompanionAd.altText,vastCompanionAd.creativeType);break;default:}vastCompanionAd.creativeView&&vastCompanionAd.creativeView.length&&vastCompanionAd.creativeView.forEac
1h(function(url){window.fetch(url,{mode:'no-cors'})})},addEventListener:function(eventName,callback){var itemIndex=-1;array.forEach(this.listeners,function(item,index){item.eventName==eventName&&item.callback==callback&&(itemIndex=index)},this),-1==itemIndex&&this.listeners.push({eventName:eventName,callback:callback,listener:on(this,eventName,lang.hitch(this,callback))})},removeEventListener:function(eventName,callback){var itemIndex=-1;array.forEach(this.listeners,function(item,index){item.eventName==eventName&&item.callback==callback&&(itemIndex=index)},this),-1<itemIndex&&(this.listeners[itemIndex].listener.remove(),this.listeners.splice(itemIndex,1))}});return companions}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}).call(exports,__webpack_require__(62))},function(module,exports,__webpack_require__){var $script=__webpack_require__(103),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__,__webpack_require__(16)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,require,Deferred){var googleIma=declare([],{constructor:function(){},init:function(){var def=new Deferred;return $script('//imasdk.googleapis.com/js/sdkloader/ima3.js',function(){def.resolve()}),def}});return googleIma}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){module.exports=new function(doc){function createNode(name,attrs){var node=doc.createElement(name),attr;for(attr in attrs)attrs.hasOwnProperty(attr)&&node.setAttribute(attr,attrs[attr]);return node}function finish(type){var p=pending[type],callback,urls;p&&(callback=p.callback,urls=p.urls,urls.shift(),pollCount=0,!urls.length&&(callback&&callback.call(p.context,p.obj),pending[type]=null,queue[type].length&&load(type)))}function getEnv(){var ua=navigator.userAgent;env={async:!0===doc.createElement('script').async},(env.webkit=/AppleWebKit\//.test(ua))||(env.ie=/MSIE|Trident/.test(ua))||(env.opera=/Opera/.test(ua))||(env.gecko=/Gecko\//.test(ua))||(env.unknown=!0)}function load(type,urls,callback,obj,context){var _finish=function(){finish(type)},isCSS='css'===type,nodes=[],i,len,node,p,pendingUrls,url;if(env||getEnv(),urls)if(urls='string'==typeof urls?[urls]:urls.concat(),isCSS||env.async||env.gecko||env.opera)queue[type].push({urls:urls,callback:callback,obj:obj,context:context});else for(i=0,len=urls.length;i<len;++i)queue[type].push({urls:[urls[i]],callback:i===len-1?callback:null,obj:obj,context:context});if(!pending[type]&&(p=pending[type]=queue[type].shift())){for(head||(head=doc.head||doc.getElementsByTagName('head')[0]),pendingUrls=p.urls.concat(),(i=0,len=pendingUrls.length);i<len;++i)url=pendingUrls[i],isCSS?node=env.gecko?createNode('style'):createNode('link',{href:url,rel:'stylesheet'}):(node=createNode('script',{src:url}),node.async=!1),node.className='lazyload',node.setAttribute('charset','utf-8'),env.ie&&!isCSS&&'onreadystatechange'in node&&!('draggable'in node)?node.onreadystatechange=function(){/loaded|complete/.test(node.readyState)&&(node.onreadystatechange=null,_finish())}:isCSS&&(env.gecko||env.webkit)?env.webkit?(p.urls[i]=node.href,pollWebKit()):(node.innerHTML='@import "'+url+'";',pollGecko(node)):node.onload=node.onerror=_finish,nodes.push(node);for(i=0,len=nodes.length;i<len;++i)head.appendChild(nodes[i])}}function pollGecko(node){var hasRules;try{hasRules=!!node.sheet.cssRules}catch(ex){return pollCount+=1,void(200>pollCount?setTimeout(function(){pollGecko(node)},50):hasRules&&finish('css'))}finish('css')}function pollWebKit(){var css=pending.css,i;if(css){for(i=styleSheets.length;0<=--i;)if(styleSheets[i].href===css.urls[0]){finish('css');break}pollCount+=1,css&&(200>pollCount?setTimeout(pollWebKit,50):finish('css'))}}var pending={},pollCount=0,queue={css:[],js:[]},styleSheets=doc.styleSheets,env,head;return{css:function(urls,callback,obj,context){load('css',urls,callback,obj,context)},js:function(urls,callback,obj,context){load('js',urls,callback,obj,context)}}}(window.document)},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_RESULT__;(function(module){var xmlToJSON=function(){this.version='1.3';var options={mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!0,namespaceKey:'_ns',textKey:'_text',valueKey:'_value',attrKey:'_attr',cdataKey:'_cdata',attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!0},prefixMatch=new RegExp(/(?!xmlns)^.*:/),trimMatch=new RegExp(/^\s+|\s+$/g);return this.grokType=function(sValue){return /^\s*$/.test(sValue)?null:/^(?:true|false)$/i.test(sValue)?'true'===sValue.toLowerCase():isFinite(sValue)?parseFloat(sValue):sValue},this.parseString=function(xmlString,opt){return this.parseXML(this.stringToXML(xmlString),opt)},this.parseXML=function(oXMLParent,opt){for(var key in opt)options[key]=opt[key];var vResult={},nLength=0,sCollectedTxt='';if(options.xmlns&&oXMLParent.namespaceURI&&(vResult[options.namespaceKey]=oXMLParent.namespaceURI),oXMLParent.attributes&&0<oXMLParent.attributes.length){var vAttribs={};for(nLength;nLength<oXMLParent.attributes.length;nLength++){var oAttrib=oXMLParent.attributes.item(nLength);vContent={};var attribName='';attribName=options.stripAttrPrefix?oAttrib.name.replace(prefixMatch,''):oAttrib.name,vContent[options.valueKey]=options.grokAttr?this.grokType(oAttrib.value.replace(trimMatch,'')):oAttrib.value.replace(trimMatch,''),options.xmlns&&oAttrib.namespaceURI&&(vContent[options.namespaceKey]=oAttrib.namespaceURI),options.attrsAsObject?vAttribs[attribName]=vContent:vResult[options.attrKey+attribName]=vContent}options.attrsAsObject&&(vResult[options.attrKey]=vAttribs)}if(oXMLParent.hasChildNodes())for(var nItem=0,oNode,sProp,vContent;nItem<oXMLParent.childNodes.length;nItem++)oNode=oXMLParent.childNodes.item(nItem),4===oNode.nodeType?options.mergeCDATA?sCollectedTxt+=oNode.nodeValue:vResult.hasOwnProperty(options.cdataKey)?(vResult[options.cdataKey].constructor!==Array&&(vResult[options.cdataKey]=[vResult[options.cdataKey]]),vResult[options.cdataKey].push(oNode.nodeValue)):options.childrenAsArray?(vResult[options.cdataKey]=[],vResult[options.cdataKey].push(oNode.nodeValue)):vResult[options.cdataKey]=oNode.nodeValue:3===oNode.nodeType?sCollectedTxt+=oNode.nodeValue:1===oNode.nodeType&&(0==nLength&&(vResult={}),sProp=options.stripElemPrefix?oNode.nodeName.replace(prefixMatch,''):oNode.nodeName,vContent=xmlToJSON.parseXML(oNode),vResult.hasOwnProperty(sProp)?(vResult[sProp].constructor!==Array&&(vResult[sProp]=[vResult[sProp]]),vResult[sProp].push(vContent)):(options.childrenAsArray?(vResult[sProp]=[],vResult[sProp].push(vContent)):vResult[sProp]=vContent,nLength++));else sCollectedTxt||(options.childrenAsArray?(vResult[options.textKey]=[],vResult[options.textKey].push(null)):vResult[options.textKey]=null);if(sCollectedTxt)if(options.grokText){var value=this.grokType(sCollectedTxt.replace(trimMatch,''));null!==value&&void 0!==value&&(vResult[options.textKey]=value)}else vResult[options.textKey]=options.normalize?sCollectedTxt.replace(trimMatch,'').replace(/\s+/g,' '):sCollectedTxt.replace(trimMatch,'');return vResult},this.xmlToString=function(xmlDoc){try{var xmlString=xmlDoc.xml?xmlDoc.xml:new XMLSerializer().serializeToString(xmlDoc);return xmlString}catch(err){return null}},this.stringToXML=function(xmlString){try{var xmlDoc=null;if(window.DOMParser){var parser=new DOMParser;
1return xmlDoc=parser.parseFromString(xmlString,'text/xml'),xmlDoc}return xmlDoc=new ActiveXObject('Microsoft.XMLDOM'),xmlDoc.async=!1,xmlDoc.loadXML(xmlString),xmlDoc}catch(e){return null}},this}.call({});'undefined'!=typeof module&&null!==module&&module.exports?module.exports=xmlToJSON:(__WEBPACK_AMD_DEFINE_RESULT__=function(){return xmlToJSON}.call(exports,__webpack_require__,exports,module),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__)))}).call(exports,__webpack_require__(31)(module))},function(module,exports,__webpack_require__){var Platform=__webpack_require__(14),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(84),__webpack_require__(9)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,cookie){function _setCookie(cookieName){var cid=_generateCid(),d=new Date;d.setTime(d.getTime()+1e3*(60*(60*(24*365))));var expires='expires='+d.toUTCString();return cookie(cookieName,cid,{expires:expires,path:'/'}),cid}function _generateCid(){var d=new Date().getTime(),cid='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){var r=0|(d+16*Math.random())%16;return d=Math.floor(d/16),('x'==c?r:8|7&r).toString(16)});return cid}var GARequest=declare([],{GA_ENDPOINT:'https://www.googletagmanager.com/gtag/js?id=',GA_ENDPOINT_DEBUG:'https://www.googletagmanager.com/gtag/js?id=',COOKIE_NAME:'sdk_cid',TYPE:'hitType',CATEGORY:'eventCategory',ACTION:'eventAction',LABEL:'eventLabel',DIM_TECH:'cd1',DIM_MEDIA_TYPE:'cd2',DIM_MOUNT:'cd3',DIM_STATION:'cd4',DIM_BROADCASTER:'cd5',DIM_MEDIA_FORMAT:'cd6',DIM_AD_SOURCE:'cd8',DIM_AD_FORMAT:'cd9',DIM_AD_PARSER:'cd10',DIM_ADBLOCK:'cd11',DIM_SBM:'cd12',DIM_HLS:'cd13',DIM_AUDIO_ADAPTIVE:'cd14',DIM_IDSYNC:'cd15',DIM_ALTERNATE_CONTENT:'cd16',DIM_AD_COMPANIONS_TYPE:'cd17',DIM_ERROR_MESSAGE:'cd18',METRIC_CONNECTION_TIME:'cm1',METRIC_STREAM_ERROR_TIME:'cm2',METRIC_LOAD_TIME:'cm3',active:!0,constructor:function(){void 0,this.tid=null,this.v=1,this.cid=null,this.an='web-sdk',this.av=null,this.aid=null,this.appInstallerId='custom',this.active=!0,this.debug=!1,this.category=null,this.sampleRate=5},setProperties:function(active=!0,appInstallerId='',debug=!1,platformId='prod01',trackingId=null,sampleRate=5,trackingEvents=[this.ACTION_PLAY,this.ACTION_STOP,this.ACTION_PAUSE,this.ACTION_RESUME],category=null){this.setActive(active),this.appInstallerId=appInstallerId,this.debug=debug,this.setPlatform(platformId,trackingId),this.sampleRate=sampleRate,this.category=category,this.trackingEvents=trackingEvents.map(item=>item.toUpperCase()),this.trackingEvents.includes(this.ACTION_ALL.toUpperCase())&&(this.trackingEvents=[this.ACTION_PLAY.toUpperCase(),this.ACTION_STOP.toUpperCase(),this.ACTION_PAUSE.toUpperCase(),this.ACTION_RESUME.toUpperCase()])},isGoogleAnalytics4:function(){var trackingType=this.tid.split('-')[0];return'G'===trackingType},loadGoogleAnalytics:function(){this.isGoogleAnalytics4()?this.loadGoogleAnalytics4():this.loadLegacyGoogleAnalytics()},loadGoogleAnalytics4:function(){function gtag(){dataLayer.push(arguments)}var trackingId=this.tid,win=window,doc=document,script='script',googleTag='gtag',scriptTag,scriptTagElement;win.dataLayer=window.dataLayer||[],win[googleTag]=win[googleTag]||gtag,scriptTag=doc.createElement(script),scriptTag.async=1,scriptTag.src='https://www.googletagmanager.com/gtag/js?id='+trackingId,scriptTagElement=doc.getElementsByTagName(script)[0],scriptTagElement.parentNode.insertBefore(scriptTag,scriptTagElement),gtag('js',new Date),gtag('config',trackingId,{cookieDomain:'auto',sampleRate:this.sampleRate,trackingId:trackingId,appId:this.aid,appInstallerId:this.appInstallerId,appName:this.an,appVersion:this.av,clientId:this.cid,name:'tritonWebSdkTracker'})},loadLegacyGoogleAnalytics:function(){var i=window,d=document,o='script',g=this.debug?'https://www.google-analytics.com/analytics_debug.js':'https://www.google-analytics.com/analytics.js',r='ga',s,m;i.GoogleAnalyticsObject=r,i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date,s=d.createElement(o),m=d.getElementsByTagName(o)[0],s.async=1,s.src=g,m.parentNode.insertBefore(s,m),ga('create',{cookieDomain:'auto',sampleRate:this.sampleRate,trackingId:this.tid,appId:this.aid,appInstallerId:this.appInstallerId,appName:this.an,appVersion:this.av,clientId:this.cid,name:'tritonWeb
1SdkTracker'}),ga('tritonWebSdkTracker.send','pageview')},setActive:function(active){this.active=active,active?this.cid=this.getCookie():this.delete_cookie()},setPlatform:function(platformId,trackingId){this.platform='localhost'===window.location.hostname||-1<window.location.hostname.search('10.100')?new Platform('dev01'):new Platform(platformId),this.tid=trackingId?trackingId:this.platform.endpoint.UA},request:function(object){void 0,this.category&&(object.eventCategory=this.category),this.isGoogleAnalytics4()?gtag('event','tritonWebSdkTracker.send',object):ga('tritonWebSdkTracker.send',object)},delete_cookie:function(){cookie(this.COOKIE_NAME,'',{expires:'Thu, 01 Jan 1970 00:00:01 GMT',path:'/'})},getCookie:function(){for(var cname=this.COOKIE_NAME,name=cname+'=',ca=document.cookie.split(';'),i=0,c;i<ca.length;i++){for(c=ca[i];' '==c.charAt(0);)c=c.substring(1);if(0==c.indexOf(name))return c.substring(name.length,c.length)}return _setCookie(this.COOKIE_NAME)}});return GARequest}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){function webpackContext(req){return __webpack_require__(webpackContextResolve(req))}function webpackContextResolve(req){return map[req]||function(){throw new Error('Cannot find module \''+req+'\'.')}()}var map={'./en.json':60,'./es.json':99,'./fr.json':100,'./pt.json':101};webpackContext.keys=function(){return Object.keys(map)},webpackContext.resolve=webpackContextResolve,module.exports=webpackContext,webpackContext.id=118},function(module,exports){var require,require;(function(global){(function(f){module.exports=f()})(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a='function'==typeof require&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error('Cannot find module \''+o+'\'');throw f.code='MODULE_NOT_FOUND',f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i='function'==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module,exports){(function(process,global){(function(global,factory){'object'==typeof exports&&'undefined'!=typeof module?module.exports=factory():'function'==typeof define&&define.amd?define(factory):global.ES6Promise=factory()})(this,function(){'use strict';function objectOrFunction(x){var type=typeof x;return null!==x&&('object'==type||'function'==type)}function isFunction(x){return'function'==typeof x}function useVertxTimer(){return'undefined'==typeof vertxNext?useSetTimeout():function(){vertxNext(flush)}}function useSetTimeout(){var globalSetTimeout=setTimeout;return function(){return globalSetTimeout(flush,1)}}function flush(){for(var i=0;i<len;i+=2){var callback=queue[i],arg=queue[i+1];callback(arg),queue[i]=void 0,queue[i+1]=void 0}len=0}function then(onFulfillment,onRejection){var parent=this,child=new this.constructor(noop);void 0===child[PROMISE_ID]&&makePromise(child);var _state=parent._state;if(_state){var callback=arguments[_state-1];asap(function(){return invokeCallback(_state,child,callback,parent._result)})}else subscribe(parent,child,onFulfillment,onRejection);return child}function resolve$1(object){var Constructor=this;if(object&&'object'==typeof object&&object.constructor===Constructor)return object;var promise=new Constructor(noop);return resolve(promise,object),promise}function noop(){}function selfFulfillment(){return new TypeError('You cannot resolve a promise with itself')}function cannotReturnOwn(){return new TypeError('A promises callback cannot return that same promise.')}function tryThen(then$$1,value,fulfillmentHandler,rejectionHandler){try{then$$1.call(value,fulfillmentHandler,rejectionHandler)}catch(e){return e}}function handleForeignThenable(promise,thenable,then$$1){asap(function(promise){var sealed=!1,error=tryThen(then$$1,thenable,function(value){sealed||(sealed=!0,thenable===value?fulfill(promise,value):resolve(promise,value))},function(reason){sealed||(sealed=!0,reject(promise,reason))},'Settle: '+(promise._label||' unknown promise'));!sealed&&error&&(sealed=!0,reject(promise,error))},promise)}function handleOwnThenable(promise,thenable){thenable._state===FULFILLED?fulfill(promise,thenable._result):thenable._state===REJECTED?reject(promise,thenable._result):subscribe(thenable,void 0,function(value){return resolve(promise,value)},function(reason){return reject(promise,reason)})}function handleMaybeThenable(promise,maybeThenable,then$$1){maybeThenable.constructor===promise.constructor&&then$$1===then&&maybeThenable.constructor.resolve===resolve$1?handleOwnThenable(promise,maybeThenable):void 0===then$$1?fulfill(promise,maybeThenable):isFunction(then$$1)?handleForeignThenable(promise,maybeThenable,then$$1):fulfill(promise,maybeThenable)}function resolve(promise,value){if(promise===value)reject(promise,selfFulfillment());else if(objectOrFunction(value)){var then$$1;try{then$$1=value.then}catch(error){return void reject(promise,error)}handleMaybeThenable(promise,value,then$$1)}else fulfill(promise,value)}function publishRejection(promise){promise._onerror&&promise._onerror
vendor: 2,127 bytes, line 1
1(promise._result),publish(promise)}function fulfill(promise,value){promise._state!==PENDING||(promise._result=value,promise._state=FULFILLED,0!==promise._subscribers.length&&asap(publish,promise))}function reject(promise,reason){promise._state!==PENDING||(promise._state=REJECTED,promise._result=reason,asap(publishRejection,promise))}function subscribe(parent,child,onFulfillment,onRejection){var _subscribers=parent._subscribers,length=_subscribers.length;parent._onerror=null,_subscribers[length]=child,_subscribers[length+FULFILLED]=onFulfillment,_subscribers[length+REJECTED]=onRejection,0===length&&parent._state&&asap(publish,parent)}function publish(promise){var subscribers=promise._subscribers,settled=promise._state;if(0!==subscribers.length){for(var child=void 0,callback=void 0,detail=promise._result,i=0;i<subscribers.length;i+=3)child=subscribers[i],callback=subscribers[i+settled],child?invokeCallback(settled,child,callback,detail):callback(detail);promise._subscribers.length=0}}function invokeCallback(settled,promise,callback,detail){var hasCallback=isFunction(callback),succeeded=!0,value,error;if(hasCallback){try{value=callback(detail)}catch(e){succeeded=!1,error=e}if(promise===value)return void reject(promise,cannotReturnOwn())}else value=detail;promise._state!==PENDING||(hasCallback&&succeeded?resolve(promise,value):!1==succeeded?reject(promise,error):settled===FULFILLED?fulfill(promise,value):settled===REJECTED&&reject(promise,value))}function initializePromise(promise,resolver){try{resolver(function(value){resolve(promise,value)},function(reason){reject(promise,reason)})}catch(e){reject(promise,e)}}function nextId(){return id++}function makePromise(promise){promise[PROMISE_ID]=id++,promise._state=void 0,promise._result=void 0,promise._subscribers=[]}function validationError(){return new Error('Array Methods must be provided an Array')}function needsResolver(){throw new TypeError('You must pass a resolver function as the first argument to the promise constructor')}function needsNew(){throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object c
1onstructor cannot be called as a function.')}var _isArray=Array.isArray?Array.isArray:function(x){return'[object Array]'===Object.prototype.toString.call(x)};var isArray=_isArray,len=0,vertxNext=void 0,customSchedulerFn=void 0,asap=function(callback,arg){queue[len]=callback,queue[len+1]=arg,len+=2,2==len&&(customSchedulerFn?customSchedulerFn(flush):scheduleFlush())},browserWindow='undefined'==typeof window?void 0:window,browserGlobal=browserWindow||{},BrowserMutationObserver=browserGlobal.MutationObserver||browserGlobal.WebKitMutationObserver,isNode='undefined'==typeof self&&'undefined'!=typeof process&&'[object process]'==={}.toString.call(process),isWorker='undefined'!=typeof Uint8ClampedArray&&'undefined'!=typeof importScripts&&'undefined'!=typeof MessageChannel,queue=Array(1e3),scheduleFlush=void 0;scheduleFlush=isNode?function(){return function(){return process.nextTick(flush)}}():BrowserMutationObserver?function(){var iterations=0,observer=new BrowserMutationObserver(flush),node=document.createTextNode('');return observer.observe(node,{characterData:!0}),function(){node.data=iterations=++iterations%2}}():isWorker?function(){var channel=new MessageChannel;return channel.port1.onmessage=flush,function(){return channel.port2.postMessage(0)}}():void 0===browserWindow&&'function'==typeof _dereq_?function(){try{var vertx=Function('return this')().require('vertx');return vertxNext=vertx.runOnLoop||vertx.runOnContext,useVertxTimer()}catch(e){return useSetTimeout()}}():useSetTimeout();var PROMISE_ID=Math.random().toString(36).substring(2),PENDING=void 0,FULFILLED=1,REJECTED=2,id=0,Enumerator=function(){function Enumerator(Constructor,input){this._instanceConstructor=Constructor,this.promise=new Constructor(noop),this.promise[PROMISE_ID]||makePromise(this.promise),isArray(input)?(this.length=input.length,this._remaining=input.length,this._result=Array(this.length),0===this.length?fulfill(this.promise,this._result):(this.length=this.length||0,this._enumerate(input),0===this._remaining&&fulfill(this.promise,this._result))):reject(this.promise,validationError())}return Enumerator.prototype._enumerate=function(input){for(var i=0;this._state===PENDING&&i<input.length;i++)this._eachEntry(input[i],i)},Enumerator.prototype._eachEntry=function(entry,i){var c=this._instanceConstructor,resolve$$1=c.resolve;if(resolve$$1===resolve$1){var _then=void 0,error=void 0,didError=!1;try{_then=entry.then}catch(e){didError=!0,error=e}if(_then===then&&entry._state!==PENDING)this._settledAt(entry._state,i,entry._result);else if('function'!=typeof _then)this._remaining--,this._result[i]=entry;else if(c===Promise$1){var promise=new c(noop);didError?reject(promise,error):handleMaybeThenable(promise,entry,_then),this._willSettleAt(promise,i)}else this._willSettleAt(new c(function(resolve$$1){return resolve$$1(entry)}),i)}else this._willSettleAt(resolve$$1(entry),i)},Enumerator.prototype._settledAt=function(state,i,value){var promise=this.promise;promise._state===PENDING&&(this._remaining--,state===REJECTED?reject(promise,value):this._result[i]=value),0===this._remaining&&fulfill(promise,this._result)},Enumerator.prototype._willSettleAt=function(promise,i){var enumerator=this;subscribe(promise,void 0,function(value){return enumerator._settledAt(FULFILLED,i,value)},function(reason){return enumerator._settledAt(REJECTED,i,reason)})},Enumerator}(),Promise$1=function(){function Promise(resolver){this[PROMISE_ID]=nextId(),this._result=this._state=void 0,this._subscribers=[],noop!==resolver&&('function'!=typeof resolver&&needsResolver(),this instanceof Promise?initializePromise(this,resolver):needsNew())}return Promise.prototype.catch=function(onRejection){return this.then(null,onRejection)},Promise.prototype.finally=function(callback){var promise=this,constructor=promise.constructor;return isFunction(callback)?promise.then(function(value){return constructor.resolve(callback()).then(function(){return value})},function(reason){return constructor.resolve(callback()).then(function(){throw reason})}):promise.then(callback,callback)},Promise}();return Promise$1.prototype.then=then,Promise$1.all=function(entries){return new Enumerator(this,entries).promise},Promise$1.race=function(entries){var Constructor=this;return isArray(entries)?new Constructor(function(resolve,reject){for(var length=entries.length,i=0;i<length;i++)Constructor.resolve(entries[i]).then(resolve,reject)}):new Constructor(function(_,reject){return reject(new TypeError('You must pass an array to race.'))})},Promise$1.resolve=resolve$1,Promise$1.reject=function(reason){var Constructor=this,promise=new Constructor(noop);return reject(promise,reason),promise}
vendor: 6,208 bytes, line 1
1,Promise$1._setScheduler=function(scheduleFn){customSchedulerFn=scheduleFn},Promise$1._setAsap=function(asapFn){asap=asapFn},Promise$1._asap=asap,Promise$1.polyfill=function(){var local;if('undefined'!=typeof global)local=global;else if('undefined'!=typeof self)local=self;else try{local=Function('return this')()}catch(e){throw new Error('polyfill failed because global object is unavailable in this environment')}var P=local.Promise;if(P){var promiseToString=null;try{promiseToString=Object.prototype.toString.call(P.resolve())}catch(e){}if('[object Promise]'===promiseToString&&!P.cast)return}local.Promise=Promise$1},Promise$1.Promise=Promise$1,Promise$1})}).call(this,_dereq_('_process'),'undefined'==typeof global?'undefined'==typeof self?'undefined'==typeof window?{}:window:self:global)},{_process:3}],2:[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return'function'==typeof arg}function isNumber(arg){return'number'==typeof arg}function isObject(arg){return'object'==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError('n must be a positive number');return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),'error'===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))if(er=arguments[1],er instanceof Error)throw er;else{var err=new Error('Uncaught, unspecified "error" event. ('+er+')');throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args);}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i<len;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError('listener must be a function');return this._events||(this._events={}),this._events.newListener&&this.emit('newListener',type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&0<m&&this._events[type].length>m&&(this._events[type].warned=!0,void 0)),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError('listener must be a function');var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit('removeListener',type,listener);else if(isObject(list)){for(i=length;0<i--;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit('removeListener',type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)'removeListener'!==key&&this.removeAllListeners(key);return this.removeAllListeners('removeListener'),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[],ret},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],3:[function(_dereq_,module){function defaultSetTimout(){throw new Error('setTimeout has not been defined')}function defaultClearTimeout(){throw new Error('clearTimeout has not been defined')}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,
1currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}var process=module.exports={},cachedSetTimeout,cachedClearTimeout;(function(){try{cachedSetTimeout='function'==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout='function'==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}})();var queue=[],draining=!1,queueIndex=-1,currentQueue;process.nextTick=function(fun){var args=Array(arguments.length-1);if(1<arguments.length)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title='browser',process.browser=!0,process.env={},process.argv=[],process.version='',process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(){return[]},process.binding=function(){throw new Error('process.binding is not supported')},process.cwd=function(){return'/'},process.chdir=function(){throw new Error('process.chdir is not supported')},process.umask=function(){return 0}},{}],4:[function(_dereq_,module){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){function resolveSources(key){for(var depPath in workerSources[key]=!0,sources[key][1]){var depKey=sources[key][1][depPath];workerSources[depKey]||resolveSources(depKey)}}for(var cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length,wkey;i<l;i++){var key=cacheKeys[i],exp=cache[key].exports;if(exp===fn||exp&&exp.default===fn){wkey=key;break}}if(!wkey){wkey=Math.floor(Math.pow(16,8)*Math.random()).toString(16);for(var wcache={},i=0,l=cacheKeys.length,key;i<l;i++)key=cacheKeys[i],wcache[key]=key;sources[wkey]=['function(require,module,exports){'+fn+'(self); }',wcache]}var skey=Math.floor(Math.pow(16,8)*Math.random()).toString(16),scache={};scache[wkey]=wkey,sources[skey]=['function(require,module,exports){var f = require('+stringify(wkey)+');(f.default ? f.default : f)(self);}',scache];var workerSources={};resolveSources(skey);var src='('+bundleFn+')({'+Object.keys(workerSources).map(function(key){return stringify(key)+':['+sources[key][0]+','+stringify(sources[key][1])+']'}).join(',')+'},{},['+stringify(skey)+'])',URL=window.URL||window.webkitURL||window.mozURL||window.msURL,blob=new Blob([src],{type:'text/javascript'});if(options&&options.bare)return blob;var workerUrl=URL.createObjectURL(blob),worker=new Worker(workerUrl);return worker.objectURL=workerUrl,worker}},{}],5:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.createDefaultConfig=function(){return Object.assign({},defaultConfig)};var defaultConfig=exports.defaultConfig={enableWorker:!1,enableStashBuffer:!0,stashInitialSize:void 0,isLive:!1,lazyLoad:!0,lazyLoadMaxDuration:180,lazyLoadRecoverDuration:30,deferLoadAfterSourceOpen:!0,autoCleanupMaxBackwardDuration:180,autoCleanupMinBackwardDuration:120,statisticsInfoReportInterval:600,fixAudioTimestampGap:!0,accurateSeek:!1,seekType:'range',seekParamStart:'bstart',seekParamEnd:'bend',rangeLoadZeroStart:!1,customSeekHandler:void 0,reuseRedirectedURL:!1,headers:void 0,customLoader:void 0}},{}],6:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_ioController=_dereq_('../io/io-controller.js'),_ioController2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_ioController),_config=_dereq_('../config.js'),Features=function(){function Features(){_classCallCheck(this,Features)}return _createClass(Features,null,[{key:'supportMSEH264Playback',value:function(){return window.MediaSource&&window.MediaSource.isTypeSupp
vendor: 5,724 bytes, line 1
1orted('video/mp4; codecs="avc1.42E01E,mp4a.40.2"')}},{key:'supportNetworkStreamIO',value:function(){var ioctl=new _ioController2.default({},(0,_config.createDefaultConfig)()),loaderType=ioctl.loaderType;return ioctl.destroy(),'fetch-stream-loader'==loaderType||'xhr-moz-chunked-loader'==loaderType}},{key:'getNetworkLoaderTypeName',value:function(){var ioctl=new _ioController2.default({},(0,_config.createDefaultConfig)()),loaderType=ioctl.loaderType;return ioctl.destroy(),loaderType}},{key:'supportNativeMediaPlayback',value:function(mimeType){void 0==Features.videoElement&&(Features.videoElement=window.document.createElement('video'));var canPlay=Features.videoElement.canPlayType(mimeType);return'probably'===canPlay||'maybe'==canPlay}},{key:'getFeatureList',value:function(){var features={mseFlvPlayback:!1,mseLiveFlvPlayback:!1,networkStreamIO:!1,networkLoaderName:'',nativeMP4H264Playback:!1,nativeWebmVP8Playback:!1,nativeWebmVP9Playback:!1};return features.mseFlvPlayback=Features.supportMSEH264Playback(),features.networkStreamIO=Features.supportNetworkStreamIO(),features.networkLoaderName=Features.getNetworkLoaderTypeName(),features.mseLiveFlvPlayback=features.mseFlvPlayback&&features.networkStreamIO,features.nativeMP4H264Playback=Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'),features.nativeWebmVP8Playback=Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'),features.nativeWebmVP9Playback=Features.supportNativeMediaPlayback('video/webm; codecs="vp9"'),features}}]),Features}();exports.default=Features},{'../config.js':5,'../io/io-controller.js':23}],7:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),MediaInfo=function(){function MediaInfo(){_classCallCheck(this,MediaInfo),this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=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 _createClass(MediaInfo,[{key:'isComplete',value:function(){var audioInfoComplete=!1===this.hasAudio||!0===this.hasAudio&&null!=this.audioCodec&&null!=this.audioSampleRate&&null!=this.audioChannelCount,videoInfoComplete=!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.refFrames&&null!=this.chromaFormat&&null!=this.sarNum&&null!=this.sarDen;return null!=this.mimeType&&null!=this.duration&&null!=this.metadata&&null!=this.hasKeyframesIndex&&audioInfoComplete&&videoInfoComplete}},{key:'isSeekable',value:function(){return!0===this.hasKeyframesIndex}},{key:'getNearestKeyframe',value:function(milliseconds){if(null==this.keyframesIndex)return null;var table=this.keyframesIndex,keyframeIdx=this._search(table.times,milliseconds);return{index:keyframeIdx,milliseconds:table.times[keyframeIdx],fileposition:table.filepositions[keyframeIdx]}}},{key:'_search',value:function(list,value){var idx=0,last=list.length-1,mid=0,lbound=0,ubound=last;for(value<list[0]&&(idx=0,lbound=ubound+1);lbound<=ubound;)if(mid=lbound+Math.floor((ubound-lbound)/2),mid==last||value>=list[mid]&&value<list[mid+1]){idx=mid;break}else list[mid]<value?lbound=mid+1:ubound=mid-1;return idx}}]),MediaInfo}();exports.default=MediaInfo},{}],8:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),SampleInfo=exports.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},MediaSegmentInfo=exports.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=[],this.firstSample=null,this.lastSample=null}return _createClass(MediaSegmentInfo,[{key:'appendSyncPoint',value:function(sampleInfo){sampleInfo.isSyncPoint=!0,this.syncPoints.push(sampleInfo)}}]),MediaSegmentInfo}
1(),IDRSampleList=exports.IDRSampleList=function(){function IDRSampleList(){_classCallCheck(this,IDRSampleList),this._list=[]}return _createClass(IDRSampleList,[{key:'clear',value:function(){this._list=[]}},{key:'appendArray',value:function(syncPoints){var list=this._list;0===syncPoints.length||(0<list.length&&syncPoints[0].originalDts<list[list.length-1].originalDts&&this.clear(),Array.prototype.push.apply(list,syncPoints))}},{key:'getLastSyncPointBeforeDts',value:function(dts){if(0==this._list.length)return null;var list=this._list,idx=0,last=list.length-1,mid=0,lbound=0,ubound=last;for(dts<list[0].dts&&(idx=0,lbound=ubound+1);lbound<=ubound;)if(mid=lbound+Math.floor((ubound-lbound)/2),mid==last||dts>=list[mid].dts&&dts<list[mid+1].dts){idx=mid;break}else list[mid].dts<dts?lbound=mid+1:ubound=mid-1;return this._list[idx]}}]),IDRSampleList}(),MediaSegmentInfoList=exports.MediaSegmentInfoList=function(){function MediaSegmentInfoList(type){_classCallCheck(this,MediaSegmentInfoList),this._type=type,this._list=[],this._lastAppendLocation=-1}return _createClass(MediaSegmentInfoList,[{key:'isEmpty',value:function(){return 0===this._list.length}},{key:'clear',value:function(){this._list=[],this._lastAppendLocation=-1}},{key:'_searchNearestSegmentBefore',value:function(originalBeginDts){var list=this._list;if(0===list.length)return-2;var last=list.length-1,mid=0,lbound=0,ubound=last,idx=0;if(originalBeginDts<list[0].originalBeginDts)return idx=-1,idx;for(;lbound<=ubound;)if(mid=lbound+Math.floor((ubound-lbound)/2),mid==last||originalBeginDts>list[mid].lastSample.originalDts&&originalBeginDts<list[mid+1].originalBeginDts){idx=mid;break}else list[mid].originalBeginDts<originalBeginDts?lbound=mid+1:ubound=mid-1;return idx}},{key:'_searchNearestSegmentAfter',value:function(originalBeginDts){return this._searchNearestSegmentBefore(originalBeginDts)+1}},{key:'append',value:function(mediaSegmentInfo){var list=this._list,msi=mediaSegmentInfo,lastAppendIdx=this._lastAppendLocation,insertIdx=0;-1!==lastAppendIdx&&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:0<list.length&&(insertIdx=this._searchNearestSegmentBefore(msi.originalBeginDts)+1),this._lastAppendLocation=insertIdx,this._list.splice(insertIdx,0,msi)}},{key:'getLastSegmentBefore',value:function(originalBeginDts){var idx=this._searchNearestSegmentBefore(originalBeginDts);return 0<=idx?this._list[idx]:null}},{key:'getLastSampleBefore',value:function(originalBeginDts){var segment=this.getLastSegmentBefore(originalBeginDts);return null==segment?null:segment.lastSample}},{key:'getLastSyncPointBefore',value:function(originalBeginDts){for(var segmentIdx=this._searchNearestSegmentBefore(originalBeginDts),syncPoints=this._list[segmentIdx].syncPoints;0===syncPoints.length&&0<segmentIdx;)segmentIdx--,syncPoints=this._list[segmentIdx].syncPoints;return 0<syncPoints.length?syncPoints[syncPoints.length-1]:null}},{key:'type',get:function(){return this._type}},{key:'length',get:function(){return this._list.length}}]),MediaSegmentInfoList}()},{}],9:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=_interopRequireDefault(_events),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_browser=_dereq_('../utils/browser.js'),_browser2=_interopRequireDefault(_browser),_mseEvents=_dereq_('./mse-events.js'),_mseEvents2=_interopRequireDefault(_mseEvents),_mediaSegmentInfo=_dereq_('./media-segment-info.js'),_exception=_dereq_('../utils/exception.js'),MSEController=function(){function MSEController(config){_classCallCheck(this,MSEController),this.TAG='MSEController',this._config=config,this._emitter=new _events2.default,this._config.isLive&&void 0==this._config.autoCleanupSourceBuffer&&(this._config.autoCleanupSourceBuffer=!0),this.e={onSourceOpen:this._onSourceOpen.bind(this),onSourceEnded:this._onSourceEnded.bind(this),onSourceClose:this._onSourceClose.bind(this),onSourceBufferError:this._onSourceBufferError.bind(this),onSourceBufferUpdateEnd:this._onSourceBufferUpdateEnd.bind(this)},this._mediaSource=null,this._mediaSourceObjectURL=null,this._mediaElement=null,this._isBufferFull=!1,this._hasPendingEos=!1,this._requireSetMediaDuration=!1,this._pendingMediaDuration=0,this._pendingSourceBufferInit=[],this._mimeTypes={video:null,audio:null},this._sourceBuffers={video:null,audio:null},this._lastInitSegments={video:null,audio:null},this._pendingSegments={video:[],audio:[]},this._pendingRemoveRanges={video:[],audio:[]},this._idrList=new _mediaSegmentInfo.IDRSampleList}return _createClass(MSEController,[{key:'destroy',value:function(){(this._mediaElement||this._mediaSource)&&this.detachMediaElement(),this.e=null,this._emitter.removeAllListeners(),this._emitter=null}},{key:'on',value:function(event,listener){this._emitter.addListener(event,listener)}},{key:'off',value:function(event,listener){this._emitter.removeListener(event,listener)}},{key:'attachMediaElement',value:function(mediaElement){if(this._mediaSource)throw new _exception.IllegalStateException('MediaSource has been attached to an HTMLMediaElement!');var ms=this._mediaSource=new window.MediaSource;ms.addEventListener('sourceopen',this.e.onSourceOpen),ms.addEventListener('sourceended',this.e.onSourceEnded),ms.addEventListener('sourceclose',this.e.onSourceClose),this._mediaElement=mediaElement,this._mediaSourceObjectURL=window.URL.createObjectURL(this._mediaSource),mediaElement.src=this._mediaSourceObjectURL}},{key:'detachMediaElement',value:function(){if(this._mediaSource){var ms=this._mediaSource;
1for(var type in this._sourceBuffers){var ps=this._pendingSegments[type];ps.splice(0,ps.length),this._pendingSegments[type]=null,this._pendingRemoveRanges[type]=null,this._lastInitSegments[type]=null;var sb=this._sourceBuffers[type];if(sb){if('closed'!==ms.readyState){try{ms.removeSourceBuffer(sb)}catch(error){_logger2.default.e(this.TAG,error.message)}sb.removeEventListener('error',this.e.onSourceBufferError),sb.removeEventListener('updateend',this.e.onSourceBufferUpdateEnd)}this._mimeTypes[type]=null,this._sourceBuffers[type]=null}}if('open'===ms.readyState)try{ms.endOfStream()}catch(error){_logger2.default.e(this.TAG,error.message)}ms.removeEventListener('sourceopen',this.e.onSourceOpen),ms.removeEventListener('sourceended',this.e.onSourceEnded),ms.removeEventListener('sourceclose',this.e.onSourceClose),this._pendingSourceBufferInit=[],this._isBufferFull=!1,this._idrList.clear(),this._mediaSource=null}this._mediaElement&&(this._mediaElement.src='',this._mediaElement.removeAttribute('src'),this._mediaElement=null),this._mediaSourceObjectURL&&(window.URL.revokeObjectURL(this._mediaSourceObjectURL),this._mediaSourceObjectURL=null)}},{key:'appendInitSegment',value:function(initSegment,deferred){if(!this._mediaSource||'open'!==this._mediaSource.readyState)return this._pendingSourceBufferInit.push(initSegment),void this._pendingSegments[initSegment.type].push(initSegment);var is=initSegment,mimeType=''+is.container;is.codec&&0<is.codec.length&&(mimeType+=';codecs='+is.codec);var firstInitSegment=!1;if(_logger2.default.v(this.TAG,'Received Initialization Segment, mimeType: '+mimeType),this._lastInitSegments[is.type]=is,mimeType!==this._mimeTypes[is.type]){if(!this._mimeTypes[is.type]){firstInitSegment=!0;try{var sb=this._sourceBuffers[is.type]=this._mediaSource.addSourceBuffer(mimeType);sb.addEventListener('error',this.e.onSourceBufferError),sb.addEventListener('updateend',this.e.onSourceBufferUpdateEnd)}catch(error){return _logger2.default.e(this.TAG,error.message),void this._emitter.emit(_mseEvents2.default.ERROR,{code:error.code,msg:error.message})}}else _logger2.default.v(this.TAG,'Notice: '+is.type+' mimeType changed, origin: '+this._mimeTypes[is.type]+', target: '+mimeType);this._mimeTypes[is.type]=mimeType}deferred||this._pendingSegments[is.type].push(is),firstInitSegment||!this._sourceBuffers[is.type]||this._sourceBuffers[is.type].updating||this._doAppendSegments(),_browser2.default.safari&&'audio/mpeg'===is.container&&0<is.mediaDuration&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=is.mediaDuration/1e3,this._updateMediaSourceDuration())}},{key:'appendMediaSegment',value:function(mediaSegment){var ms=mediaSegment;this._pendingSegments[ms.type].push(ms),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var sb=this._sourceBuffers[ms.type];!sb||sb.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()}},{key:'seek',value:function(){for(var type in this._sourceBuffers)if(this._sourceBuffers[type]){var sb=this._sourceBuffers[type];if('open'===this._mediaSource.readyState)try{sb.abort()}catch(error){_logger2.default.e(this.TAG,error.message)}this._idrList.clear();var ps=this._pendingSegments[type];if(ps.splice(0,ps.length),'closed'!==this._mediaSource.readyState){for(var i=0;i<sb.buffered.length;i++){var start=sb.buffered.start(i),end=sb.buffered.end(i);this._pendingRemoveRanges[type].push({start:start,end:end})}if(sb.updating||this._doRemoveRanges(),_browser2.default.safari){var lastInitSegment=this._lastInitSegments[type];lastInitSegment&&(this._pendingSegments[type].push(lastInitSegment),!sb.updating&&this._doAppendSegments())}}}}},{key:'endOfStream',value:function(){var ms=this._mediaSource,sb=this._sourceBuffers;return ms&&'open'===ms.readyState?void(sb.video&&sb.video.updating||sb.audio&&sb.audio.updating?this._hasPendingEos=!0:(this._hasPendingEos=!1,ms.endOfStream())):void(ms&&'closed'===ms.readyState&&this._hasPendingSegments()&&(this._hasPendingEos=!0))}},{key:'getNearestKeyframe',value:function(dts){return this._idrList.getLastSyncPointBeforeDts(dts)}},{key:'_needCleanupSourceBuffer',value:function(){if(!this._config.autoCleanupSourceBuffer)return!1;var currentTime=this._mediaElement.currentTime;for(var type in this._sourceBuffers){var sb=this._sourceBuffers[t
vendor: 34,133 bytes, line 1
1ype];if(sb){var buffered=sb.buffered;if(1<=buffered.length&¤tTime-buffered.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1}},{key:'_doCleanupSourceBuffer',value:function(){var currentTime=this._mediaElement.currentTime;for(var type in this._sourceBuffers){var sb=this._sourceBuffers[type];if(sb){for(var buffered=sb.buffered,doRemove=!1,i=0;i<buffered.length;i++){var start=buffered.start(i),end=buffered.end(i);if(!(start<=currentTime&¤tTime<end+3))end<currentTime&&(doRemove=!0,this._pendingRemoveRanges[type].push({start:start,end:end}));else if(currentTime-start>=this._config.autoCleanupMaxBackwardDuration){doRemove=!0;var removeEnd=currentTime-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[type].push({start:start,end:removeEnd})}}doRemove&&!sb.updating&&this._doRemoveRanges()}}}},{key:'_updateMediaSourceDuration',value:function(){var sb=this._sourceBuffers;if(0!==this._mediaElement.readyState&&'open'===this._mediaSource.readyState&&!(sb.video&&sb.video.updating||sb.audio&&sb.audio.updating)){var current=this._mediaSource.duration,target=this._pendingMediaDuration;0<target&&(isNaN(current)||target>current)&&(_logger2.default.v(this.TAG,'Update MediaSource duration from '+current+' to '+target),this._mediaSource.duration=target),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}}},{key:'_doRemoveRanges',value:function(){for(var type in this._pendingRemoveRanges)if(this._sourceBuffers[type]&&!this._sourceBuffers[type].updating)for(var sb=this._sourceBuffers[type],ranges=this._pendingRemoveRanges[type],range;ranges.length&&!sb.updating;)range=ranges.shift(),sb.remove(range.start,range.end)}},{key:'_doAppendSegments',value:function(){var pendingSegments=this._pendingSegments;for(var type in pendingSegments)if(this._sourceBuffers[type]&&!this._sourceBuffers[type].updating&&0<pendingSegments[type].length){var segment=pendingSegments[type].shift();if(segment.timestampOffset){var currentOffset=this._sourceBuffers[type].timestampOffset,targetOffset=segment.timestampOffset/1e3,delta=Math.abs(currentOffset-targetOffset);.1<delta&&(_logger2.default.v(this.TAG,'Update MPEG audio timestampOffset from '+currentOffset+' to '+targetOffset),this._sourceBuffers[type].timestampOffset=targetOffset),delete segment.timestampOffset}if(!segment.data||0===segment.data.byteLength)continue;try{this._sourceBuffers[type].appendBuffer(segment.data),this._isBufferFull=!1,'video'==type&&segment.hasOwnProperty('info')&&this._idrList.appendArray(segment.info.syncPoints)}catch(error){this._pendingSegments[type].unshift(segment),22===error.code?(!this._isBufferFull&&this._emitter.emit(_mseEvents2.default.BUFFER_FULL),this._isBufferFull=!0):(_logger2.default.e(this.TAG,error.message),this._emitter.emit(_mseEvents2.default.ERROR,{code:error.code,msg:error.message}))}}}},{key:'_onSourceOpen',value:function(){if(_logger2.default.v(this.TAG,'MediaSource onSourceOpen'),this._mediaSource.removeEventListener('sourceopen',this.e.onSourceOpen),0<this._pendingSourceBufferInit.length)for(var pendings=this._pendingSourceBufferInit,segment;pendings.length;)segment=pendings.shift(),this.appendInitSegment(segment,!0);this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(_mseEvents2.default.SOURCE_OPEN)}},{key:'_onSourceEnded',value:function(){_logger2.default.v(this.TAG,'MediaSource onSourceEnded')}},{key:'_onSourceClose',value:function(){_logger2.default.v(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:'_hasPendingSegments',value:function(){var ps=this._pendingSegments;return 0<ps.video.length||0<ps.audio.length}},{key:'_hasPendingRemoveRanges',value:function(){var prr=this._pendingRemoveRanges;return 0<prr.video.length||0<prr.audio.length}},{key:'_onSourceBufferUpdateEnd',value:function(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(_mseEvents2.default.UPDATE_END)}},{key:'_onSourceBufferError',value:function(e){_logger2.default.e(this.TAG,'SourceBuffer Error: '+e)}}]),MSEController}();exports.default=MSEController},{'../utils/browser.js':39,'../utils/exception.js':40,'../utils/logger.js':41,'./media-segment-info.js':8,'./mse-events.js':10,events:2}],10:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});exports.default={ERROR:'error',SOURCE_OPEN:'source_open',UPDATE_END:'update_end',BUFFER_FULL:'buffer_full'}},{}],11:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=_interopRequireDefault(_events),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_loggingControl=_dereq_('../utils/logging-control.js'),_loggingControl2=_interopRequireDefault(_loggingControl),_transmuxingController=_dereq_('./transmuxing-controller.js'),_transmuxingController2=_interopRequireDefault(_transmuxingController),_transmuxingEvents=_dereq_('./transmuxing-events.js'),_transmuxingEvents2=_interopRequireDefault(_transmuxingEvents),_transmuxingWorker=_dereq_('./transmuxing-worker.js'),_transmuxingWorker2=_interopRequireDefault(_transmuxingWorker),_mediaInfo=_dereq_('./media-info.js'),_mediaInfo2=_interopRequireDefault(_mediaInfo),Transmuxer=function(){function Transmuxer(mediaDataSource,config){if(_classCallCheck(this,Transmuxer),this.TAG='Transmuxer',this._emitter=new _events2.default,config.enableWorker&&'undefined'!=typeof Worker)try{var work=_dereq_('webworkify');this._worker=work(_transmuxingWorker2.default),this._workerDestroying=!1,this._worker.addEventListener('message',this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:'init',param:[mediaDataSource,config]}),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this)},_loggingControl2.default.registerListener(this.e.onLoggingConfigChanged),this._worker.postMessage({cmd:'logging_config',param:_loggingControl2.default.getConfig()})}catch(error){_logger2.default.e(this.TAG,'Error while initialize transmuxing worker, fallback to inline transmuxing'),this._worker=null,this._controller=new _transmuxingController2.default(mediaDataSource,config)}else this._controller=new _transmuxingController2.default(mediaDataSource,config);if(this._controller){var ctl=this._controller;ctl.on(_transmuxingEvents2.default.IO_ERROR,this._onIOError.bind(this)),ctl.on(_transmuxingEvents2.default.DEMUX_ERROR,this._onDemuxError.bind(this)),ctl.on(_transmuxingEvents2.default.INIT_SEGMENT,this._onInitSegment.bind(this)),ctl.on(_transmuxingEvents2.default.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),ctl.on(_transmuxingEvents2.default.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),ctl.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),ctl.on(_transmuxingEvents2.default.MEDIA_INFO,this._onMediaInfo.bind(this)),ctl.on(_transmuxingEvents2.default.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),ctl.on(_transmuxingEvents2.default.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),ctl.on(_transmuxingEvents2.default.STREAMDATA_ARRIVED,this._onStreamDataArrived.bind(this)),ctl.on(_transmuxingEvents2.default.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),ctl.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}return _createClass(Transmuxer,[{key:'destroy',value:function(){this._worker?!this._workerDestroying&&(this._workerDestroying=!0,this._worker.postMessage({cmd:'destroy'}),_loggingControl2.default.removeListener(this.e.onLoggingConfigChanged),this.e=null):(this._controller.destroy(),this._controller=null),this._emitter.removeAllListeners(),this._emitter=null}},{key:'on',value:function(event,listener){this._emitter.addListener(event,listener)}},{key:'off',value:function(event,listener){this._emitter.removeListener(event,listener)}},{key:'hasWorker',value:function(){return null!=this._worker}},{key:'open',value:function(){this._worker?this._worker.postMessage({cmd:'start'}):this._controller.start()}},{key:'close',value:function(){this._worker?this._worker.postMessage({cmd:'stop'}):this._controller.stop()}},{key:'seek',value:function(milliseconds){this._worker?this._worker.postMessage({cmd:'seek',param:milliseconds}):this._controller.seek(milliseconds)}},{key:'pause',value:function(){this._worker?this._worker.postMessage({cmd:'pause'}):this._controller.pause()}},{key:'resume',value:function(){this._worker?this._worker.postMessage({cmd:'resume'}):this._controller.resume()}},{key:'_onInitSegment',value:function(type,initSegment){var _this=this;Promise.resolve().then(function(){_this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT,type,initSegment)})}},{key:'_onMediaSegment',value:function(type,mediaSegment){var _this2=this;Promise.resolve().then(function(){_this2._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT,type,mediaSegment)})}},{key:'_onLoadingComplete',value:function(){var _this3=this;Promise.resolve().then(function(){_this3._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE)})}},{key:'_onRecoveredEarlyEof',value:function(){var _this4=this;Promise.resolve().then(function(){_this4._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF)})}},{key:'_onMediaInfo',value:function(mediaInfo){var _this5=this;Promise.resolve().then(function(){_this5._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO,mediaInfo)})}},{key:'_onMetaDataArrived',value:function(metadata){var _this6=this;Promise.resolve().then(function(){_this6._emitter.emit(_transmuxingEvents2.default.METADATA_ARRIVED,metadata)})}},{key:'_onScriptDataArrived',value:function(data){var _this7=this;Promise.resolve().then(function(){_this7._emitter.emit(_transmuxingEvents2.default.SCRIPTDATA_ARRIVED,data)})}},{key:'_onStreamDataArrived',value:function(data){var _this8=this;Promise.resolve().then(function(){_this8._emitter.emit(_transmuxingEvents2.default.STREAMDATA_ARRIVED,data)})}},{key:'_onStatisticsInfo',value:function(statisticsInfo){var _this9=this;Promise.resolve().then(function(){_this9._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO,statisticsInfo)})}},{key:'_onIOError',value:function(type,info){var _this10=this;Promise.resolve().then(function(){_this10._emitter.emit(_transmuxingEvents2.default.IO_ERROR,type,info)})}},{key:'_onDemuxError',value:function(type,info){var _this11=this;Promise.resolve().then(function(){_this11._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR,type,info)})}},{key:'_onRecommendSeekpoint',value:function(milliseconds){var _this12=this;Promise.resolve().then(function(){_this12._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT,milliseconds)})}},{key:'_onLoggingConfigChanged',value:function(config){this._worker&&this._worker.postMessage({cmd:'logging_config',param:config})}},{key:'_onWorkerMessage',value:function(e){var message=e.data,data=message.data;if('destroyed'===message.msg||this._workerDestroying)return this._workerDestroying=!1,this._worker.terminate(),void(this._worker=null);switch(message.msg){case _transmuxingEvents2.default.INIT_SEGMENT:case _transmuxingEvents2.default.MEDIA_SEGMENT:this._emitter.emit(message.msg,data.type,data.data);break;case _transmuxingEvents2.default.LOADING_COMPLETE:case _transmuxingEvents2.default.RECOVERED_EARLY_EOF:this._emitter.emit(message.msg);break;case _transmuxingEvents2.default.MEDIA_INFO:Object.setPrototypeOf(data,_mediaInfo2.default.prototype),this._emitter.emit(message.msg,data);break;case _transmuxingEvents2.default.METADATA_ARRIVED:case _transmuxingEvents2.default.SCRIPTDATA_ARRIVED:case _transmuxingEvents2.default.STREAMDATA_ARRIVED:case _transmuxingEvents2.default.STATISTICS_INFO:this._emitter.emit(message.msg,data);break;case _transmuxingEvents2.default.IO_ERROR:case _transmuxingEvents2.default.DEMUX_ERROR:this._emitter.emit(message.msg,data.type,data.info);break;case _transmuxingEvents2.default.RECOMMEND_SEEKPOINT:this._emitter.emit(message.msg,data);break;case'logcat_callback':_logger2.default.emitter.emit('log',data.type,data.logcat);break;default:}}}]),Transmuxer}();exports.default=Transmuxer},{'../utils/logger.js':41,'../utils/logging-control.js':42,'./media-info.js':7,'./transmuxing-controller.js':12,'./transmuxing-events.js':13,'./transmuxing-worker.js':14,events:2,webworkify:4}],12:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=_interopRequireDefault(_events),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_browser=_dereq_('../utils/browser.js'),_browser2=_interopRequireDefault(_browser),_mediaInfo=_dereq_('./media-info.js'),_mediaInfo2=_interopRequireDefault(_mediaInfo),_flvDemuxer=_dereq_('../demux/flv-demuxer.js'),_flvDemuxer2=_interopRequireDefault(_flvDemuxer),_mp4Remuxer=_dereq_('../remux/mp4-remuxer.js'),_mp4Remuxer2=_interopRequireDefault(_mp4Remuxer),_demuxErrors=_dereq_('../demux/demux-errors.js'),_demuxErrors2=_interopRequireDefault(_demuxErrors),_ioController=_dereq_('../io/io-controller.js'),_ioController2=_interopRequireDefault(_ioController),_transmuxingEvents=_dereq_('./transmuxing-events.js'),_transmuxingEvents2=_interopRequireDefault(_transmuxingEvents),_loader=_dereq_('../io/loader.js'),TransmuxingController=function(){function TransmuxingController(mediaDataSource,config){_classCallCheck(this,TransmuxingController),this.TAG='TransmuxingController',this._emitter=new _events2.default,this._config=config,mediaDataSource.segments||(mediaDataSource.segments=[{duration:mediaDataSource.duration,filesize:mediaDataSource.filesize,url:mediaDataSource.url}]),'boolean'!=typeof mediaDataSource.cors&&(mediaDataSource.cors=!0),'boolean'!=typeof mediaDataSource.withCredentials&&(mediaDataSource.withCredentials=!1),this._mediaDataSource=mediaDataSource,this._currentSegmentIndex=0;var totalDuration=0;this._mediaDataSource.segments.forEach(function(segment){segment.timestampBase=totalDuration,totalDuration+=segment.duration,segment.cors=mediaDataSource.cors,segment.withCredentials=mediaDataSource.withCredentials,config.referrerPolicy&&(segment.referrerPolicy=config.referrerPolicy)}),isNaN(totalDuration)||this._mediaDataSource.duration===totalDuration||(this._mediaDataSource.duration=totalDuration),this._mediaInfo=null,this._demuxer=null,this._remuxer=null,this._ioctl=null,this._pendingSeekTime=null,this._pendingResolveSeekPoint=null,this._statisticsReporter=null}return _createClass(TransmuxingController,[{key:'destroy',value:function(){this._mediaInfo=null,this._mediaDataSource=null,this._statisticsReporter&&this._disableStatisticsReporter(),this._ioctl&&(this._ioctl.destroy(),this._ioctl=null),this._demuxer&&(this._demuxer.destroy(),this._demuxer=null),this._remuxer&&(this._remuxer.destroy(),this._remuxer=null),this._emitter.removeAllListeners(),this._emitter=null}},{key:'on',value:function(event,listener){this._emitter.addListener(event,listener)}},{key:'off',value:function(event,listener){this._emitter.removeListener(event,listener)}},{key:'start',value:function(){this._loadSegment(0),this._enableStatisticsReporter()}},{key:'_loadSegment',value:function(segmentIndex,optionalFrom){this._currentSegmentIndex=segmentIndex;var dataSource=this._mediaDataSource.segments[segmentIndex],ioctl=this._ioctl=new _ioController2.default(dataSource,this._config,segmentIndex);ioctl.onError=this._onIOException.bind(this),ioctl.onSeeked=this._onIOSeeked.bind(this),ioctl.onComplete=this._onIOComplete.bind(this),ioctl.onRedirect=this._onIORedirect.bind(this),ioctl.onRecoveredEarlyEof=this._onIORecoveredEarlyEof.bind(this),optionalFrom?this._demuxer.bindDataSource(this._ioctl):ioctl.onDataArrival=this._onInitChunkArrival.bind(this),ioctl.open(optionalFrom)}},{key:'stop',value:function(){this._internalAbort(),this._disableStatisticsReporter()}},{key:'_internalAbort',value:function(){this._ioctl&&(this._ioctl.destroy(),this._ioctl=null)}},{key:'pause',value:function(){this._ioctl&&this._ioctl.isWorking()&&(this._ioctl.pause(),this._disableStatisticsReporter())}},{key:'resume',value:function(){this._ioctl&&this._ioctl.isPaused()&&(this._ioctl.resume(),this._enableStatisticsReporter())}},{key:'seek',value:function(milliseconds){if(null!=this._mediaInfo&&this._mediaInfo.isSeekable()){var targetSegmentIndex=this._searchSegmentIndexContains(milliseconds);if(targetSegmentIndex===this._currentSegmentIndex){var segmentInfo=this._mediaInfo.segments[targetSegmentIndex];if(void 0==segmentInfo)this._pendingSeekTime=milliseconds;else{var keyframe=segmentInfo.getNearestKeyframe(milliseconds);this._remuxer.seek(keyframe.milliseconds),this._ioctl.seek(keyframe.fileposition),this._pendingResolveSeekPoint=keyframe.milliseconds}}else{var targetSegmentInfo=this._mediaInfo.segments[targetSegmentIndex];if(void 0==targetSegmentInfo)this._pendingSeekTime=milliseconds,this._internalAbort(),this._remuxer.seek(),this._remuxer.insertDiscontinuity(),this._loadSegment(targetSegmentIndex);else{var _keyframe=targetSegmentInfo.getNearestKeyframe(milliseconds);this._internalAbort(),this._remuxer.seek(milliseconds),this._remuxer.insertDiscontinuity(),this._demuxer.resetMediaInfo(),this._demuxer.timestampBase=this._mediaDataSource.segments[targetSegmentIndex].timestampBase,this._loadSegment(targetSegmentIndex,_keyframe.fileposition),this._pendingResolveSeekPoint=_keyframe.milliseconds,this._reportSegmentMediaInfo(targetSegmentIndex)}}this._enableStatisticsReporter()}}},{key:'_searchSegmentIndexContains',value:function(milliseconds){for(var segments=this._mediaDataSource.segments,idx=segments.length-1,i=0;i<segments.length;i++)if(milliseconds<segments[i].timestampBase){idx=i-1;break}return idx}},{key:'_onInitChunkArrival',value:function(data,byteStart){var _this=this,probeData=null,consumed=0;if(0<byteStart)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,consumed=this._demuxer.parseChunks(data,byteStart);else if((probeData=_flvDemuxer2.default.probe(data)).match){this._demuxer=new _flvDemuxer2.default(probeData,this._config),this._remuxer||(this._remuxer=new _mp4Remuxer2.default(this._config));var mds=this._mediaDataSource;void 0==mds.duration||isNaN(mds.duration)||(this._demuxer.overridedDuration=mds.duration),'boolean'==typeof mds.hasAudio&&(this._demuxer.overridedHasAudio=mds.hasAudio),'boolean'==typeof mds.hasVideo&&(this._demuxer.overridedHasVideo=mds.hasVideo),this._demuxer.timestampBase=mds.segments[this._currentSegmentIndex].timestampBase,this._demuxer.onError=this._onDemuxException.bind(this),this._demuxer.onMediaInfo=this._onMediaInfo.bind(this),this._demuxer.onMetaDataArrived=this._onMetaDataArrived.bind(this),this._demuxer.onScriptDataArrived=this._onScriptDataArrived.bind(this),this._demuxer.onStreamDataArrived=this._onStreamDataArrived.bind(this),this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this),consumed=this._demuxer.parseChunks(data,byteStart)}else probeData=null,_logger2.default.e(this.TAG,'Non-FLV, Unsupported media type!'),Promise.resolve().then(function(){_this._internalAbort()}),this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR,_demuxErrors2.default.FORMAT_UNSUPPORTED,'Non-FLV, Unsupported media type'),consumed=0;return consumed}},{key:'_onMediaInfo',value:function(mediaInfo){var _this2=this;null==this._mediaInfo&&(this._mediaInfo=Object.assign({},mediaInfo),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=this._mediaDataSource.segments.length,Object.setPrototypeOf(this._mediaInfo,_mediaInfo2.default.prototype));var segmentInfo=Object.assign({},mediaInfo);Object.setPrototypeOf(segmentInfo,_mediaInfo2.default.prototype),this._mediaInfo.segments[this._currentSegmentIndex]=segmentInfo,this._reportSegmentMediaInfo(this._currentSegmentIndex),null!=this._pendingSeekTime&&Promise.resolve().then(function(){var target=_this2._pendingSeekTime;_this2._pendingSeekTime=null,_this2.seek(target)})}},{key:'_onMetaDataArrived',value:function(metadata){this._emitter.emit(_transmuxingEvents2.default.METADATA_ARRIVED,metadata)}},{key:'_onScriptDataArrived',value:function(data){this._emitter.emit(_transmuxingEvents2.default.SCRIPTDATA_ARRIVED,data)}},{key:'_onStreamDataArrived',value:function(data){this._emitter.emit(_transmuxingEvents2.default.STREAMDATA_ARRIVED,data)}},{key:'_onIOSeeked',value:function(){this._remuxer.insertDiscontinuity()}},{key:'_onIOComplete',value:function(extraData){var nextSegmentIndex=extraData+1;nextSegmentIndex<this._mediaDataSource.segments.length?(this._internalAbort(),this._remuxer.flushStashedSamples(),this._loadSegment(nextSegmentIndex)):(this._remuxer.flushStashedSamples(),this._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE),this._disableStatisticsReporter())}},{key:'_onIORedirect',value:function(redirectedURL){var segmentIndex=this._ioctl.extraData;this._mediaDataSource.segments[segmentIndex].redirectedURL=redirectedURL}},{key:'_onIORecoveredEarlyEof',value:function(){this._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF)}},{key:'_onIOException',value:function(type,info){_logger2.default.e(this.TAG,'IOException: type = '+type+', code = '+info.code+', msg = '+info.msg),this._emitter.emit(_transmuxingEvents2.default.IO_ERROR,type,info),this._disableStatisticsReporter()}},{key:'_onDemuxException',value:function(type,info){_logger2.default.e(this.TAG,'DemuxException: type = '+type+', info = '+info),this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR,type,info)}},{key:'_onRemuxerInitSegmentArrival',value:function(type,initSegment){this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT,type,initSegment)}},{key:'_onRemuxerMediaSegmentArrival',value:function(type,mediaSegment){if(null==this._pendingSeekTime&&(this._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT,type,mediaSegment),null!=this._pendingResolveSeekPoint&&'video'===type)){var syncPoints=mediaSegment.info.syncPoints,seekpoint=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=null,_browser2.default.safari&&0<syncPoints.length&&syncPoints[0].originalDts===seekpoint&&(seekpoint=syncPoints[0].pts),this._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT,seekpoint)}}},{key:'_enableStatisticsReporter',value:function(){null==this._statisticsReporter&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))}},{key:'_disableStatisticsReporter',value:function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)}},{key:'_reportSegmentMediaInfo',value:function(segmentIndex){var segmentInfo=this._mediaInfo.segments[segmentIndex],exportInfo=Object.assign({},segmentInfo);exportInfo.duration=this._mediaInfo.duration,exportInfo.segmentCount=this._mediaInfo.segmentCount,delete exportInfo.segments,delete exportInfo.keyframesIndex,this._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO,exportInfo)}},{key:'_reportStatisticsInfo',value:function(){var info={};info.url=this._ioctl.currentURL,info.hasRedirect=this._ioctl.hasRedirect,info.hasRedirect&&(info.redirectedURL=this._ioctl.currentRedirectedURL),info.speed=this._ioctl.currentSpeed,info.loaderType=this._ioctl.loaderType,info.currentSegmentIndex=this._currentSegmentIndex,info.totalSegmentCount=this._mediaDataSource.segments.length,this._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO,info)}}]),TransmuxingController}();exports.default=TransmuxingController},{'../demux/demux-errors.js':16,'../demux/flv-demuxer.js':18,'../io/io-controller.js':23,'../io/loader.js':24,'../remux/mp4-remuxer.js':38,'../utils/browser.js':39,'../utils/logger.js':41,'./media-info.js':7,'./transmuxing-events.js':13,events:2}],13:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});exports.default={IO_ERROR:'io_error',DEMUX_ERROR:'demux_error',INIT_SEGMENT:'init_segment',MEDIA_SEGMENT:'media_segment',LOADING_COMPLETE:'loading_complete',RECOVERED_EARLY_EOF:'recovered_early_eof',MEDIA_INFO:'media_info',METADATA_ARRIVED:'metadata_arrived',SCRIPTDATA_ARRIVED:'scriptdata_arrived',STREAMDATA_ARRIVED:'streamdata_arrived',STATISTICS_INFO:'statistics_info',RECOMMEND_SEEKPOINT:'recommend_seekpoint'}},{}],14:[function(_dereq_,module,exports){'use strict';function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(exports,'__esModule',{value:!0});var _logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_loggingControl=_dereq_('../utils/logging-control.js'),_loggingControl2=_interopRequireDefault(_loggingControl),_polyfill=_dereq_('../utils/polyfill.js'),_polyfill2=_interopRequireDefault(_polyfill),_transmuxingController=_dereq_('./transmuxing-controller.js'),_transmuxingController2=_interopRequireDefault(_transmuxingController),_transmuxingEvents=_dereq_('./transmuxing-events.js'),_transmuxingEvents2=_interopRequireDefault(_transmuxingEvents);exports.default=function(self){function onInitSegment(type,initSegment){var obj={msg:_transmuxingEvents2.default.INIT_SEGMENT,data:{type:type,data:initSegment}};self.postMessage(obj,[initSegment.data])}function onMediaSegment(type,mediaSegment){var obj={msg:_transmuxingEvents2.default.MEDIA_SEGMENT,data:{type:type,data:mediaSegment}};self.postMessage(obj,[mediaSegment.data])}function onLoadingComplete(){var obj={msg:_transmuxingEvents2.default.LOADING_COMPLETE};self.postMessage(obj)}function onRecoveredEarlyEof(){var obj={msg:_transmuxingEvents2.default.RECOVERED_EARLY_EOF};self.postMessage(obj)}function onMediaInfo(mediaInfo){var obj={msg:_transmuxingEvents2.default.MEDIA_INFO,data:mediaInfo};self.postMessage(obj)}function onMetaDataArrived(metadata){var obj={msg:_transmuxingEvents2.default.METADATA_ARRIVED,data:metadata};self.postMessage(obj)}function onStreamDataArrived(data){var obj={msg:_transmuxingEvents2.default.STREAMDATA_ARRIVED,data:data};self.postMessage(obj)}function onScriptDataArrived(data){var obj={msg:_transmuxingEvents2.default.SCRIPTDATA_ARRIVED,data:data};self.postMessage(obj)}function onStatisticsInfo(statInfo){var obj={msg:_transmuxingEvents2.default.STATISTICS_INFO,data:statInfo};self.postMessage(obj)}function onIOError(type,info){self.postMessage({msg:_transmuxingEvents2.default.IO_ERROR,data:{type:type,info:info}})}function onDemuxError(type,info){self.postMessage({msg:_transmuxingEvents2.default.DEMUX_ERROR,data:{type:type,info:info}})}function onRecommendSeekpoint(milliseconds){self.postMessage({msg:_transmuxingEvents2.default.RECOMMEND_SEEKPOINT,data:milliseconds})}var controller=null,logcatListener=function(type,str){self.postMessage({msg:'logcat_callback',data:{type:type,logcat:str}})}.bind(this);_polyfill2.default.install(),self.addEventListener('message',function(e){switch(e.data.cmd){case'init':controller=new _transmuxingController2.default(e.data.param[0],e.data.param[1]),controller.on(_transmuxingEvents2.default.IO_ERROR,onIOError.bind(this)),controller.on(_transmuxingEvents2.default.DEMUX_ERROR,onDemuxError.bind(this)),controller.on(_transmuxingEvents2.default.INIT_SEGMENT,onInitSegment.bind(this)),controller.on(_transmuxingEvents2.default.MEDIA_SEGMENT,onMediaSegment.bind(this)),controller.on(_transmuxingEvents2.default.LOADING_COMPLETE,onLoadingComplete.bind(this)),controller.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF,onRecoveredEarlyEof.bind(this)),controller.on(_transmuxingEvents2.default.MEDIA_INFO,onMediaInfo.bind(this)),controller.on(_transmuxingEvents2.default.METADATA_ARRIVED,onMetaDataArrived.bind(this)),controller.on(_transmuxingEvents2.default.STREAMDATA_ARRIVED,onStreamDataArrived.bind(this)),controller.on(_transmuxingEvents2.default.SCRIPTDATA_ARRIVED,onScriptDataArrived.bind(this)),controller.on(_transmuxingEvents2.default.STATISTICS_INFO,onStatisticsInfo.bind(this)),controller.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT,onRecommendSeekpoint.bind(this));break;case'destroy':controller&&(controller.destroy(),controller=null),self.postMessage({msg:'destroyed'});break;case'start':controller.start();break;case'stop':controller.stop();break;case'seek':controller.seek(e.data.param);break;case'pause':controller.pause();break;case'resume':controller.resume();break;case'logging_config':{var config=e.data.param;_loggingControl2.default.applyConfig(config),!0===config.enableCallback?_loggingControl2.default.addLogListener(logcatListener):_loggingControl2.default.removeLogListener(logcatListener);break}}})}},{'../utils/logger.js':41,'../utils/logging-control.js':42,'../utils/polyfill.js':43,'./transmuxing-controller.js':12,'./transmuxing-events.js':13}],15:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_utf8Conv=_dereq_('../utils/utf8-conv.js'),_utf8Conv2=_interopRequireDefault(_utf8Conv),_exception=_dereq_('../utils/exception.js'),le=function(){var buf=new ArrayBuffer(2);return new DataView(buf).setInt16(0,256,!0),256===new Int16Array(buf)[0]}(),AMF=function(){function AMF(){_classCallCheck(this,AMF)}return _createClass(AMF,null,[{key:'parseScriptData',value:function(arrayBuffer,dataOffset,dataSize){var data={};try{var name=AMF.parseValue(arrayBuffer,dataOffset,dataSize),value=AMF.parseValue(arrayBuffer,dataOffset+name.size,dataSize-name.size);data[name.data]=value.data}catch(e){_logger2.default.e('AMF',e.toString())}return data}},{key:'parseObject',value:function(arrayBuffer,dataOffset,dataSize){if(3>dataSize)throw new _exception.IllegalStateException('Data not enough when parse ScriptDataObject');var name=AMF.parseString(arrayBuffer,dataOffset,dataSize),value=AMF.parseValue(arrayBuffer,dataOffset+name.size,dataSize-name.size),isObjectEnd=value.objectEnd;return{data:{name:name.data,value:value.data},size:name.size+value.size,objectEnd:isObjectEnd}}},{key:'parseVariable',value:function(arrayBuffer,dataOffset,dataSize){return AMF.parseObject(arrayBuffer,dataOffset,dataSize)}},{key:'parseString',value:function(arrayBuffer,dataOffset,dataSize){if(2>dataSize)throw new _exception.IllegalStateException('Data not enough when parse String');var v=new DataView(arrayBuffer,dataOffset,dataSize),length=v.getUint16(0,!le),str=void 0;return str=0<length?(0,_utf8Conv2.default)(new Uint8Array(arrayBuffer,dataOffset+2,length)):'',{data:str,size:2+length}}},{key:'parseLongString',value:function(arrayBuffer,dataOffset,dataSize){if(4>dataSize)throw new _exception.IllegalStateException('Data not enough when parse LongString');var v=new DataView(arrayBuffer,dataOffset,dataSize),length=v.getUint32(0,!le),str=void 0;return str=0<length?(0,_utf8Conv2.default)(new Uint8Array(arrayBuffer,dataOffset+4,length)):'',{data:str,size:4+length}}},{key:'parseDate',value:function(arrayBuffer,dataOffset,dataSize){if(10>dataSize)throw new _exception.IllegalStateException('Data size invalid when parse Date');var v=new DataView(arrayBuffer,dataOffset,dataSize),timestamp=v.getFloat64(0,!le),localTimeOffset=v.getInt16(8,!le);return timestamp+=1e3*(60*localTimeOffset),{data:new Date(timestamp),size:10}}},{key:'parseValue',value:function(arrayBuffer,dataOffset,dataSize){if(1>dataSize)throw new _exception.IllegalStateException('Data not enough when parse Value');var v=new DataView(arrayBuffer,dataOffset,dataSize),offset=1,type=v.getUint8(0),value=void 0,objectEnd=!1;
1try{switch(type){case 0:value=v.getFloat64(1,!le),offset+=8;break;case 1:{var b=v.getUint8(1);value=!!b,offset+=1;break}case 2:{var amfstr=AMF.parseString(arrayBuffer,dataOffset+1,dataSize-1);value=amfstr.data,offset+=amfstr.size;break}case 3:{value={};var terminal=0;for(9==(16777215&v.getUint32(dataSize-4,!le))&&(terminal=3);offset<dataSize-4;){var amfobj=AMF.parseObject(arrayBuffer,dataOffset+offset,dataSize-offset-terminal);if(amfobj.objectEnd)break;value[amfobj.data.name]=amfobj.data.value,offset+=amfobj.size}if(offset<=dataSize-3){var marker=16777215&v.getUint32(offset-1,!le);9==marker&&(offset+=3)}break}case 8:{value={},offset+=4;var _terminal=0;for(9==(16777215&v.getUint32(dataSize-4,!le))&&(_terminal=3);offset<dataSize-8;){var amfvar=AMF.parseVariable(arrayBuffer,dataOffset+offset,dataSize-offset-_terminal);if(amfvar.objectEnd)break;value[amfvar.data.name]=amfvar.data.value,offset+=amfvar.size}if(offset<=dataSize-3){var _marker=16777215&v.getUint32(offset-1,!le);9==_marker&&(offset+=3)}break}case 9:value=void 0,offset=1,objectEnd=!0;break;case 10:{value=[];
1var strictArrayLength=v.getUint32(1,!le);offset+=4;for(var i=0,val;i<strictArrayLength;i++)val=AMF.parseValue(arrayBuffer,dataOffset+offset,dataSize-offset),value.push(val.data),offset+=val.size;break}case 11:{var date=AMF.parseDate(arrayBuffer,dataOffset+1,dataSize-1);value=date.data,offset+=date.size;break}case 12:{var amfLongStr=AMF.parseString(arrayBuffer,dataOffset+1,dataSize-1);value=amfLongStr.data,offset+=amfLongStr.size;break}default:offset=dataSize,_logger2.default.w('AMF','Unsupported AMF value type '+type);}}catch(e){_logger2.default.e('AMF',e.toString())}return{data:value,size:offset,objectEnd:objectEnd}}}]),AMF}();exports.default=AMF},{'../utils/exception.js':40,'../utils/logger.js':41,'../utils/utf8-conv.js':44}],16:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});exports.default={OK:'OK',FORMAT_ERROR:'FormatError',FORMAT_UNSUPPORTED:'FormatUnsupported',CODEC_UNSUPPORTED:'CodecUnsupported'}},{}],17:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_exception=_dereq_('../utils/exception.js'),ExpGolomb=function(){function ExpGolomb(uint8array){_classCallCheck(this,ExpGolomb),this.TAG='ExpGolomb',this._buffer=uint8array,this._buffer_index=0,this._total_bytes=uint8array.byteLength,this._total_bits=8*uint8array.byteLength,this._current_word=0,this._current_word_bits_left=0}return _createClass(ExpGolomb,[{key:'destroy',value:function(){this._buffer=null}},{key:'_fillCurrentWord',value:function(){var buffer_bytes_left=this._total_bytes-this._buffer_index;if(0>=buffer_bytes_left)throw new _exception.IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');var bytes_read=Math.min(4,buffer_bytes_left),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,!1),this._buffer_index+=bytes_read,this._current_word_bits_left=8*bytes_read}},{key:'readBits',value:function(bits){if(32<bits)throw new _exception.InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');if(bits<=this._current_word_bits_left){var _result=this._current_word>>>32-bits;return this._current_word<<=bits,this._current_word_bits_left-=bits,_result}var result=this._current_word_bits_left?this._current_word:0;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),result2=this._current_word>>>32-bits_read_next;return this._current_word<<=bits_read_next,this._current_word_bits_left-=bits_read_next,result=result<<bits_read_next|result2,result}},{key:'readBool',value:function(){return 1===this.readBits(1)}},{key:'readByte',value:function(){return this.readBits(8)}},{key:'_skipLeadingZero',value:function(){var zero_count;for(zero_count=0;zero_count<this._current_word_bits_left;zero_count++)if(0!=(this._current_word&2147483648>>>zero_count))return this._current_word<<=zero_count,this._current_word_bits_left-=zero_count,zero_count;return this._fillCurrentWord(),zero_count+this._skipLeadingZero()}},{key:'readUEG',value:function(){var leading_zeros=this._skipLeadingZero();return this.readBits(leading_zeros+1)-1}},{key:'readSEG',value:function(){var value=this.readUEG();return 1&value?value+1>>>1:-1*(value>>>1)}}]),ExpGolomb}();exports.default=ExpGolomb},{'../utils/exception.js':40}],18:[function(_dereq_,module,exports){'use strict';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 ReadBig32(array,index){return array[index]<<24|array[index+1]<<16|array[index+2]<<8|array[index+3]}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_amfParser=_dereq_('./amf-parser.js'),_amfParser2=_interopRequireDefault(_amfParser),_spsParser=_dereq_('./s
1ps-parser.js'),_spsParser2=_interopRequireDefault(_spsParser),_demuxErrors=_dereq_('./demux-errors.js'),_demuxErrors2=_interopRequireDefault(_demuxErrors),_mediaInfo=_dereq_('../core/media-info.js'),_mediaInfo2=_interopRequireDefault(_mediaInfo),_exception=_dereq_('../utils/exception.js'),FLVDemuxer=function(){function FLVDemuxer(probeData,config){_classCallCheck(this,FLVDemuxer),this.TAG='FLVDemuxer',this._config=config,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onStreamDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._dataOffset=probeData.dataOffset,this._firstParse=!0,this._dispatch=!1,this._hasAudio=probeData.hasAudioTrack,this._hasVideo=probeData.hasVideoTrack,this._hasAudioFlagOverrided=!1,this._hasVideoFlagOverrided=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new _mediaInfo2.default,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._flvSoundRateTable=[5500,11025,22050,44100,48e3],this._mpegSamplingRates=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],this._mpegAudioV10SampleRateTable=[44100,48e3,32e3,0],this._mpegAudioV20SampleRateTable=[22050,24e3,16e3,0],this._mpegAudioV25SampleRateTable=[11025,12e3,8e3,0],this._mpegAudioL1BitRateTable=[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1],this._mpegAudioL2BitRateTable=[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],this._mpegAudioL3BitRateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],this._videoTrack={type:'video',id:1,sequenceNumber:0,samples:[],length:0},this._audioTrack={type:'audio',id:2,sequenceNumber:0,samples:[],length:0},this._littleEndian=function(){var buf=new ArrayBuffer(2);return new DataView(buf).setInt16(0,256,!0),256===new Int16Array(buf)[0]}()}return _createClass(FLVDemuxer,[{key:'destroy',value:function(){this._mediaInfo=null,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._videoTrack=null,this._audioTrack=null,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onStreamDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null}},{key:'bindDataSource',value:function(loader){return loader.onDataArrival=this.parseChunks.bind(this),this}},{key:'resetMediaInfo',value:function(){this._mediaInfo=new _mediaInfo2.default}},{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}},{key:'parseChunks',value:function(chunk,byteStart){if(!this._onError||!this._onMediaInfo||!this._onTrackMetadata||!this._onDataAvailable)throw new _exception.IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');var offset=0,le=this._littleEndian;if(0===byteStart)if(13<chunk.byteLength){var probeData=FLVDemuxer.probe(chunk);offset=probeData.dataOffset}else return 0;if(this._firstParse){this._firstParse=!1,byteStart+offset!==this._dataOffset&&_logger2.default.w(this.TAG,'First time parsing but chunk byteStart invalid!');var v=new DataView(chunk,offset),prevTagSize0=v.getUint32(0,!le);0!==prevTagSize0&&_logger2.default.w(this.TAG,'PrevTagSize0 !== 0 !!!'),offset+=4}for(;offset<chunk.byteLength;){this._dispatch=!0;var _v=new DataView(chunk,offset);if(offset+11+4>chunk.byteLength)break;var tagType=_v.getUint8(0),dataSize=16777215&_v.getUint32(0,!le);if(offset+11+dataSize+4>chunk.byteLength)break;if(8!==tagType&&9!==tagType&&18!==tagType){_logger2.default.w(this.TAG,'Unsupported tag type '+tagType+', skipped'),offset+=11+dataSize+4;continue}var ts2=_v.getUint8(4),ts1=_v.getUint8(5),ts0=_v.getUint8(6),ts3=_v.getUint8(7),timestamp=ts0|ts1<<8|ts2<<16|ts3<<24,streamId=16777215&_v.getUint32(7,!le);0!=streamId&&_logger2.default.w(this.TAG,'Meet tag which has StreamID != 0!');var dataOffset=offset+11,streamArrivedCallbackData={tagType:tagType,timestamp:timestamp,size:dataSize};8===tagType?this._parseAudioData(chunk,dataOffset,dataSize,timestamp,streamArrivedCallbackData):9===tagType?this._parseVideoData(chunk,dataOffset,dataSize,timestamp,byteStart+offset):18===tagType?this._parseScriptData(chunk,dataOffset,dataSize,timestamp,streamArrivedCallbackData):void 0,this._onStreamDataArrived&&this._onStreamDataArrived(Object.assign({},streamArrivedCallbackData));var prevTagSize=_v.getUint32(11+dataSize,!le);prevTagSize!==11+dataSize&&_logger2.default.w(this.TAG,'Invalid PrevTagSize '+prevTagSize),offset+=11+dataSize+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),offset}},{key:'_parseScriptData',value:function(arrayBuffer,dataOffset,dataSize,tagTimestamp,streamArrivedCallbackData){var scriptData=_amfParser2.default.parseScriptData(arrayBuffer,dataOffset,dataSize);if(scriptData.tagTimestamp=tagTimestamp,scriptData.hasOwnProperty('onMetaData')){if(null==scriptData.onMetaData||'object'!==_typeof(scriptData.onMetaData))return void _logger2.default.w(this.TAG,'Invalid onMetaData structure!');this._metadata&&_logger2.default.w(this.TAG,'Found another onMetaData tag!'),this._metadata=scriptData;var onMetaData=this._metadata.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},onMetaData)),'boolean'==typeof onMetaData.hasAudio&&!1===this._hasAudioFlagOverrided&&(this._hasAudio=onMetaData.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),'boolean'==typeof onMetaData.hasVideo&&!1===this._hasVideoFlagOverrided&&(this._hasVideo=onMetaData.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),'number'==typeof onMetaData.audiodatarate&&(this._mediaInfo.audioDataRate=onMetaData.audiodatarate),'number'==typeof onMetaData.videodatarate&&(this._mediaInfo.videoDataRate=onMetaData.videodatarate),'number'==typeof onMetaData.width&&(this._mediaInfo.width=onMetaData.width),'number'==typeof onMetaData.height&&(this._mediaInfo.height=onMetaData.height),'number'!=typeof onMetaData.duration)this._mediaInfo.duration=0;else if(!this._durationOverrided){var duration=Math.floor(onMetaData.duration*this._timescale);this._duration=duration,this._mediaInfo.duration=duration}if('number'==typeof onMetaData.framerate){var fps_num=Math.floor(1e3*onMetaData.framerate);if(0<fps_num){var fps=fps_num/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=fps,this._referenceFrameRate.fps_num=fps_num,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=fps}}if('object'===_typeof(onMetaData.keyframes)){this._mediaInfo.hasKeyframesIndex=!0;var keyframes=onMetaData.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(keyframes),onMetaData.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;this._dispatch=!1,this._mediaInfo.metadata=onMetaData,_logger2.default.v(this.TAG,'Parsed onMetaData'),this._mediaInfo.isComplete()&&this._onMediaInfo(this._mediaInfo),streamArrivedCallbackData.meta=this._mediaInfo}0<Object.keys(scriptData).length&&(streamArrivedCallbackData.meta=scriptData,this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},scriptData)))}},{key:'_parseKeyframesIndex',value:function(keyframes){for(var times=[],filepositions=[],i=1,time;i<keyframes.times.length;i++)time=this._timestampBase+Math.floor(1e3*keyframes.times[i]),times.push(time),filepositions.push(keyframes.filepositions[i]);return{times:times,filepositions:filepositions}}},{key:'_parseAudioData',value:function(arrayBuffer,dataOffset,dataSize,tagTimestamp,streamArrivedCallbackData){if(1>=dataSize)return void _logger2.default.w(this.TAG,'Flv: Invalid audio packet, missing SoundData payload!');if(!0!==this._hasAudioFlagOverrided||!1!==this._hasAudio){var le=this._littleEndian,v=new DataView(arrayBuffer,dataOffset,dataSize),soundSpec=v.getUint8(0),soundFormat=soundSpec>>>4;if(2!=soundFormat&&10!=soundFormat)return void this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED,'Flv: Unsupported audio codec idx: '+soundFormat);var soundRate=0,soundRateIndex=(12&soundSpec)>>>2;if(0<=soundRateIndex&&4>=soundRateIndex)soundRate=this._flvSoundRateTable[soundRateIndex];else return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: Invalid audio sample rate idx: '+soundRateIndex);var meta=this._audioMetadata,track=this._audioTrack;if(meta||(!1===this._hasAudio&&!1===this._hasAudioFlagOverrided&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),meta=this._audioMetadata={},meta.type='audio',meta.id=track.id,meta.timescale=this._timescale,meta.duration=this._duration,meta.audioSampleRate=soundRate,meta.channelCount=0==(1&soundSpec)?1:2),10==soundFormat){streamArrivedCallbackData.soundFormat='AAC';var aacData=this._parseAACAudioData(arrayBuffer,dataOffset+1,dataSize-1);if(void 0==aacData)return;if(0===aacData.packetType){meta.config&&_logger2.default.w(this.TAG,'Found another AudioSpecificConfig!');var misc=aacData.data;meta.audioSampleRate=misc.samplingRate,meta.channelCount=misc.channelCount,meta.codec=misc.codec,meta.originalCodec=misc.originalCodec,meta.config=misc.config,meta.refSampleDuration=1024/meta.audioSampleRate*meta.timescale,_logger2.default.v(this.TAG,'Parsed AudioSpecificConfig'),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata('audio',meta);var mi=this._mediaInfo;mi.audioCodec=meta.originalCodec,mi.audioSampleRate=meta.audioSampleRate,mi.audioChannelCount=meta.channelCount,mi.hasVideo?null!=mi.videoCodec&&(mi.mimeType='video/x-flv; codecs="'+mi.videoCodec+','+mi.audioCodec+'"'):mi.mimeType='video/x-flv; codecs="'+mi.audioCodec+'"',mi.isComplete()&&this._onMediaInfo(mi)}else if(1===aacData.packetType){var dts=this._timestampBase+tagTimestamp,aacSample={unit:aacData.data,length:aacData.data.byteLength,dts:dts,pts:dts};track.samples.push(aacSample),track.length+=aacData.data.length}else _logger2.default.e(this.TAG,'Flv: Unsupported AAC data type '+aacData.packetType)}else if(2==soundFormat){if(streamArrivedCallbackData.soundFormat='MP3',!meta.codec){var _misc=this._parseMP3AudioData(arrayBuffer,dataOffset+1,dataSize-1,!0);if(void 0==_misc)return;meta.audioSampleRate=_misc.samplingRate,meta.channelCount=_misc.channelCount,meta.codec=_misc.codec,meta.originalCodec=_misc.originalCodec,meta.refSampleDuration=1152/meta.audioSampleRate*meta.timescale,_logger2.default.v(this.TAG,'Parsed MPEG Audio Frame Header'),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata('audio',meta);var _mi=this._mediaInfo;_mi.audioCodec=meta.codec,_mi.audioSampleRate=meta.audioSampleRate,_mi.audioChannelCount=meta.channelCount,_mi.audioDataRate=_misc.bitRate,_mi.hasVideo?null!=_mi.videoCodec&&(_mi.mimeType='video/x-flv; codecs="'+_mi.videoCodec+','+_mi.audioCodec+'"'):_mi.mimeType='video/x-flv; codecs="'+_mi.audioCodec+'"',_mi.isComplete()&&this._onMediaInfo(_mi)}var data=this._parseMP3AudioData(arrayBuffer,dataOffset+1,dataSize-1,!1);if(void 0==data)return;var _dts=this._timestampBase+tagTimestamp,mp3Sample={unit:data,length:data.byteLength,dts:_dts,pts:_dts};track.samples.push(mp3Sample),track.length+=data.length}streamArrivedCallbackData.meta=meta}}},{key:'_parseAACAudioData',value:function(arrayBuffer,dataOffset,dataSize){if(1>=dataSize)return void _logger2.default.w(this.TAG,'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');var result={},array=new Uint8Array(arrayBuffer,dataOffset,dataSize);return result.packetType=array[0],result.data=0===array[0]?this._parseAACAudioSpecificConfig(arrayBuffer,dataOffset+1,dataSize-1):array.subarray(1),result}},{key:'_parseAACAudioSpecificConfig',value:function(arrayBuffer,dataOffset,dataSize){var array=new Uint8Array(arrayBuffer,dataOffset,dataSize),config=null,audioObjectType=0,originalAudioObjectType=0,audioExtensionObjectType=null,samplingIndex=0,extensionSamplingIndex=null;
1if(audioObjectType=originalAudioObjectType=array[0]>>>3,samplingIndex=(7&array[0])<<1|array[1]>>>7,0>samplingIndex||samplingIndex>=this._mpegSamplingRates.length)return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: AAC invalid sampling frequency index!');var samplingFrequence=this._mpegSamplingRates[samplingIndex],channelConfig=(120&array[1])>>>3;if(0>channelConfig||8<=channelConfig)return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: AAC invalid channel configuration');5==audioObjectType&&(extensionSamplingIndex=(7&array[1])<<1|array[2]>>>7,audioExtensionObjectType=(124&array[2])>>>2);var userAgent=self.navigator.userAgent.toLowerCase();return-1===userAgent.indexOf('firefox')?-1===userAgent.indexOf('android')?(audioObjectType=5,extensionSamplingIndex=samplingIndex,config=[,,,,],6<=samplingIndex?extensionSamplingIndex=samplingIndex-3:1==channelConfig&&(audioObjectType=2,config=[,,],extensionSamplingIndex=samplingIndex)):(audioObjectType=2,config=[,,],extensionSamplingIndex=samplingIndex):6<=samplingIndex?(audioObjectType=5,config=[,,,,],extensionSamplingIndex=samplingIndex-3):(audioObjectType=2,config=[,,],extensionSamplingIndex=samplingIndex),config[0]=audioObjectType<<3,config[0]|=(15&samplingIndex)>>>1,config[1]=(15&samplingIndex)<<7,config[1]|=(15&channelConfig)<<3,5==audioObjectType&&(config[1]|=(15&extensionSamplingIndex)>>>1,config[2]=(1&extensionSamplingIndex)<<7,config[2]|=8,config[3]=0),{config:config,samplingRate:samplingFrequence,channelCount:channelConfig,codec:'mp4a.40.'+audioObjectType,originalCodec:'mp4a.40.'+originalAudioObjectType}}},{key:'_parseMP3AudioData',value:function(arrayBuffer,dataOffset,dataSize,requestHeader){if(4>dataSize)return void _logger2.default.w(this.TAG,'Flv: Invalid MP3 packet, header missing!');var le=this._littleEndian,array=new Uint8Array(arrayBuffer,dataOffset,dataSize),result=null;if(requestHeader){if(255!==array[0])return;var ver=3&array[1]>>>3,layer=(6&array[1])>>1,bitrate_index=(240&array[2])>>>4,sampling_freq_index=(12&array[2])>>>2,channel_mode=3&array[3]>>>6,channel_count=3===channel_mode?1:2,sample_rate=0,bit_rate=0,object_type=34,codec='mp3';0==ver?sample_rate=this._mpegAudioV25SampleRateTable[sampling_freq_index]:2==ver?sample_rate=this._mpegAudioV20SampleRateTable[sampling_freq_index]:3==ver?sample_rate=this._mpegAudioV10SampleRateTable[sampling_freq_index]:void 0,1==layer?(object_type=34,bitrate_index<this._mpegAudioL3BitRateTable.length&&(bit_rate=this._mpegAudioL3BitRateTable[bitrate_index])):2==layer?(object_type=33,bitrate_index<this._mpegAudioL2BitRateTable.length&&(bit_rate=this._mpegAudioL2BitRateTable[bitrate_index])):3==layer?(object_type=32,bitrate_index<this._mpegAudioL1BitRateTable.length&&(bit_rate=this._mpegAudioL1BitRateTable[bitrate_index])):void 0,result={bitRate:bit_rate,samplingRate:sample_rate,channelCount:channel_count,codec:codec,originalCodec:codec}}else result=array;return result}},{key:'_parseVideoData',value:function(arrayBuffer,dataOffset,dataSize,tagTimestamp,tagPosition){if(1>=dataSize)return void _logger2.default.w(this.TAG,'Flv: Invalid video packet, missing VideoData payload!');if(!0!==this._hasVideoFlagOverrided||!1!==this._hasVideo){var spec=new Uint8Array(arrayBuffer,dataOffset,dataSize)[0],codecId=15&spec;
1return 7==codecId?void this._parseAVCVideoPacket(arrayBuffer,dataOffset+1,dataSize-1,tagTimestamp,tagPosition,(240&spec)>>>4):void this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED,'Flv: Unsupported codec in video frame: '+codecId)}}},{key:'_parseAVCVideoPacket',value:function(arrayBuffer,dataOffset,dataSize,tagTimestamp,tagPosition,frameType){if(4>dataSize)return void _logger2.default.w(this.TAG,'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');var le=this._littleEndian,v=new DataView(arrayBuffer,dataOffset,dataSize),packetType=v.getUint8(0),cts_unsigned=16777215&v.getUint32(0,!le);if(0===packetType)this._parseAVCDecoderConfigurationRecord(arrayBuffer,dataOffset+4,dataSize-4);else if(1===packetType)this._parseAVCVideoData(arrayBuffer,dataOffset+4,dataSize-4,tagTimestamp,tagPosition,frameType,cts_unsigned<<8>>8);else if(2===packetType);else return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: Invalid video packet type '+packetType)}},{key:'_parseAVCDecoderConfigurationRecord',value:function(arrayBuffer,dataOffset,dataSize){if(7>dataSize)return void _logger2.default.w(this.TAG,'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');var meta=this._videoMetadata,track=this._videoTrack,le=this._littleEndian,v=new DataView(arrayBuffer,dataOffset,dataSize);meta?'undefined'!=typeof meta.avcc&&_logger2.default.w(this.TAG,'Found another AVCDecoderConfigurationRecord!'):(!1===this._hasVideo&&!1===this._hasVideoFlagOverrided&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),meta=this._videoMetadata={},meta.type='video',meta.id=track.id,meta.timescale=this._timescale,meta.duration=this._duration);var version=v.getUint8(0),avcProfile=v.getUint8(1),profileCompatibility=v.getUint8(2),avcLevel=v.getUint8(3);if(1!==version||0===avcProfile)return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: Invalid AVCDecoderConfigurationRecord');if(this._naluLengthSize=(3&v.getUint8(4))+1,3!==this._naluLengthSize&&4!==this._naluLengthSize)return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: Strange NaluLengthSizeMinusOne: '+(this._naluLengthSize-1));var spsCount=31&v.getUint8(5);if(0==spsCount)return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');1<spsCount&&_logger2.default.w(this.TAG,'Flv: Strange AVCDecoderConfigurationRecord: SPS Count = '+spsCount);for(var offset=6,i=0,len;i<spsCount;i++)if(len=v.getUint16(offset,!le),offset+=2,0!==len){var sps=new Uint8Array(arrayBuffer,dataOffset+offset,len);offset+=len;var config=_spsParser2.default.parseSPS(sps);if(0===i){meta.codecWidth=config.codec_size.width,meta.codecHeight=config.codec_size.height,meta.presentWidth=config.present_size.width,meta.presentHeight=config.present_size.height,meta.profile=config.profile_string,meta.level=config.level_string,meta.bitDepth=config.bit_depth,meta.chromaFormat=config.chroma_format,meta.sarRatio=config.sar_ratio,meta.frameRate=config.frame_rate,(!1===config.frame_rate.fixed||0===config.frame_rate.fps_num||0===config.frame_rate.fps_den)&&(meta.frameRate=this._referenceFrameRate);var fps_den=meta.frameRate.fps_den,fps_num=meta.frameRate.fps_num;meta.refSampleDuration=meta.timescale*(fps_den/fps_num);for(var codecArray=sps.subarray(1,4),codecString='avc1.',j=0,h;3>j;j++)h=codecArray[j].toString(16),2>h.length&&(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.refFrames=config.ref_frames,mi.chromaFormat=config.chroma_format_string,mi.sarNum=meta.sarRatio.width,mi.sarDen=meta.sarRatio.height,mi.videoCodec=codecString,mi.hasAudio?null!=mi.audioCodec&&(mi.mimeType='video/x-flv; codecs="'+mi.videoCodec+','+mi.audioCodec+'"'):mi.mimeType='video/x-flv; codecs="'+mi.videoCodec+'"',mi.isComplete()&&this._onMediaInfo(mi)}}var ppsCount=v.getUint8(offset);if(0===ppsCount)return void this._onError(_demuxErrors2.default.FORMAT_ERROR,'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');1<ppsCount&&_logger2.default.w(this.TAG,'Flv: Strange AVCDecoderConfigurationRecord: PPS Count = '+ppsCount),offset++;for(var _i=0,_len;_i<ppsCount;_i++)(_len=v.getUint16(offset,!le),offset+=2,0!==_len)&&(offset+=_len);meta.avcc=new Uint8Array(dataSize),meta.avcc.set(new Uint8Array(arrayBuffer,dataOffset,dataSize),0),_logger2.default.v(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',meta)}},{key:'_parseAVCVideoData',value:function(arrayBuffer,dataOffset,dataSize,tagTimestamp,tagPosition,frameType,cts){for(var le=this._littleEndian,v=new DataView(arrayBuffer,dataOffset,dataSize),units=[],length=0,offset=0,lengthSize=this._naluLengthSize,dts=this._timestampBase+tagTimestamp,keyframe=1===frameType;offset<dataSize;){if(offset+4>=dataSize){_logger2.default.w(this.TAG,'Malformed Nalu near timestamp '+dts+', offset = '+offset+', dataSize = '+dataSize);break}var naluSize=v.getUint32(offset,!le);if(3===lengthSize&&(naluSize>>>=8),naluSize>dataSize-lengthSize)return void _logger2.default.w(this.TAG,'Malformed Nalus near timestamp '+dts+', NaluSize > DataSize!');var unitType=31&v.getUint8(offset+lengthSize);5==unitType&&(keyframe=!0);var data=new Uint8Array(arrayBuffer,dataOffset+offset,lengthSize+naluSize);units.push({type:unitType,data:data}),length+=data.byteLength,offset+=lengthSize+naluSize}if(units.length){var track=this._videoTrack,avcSample={units:units,length:length,isKeyframe:keyframe,dts:dts,cts:cts,pts:dts+cts};keyframe&&(avcSample.fileposition=tagPosition),track.samples.push(avcSample),track.length+=length}}},{key:'onTrackMetadata',get:function(){return this._onTrackMetadata},set:function(callback){this._onTrackMetadata=callback}},{key:'onMediaInfo',get:function(){return this._onMediaInfo},set:function(callback){this._onMediaInfo=callback}},{key:'onMetaDataArrived',get:function(){return this._onMetaDataArrived},set:function(callback){this._onMetaDataArrived=callback}},{key:'onScriptDataArrived',get:function(){return this._onScriptDataArrived},set:function(callback){this._onScriptDataArrived=callback}},{key:'onStreamDataArrived',get:function(){return this._onStreamDataArrived},set:function(callback){this._onStreamDataArrived=callback}},{key:'onError',get:function(){return this._onError},set:function(callback){this._onError=callback}},{key:'onDataAvailable',get:function(){return this._onDataAvailable},set:function(callback){this._onDataAvailable=callback}},{key:'timestampBase',get:function(){return this._timestampBase},set:function(base){this._timestampBase=base}},{key:'overridedDuration',get:function(){return this._duration},set:function(duration){this._durationOverrided=!0,this._duration=duration,this._mediaInfo.duration=duration}},{key:'overridedHasAudio',set:function(hasAudio){this._hasAudioFlagOverrided=!0,this._hasAudio=hasAudio,this._mediaInfo.hasAudio=hasAudio}},{key:'overridedHasVideo',set:function(hasVideo){this._hasVideoFlagOverrided=!0,this._hasVideo=hasVideo,this._mediaInfo.hasVideo=hasVideo}}],[{key:'probe',value:function(buffer){var data=new Uint8Array(buffer),mismatch={match:!1};if(70!==data[0]||76!==data[1]||86!==data[2]||1!==data[3])return mismatch;var hasAudio=0!=(4&data[4])>>>2,hasVideo=0!=(1&data[4]),offset=ReadBig32(data,5);return 9>offset?mismatch:{match:!0,consumed:offset,dataOffset:offset,hasAudioTrack:hasAudio,hasVideoTrack:hasVideo}}}]),FLVDemuxer}();exports.default=FLVDemuxer},{'../core/media-info.js':7,'../utils/exception.js':40,'../utils/logger.js':41,'./amf-parser.js':15,'./demux-errors.js':16,'./sps-parser.js':19}],19:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_expGolomb=_dereq_('./exp-golomb.js'),_expGolomb2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_expGolomb),SPSParser=function(){function SPSParser(){_classCallCheck(this,SPSParser)}return _createClass(SPSParser,null,[{key:'_ebsp2rbsp',value:function(uint8array){for(var src=uint8array,src_length=src.byteLength,dst=new Uint8Array(src_length),dst_idx=0,i=0;i<src_length;i++)2<=i&&3===src[i]&&0===src[i-1]&&0===src[i-2]||(dst[dst_idx]=src[i],dst_idx++);return new Uint8Array(dst.buffer,0,dst_idx)}},{key:'parseSPS',value:function(uint8array){var rbsp=SPSParser._ebsp2rbsp(uint8array),gb=new _expGolomb2.default(rbsp);gb.readByte();var profile_idc=gb.readByte();gb.readByte();var level_idc=gb.readByte();gb.readUEG();
1var profile_string=SPSParser.getProfileString(profile_idc),level_string=SPSParser.getLevelString(level_idc),chroma_format_idc=1,chroma_format=420,bit_depth=8;if((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===profile_idc)&&(chroma_format_idc=gb.readUEG(),3===chroma_format_idc&&gb.readBits(1),3>=chroma_format_idc&&(chroma_format=[0,420,422,444][chroma_format_idc]),bit_depth=gb.readUEG()+8,gb.readUEG(),gb.readBits(1),gb.readBool()))for(var scaling_list_count=3===chroma_format_idc?12:8,i=0;i<scaling_list_count;i++)gb.readBool()&&(6>i?SPSParser._skipScalingList(gb,16):SPSParser._skipScalingList(gb,64));gb.readUEG();var pic_order_cnt_type=gb.readUEG();if(0===pic_order_cnt_type)gb.readUEG();else if(1===pic_order_cnt_type){gb.readBits(1),gb.readSEG(),gb.readSEG();for(var num_ref_frames_in_pic_order_cnt_cycle=gb.readUEG(),_i=0;_i<num_ref_frames_in_pic_order_cnt_cycle;_i++)gb.readSEG()}var ref_frames=gb.readUEG();gb.readBits(1);var pic_width_in_mbs_minus1=gb.readUEG(),pic_height_in_map_units_minus1=gb.readUEG(),frame_mbs_only_flag=gb.readBits(1);0===frame_mbs_only_flag&&gb.readBits(1),gb.readBits(1);var frame_crop_left_offset=0,frame_crop_right_offset=0,frame_crop_top_offset=0,frame_crop_bottom_offset=0,frame_cropping_flag=gb.readBool();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,fps=0,fps_fixed=!0,fps_num=0,fps_den=0,vui_parameters_present_flag=gb.readBool();if(vui_parameters_present_flag){if(gb.readBool()){var aspect_ratio_idc=gb.readByte();0<aspect_ratio_idc&&16>aspect_ratio_idc?(sar_width=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][aspect_ratio_idc-1],sar_height=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][aspect_ratio_idc-1]):255===aspect_ratio_idc&&(sar_width=gb.readByte()<<8|gb.readByte(),sar_height=gb.readByte()<<8|gb.readByte())}if(gb.readBool()&&gb.readBool(),gb.readBool()&&(gb.readBits(4),gb.readBool()&&gb.readBits(24)),gb.readBool()&&(gb.readUEG(),gb.readUEG()),gb.readBool()){var num_units_in_tick=gb.readBits(32),time_scale=gb.readBits(32);fps_fixed=gb.readBool(),fps_num=time_scale,fps_den=2*num_units_in_tick,fps=fps_num/fps_den}}var sarScale=1;(1!==sar_width||1!==sar_height)&&(sarScale=sar_width/sar_height);var crop_unit_x=0,crop_unit_y=0;if(0===chroma_format_idc)crop_unit_x=1,crop_unit_y=2-frame_mbs_only_flag;else{var sub_wc=3===chroma_format_idc?1:2,sub_hc=1===chroma_format_idc?2:1;crop_unit_x=sub_wc,crop_unit_y=sub_hc*(2-frame_mbs_only_flag)}var codec_width=16*(pic_width_in_mbs_minus1+1),codec_height=(2-frame_mbs_only_flag)*(16*(pic_height_in_map_units_minus1+1));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);return gb.destroy(),gb=null,{profile_string:profile_string,level_string:level_string,bit_depth:bit_depth,ref_frames:ref_frames,chroma_format:chroma_format,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(gb,count){for(var last_scale=8,next_scale=8,delta_scale=0,i=0;i<count;i++)0!=next_scale&&(delta_scale=gb.readSEG(),next_scale=(last_scale+delta_scale+256)%256),last_scale=0==next_scale?last_scale:next_scale}},{key:'getProfileString',value:function(profile_idc){return 66===profile_idc?'Baseline':77===profile_idc?'Main':88===profile_idc?'Extended':100===profile_idc?'High':110===profile_idc?'High10':122===profile_idc?'High422':244===profile_idc?'High444':'Unknown'}},{key:'getLevelString',value:function(level_idc){return(level_idc/10).toFixed(1)}},{key:'getChromaFormatString',value:function(chroma){return 420===chroma?'4:2:0':422===chroma?'4:2:2':444===chroma?'4:4:4':'Unknown'}}]),SPSParser}();exports.default=SPSParser},{'./exp-golomb.js':17}],20:[function(_dereq_,module,exports){'use strict';function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj}
1,_polyfill=_dereq_('./utils/polyfill.js'),_polyfill2=_interopRequireDefault(_polyfill),_features=_dereq_('./core/features.js'),_features2=_interopRequireDefault(_features),_loader=_dereq_('./io/loader.js'),_flvPlayer=_dereq_('./player/flv-player.js'),_flvPlayer2=_interopRequireDefault(_flvPlayer),_nativePlayer=_dereq_('./player/native-player.js'),_nativePlayer2=_interopRequireDefault(_nativePlayer),_playerEvents=_dereq_('./player/player-events.js'),_playerEvents2=_interopRequireDefault(_playerEvents),_playerErrors=_dereq_('./player/player-errors.js'),_loggingControl=_dereq_('./utils/logging-control.js'),_loggingControl2=_interopRequireDefault(_loggingControl),_exception=_dereq_('./utils/exception.js');_polyfill2.default.install();var flvjs={};flvjs.createPlayer=function(mediaDataSource,optionalConfig){var mds=mediaDataSource;if(null==mds||'object'!==('undefined'==typeof mds?'undefined':_typeof(mds)))throw new _exception.InvalidArgumentException('MediaDataSource must be an javascript object!');if(!mds.hasOwnProperty('type'))throw new _exception.InvalidArgumentException('MediaDataSource must has type field to indicate video file type!');switch(mds.type){case'flv':return new _flvPlayer2.default(mds,optionalConfig);default:return new _nativePlayer2.default(mds,optionalConfig);}},flvjs.isSupported=function(){return _features2.default.supportMSEH264Playback()},flvjs.getFeatureList=function(){return _features2.default.getFeatureList()},flvjs.BaseLoader=_loader.BaseLoader,flvjs.LoaderStatus=_loader.LoaderStatus,flvjs.LoaderErrors=_loader.LoaderErrors,flvjs.Events=_playerEvents2.default,flvjs.ErrorTypes=_playerErrors.ErrorTypes,flvjs.ErrorDetails=_playerErrors.ErrorDetails,flvjs.FlvPlayer=_flvPlayer2.default,flvjs.NativePlayer=_nativePlayer2.default,flvjs.LoggingControl=_loggingControl2.default,Object.defineProperty(flvjs,'version',{enumerable:!0,get:function(){return'1.5.0'}}),exports.default=flvjs},{'./core/features.js':6,'./io/loader.js':24,'./player/flv-player.js':32,'./player/native-player.js':33,'./player/player-errors.js':34,'./player/player-events.js':35,'./utils/exception.js':40,'./utils/logging-control.js':42,'./utils/polyfill.js':43}],21:[function(_dereq_,module){'use strict';module.exports=_dereq_('./flv.js').default},{'./flv.js':20}],22:[function(_dereq_,module,exports){'use strict';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&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===void 0){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if('value'in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_browser=_dereq_('../utils/browser.js'),_browser2=_interopRequireDefault(_browser),_loader=_dereq_('./loader.js'),_exception=_dereq_('../utils/exception.js'),FetchStream
1Loader=function(_BaseLoader){function FetchStreamLoader(seekHandler,config){_classCallCheck(this,FetchStreamLoader);var _this=_possibleConstructorReturn(this,(FetchStreamLoader.__proto__||Object.getPrototypeOf(FetchStreamLoader)).call(this,'fetch-stream-loader'));return _this.TAG='FetchStreamLoader',_this._seekHandler=seekHandler,_this._config=config,_this._needStash=!0,_this._requestAbort=!1,_this._contentLength=null,_this._receivedLength=0,_this}return _inherits(FetchStreamLoader,_BaseLoader),_createClass(FetchStreamLoader,null,[{key:'isSupported',value:function(){try{var isWorkWellEdge=_browser2.default.msedge&&15048<=_browser2.default.version.minor,browserNotBlacklisted=!_browser2.default.msedge||isWorkWellEdge;return self.fetch&&self.ReadableStream&&browserNotBlacklisted}catch(e){return!1}}}]),_createClass(FetchStreamLoader,[{key:'destroy',value:function(){this.isWorking()&&this.abort(),_get(FetchStreamLoader.prototype.__proto__||Object.getPrototypeOf(FetchStreamLoader.prototype),'destroy',this).call(this)}},{key:'open',value:function(dataSource,range){var _this2=this;this._dataSource=dataSource,this._range=range;var sourceURL=dataSource.url;this._config.reuseRedirectedURL&&void 0!=dataSource.redirectedURL&&(sourceURL=dataSource.redirectedURL);var seekConfig=this._seekHandler.getConfig(sourceURL,range),headers=new self.Headers;if('object'===_typeof(seekConfig.headers)){var configHeaders=seekConfig.headers;for(var key in configHeaders)configHeaders.hasOwnProperty(key)&&headers.append(key,configHeaders[key])}var params={method:'GET',headers:headers,mode:'cors',cache:'default',referrerPolicy:'no-referrer-when-downgrade'};if('object'===_typeof(this._config.headers))for(var _key in this._config.headers)headers.append(_key,this._config.headers[_key]);!1===dataSource.cors&&(params.mode='same-origin'),dataSource.withCredentials&&(params.credentials='include'),dataSource.referrerPolicy&&(params.referrerPolicy=dataSource.referrerPolicy),this._status=_loader.LoaderStatus.kConnecting,self.fetch(seekConfig.url,params).then(function(res){if(_this2._requestAbort)return _this2._requestAbort=!1,void(_this2._status=_loader.LoaderStatus.kIdle);if(res.ok&&200<=res.status&&299>=res.status){if(res.url!==seekConfig.url&&_this2._onURLRedirect){var redirectedURL=_this2._seekHandler.removeURLParameters(res.url);_this2._onURLRedirect(redirectedURL)}var lengthHeader=res.headers.get('Content-Length');return null!=lengthHeader&&(_this2._contentLength=parseInt(lengthHeader),0!==_this2._contentLength&&_this2._onContentLengthKnown&&_this2._onContentLengthKnown(_this2._contentLength)),_this2._pump.call(_this2,res.body.getReader())}if(_this2._status=_loader.LoaderStatus.kError,_this2._onError)_this2._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:res.status,msg:res.statusText});else throw new _exception.RuntimeException('FetchStreamLoader: Http code invalid, '+res.status+' '+res.statusText)}).catch(function(e){if(_this2._status=_loader.LoaderStatus.kError,_this2._onError)_this2._onError(_loader.LoaderErrors.EXCEPTION,{code:-1,msg:e.message});else throw e})}},{key:'abort',value:function(){this._requestAbort=!0}},{key:'_pump',value:function(reader){var _this3=this;return reader.read().then(function(result){if(!result.done){if(!0===_this3._requestAbort)return _this3._requestAbort=!1,_this3._status=_loader.LoaderStatus.kComplete,reader.cancel();_this3._status=_loader.LoaderStatus.kBuffering;var chunk=result.value.buffer,byteStart=_this3._range.from+_this3._receivedLength;_this3._receivedLength+=chunk.byteLength,_this3._onDataArrival&&_this3._onDataArrival(chunk,byteStart,_this3._receivedLength),_this3._pump(reader)}else if(null!==_this3._contentLength&&_this3._receivedLength<_this3._contentLength){_this3._status=_loader.LoaderStatus.kError;var type=_loader.LoaderErrors.EARLY_EOF,info={code:-1,msg:'Fetch stream meet Early-EOF'};if(_this3._onError)_this3._onError(type,info);else throw new _exception.RuntimeException(info.msg)}else _this3._status=_loader.LoaderStatus.kComplete,_this3._onComplete&&_this3._onComplete(_this3._range.from,_this3._range.from+_this3._receivedLength-1)}).catch(function(e){if(!(11===e.code&&_browser2.default.msedge)){_this3._status=_loader.LoaderStatus.kError;var type=0,info=null;if((19===e.code||'network error'===e.message)&&(null===_this3._contentLength||null!==_this3._contentLength&&_this3._receivedLength<_this3._contentLength)?(type=_loader.LoaderErrors.EARLY_EOF,info={code:e.code,msg:'Fetch stream meet Early-EOF'}):(type=_loader.LoaderErrors.EXCEPTION,info={code:e.code,msg:e.message}),_this3._onError)_this3._onError(type,info);else throw new _exception.RuntimeException(info.msg)}})}}
1]),FetchStreamLoader}(_loader.BaseLoader);exports.default=FetchStreamLoader},{'../utils/browser.js':39,'../utils/exception.js':40,'../utils/logger.js':41,'./loader.js':24}],23:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_speedSampler=_dereq_('./speed-sampler.js'),_speedSampler2=_interopRequireDefault(_speedSampler),_loader=_dereq_('./loader.js'),_fetchStreamLoader=_dereq_('./fetch-stream-loader.js'),_fetchStreamLoader2=_interopRequireDefault(_fetchStreamLoader),_xhrMozChunkedLoader=_dereq_('./xhr-moz-chunked-loader.js'),_xhrMozChunkedLoader2=_interopRequireDefault(_xhrMozChunkedLoader),_xhrMsstreamLoader=_dereq_('./xhr-msstream-loader.js'),_xhrMsstreamLoader2=_interopRequireDefault(_xhrMsstreamLoader),_xhrRangeLoader=_dereq_('./xhr-range-loader.js'),_xhrRangeLoader2=_interopRequireDefault(_xhrRangeLoader),_websocketLoader=_dereq_('./websocket-loader.js'),_websocketLoader2=_interopRequireDefault(_websocketLoader),_rangeSeekHandler=_dereq_('./range-seek-handler.js'),_rangeSeekHandler2=_interopRequireDefault(_rangeSeekHandler),_paramSeekHandler=_dereq_('./param-seek-handler.js'),_paramSeekHandler2=_interopRequireDefault(_paramSeekHandler),_exception=_dereq_('../utils/exception.js'),IOController=function(){function IOController(dataSource,config,extraData){_classCallCheck(this,IOController),this.TAG='IOController',this._config=config,this._extraData=extraData,this._stashInitialSize=393216,void 0!=config.stashInitialSize&&0<config.stashInitialSize&&(this._stashInitialSize=config.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=3145728,this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,!1===config.enableStashBuffer&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=dataSource,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(dataSource.url),this._refTotalLength=dataSource.filesize?dataSource.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new _speedSampler2.default,this._speedNormalizeList=[64,128,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}return _createClass(IOController,[{key:'destroy',value:function(){this._loader.isWorking()&&this._loader.abort(),this._loader.destroy(),this._loader=null,this._loaderClass=null,this._dataSource=null,this._stashBuffer=null,this._stashUsed=this._stashSize=this._bufferSize=this._stashByteStart=0,this._currentRange=null,this._speedSampler=null,this._isEarlyEofReconnecting=!1,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._extraData=null}},{key:'isWorking',value:function(){return this._loader&&this._loader.isWorking()&&!this._paused}},{key:'isPaused',value:function(){return this._paused}},{key:'_selectSeekHandler',value:function(){var config=this._config;if('range'===config.seekType)this._seekHandler=new _rangeSeekHandler2.default(this._config.rangeLoadZeroStart);else if('param'===config.seekType){var paramStart=config.seekParamStart||'bstart',paramEnd=config.seekParamEnd||'bend';this._seekHandler=new _paramSeekHandler2.default(paramStart,paramEnd)}else if('custom'===config.seekType){if('function'!=typeof config.customSeekHandler)throw new _exception.InvalidArgumentException('Custom seekType specified in config but invalid customSeekHandler!');this._seekHandler=new config.customSeekHandler}else throw new _exception.InvalidArgumentException('Invalid seekType in config: '+config.seekType)}},{key:'_selectLoader',value:function(){if(null!=this._config.customLoader)this._loaderClass=this._config.customLoader;else if(this._isWebSocketURL)this._loaderClass=_websocketLoader2.default;
1else if(_fetchStreamLoader2.default.isSupported())this._loaderClass=_fetchStreamLoader2.default;else if(_xhrMozChunkedLoader2.default.isSupported())this._loaderClass=_xhrMozChunkedLoader2.default;else if(_xhrRangeLoader2.default.isSupported())this._loaderClass=_xhrRangeLoader2.default;else throw new _exception.RuntimeException('Your browser doesn\'t support xhr with arraybuffer responseType!')}},{key:'_createLoader',value:function(){this._loader=new this._loaderClass(this._seekHandler,this._config),!1===this._loader.needStashBuffer&&(this._enableStash=!1),this._loader.onContentLengthKnown=this._onContentLengthKnown.bind(this),this._loader.onURLRedirect=this._onURLRedirect.bind(this),this._loader.onDataArrival=this._onLoaderChunkArrival.bind(this),this._loader.onComplete=this._onLoaderComplete.bind(this),this._loader.onError=this._onLoaderError.bind(this)}},{key:'open',value:function(optionalFrom){this._currentRange={from:0,to:-1},optionalFrom&&(this._currentRange.from=optionalFrom),this._speedSampler.reset(),optionalFrom||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))}},{key:'abort',value:function(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)}},{key:'pause',value:function(){this.isWorking()&&(this._loader.abort(),0===this._stashUsed?this._resumeFrom=this._currentRange.to+1:(this._resumeFrom=this._stashByteStart,this._currentRange.to=this._stashByteStart-1),this._stashUsed=0,this._stashByteStart=0,this._paused=!0)}},{key:'resume',value:function(){if(this._paused){this._paused=!1;var bytes=this._resumeFrom;this._resumeFrom=0,this._internalSeek(bytes,!0)}}},{key:'seek',value:function(bytes){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(bytes,!0)}},{key:'_internalSeek',value:function(bytes,dropUnconsumed){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(dropUnconsumed),this._loader.destroy(),this._loader=null;var requestRange={from:bytes,to:-1};this._currentRange={from:requestRange.from,to:-1},this._speedSampler.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,requestRange),this._onSeeked&&this._onSeeked()}},{key:'updateUrl',value:function(url){if(!url||'string'!=typeof url||0===url.length)throw new _exception.InvalidArgumentException('Url must be a non-empty string!');this._dataSource.url=url}},{key:'_expandBuffer',value:function(expectedBytes){for(var bufferNewSize=this._stashSize;bufferNewSize+1048576<expectedBytes;)bufferNewSize*=2;if(bufferNewSize+=1048576,bufferNewSize!==this._bufferSize){var newBuffer=new ArrayBuffer(bufferNewSize);if(0<this._stashUsed){var stashOldArray=new Uint8Array(this._stashBuffer,0,this._stashUsed),stashNewArray=new Uint8Array(newBuffer,0,bufferNewSize);stashNewArray.set(stashOldArray,0)}this._stashBuffer=newBuffer,this._bufferSize=bufferNewSize}}},{key:'_normalizeSpeed',value:function(input){var list=this._speedNormalizeList,last=list.length-1,mid=0,lbound=0,ubound=last;if(input<list[0])return list[0];for(;lbound<=ubound;){if(mid=lbound+Math.floor((ubound-lbound)/2),mid==last||input>=list[mid]&&input<list[mid+1])return list[mid];list[mid]<input?lbound=mid+1:ubound=mid-1}}},{key:'_adjustStashSize',value:function(normalized){var stashSizeKB=0;stashSizeKB=this._config.isLive?normalized:512>normalized?normalized:512<=normalized&&1024>=normalized?Math.floor(1.5*normalized):2*normalized,8192<stashSizeKB&&(stashSizeKB=8192);var bufferSize=1024*stashSizeKB+1048576;this._bufferSize<bufferSize&&this._expandBuffer(bufferSize),this._stashSize=1024*stashSizeKB}},{key:'_dispatchChunks',value:function(chunks,byteStart){return this._currentRange.to=byteStart+chunks.byteLength-1,this._onDataArrival(chunks,byteStart)}},{key:'_onURLRedirect',value:function(redirectedURL){this._redirectedURL=redirectedURL,this._onRedirect&&this._onRedirect(redirectedURL)}},{key:'_onContentLengthKnown',value:function(contentLength){contentLength&&this._fullRequestFlag&&(this._totalLength=contentLength,this._fullRequestFlag=!1)}},{key:'_onLoaderChunkArrival',value:function(chunk,byteStart){if(!this._onDataArrival)throw new _exception.IllegalStateException('IOController: No existing consumer (onDataArrival) callback!');if(!this._paused){this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,this._onRecoveredEarlyEof&&this._onRecoveredEarlyEof()),this._speedSampler.addBytes(chunk.byteLength);var KBps=this._speedSampler.lastSecondKBps;if(0!==KBps){var normalized=this._normalizeSpeed(KBps);this._speedNormalized!==normalized&&(this._speedNormalized=normalized,this._adjustStashSize(normalized))}if(!this._enableStash){if(0===this._stashUsed){var consumed=this._dispatchChunks(chunk,byteStart);if(consumed<chunk.byteLength){var remain=chunk.byteLength-consumed;remain>this._bufferSize&&this._expandBuffer(remain);var stashArray=new Uint8Array(this._stashBuffer,0,this._bufferSize);stashArray.set(new Uint8Array(chunk,consumed),0),this._stashUsed+=remain,this._stashByteStart=byteStart+consumed}}else{this._stashUsed+chunk.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+chunk.byteLength);var _stashArray=new Uint8Array(this._stashBuffer,0,this._bufferSize);_stashArray.set(new Uint8Array(chunk),this._stashUsed),this._stashUsed+=chunk.byteLength;var _consumed=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart);if(_consumed<this._stashUsed&&0<_consumed){var remainArray=new Uint8Array(this._stashBuffer,_consumed);_stashArray.set(remainArray,0)}this._stashUsed-=_consumed,this._stashByteStart+=_consumed}}else if(0===this._stashUsed&&0===this._stashByteStart&&(this._stashByteStart=byteStart),this._stashUsed+chunk.byteLength<=this._stashSize){var _stashArray2=new Uint8Array(this._stashBuffer,0,this._stashSize);_stashArray2.set(new Uint8Array(chunk),this._stashUsed),this._stashUsed+=chunk.byteLength}
1else{var _stashArray3=new Uint8Array(this._stashBuffer,0,this._bufferSize);if(0<this._stashUsed){var buffer=this._stashBuffer.slice(0,this._stashUsed),_consumed2=this._dispatchChunks(buffer,this._stashByteStart);if(!(_consumed2<buffer.byteLength))this._stashUsed=0,this._stashByteStart+=_consumed2;else if(0<_consumed2){var _remainArray=new Uint8Array(buffer,_consumed2);_stashArray3.set(_remainArray,0),this._stashUsed=_remainArray.byteLength,this._stashByteStart+=_consumed2}this._stashUsed+chunk.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+chunk.byteLength),_stashArray3=new Uint8Array(this._stashBuffer,0,this._bufferSize)),_stashArray3.set(new Uint8Array(chunk),this._stashUsed),this._stashUsed+=chunk.byteLength}else{var _consumed3=this._dispatchChunks(chunk,byteStart);if(_consumed3<chunk.byteLength){var _remain=chunk.byteLength-_consumed3;_remain>this._bufferSize&&(this._expandBuffer(_remain),_stashArray3=new Uint8Array(this._stashBuffer,0,this._bufferSize)),_stashArray3.set(new Uint8Array(chunk,_consumed3),0),this._stashUsed+=_remain,this._stashByteStart=byteStart+_consumed3}}}}}},{key:'_flushStashBuffer',value:function(dropUnconsumed){if(0<this._stashUsed){var buffer=this._stashBuffer.slice(0,this._stashUsed),consumed=this._dispatchChunks(buffer,this._stashByteStart),remain=buffer.byteLength-consumed;if(consumed<buffer.byteLength)if(dropUnconsumed)_logger2.default.w(this.TAG,remain+' bytes unconsumed data remain when flush buffer, dropped');else{if(0<consumed){var stashArray=new Uint8Array(this._stashBuffer,0,this._bufferSize),remainArray=new Uint8Array(buffer,consumed);stashArray.set(remainArray,0),this._stashUsed=remainArray.byteLength,this._stashByteStart+=consumed}return 0}return this._stashUsed=0,this._stashByteStart=0,remain}return 0}},{key:'_onLoaderComplete',value:function(){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)}},{key:'_onLoaderError',value:function(type,data){switch(_logger2.default.e(this.TAG,'Loader error, code = '+data.code+', msg = '+data.msg),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,type=_loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF),type){case _loader.LoaderErrors.EARLY_EOF:{if(!this._config.isLive&&this._totalLength){var nextFrom=this._currentRange.to+1;return void(nextFrom<this._totalLength&&(_logger2.default.w(this.TAG,'Connection lost, trying reconnect...'),this._isEarlyEofReconnecting=!0,this._internalSeek(nextFrom,!1)))}type=_loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;break}case _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF:case _loader.LoaderErrors.CONNECTING_TIMEOUT:case _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID:case _loader.LoaderErrors.EXCEPTION:}if(this._onError)this._onError(type,data);else throw new _exception.RuntimeException('IOException: '+data.msg)}},{key:'status',get:function(){return this._loader.status}},{key:'extraData',get:function(){return this._extraData},set:function(data){this._extraData=data}},{key:'onDataArrival',get:function(){return this._onDataArrival},set:function(callback){this._onDataArrival=callback}},{key:'onSeeked',get:function(){return this._onSeeked},set:function(callback){this._onSeeked=callback}},{key:'onError',get:function(){return this._onError},set:function(callback){this._onError=callback}},{key:'onComplete',get:function(){return this._onComplete},set:function(callback){this._onComplete=callback}},{key:'onRedirect',get:function(){return this._onRedirect},set:function(callback){this._onRedirect=callback}},{key:'onRecoveredEarlyEof',get:function(){return this._onRecoveredEarlyEof},set:function(callback){this._onRecoveredEarlyEof=callback}},{key:'currentURL',get:function(){return this._dataSource.url}},{key:'hasRedirect',get:function(){return null!=this._redirectedURL||void 0!=this._dataSource.redirectedURL}},{key:'currentRedirectedURL',get:function(){return this._redirectedURL||this._dataSource.redirectedURL}},{key:'currentSpeed',get:function(){return this._loaderClass===_xhrRangeLoader2.default?this._loader.currentSpeed:this._speedSampler.lastSecondKBps}},{key:'loaderType',get:function(){return this._loader.type}}]),IOController}();exports.default=IOController},{'../utils/exception.js':40,'../utils/logger.js':41,'./fetch-stream-loader.js':22,'./loader.js':24,'./param-seek-handler.js':25,'./range-seek-handler.js':2
16,'./speed-sampler.js':27,'./websocket-loader.js':28,'./xhr-moz-chunked-loader.js':29,'./xhr-msstream-loader.js':30,'./xhr-range-loader.js':31}],24:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0}),exports.BaseLoader=exports.LoaderErrors=exports.LoaderStatus=void 0;var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_exception=_dereq_('../utils/exception.js'),LoaderStatus=exports.LoaderStatus={kIdle:0,kConnecting:1,kBuffering:2,kError:3,kComplete:4},LoaderErrors=exports.LoaderErrors={OK:'OK',EXCEPTION:'Exception',HTTP_STATUS_CODE_INVALID:'HttpStatusCodeInvalid',CONNECTING_TIMEOUT:'ConnectingTimeout',EARLY_EOF:'EarlyEof',UNRECOVERABLE_EARLY_EOF:'UnrecoverableEarlyEof'},BaseLoader=exports.BaseLoader=function(){function BaseLoader(typeName){_classCallCheck(this,BaseLoader),this._type=typeName||'undefined',this._status=LoaderStatus.kIdle,this._needStash=!1,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}return _createClass(BaseLoader,[{key:'destroy',value:function(){this._status=LoaderStatus.kIdle,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}},{key:'isWorking',value:function(){return this._status===LoaderStatus.kConnecting||this._status===LoaderStatus.kBuffering}},{key:'open',value:function(){throw new _exception.NotImplementedException('Unimplemented abstract function!')}},{key:'abort',value:function(){throw new _exception.NotImplementedException('Unimplemented abstract function!')}},{key:'type',get:function(){return this._type}},{key:'status',get:function(){return this._status}},{key:'needStashBuffer',get:function(){return this._needStash}},{key:'onContentLengthKnown',get:function(){return this._onContentLengthKnown},set:function(callback){this._onContentLengthKnown=callback}},{key:'onURLRedirect',get:function(){return this._onURLRedirect},set:function(callback){this._onURLRedirect=callback}},{key:'onDataArrival',get:function(){return this._onDataArrival},set:function(callback){this._onDataArrival=callback}},{key:'onError',get:function(){return this._onError},set:function(callback){this._onError=callback}},{key:'onComplete',get:function(){return this._onComplete},set:function(callback){this._onComplete=callback}}]),BaseLoader}()},{'../utils/exception.js':40}],25:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),ParamSeekHandler=function(){function ParamSeekHandler(paramStart,paramEnd){_classCallCheck(this,ParamSeekHandler),this._startName=paramStart,this._endName=paramEnd}return _createClass(ParamSeekHandler,[{key:'getConfig',value:function(baseUrl,range){var url=baseUrl;if(0!==range.from||-1!==range.to){var needAnd=!0;-1===url.indexOf('?')&&(url+='?',needAnd=!1),needAnd&&(url+='&'),url+=this._startName+'='+range.from.toString(),-1!==range.to&&(url+='&'+this._endName+'='+range.to.toString())}return{url:url,headers:{}}}},{key:'removeURLParameters',value:function(seekedURL){var baseURL=seekedURL.split('?')[0],params=void 0,queryIndex=seekedURL.indexOf('?');-1!==queryIndex&&(params=seekedURL.substring(queryIndex+1));var resultParams='';if(void 0!=params&&0<params.length)for(var pairs=params.split('&'),i=0;i<pairs.length;i++){var pair=pairs[i].split('='),requireAnd=0<i;pair[0]!==this._startName&&pair[0]!==this._endName&&(requireAnd&&(resultParams+='&'),resultParams+=pairs[i])}return 0===resultParams.length?baseURL:baseURL+'?'+resultParams}}]),ParamSeekHandler}();exports.default=ParamSeekHandler},{}],26:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),RangeSeekHandler=function(){function RangeSeekHandler(zeroStart){_classCallCheck(this,RangeSeekHandler),this._zeroStart=zeroStart||!1}return _createClass(RangeSeekHandler,[{key:'getConfig',value:function(url,range){var headers={};if(0!==range.from||-1!==range.to){var param;param=-1===range.to?'bytes='+range.from.toString()+'-':'bytes='+range.from.toString()+'-'+range.to.toString(),headers.Range=param}else this._zeroStart&&(headers.Range='bytes=0-');return{url:url,headers:headers}}},{key:'removeURLParameters',value:function(seekedURL){return seekedURL}}]),RangeSeekHandler}();exports.default=RangeSeekHandler},{}],27:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),SpeedSampler=function(){function SpeedSampler(){_classCallCheck(this,SpeedSampler),this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,this._now=self.performance&&self.performance.now?self.performance.now.bind(self.performance):Date.now}
1return _createClass(SpeedSampler,[{key:'reset',value:function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0}},{key:'addBytes',value:function(bytes){0===this._firstCheckpoint?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=bytes,this._totalBytes+=bytes):1e3>this._now()-this._lastCheckpoint?(this._intervalBytes+=bytes,this._totalBytes+=bytes):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=bytes,this._totalBytes+=bytes,this._lastCheckpoint=this._now())}},{key:'currentKBps',get:function(){this.addBytes(0);var durationSeconds=(this._now()-this._lastCheckpoint)/1e3;return 0==durationSeconds&&(durationSeconds=1),this._intervalBytes/durationSeconds/1024}},{key:'lastSecondKBps',get:function(){return this.addBytes(0),0===this._lastSecondBytes?500<=this._now()-this._lastCheckpoint?this.currentKBps:0:this._lastSecondBytes/1024}},{key:'averageKBps',get:function(){var durationSeconds=(this._now()-this._firstCheckpoint)/1e3;return this._totalBytes/durationSeconds/1024}}]),SpeedSampler}();exports.default=SpeedSampler},{}],28:[function(_dereq_,module,exports){'use strict';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&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}Object.defineProperty(exports,'__esModule',{value:!0});var _get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===void 0){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if('value'in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_logger),_loader=_dereq_('./loader.js'),_exception=_dereq_('../utils/exception.js'),WebSocketLoader=function(_BaseLoader){function WebSocketLoader(){_classCallCheck(this,WebSocketLoader);var _this=_possibleConstructorReturn(this,(WebSocketLoader.__proto__||Object.getPrototypeOf(WebSocketLoader)).call(this,'websocket-loader'));return _this.TAG='WebSocketLoader',_this._needStash=!0,_this._ws=null,_this._requestAbort=!1,_this._receivedLength=0,_this}return _inherits(WebSocketLoader,_BaseLoader),_createClass(WebSocketLoader,null,[{key:'isSupported',value:function(){try{return'undefined'!=typeof self.WebSocket}catch(e){return!1}}}]),_createClass(WebSocketLoader,[{key:'destroy',value:function(){this._ws&&this.abort(),_get(WebSocketLoader.prototype.__proto__||Object.getPrototypeOf(WebSocketLoader.prototype),'destroy',this).call(this)}},{key:'open',value:function(dataSource){try{var ws=this._ws=new self.WebSocket(dataSource.url);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),this._status=_loader.LoaderStatus.kConnecting}catch(e){this._status=_loader.LoaderStatus.kError;var info={code:e.code,msg:e.message};if(this._onError)this._onError(_loader.LoaderErrors.EXCEPTION,info);else throw new _exception.RuntimeException(info.msg)}}},{key:'abort',value:function(){var ws=this._ws;ws&&(0===ws.readyState||1===ws.readyState)&&(this._requestAbort=!0,ws.close()),this._ws=null,this._status=_loader.LoaderStatus.kComplete}},{key:'_onWebSocketOpen',value:function(){this._status=_loader.LoaderStatus.kBuffering}},{key:'_onWebSocketClose',value:function(){return!0===this._requestAbort?void(this._requestAbort=!1):void(this._status=_loader.LoaderStatus.kComplete,this._onComplete&&this._onComplete(0,this._receivedLength-1))}},{key:'_onWebSocketMessage',value:function(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{this._status=_loader.LoaderStatus.kError;var info={code:-1,msg:'Unsupported WebSocket message type: '+e.data.constructor.name};if(this._onError)this._onError(_loader.LoaderErrors.EXCEPTION,info);else throw new _exception.RuntimeException(info.msg)}}},{key:'_dispatchArrayBuffer',value:function(arraybuffer){var chunk=arraybuffer,byteStart=this._receivedLength;this._receivedLength+=chunk.byteLength,this._onDataArrival&&this._onDataArrival(chunk,byteStart,this._receivedLength)}},{key:'_onWebSocketError',value:function(e){this._status=_loader.LoaderStatus.kError;var info={code:e.code,msg:e.message};if(this._onError)this._onError(_loader.LoaderErrors.EXCEPTION,info);else throw new _exception.RuntimeException(info.msg)}}]),WebSocketLoader}(_loader.BaseLoader);exports.default=WebSocketLoader},{'../utils/exception.js':40,'../utils/logger.js':41,'./loader.js':24}],29:[function(_dereq_,module,exports){'use strict';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&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===void 0){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if('value'in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_logger),_loader=_dereq_('./loader.js'),_exception=_dereq_('../utils/exception.js'),MozChunkedLoader=function(_BaseLoader){function MozChunkedLoader(seekHandler,config){_classCallCheck(this,MozChunkedLoader);var _this=_possibleConstructorReturn(this,(MozChunkedLoader.__proto__||Object.getPrototypeOf(MozChunkedLoader)).call(this,'xhr-moz-chunked-loader'));return _this.TAG='MozChunkedLoader',_this._seekHandler=seekHandler,_this._config=config,_this._needStash=!0,_this._xhr=null,_this._requestAbort=!1,_this._contentLength=null,_this._receivedLength=0,_this}return _inherits(MozChunkedLoader,_BaseLoader),_createClass(MozChunkedLoader,null,[{key:'isSupported',value:function(){try{var xhr=new XMLHttpRequest;return xhr.open('GET','https://example.com',!0),xhr.responseType='moz-chunked-arraybuffer','moz-chunked-arraybuffer'===xhr.responseType}catch(e){return _logger2.default.w('MozChunkedLoader',e.message),!1}}}]),_createClass(MozChunkedLoader,[{key:'destroy',value:function(){this.isWorking()&&this.abort(),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onloadend=null,this._xhr.onerror=null,this._xhr=null),_get(MozChunkedLoader.prototype.__proto__||Object.getPrototypeOf(MozChunkedLoader.prototype),'destroy',this).call(this)}},{key:'open',value:function(dataSource,range){this._dataSource=dataSource,this._range=range;var sourceURL=dataSource.url;this._config.reuseRedirectedURL&&void 0!=dataSource.redirectedURL&&(sourceURL=dataSource.redirectedURL);var seekConfig=this._seekHandler.getConfig(sourceURL,range);this._requestURL=seekConfig.url;var xhr=this._xhr=new XMLHttpRequest;if(xhr.open('GET',seekConfig.url,!0),xhr.responseType='moz-chunked-arraybuffer',xhr.onreadystatechange=this._onReadyStateChange.bind(this),xhr.onprogress=this._onProgress.bind(this),xhr.onloadend=this._onLoadEnd.bind(this),xhr.onerror=this._onXhrError.bind(this),dataSource.withCredentials&&(xhr.withCredentials=!0),'object'===_typeof(seekConfig.headers)){var headers=seekConfig.headers;for(var key in headers)headers.hasOwnProperty(key)&&xhr.setRequestHeader(key,headers[key])}if('object'===_typeof(this._config.headers)){var _headers=this._config.headers;for(var _key in _headers)_headers.hasOwnProperty(_key)&&xhr.setRequestHeader(_key,_headers[_key])}this._status=_loader.LoaderStatus.kConnecting,xhr.send()}},{key:'abort',value:function(){this._requestAbort=!0,this._xhr&&this._xhr.abort(),this._status=_loader.LoaderStatus.kComplete}},{key:'_onReadyStateChange',value:function(e){var xhr=e.target;if(2===xhr.readyState){if(void 0!=xhr.responseURL&&xhr.responseURL!==this._requestURL&&this._onURLRedirect){var redirectedURL=this._seekHandler.removeURLParameters(xhr.responseURL);this._onURLRedirect(redirectedURL)}if(!(0!==xhr.status&&(200>xhr.status||299<xhr.status)))this._status=_loader.LoaderStatus.kBuffering;else if(this._status=_loader.LoaderStatus.kError,this._onError)this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:xhr.status,msg:xhr.statusText});else throw new _exception.RuntimeException('MozChunkedLoader: Http code invalid, '+xhr.status+' '+xhr.statusText)}}},{key:'_onProgress',value:function(e){if(this._status!==_loader.LoaderStatus.kError){null===this._contentLength&&null!==e.total&&0!==e.total&&(this._contentLength=e.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var chunk=e.target.response,byteStart=this._range.from+this._receivedLength;this._receivedLength+=chunk.byteLength,this._onDataArrival&&this._onDataArrival(chunk,byteStart,this._receivedLength)}}},{key:'_onLoadEnd',value:function(){return!0===this._requestAbort?void(this._requestAbort=!1):void(this._status===_loader.LoaderStatus.kError||(this._status=_loader.LoaderStatus.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1)))}},{key:'_onXhrError',value:function(e){this._status=_loader.LoaderStatus.kError;var type=0,info=null;if(this._contentLength&&e.loaded<this._contentLength?(type=_loader.LoaderErrors.EARLY_EOF,info={code:-1,msg:'Moz-Chunked stream meet Early-Eof'}):(type=_loader.LoaderErrors.EXCEPTION,info={code:-1,msg:e.constructor.name+' '+e.type}),this._onError)this._onError(type,info);else throw new _exception.RuntimeException(info.msg)}}]),MozChunkedLoader}(_loader.BaseLoader);exports.default=MozChunkedLoader},{'../utils/exception.js':40,'../utils/logger.js':41,'./loader.js':24}],30:[function(_dereq_,module,exports){'use strict';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&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===void 0){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if('value'in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_logger),_loader=_dereq_('./loader.js'),_exception=_dereq_('../utils/exception.js'),MSStreamLoa
1der=function(_BaseLoader){function MSStreamLoader(seekHandler,config){_classCallCheck(this,MSStreamLoader);var _this=_possibleConstructorReturn(this,(MSStreamLoader.__proto__||Object.getPrototypeOf(MSStreamLoader)).call(this,'xhr-msstream-loader'));return _this.TAG='MSStreamLoader',_this._seekHandler=seekHandler,_this._config=config,_this._needStash=!0,_this._xhr=null,_this._reader=null,_this._totalRange=null,_this._currentRange=null,_this._currentRequestURL=null,_this._currentRedirectedURL=null,_this._contentLength=null,_this._receivedLength=0,_this._bufferLimit=16777216,_this._lastTimeBufferSize=0,_this._isReconnecting=!1,_this}return _inherits(MSStreamLoader,_BaseLoader),_createClass(MSStreamLoader,null,[{key:'isSupported',value:function(){try{if('undefined'==typeof self.MSStream||'undefined'==typeof self.MSStreamReader)return!1;var xhr=new XMLHttpRequest;return xhr.open('GET','https://example.com',!0),xhr.responseType='ms-stream','ms-stream'===xhr.responseType}catch(e){return _logger2.default.w('MSStreamLoader',e.message),!1}}}]),_createClass(MSStreamLoader,[{key:'destroy',value:function(){this.isWorking()&&this.abort(),this._reader&&(this._reader.onprogress=null,this._reader.onload=null,this._reader.onerror=null,this._reader=null),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr=null),_get(MSStreamLoader.prototype.__proto__||Object.getPrototypeOf(MSStreamLoader.prototype),'destroy',this).call(this)}},{key:'open',value:function(dataSource,range){this._internalOpen(dataSource,range,!1)}},{key:'_internalOpen',value:function(dataSource,range,isSubrange){this._dataSource=dataSource,isSubrange?this._currentRange=range:this._totalRange=range;var sourceURL=dataSource.url;this._config.reuseRedirectedURL&&(void 0==this._currentRedirectedURL?void 0!=dataSource.redirectedURL&&(sourceURL=dataSource.redirectedURL):sourceURL=this._currentRedirectedURL);var seekConfig=this._seekHandler.getConfig(sourceURL,range);this._currentRequestURL=seekConfig.url;var reader=this._reader=new self.MSStreamReader;reader.onprogress=this._msrOnProgress.bind(this),reader.onload=this._msrOnLoad.bind(this),reader.onerror=this._msrOnError.bind(this);var xhr=this._xhr=new XMLHttpRequest;if(xhr.open('GET',seekConfig.url,!0),xhr.responseType='ms-stream',xhr.onreadystatechange=this._xhrOnReadyStateChange.bind(this),xhr.onerror=this._xhrOnError.bind(this),dataSource.withCredentials&&(xhr.withCredentials=!0),'object'===_typeof(seekConfig.headers)){var headers=seekConfig.headers;for(var key in headers)headers.hasOwnProperty(key)&&xhr.setRequestHeader(key,headers[key])}if('object'===_typeof(this._config.headers)){var _headers=this._config.headers;for(var _key in _headers)_headers.hasOwnProperty(_key)&&xhr.setRequestHeader(_key,_headers[_key])}this._isReconnecting?this._isReconnecting=!1:this._status=_loader.LoaderStatus.kConnecting,xhr.send()}},{key:'abort',value:function(){this._internalAbort(),this._status=_loader.LoaderStatus.kComplete}},{key:'_internalAbort',value:function(){this._reader&&(1===this._reader.readyState&&this._reader.abort(),this._reader.onprogress=null,this._reader.onload=null,this._reader.onerror=null,this._reader=null),this._xhr&&(this._xhr.abort(),this._xhr.onreadystatechange=null,this._xhr=null)}},{key:'_xhrOnReadyStateChange',value:function(e){var xhr=e.target;if(2===xhr.readyState){if(200<=xhr.status&&299>=xhr.status){if(this._status=_loader.LoaderStatus.kBuffering,void 0!=xhr.responseURL){var redirectedURL=this._seekHandler.removeURLParameters(xhr.responseURL);xhr.responseURL!==this._currentRequestURL&&redirectedURL!==this._currentRedirectedURL&&(this._currentRedirectedURL=redirectedURL,this._onURLRedirect&&this._onURLRedirect(redirectedURL))}var lengthHeader=xhr.getResponseHeader('Content-Length');if(null!=lengthHeader&&null==this._contentLength){var length=parseInt(lengthHeader);0<length&&(this._contentLength=length,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength))}}else if(this._status=_loader.LoaderStatus.kError,this._onError)this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:xhr.status,msg:xhr.statusText});
1else throw new _exception.RuntimeException('MSStreamLoader: Http code invalid, '+xhr.status+' '+xhr.statusText);}else if(3===xhr.readyState&&200<=xhr.status&&299>=xhr.status){this._status=_loader.LoaderStatus.kBuffering;var msstream=xhr.response;this._reader.readAsArrayBuffer(msstream)}}},{key:'_xhrOnError',value:function(e){this._status=_loader.LoaderStatus.kError;var type=_loader.LoaderErrors.EXCEPTION,info={code:-1,msg:e.constructor.name+' '+e.type};if(this._onError)this._onError(type,info);else throw new _exception.RuntimeException(info.msg)}},{key:'_msrOnProgress',value:function(e){var reader=e.target,bigbuffer=reader.result;if(null==bigbuffer)return void this._doReconnectIfNeeded();var slice=bigbuffer.slice(this._lastTimeBufferSize);this._lastTimeBufferSize=bigbuffer.byteLength;var byteStart=this._totalRange.from+this._receivedLength;this._receivedLength+=slice.byteLength,this._onDataArrival&&this._onDataArrival(slice,byteStart,this._receivedLength),bigbuffer.byteLength>=this._bufferLimit&&(_logger2.default.v(this.TAG,'MSStream buffer exceeded max size near '+(byteStart+slice.byteLength)+', reconnecting...'),this._doReconnectIfNeeded())}},{key:'_doReconnectIfNeeded',value:function(){if(null==this._contentLength||this._receivedLength<this._contentLength){this._isReconnecting=!0,this._lastTimeBufferSize=0,this._internalAbort();var range={from:this._totalRange.from+this._receivedLength,to:-1};this._internalOpen(this._dataSource,range,!0)}}},{key:'_msrOnLoad',value:function(){this._status=_loader.LoaderStatus.kComplete,this._onComplete&&this._onComplete(this._totalRange.from,this._totalRange.from+this._receivedLength-1)}},{key:'_msrOnError',value:function(e){this._status=_loader.LoaderStatus.kError;var type=0,info=null;if(this._contentLength&&this._receivedLength<this._contentLength?(type=_loader.LoaderErrors.EARLY_EOF,info={code:-1,msg:'MSStream meet Early-Eof'}):(type=_loader.LoaderErrors.EARLY_EOF,info={code:-1,msg:e.constructor.name+' '+e.type}),this._onError)this._onError(type,info);else throw new _exception.RuntimeException(info.msg)}}]),MSStreamLoader}(_loader.BaseLoader);exports.default=MSStreamLoader},{'../utils/exception.js':40,'../utils/logger.js':41,'./loader.js':24}],31:[function(_dereq_,module,exports){'use strict';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&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===void 0){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if('value'in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_speedSampler=_dereq_('./s
1peed-sampler.js'),_speedSampler2=_interopRequireDefault(_speedSampler),_loader=_dereq_('./loader.js'),_exception=_dereq_('../utils/exception.js'),RangeLoader=function(_BaseLoader){function RangeLoader(seekHandler,config){_classCallCheck(this,RangeLoader);var _this=_possibleConstructorReturn(this,(RangeLoader.__proto__||Object.getPrototypeOf(RangeLoader)).call(this,'xhr-range-loader'));return _this.TAG='RangeLoader',_this._seekHandler=seekHandler,_this._config=config,_this._needStash=!1,_this._chunkSizeKBList=[128,256,384,512,768,1024,1536,2048,3072,4096,5120,6144,7168,8192],_this._currentChunkSizeKB=384,_this._currentSpeedNormalized=0,_this._zeroSpeedChunkCount=0,_this._xhr=null,_this._speedSampler=new _speedSampler2.default,_this._requestAbort=!1,_this._waitForTotalLength=!1,_this._totalLengthReceived=!1,_this._currentRequestURL=null,_this._currentRedirectedURL=null,_this._currentRequestRange=null,_this._totalLength=null,_this._contentLength=null,_this._receivedLength=0,_this._lastTimeLoaded=0,_this}return _inherits(RangeLoader,_BaseLoader),_createClass(RangeLoader,null,[{key:'isSupported',value:function(){try{var xhr=new XMLHttpRequest;return xhr.open('GET','https://example.com',!0),xhr.responseType='arraybuffer','arraybuffer'===xhr.responseType}catch(e){return _logger2.default.w('RangeLoader',e.message),!1}}}]),_createClass(RangeLoader,[{key:'destroy',value:function(){this.isWorking()&&this.abort(),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr=null),_get(RangeLoader.prototype.__proto__||Object.getPrototypeOf(RangeLoader.prototype),'destroy',this).call(this)}},{key:'open',value:function(dataSource,range){this._dataSource=dataSource,this._range=range,this._status=_loader.LoaderStatus.kConnecting;var useRefTotalLength=!1;void 0!=this._dataSource.filesize&&0!==this._dataSource.filesize&&(useRefTotalLength=!0,this._totalLength=this._dataSource.filesize),this._totalLengthReceived||useRefTotalLength?this._openSubRange():(this._waitForTotalLength=!0,this._internalOpen(this._dataSource,{from:0,to:-1}))}},{key:'_openSubRange',value:function(){var chunkSize=1024*this._currentChunkSizeKB,from=this._range.from+this._receivedLength,to=from+chunkSize;null!=this._contentLength&&to-this._range.from>=this._contentLength&&(to=this._range.from+this._contentLength-1),this._currentRequestRange={from:from,to:to},this._internalOpen(this._dataSource,this._currentRequestRange)}},{key:'_internalOpen',value:function(dataSource,range){this._lastTimeLoaded=0;var sourceURL=dataSource.url;this._config.reuseRedirectedURL&&(void 0==this._currentRedirectedURL?void 0!=dataSource.redirectedURL&&(sourceURL=dataSource.redirectedURL):sourceURL=this._currentRedirectedURL);var seekConfig=this._seekHandler.getConfig(sourceURL,range);this._currentRequestURL=seekConfig.url;var xhr=this._xhr=new XMLHttpRequest;if(xhr.open('GET',seekConfig.url,!0),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),dataSource.withCredentials&&(xhr.withCredentials=!0),'object'===_typeof(seekConfig.headers)){var headers=seekConfig.headers;for(var key in headers)headers.hasOwnProperty(key)&&xhr.setRequestHeader(key,headers[key])}if('object'===_typeof(this._config.headers)){var _headers=this._config.headers;for(var _key in _headers)_headers.hasOwnProperty(_key)&&xhr.setRequestHeader(_key,_headers[_key])}xhr.send()}},{key:'abort',value:function(){this._requestAbort=!0,this._internalAbort(),this._status=_loader.LoaderStatus.kComplete}},{key:'_internalAbort',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:'_onReadyStateChange',value:function(e){var xhr=e.target;if(2===xhr.readyState){if(void 0!=xhr.responseURL){var redirectedURL=this._seekHandler.removeURLParameters(xhr.responseURL);xhr.responseURL!==this._currentRequestURL&&redirectedURL!==this._currentRedirectedURL&&(this._currentRedirectedURL=redirectedURL,this._onURLRedirect&&this._onURLRedirect(redirectedURL))}if(200<=xhr.status&&299>=xhr.status){if(this._waitForTotalLength)return;this._status=_loader.LoaderStatus.kBuffering}else if(this._status=_loader.LoaderStatus.kError,this._onError)this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:xhr.status,msg:xhr.statusText});else throw new _exception.RuntimeException('RangeLoader: Http code invalid, '+xhr.status+' '+xhr.statusText)}}},{key:'_onProgress',value:function(e){if(this._status!==_loader.LoaderStatus.kError){if(null===this._contentLength){var openNextRange=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,openNextRange=!0;var total=e.total;this._internalAbort(),null!=total&0!==total&&(this._totalLength=total)}if(this._contentLength=-1===this._range.to?this._totalLength-this._range.from:this._range.to-this._range.from+1,openNextRange)return void this._openSubRange();this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}var delta=e.loaded-this._lastTimeLoaded;this._lastTimeLoaded=e.loaded,this._speedSampler.addBytes(delta)}}},{key:'_normalizeSpeed',value:function(input){var list=this._chunkSizeKBList,last=list.length-1,mid=0,lbound=0,ubound=last;if(input<list[0])return list[0];for(;lbound<=ubound;){if(mid=lbound+Math.floor((ubound-lbound)/2),mid==last||input>=list[mid]&&input<list[mid+1])return list[mid];list[mid]<input?lbound=mid+1:ubound=mid-1}
1}},{key:'_onLoad',value:function(e){if(this._status!==_loader.LoaderStatus.kError){if(this._waitForTotalLength)return void(this._waitForTotalLength=!1);this._lastTimeLoaded=0;var KBps=this._speedSampler.lastSecondKBps;if(0===KBps&&(this._zeroSpeedChunkCount++,3<=this._zeroSpeedChunkCount&&(KBps=this._speedSampler.currentKBps)),0!==KBps){var normalized=this._normalizeSpeed(KBps);this._currentSpeedNormalized!==normalized&&(this._currentSpeedNormalized=normalized,this._currentChunkSizeKB=normalized)}var chunk=e.target.response,byteStart=this._range.from+this._receivedLength;this._receivedLength+=chunk.byteLength;var reportComplete=!1;null!=this._contentLength&&this._receivedLength<this._contentLength?this._openSubRange():reportComplete=!0,this._onDataArrival&&this._onDataArrival(chunk,byteStart,this._receivedLength),reportComplete&&(this._status=_loader.LoaderStatus.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1))}}},{key:'_onXhrError',value:function(e){this._status=_loader.LoaderStatus.kError;var type=0,info=null;if(this._contentLength&&0<this._receivedLength&&this._receivedLength<this._contentLength?(type=_loader.LoaderErrors.EARLY_EOF,info={code:-1,msg:'RangeLoader meet Early-Eof'}):(type=_loader.LoaderErrors.EXCEPTION,info={code:-1,msg:e.constructor.name+' '+e.type}),this._onError)this._onError(type,info);else throw new _exception.RuntimeException(info.msg)}},{key:'currentSpeed',get:function(){return this._speedSampler.lastSecondKBps}}]),RangeLoader}(_loader.BaseLoader);exports.default=RangeLoader},{'../utils/exception.js':40,'../utils/logger.js':41,'./loader.js':24,'./speed-sampler.js':27}],32:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=_interopRequireDefault(_events),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_browser=_dereq_('../utils/browser.js'),_browser2=_interopRequireDefault(_browser),_playerEvents=_dereq_('./player-events.js'),_playerEvents2=_interopRequireDefault(_playerEvents),_transmuxer=_dereq_('../core/transmuxer.js'),_transmuxer2=_interopRequireDefault(_transmuxer),_transmuxingEvents=_dereq_('../core/transmuxing-events.js'),_transmuxingEvents2=_interopRequireDefault(_transmuxingEvents),_mseController=_dereq_('../core/mse-controller.js'),_mseController2=_interopRequireDefault(_mseController),_mseEvents=_dereq_('../core/mse-events.js'),_mseEvents2=_interopRequireDefault(_mseEvents),_playerErrors=_dereq_('./player-errors.js'),_config=_dereq_('../config.js'),_exception=_dereq_('../utils/exception.js'),FlvPlayer=function(){function FlvPlayer(mediaDataSource,config){if(_classCallCheck(this,FlvPlayer),this.TAG='FlvPlayer',this._type='FlvPlayer',this._emitter=new _events2.default,this._config=(0,_config.createDefaultConfig)(),'object'===('undefined'==typeof config?'undefined':_typeof(config))&&Object.assign(this._config,config),'flv'!==mediaDataSource.type.toLowerCase())throw new _exception.InvalidArgumentException('FlvPlayer requires an flv MediaDataSource input!');!0===mediaDataSource.isLive&&(this._config.isLive=!0),this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this),onvSeeking:this._onvSeeking.bind(this),onvCanPlay:this._onvCanPlay.bind(this),onvStalled:this._onvStalled.bind(this),onvProgress:this._onvProgress.bind(this)},this._now=self.performance&&self.performance.now?self.performance.now.bind(self.performance):Date.now,this._pendingSeekTime=null,this._requestSetTime=!1,this._seekpointRecord=null,this._progressChecker=null,this._mediaDataSource=mediaDataSource,this._mediaElement=null,this._msectl=null,this._transmuxer=null,this._mseSourceOpened=!1,this._hasPendingLoad=!1,this._receivedCanPlay=!1,this._mediaInfo=null,this._statisticsInfo=null;var chromeNeedIDRFix=_browser2.default.chrome&&(50>_browser2.default.version.major||50===_browser2.default.version.major&&2661>_browser2.default.version.build);this._alwaysSeekKeyframe=!!(chromeNeedIDRFix||_browser2.default.msedge||_browser2.default.msie),this._alwaysSeekKeyframe&&(this._config.accurateSeek=!1)}return _createClass(FlvPlayer,[{key:'destroy',value:function(){null!=this._progressChecker&&(window.clearInterval(this._progressChecker),this._progressChecker=null),this._transmuxer&&this.unload(),this._mediaElement&&this.detachMediaElement(),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null}},{key:'on',value:function(event,listener){var _this=this;event===_playerEvents2.default.MEDIA_INFO?null!=this._mediaInfo&&Promise.resolve().then(function(){_this._emitter.emit(_playerEvents2.default.MEDIA_INFO,_this.mediaInfo)}):event===_playerEvents2.default.STATISTICS_INFO&&null!=this._statisticsInfo&&Promise.resolve().then(function(){_this._emitter.emit(_playerEvents2.default.STATISTICS_INFO,_this.statisticsInfo)}),this._emitter.addListener(event,listener)}},{key:'off',value:function(event,listener){this._emitter.removeListener(event,listener)}},{key:'attachMediaElement',value:function(mediaElement){var _this2=this;if(this._mediaElement=mediaElement,mediaElement.addEventListener('loadedmetadata',this.e.onvLoadedMetadata),mediaElement.addEventListener('seeking',this.e.onvSeeking),mediaElement.addEventListener('canplay',this.e.onvCanPlay),mediaElement.addEventListener('stalled',this.e.onvStalled),mediaElement.addEventListener('progress',this.e.onvProgress),this._msectl=new _mseController2.default(this._config),this._msectl.on(_mseEvents2.default.UPDATE_END,this._onmseUpdateEnd.bind(this)),this._msectl.on(_mseEvents2.default.BUFFER_FULL,this._onmseBufferFull.bind(this)),this._msectl.on(_mseEvents2.default.SOURCE_OPEN,function(){_this2._mseSourceOpened=!0,_this2._hasPendingLoad&&(_this2._hasPendingLoad=!1,_this2.load())}),this._msectl.on(_mseEvents2.default.ERROR,function(info){_this2._emitter.emit(_playerEvents2.default.ERROR,_playerErrors.ErrorTypes.MEDIA_ERROR,_playerErrors.ErrorDetails.MEDIA_MSE_ERROR,info)}
vendor: 14,316 bytes, line 1
1),this._msectl.attachMediaElement(mediaElement),null!=this._pendingSeekTime)try{mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(e){}}},{key:'detachMediaElement',value:function(){this._mediaElement&&(this._msectl.detachMediaElement(),this._mediaElement.removeEventListener('loadedmetadata',this.e.onvLoadedMetadata),this._mediaElement.removeEventListener('seeking',this.e.onvSeeking),this._mediaElement.removeEventListener('canplay',this.e.onvCanPlay),this._mediaElement.removeEventListener('stalled',this.e.onvStalled),this._mediaElement.removeEventListener('progress',this.e.onvProgress),this._mediaElement=null),this._msectl&&(this._msectl.destroy(),this._msectl=null)}},{key:'load',value:function(){var _this3=this;if(!this._mediaElement)throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');if(this._transmuxer)throw new _exception.IllegalStateException('FlvPlayer.load() has been called, please call unload() first!');return this._hasPendingLoad?void 0:this._config.deferLoadAfterSourceOpen&&!1===this._mseSourceOpened?void(this._hasPendingLoad=!0):void(0<this._mediaElement.readyState&&(this._requestSetTime=!0,this._mediaElement.currentTime=0),this._transmuxer=new _transmuxer2.default(this._mediaDataSource,this._config),this._transmuxer.on(_transmuxingEvents2.default.INIT_SEGMENT,function(type,is){_this3._msectl.appendInitSegment(is)}),this._transmuxer.on(_transmuxingEvents2.default.MEDIA_SEGMENT,function(type,ms){if(_this3._msectl.appendMediaSegment(ms),_this3._config.lazyLoad&&!_this3._config.isLive){var currentTime=_this3._mediaElement.currentTime;ms.info.endDts>=1e3*(currentTime+_this3._config.lazyLoadMaxDuration)&&null==_this3._progressChecker&&(_logger2.default.v(_this3.TAG,'Maximum buffering duration exceeded, suspend transmuxing task'),_this3._suspendTransmuxer())}}),this._transmuxer.on(_transmuxingEvents2.default.LOADING_COMPLETE,function(){_this3._msectl.endOfStream(),_this3._emitter.emit(_playerEvents2.default.LOADING_COMPLETE)}),this._transmuxer.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF,function(){_this3._emitter.emit(_playerEvents2.default.RECOVERED_EARLY_EOF)}),this._transmuxer.on(_transmuxingEvents2.default.IO_ERROR,function(detail,info){_this3._emitter.emit(_playerEvents2.default.ERROR,_playerErrors.ErrorTypes.NETWORK_ERROR,detail,info)}),this._transmuxer.on(_transmuxingEvents2.default.DEMUX_ERROR,function(detail,info){_this3._emitter.emit(_playerEvents2.default.ERROR,_playerErrors.ErrorTypes.MEDIA_ERROR,detail,{code:-1,msg:info})}),this._transmuxer.on(_transmuxingEvents2.default.MEDIA_INFO,function(mediaInfo){_this3._mediaInfo=mediaInfo,_this3._emitter.emit(_playerEvents2.default.MEDIA_INFO,Object.assign({},mediaInfo))}),this._transmuxer.on(_transmuxingEvents2.default.METADATA_ARRIVED,function(metadata){_this3._emitter.emit(_playerEvents2.default.METADATA_ARRIVED,metadata)}),this._transmuxer.on(_transmuxingEvents2.default.STREAMDATA_ARRIVED,function(data){_this3._emitter.emit(_playerEvents2.default.STREAMDATA_ARRIVED,data)}),this._transmuxer.on(_transmuxingEvents2.default.SCRIPTDATA_ARRIVED,function(data){_this3._emitter.emit(_playerEvents2.default.SCRIPTDATA_ARRIVED,data)}),this._transmuxer.on(_transmuxingEvents2.default.STATISTICS_INFO,function(statInfo){_this3._statisticsInfo=_this3._fillStatisticsInfo(statInfo),_this3._emitter.emit(_playerEvents2.default.STATISTICS_INFO,Object.assign({},_this3._statisticsInfo))}),this._transmuxer.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT,function(milliseconds){_this3._mediaElement&&!_this3._config.accurateSeek&&(_this3._requestSetTime=!0,_this3._mediaElement.currentTime=milliseconds/1e3)}),this._transmuxer.open())}},{key:'unload',value:function(){this._mediaElement&&this._mediaElement.pause(),this._msectl&&this._msectl.seek(0),this._transmuxer&&(this._transmuxer.close(),this._transmuxer.destroy(),this._transmuxer=null)}},{key:'play',value:function(){return this._mediaElement.play()}},{key:'pause',value:function(){this._mediaElement.pause()}},{key:'_fillStatisticsInfo',value:function(statInfo){if(statInfo.playerType=this._type,!(this._mediaElement instanceof HTMLVideoElement))return statInfo;var hasQualityInfo=!0,decoded=0,dropped=0;if(this._mediaElement.getVideoPlaybackQuality){var quality=this._mediaElement.getVideoPlaybackQuality();decoded=quality.totalVideoFrames,dropped=quality.droppedVideoFrames}else void 0==this._mediaElement.webkitDecodedFrameCount?hasQualityInfo=!1:(decoded=this._mediaElement.webkitDecodedFrameCount,dropped=this._mediaElement.webkitDroppedFrameCount);return hasQualityInfo&&(statInfo.decodedFrames=decoded,statInfo.droppedFrames=dropped),statInfo}},{key:'_onmseUpdateEnd',value:function(){if(this._config.lazyLoad&&!this._config.isLive){for(var buffered=this._mediaElement.buffered,currentTime=this._mediaElement.currentTime,currentRangeStart=0,currentRangeEnd=0,i=0;i<buffered.length;i++){var start=buffered.start(i),end=buffered.end(i);if(start<=currentTime&¤tTime<end){currentRangeStart=start,currentRangeEnd=end;break}}currentRangeEnd>=currentTime+this._config.lazyLoadMaxDuration&&null==this._progressChecker&&(_logger2.default.v(this.TAG,'Maximum buffering duration exceeded, suspend transmuxing task'),this._suspendTransmuxer())}}},{key:'_onmseBufferFull',value:function(){_logger2.default.v(this.TAG,'MSE SourceBuffer is full, suspend transmuxing task'),null==this._progressChecker&&this._suspendTransmuxer()}},{key:'_suspendTransmuxer',value:function(){this._transmuxer&&(this._transmuxer.pause(),null==this._progressChecker&&(this._progressChecker=window.setInterval(this._checkProgressAndResume.bind(this),1e3)))}},{key:'_checkProgressAndResume',value:function(){for(var currentTime=this._mediaElement.currentTime,buffered=this._mediaElement.buffered,needResume=!1,i=0;i<buffered.length;i++){var from=buffered.start(i),to=buffered.end(i);if(currentTime>=from&¤tTime<to){currentTime>=to-this._config.lazyLoadRecoverDuration&&(needResume=!0);break}}needResume&&(window.clearInterval(this._progressChecker),this._progressChecker=null,needResume&&(_logger2.default.v(this.TAG,'Continue loading from paused position'),this._transmuxer.resume()))}},{key:'_isTimepointBuffered',value:function(seconds){for(var buffered=this._mediaElement.buffered,i=0;i<buffered.length;i++){var from=buffered.start(i),to=buffered.end(i);if(seconds>=from&&seconds<to)return!0}return!1}},{key:'_internalSeek',value:function(seconds){var directSeek=this._isTimepointBuffered(seconds),directSeekBegin=!1,directSeekBeginTime=0;if(1>seconds&&0<this._mediaElement.buffered.length){var videoBeginTime=this._mediaElement.buffered.start(0);(1>videoBeginTime&&seconds<videoBeginTime||_browser2.default.safari)&&(directSeekBegin=!0,directSeekBeginTime=_browser2.default.safari?.1:videoBeginTime)}if(directSeekBegin)this._requestSetTime=!0,this._mediaElement.currentTime=directSeekBeginTime;else if(directSeek){if(!this._alwaysSeekKeyframe)this._requestSetTime=!0,this._mediaElement.currentTime=seconds;else{var idr=this._msectl.getNearestKeyframe(Math.floor(1e3*seconds));this._requestSetTime=!0,this._mediaElement.currentTime=null==idr?seconds:idr.dts/1e3}null!=this._progressChecker&&this._checkProgressAndResume()}else null!=this._progressChecker&&(window.clearInterval(this._progressChecker),this._progressChecker=null),this._msectl.seek(seconds),this._transmuxer.seek(Math.floor(1e3*seconds)),this._config.accurateSeek&&(this._requestSetTime=!0,this._mediaElement.currentTime=seconds)}},{key:'_checkAndApplyUnbufferedSeekpoint',value:function(){if(this._seekpointRecord)if(this._seekpointRecord.recordTime<=this._now()-100){var target=this._mediaElement.currentTime;this._seekpointRecord=null,this._isTimepointBuffered(target)||(null!=this._progressChecker&&(window.clearTimeout(this._progressChecker),this._progressChecker=null),this._msectl.seek(target),this._transmuxer.seek(Math.floor(1e3*target)),this._config.accurateSeek&&(this._requestSetTime=!0,this._mediaElement.currentTime=target))}else window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this),50)}},{key:'_checkAndResumeStuckPlayback',value:function(stalled){var media=this._mediaElement;if(stalled||!this._receivedCanPlay||2>media.readyState){var buffered=media.buffered;0<buffered.length&&media.currentTime<buffered.start(0)&&(_logger2.default.w(this.TAG,'Playback seems stuck at '+media.currentTime+', seek to '+buffered.start(0)),this._requestSetTime=!0,this._mediaElement.currentTime=buffered.start(0),this._mediaElement.removeEventListener('progress',this.e.onvProgress))}else this._mediaElement.removeEventListener('progress',this.e.onvProgress)}},{key:'_onvLoadedMetadata',value:function(){null!=this._pendingSeekTime&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null)}},{key:'_onvSeeking',value:function(){var target=this._mediaElement.currentTime,buffered=this._mediaElement.buffered;if(this._requestSetTime)return void(this._requestSetTime=!1);if(1>target&&0<buffered.length){var videoBeginTime=buffered.start(0);if(1>videoBeginTime&&target<videoBeginTime||_browser2.default.safari)return this._requestSetTime=!0,void(this._mediaElement.currentTime=_browser2.default.safari?.1:videoBeginTime)}if(this._isTimepointBuffered(target)){if(this._alwaysSeekKeyframe){var idr=this._msectl.getNearestKeyframe(Math.floor(1e3*target));null!=idr&&(this._requestSetTime=!0,this._mediaElement.currentTime=idr.dts/1e3)}return void(null!=this._progressChecker&&this._checkProgressAndResume())}this._seekpointRecord={seekPoint:target,recordTime:this._now()},window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this),50)}},{key:'_onvCanPlay',value:function(){this._receivedCanPlay=!0,this._mediaElement.removeEventListener('canplay',this.e.onvCanPlay)}},{key:'_onvStalled',value:function(){this._checkAndResumeStuckPlayback(!0)}},{key:'_onvProgress',value:function(){this._checkAndResumeStuckPlayback()}},{key:'type',get:function(){return this._type}},{key:'buffered',get:function(){return this._mediaElement.buffered}},{key:'duration',get:function(){return this._mediaElement.duration}},{key:'volume',get:function(){return this._mediaElement.volume},set:function(value){this._mediaElement.volume=value}},{key:'muted',get:function(){return this._mediaElement.muted},set:function(muted){this._mediaElement.muted=muted}},{key:'currentTime',get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(seconds){this._mediaElement?this._internalSeek(seconds):this._pendingSeekTime=seconds}},{key:'mediaInfo',get:function(){return Object.assign({},this._mediaInfo)}},{key:'statisticsInfo',get:function(){return null==this._statisticsInfo&&(this._statisticsInfo={}),this._statisticsInfo=this._fillStatisticsInfo(this._statisticsInfo),Object.assign({},this._statisticsInfo)}}]),FlvPlayer}();exports.default=FlvPlayer},{'../config.js':5,'../core/mse-controller.js':9,'../core/mse-events.js':10,'../core/transmuxer.js':11,'../core/transmuxing-events.js':13,'../utils/browser.js':39,'../utils/exception.js':40,'../utils/logger.js':41,'./player-errors.js':34,'./player-events.js':35,events:2}],33:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=_interopRequireDefault(_events),_playerEvents=_dereq_('./player-events.js'),_playerEvents2=_interopRequireDefault(_playerEvents),_config=_dereq_('../config.js'),_exception=_dereq_('../utils/exception.js'),NativePlayer=function(){function NativePlayer(mediaDataSource,config){if(_classCallCheck(this,NativePlayer),this.TAG='NativePlayer',this._type='NativePlayer',this._emitter=new _events2.default,this._config=(0,_config.createDefaultConfig)(),'object'===('undefined'==typeof config?'undefined':_typeof(config))&&Object.assign(this._config,config),'flv'===mediaDataSource.type.toLowerCase())throw new _exception.InvalidArgumentException('NativePlayer does\'t support flv MediaDataSource input!');if(mediaDataSource.hasOwnProperty('segments'))throw new _exception.InvalidArgumentException('NativePlayer('+mediaDataSource.type+') doesn\'t support multipart playback!');this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this)},this._pendingSeekTime=null,this._statisticsReporter=null,this._mediaDataSource=mediaDataSource,this._mediaElement=null}return _createClass(NativePlayer,[{key:'destroy',value:function(){this._mediaElement&&(this.unload(),this.detachMediaElement()),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null}},{key:'on',value:function(event,listener){var _this=this;event===_playerEvents2.default.MEDIA_INFO?null!=this._mediaElement&&0!==this._mediaElement.readyState&&Promise.resolve().then(function(){_this._emitter.emit(_playerEvents2.default.MEDIA_INFO,_this.mediaInfo)}):event===_playerEvents2.default.STATISTICS_INFO&&null!=this._mediaElement&&0!==this._mediaElement.readyState&&Promise.resolve().then(function(){_this._emitter.emit(_playerEvents2.default.STATISTICS_INFO,_this.statisticsInfo)}),this._emitter.addListener(event,listener)}},{key:'off',value:function(event,listener){this._emitter.removeListener(event,listener)}},{key:'attachMediaElement',value:function(mediaElement){if(this._mediaElement=mediaElement,mediaElement.addEventListener('loadedmetadata',this.e.onvLoadedMetadata),null!=this._pe
1ndingSeekTime)try{mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(e){}}},{key:'detachMediaElement',value:function(){this._mediaElement&&(this._mediaElement.src='',this._mediaElement.removeAttribute('src'),this._mediaElement.removeEventListener('loadedmetadata',this.e.onvLoadedMetadata),this._mediaElement=null),null!=this._statisticsReporter&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)}},{key:'load',value:function(){if(!this._mediaElement)throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');this._mediaElement.src=this._mediaDataSource.url,0<this._mediaElement.readyState&&(this._mediaElement.currentTime=0),this._mediaElement.preload='auto',this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)}},{key:'unload',value:function(){this._mediaElement&&(this._mediaElement.src='',this._mediaElement.removeAttribute('src')),null!=this._statisticsReporter&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)}},{key:'play',value:function(){return this._mediaElement.play()}},{key:'pause',value:function(){this._mediaElement.pause()}},{key:'_onvLoadedMetadata',value:function(){null!=this._pendingSeekTime&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(_playerEvents2.default.MEDIA_INFO,this.mediaInfo)}},{key:'_reportStatisticsInfo',value:function(){this._emitter.emit(_playerEvents2.default.STATISTICS_INFO,this.statisticsInfo)}},{key:'type',get:function(){return this._type}},{key:'buffered',get:function(){return this._mediaElement.buffered}},{key:'duration',get:function(){return this._mediaElement.duration}},{key:'volume',get:function(){return this._mediaElement.volume},set:function(value){this._mediaElement.volume=value}},{key:'muted',get:function(){return this._mediaElement.muted},set:function(muted){this._mediaElement.muted=muted}},{key:'currentTime',get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(seconds){this._mediaElement?this._mediaElement.currentTime=seconds:this._pendingSeekTime=seconds}},{key:'mediaInfo',get:function(){var mediaPrefix=this._mediaElement instanceof HTMLAudioElement?'audio/':'video/',info={mimeType:mediaPrefix+this._mediaDataSource.type};return this._mediaElement&&(info.duration=Math.floor(1e3*this._mediaElement.duration),this._mediaElement instanceof HTMLVideoElement&&(info.width=this._mediaElement.videoWidth,info.height=this._mediaElement.videoHeight)),info}},{key:'statisticsInfo',get:function(){var info={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return info;var hasQualityInfo=!0,decoded=0,dropped=0;if(this._mediaElement.getVideoPlaybackQuality){var quality=this._mediaElement.getVideoPlaybackQuality();decoded=quality.totalVideoFrames,dropped=quality.droppedVideoFrames}else void 0==this._mediaElement.webkitDecodedFrameCount?hasQualityInfo=!1:(decoded=this._mediaElement.webkitDecodedFrameCount,dropped=this._mediaElement.webkitDroppedFrameCount);return hasQualityInfo&&(info.decodedFrames=decoded,info.droppedFrames=dropped),info}}]),NativePlayer}();exports.default=NativePlayer},{'../config.js':5,'../utils/exception.js':40,'./player-events.js':35,events:2}],34:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.ErrorDetails=exports.ErrorTypes=void 0;var _loader=_dereq_('../io/loader.js'),_demuxErrors=_dereq_('../demux/demux-errors.js'),_demuxErrors2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_demuxErrors),ErrorTypes=exports.ErrorTypes={NETWORK_ERROR:'NetworkError',MEDIA_ERROR:'MediaError',OTHER_ERROR:'OtherError'},ErrorDetails=exports.ErrorDetails={NETWORK_EXCEPTION:_loader.LoaderErrors.EXCEPTION,NETWORK_STATUS_CODE_INVALID:_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:_loader.LoaderErrors.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:_loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:'MediaMSEError',MEDIA_FORMAT_ERROR:_demuxErrors2.default.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:_demuxErrors2.default.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:_demuxErrors2.default.CODEC_UNSUPPORTED}},{'../demux/demux-errors.js':16,'../io/loader.js':24}],35:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});exports.default={ERROR:'error',LOADING_COMPLETE:'loading_complete',RECOVERED_EARLY_EOF:'recovered_early_eof',MEDIA_INFO:'media_info',METADATA_ARRIVED:'metadata_arrived',STREAMDATA_ARRIVED:'streamdata_arrived',SCRIPTDATA_ARRIVED:'scriptdata_arrived',STATISTICS_INFO:'statistics_info'}},{}],36:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),AAC=function(){function AAC(){_classCallCheck(this,AAC)}return _createClass(AAC,null,[{key:'getSilentFrame',value:function(codec,channelCount){if('mp4a.40.2'===codec){if
1(1===channelCount)return new Uint8Array([0,200,0,128,35,128]);if(2===channelCount)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===channelCount)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===channelCount)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===channelCount)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===channelCount)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])}else{if(1===channelCount)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===channelCount)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===channelCount)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}}]),AAC}();exports.default=AAC},{}],37:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),MP4=function(){function MP4(){_classCallCheck(this,MP4)}return _createClass(MP4,null,[{key:'init',value:function(){for(var name in 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:[],'.mp3':[]},MP4.types)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([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),constants.STSD_PREFIX=new Uint8Array([0,0,0,0,0,0,0,1]),constants.STTS=new Uint8Array([0,0,0,0,0,0,0,0]),constants.STSC=constants.STCO=constants.STTS,constants.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),constants.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]),constants.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]),constants.DREF=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),constants.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),constants.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}},{key:'box',value:function(type){for(var size=8,result=null,datas=Array.prototype.slice.call(arguments,1),arrayCount=datas.length,i=0;i<arrayCount;i++)size+=datas[i].byteLength;result=new Uint8Array(size),result[0]=255&size>>>24,result[1]=255&size>>>16,result[2]=255&size>>>8,result[3]=255&size,result.set(type,4);for(var offset=8,_i=0;_i<arrayCount;_i++)result.set(datas[_i],offset),offset+=datas[_i].byteLength;return result}},{key:'generateInitSegment',value:function(meta){var ftyp=MP4.box(MP4.types.ftyp,MP4.constants.FTYP),moov=MP4.moov(meta),result=new Uint8Array(ftyp.byteLength+moov.byteLength);return result.set(ftyp,0),result.set(moov,ftyp.byteLength),result}},{key:'moov',value:function(meta){var mvhd=MP4.mvhd(meta.timescale,meta.duration),trak=MP4.trak(meta),mvex=MP4.mvex(meta);return MP4.box(MP4.types.moov,mvhd,trak,mvex)}},{key:'mvhd',value:function(timescale,duration){return MP4.box(MP4.types.mvhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,255×cale>>>24,255×cale>>>16,255×cale>>>8,255×cale,255&duration>>>24,255&duration>>>16,255&duration>>>8,255&duration,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(meta){return MP4.box(MP4.types.trak,MP4.tkhd(meta),MP4.mdia(meta))}},{key:'tkhd',value:function(meta){var trackId=meta.id,duration=meta.duration,width=meta.presentWidth,height=meta.presentHeight;return MP4.box(MP4.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,255&trackId>>>24,255&trackId>>>16,255&trackId>>>8,255&trackId,0,0,0,0,255&duration>>>24,255&duration>>>16,255&duration>>>8,255&duration,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,255&width>>>8,255&width,0,0,255&height>>>8,255&height,0,0]))}},{key:'mdia',value:function(meta){return MP4.box(MP4.types.mdia,MP4.mdhd(meta),MP4.hdlr(meta),MP4.minf(meta))}},{key:'mdhd',value:function(meta){var timescale=meta.timescale,duration=meta.duration;return MP4.box(MP4.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,255×cale>>>24,255×cale>>>16,255×cale>>>8,255×cale,255&duration>>>24,255&duration>>>16,255&duration>>>8,255&duration,85,196,0,0]))}},{key:'hdlr',value:function(meta){var data=null;return data='audio'===meta.type?MP4.constants.HDLR_AUDIO:MP4.constants.HDLR_VIDEO,MP4.box(MP4.types.hdlr,data)}},{key:'minf',value:function(meta){var xmhd=null;return xmhd='audio'===meta.type?MP4.box(MP4.types.smhd,MP4.constants.SMHD):MP4.box(MP4.types.vmhd,MP4.constants.VMHD),MP4.box(MP4.types.minf,xmhd,MP4.dinf(),MP4.stbl(meta))}},{key:'dinf',value:function(){var result=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,MP4.constants.DREF));return result}},{key:'stbl',value:function(meta){var result=MP4.box(MP4.types.stbl,MP4.stsd(meta),MP4.box(MP4.types.stts,MP4.constants.STTS),MP4.box(MP4.types.stsc,MP4.constants.STSC),MP4.box(MP4.types.stsz,MP4.constants.STSZ),MP4.box(MP4.types.stco,MP4.constants.STCO));return result}},{key:'stsd',value:function(meta){return'audio'===meta.type?'mp3'===meta.
vendor: 17,775 bytes, line 1
1codec?MP4.box(MP4.types.stsd,MP4.constants.STSD_PREFIX,MP4.mp3(meta)):MP4.box(MP4.types.stsd,MP4.constants.STSD_PREFIX,MP4.mp4a(meta)):MP4.box(MP4.types.stsd,MP4.constants.STSD_PREFIX,MP4.avc1(meta))}},{key:'mp3',value:function(meta){var channelCount=meta.channelCount,sampleRate=meta.audioSampleRate,data=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,channelCount,0,16,0,0,0,0,255&sampleRate>>>8,255&sampleRate,0,0]);return MP4.box(MP4.types['.mp3'],data)}},{key:'mp4a',value:function(meta){var channelCount=meta.channelCount,sampleRate=meta.audioSampleRate,data=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,channelCount,0,16,0,0,0,0,255&sampleRate>>>8,255&sampleRate,0,0]);return MP4.box(MP4.types.mp4a,data,MP4.esds(meta))}},{key:'esds',value:function(meta){var config=meta.config||[],configSize=config.length,data=new Uint8Array([0,0,0,0,3,23+configSize,0,1,0,4,15+configSize,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([configSize]).concat(config).concat([6,1,2]));return MP4.box(MP4.types.esds,data)}},{key:'avc1',value:function(meta){var avcc=meta.avcc,width=meta.codecWidth,height=meta.codecHeight,data=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,255&width>>>8,255&width,255&height>>>8,255&height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,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 MP4.box(MP4.types.avc1,data,MP4.box(MP4.types.avcC,avcc))}},{key:'mvex',value:function(meta){return MP4.box(MP4.types.mvex,MP4.trex(meta))}},{key:'trex',value:function(meta){var trackId=meta.id,data=new Uint8Array([0,0,0,0,255&trackId>>>24,255&trackId>>>16,255&trackId>>>8,255&trackId,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return MP4.box(MP4.types.trex,data)}},{key:'moof',value:function(track,baseMediaDecodeTime){return MP4.box(MP4.types.moof,MP4.mfhd(track.sequenceNumber),MP4.traf(track,baseMediaDecodeTime))}},{key:'mfhd',value:function(sequenceNumber){var data=new Uint8Array([0,0,0,0,255&sequenceNumber>>>24,255&sequenceNumber>>>16,255&sequenceNumber>>>8,255&sequenceNumber]);return MP4.box(MP4.types.mfhd,data)}},{key:'traf',value:function(track,baseMediaDecodeTime){var trackId=track.id,tfhd=MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,255&trackId>>>24,255&trackId>>>16,255&trackId>>>8,255&trackId])),tfdt=MP4.box(MP4.types.tfdt,new Uint8Array([0,0,0,0,255&baseMediaDecodeTime>>>24,255&baseMediaDecodeTime>>>16,255&baseMediaDecodeTime>>>8,255&baseMediaDecodeTime])),sdtp=MP4.sdtp(track),trun=MP4.trun(track,sdtp.byteLength+16+16+8+16+8+8);return MP4.box(MP4.types.traf,tfhd,tfdt,trun,sdtp)}},{key:'sdtp',value:function(track){for(var samples=track.samples||[],sampleCount=samples.length,data=new Uint8Array(4+sampleCount),i=0,flags;i<sampleCount;i++)flags=samples[i].flags,data[i+4]=flags.isLeading<<6|flags.dependsOn<<4|flags.isDependedOn<<2|flags.hasRedundancy;return MP4.box(MP4.types.sdtp,data)}},{key:'trun',value:function(track,offset){var samples=track.samples||[],sampleCount=samples.length,dataSize=12+16*sampleCount,data=new Uint8Array(dataSize);offset+=8+dataSize,data.set([0,0,15,1,255&sampleCount>>>24,255&sampleCount>>>16,255&sampleCount>>>8,255&sampleCount,255&offset>>>24,255&offset>>>16,255&offset>>>8,255&offset],0);for(var i=0;i<sampleCount;i++){var duration=samples[i].duration,size=samples[i].size,flags=samples[i].flags,cts=samples[i].cts;data.set([255&duration>>>24,255&duration>>>16,255&duration>>>8,255&duration,255&size>>>24,255&size>>>16,255&size>>>8,255&size,flags.isLeading<<2|flags.dependsOn,flags.isDependedOn<<6|flags.hasRedundancy<<4|flags.isNonSync,0,0,255&cts>>>24,255&cts>>>16,255&cts>>>8,255&cts],12+16*i)}return MP4.box(MP4.types.trun,data)}},{key:'mdat',value:function(data){return MP4.box(MP4.types.mdat,data)}}]),MP4}();MP4.init(),exports.default=MP4},{}],38:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_logger=_dereq_('../utils/logger.js'),_logger2=_interopRequireDefault(_logger),_mp4Generator=_dereq_('./mp4-generator.js'),_mp4Generator2=_interopRequireDefault(_mp4Generator),_aacSilent=_dereq_('./aac-silent.js'),_aacSilent2=_interopRequireDefault(_aacSilent),_browser=_dereq_('../utils/browser.js'),_browser2=_interopRequireDefault(_browser),_mediaSegmentInfo=_dereq_('../core/media-segment-info.js'),_exception=_dereq_('../utils/exception.js'),MP4Remuxer=function(){function MP4Remuxer(config){_classCallCheck(this,MP4Remuxer),this.TAG='MP4Remuxer',this._config=config,this._isLive=!0===config.isLive,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=Infinity,this._videoDtsBase=Infinity,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new _mediaSegmentInfo.MediaSegmentInfoList('audio'),this._videoSegmentInfoList=new _mediaSegmentInfo.MediaSegmentInfoList('video'),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!!(_browser2.default.chrome&&(50>_browser2.default.version.major||50===_browser2.default.version.major&&2661>_browser2.default.version.build)),this._fillSilentAfterSeek=_browser2.default.msedge||_browser2.default.msie,this._mp3UseMpegAudio=!_browser2.default.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}return _createClass(MP4Remuxer,[{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(producer){return producer.onDataAvailable=this.remux.bind(this),producer.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this}},{key:'insertDiscontinuity',value:function(){this._audioNextDts=this._videoNextDts=void 0}},{key:'seek',value:function(){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()}},{key:'remux',value:function(audioTrack,videoTrack){if(!this._onMediaSegment)throw new _exception.IllegalStateException('MP4Remuxer: onMediaSegment callback must be specificed!');this._dtsBaseInited||this._calculateDtsBase(audioTrack,videoTrack),this._remuxVideo(videoTrack),this._remuxAudio(audioTrack)}},{key:'_onTrackMetadataReceived',value:function(type,metadata){var metabox=null,container='mp4',codec=metadata.codec;if('audio'===type)this._audioMeta=metadata,'mp3'===metadata.codec&&this._mp3UseMpegAudio?(container='mpeg',codec='',metabox=new Uint8Array):metabox=_mp4Generator2.default.generateInitSegment(metadata);else if('video'===type)this._videoMeta=metadata,metabox=_mp4Generator2.default.generateInitSegment(metadata);else return;if(!this._onInitSegment)throw new _exception.IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!');this._onInitSegment(type,{type:type,data:metabox.buffer,codec:codec,container:type+'/'+container,mediaDuration:metadata.duration})}},{key:'_calculateDtsBase',value:function(audioTrack,videoTrack){this._dtsBaseInited||(audioTrack.samples&&audioTrack.samples.length&&(this._audioDtsBase=audioTrack.samples[0].dts),videoTrack.samples&&videoTrack.samples.length&&(this._videoDtsBase=videoTrack.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)}},{key:'flushStashedSamples',value:function(){var videoSample=this._videoStashedLastSample,audioSample=this._audioStashedLastSample,videoTrack={type:'video',id:1,sequenceNumber:0,samples:[],length:0};null!=videoSample&&(videoTrack.samples.push(videoSample),videoTrack.length=videoSample.length);var audioTrack={type:'audio',id:2,sequenceNumber:0,samples:[],length:0};null!=audioSample&&(audioTrack.samples.push(audioSample),audioTrack.length=audioSample.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(videoTrack,!0),this._remuxAudio(audioTrack,!0)}},{key:'_remuxAudio',value:function(audioTrack,force){if(null!=this._audioMeta){var track=audioTrack,samples=track.samples,dtsCorrection=void 0,firstDts=-1,lastDts=-1,refSampleDuration=this._audioMeta.refSampleDuration,mpegRawTrack='mp3'===this._audioMeta.codec&&this._mp3UseMpegAudio,firstSegmentAfterSeek=this._dtsBaseInited&&void 0===this._audioNextDts,insertPrefixSilentFrame=!1;if(samples&&0!==samples.length&&(1!==samples.length||force)){var offset=0,mdatbox=null,mdatBytes=0;mpegRawTrack?(offset=0,mdatBytes=track.length):(offset=8,mdatBytes=8+track.length);var lastSample=null;if(1<samples.length&&(lastSample=samples.pop(),mdatBytes-=lastSample.length),null!=this._audioStashedLastSample){var sample=this._audioStashedLastSample;this._audioStashedLastSample=null,samples.unshift(sample),mdatBytes+=sample.length}null!=lastSample&&(this._audioStashedLastSample=lastSample);var firstSampleOriginalDts=samples[0].dts-this._dtsBase;if(this._audioNextDts)dtsCorrection=firstSampleOriginalDts-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())dtsCorrection=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&'mp3'!==this._audioMeta.originalCodec&&(insertPrefixSilentFrame=!0);else{var _lastSample=this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);if(null!=_lastSample){var distance=firstSampleOriginalDts-(_lastSample.originalDts+_lastSample.duration);3>=distance&&(distance=0);var expectedDts=_lastSample.dts+_lastSample.duration+distance;dtsCorrection=firstSampleOriginalDts-expectedDts}else dtsCorrection=0}if(insertPrefixSilentFrame){var firstSampleDts=firstSampleOriginalDts-dtsCorrection,videoSegment=this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts);if(null!=videoSegment&&videoSegment.beginDts<firstSampleDts){var silentUnit=_aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount);if(silentUnit){var dts=videoSegment.beginDts,silentFrameDuration=firstSampleDts-videoSegment.beginDts;_logger2.default.v(this.TAG,'InsertPrefixSilentAudio: dts: '+dts+', duration: '+silentFrameDuration),samples.unshift({unit:silentUnit,dts:dts,pts:dts}),mdatBytes+=silentUnit.byteLength}}else insertPrefixSilentFrame=!1}for(var mp4Samples=[],i=0;i<samples.length;i++){var _sample=samples[i],unit=_sample.unit,originalDts=_sample.dts-this._dtsBase,_dts=originalDts-dtsCorrection;-1===firstDts&&(firstDts=_dts);var sampleDuration=0;if(i!==samples.length-1){var nextDts=samples[i+1].dts-this._dtsBase-dtsCorrection;sampleDuration=nextDts-_dts}else if(null!=lastSample){var _nextDts=lastSample.dts-this._dtsBase-dtsCorrection;sampleDuration=_nextDts-_dts}else sampleDuration=1<=mp4Samples.length?mp4Samples[mp4Samples.length-1].duration:Math.floor(refSampleDuration);var needFillSilentFrames=!1,silentFrames=null;if(sampleDuration>1.5*refSampleDuration&&'mp3'!==this._audioMeta.codec&&this._fillAudioTimestampGap&&!_browser2.default.safari){needFillSilentFrames=!0;var delta=Math.abs(sampleDuration-refSampleDuration),frameCount=Math.ceil(delta/refSampleDuration),currentDts=_dts+refSampleDuration;_logger2.default.w(this.TAG,'Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync.\ndts: '+(_dts+sampleDuration)+' ms, expected: '+(_dts+Math.round(refSampleDuration))+' ms, '+('delta: '+Math.round(delta)+' ms, generate: '+frameCount+' frames'));var _silentUnit=_aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount);null==_silentUnit&&(_logger2.default.w(this.TAG,'Unable to generate silent frame for '+(this._audioMeta.originalCodec+' with '+this._audioMeta.channelCount+' channels, repeat last frame')),_silentUnit=unit),silentFrames=[];for(var j=0,intDts;j<frameCount;j++){if(intDts=Math.round(currentDts),0<silentFrames.length){var previousFrame=silentFrames[silentFrames.length-1];previousFrame.duration=intDts-previousFrame.dts}var frame={dts:intDts,pts:intDts,cts:0,unit:_silentUnit,size:_silentUnit.byteLength,duration:0,originalDts:originalDts,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}};silentFrames.push(frame),mdatBytes+=frame.size,currentDts+=refSampleDuration}var lastFrame=silentFrames[silentFrames.length-1];lastFrame.duration=_dts+sampleDuration-lastFrame.dts,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}}),needFillSilentFrames&&mp4Samples.push.apply(mp4Samples,silentFrames)}mpegRawTrack?mdatbox=new Uint8Array(mdatBytes):(mdatbox=new Uint8Array(mdatBytes),mdatbox[0]=255&mdatBytes>>>24,mdatbox[1]=255&mdatBytes>>>16,mdatbox[2]=255&mdatBytes>>>8,mdatbox[3]=255&mdatBytes,mdatbox.set(_mp4Generator2.default.types.mdat,4));for(var _i=0,_unit;_i<mp4Samples.length;_i++)_unit=mp4Samples[_i].unit,mdatbox.set(_unit,offset),offset+=_unit.byteLength;var latest=mp4Samples[mp4Samples.length-1];lastDts=latest.dts+latest.duration,this._audioNextDts=lastDts;var info=new _mediaSegmentInfo.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 _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts,mp4Samples[0].pts,mp4Samples[0].duration,mp4Samples[0].originalDts,!1),info.lastSample=new _mediaSegmentInfo.SampleInfo(latest.dts,latest.pts,latest.duration,latest.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(info),track.samples=mp4Samples,track.sequenceNumber++;var moofbox=null;moofbox=mpegRawTrack?new Uint8Array:_mp4Generator2.default.moof(track,firstDts),track.samples=[],track.length=0;var segment={type:'audio',data:this._mergeBoxes(moofbox,mdatbox).buffer,sampleCount:mp4Samples.length,info:info};mpegRawTrack&&firstSegmentAfterSeek&&(segment.timestampOffset=firstDts),this._onMediaSegment('audio',segment)}}}},{key:'_remuxVideo',value:function(videoTrack,force){if(null!=this._videoMeta){var track=videoTrack,samples=track.samples,dtsCorrection=void 0,firstDts=-1,lastDts=-1,firstPts=-1,lastPts=-1;if(samples&&0!==samples.length&&(1!==samples.length||force)){var offset=8,mdatbox=null,mdatBytes=8+videoTrack.length,lastSample=null;if(1<samples.length&&(lastSample=samples.pop(),mdatBytes-=lastSample.length),null!=this._videoStashedLastSample){var sample=this._videoStashedLastSample;this._videoStashedLastSample=null,samples.unshift(sample),mdatBytes+=sample.length}null!=lastSample&&(this._videoStashedLastSample=lastSample);var firstSampleOriginalDts=samples[0].dts-this._dtsBase;if(this._videoNextDts)dtsCorrection=firstSampleOriginalDts-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())dtsCorrection=0;else{var _lastSample2=this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);if(null!=_lastSample2){var distance=firstSampleOriginalDts-(_lastSample2.originalDts+_lastSample2.duration);3>=distance&&(distance=0);var expectedDts=_lastSample2.dts+_lastSample2.duration+distance;dtsCorrection=firstSampleOriginalDts-expectedDts}else dtsCorrection=0}for(var info=new _mediaSegmentInfo.MediaSegmentInfo,mp4Samples=[],i=0;i<samples.length;i++){var _sample2=samples[i],originalDts=_sample2.dts-this._dtsBase,isKeyframe=_sample2.isKeyframe,dts=originalDts-dtsCorrection,cts=_sample2.cts,pts=dts+cts;-1===firstDts&&(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 if(null!=lastSample){var _nextDts2=lastSample.dts-this._dtsBase-dtsCorrection;sampleDuration=_nextDts2-dts}else sampleDuration=1<=mp4Samples.length?mp4Samples[mp4Samples.length-1].duration:Math.floor(this._videoMeta.refSampleDuration);if(isKeyframe){var syncPoint=new _mediaSegmentInfo.SampleInfo(dts,pts,sampleDuration,_sample2.dts,!0);syncPoint.fileposition=_sample2.fileposition,info.appendSyncPoint(syncPoint)}mp4Samples.push({dts:dts,pts:pts,cts:cts,units:_sample2.units,size:_sample2.length,isKeyframe:isKeyframe,duration:sampleDuration,originalDts:originalDts,flags:{isLeading:0,dependsOn:isKeyframe?2:1,isDependedOn:isKeyframe?1:0,hasRedundancy:0,isNonSync:isKeyframe?0:1}})}mdatbox=new Uint8Array(mdatBytes),mdatbox[0]=255&mdatBytes>>>24,mdatbox[1]=255&mdatBytes>>>16,mdatbox[2]=255&mdatBytes>>>8,mdatbox[3]=255&mdatBytes,mdatbox.set(_mp4Generator2.default.types.mdat,4);for(var _i2=0,units;_i2<mp4Samples.length;_i2++)for(units=mp4Samples[_i2].units;units.length;){var unit=units.shift(),data=unit.data;mdatbox.set(data,offset),offset+=data.byteLength}var latest=mp4Samples[mp4Samples.length-1];if(lastDts=latest.dts+latest.duration,lastPts=latest.pts+latest.duration,this._videoNextDts=lastDts,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=ne
1w _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts,mp4Samples[0].pts,mp4Samples[0].duration,mp4Samples[0].originalDts,mp4Samples[0].isKeyframe),info.lastSample=new _mediaSegmentInfo.SampleInfo(latest.dts,latest.pts,latest.duration,latest.originalDts,latest.isKeyframe),this._isLive||this._videoSegmentInfoList.append(info),track.samples=mp4Samples,track.sequenceNumber++,this._forceFirstIDR){var flags=mp4Samples[0].flags;flags.dependsOn=2,flags.isNonSync=0}var moofbox=_mp4Generator2.default.moof(track,firstDts);track.samples=[],track.length=0,this._onMediaSegment('video',{type:'video',data:this._mergeBoxes(moofbox,mdatbox).buffer,sampleCount:mp4Samples.length,info:info})}}}},{key:'_mergeBoxes',value:function(moof,mdat){var result=new Uint8Array(moof.byteLength+mdat.byteLength);return result.set(moof,0),result.set(mdat,moof.byteLength),result}},{key:'onInitSegment',get:function(){return this._onInitSegment},set:function(callback){this._onInitSegment=callback}},{key:'onMediaSegment',get:function(){return this._onMediaSegment},set:function(callback){this._onMediaSegment=callback}}]),MP4Remuxer}();exports.default=MP4Remuxer},{'../core/media-segment-info.js':8,'../utils/browser.js':39,'../utils/exception.js':40,'../utils/logger.js':41,'./aac-silent.js':36,'./mp4-generator.js':37}],39:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var Browser={};(function(){var ua=self.navigator.userAgent.toLowerCase(),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)||0<=ua.indexOf('trident')&&/(rv)(?::| )([\w.]+)/.exec(ua)||0>ua.indexOf('compatible')&&/(firefox)[ \/]([\w.]+)/.exec(ua)||[],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)||[],matched={browser:match[5]||match[3]||match[1]||'',version:match[2]||match[4]||'0',majorVersion:match[4]||match[2]||'0',platform:platform_match[0]||''},browser={};if(matched.browser){browser[matched.browser]=!0;var versionArray=matched.majorVersion.split('.');browser.version={major:parseInt(matched.majorVersion,10),string:matched.version},1<versionArray.length&&(browser.version.minor=parseInt(versionArray[1],10)),2<versionArray.length&&(browser.version.build=parseInt(versionArray[2],10))}if(matched.platform&&(browser[matched.platform]=!0),(browser.chrome||browser.opr||browser.safari)&&(browser.webkit=!0),browser.rv||browser.iemobile){browser.rv&&delete browser.rv;var msie='msie';matched.browser=msie,browser[msie]=!0}if(browser.edge){delete browser.edge;var msedge='msedge';matched.browser=msedge,browser[msedge]=!0}if(browser.opr){var opera='opera';matched.browser=opera,browser[opera]=!0}if(browser.safari&&browser.android){var android='android';matched.browser=android,browser[android]=!0}for(var key in browser.name=matched.browser,browser.platform=matched.platform,Browser)Browser.hasOwnProperty(key)&&delete Browser[key];Object.assign(Browser,browser)})(),exports.default=Browser},{}],40:[function(_dereq_,module,exports){'use strict';function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return call&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),RuntimeException=exports.RuntimeException=function(){function RuntimeException(message){_classCallCheck(this,RuntimeException),this._message=message}return _createClass(RuntimeException,[{key:'toString',value:function(){return this.name+': '+this.message}},{key:'name',get:function(){return'RuntimeException'}},{key:'message',get:function(){return this._message}}]),RuntimeException}(),IllegalStateException=exports.IllegalStateException=function(_RuntimeException){function IllegalStateException(message){return _classCallCheck(this,IllegalStateException),_possibleConstructorReturn(this,(IllegalStateException.__proto__||Object.getPrototypeOf(IllegalStateException)).call(this,message))}return _inherits(IllegalStateException,_RuntimeException),_createClass(IllegalStateException,[{key:'name',get:function(){return'IllegalStateException'}}]),IllegalStateException}(RuntimeException),InvalidArgumentException=exports.InvalidArgumentException=function(_RuntimeException2){function InvalidArgumentException(message){return _classCallCheck(this,InvalidArgumentException),_possibleConstructorReturn(this,(InvalidArgumentException.__proto__||Object.getPrototypeOf(Invali
1dArgumentException)).call(this,message))}return _inherits(InvalidArgumentException,_RuntimeException2),_createClass(InvalidArgumentException,[{key:'name',get:function(){return'InvalidArgumentException'}}]),InvalidArgumentException}(RuntimeException),NotImplementedException=exports.NotImplementedException=function(_RuntimeException3){function NotImplementedException(message){return _classCallCheck(this,NotImplementedException),_possibleConstructorReturn(this,(NotImplementedException.__proto__||Object.getPrototypeOf(NotImplementedException)).call(this,message))}return _inherits(NotImplementedException,_RuntimeException3),_createClass(NotImplementedException,[{key:'name',get:function(){return'NotImplementedException'}}]),NotImplementedException}(RuntimeException)},{}],41:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(_events),Log=function(){function Log(){_classCallCheck(this,Log)}return _createClass(Log,null,[{key:'e',value:function(tag,msg){(!tag||Log.FORCE_GLOBAL_TAG)&&(tag=Log.GLOBAL_TAG);var str='['+tag+'] > '+msg;Log.ENABLE_CALLBACK&&Log.emitter.emit('log','error',str),Log.ENABLE_ERROR&&(function(){}?void 0:(function(){},void 0))}},{key:'i',value:function(tag,msg){(!tag||Log.FORCE_GLOBAL_TAG)&&(tag=Log.GLOBAL_TAG);var str='['+tag+'] > '+msg;Log.ENABLE_CALLBACK&&Log.emitter.emit('log','info',str),Log.ENABLE_INFO&&(function(){},void 0)}},{key:'w',value:function(tag,msg){(!tag||Log.FORCE_GLOBAL_TAG)&&(tag=Log.GLOBAL_TAG);var str='['+tag+'] > '+msg;Log.ENABLE_CALLBACK&&Log.emitter.emit('log','warn',str),Log.ENABLE_WARN&&(function(){},void 0)}},{key:'d',value:function(tag,msg){(!tag||Log.FORCE_GLOBAL_TAG)&&(tag=Log.GLOBAL_TAG);var str='['+tag+'] > '+msg;Log.ENABLE_CALLBACK&&Log.emitter.emit('log','debug',str),Log.ENABLE_DEBUG&&(function(){},void 0)}},{key:'v',value:function(tag,msg){(!tag||Log.FORCE_GLOBAL_TAG)&&(tag=Log.GLOBAL_TAG);var str='['+tag+'] > '+msg;Log.ENABLE_CALLBACK&&Log.emitter.emit('log','verbose',str),Log.ENABLE_VERBOSE&&void 0}}]),Log}();Log.GLOBAL_TAG='flv.js',Log.FORCE_GLOBAL_TAG=!1,Log.ENABLE_ERROR=!0,Log.ENABLE_INFO=!0,Log.ENABLE_WARN=!0,Log.ENABLE_DEBUG=!0,Log.ENABLE_VERBOSE=!0,Log.ENABLE_CALLBACK=!1,Log.emitter=new _events2.default,exports.default=Log},{events:2}],42:[function(_dereq_,module,exports){'use strict';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')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_events=_dereq_('events'),_events2=_interopRequireDefault(_events),_logger=_dereq_('./logger.js'),_logger2=_interopRequireDefault(_logger),LoggingControl=function(){function LoggingControl(){_classCallCheck(this,LoggingControl)}return _createClass(LoggingControl,null,[{key:'getConfig',value:function(){return{globalTag:_logger2.default.GLOBAL_TAG,forceGlobalTag:_logger2.default.FORCE_GLOBAL_TAG,enableVerbose:_logger2.default.ENABLE_VERBOSE,enableDebug:_logger2.default.ENABLE_DEBUG,enableInfo:_logger2.default.ENABLE_INFO,enableWarn:_logger2.default.ENABLE_WARN,enableError:_logger2.default.ENABLE_ERROR,enableCallback:_logger2.default.ENABLE_CALLBACK}}},{key:'applyConfig',value:function(config){_logger2.default.GLOBAL_TAG=config.globalTag,_logger2.default.FORCE_GLOBAL_TAG=config.forceGlobalTag,_logger2.default.ENABLE_VERBOSE=config.enableVerbose,_logger2.default.ENABLE_DEBUG=config.enableDebug,_logger2.default.ENABLE_INFO=config.enableInfo,_logger2.default.ENABLE_WARN=config.enableWarn,_logger2.default.ENABLE_ERROR=config.enableError,_logger2.default.ENABLE_CALLBACK=config.enableCallback}},{key:'_notifyChange',value:function(){var emitter=LoggingControl.emitter;if(0<emitter.listenerCount('change')){var config=LoggingControl.getConfig();emitter.emit('change',config)}}},{key:'registerListener',value:function(listener){LoggingControl.emitter.addListener('change',listener)}},{key:'removeListener',value:function(listener){LoggingControl.emitter.removeListener('change',listener)}},{key:'addLogListener',value:function(listener){_logger2.default.emitter.addListener('log',listener),0<_logger2.default.emitter.listenerCount('log')&&(_logger2.default.ENABLE_CALLBACK=!0,LoggingControl._notifyChange())}},{key:'removeLogListener',value:function(listener){_logger2.default.emitter.removeListener('log',listener),0===_logger2.default.emitter.listenerCount('log')&&(_logger2.default.ENABLE_CALLBACK=!1,LoggingControl._notifyChange())}},{key:'forceGlobalTag',get:function(){return _logger2.default.FORCE_GLOBAL_TAG},set:function(enable){_logger2.default.FORCE_GLOBAL_TAG=enable,LoggingControl._notifyChange()}},{key:'globalTag',get:function(){return _logger2.default.GLOBAL_TAG}
1,set:function(tag){_logger2.default.GLOBAL_TAG=tag,LoggingControl._notifyChange()}},{key:'enableAll',get:function(){return _logger2.default.ENABLE_VERBOSE&&_logger2.default.ENABLE_DEBUG&&_logger2.default.ENABLE_INFO&&_logger2.default.ENABLE_WARN&&_logger2.default.ENABLE_ERROR},set:function(enable){_logger2.default.ENABLE_VERBOSE=enable,_logger2.default.ENABLE_DEBUG=enable,_logger2.default.ENABLE_INFO=enable,_logger2.default.ENABLE_WARN=enable,_logger2.default.ENABLE_ERROR=enable,LoggingControl._notifyChange()}},{key:'enableDebug',get:function(){return _logger2.default.ENABLE_DEBUG},set:function(enable){_logger2.default.ENABLE_DEBUG=enable,LoggingControl._notifyChange()}},{key:'enableVerbose',get:function(){return _logger2.default.ENABLE_VERBOSE},set:function(enable){_logger2.default.ENABLE_VERBOSE=enable,LoggingControl._notifyChange()}},{key:'enableInfo',get:function(){return _logger2.default.ENABLE_INFO},set:function(enable){_logger2.default.ENABLE_INFO=enable,LoggingControl._notifyChange()}},{key:'enableWarn',get:function(){return _logger2.default.ENABLE_WARN},set:function(enable){_logger2.default.ENABLE_WARN=enable,LoggingControl._notifyChange()}},{key:'enableError',get:function(){return _logger2.default.ENABLE_ERROR},set:function(enable){_logger2.default.ENABLE_ERROR=enable,LoggingControl._notifyChange()}}]),LoggingControl}();LoggingControl.emitter=new _events2.default,exports.default=LoggingControl},{'./logger.js':41,events:2}],43:[function(_dereq_,module,exports){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),Polyfill=function(){function Polyfill(){_classCallCheck(this,Polyfill)}return _createClass(Polyfill,null,[{key:'install',value:function(){Object.setPrototypeOf=Object.setPrototypeOf||function(obj,proto){return obj.__proto__=proto,obj},Object.assign=Object.assign||function(target){if(void 0===target||null===target)throw new TypeError('Cannot convert undefined or null to object');for(var output=Object(target),i=1,source;i<arguments.length;i++)if(source=arguments[i],void 0!==source&&null!==source)for(var key in source)source.hasOwnProperty(key)&&(output[key]=source[key]);return output},'function'!=typeof self.Promise&&_dereq_('es6-promise').polyfill()}}]),Polyfill}();Polyfill.install(),exports.default=Polyfill},{'es6-promise':1}],44:[function(_dereq_,module,exports){'use strict';function checkContinuation(uint8array,start,checkLength){var array=uint8array;if(start+checkLength<array.length){for(;checkLength--;)if(128!=(192&array[++start]))return!1;return!0}return!1}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=function(uint8array){for(var out=[],input=uint8array,i=0,length=uint8array.length;i<length;){if(128>input[i]){out.push(String.fromCharCode(input[i])),++i;continue}else if(192>input[i]);else if(224>
1input[i]){if(checkContinuation(input,i,1)){var ucs4=(31&input[i])<<6|63&input[i+1];if(128<=ucs4){out.push(String.fromCharCode(65535&ucs4)),i+=2;continue}}}else if(240>input[i]){if(checkContinuation(input,i,2)){var _ucs=(15&input[i])<<12|(63&input[i+1])<<6|63&input[i+2];if(2048<=_ucs&&55296!=(63488&_ucs)){out.push(String.fromCharCode(65535&_ucs)),i+=3;continue}}}else if(248>input[i]&&checkContinuation(input,i,3)){var _ucs2=(7&input[i])<<18|(63&input[i+1])<<12|(63&input[i+2])<<6|63&input[i+3];if(65536<_ucs2&&1114112>_ucs2){_ucs2-=65536,out.push(String.fromCharCode(55296|_ucs2>>>10)),out.push(String.fromCharCode(56320|1023&_ucs2)),i+=4;continue}}out.push(String.fromCharCode(65533)),++i}return out.join('')}},{}]},{},[21])(21)})}).call(exports,function(){return this}())},function(){var swfobject=function(){function f(){if(!J){try{var Z=j.getElementsByTagName('body')[0].appendChild(C('span'));Z.parentNode.removeChild(Z)}catch(aa){return}J=!0;for(var X=U.length,Y=0;Y<X;Y++)U[Y]()}}function K(X){J?X():U[U.length]=X}function s(Y){if(typeof O.addEventListener!=D)O.addEventListener('load',Y,!1);else if(typeof j.addEventListener!=D)j.addEventListener('load',Y,!1);else if(typeof O.attachEvent!=D)i(O,'onload',Y);else if('function'==typeof O.onload){var X=O.onload;O.onload=function(){X(),Y()}}else O.onload=Y}function h(){T?V():H()}function V(){var X=j.getElementsByTagName('body')[0],aa=C(r);aa.setAttribute('type',q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable('$version');ab&&(ab=ab.split(' ')[1].split(','),M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)])}else if(10>Y)return Y++,void setTimeout(arguments.callee,10);X.removeChild(aa),Z=null,H()})()}else H()}function H(){var ag=o.length;if(0<ag)for(var af=0;af<ag;af++){var Y=o[af].id,ab=o[af].callbackFn,aa={success:!1,id:Y};if(0<M.pv[0]){var ae=c(Y);if(ae)if(F(o[af].swfVersion)&&!(M.wk&&312>M.wk))w(Y,!0),ab&&(aa.success=!0,aa.ref=z(Y),ab(aa));else if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall,ai.width=ae.getAttribute('width')||'0',ai.height=ae.getAttribute('height')||'0',ae.getAttribute('class')&&(ai.styleclass=ae.getAttribute('class')),ae.getAttribute('align')&&(ai.align=ae.getAttribute('align'));for(var ah={},X=ae.getElementsByTagName('param'),ac=X.length,ad=0;ad<ac;ad++)'movie'!=X[ad].getAttribute('name').toLowerCase()&&(ah[X[ad].getAttribute('name')]=X[ad].getAttribute('value'));P(ai,ah,Y,ab)}else p(ae),ab&&ab(aa)}else if(w(Y,!0),ab){var Z=z(Y);Z&&typeof Z.SetVariable!=D&&(aa.success=!0,aa.ref=Z),ab(aa)}}}function z(aa){var X=null,Y=c(aa);if(Y&&'OBJECT'==Y.nodeName)if(typeof Y.SetVariable!=D)X=Y;else{var Z=Y.getElementsByTagName(r)[0];Z&&(X=Z)}return X}function A(){return!a&&F('6.0.65')&&(M.win||M.mac)&&!(M.wk&&312>M.wk)}function P(aa,ab,X,Z){a=!0,E=Z||null,B={success:!1,id:X};var ae=c(X);if(ae){'OBJECT'==ae.nodeName?(l=g(ae),Q=null):(l=ae,Q=X),aa.id=R,(typeof aa.width==D||!/%$/.test(aa.width)&&310>parseInt(aa.width,10))&&(aa.width='310'),(typeof aa.height==D||!/%$/.test(aa.height)&&137>parseInt(aa.height,10))&&(aa.height='137'),j.title=j.title.slice(0,47)+' - Flash Player Installation';var ad=M.ie&&M.win?'ActiveX':'PlugIn',ac='MMredirectURL='+O.location.toString().replace(/&/g,'%26')+'&MMplayerType='+ad+'&MMdoctitle='+j.title;if(typeof ab.flashvars==D?ab.flashvars=ac:ab.flashvars+='&'+ac,M.ie&&M.win&&4!=ae.readyState){var Y=C('div');X+='SWFObjectNew',Y.setAttribute('id',X),ae.parentNode.insertBefore(Y,ae),ae.style.display='none',function(){4==ae.readyState?ae.parentNode.removeChild(ae):setTimeout(arguments.callee,10)}()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&4!=Y.readyState){var X=C('div');Y.parentNode.insertBefore(X,Y),X.parentNode.replaceChild(g(Y),X),Y.style.display='none',function(){4==Y.readyState?Y.parentNode.removeChild(Y):setTimeout(arguments.callee,10)}()}else Y.parentNode.replaceChild(g(Y),Y)}function g(ab){var aa=C('div');if(M.win&&M.ie)aa.innerHTML=ab.innerHTML;else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad)for(var X=ad.length,Z=0;Z<X;Z++)(1!=ad[Z].nodeType||'PARAM'!=ad[Z].nodeName)&&8!=ad[Z].nodeType&&aa.appendChild(ad[Z].cloneNode(!0))}}return aa}function u(ai,ag,Y){var aa=c(Y),X;if(M.wk&&312>M.wk)return X;if(aa)if(typeof ai.id==D&&(ai.id=Y),M.ie&&M.win){var ah='';for(var ae in ai)ai[ae]!=Object.prototype[ae]&&('data'==ae.toLowerCase()?ag.movie=ai[ae]:'styleclass'==ae.toLowerCase()?ah+=' class="'+ai[ae]+'"':'classid'!=ae.toLowerCase()&&(ah+=' '+ae+'="'+ai[ae]+'"'));var af='';for(var ad in ag)ag[ad]!=Object.prototype[ad]&&(af+='<param name="'+ad+'" value="'+ag[ad]+'" />');aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+'>'+af+'</object>',N[N.length]=ai.id,X=c(ai.id)}else{var Z=C(r);for(var ac in Z.setAttribute('type',q),ai)ai[ac]!=Object.prototype[ac]&&('styleclass'==ac.toLowerCase()?Z.setAttribute('class',ai[ac]):'classid'!=ac.toLowerCase()&&Z.setAttribute(ac,ai[ac]));for(var ab in ag)ag[ab]!=Object.prototype[ab]&&'movie'!=ab.toLowerCase()&&e(Z,ab,ag[ab]);aa.parentNode.replaceChild(Z,aa),X=Z}return X}function e(Z,X,Y){var aa=C('param');aa.setAttribute('name',X),aa.setAttribute('value',Y),Z.appendChild(aa)}function y(Y){var X=c(Y);X&&'OBJECT'==X.nodeName&&(M.ie&&M.win?(X.style.display='none',function(){4==X.readyState?b(Y):setTimeout(arguments.callee,10)}()):X.parentNode.removeChild(X))}function b(Z){var Y=c(Z);if(Y){for(var X in Y)'function'==typeof Y[X]&&(Y[X]=null);Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y),I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split('.');return X[0]=parseInt(X[0],10),X[1]=parseInt(X[1],10)||0,X[2]=parseInt(X[2],10)||0,!!(Y[0]>X[0]||Y[0]==X[0]&&Y[1]>X[1]||Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2])}function v(ac,Y,ad,ab){if(!(M.ie&&M.mac)){var aa=j.getElementsByTagName('head')[0];if(aa){var X=ad&&'string'==typeof ad?ad:'screen';if(ab&&(n=null,G=null),!n||G!=X){var Z=C('style');Z.setAttribute('type','text/css'),Z.setAttribute('media',X),n=aa.appendChild(Z),M.ie&&M.win&&typeof j.styleSheets!=D&&0<j.styleSheets.length&&(n=j.styleSheets[j.styleSheets.length-1]),G=X}M.ie&&M.win?n&&typeof n.addRule==r&&n.addRule(ac,Y):n&&typeof j.createTextNode!=D&&n.appendChild(j.createTextNode(ac+' {'+Y+'}'))}}}function w(Z,X){if(m){var Y=X?'visible':'hidden';J&&c(Z)?c(Z).style.visibility=Y:v('#'+Z,'visibility:'+Y)}}function L(Y){var Z=/[\\\"<>\.;]/,X=null!=Z.exec(Y);return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var D='undefined',r='object',S='Shockwave Flash',q='application/x-shockwave-flash',R='SWFObjectExprInst',x='onreadystatechange',O=window,j=document,t=navigator,T=!1,U=[h],o=[],N=[],I=[],J=!1,a=!1,m=!0,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=!!/webkit/.test(ah)&&parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,'$1')),X=!1,ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r)ab=t.plugins[S].description,ab&&(typeof t.mimeTypes==D||!t.mimeTypes[q]||t.mimeTypes[q].enabledPlugin)&&(T=!0,X=!1,ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,'$1'),ag[0]=parseInt(ab.replace(/^(.*)\..*$/,'$1'),10),ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,'$1'),10),ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,'$1'),10):0);else if(typeof O.ActiveXObject!=D)try{var ad=new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
1ad&&(ab=ad.GetVariable('$version'),ab&&(X=!0,ab=ab.split(' ')[1].split(','),ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]))}catch(Z){}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){M.w3&&((typeof j.readyState!=D&&'complete'==j.readyState||typeof j.readyState==D&&(j.getElementsByTagName('body')[0]||j.body))&&f(),!J&&(typeof j.addEventListener!=D&&j.addEventListener('DOMContentLoaded',f,!1),M.ie&&M.win&&(j.attachEvent(x,function(){'complete'==j.readyState&&(j.detachEvent(x,arguments.callee),f())}),O==top&&function(){if(!J){try{j.documentElement.doScroll('left')}catch(X){return void setTimeout(arguments.callee,0)}f()}}()),M.wk&&function(){return J?void 0:/loaded|complete/.test(j.readyState)?void f():void setTimeout(arguments.callee,0)}(),s(f)))}(),d=function(){M.ie&&M.win&&window.attachEvent('onunload',function(){for(var ac=I.length,ab=0;ab<ac;ab++)I[ab][0].detachEvent(I[ab][1],I[ab][2]);for(var Z=N.length,aa=0;aa<Z;aa++)y(N[aa]);for(var Y in M)M[Y]=null;for(var X in M=null,swfobject)swfobject[X]=null;swfobject=null})}(),l,Q,E,B,n,G;return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab,Y.swfVersion=X,Y.expressInstall=aa,Y.callbackFn=Z,o[o.length]=Y,w(ab,!1)}else Z&&Z({success:!1,id:ab})},getObjectById:function(X){if(M.w3)return z(X)},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:!1,id:ah};M.w3&&!(M.wk&&312>M.wk)&&ab&&ah&&ae&&ag&&Y?(w(ah,!1),K(function(){ae+='',ag+='';var aj={};if(af&&typeof af==r)for(var al in af)aj[al]=af[al];aj.data=ab,aj.width=ae,aj.height=ag;var am={};if(ad&&typeof ad==r)for(var ak in ad)am[ak]=ad[ak];if(Z&&typeof Z==r)for(var ai in Z)typeof am.flashvars==D?am.flashvars=ai+'='+Z[ai]:am.flashvars+='&'+ai+'='+Z[ai];if(F(Y)){var an=u(aj,am,ah);aj.id==ah&&w(ah,!0),X.success=!0,X.ref=an}else{if(aa&&A())return aj.data=aa,void P(aj,am,ah,ac);w(ah,!0)}ac&&ac(X)})):ac&&ac(X)},switchOffAutoHideShow:function(){m=!1},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){return M.w3?u(Z,Y,X):void 0},showExpressInstall:function(Z,aa,X,Y){M.w3&&A()&&P(Z,aa,X,Y)},removeSWF:function(X){M.w3&&y(X)},createCSS:function(aa,Z,Y,X){M.w3&&v(aa,Z,Y,X)},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)&&(Z=Z.split('?')[1]),null==aa)return L(Z);for(var Y=Z.split('&'),X=0;X<Y.length;X++)if(Y[X].substring(0,Y[X].indexOf('='))==aa)return L(Y[X].substring(Y[X].indexOf('=')+1))}return''},expressInstallCallback:function(){if(a){var X=c(R);X&&l&&(X.parentNode.replaceChild(l,X),Q&&(w(Q,!0),M.ie&&M.win&&(l.style.display='block')),E&&E(B)),a=!1}}}}()},function(module,exports,__webpack_require__){(function(swfobject){var declare=__webpack_require__(1),lang=__webpack_require__(2),on=__webpack_require__(3),Evented=__webpack_require__(13),array=__webpack_require__(6),ModuleManager=__webpack_require__(107),BannerCapabilityFlags=__webpack_require__(110),BlockAdBlock=__webpack_require__(112),GAEventRequest=__webpack_require__(34),i18n=__webpack_require__(19),MediaElement=__webpack_require__(25);window.TDSdk=declare([],{NAME:'TDSdk',constructor:function(playerConfig){void 0,this.listeners=[],this.target=new Evented,this.abBlockProcessFinish=!1,this.MediaElement=MediaElement,this._initGoogleAnalytics(),on(this.target,'module-ready',lang.hitch(this,this._onModuleReady));var blockAdBlock=new BlockAdBlock;'undefined'==typeof blockAdBlock.fab?this._onAdBlock(playerConfig,!0):(blockAdBlock.fab.onDetected(lang.hitch(this,this._onAdBlock,playerConfig,!0)),blockAdBlock.fab.onNotDetected(lang.hitch(this,this._onAdBlock,playerConfig,!1)),blockAdBlock.fab.check()),playerConfig.playerReady&&this.addEventListener('player-ready',playerConfig.playerReady),playerConfig.configurationError&&this.addEventListener('configuration-error',playerConfig.configurationError),playerConfig.moduleError&&this.addEventListener('module-error',playerConfig.moduleError),playerConfig.adBlockerDetected&&this.addEventListener('ad-blocker-detected',playerConfig.adBlockerDetected),this.loadModules()},getGAEventRequest:function(){return GAEventRequest},_parseConfig:function(playerConfig,isBlocked){if(!playerConfig||!playerConfig.coreModules)return{coreModules:[]};var banners=[],companionAdSelectionSettings={},filteredArr=array.filter(playerConfig.coreModules,function(item){return'SyncBanners'==item.id});if(filteredArr.length&&!isBlocked){var syncBanners=filteredArr[0];companionAdSelectionSettings=syncBanners,array.forEach(syncBanners.elements,function(element){if(void 0!=element.width&&void 0!=element.height){var token=element.width+'x'+element.height;-1!=array.indexOf(BannerCapabilityFlags,token)&&banners.push(token)}},this)}if(filteredArr=array.filter(playerConfig.coreModules,function(item){return'MediaPlayer'==item.id}),filteredArr.length){var mediaPlayer=filteredArr[0];mediaPlayer.adBlockerDetected=isBlocked,mediaPlayer.adBlockerDetected&&void 0!=mediaPlayer.plugins&&(this._removeMediaplayerPlugins('vastAd',mediaPlayer.plugins),this._removeMediaplayerPlugins('mediaAd',mediaPlayer.plugins)),mediaPlayer.companionAdSelectionSettings=companionAdSelectionSettings,void 0==mediaPlayer.defaultTrackingParameters&&(mediaPlayer.defaultTrackingParameters={}),mediaPlayer.defaultTrackingParameters.banners=void 0==mediaPlayer.defaultTrackingParameters.banners?banners:this._unique(mediaPlayer.defaultTrackingParameters.banners.concat(banners
1)),mediaPlayer.defaultTrackingParameters.log={},mediaPlayer.defaultTrackingParameters.log.tdsdk='js-'+this.version.value.substring(0,3),mediaPlayer.defaultTrackingParameters.log.pname=this.NAME,mediaPlayer.defaultTrackingParameters.log.pversion=this.version.value.substring(0,3)}return playerConfig.analytics&&'object'==typeof playerConfig.analytics?playerConfig.analytics.active?(GAEventRequest.setProperties(playerConfig.analytics.active,playerConfig.analytics.appInstallerId,playerConfig.analytics.debug,playerConfig.analytics.platformId,playerConfig.analytics.trackingId,playerConfig.analytics.sampleRate,playerConfig.analytics.trackingEvents,playerConfig.analytics.category),GAEventRequest.loadGoogleAnalytics()):GAEventRequest.setActive(!1):GAEventRequest.setActive(!1),'string'==typeof playerConfig.locale&&i18n.setLocalization(playerConfig.locale),playerConfig},_removeMediaplayerPlugins:function(pluginToRemove,pluginsArray){array.forEach(pluginsArray,function(item,i){item&&item.id==pluginToRemove&&pluginsArray.splice(i,1)})},_onModuleReady:function(e){e.data.module.api&&declare.safeMixin(this,e.data.module.api),this[e.data.id]=e.data.module},_onAdBlock:function(playerConfig,isBlocked){playerConfig&&(this.abBlockProcessFinish=!0,playerConfig.adBlockerDetected=isBlocked,this.moduleManager=new ModuleManager(this._parseConfig(playerConfig,isBlocked),this.target),this.loadModulesCalled&&this.moduleManager.loadModules())},loadModules:function(){this.abBlockProcessFinished?this.moduleManager.loadModules():this.loadModulesCalled=!0},loadModule:function(moduleId,moduleConfig){this.moduleManager.loadModule(moduleId,moduleConfig)},getModuleById:function(moduleId){return this.moduleManager.getModuleById(moduleId)},_initGoogleAnalytics:function(){void 0,GAEventRequest.av=this.version.value+'.'+this.version.build,GAEventRequest.aid=this.version.value},addEventListener:function(eventName,callback){var itemIndex=-1;array.forEach(this.listeners,function(item,index){item.eventName==eventName&&item.callback==callback&&(itemIndex=index)},this),-1==itemIndex&&this.listeners.push({eventName:eventName,callback:callback,listener:on(this.target,eventName,lang.hitch(this,callback))})},removeEventListener:function(eventName,callback){var itemIndex=-1;array.forEach(this.listeners,function(item,index){item.eventName==eventName&&item.callback==callback&&(itemIndex=index)},this),-1<itemIndex&&(this.listeners[itemIndex].listener.remove(),this.listeners.splice(itemIndex,1))},_unique:function(arr){var test={};return array.filter(arr,function(val){return!test[val]&&(test[val]=!0)})},version:{value:'2.9.69',build:'513',codename:'bitter lime'},flash:{available:0<swfobject.getFlashPlayerVersion().major,version:swfobject.getFlashPlayerVersion()}})}).call(exports,__webpack_require__(62))},function(module,exports,__webpack_require__){var AudioPriority=__webpack_require__(75),OsPlatform=__webpack_require__(21),i18n=__webpack_require__(19),ConnectionIterator=__webpack_require__(144),LiveStreamConfig=__webpack_require__(145),LocationHelper=__webpack_require__(24),MediaElement=__webpack_require__(25),_=__webpack_require__(7),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(6),__webpack_require__(1),__webpack_require__(2),__webpack_require__(4),__webpack_require__(3),__webpack_require__(18),__webpack_require__(17),__webpack_require__(8),__webpack_require__(11),__webpack_require__(20),__webpack_require__(66),__webpack_require__(12),__webpack_require__(139),__webpack_require__(138),__webpack_require__(64)],__WEBPACK_AMD_DEFINE_RESULT__=function(array,declare,lang,has,on,topic,win,dom,domConstruct,domAttr,AdManager,coreModule,Html5,Flash,StreamingMode){var module=declare([coreModule],{LIVE_PLAYING:'livePlaying',LIVE_STOPPED:'liveStopped',statusMap:{GETTING_STATION_INFORMATION:{status:'gettingStationInformation',code:'GETTING_STATION_INFORMATION'},STATION_NOT_FOUND:{status:'stationNotFound',code:'STATION_NOT_FOUND'},PLAY_NOT_ALLOWED:{status:'playbackNotAllowed',code:'PLAY_NOT_ALLOWED'}},constructor:function(config){void 0,this.inherited(arguments);var self=this;'function'==typeof __cmp?(void 0,__cmp('getConsentData',null,function(consentData){self.consentData=consentData,self.config.idSync!=void 0&&self._loadIdSync(self.config.idSync)})):'function'==typeof __tcfapi?__tcfapi('getTCData',2,(tcData,success)=>{success?(self.consentData=tcData,self.config.idSync!=void 0&&self._loadIdSync(self.config.idSync)):void 0}):this.config.idSync!=void 0&&this._loadIdSync(this.config.idSync),this.liveStreamConfig=null,this.streamingConnections=null,this.liveStreamConfiguration=null,this.tech=null,this.techErrors=[],this.techPriority=this.config.techPriority&&0<this.config.techPriority.length?this.config.techPriority:['Html5','Flash'],this.geoTargeting=this.config.geoTargeting==void 0?{desktop:{isActive:!0},iOS:{isActive:!1},android:{isActive:!1}}:this.config.geoTargeting,this.isGeoTargetingActive=!1,this.position=null,this.geoTargeting&&this._initGeoTargeting(),this.hls=!(config.hls!=void 0)||config.hls,this.audioAdaptive=config.audioAdaptive!=void 0&&config.audioAdaptive,config.audioAdaptive&&(config.forceHls=!0),this.adManager=null,this._lowActivated=!1,this._isPlaying=!1,this.fallbackTried=!1,this.api={play:lang.hitch(this,this._play),pause:lang.hitch(this,this._pause),stop:lang.hitch(this,this._stop),resume:lang.hitch(this,this._resume),seekFromLive:lang.hitch(this,this._seekFromLive),seek:lang.hitch(this,this._seek),changePlayBackRate:lang.hitch(this,this._changePlayBackRate),seekLive:lang.hitch(this,this.seekLive),restartConnectionTimeOut:lang.hitch(this,this.restartConnectionTimeOut),setVolume:lang.hitch(this,this.setVolume),getVolume:lang.hitch(this,this.getVolume),mute:lang.hitch(this,this.mute),unMute:lang.hitch(this,this.unMute),playAd:lang.hitch(this,this.playAd),skipAd:lang.hitch(this,this.skipAd),destroyAd:lang.hitch(this,this.destroyAd),initMediaElement:lang.hitch(this,this._initMediaElement),destroy:lang.hitch(this,this._destroy),reloadSyncBanner:lang.hitch(this,this.reloadSyncBanner),getCloudStreamInfo:lang.hitch(this,this._getCloudStreamInfo),playProgram:lang.hitch(this,this._playProgram)},topic.subscribe('api/request',lang.hitch(this,this._onApiInternalRequest)),topic.subscribe('streamingModeChange',lang.hitch(this,this._switchStreamingMode))},start:function(){void 0,on(this.target,'tech-ready',lang.hitch(this,this._onTechReady)),on(this.target,'tech-error',lang.hitch(this,this._onTechError)),this._loadTech(this.techPriority[0])},_onApiInternalRequest:function(){var action=arguments[0],fn=lang.hitch(this,this.INTERNAL_REQUEST_API_FUNCTIONS[action]);'function'==typeof fn&&fn(arguments[1])},_onApiRequestGetVastInstream:function(adBreakData){void 0,void 0,null==adBreakData.vastUrl?null!=adBreakData.adVast&&this._getAdManager().playAd('vastAd',{rawXML:adBreakData.adVast,skipMediaAdPlayback:!0,adBreak:!0}):this._getAdManager().playAd('vastAd',{url:adBreakData.vastUrl,skipMediaAdPlayback:!0,adBreak:!0})},_switchStreamingMode:function(){var mode=arguments[0];mode==StreamingMode.CLOUD_STREAMING?(this._stop(),setTimeout(()=>{this._playTimeshift()},500)):(this._stop(),setTimeout(()=>{let params=this._getCurrentLiveApiParams();params.timeShift=!1,params.isProgram=!1,this._play(params)},500))},_hqTags:[],addHqTag:function(tag){-1==array.indexOf(this._hqTags,tag)&&this._hqTags.push(tag)},removeHqTag:function(tag){var idx=array.indexOf(this._hqTags,tag);-1!=idx&&this._hqTags.splice(idx,1)},_lowTags:['low-bw'],addLowTag:function(tag){-1==array.indexOf(this._lowTags,tag)&&this._lowTags.push(tag)},removeLowTag:function(tag){var idx=array.indexOf(this._lowTags,tag);-1!=idx&&this._lowTags.splice(idx,1)},_hqEnabled:!1,enableHQ:function(){this._hqEnabled=!0,!this.isHQ()&&this.isPlaying()&&(this._stop(),this._play(this._getCurrentLiveApiParams()))},disableHQ:function(){this._hqEnabled=!1,this.isHQ()&&this.isPlaying()&&(this._stop(),this._play(this._getCurrentLiveApiParams()))},_lowEnabled:!0,enableLow:function(){this._lowEnabled=!0,this._refreshConnectionIterator()},disableLow:function(){this._lowEnabled=!1,this.isLow()&&this.isPlaying()&&(this._stop(),this._play(this._getCurrentLiveApiParams()))},activateLow:function(){this._lowEnabled&&(this._lowActivated=!0,!this.isLow()&&this.isPlaying()?(this._stop(),this._play(this._getCurrentLiveApiParams())):this._refreshConnectionIterator())},deactivateLow:function(){this._lowActivated=!1,this.isLow()&&this.isPlaying()?(this._stop(),this._play(this._getCurrentLiveApiParams())):this._refreshConnectionIterator()},_refreshConnectionIterator:function(streamingConnections){if(streamingConnections)return 0<streamingConnections.length?(this.emit
1('stream-config-ready'),this.tech.setConnectionIterator(new ConnectionIterator(streamingConnections)),!0):(this.emit('stream-config-error',{errors:this.liveStreamConfig.mountPointsError}),this.tech.setConnectionIterator(null),this._emitStreamStatusByCode(this.statusMap.STATION_NOT_FOUND),!1)},_loadTech:function(techType){var successCallback=lang.hitch(this,this._techLoaded),errorCallback=lang.hitch(this,this._techLoadingError);switch(techType){case'Html5':this._techLoaded(Html5,techType);break;case'Flash':this._techLoaded(Flash,techType);break;default:}},_techLoaded:function(TechInstance,techType){void 0,this.tech=new TechInstance(this.config,this.target,techType),this.tech.start()},_techLoadingError:function(error){void 0,this.emit('module-error',{id:'MediaPlayer',error:error})},_onTechReady:function(){void 0,this.liveStreamConfig=new LiveStreamConfig(this.config.platformId,OsPlatform,this.tech.type,this.config.hls,this.config.audioAdaptive,this.config.forceHls,this.config.forceHslts,this.config.playerServicesRegion),on(this.target,'stream-start',lang.hitch(this,this._onStreamStart)),on(this.target,'stream-stop',lang.hitch(this,this._onStreamStop)),this.emit('module-ready',{id:'MediaPlayer',module:this})},_onStreamStart:function(){this._isPlaying=!0},_onStreamStop:function(){this._isPlaying=!1},_onTechError:function(e){void 0,1<this.techPriority.length&&!1==this.fallbackTried?(this.techErrors.push(e),this.fallbackTried=!0,this._loadTech(this.techPriority[1])):(this.techErrors.push(e),this.emit('module-error',{id:'MediaPlayer',errors:this.techErrors}))},_initGeoTargeting:function(){has('ios')!=void 0&&this.geoTargeting.iOS!=void 0&&this.geoTargeting.iOS.isActive!=void 0&&!0==this.geoTargeting.iOS.isActive?this.isGeoTargetingActive=!0:has('android')!=void 0&&this.geoTargeting.android!=void 0&&this.geoTargeting.android.isActive!=void 0&&!0==this.geoTargeting.android.isActive?this.isGeoTargetingActive=!0:has('ios')==void 0&&has('android')==void 0&&this.geoTargeting.desktop!=void 0&&this.geoTargeting.desktop.isActive!=void 0&&!0==this.geoTargeting.desktop.isActive&&(this.isGeoTargetingActive=!0),!0==this.isGeoTargetingActive&&this._getLocation()},_play:function(params){if(void 0!=params){if(this.tech.prepare(),this._initMediaElement(),params.timeShift||params.forceTimeShift){var transports=this.liveStreamConfig.TIMESHIFT_TRANSPORT;params.timeshiftEnabled=!1,this.liveStreamConfig=new LiveStreamConfig(this.config.platformId,OsPlatform,this.tech.type,!0,this.config.audioAdaptive,!0,!0,this.config.playerServicesRegion)}else{var transports=this.liveStreamConfig.DEFAULT_TRANSPORTS;params.timeshiftEnabled=!1}if(params.forceTimeShift)return params.timeshiftEnabled=!0,this._liveApiParams=params,void this._playTimeshift();var self=this;if(params.trackingParameters=this._getFinalTrackingParameters(params.trackingParameters),void 0!=params.file&&''!=params.file)self.tech.play(params);else{this._emitStreamStatusByCode(this.statusMap.GETTING_STATION_INFORMATION),this._liveApiParams=params;var liveStreamConfigParams={station:params.station,mount:params.mount,transports:transports},mountTags=[];this._hqEnabled&&(mountTags=mountTags.concat(this._hqTags)),this._lowEnabled&&(mountTags=mountTags.concat(this._lowTags)),this.liveStreamConfig.getStreamingConnections(liveStreamConfigParams,mountTags,!1,!1).then(function(streamingConnections){this.streamingConnections=streamingConnections,self._refreshConnectionIterator(streamingConnections)&&self.tech.play(params)}).catch(function(error){self.emit('stream-config-load-error',{error:error})})}}},_playTimeshift:function(isProgram,programID,offset){if(void 0==this._getCurrentLiveApiParams)return;let params=this._getCurrentLiveApiParams();params.isProgram=isProgram,params.offset=offset,params.timeShift=!0,params.timeshiftEnabled=!0,this.tech.prepare(),this._initMediaElement();var self=this;void 0,this._emitStreamStatusByCode(this.statusMap.GETTING_STATION_INFORMATION);var transports=this.liveStreamConfig.TIMESHIFT_TRANSPORT,liveStreamConfigParams={station:params.station,mount:params.mount,transports:transports,isProgram:isProgram,programID:programID};this.liveStreamConfig.getStreamingConnections(liveStreamConfigParams,[],!1,!0).then(function(streamingConnections){this.streamingConnections=streamingConnections,streamingConnections&&0==streamingConnections.length?self.emit('stream-config-load-error',{error:'No Timeshift mount enabled'}):self._refreshConnectionIterator(streamingConnections)&&self.tech.play(params)}).catch(function(error){self.emit('stream-config-load-error',{error:error})})},_changePlayBackRate:function(rate){this.tech.changePlayBackRate(rate)},isPlaying:function(){return this._isPlaying},hasHQ:function(){var self=this;return _.some(this._hqTags,function(tag){self.tagsToLookup(tag,self.streamingConnections)})},tagsToLookup:function(tag,streamingConnections){return _.some(streamingConnections,function(sc){return _.some(sc.tags,function(sc_tag){return sc_tag.name===tag})})},isHQ:function(){var self=this;return!!this.tech.currentConnection()&&null!=this.tech.currentConnection()&&_.some(this._hqTags,function(tag){self.tagsToLookup(tag,[self.tech.currentConnection()])})},hasLow:function(){var self=this;return _.some(this._lowTags,function(tag){self.tagsToLookup(tag,self.streamingConnections)})},isLow:function(){var self=this;return!!this.tech.currentConnection()&&null!=this.tech.currentConnection()&&_.some(this._lowTags,function(tag){self.tagsToLookup(tag,[self.tech.currentConnection()])})},_pause:function(){void 0,this.tech.pause()},_stop:function(){void 0,this.tech.stop()},_resume:function(){void 0,this.tech.resume()},_seek:function(seekOffset){void 0,this.tech.seek(seekOffset)},_seekFromLive:function(seconds){void 0,this.tech.seekFromLive(seconds)},_getCloudStreamInfo:function(stationName){var liveStreamConfigParams={station:stationName,transports:this.liveStreamConfig.TIMESHIFT_TRANSPORT},context=this;this.liveStreamConfig.getStreamingConnections(liveStreamConfigParams,[],!1,!0).then(function(streamingConnections){if(streamingConnections){let streamInfoUrl='https://'+streamingConnections[0].mrHost
1+'/'+streamingConnections[0].mount+'/CLOUD/stream-info';void 0,fetch(streamInfoUrl).then(response=>{if(!response.ok)throw new Error(`Request failed with status ${reponse.status}`);return response.json()}).then(lang.hitch(context,context._onCloudStreamLoadInfoComplete)).catch(error=>{context.emit('timeshift-program-load-error',{error:error})})}}).catch(function(){context.emit('timeshift-program-load-error',{error:'Could not load program'})})},_onCloudStreamLoadInfoComplete:function(data){data||(programs='{"programs":[]}',this.emit('timeshift-info',data.programs)),data.programs.properties&&(programs={maximum_rewind_time_sec:data.maximum_rewind_time_sec,programs:[data.programs]},this.emit('timeshift-info',programs))},_playProgram:function(programID,offset,station){void 0,this._stop();void 0==station||(this._liveApiParams?(this._liveApiParams.station=station,this._liveApiParams.timeShift=!0,this._liveApiParams.timeshiftEnabled=!0):this._liveApiParams={station:station,timeShift:!0,timeshiftEnabled:!0},this._stop(),setTimeout(()=>{this._playTimeshift(!0,programID,offset)},500))},seekLive:function(){void 0,this.tech.seekLive()},restartConnectionTimeOut:function(){void 0,this.tech.restartConnectionTimeOut()},setVolume:function(volumePercent){void 0,this.tech.setVolume(volumePercent)},getVolume:function(){return this.tech.getVolume()},mute:function(){void 0,this.tech.mute()},unMute:function(){void 0,this.tech.unMute()},playAd:function(adServerType,config){void 0,config.trackingParameters=this._getFinalTrackingParameters(config.trackingParameters),this._getAdManager().playAd(adServerType,config),this.tech.playAdCalled=!0},skipAd:function(){void 0,this._getAdManager().skipAd()},reloadSyncBanner:function(){void 0,this._getAdManager().reloadSyncBanner()},destroyAd:function(){void 0,this._getAdManager().destroyAd(!0)},_initMediaElement:function(){void 0,MediaElement.init()},_destroy:function(){this._stop(),setTimeout(function(){var playerElement=document.getElementById('tdplayer_ondemand');playerElement&&domConstruct.destroy(playerElement),MediaElement.destroyAudioElement(),MediaElement.resetAudioNode()},500)},_getAdManager:function(){return null==this.adManager&&(this.adManager=new AdManager(this.tech,this.tech.type,this.target,this.config)),this.adManager},_emitStreamStatusByCode:function(statusMapEntry){var statusMessages=i18n.getLocalization();void 0==statusMessages||statusMessages[statusMapEntry.status]&&this.emit('stream-status',{code:statusMapEntry.code,status:statusMessages[statusMapEntry.status]})},_getLocation:function(){window.navigator.geolocation&&window.navigator.geolocation.getCurrentPosition(lang.hitch(this,this._setPosition),lang.hitch(this,this._getPositionErrorHandler),{enableHighAccuracy:!0,timeout:2e3})},_setPosition:function(position){this.position=position!=void 0&&position.coords.latitude!=void 0&&position.coords.longitude!=void 0?position:null},_getPositionErrorHandler:function(){void 0,this.position=null},_getGeoTargetingPos:function(trackingParameters){return null!=this.position&&void 0!=this.position&&void 0!=this.position.coords.latitude&&void 0!=this.position.coords.longitude?void 0==trackingParameters?{lat:parseFloat(this.position.coords.latitude.toFixed(1)),long:parseFloat(this.position.coords.longitude.toFixed(1))}:(trackingParameters.lat=parseFloat(this.position.coords.latitude.toFixed(1)),trackingParameters.long=parseFloat(this.position.coords.longitude.toFixed(1)),trackingParameters):trackingParameters},_getFinalTrackingParameters:function(trackingParameters){for(var userData in void 0==trackingParameters&&(trackingParameters={}),trackingParameters.tdsdk=this.config.defaultTrackingParameters.log.tdsdk,trackingParameters.swm=!!this.config.streamWhileMuted&&this.config.streamWhileMuted,this.isGeoTargetingActive&&(trackingParameters=this._getGeoTargetingPos(trackingParameters)),_.isEmpty(this.config.defaultTrackingParameters.banners)&&(this.config.defaultTrackingParameters.banners=[],this.config.defaultTrackingParameters.banners.push('none')),'Flash'!=this.tech.type||this.config.adBlockerDetected||-1!==this.config.defaultTrackingParameters.banners.indexOf('none')||(-1==array.indexOf(this.config.defaultTrackingParameters.banners,'swf')&&this.config.defaultTrackingParameters.banners.push('swf'),-1==array.indexOf(this.config.defaultTrackingParameters.banners,'vpaid')&&this.config.defaultTrackingParameters.banners.push('vpaid')),trackingParameters.pname||(trackingParameters.pname=this.config.defaultTrackingParameters.log.pname,trackingParameters.pversion=this.config.defaultTrackingParameters.log.pversion),void 0!=this.config.defaultTrackingParameters.banners&&this.config.defaultTrackingParameters.banners.length&&(void 0!=trackingParameters.banners&&trackingParameters.banners.length&&-1==trackingParameters.banners.indexOf(this.config.defaultTrackingParameters.banners.join())?trackingParameters.banners+=','+this.config.defaultTrackingParameters.banners.join():trackingParameters.banners=this.config.defaultTrackingParameters.banners.join()),this.config.defaultTrackingParameters.user)trackingParameters[userData]=this.config.defaultTrackingParameters.user[userData];return this.consentData&&(trackingParameters.gdpr=this.consentData.gdprApplies?1:0,trackingParameters.gdpr_consent=this.consentData.consentData?this.consentData.consentData:this.consentData.tcString),trackingParameters},_getCurrentLiveApiParams:function(){return this._liveApiParams},_loadIdSync:function(config){var queryParam=this._getIdSyncQueryParam(config);switch(dom.byId('idSyncScript',document)&&domConstruct.destroy(dom.byId('idSyncScript',document)),scriptTag=domConstruct.create('script',{id:'idSyncScript'},dom.byId(this.config.playerId,document)),domAttr.set(scriptTag,'type','text/javascript'),this.config.platformId){case'dev01':d
1omAttr.set(scriptTag,'src','//playerservices.dev01.stw:8082/api/idsync.js?'+queryParam);break;case'preprod01':domAttr.set(scriptTag,'src','//playerservices.preprod01.streamtheworld.net/api/idsync.js?'+queryParam);break;case'preprodsecured01':domAttr.set(scriptTag,'src','https://playerservices.preprod01.streamtheworld.net/api/idsync.js?'+queryParam);break;default:domAttr.set(scriptTag,'src','//playerservices.live.streamtheworld.com/api/idsync.js?'+queryParam);}document.getElementsByTagName('body')[0].appendChild(scriptTag)},_getIdSyncQueryParam:function(config){var queryParam;if(config.station?queryParam='station='+config.station:config.stationId?queryParam='stationId='+config.stationId:config.mount&&(queryParam='mount='+config.mount),void 0!=queryParam){this.consentData&&(config.gdpr=this.consentData.gdprApplies?1:0,config.gdpr_consent=this.consentData.consentData?this.consentData.consentData:this.consentData.tcString),queryParam=config.gdpr&&config.gdpr.toString().match(/^[0,1]$/g)?queryParam+'&gdpr='+config.gdpr:queryParam,queryParam=config.gdpr_consent?queryParam+'&gdpr_consent='+config.gdpr_consent:queryParam;var dob=config.dob&&!isNaN(Date.parse(config.dob))?new Date(config.dob.replace(/-/g,'/')):null;if(dob){var year=dob.getFullYear(),month=10>dob.getMonth()+1?'0'+(dob.getMonth()+1):dob.getMonth()+1,day=10>dob.getDate()?'0'+dob.getDate():dob.getDate();queryParam=dob?queryParam+'&dob='+year+'-'+month+'-'+day:queryParam}return queryParam=config.yob&&!isNaN(config.yob)&&-1===queryParam.indexOf('dob')?queryParam+'&yob='+config.yob:queryParam,queryParam=config.age&&!isNaN(config.age)&&0<config.age&&125>=config.age&&-1===queryParam.indexOf('dob')&&-1===queryParam.indexOf('yob')?queryParam+'&age='+config.age:queryParam,queryParam=config.gender&&config.gender.match(/[m,f,o]/g)&&1===config.gender.length?queryParam+'&gender='+config.gender:queryParam,queryParam=config.ip&&config.ip.match(/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/g)?queryParam+'&ip='+config.ip:queryParam,queryParam}}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var Platform=__webpack_require__(14),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(16),__webpack_require__(2),__webpack_require__(9),__webpack_require__(12),__webpack_require__(159)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,Deferred,lang,XhrProvider,coreModule,Song){var npe=declare([coreModule],{constructor:function(config){void 0,this.platform=new Platform(config.platformId),this.library=[],this.inherited(arguments)},start:function(){void 0,this.emit('module-ready',{id:'Npe',module:this})},loadNpeMetadata:function(npUrl,artist,title){var npeId=this._urlToNPEId(npUrl),song=this.getSongByNpeId(npeId);if(null!=song){this.emit('npe-song',{song:song});var deferred=new Deferred;return deferred.resolve({song:song}),deferred}return this._fetchData(!1,npeId,npUrl,artist,title,new Deferred)},getSongByNpeId:function(npeId){for(var libraryLength=this.library.length,i=0;i<libraryLength;i++)if(this.library[i].npeId==npeId)return this.library[i];return null},getDynamicUrl:function(){return this.platform.endpoint.npe},_getDynamicSongUrl:function(artist,title){return this.getDynamicUrl()+'song?artist='+encodeURIComponent(artist)+'&title='+encodeURIComponent(title)},_fetchData:function(isDynamicCall,npeId,npUrl,artist,title,deferred){isDynamicCall&&(npUrl=this._getDynamicSongUrl(artist,title));var xhrProv=new XhrProvider;return xhrProv.request(npUrl,{npeId:npeId,npUrl:npUrl,isDynamicCall:isDynamicCall,artist:artist,title:title,deferred:deferred},this._getRequestArgs(),lang.hitch(this,this._onLoadComplete),lang.hitch(this,this._onLoadError)),deferred},_onLoadError:function(requestData){return!1==requestData.isDynamicCall?void this._fetchData(!0,requestData.npeId,null,requestData.artist,requestData.title,requestData.deferred):(this.emit('npe-song-error',{npeId:this._urlToNPEId(requestData.npUrl)}),requestData.deferred.reject({npeId:this._urlToNPEId(requestData.npUrl)}))},_onLoadComplete:function(requestData,data){var song=new Song(data.song,this._urlToNPEId(requestData.npUrl),this.config.platformId);
1return this.library.push(song),this.emit('npe-song',{song:song}),requestData.deferred.resolve({song:song})},_getRequestArgs:function(){return{handleAs:'json',preventCache:!1,headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}}},_urlToNPEId:function(npUrl){if(null==npUrl||npUrl==void 0||''==npUrl)return null;var idx=npUrl.lastIndexOf('/');return npUrl.substr(idx-2,2)+npUrl.substring(idx+1,npUrl.lastIndexOf('.'))}});return npe}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var Platform=__webpack_require__(14),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(12),__webpack_require__(9)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,coreModule,XhrProvider){var module=declare([coreModule],{constructor:function(config){void 0,this.platform=new Platform(config.platformId),this.inherited(arguments)},start:function(){void 0,this.emit('module-ready',{id:'PlayerWebAdmin',module:this})},load:function(mount,streamid){var successCallback=lang.hitch(this,this._onLoadComplete),errorCallback=lang.hitch(this,this._onLoadError),xhrProv=new XhrProvider,requestArgs=this._getRequestArgs(mount,streamid);xhrProv.request(this.platform.endpoint.playerWebAdmin,requestArgs.query,{handleAs:'xml',preventCache:!0,query:requestArgs.query,headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}},function(query,data){successCallback(mount,JSON.parse(data))},function(query,error){errorCallback(mount,'An unexpected error occurred: '+error)})},_onLoadError:function(mount,error){void 0,this.emit('pwa-data-error',{mount:mount,error:error})},_onLoadComplete:function(mount,data){void 0,void 0,void 0,this.emit('pwa-data-loaded',{mount:mount,config:data})},_getRequestArgs:function(mount,streamid){return{jsonp:'callback',preventCache:!0,query:{callsign:mount,streamid:streamid}}}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(6),__webpack_require__(8),__webpack_require__(3),__webpack_require__(11),__webpack_require__(12),__webpack_require__(113)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,array,dom,on,domConstruct,coreModule,Companions){var module=declare([coreModule],{LEGACY:'legacy',VAST:'vast',constructor:function(config){void 0,this.inherited(arguments),this._vastCompanionPriority=config.vastCompanionPriority||['static','iframe','html'],this.companions=new Companions},start:function(){void 0,this.config.elements&&(void 0,on(this.target,'vast-process-complete',lang.hitch(this,this._onVastProcessComplete)),on(this.target,'vast-companions-ready',lang.hitch(this,this._onVastCompanionsReady)),on(this.target,'ad-break-cue-point',lang.hitch(this,this._onAdBreakCuePoint)),on(this.target,'ad-break-cue-point-complete',lang.hitch(this,this._onAdBreakCuePointComplete)),on(this.target,'stream-stop',lang.hitch(this,this._onStreamStop))),this.emit('module-ready',{id:'SyncBanners',module:this})},getSyncedElementBySize:function(width,height){var element=null;return array.forEach(this.config.elements,function(item){item.width==width&&item.height==height&&(element=item)},this),element},_onAdBreakCuePoint:function(e){void 0,void 0;var adBreakData=e.data.adBreakData,adUrl=adBreakData.url;if(adBreakData.isVastInStream)this._cleanAdVastListeners(),this.vastProcessCompleteListener=on(this.target,'vast-process-complete',lang.hitch(this,this._onVastProcessComplete)),this.vastErrorListener=on(this.target,'ad-playback-error',lang.hitch(this,this._onVastAdPlaybackError));else if(adUrl&&1<adUrl.length&&-1!=adUrl.indexOf('|')){var primaryElementUrl=adUrl.split('|')[1],secondaryElementUrl=adUrl.split('|')[0];primaryElementUrl&&1<primaryElementUrl.length&&null!=this.getSyncedElementBySize(300,250)&&(void 0,this.emit
1('ad-break-synced-element',{type:this.LEGACY,id:this.getSyncedElementBySize(300,250).id,url:primaryElementUrl}),this._loadElementIframe(this.getSyncedElementBySize(300,250).id,primaryElementUrl,300,250)),secondaryElementUrl&&1<secondaryElementUrl.length&&null!=this.getSyncedElementBySize(728,90)&&(void 0,this.emit('ad-break-synced-element',{type:this.LEGACY,id:this.getSyncedElementBySize(728,90).id,url:secondaryElementUrl}),this._loadElementIframe(this.getSyncedElementBySize(728,90).id,secondaryElementUrl,728,90))}},_onAdBreakCuePointComplete:function(){void 0,this.config.keepElementsVisible||this._hideElements()},_onStreamStop:function(){this._hideElements()},_hideElements:function(){var bigboxElement=this.getSyncedElementBySize(300,250);null!=bigboxElement&&null!=dom.byId(bigboxElement.id,document)&&domConstruct.empty(dom.byId(bigboxElement.id,document));var lbElement=this.getSyncedElementBySize(728,90);null!=lbElement&&null!=dom.byId(lbElement.id,document)&&domConstruct.empty(dom.byId(lbElement.id,document))},_loadElementIframe:function(containerId,adSpotUrl,width,height){var container=dom.byId(containerId,document);null==container||(domConstruct.empty(container),domConstruct.create('iframe',{src:adSpotUrl,width:width,height:height,scrolling:'no',frameborder:0,marginheight:0,marginwidth:0,allowtransparency:!0,style:{margin:0,padding:0}},container))},_showVastCompanions:function(e){void 0,void 0,this._cleanAdVastListeners();var vastCompanions=this._filterCompanionAds(e.data.companions);vastCompanions&&vastCompanions.length&&array.forEach(vastCompanions,function(item,index){var syncAdElement=this.getSyncedElementBySize(item.width,item.height);null!=syncAdElement&&null!=dom.byId(syncAdElement.id,document)&&(this.emit('ad-break-synced-element',{type:this.VAST,id:syncAdElement.id,data:vastCompanions[index]}),this.companions.loadVASTCompanionAd(syncAdElement.id,vastCompanions[index]))},this)},_onVastProcessComplete:function(e){void 0,this._showVastCompanions(e)},_onVastCompanionsReady:function(e){void 0,this._showVastCompanions(e)},_onVastAdPlaybackError:function(){void 0,void 0,this._cleanAdVastListeners()},_cleanAdVastListeners:function(){this.vastProcessCompleteListener&&this.vastProcessCompleteListener.remove(),this.vastErrorListener&&this.vastErrorListener.remove()},_filterCompanionAds:function(companionAds){if(!companionAds||!companionAds.length)return companionAds;var companions=[],size=[];return array.forEach(this._vastCompanionPriority,function(item){array.forEach(companionAds,function(companionAd){var companionAdSize=companionAd.width+companionAd.height;companionAd.resourceType.name==item&&0>array.indexOf(size,companionAdSize)&&(companions.push(companionAd),size.push(companionAdSize))},this)},this),companions}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(12),__webpack_require__(8),__webpack_require__(11)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,coreModule,dom,domConstruct){var targetspot=declare([coreModule],{constructor:function(){void 0,this.inherited(arguments)},start:function(){void 0,this.emit('module-ready',{id:'TargetSpot',module:this})},embed:function(containerId,stationId,volume,prl){var tsWrapper=domConstruct.create('div',{id:'tsWrapper'},dom.byId(containerId,document));window.ts_ready=lang.hitch(this,this._tsReady);try{window.ts_swf_embed(tsWrapper.id,this._getComponentSettings(stationId,volume,prl))}catch(e){this.emit('module-error',{id:'TargetSpot',error:'Error in targetSpot::embed: '+e.message})}},_getComponentSettings:function(stationId,volume,prl){return{w:300,h:250,prl:prl,pageDomain:'player.tritondigital.com',htmlBanner:0,s:stationId,v:volume}},playAd:function(duration){void 0,window.ts_streamEvent({eventType:'playAd',eventDuration:duration})},playPreroll:function(){void 0,window.ts_streamEvent({eventType:'tsPlayPreroll'})},interruptAd:function(){void 0,window.ts_streamEvent({eventType:'interruptAd'})},setStationId:function(stationId){void 0,window.ts_setStation({stationId:stationId})},setVolume:function(volume){void 0,window.ts_setVolume({volume:volume})},ts_setTargeting:function(eventType,eventData){void 0,window.ts_setTargeting({eventType:eventType,eventData:eventData})},_tsReady:function(){void 0,window.ts_mutePlayer=lang.hitch(this,this._ts_mutePlayer),window.ts_unmutePlayer=lang.hitch(this,this._ts_unmutePlayer),window.ts_noAds=lang.hitch(this,this._ts_noAds),window.ts_noPreRoll=lang.hitch(this,this._ts_noPreRoll),window.ts_adStarted=lang.hitch(this,this._ts_adStarted),window.ts_adFinished=lang.hitch(this,this._ts_adFinished),this.emit
1('targetspot-ready')},_ts_mutePlayer:function(){void 0,this.emit('targetspot-mute')},_ts_unmutePlayer:function(){void 0,this.emit('targetspot-unmute')},_ts_noAds:function(){void 0,this.emit('targetspot-no-ads')},_ts_noPreRoll:function(){void 0,this.emit('targetspot-no-preroll')},_ts_adStarted:function(){void 0,this.emit('targetspot-ad-started')},_ts_adFinished:function(){void 0,this.emit('targetspot-ad-finished')}});return targetspot}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var LazyLoad=__webpack_require__(115),Platform=__webpack_require__(14),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(16),__webpack_require__(12)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,Deferred,coreModule){var module=declare([coreModule],{constructor:function(config){void 0,this.inherited(arguments),this.see=null,this.seeRegApi=null,this.seeMetaApi=null,this.tenantId=config.tenantId,this.seeApiUrl=config.seeApiUrl,this.platform=new Platform(config.platformId)},start:function(){void 0,this.emit('module-ready',{id:'UserRegistration',module:this})},init:function(){var seeApiUrl=(this.seeApiUrl==void 0?this.platform.endpoint.see:this.seeApiUrl).replace('{tenantId}',this.tenantId),def=new Deferred;LazyLoad.js(seeApiUrl,function(){def.resolve()});var successCallback=lang.hitch(this,this._seeApiLoaded),errorCallback=lang.hitch(this,this._seeApiError);def.then(function(){window._See.bindEvent('RegApiReady',successCallback)},function(){errorCallback()},function(){})},_seeApiLoaded:function(){void 0,this.see=window._See,this.seeRegApi=window._See?window._See.regApi:void 0,this.seeMetaApi=window._See?window._See.metaApi:void 0,this.see.source='StreamingPlayer',this.see==void 0?this._seeApiError():this.see.bindOrFireEvent('metaApiReady',lang.hitch(this,function(){this.emit('see-api-loaded'),this.isLoggedIn()&&this.emit('user-logged-in')}))},_seeApiError:function(){void 0,this.emit('see-api-error')},login:function(params){if(void 0==this.seeRegApi)return void this.emit('see-regapi-not-ready');switch(params.method){case'Userpwd':this.seeRegApi.login(params.username,params.password,params.persist,lang.hitch(this,this._onLoginHandler));break;case'Facebook':this.seeRegApi.loginFacebook(lang.hitch(this,this._onLoginHandler));break;case'Google':this.seeRegApi.loginGoogle(lang.hitch(this,this._onLoginHandler));break;default:}},connectSocial:function(network){if(void 0==this.seeRegApi)return void this.emit('see-regapi-not-ready');switch(network){case'Facebook':this.seeRegApi.loginFacebook(lang.hitch(this,this._onConnectSocialHandler));break;case'Google':this.seeRegApi.loginGoogle(lang.hitch(this,this._onConnectSocialHandler));break;default:}},removeSocial:function(network){if(void 0==this.seeRegApi)return void this.emit('see-regapi-not-ready');switch(network){case'Facebook':this.seeRegApi.removeSocial('facebook',lang.hitch(this,this._onRemoveSocialHandler));break;case'Google':this.seeRegApi.removeSocial('google',lang.hitch(this,this._onRemoveSocialHandler));break;default:}},isLoggedIn:function(){return this.see.config.user.is_loggedin},logout:function(){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.logout(lang.hitch(this,this._onLogoutHandler)))},forgotPassword:function(username,reseturl){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.forgotPassword(username,lang.hitch(this,this._onForgotPasswordHandler),reseturl))},resetPassword:function(token,password){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.resetPassword(token,password,lang.hitch(this,this._onResetPasswordHandler)))},getUserDetails:function(refresh){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.getUserDetails(lang.hitch(this,this._onGetUserDetailsHandler),refresh))},registerFields:function(){return void 0==this.seeRegApi?void this.emit
1('see-regapi-not-ready'):void(void 0,this.seeRegApi.registerFields(lang.hitch(this,this._onRegisterFieldsHandler)))},registerUser:function(fields,persist){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.registerUser(fields,persist,lang.hitch(this,this._onRegisterUserHandler)))},updateUser:function(fields){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.updateUser(fields,lang.hitch(this,this._onUpdateUserHandler)))},completeRegisterUser:function(fields){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.completeRegister(fields,lang.hitch(this,this._onLoginHandler)))},setLanguage:function(language){void 0,this.see.setLanguage(language,lang.hitch(this,this._onSetLanguageHandler))},getStatusLevel:function(ladder,refresh){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.getStatusLevel(ladder,refresh,lang.hitch(this,this._onGetStatusLevel)))},getLadderStatusLevels:function(ladder){return void 0==this.seeRegApi?void this.emit('see-regapi-not-ready'):void(void 0,this.seeRegApi.getLadderStatusLevels(ladder,lang.hitch(this,this._onGetLadderStatusLevels)))},metaSet:function(doc,type,options){return this.seeMetaApi?void(void 0,options='object'==typeof options?options:{},options.callback=lang.hitch(this,this._onMetaSetHandler),this.seeMetaApi.set(doc,type,options)):void this.emit('see-metaapi-not-ready')},metaGet:function(id,options){return this.seeMetaApi?void(void 0,options='object'==typeof options?options:{},options.callback=lang.hitch(this,this._onMetaGetHandler),this.seeMetaApi.get(id,options)):void this.emit('see-metaapi-not-ready')},metaUpdate:function(id,doc){if(!this.seeMetaApi)return void this.emit('see-metaapi-not-ready');var options={callback:lang.hitch(this,this._onMetaUpdateHandler)};this.seeMetaApi.update(id,doc,options)},metaDelete:function(id){if(!this.seeMetaApi)return void this.emit('see-metaapi-not-ready');var options={callback:lang.hitch(this,this._onMetaDeleteHandler)};this.seeMetaApi.del(id,options)},metaClear:function(type){if(!this.seeMetaApi)return void this.emit('see-metaapi-not-ready');var options={callback:lang.hitch(this,this._onMetaClearHandler)};this.seeMetaApi.clear(type,options)},metaList:function(type,options){return this.seeMetaApi?void(void 0,options='object'==typeof options?options:{},options.callback=lang.hitch(this,this._onMetaListHandler),this.seeMetaApi.list(type,options)):void this.emit('see-metaapi-not-ready')},triggerEvent:function(eventName){return this.see?void(void 0,this.see.triggerEvent(eventName)):void this.emit('see-not-ready')},bindEvent:function(eventName,action,scope){return this.see?void(void 0,this.see.bindEvent(eventName,action,scope)):void this.emit('see-not-ready')},bindOrFireEvent:function(eventName,action,scope){return this.see?void(void 0,this.see.bindOrFireEvent(eventName,action,scope)):void this.emit('see-not-ready')},cookieTest:function(){return this.see?void(void 0,callback=lang.hitch(this,this._onCookieTest),this.see.cookieTest(callback)):void this.emit('see-not-ready')},isGamesEnabled:function(){if(!this.see)return this.emit('see-not-ready'),!1;return this.see.config.tenant.playerShowGames},getUserConfig:function(){if(!this.see)return this.emit('see-not-ready'),!1;return this.see.config.user},getConfig:function(){if(!this.see)return this.emit('see-not-ready'),!1;return this.see.config},initWidgets:function(element){return this.see?void(void 0,this.see.initWidgets(element)):(this.emit('see-not-ready'),!1)},_onLoginHandler:function(result){switch(result.status){case'PASS':this.emit('user-logged-in',result.context);break;case'FAIL':this.emit('user-login-error',result.context);break;case'DELAY':default:}},_onConnectSocialHandler:function(result){switch(result.status){case'PASS':this.emit('social-connect',result.context);break;case'FAIL':this.emit('social-connect-error',result.context);break;case'DELAY':default:}},_onRemoveSocialHandler:function(result){switch(result.status){case'PASS':this.emit
1('social-remove',result.context);break;case'FAIL':this.emit('social-remove-error',result.context);break;case'DELAY':default:}},_onLogoutHandler:function(result){switch(result.status){case'PASS':this.emit('user-logged-out',result.context);break;case'FAIL':this.emit('user-logout-error',result.context);break;case'DELAY':default:}},_onForgotPasswordHandler:function(result){switch(result.status){case'PASS':this.emit('forgot-password',result.context);break;case'FAIL':this.emit('forgot-password-error',result.context);break;case'DELAY':default:}},_onResetPasswordHandler:function(result){switch(result.status){case'PASS':this.emit('reset-password',result.context);break;case'FAIL':this.emit('reset-password-error',result.context);break;case'DELAY':default:}},_onGetUserDetailsHandler:function(result){switch(result.status){case'PASS':this.emit('user-details',result.context);break;case'FAIL':this.emit('user-details-error',result.context);break;case'DELAY':default:}},_onRegisterFieldsHandler:function(result){switch(result.status){case'PASS':this.emit('register-fields',result.context);break;case'FAIL':this.emit('register-fields-error',result.context);break;case'DELAY':default:}},_onRegisterUserHandler:function(result){switch(result.status){case'PASS':this.emit('register-user',result.context);break;case'FAIL':this.emit('register-user-error',result.context);break;case'DELAY':default:}},_onUpdateUserHandler:function(result){switch(result.status){case'PASS':this.emit('user-update',result.context);break;case'FAIL':this.emit('user-update-error',result.context);break;case'DELAY':default:}},_onSetLanguageHandler:function(result){switch(result.status){case'PASS':this.emit('language-change-success',result.context);break;case'FAIL':this.emit('language-change-error',result.context);break;default:}},_onGetStatusLevel:function(result){switch(result.status){case'PASS':this.emit('user-status',result.context);break;case'FAIL':this.emit('user-status-error',result.context);break;case'DELAY':default:}},_onGetLadderStatusLevels:function(result){switch(result.status){case'PASS':this.emit('status-levels',result.context);break;case'FAIL':this.emit('status-levels-error',result.context);break;case'DELAY':default:}},_onMetaSetHandler:function(result){switch(result.status){case'PASS':this.emit('meta-set',result.context);break;case'FAIL':this.emit('meta-set-error',result.context);break;default:}},_onMetaGetHandler:function(result){switch(result.status){case'PASS':this.emit('meta-get',result.context);break;case'FAIL':this.emit('meta-get-error',result.context);break;default:}},_onMetaUpdateHandler:function(result){switch(result.status){case'PASS':this.emit('meta-update',result.context);break;case'FAIL':this.emit('meta-update-error',result.context);break;default:}},_onMetaDeleteHandler:function(result){switch(result.status){case'PASS':this.emit('meta-delete',result.context);break;case'FAIL':this.emit('meta-delete-error',result.context);break;default:}},_onMetaClearHandler:function(result){switch(result.status){case'PASS':this.emit('meta-clear',result.context);break;case'FAIL':this.emit('meta-clear-error',result.context);break;default:}},_onMetaListHandler:function(result){switch(result.status){case'PASS':this.emit('meta-list',result.context);break;case'FAIL':this.emit('meta-list-error',result.context);break;default:}},_onCookieTest:function(result){switch(result.status){case'PASS':this.emit('cookie-test-pass');break;case'FAIL':this.emit('cookie-test-fail');break;default:}}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(44),__webpack_require__(63),__webpack_require__(32),__webpack_require__(4)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,adModule,TritonRunSpot4Helper,AdServerType,has){var ImaSdkModule=declare([adModule],{VAST_COMPANIONS_PRIORITY:['static','iframe','html'],IMA_LIBRARY_URL:'//imasdk.googleapis.com/js/sdkloader/ima3.js',_videoContent:null,_countdownTimer:null,_adDisplayContainer:null,_currentAd:null,_adsLoader:null,_adsRequest:null,_adsManager:null,_currentAdConfig:null,constructor:function(target,config){void 0,this.config=config,this._imaSdkLoaded=!1},init:function(adConfig){void 0,this._destroy(),this._currentAdConfig=adConfig,this.createAdDisplayContainer()},reloadSyncBanner:function(){this._destroy(),this.createAdDisplayContainer()},destroyAd:function(shouldRemoveAdsRef){void 0,this._destroy(shouldRemoveAdsRef),!1!=shouldRemoveAdsRef&&this.emit
1(this.AD_MODULE_PLAYBACK_DESTROY)},skipAd:function(){void 0,this._adsManager&&this._adsManager.getAdSkippableState()?this._adsManager.skip():(void 0,this.emit(this.AD_MODULE_SKIPPABLE_STATE,{state:this._adsManager.getAdSkippableState()}))},createAdDisplayContainer:function(){void 0,this._videoContent=document.getElementById('tdplayer_od_videonode'),this._adDisplayContainer||(this._adDisplayContainer=new google.ima.AdDisplayContainer(document.getElementById(this.config.playerId),this._videoContent),this._adDisplayContainer.initialize()),this.requestAds()},requestAds:function(){if(this._adsLoader=new google.ima.AdsLoader(this._adDisplayContainer),this._adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,lang.hitch(this,this._onAdsManagerLoaded),!1),this._adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,lang.hitch(this,this._onAdError),!1),this._adsRequest=new google.ima.AdsRequest,void 0!==this._currentAdConfig.url)this._adsRequest.adTagUrl=this._currentAdConfig.url+(void 0==this.config.allowPersonalisedAds||this.config.allowPersonalisedAds?'':'&npa=1');else if(void 0!==this._currentAdConfig.sid){var tritonRunSpot4Helper=new TritonRunSpot4Helper,vastUrl=tritonRunSpot4Helper.getVastUri(tritonRunSpot4Helper.ENDPOINT,this._currentAdConfig.sid,this._currentAdConfig.mediaformat);this._adsRequest.adTagUrl=vastUrl}else void 0!==this._currentAdConfig.rawXML&&(this._adsRequest.adsResponse=this._currentAdConfig.rawXML);this._adsLoader.requestAds(this._adsRequest)},_onAdsManagerLoaded:function(adsManagerLoadedEvent){var self=this,adsRenderingSettings=new google.ima.AdsRenderingSettings;if(this._adsManager=adsManagerLoadedEvent.getAdsManager(this._videoContent,adsRenderingSettings),void 0!==this._adsManager){this._adsManager.addEventListener(google.ima.AdEvent.Type.STARTED,lang.hitch(this,this._onCompanionsReady)),this._adsManager.addEventListener(google.ima.AdEvent.Type.STARTED,lang.hitch(this,this._onStarted)),this._adsManager.addEventListener(google.ima.AdEvent.Type.ALL_ADS_COMPLETED,lang.hitch(this,this._onAllAdsCompleted)),this._adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,lang.hitch(this,this._onContentResumeRequested)),this._adsManager.addEventListener(google.ima.AdEvent.Type.RESUMED,lang.hitch(this,this._onResumed)),this._adsManager.addEventListener(google.ima.AdEvent.Type.PAUSED,lang.hitch(this,this._onAdPaused)),this._adsManager.addEventListener(google.ima.AdEvent.Type.STARTED,lang.hitch(this,this._onQuartileEvent)),this._adsManager.addEventListener(google.ima.AdEvent.Type.FIRST_QUARTILE,lang.hitch(this,this._onQuartileEvent)),this._adsManager.addEventListener(google.ima.AdEvent.Type.MIDPOINT,lang.hitch(this,this._onQuartileEvent)),this._adsManager.addEventListener(google.ima.AdEvent.Type.THIRD_QUARTILE,lang.hitch(this,this._onQuartileEvent)),this._adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETED,lang.hitch(this,this._onQuartileEvent)),this._adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,lang.hitch(this,this._onAdError));var startWidth=document.getElementById(this.config.playerId).offsetWidth,startHeight=document.getElementById(self.config.playerId).offsetHeight;this.resizeHandler=setInterval(function(){startWidth!=document.getElementById(self.config.playerId).offsetWidth&&(startWidth=document.getElementById(self.config.playerId).offsetWidth,startHeight=document.getElementById(self.config.playerId).offsetHeight,self._adsManager.resize(startWidth,startHeight,google.ima.ViewMode.NORMAL),self._resizeVideoTag(startWidth,startHeight))},250),this._resizeVideoTag(startWidth,startHeight);try{var width=document.getElementById(this.config.playerId).offsetWidth,height=document.getElementById(this.config.playerId).offsetHeight;this._adsManager.init(width,height,google.ima.ViewMode.NORMAL),this._adsManager.start()}catch(adError){}}},_resizeVideoTag:function(offsetWidth,offsetHeight){var videoElement=document.getElementById('tdplayer_od_videonode');has('ios')!=void 0&&videoElement?(videoElement.width=offsetWidth,videoElement.height=offsetHeight):videoElement&&(videoElement.style.width='0px',videoElement.style.height='0px')},_onAdPaused:function(){void 0,this._removeCountdownTimer(),this._adsManager.resume()},_onResumed:function(){var self=this;this._adsManager&&(this._countdownTimer=setInterval(function(){var timeRemaining=parseInt(self._adsManager.getRemainingTime());self._onRemainingTimeChanged(timeRemaining)},250))},_onStarted:function(adEvent){var self=this;this._removeCountdownTimer(),this._currentAd=adEvent.getAd(),this._countdownTimer=setInterval(function(){var timeRemaining=parseInt(self._adsManager.getRemainingTime());self._onRemainingTimeChanged(timeRemaining)}
1,250),this.emit(this.AD_MODULE_PLAYBACK_START,{type:AdServerType.VAST_AD})},_onAllAdsCompleted:function(){void 0,this._destroy(),this.emit(this.AD_MODULE_PLAYBACK_COMPLETE,{type:AdServerType.VAST_AD})},_onRemainingTimeChanged:function(remainingTime){void 0,this.emit(this.AD_MODULE_COUNTDOWN,{countDown:remainingTime})},_onContentResumeRequested:function(){void 0,this._removeCountdownTimer()},_removeCountdownTimer:function(){void 0,this._countdownTimer&&clearInterval(this._countdownTimer)},_onAdError:function(adErrorEvent){void 0,void 0,this.emit(this.AD_MODULE_PLAYBACK_ERROR,{error:{message:adErrorEvent.getError().getMessage(),code:adErrorEvent.getError().getErrorCode()}}),this._destroy()},_onCompanionsReady:function(adEvent){if(void 0!=this.config.companionAdSelectionSettings&&void 0!=this.config.companionAdSelectionSettings.elements){for(var companionAdSelectionSettings=new google.ima.CompanionAdSelectionSettings,vastCompanionPriorities=void 0===this.config.companionAdSelectionSettings.vastCompanionPriority?this.VAST_COMPANIONS_PRIORITY:this.config.companionAdSelectionSettings.vastCompanionPriority,companions=[],i=0,element;i<this.config.companionAdSelectionSettings.elements.length;i++){element=this.config.companionAdSelectionSettings.elements[i];for(var j=0,vastCompanionPriority;j<vastCompanionPriorities.length;j++){vastCompanionPriority=vastCompanionPriorities[j],companionAdSelectionSettings.creativeType=google.ima.CompanionAdSelectionSettings.CreativeType.ALL,companionAdSelectionSettings.sizeCriteria=google.ima.CompanionAdSelectionSettings.SizeCriteria.SELECT_EXACT_MATCH,'static'===vastCompanionPriority?companionAdSelectionSettings.resourceType=google.ima.CompanionAdSelectionSettings.ResourceType.STATIC:'html'===vastCompanionPriority?companionAdSelectionSettings.resourceType=google.ima.CompanionAdSelectionSettings.ResourceType.HTML:'iframe'===vastCompanionPriority?companionAdSelectionSettings.resourceType=google.ima.CompanionAdSelectionSettings.ResourceType.IFRAME:void 0;var tmpCompanion=adEvent.getAd().getCompanionAds(element.width,element.height,companionAdSelectionSettings);if(0<tmpCompanion.length){var vastCompanion={};vastCompanion.width=element.width,vastCompanion.height=element.height,vastCompanion.content=tmpCompanion[0].getContent(),vastCompanion.resourceType={},vastCompanion.resourceType.name=vastCompanionPriority,companions.push(vastCompanion);break}}}0<companions.length&&this.emit(this.AD_MODULE_COMPANIONS,{companions:companions})}},_onQuartileEvent:function(adEvent){switch(adEvent.type){case google.ima.AdEvent.Type.STARTED:this.emit(this.AD_MODULE_QUARTILE,{adQuartile:this.adQuartile.getQuartileByIndex(0),error:!1});break;case google.ima.AdEvent.Type.FIRST_QUARTILE:this.emit(this.AD_MODULE_QUARTILE,{adQuartile:this.adQuartile.getQuartileByIndex(1),error:!1});break;case google.ima.AdEvent.Type.MIDPOINT:this.emit(this.AD_MODULE_QUARTILE,{adQuartile:this.adQuartile.getQuartileByIndex(2),error:!1});break;case google.ima.AdEvent.Type.THIRD_QUARTILE:this.emit(this.AD_MODULE_QUARTILE,{adQuartile:this.adQuartile.getQuartileByIndex(3),error:!1});break;case google.ima.AdEvent.Type.COMPLETED:this.emit(this.AD_MODULE_QUARTILE,{adQuartile:this.adQuartile.getQuartileByIndex(4),error:!1});break;default:}},_destroy:function(shouldRemoveAdsRef){void 0,shouldRemoveAdsRef&&(this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adsLoader&&this._adsLoader.destroy(),this._adsManager&&this._adsManager.destroy()),this.resizeHandler&&clearInterval(this.resizeHandler),this._resizeVideoTag(0,0),this._videoContent&&('function'==typeof this._videoContent.exitFullscreen?this._videoContent.exitFullscreen():'function'==typeof this._videoContent.webkitExitFullscreen?this._videoContent.webkitExitFullscreen():'function'==typeof this._videoContent.mozCancelFullScreen?this._videoContent.mozCancelFullScreen():'function'==typeof this._videoContent.msExitFullscreen&&this._videoContent.msExitFullscreen()),this._removeCountdownTimer()}});return ImaSdkModule}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(44),__webpack_require__(32)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,adModule,AdServerType){var mediaAdModule=declare([adModule],{constructor:function(target,config){void 0,this.target=target,this.config=config},init:function(adConfig){void 0,this.inherited(arguments),adConfig.mediaUrl==void 0?this.emit
1(this.AD_MODULE_MEDIA_EMPTY,{adServerType:AdServerType.MEDIA_AD}):this.playAdUrl(adConfig)},playAdUrl:function(adConfig){var pattern=/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/,isWebUrl=pattern.test(adConfig.mediaUrl);if(!0==isWebUrl){var clickThrough=adConfig.linkUrl==void 0?null:adConfig.linkUrl;this.emit(this.AD_MODULE_MEDIA_READY,{adServerType:AdServerType.MEDIA_AD,mediaFiles:[{url:adConfig.mediaUrl}],clickThrough:clickThrough,clickTrackings:null})}else this.emit(this.AD_MODULE_MEDIA_EMPTY,{adServerType:AdServerType.MEDIA_AD})}});return mediaAdModule}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var xmlParser=__webpack_require__(15),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(6),__webpack_require__(39),__webpack_require__(9),__webpack_require__(44),__webpack_require__(135),__webpack_require__(136),__webpack_require__(134),__webpack_require__(32),__webpack_require__(63)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,array,request,XhrProvider,adModule,vast1Parser,vast2Parser,daastParser,AdServerType,TritonRunSpot4Helper){var vastAdModule=declare([adModule],{VAST_1_ROOT:'VideoAdServingTemplate',VAST_2_ROOT:'VAST',DAAST_ROOT:'DAAST',VERSION_1_0:'1.0',VERSION_2_0:'2.0',DAAST_VERSION_1_0:'DAAST_1.0',constructor:function(target){void 0,this.target=target,this._adConfig=null,this._mediaAdBlankFiles=null,this._skipMediaAdPlayback=!1,this._adBreak=!1,this._defaultSequence=-1,this._vastWrapperAd=null,this._wrapperCachedData=null,this.vastParser=null,this.vastDocument=null,this.onPlaybackStartHandler=null,this.onQuartileReachedHandler=null,this.onClickTrackingElementClickedHandler=null,this.xhrProv=new XhrProvider,this._loadTimes=0,this._maxLoadTimes=5},init:function(adConfig){void 0,this._adConfig=adConfig,this.inherited(arguments),this._adBreak=!!adConfig.adBreak,this._skipMediaAdPlayback=adConfig.skipMediaAdPlayback!=void 0&&adConfig.skipMediaAdPlayback,this._defaultSequence=adConfig.sequence==void 0?-1:adConfig.sequence,this.loadVast(adConfig)},loadVast:function(config){if(config.rawXML!=void 0)this._parseVast(xmlParser.parse(config.rawXML).documentElement);else if(config.url!=void 0){this.setMediaAdBlankFiles(null);var requestArgs=this._getRequestArgs();(-1<config.url.indexOf('od-spy.live.streamtheworld.com')||-1<config.url.indexOf('frequencyads')||-1<config.url.indexOf('s3'))&&(requestArgs.withCredentials=!1),this.xhrProv.request(config.url,config.url,requestArgs,lang.hitch(this,this._onVastLoadComplete),lang.hitch(this,this._onVastLoadError))}else if(config.sid!=void 0){var tritonRunSpot4Helper=new TritonRunSpot4Helper,vastUrl=tritonRunSpot4Helper.getVastUri(tritonRunSpot4Helper.ENDPOINT,this.config.sid,config.mediaformat);this.setMediaAdBlankFiles(tritonRunSpot4Helper.mediaAdBlankFiles),this.xhrProv.request(vastUrl,vastUrl,this._getRequestArgs(),lang.hitch(this,this._onVastLoadComplete),lang.hitch(this,this._onVastLoadError))}},setMediaAdBlankFiles:function(array){this._mediaAdBlankFiles=array},getVastInlineAd:function(){return this.vastDocument.vastAd.inlineAd},reloadSyncBanner:function(){null!=this._adConfig&&this.loadVast(this._adConfig)},_onVastLoadComplete:function(url,data){void 0,this._parseVast(data)},_onVastLoadError:function(url,error){void 0,null!=this._vastWrapperAd&&(null!=this._vastWrapperAd.error&&''!=this._vastWrapperAd.error&&this.xhrProv.request(this._vastWrapperAd.error,this._vastWrapperAd.error,this._getRequestArgs(),null,null),this._vastWrapperAd=null),!1==this._adBreak&&this.emit(this.AD_MODULE_VAST_ERROR,{error:error})},_parseVast:function(data){if(this.vastDocument=null,this.vastParser=null,void 0==data||void 0==data.nodeName)return void this.emit(this.AD_MODULE_VAST_EMPTY,{adServerType:AdServerType.VAST_AD});var version=this._getVersion(data.nodeName);if(this.vastParser=this._getVastParser(version),null!=this.vastParser&&(this.vastDocument=this.vastParser.parse(data)),null==this.vastDocument){if('2.0'===version){var errorURL=this.vastParser.parseMissedOpportunityError(data);if(errorURL){var requestArgs=this._getRequestArgs();requestArgs.withCredentials=!1,this.xhrProv.request(errorURL,null,requestArgs,null,null)}}
1this._loadTimes=0,this.emit(this.AD_MODULE_VAST_EMPTY,{adServerType:AdServerType.VAST_AD})}else if(this._shouldLoadVASTWrapper(this.vastDocument.vastAd))this._loadTimes++,this._vastWrapperAd=this.vastDocument.vastAd.wrapperAd,this._cacheWrapperData(this._vastWrapperAd),this.loadVast({url:this.vastDocument.vastAd.wrapperAd.vastAdTagURL,skipMediaAdPlayback:this._skipMediaAdPlayback,sequence:this._defaultSequence});else{this._loadTimes=0,null!=this._vastWrapperAd&&(this.vastDocument.vastAd.inlineAd.addWrapperLinearTrackingEvents(this._wrapperCachedData.wrapperTrackingEvents),this.vastDocument.vastAd.inlineAd.addImpressions(this._wrapperCachedData.wrapperImpressions),this.vastDocument.vastAd.inlineAd.addWrapperLinearVideoClickTracking(this._wrapperCachedData.wrapperVideoClickTracking),this._vastWrapperAd=null,this._wrapperCachedData=null),this._vastWrapperAd=null;var adEmpty=!0;if(void 0!=this.vastDocument.vastAd.inlineAd.getCompanionAds(this._defaultSequence)&&0<this.vastDocument.vastAd.inlineAd.getCompanionAds(this._defaultSequence).length&&(adEmpty=!1,this.emit(this.AD_MODULE_COMPANIONS,{companions:this.vastDocument.vastAd.inlineAd.getCompanionAds(this._defaultSequence)})),!0==this._skipMediaAdPlayback)return;var mediaFiles=this._checkMediaAdBlankFiles(this.vastDocument.vastAd.inlineAd.getLinearMediaFiles(this._defaultSequence));if(null!=mediaFiles){adEmpty=!1;var videoClick=this.vastDocument.vastAd.inlineAd.getLinearVideoClick(this._defaultSequence),clickThrough=null==videoClick?null:videoClick.clickThrough,clickTrackings=null==videoClick?null:videoClick.clickTrackings;this.emit(this.AD_MODULE_MEDIA_READY,{adServerType:AdServerType.VAST_AD,mediaFiles:mediaFiles,clickThrough:clickThrough,clickTrackings:clickTrackings})}else adEmpty&&this.emit(this.AD_MODULE_MEDIA_EMPTY,{adServerType:AdServerType.VAST_AD})}},_getVersion:function(node){return node===this.VAST_1_ROOT?this.VERSION_1_0:node===this.VAST_2_ROOT?this.VERSION_2_0:node===this.DAAST_ROOT?this.DAAST_VERSION_1_0:null},_cacheWrapperData:function(){null==this._wrapperCachedData&&(this._wrapperCachedData={wrapperImpressions:[],wrapperTrackingEvents:[],wrapperVideoClickTracking:[]});var wrapperTrackingEvents=this._vastWrapperAd.getLinearTrackingEvents(this._defaultSequence);null!=wrapperTrackingEvents&&0<wrapperTrackingEvents.length&&(this._wrapperCachedData.wrapperTrackingEvents=this._wrapperCachedData.wrapperTrackingEvents.concat(wrapperTrackingEvents));var wrapperImpressions=this._vastWrapperAd.impressions;null!=wrapperImpressions&&0<wrapperImpressions.length&&(this._wrapperCachedData.wrapperImpressions=this._wrapperCachedData.wrapperImpressions.concat(wrapperImpressions));var wrapperVideoClick=this._vastWrapperAd.getLinearVideoClick(this._defaultSequence);null!=wrapperVideoClick&&0<wrapperVideoClick.clickTrackings.length&&(this._wrapperCachedData.wrapperVideoClickTracking=this._wrapperCachedData.wrapperVideoClickTracking.concat(wrapperVideoClick.clickTrackings))},_shouldLoadVASTWrapper:function(adVast){return!!(null!=adVast.wrapperAd&&null!=adVast.wrapperAd.vastAdTagURL&&this._loadTimes<=this._maxLoadTimes)},_getVastParser:function(version){return version===this.VERSION_1_0?(null==this.vastParser&&(this.vastParser=new vast1Parser(this.target)),this.vastParser):version===this.VERSION_2_0?(null==this.vastParser&&(this.vastParser=new vast2Parser(this.target)),this.vastParser):version===this.DAAST_VERSION_1_0?(null==this.vastParser&&(this.vastParser=new daastParser(this.target)),this.vastParser):null},_checkMediaAdBlankFiles:function(mediaFiles){if(null==mediaFiles)return null;for(var mediaFilesArr=[],mediaFilesLength=mediaFiles.length,i=0;i<mediaFilesLength;i++)this._isMediaAdBlankFile(mediaFiles[i].url)||mediaFilesArr.push(mediaFiles[i]);return mediaFilesArr},_isMediaAdBlankFile:function(url){if(null==this._mediaAdBlankFiles||0==this._mediaAdBlankFiles.length)return!1;for(var mediaFileName=url.substr(url.lastIndexOf('/')+1),mediaAdBlankFilesLength=this._mediaAdBlankFiles.length,i=0;i<mediaAdBlankFilesLength;i++)if(this._mediaAdBlankFiles[i]==mediaFileName)return!0;return!1},_getRequestArgs:function(){return{handleAs:'xml',preventCache:!1,withCredentials:!0,headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}}}});return vastAdModule}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(46)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,VASTCompanionAd){var daastCompanionAd=declare(VASTCompanionAd,{constructor:function(){void 0,this.logoTile=null,this.logoTitle=null,this.logoArtist=null,this.logoURL=null}});return daastCompanionAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vast1InlineAd=declare([],{constructor:function(){void 0,this.trackingEvents=[],this.companionAds=[],this.nonLinearAds=[],this.video=null,this.inherited(arguments)},addWrapperLinearTrackingEvents:function(value){this.trackingEvents=this.trackingEvents.concat(value)},addWrapperLinearVideoClickTracking:function(value){null==this.video||(this.video.videoClick.clickTrackings=this.video.videoClick.clickTrackings.concat(value))},addImpression:function(value){this.impressions.push(value)},addImpressions:function(value){null!=value&&(this.impressions=this.impressions.concat(value))},getLinearTrackingEvents:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),this.trackingEvents},getCompanionAdUrl:function(width,height,vastResourceType,sequence){var companionAds=this.getCompanionAds(sequence);if(null==companionAds)return null;for(var dimensionFit=!1,arrayLength=companionAds.length,i=0;i<arrayLength;i++)if(dimensionFit=companionAds[i].width==width&&companionAds[i].height==height,!0!=dimensionFit){if(null==vastResourceType)return companionAds[i];if(companionAds[i].resourceType==vastResourceType)return companionAds[i]}return null},getCompanionAds:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),this.companionAds},getLinearMediaFiles:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),this.video.mediaFiles},getLinearMediaFileByIndex:function(index,sequence){var sequence=sequence;void 0==sequence&&(sequence=-1);var index=index;return void 0==index&&(index=0),null!=this.video&&null!=this.video.mediaFiles[index]?this.video.mediaFiles[index]:null},getLinearVideoClick:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),this.video.videoClick},getNonLinearAds:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),this.nonLinearAds},getLinearDuration:function(sequence){var sequence=sequence;return void 0==sequence&&(sequence=-1),this.video.duration},addCompanionAd:function(companionAd){this.companionAds.push(companionAd)},addNonLinearAd:function(nonLinearAd){this.nonLinearAds.push(nonLinearAd)}});return vast1InlineAd}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare){var vastVideo=declare([],{constructor:function(){void 0,this.duration=null,this.adID=null,this.videoClick=null,this.mediaFiles=[]}});return vastVideo}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var xmlParser=__webpack_require__(15),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(54),__webpack_require__(53),__webpack_require__(47),__webpack_require__(45),__webpack_require__(68),__webpack_require__(52),__webpack_require__(67),__webpack_require__(69),__webpack_require__(70),__webpack_require__(131),__webpack_require__(50),__webpack_require__(51),__webpack_require__(48),__webpack_require__(49)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,VASTParser,VASTElement,VASTDocument,VASTAd,VAST2InlineAd,VASTWrapperAd,VAST2Creative,VASTLinearElement,VASTNonLinearAd,DAASTCompanionAd,VASTTrackingEvent,VASTVideoClick,VASTMediaFile,VASTResourceType){var daastparser=declare([VASTParser],{AD:'Ad',IMPRESSION:'Impression',DAAST_AD_TAG_URI:'DAASTAdTagURI',CREATIVES:'Creatives',CREATIVE:'Creative',constructor:function(){void 0,this.vastDocument=null,this.inherited(arguments)},parse:function(xml){this.vastDocument=new VASTDocument;var adXML=xml.getElementsByTagName(this.AD);if(void 0==adXML[0])return null;var id=adXML[0].getAttribute(VASTElement.ID),vastAd=new VASTAd(id);return this.vastDocument.vastAd=vastAd,this._parseAdTag(adXML),this.vastDocument},_parseAdTag:function(xml){for(var xmlLength=xml.length,i=0;i<xmlLength;i++)if(0<xml[i].getElementsByTagName(VASTElement.INLINE).length)this.vastDocument.vastAd.inlineAd=this._parseInLineTag(xml[i].getElementsByTagName(VASTElement.INLINE));else if(0<xml[i].getElementsByTagName(VASTElement.WRAPPER).length)this.vastDocument.vastAd.wrapperAd=this._parseWrapperTag(xml[i].getElementsByTagName(VASTElement.WRAPPER));else;},_parseInLineTag:function(xml){for(var daastInline=new VAST2InlineAd,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.AD_SYSTEM?daastInline.adSystem=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.AD_TITLE?daastInline.adTitle=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.ERROR?daastInline.errorURL=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.DESCRIPTION?daastInline.description=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.EXPIRES?daastInline.expires=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.CATEGORY?daastInline.category=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.SURVEY?daastInline.survey=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.ADVERTISER&&(daastInline.advertiser=xmlParser.textContent(nodeArray[i]));return daastInline.impressions=this._parseImpressionTag(xml[0].getElementsByTagName(this.IMPRESSION)),daastInline.creatives=this._parseCreatives(xml[0].getElementsByTagName(this.CREATIVES)),daastInline},_parseWrapperTag:function(xml){for(var vastWrapperAd=new VASTWrapperAd,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==this.DAAST_AD_TAG_URI?vastWrapperAd.vastAdTagURL=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.ERROR&&(vastWrapperAd.error=this.trim(xmlParser.textContent(nodeArray[i])));return vastWrapperAd.impressions=this._parseImpressionTag(xml[0].getElementsByTagName(this.IMPRESSION)),vastWrapperAd.creatives=this._parseCreatives(xml[0].getElementsByTagName(this.CREATIVES)),vastWrapperAd},_parseImpressionTag:function(xml){var impressionsArray=[];if(xml==void 0)return impressionsArray;for(var impressionsArrayLength=xml.length,i=0;i<impressionsArrayLength;i++)impressionsArray.push(this.trim(xmlParser.textContent(xml[i])));return impressionsArray},_parseCreatives:function(xml){var creativesArray=[];if(xml[0]==void 0||xml[0].getElementsByTagName(this.CREATIVE)==void 0)return creativesArray;for(var creativesArrayLength=xml[0].getElementsByTagName(this.CREATIVE).length,creativeArray=xml[0].getElementsByTagName(this.CREATIVE),i=0,creative;i<creativesArrayLength;i++)creative=this._parseCreative(creativeArray[i]),creativesArray.push(creative);return creativesArray},_parseCreative:function(xml){var creative=new VAST2Creative;return creative.adID=xml.getAttribute(VASTElement.AD_ID),creative.id=xml.getAttribute(VASTElement.ID),creative.sequence=xml.getAttribute(VASTElement.SEQUENCE),0==xml.getElementsByTagName(VASTElement.LINEAR).length?0==xml.getElementsByTagName(VASTElement.NON_LINEAR_ADS).length?0!=xml.getElementsByTagName(VASTElement.COMPANION_ADS).length&&(creative.companionAds=this._parseCreativeCompanionAds(xml.getElementsByTagName(VASTElement.COMPANION_ADS))):creative.nonLinearAds=this._parseCreativeNonLinearAds(xml.getElementsByTagName(VASTElement.NON_LINEAR_ADS)):creative.linearElement=this._parseCreativeLinear(xml.getElementsByTagName(VASTElement.LINEAR)),creative},_parseCreativeLinear:function(xml){for(var vastLinearElement=new VASTLinearElement,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.DURATION?vastLinearElement.duration=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.TRACKING_EVENTS?vastLinearElement.trackingEvents=this._parseTrackingEvents(nodeArray[i]):nodeArray[i].nodeName==VASTElement.AUDIO_INTERACTIONS?vastLinearElement.videoClick=this._parseVideoClick(nodeArray[i]):nodeArray[i].nodeName==VASTElement.MEDIA_FILES&&(vastLinearElement.mediaFiles=this._parseMediaFiles(nodeArray[i]));return vastLinearElement},_parseCreativeNonLinearAds:function(xml){for(var vastNonLinearAds=[],nonLinearAd=xml[0].getElementsByTagName(VASTElement.NON_LINEAR),nonLinearAdLength=nonLinearAd.length,i=0,vastNonLinearAd;i<nonLinearAdLength;i++){vastNonLinearAd=new VASTNonLinearAd,vastNonLinearAd.id=nonLinearAd[i].getAttribute(VASTElement.ID),vastNonLinearAd.width=nonLinearAd[i].getAttribute(VASTElement.WIDTH),vastNonLinearAd.height=nonLinearAd[i].getAttribute(VASTElement.HEIGHT),vastNonLinearAd.expandedWidth=nonLinearAd[i].getAttribute(VASTElement.EXPANDED_WIDTH),vastNonLinearAd.expandedHeight=nonLinearAd[i].getAttribute(VASTElement.EXPANDED_HEIGHT),vastNonLinearAd.scalable=!('true'!=nonLinearAd[i].getAttribute(VASTElement.SCALABLE)),vastNonLinearAd.maintainAspectRatio=!('true'!=nonLinearAd[i].getAttribute(VASTElement.MAINTAIN_ASPECT_RATIO)),vastNonLinearAd.apiFramework=nonLinearAd[i].getAttribute(VASTElement.API_FRAMEWORK),vastNonLinearAd.minSuggestedDuration=nonLinearAd[i].getAttribute(VASTElement.MIN_SUGGESTED_DURATION);for(var nodeArray=nonLinearAd[i].childNodes,nodeArrayLength=nodeArray.length,j=0;j<nodeArrayLength;j++)if(nodeArray[j].nodeName==VASTElement.AD_PARAMETERS)vastNonLinearAd.adParameters=xmlParser.textContent(nodeArray[j]);else if(nodeArray[j].nodeName==VASTElement.NON_LINEAR_CLICK_THROUGH)vastNonLinearAd.clickThroughURL=this.trim(xmlParser.textContent(nodeArray[j]));else if(nodeArray[j].nodeName==VASTElement.IFRAME_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.IFRAME,vastNonLinearAd.resourceType=vastResourceType,vastNonLinearAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}else if(nodeArray[j].nodeName==VASTElement.HTML_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.HTML,vastNonLinearAd.resourceType=vastResourceType,vastNonLinearAd.code=xmlParser.textContent(nodeArray[j])}else if(nodeArray[j].nodeName==VASTElement.STATIC_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.STATIC,vastNonLinearAd.resourceType=vastResourceType,vastNonLinearAd.creativeType=nodeArray[j].getAttribute(VASTElement.CREATIVE_TYPE),vastNonLinearAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}vastNonLinearAds.push(vastNonLinearAd)}return vastNonLinearAd},_parseCreativeCompanionAds:function(xml){for(var daastCompanionAds=[],companions=xml[0].getElementsByTagName(VASTElement.COMPANION),companionsLength=companions.length,i=0,daastCompanionAd;i<companionsLength;i++){daastCompanionAd=new DAASTCompanionAd,daastCompanionAd.id=companions[i].getAttribute(VASTElement.ID),daastCompanionAd.width=companions[i].getAttribute(VASTElement.WIDTH),daastCompanionAd.height=companions[i].getAttribute(VASTElement.HEIGHT),daastCompanionAd.expandedWidth=companions[i].getAttribute(VASTElement.EXPANDED_WIDTH),daa
1stCompanionAd.expandedHeight=companions[i].getAttribute(VASTElement.EXPANDED_HEIGHT),daastCompanionAd.logoTile=companions[i].getAttribute(VASTElement.LOGO_TILE),daastCompanionAd.logoTitle=companions[i].getAttribute(VASTElement.LOGO_TITLE),daastCompanionAd.logoArtist=companions[i].getAttribute(VASTElement.LOGO_ARTIST),daastCompanionAd.logoTile=companions[i].getAttribute(VASTElement.LOGO_TILE);for(var nodeArray=companions[i].childNodes,nodeArrayLength=nodeArray.length,j=0;j<nodeArrayLength;j++)if(nodeArray[j].nodeName==VASTElement.AD_PARAMETERS)daastCompanionAd.adParameters=xmlParser.textContent(nodeArray[j]);else if(nodeArray[j].nodeName==VASTElement.ALT_TEXT)daastCompanionAd.altText=xmlParser.textContent(nodeArray[j]);else if(nodeArray[j].nodeName==VASTElement.COMPANION_CLICK_THROUGH)daastCompanionAd.clickThroughURL=this.trim(xmlParser.textContent(nodeArray[j]));else if(nodeArray[j].nodeName==VASTElement.IFRAME_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.IFRAME,daastCompanionAd.resourceType=vastResourceType,daastCompanionAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}else if(nodeArray[j].nodeName==VASTElement.HTML_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.HTML,daastCompanionAd.resourceType=vastResourceType,daastCompanionAd.code=xmlParser.textContent(nodeArray[j])}else if(nodeArray[j].nodeName==VASTElement.STATIC_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.STATIC,daastCompanionAd.resourceType=vastResourceType,daastCompanionAd.creativeType=nodeArray[j].getAttribute(VASTElement.CREATIVE_TYPE),daastCompanionAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}else if(nodeArray[j].nodeName==VASTElement.TRACKING_EVENTS){var trackings=nodeArray[j].getElementsByTagName(VASTElement.TRACKING),trackingsLength=trackings.length;if(0<trackingsLength){var type=trackings[0].getAttribute(VASTElement.EVENT);type==VASTElement.CREATIVE_VIEW&&(daastCompanionAd.creativeView=this.trim(xmlParser.textContent(nodeArray[j])))}}daastCompanionAds.push(daastCompanionAd)}return daastCompanionAds},_parseTrackingEvents:function(xml){for(var vastTrackingEvents=[],trackings=xml.getElementsByTagName(VASTElement.TRACKING),trackingsLength=trackings.length,i=0,vastTrackingEvent;i<trackingsLength;i++)vastTrackingEvent=new VASTTrackingEvent,vastTrackingEvent.urls.push(xmlParser.textContent(trackings[i])),vastTrackingEvent.type=trackings[i].getAttribute(VASTElement.EVENT),vastTrackingEvents.push(vastTrackingEvent);return vastTrackingEvents},_parseVideoClick:function(xml){for(var vastVideoClick=new VASTVideoClick,nodeArray=xml.childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.CLICK_THROUGH?vastVideoClick.clickThrough=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.CLICK_TRACKING?vastVideoClick.clickTrackings.push(this.trim(xmlParser.textContent(nodeArray[i]))):nodeArray[i].nodeName==VASTElement.CUSTOM_CLICK&&vastVideoClick.customClicks.push(this.trim(xmlParser.textContent(nodeArray[i])));return vastVideoClick},_parseMediaFiles:function(xml){for(var vastMediaFiles=[],mediaFiles=xml.getElementsByTagName(VASTElement.MEDIA_FILE),mediaFilesLength=mediaFiles.length,i=0,vastMediaFile;i<mediaFilesLength;i++)vastMediaFile=new VASTMediaFile,vastMediaFile.id=mediaFiles[i].getAttribute(VASTElement.ID),vastMediaFile.bitrate=mediaFiles[i].getAttribute(VASTElement.BITRATE),vastMediaFile.minbitrate=mediaFiles[i].getAttribute(VASTElement.MIN_BITRATE),vastMediaFile.maxbitrate=mediaFiles[i].getAttribute(VASTElement.MAX_BITRATE),vastMediaFile.codec=mediaFiles[i].getAttribute(VASTElement.CODEC),vastMediaFile.height=mediaFiles[i].getAttribute(VASTElement.HEIGHT),vastMediaFile.width=mediaFiles[i].getAttribute(VASTElement.WIDTH),vastMediaFile.delivery=mediaFiles[i].getAttribute(VASTElement.DELIVERY),vastMediaFile.type=mediaFiles[i].getAttribute(VASTElement.TYPE),vastMediaFile.scalable='true'==mediaFiles[i].getAttribute(VASTElement.SCALABLE),vastMediaFile.maintainAspectRatio='true'==mediaFiles[i].getAttribute(VASTElement.MAINTAIN_ASPECT_RATIO),vastMediaFile.apiFramework=mediaFiles[i].getAttribute(VASTElement.API_FRAMEWORK),vastMediaFile.url=this.trim(xmlParser.textContent(mediaFiles[i])),vastMediaFiles.push(vastMediaFile);return vastMediaFiles}});return daastparser}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var xmlParser=__webpack_require__(15),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(54),__webpack_require__(53),__webpack_require__(47),__webpack_require__(45),__webpack_require__(132),__webpack_require__(52),__webpack_require__(133),__webpack_require__(51),__webpack_require__(50),__webpack_require__(46),__webpack_require__(48),__webpack_require__(49)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,VASTParser,VASTElement,VASTDocument,VASTAd,VAST1InlineAd,VASTWrapperAd,VASTVideo,VASTVideoClick,VASTTrackingEvent,VASTCompanionAd,VASTMediaFile,VASTResourceType){var vast1parser=declare([VASTParser],{AD:'Ad',VAST_AD_TAG_URL:'VASTAdTagURL',VIDEO:'Video',URL:'URL',CODE:'Code',RESOURCE_TYPE:'resourceType',constructor:function(){void 0,this.vastDocument=null,this.inherited(arguments)},parse:function(xml){this.vastDocument=new VASTDocument;var adXML=xml.getElementsByTagName(this.AD);if(void 0==adXML[0])return null;var id=adXML[0].getAttribute(VASTElement.ID),vastAd=new VASTAd(id);return this.vastDocument.vastAd=vastAd,this._parseAdTag(adXML),this.vastDocument},_parseAdTag:function(xml){for(var xmlLength=xml.length,i=0;i<xmlLength;i++)if(0<xml[i].getElementsByTagName(VASTElement.INLINE).length)this.vastDocument.vastAd.inlineAd=this._parseInLineTag(xml[i].getElementsByTagName(VASTElement.INLINE));else if(0<xml[i].getElementsByTagName(VASTElement.WRAPPER).length)this.vastDocument.vastAd.wrapperAd=this._parseWrapperTag(xml[i].getElementsByTagName(VASTElement.WRAPPER));else;},_parseInLineTag:function(xml){for(var vast1Inline=new VAST1InlineAd,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.AD_SYSTEM?vast1Inline.adSystem=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.AD_TITLE?vast1Inline.adTitle=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.ERROR&&(vast1Inline.errorURL=this.trim(xmlParser.textContent(nodeArray[i])));vast1Inline.video=this._parseVideo(xml[0].getElementsByTagName(this.VIDEO)),vast1Inline.impressions=this._parseImpressions(xml[0].getElementsByTagName(VASTElement.IMPRESSION));var trackingEventsXML=xml[0].getElementsByTagName(VASTElement.TRACKING_EVENTS);return void 0!=trackingEventsXML&&0<trackingEventsXML.length&&(vast1Inline.trackingEvents=this._parseTrackingEvents(trackingEventsXML[0])),vast1Inline.companionAds=this._parseCompanionsAds(xml[0].getElementsByTagName(VASTElement.COMPANION_ADS)),vast1Inline.nonLinearAds=this._parseNonLinearAds(xml[0].getElementsByTagName(VASTElement.NON_LINEAR_ADS)),vast1Inline},_parseImpressions:function(xml){var impressionsArray=[];if(xml==void 0||0==xml.length)return impressionsArray;
1for(var urlArrayLength=xml[0].getElementsByTagName(this.URL).length,urlArray=xml[0].getElementsByTagName(this.URL),i=0;i<urlArrayLength;i++)impressionsArray.push(xmlParser.textContent(urlArray[i]));return impressionsArray},_parseVideo:function(xml){for(var vastVideo=new VASTVideo,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.DURATION?vastVideo.duration=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.AD_ID?vastVideo.adID=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.VIDEO_CLICKS?vastVideo.videoClick=this._parseVideoClick(nodeArray[i]):nodeArray[i].nodeName==VASTElement.MEDIA_FILES&&(vastVideo.mediaFiles=this._parseMediaFiles(nodeArray[i]));return vastVideo},_parseVideoClick:function(xml){for(var vastVideoClick=new VASTVideoClick,nodeArray=xml.childNodes,nodeArrayLength=nodeArray.length,urls=null,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.CLICK_THROUGH?(urls=this._parseURLTags(nodeArray[i]),0<urls.length&&(vastVideoClick.clickThrough=urls[0])):nodeArray[i].nodeName==VASTElement.CLICK_TRACKING?vastVideoClick.clickTrackings=this._parseURLTags(nodeArray[i]):nodeArray[i].nodeName==VASTElement.CUSTOM_CLICK&&(vastVideoClick.customClicks=this._parseURLTags(nodeArray[i]));return vastVideoClick},_parseMediaFiles:function(xml){for(var vastMediaFiles=[],mediaFiles=xml.getElementsByTagName(VASTElement.MEDIA_FILE),mediaFilesLength=mediaFiles.length,i=0,vastMediaFile;i<mediaFilesLength;i++)vastMediaFile=new VASTMediaFile,vastMediaFile.id=mediaFiles[i].getAttribute(VASTElement.ID),vastMediaFile.bitrate=mediaFiles[i].getAttribute(VASTElement.BITRATE),vastMediaFile.height=mediaFiles[i].getAttribute(VASTElement.HEIGHT),vastMediaFile.width=mediaFiles[i].getAttribute(VASTElement.WIDTH),vastMediaFile.delivery=mediaFiles[i].getAttribute(VASTElement.DELIVERY),vastMediaFile.type=mediaFiles[i].getAttribute(VASTElement.TYPE),vastMediaFile.url=this.trim(this.getTagValue(mediaFiles[i],'URL')),vastMediaFiles.push(vastMediaFile);return vastMediaFiles},_parseTrackingEvents:function(xml){for(var vastTrackingEvents=[],trackings=xml.getElementsByTagName(VASTElement.TRACKING),trackingsLength=trackings.length,i=0,vastTrackingEvent,urlArray,urlArrayLength;i<trackingsLength;i++){vastTrackingEvent=new VASTTrackingEvent,urlArray=trackings[i].getElementsByTagName(this.URL),urlArrayLength=urlArray.length;for(var j=0;j<urlArrayLength;j++)vastTrackingEvent.urls.push(this.trim(xmlParser.textContent(urlArray[j])));vastTrackingEvent.type=trackings[i].getAttribute(VASTElement.EVENT),vastTrackingEvents.push(vastTrackingEvent)}return vastTrackingEvents},_parseCompanionsAds:function(xml){for(var vastCompanionAds=[],companions=xml[0].getElementsByTagName(VASTElement.COMPANION),companionsLength=companions.length,nodeArray=null,i=0,nodeArrayLength,vastCompanionAd;i<companionsLength;i++){vastCompanionAd=new VASTCompanionAd,vastCompanionAd.id=companions[i].getAttribute(VASTElement.ID),vastCompanionAd.width=companions[i].getAttribute(VASTElement.WIDTH),vastCompanionAd.height=companions[i].getAttribute(VASTElement.HEIGHT),vastCompanionAd.expandedWidth=companions[i].getAttribute(VASTElement.EXPANDED_WIDTH),vastCompanionAd.expandedHeight=companions[i].getAttribute(VASTElement.EXPANDED_HEIGHT);var vastResourceType=new VASTResourceType;vastResourceType.name=companions[i].getAttribute(this.RESOURCE_TYPE).toLowerCase(),vastCompanionAd.resourceType=vastResourceType,vastCompanionAd.creativeType=companions[i].getAttribute(VASTElement.CREATIVE_TYPE),nodeArray=companions[i].childNodes,nodeArrayLength=nodeArray.length;for(var j=0;j<nodeArrayLength;j++)nodeArray[j].nodeName==VASTElement.AD_PARAMETERS?vastCompanionAd.adParameters=xmlParser.textContent(nodeArray[j]):nodeArray[j].nodeName==VASTElement.ALT_TEXT?vastCompanionAd.altText=xmlParser.textContent(nodeArray[j]):nodeArray[j].nodeName==VASTElement.COMPANION_CLICK_THROUGH?vastCompanionAd.clickThroughURL=this.trim(xmlParser.textContent(nodeArray[j])):nodeArray[j].nodeName==this.URL?vastCompanionAd.url=this.trim(xmlParser.textContent(nodeArray[j])):nodeArray[j].nodeName==this.CODE&&(vastCompanionAd.code=this.trim(xmlParser.textContent(nodeArray[j])));vastCompanionAds.push(vastCompanionAd)}return vastCompanionAds},_parseNonLinearAds:function(){return null},_parseWrapperTag:function(xml){for(var vastWrapperAd=new VASTWrapperAd,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==this.VAST_AD_TAG_URL?vastWrapperAd.vastAdTagURL=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.VIDEO_CLICKS?vastWrapperAd.videoClicks=this._parseVideoClick(nodeArray[i]):nodeArray[i].nodeName==VASTElement.ERROR?vastWrapperAd.error=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.TRACKING_EVENTS&&(vastWrapperAd.trackingEvents=this._parseTrackingEvents(nodeArray[i]));return vastWrapperAd.impressions=this._parseImpressions(xml[0].getElementsByTagName(VASTElement.IMPRESSION)),vastWrapperAd},_parseURLTags:function(xml){for(var urls=[],nodeArray=xml.childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==this.URL&&urls.push(this.trim(xmlParser.textContent(nodeArray[i])));return urls}});return vast1parser}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var xmlParser=__webpack_require__(15),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(54),__webpack_require__(53),__webpack_require__(47),__webpack_require__(45),__webpack_require__(68),__webpack_require__(52),__webpack_require__(67),__webpack_require__(69),__webpack_require__(70),__webpack_require__(46),__webpack_require__(50),__webpack_require__(51),__webpack_require__(48),__webpack_require__(49)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,VASTParser,VASTElement,VASTDocument,VASTAd,VAST2InlineAd,VASTWrapperAd,VAST2Creative,VASTLinearElement,VASTNonLinearAd,VASTCompanionAd,VASTTrackingEvent,VASTVideoClick,VASTMediaFile,VASTResourceType){var vast2parser=declare([VASTParser],{AD:'Ad',IMPRESSION:'Impression',VAST_AD_TAG_URI:'VASTAdTagURI',CREATIVES:'Creatives',CREATIVE:'Creative',constructor:function(){void 0,this.vastDocument=null,this.inherited(arguments)},parse:function(xml){this.vastDocument=new VASTDocument;var adXML=xml.getElementsByTagName(this.AD);if(void 0==adXML[0])return null;var id=adXML[0].getAttribute(VASTElement.ID),vastAd=new VASTAd(id);return this.vastDocument.vastAd=vastAd,this._parseAdTag(adXML),this.vastDocument},parseMissedOpportunityError:function(xml){this.vastDocument=new VASTDocument;var errorXML=xml.getElementsByTagName(VASTElement.ERROR);if(void 0==errorXML[0])return null;var errorURL=this.trim(xmlParser.textContent(errorXML[0]));return errorURL=errorURL.replace('[TD_DURATION]','0'),errorURL=errorURL.replace('[ERRORCODE]','202'),errorURL},_parseAdTag:function(xml){for(var xmlLength=xml.length,i=0;i<xmlLength;i++)if(0<xml[i].getElementsByTagName(VASTElement.INLINE).length)this.vastDocument.vastAd.inlineAd=this._parseInLineTag(xml[i].getElementsByTagName(VASTElement.INLINE));else if(0<xml[i].getElementsByTagName(VASTElement.WRAPPER).length)this.vastDocument.vastAd.wrapperAd=this._parseWrapperTag(xml[i].getElementsByTagName(VASTElement.WRAPPER));else;},_parseInLineTag:function(xml){for(var vast2Inline=new VAST2InlineAd,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.AD_SYSTEM?vast2Inline.adSystem=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.AD_TITLE?vast2Inline.adTitle=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.ERROR?vast2Inline.errorURL=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.DESCRIPTION&&(vast2Inline.description=xmlParser.textContent(nodeArray[i]));return vast2Inline.impressions=this._parseImpressionTag(xml[0].getElementsByTagName(this.IMPRESSION)),vast2Inline.creatives=this._parseCreatives(xml[0].getElementsByTagName(this.CREATIVES)),vast2Inline},_parseWrapperTag:function(xml){for(var vastWrapperAd=new VASTWrapperAd,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==this.VAST_AD_TAG_URI?vastWrapperAd.vastAdTagURL=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.ERROR&&(vastWrapperAd.error=this.trim(xmlParser.textContent(nodeArray[i])));return vastWrapperAd.impressions=this._parseImpressionTag(xml[0].getElementsByTagName(this.IMPRESSION)),vastWrapperAd.creatives=this._parseCreatives(xml[0].getElementsByTagName(this.CREATIVES)),vastWrapperAd},_parseImpressionTag:function(xml){var impressionsArray=[];if(xml==void 0)return impressionsArray;for(var impressionsArrayLength=xml.length,i=0;i<impressionsArrayLength;i++)impressionsArray.push(this.trim(xmlParser.textContent(xml[i])));return impressionsArray},_parseCreatives:function(xml){var creativesArray=[];if(xml[0]==void 0||xml[0].getElementsByTagName(this.CREATIVE)==void 0)return creativesArray;for(var creativesArrayLength=xml[0].getElementsByTagName(this.CREATIVE).length,creativeArray=xml[0].getElementsByTagName(this.CREATIVE),i=0,creative;i<creativesArrayLength;i++)creative=this._parseCreative(creativeArray[i]),creativesArray.push(creative);return creativesArray},_parseCreative:function(xml){var creative=new VAST2Creative;return creative.adID=xml.getAttribute(VASTElement.AD_ID),creative.id=xml.getAttribute(VASTElement.ID),creative.sequence=xml.getAttribute(VASTElement.SEQUENCE),0==xml.getElementsByTagName(VASTElement.LINEAR).length?0==xml.getElementsByTagName(VASTElement.NON_LINEAR_ADS).length?0!=xml.getElementsByTagName(VASTElement.COMPANION_ADS).length&&(creative.companionAds=this._parseCreativeCompanionAds(xml.getElementsByTagName(VASTElement.COMPANION_ADS))):creative.nonLinearAds=this._parseCreativeNonLinearAds(xml.getElementsByTagName(VASTElement.NON_LINEAR_ADS)):creative.linearElement=this._parseCreativeLinear(xml.getElementsByTagName(VASTElement.LINEAR)),creative},_parseCreativeLinear:function(xml){for(var vastLinearElement=new VASTLinearElement,nodeArray=xml[0].childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.DURATION?vastLinearElement.duration=xmlParser.textContent(nodeArray[i]):nodeArray[i].nodeName==VASTElement.TRACKING_EVENTS?vastLinearElement.trackingEvents=this._parseTrackingEvents(nodeArray[i]):nodeArray[i].nodeName==VASTElement.VIDEO_CLICKS?vastLinearElement.videoClick=this._parseVideoClick(nodeArray[i]):nodeArray[i].nodeName==VASTElement.MEDIA_FILES&&(vastLinearElement.mediaFiles=this._parseMediaFiles(nodeArray[i]));return vastLinearElement},_parseCreativeNonLinearAds:function(xml){for(var vastNonLinearAds=[],nonLinearAd=xml[0].getElementsByTagName(VASTElement.NON_LINEAR),nonLinearAdLength=nonLinearAd.length,i=0,vastNonLinearAd;i<nonLinearAdLength;i++){vastNonLinearAd=new VASTNonLinearAd,vastNonLinearAd.id=nonLinearAd[i].getAttribute(VASTElement.ID),vastNonLinearAd.width=nonLinearAd[i].getAttribute(VASTElement.WIDTH),vastNonLinearAd.height=nonLinearAd[i].getAttribute(VASTElement.HEIGHT),vastNonLinearAd.expandedWidth=nonLinearAd[i].getAttribute(VASTElement.EXPANDED_WIDTH),vastNonLinearAd.expandedHeight=nonLinearAd[i].getAttribute(VASTElement.EXPANDED_HEIGHT),vastNonLinearAd.scalable=!('true'!=nonLinearAd[i].getAttribute(VASTElement.SCALABLE)),vastNonLinearAd.maintainAspectRatio=!('true'!=nonLinearAd[i].getAttribute(VASTElement.MAINTAIN_ASPECT_RATIO)),vastNonLinearAd.apiFramework=nonLinearAd[i].getAttribute(VASTElement.API_FRAMEWORK),vastNonLinearAd.minSuggestedDuration=nonLinearAd[i].getAttribute(VASTElement.MIN_SUGGESTED_DURATION);for(var nodeArray=nonLinearAd[i].childNodes,nodeArrayLength=nodeArray.length,j=0;j<nodeArrayLength;j++)if(nodeArray[j].nodeName==VASTElement.AD_PARAMETERS)vastNonLinearAd.adParameters=xmlParser.textContent(nodeArray[j]);else if(nodeArray[j].nodeName==VASTElement.NON_LINEAR_CLICK_THROUGH)vastNonLinearAd.clickThroughURL=this.trim(xmlParser.textContent(nodeArray[j]));else if(nodeArray[j].nodeName==VASTElement.IFRAME_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.IFRAME,vastNonLinearAd.resourceType=vastResourceType,vastNonLinearAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}else if(nodeArray[j].nodeName==VASTElement.HTML_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.HTML,vastNonLinearAd.resourceType=vastResourceType,vastNonLinearAd.code=xmlParser.textContent(nodeArray[j])}else if(nodeArray[j].nodeName==VASTElement.STATIC_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.STATIC,vastNonLinearAd.resourceType=vastResourceType,vastNonLinearAd.creativeType=nodeArray[j].getAttribute(VASTElement.CREATIVE_TYPE),vastNonLinearAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}vastNonLinearAds.push(vastNonLinearAd)}return vastNonLinearAd},_parseCreativeCompanionAds:function(xml){for(var vastCompanionAds=[],companions=xml[0].getElementsByTagName(VASTElement.COMPANION),companionsLength=companions.length,i=0,vastCompanionAd;i<companionsLength;i++){vastCompanionAd=new VASTCompanionAd,vastCompanionAd.id=companions[i].getAttribute(VASTElement.ID),vastCompanionAd.width=companions[i].getAttribute(VASTElement.WIDTH),vastCompanionAd.height=companions[i].getAttribute(VASTElement.HEIGHT),vastCompanionAd.expandedWidth=companions[i].getAttribute(VASTElement.EXPANDED_WIDTH),vastCompanionAd.expandedHeight=companions[i].getAttribute(VASTElement.EXPANDED_HEIGHT);for(var nodeArray=companions[i].childNodes,nodeArrayLength=nodeArray.length,j=0;j<nodeArrayLength;j++)if(nodeArray[j].nodeName==VASTElement.AD_PARAMETERS)vastCompanionAd.adParameters=xmlParser.textContent(nodeArray[j]);else if(nodeArray[j].nodeName==VASTElement.ALT_TEXT)vastCompanionAd.altText=xmlParser.textContent(nodeArray[j]);else if(nodeArray[j].nodeName==VASTElement.COMPANION_CLICK_THROUGH)vastCompanionAd.clickThroughURL=this.trim(xmlParser.textContent(nodeArray[j]));else if(nodeArray[j].nodeName==VASTElement.IFRAME_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.IFRAME,vastCompanionAd.resourceType=vastResourceType,vastCompanionAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}else if(nodeArray[j].nodeName==VASTElement.HTML_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.HTML,vastCompanionAd.resourceType=vastResourceType,vastCompanionAd.code=xmlParser.textContent(nodeArray[j])}else if(nodeArray[j].nodeName==VASTElement.STATIC_RESOURCE){var vastResourceType=new VASTResourceType;vastResourceType.name=vastResourceType.STATIC,vastCompanionAd.resourceType=vastResourceType,vastCompanionAd.creativeType=nodeArray[j].getAttribute(VASTElement.CREATIVE_TYPE),vastCompanionAd.url=this.trim(xmlParser.textContent(nodeArray[j]))}else if(nodeArray[j].nodeName==VASTElement.TRACKING_EVENTS){var trackings=nodeArray[j].getElementsByTagName(VASTElement.TRACKING),trackingsLength=trackings.length;if(0<trackingsLength){vastCompanionAd.creativeView=[];
1for(var k=0,type;k<trackingsLength;k++)type=trackings[k].getAttribute(VASTElement.EVENT),type==VASTElement.CREATIVE_VIEW&&vastCompanionAd.creativeView.push(this.trim(xmlParser.textContent(trackings[k])))}}vastCompanionAds.push(vastCompanionAd)}return vastCompanionAds},_parseTrackingEvents:function(xml){for(var vastTrackingEvents=[],trackings=xml.getElementsByTagName(VASTElement.TRACKING),trackingsLength=trackings.length,i=0,vastTrackingEvent;i<trackingsLength;i++)vastTrackingEvent=new VASTTrackingEvent,vastTrackingEvent.urls.push(xmlParser.textContent(trackings[i])),vastTrackingEvent.type=trackings[i].getAttribute(VASTElement.EVENT),vastTrackingEvents.push(vastTrackingEvent);return vastTrackingEvents},_parseVideoClick:function(xml){for(var vastVideoClick=new VASTVideoClick,nodeArray=xml.childNodes,nodeArrayLength=nodeArray.length,i=0;i<nodeArrayLength;i++)nodeArray[i].nodeName==VASTElement.CLICK_THROUGH?vastVideoClick.clickThrough=this.trim(xmlParser.textContent(nodeArray[i])):nodeArray[i].nodeName==VASTElement.CLICK_TRACKING?vastVideoClick.clickTrackings.push(this.trim(xmlParser.textContent(nodeArray[i]))):nodeArray[i].nodeName==VASTElement.CUSTOM_CLICK&&vastVideoClick.customClicks.push(this.trim(xmlParser.textContent(nodeArray[i])));return vastVideoClick},_parseMediaFiles:function(xml){for(var vastMediaFiles=[],mediaFiles=xml.getElementsByTagName(VASTElement.MEDIA_FILE),mediaFilesLength=mediaFiles.length,i=0,vastMediaFile;i<mediaFilesLength;i++)vastMediaFile=new VASTMediaFile,vastMediaFile.id=mediaFiles[i].getAttribute(VASTElement.ID),vastMediaFile.bitrate=mediaFiles[i].getAttribute(VASTElement.BITRATE),vastMediaFile.height=mediaFiles[i].getAttribute(VASTElement.HEIGHT),vastMediaFile.width=mediaFiles[i].getAttribute(VASTElement.WIDTH),vastMediaFile.delivery=mediaFiles[i].getAttribute(VASTElement.DELIVERY),vastMediaFile.type=mediaFiles[i].getAttribute(VASTElement.TYPE),vastMediaFile.scalable='true'==mediaFiles[i].getAttribute(VASTElement.SCALABLE),vastMediaFile.maintainAspectRatio='true'==mediaFiles[i].getAttribute(VASTElement.MAINTAIN_ASPECT_RATIO),vastMediaFile.apiFramework=mediaFiles[i].getAttribute(VASTElement.API_FRAMEWORK),vastMediaFile.url=this.trim(xmlParser.textContent(mediaFiles[i])),vastMediaFiles.push(vastMediaFile);return vastMediaFiles}});return vast2parser}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(3)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,on){var module=declare([],{TDAS_REG_ONLY:'tdas-reg-only',constructor:function(getModuleById,target){void 0,this.mediaPlayer=getModuleById('MediaPlayer'),this.userRegistration=getModuleById('UserRegistration'),this.mediaPlayer.addHqTag(this.TDAS_REG_ONLY),on(target,'stream-start',lang.hitch(this,this._onStreamStarted)),on(target,'stream-stop',lang.hitch(this,this._onStreamStopped)),on(target,'user-logged-out',lang.hitch(this,this._onUserLoggedOut)),on(target,'user-details',lang.hitch(this,this._onUserDetails)),this.inherited(arguments)},_onStreamStarted:function(){this.userRegistration.triggerEvent('playerStart')},_onStreamStopped:function(){this.userRegistration.triggerEvent('playerStop')},_onUserLoggedOut:function(){void 0,void 0,this._removeUserParameters(),this.mediaPlayer.disableHQ()},_onUserDetails:function(result){if(result.data||result.data){var userData={};if(result.data.dob){var dobArr=result.data.dob.split('/');userData.dob=dobArr[2]+'-'+dobArr[0]+'-'+dobArr[1]}result.data.gender&&(userData.gender=result.data.gender.substr(0,1).toLowerCase()),result.data.zip&&(userData.postalcode=result.data.zip),result.data.country&&(userData.country=result.data.country),result.data.vid&&(userData['tdas-vid']=this.userRegistration.tenantId.toString()+'.'+result.data.vid.toString()),result.data.tdas&&(userData['tdas-utags']=result.data.tdas['user-tags'],userData['tdas-utcheck']=result.data.tdas['user-tags-h
vendor: 4,481 bytes, line 1
1ash']),void 0==this.mediaPlayer.config.defaultTrackingParameters&&(this.mediaPlayer.config.defaultTrackingParameters={}),this.mediaPlayer.config.defaultTrackingParameters.user=userData,this.mediaPlayer.enableHQ()}},_removeUserParameters:function(){this.mediaPlayer.config.defaultTrackingParameters.user={}}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var i18n=__webpack_require__(19),Platform=__webpack_require__(14),flvjs=__webpack_require__(119),PlaybackState=__webpack_require__(22),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(8),__webpack_require__(20),__webpack_require__(42),__webpack_require__(33),__webpack_require__(41),__webpack_require__(71),__webpack_require__(72),__webpack_require__(11),__webpack_require__(18),__webpack_require__(66),__webpack_require__(73)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,dom,domAttr,TrackCuePoint,BreakCuePoint,HlsCuePoint,errorCode,techModule,domConstruct,topic,AdManager,Html5OnDemand){var module=declare([techModule],{SUPPORTED_EVENTS:['onMetaData','onCuePoint','onCuePointPreview','onCuePointPreviewExpired'],cuePointMap:{timestamp:'timestamp',type:'name',cue_title:TrackCuePoint.CUE_TITLE,track_artist_name:TrackCuePoint.ARTIST_NAME,track_album_name:TrackCuePoint.ALBUM_NAME,program_id:TrackCuePoint.PROGRAM_ID,cue_time_duration:TrackCuePoint.CUE_TIME_DURATION,cue_time_start:TrackCuePoint.CUE_TIME_START,track_id:TrackCuePoint.TRACK_ID,track_nowplaying_url:TrackCuePoint.NOW_PLAYING_URL,track_cover_url:TrackCuePoint.TRACK_COVER_URL,ad_id:BreakCuePoint.AD_ID,ad_type:BreakCuePoint.AD_TYPE,cue_title:BreakCuePoint.CUE_TITLE,cue_time_duration:BreakCuePoint.CUE_TIME_DURATION,ad_url:BreakCuePoint.AD_URL,ad_vast_url:BreakCuePoint.AD_VAST_URL,ad_vast:BreakCuePoint.AD_VAST,hls_track_id:HlsCuePoint.HLS_TRACK_ID,hls_segment_id:HlsCuePoint.HLS_SEGMENT_ID},eventMap:{onPlayerReady:'tech-ready',onStreamStarted:'stream-start',onStreamStopped:'stream-stop',onStreamFailed:'stream-fail',onStreamStatus:'_onStreamStatus',onTrackCuePoint:'_onTrackCuePoint',onSpeechCuePoint:'_onSpeechCuePoint',onCustomCuePoint:'_onCustomCuePoint',onTargetSpot:'targetspot-cue-point',onAdBreak:'_onAdBreakCuePoint',onSeekFailed:'seek-fail',onSeekInvalidTime:'seek-invalid-time',onTimeShiftPlaybackModeChanged:'time-shift-playback-mode-change',onTimeShiftStreamStart:'time-shift-stream-start',onTimeShiftPlayheadUpdate:'time-shift-playhead-update',onAdPlaybackStart:'ad-playback-start',onAdPlaybackComplete:'ad-playback-complete',onAdPlaybackError:'_onAdPlaybackError',onAdPlaybackSkippableState:'ad-playback-skippable-state',onAdCountdown:'ad-countdown',onAdQuartile:'ad-quartile',onVastProcessComplete:'vast-process-complete',onVastCompanionsReady:'vast-companions-ready',onConfigurationError:'configuration-error',onVideoMidRollPlaybackStart:'video-mid-roll-playback-start',onVideoMidRollPlaybackComplete:'video-mid-roll-playback-complete',onVpaidAdCompanions:'vpaid-ad-companions',onMediaLoadingStatus:'media-loading-status',onMediaPlaybackStatus:'_onMediaPlaybackStatus',onMediaPlaybackTimeUpdate:'media-playback-timeupdate',onMediaPlaybackMetadata:'media-playback-metadata',onMediaError:'_onMediaError'},statusMap:{LIVE_PAUSE:'paused',LIVE_PLAYING:'onAir',LIVE_STOP:'disconnected',LIVE_FAILED:'streamUnavailable',LIVE_BUFFERING:'buffering',LIVE_CONNECTING:'connecting',LIVE_RECONNECTING:'reconnecting',MEDIA_TIME_UPDATE:'timeupdate',MEDIA_SEEK_FAILED:'seekfailed',MEDIA_SEEK_INVALID_TIME:'seekinvalidtime',MEDIA_ENDED:'ended',MEDIA_PAUSED:'pause',MEDIA_STARTED:'play',MEDIA_STOPPED:'stop',MEDIA_RESUMED:'play',MEDIA_SEEKED:'play',MEDIA_BUFFERING:'buffering'},CDN_URL:'sdk.listenlive.co',constructor:function(config,target){void 0,this.adManager=null,this.errorCode=new errorCode,this.target=target,this.config.platformId=this.config.platformId!=void 0&&''!=this.config.platformId?this.config.platformId:'prod01';var platform=new Platform(this.config.platformId);this.config.moduleDir=platform.endpoint.coreModuleDir,this._isAdBreak=!1,this.playerStarted,this.inherited(arguments)},start:function(){void 0,this.inherited(arguments),flvjs.isSupported()&&this._embedFlash(),this.html5OnDemand=new Html5OnDemand(this.playerNode)},_onReady:function(){},_onError:function(data){error={}
1,error.code=1,error.message=data,void 0,this.emit('tech-error',{error:error})},_onMetadata:function(metadata){void 0,this.emit('metadata-cue-point',metadata)},_onStreamData:function(data){delay=data.timestamp-(new Date().getTime()-this.playerStarted),data.delay=delay,window.setTimeout(()=>{this.emit('stream-data',data)},delay)},prepare:function(){this.inherited(arguments)},playStream:function(params){this.inherited(arguments),void 0,this._createPlayer(params.url),this.emit('flv-player-status',{type:'stream',status:'playing'})},pauseStream:function(){this.inherited(arguments),this.flashMovie.tdPlayer_pauseStream()},stopStream:function(){this.inherited(arguments),this.player&&(this.player.pause(),this.player.unload(),this.player.detachMediaElement(),this.player.destroy(),this.player=null,this.emit('flv-player-status',{type:'stream',status:'stopped'}))},resumeStream:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_resumeStream&&this.flashMovie.tdPlayer_resumeStream()},seekStream:function(seekOffset){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_seekStream&&this.flashMovie.tdPlayer_seekStream(seekOffset)},seekLive:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_seekLive&&this.flashMovie.tdPlayer_seekLive()},setVolume:function(volumePercent){this.inherited(arguments),this.videoNode.volume=volumePercent},mute:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_mute&&this.flashMovie.tdPlayer_mute()},unMute:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_unMute&&this.flashMovie.tdPlayer_unMute()},skipAd:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_skipAd&&this.flashMovie.tdPlayer_skipAd()},playMedia:function(params){this.inherited(arguments),this._createPlayer(params.url),this.emit('flv-player-status',{type:'media',status:'playing'})},pauseMedia:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_pauseMedia&&this.flashMovie.tdPlayer_pauseMedia()},resumeMedia:function(){this.inherited(arguments),'function'==typeof this.flashMovie.tdPlayer_resumeMedia&&this.flashMovie.tdPlayer_resumeMedia()},stopMedia:function(){this.inherited(arguments),this.player&&(this.player.pause(),this.player.unload(),this.player.detachMediaElement(),this.player.destroy(),this.player=null,this.emit('flv-player-status',{type:'media',status:'stopped'}))},seekMedia:function(seekOffset){this.inherited(arguments),0==seekOffset&&(seekOffset=.001),'function'==typeof this.flashMovie.tdPlayer_seekMedia&&this.flashMovie.tdPlayer_seekMedia(seekOffset)},_onStop:function(){this._emitStreamStatus(PlaybackState.STOP)},_onPlay:function(){this._emitStreamStatus(PlaybackState.PLAY)},_emitStreamStatus:function(playbackState){var statusMessages=i18n.getLocalization();if(void 0!=statusMessages){let msg={};msg.status=statusMessages[playbackState],msg.status&&this.emit('stream-status',msg)}},_onStreamStatus:function(data){var targetNode=dom.byId(data.id,document);if(targetNode){var statusMessages=i18n.getLocalization(),msg=this.statusMap[data.code];msg&&statusMessages[msg]&&(data.status=statusMessages[msg]),this.emit('stream-status',data,targetNode)}else;},_onMediaPlaybackStatus:function(data){var targetNode=dom.byId(data.id,document);if(targetNode){var statusMessages=i18n.getLocalization(),msg=this.statusMap[data.code];msg&&statusMessages[msg]&&(data.status=statusMessages[msg]),'MEDIA_STARTED'===data.code&&this.emit('media-playback-started'),this.emit('media-playback-status',data,targetNode)}else;},_onMediaError:function(data){var targetNode=dom.byId(data.id,document);if(targetNode){var statusMessages=i18n.getLocalization();statusMessages.error&&(data.error=statusMessages.error),this.emit('media-playback-error',data,targetNode)}else;},_onTrackCuePoint:function(data){void 0,this.emit('track-cue-point',data)},_onSpeechCuePoint:function(data){void 0,data.cuePoint&&(data.cuePoint.mount=this.connection.mount),this.emit('speech-cue-point',data)},_onCustomCuePoint:function(data){void 0,data.cuePoint&&(data.cuePoint.mount=this.connection.mount),this.emit
1('custom-cue-point',data)},_onAdBreakCuePoint:function(data){void 0,this._adBreak=!!data.adBreakData.isVastInStream,this.emit('ad-break-cue-point',data)},_onAdPlaybackError:function(data){void 0,this._adBreak||this.emit('ad-playback-error',data)},_onLoadingComplete:function(){},_onScriptData:function(data){void 0,void 0;var cuePoint={};if(data.onCuePoint)if(cuePoint=this.__onCuePoint(data.onCuePoint),cuePoint.tagTimestamp=data.tagTimestamp,cuePoint.parameters.tag_timestamp=data.tagTimestamp,cuePoint.parameters.tag_timestamp&&(cuePoint.parameters.tag_timestamp_formatted=this.toHHMMSS(data.tagTimestamp/1e3)),0==data.tagTimestamp&&(this.playerStarted=new Date().getTime()),delay=data.tagTimestamp-(new Date().getTime()-this.playerStarted),cuePoint.parameters.time_played=moment(new Date().getTime()+delay).format('HH:mm:ss.SSS'),'ad'==cuePoint.type){var adBreakData={};adBreakData.type='ad',adBreakData.tagTimestamp=data.tagTimestamp,adBreakData.tagTimestampFormatted=this.toHHMMSS(data.tagTimestamp/1e3),adBreakData.timePlayed=cuePoint.parameters.time_played,adBreakData.adVast=void 0!=cuePoint[BreakCuePoint.AD_VAST]&&''!=cuePoint[BreakCuePoint.AD_VAST]?cuePoint[BreakCuePoint.AD_VAST]:null,adBreakData.adType=void 0!=cuePoint[BreakCuePoint.AD_TYPE]&&''!=cuePoint[BreakCuePoint.AD_TYPE]?cuePoint[BreakCuePoint.AD_TYPE]:null,adBreakData.cueID=void 0!=cuePoint[BreakCuePoint.AD_ID]&&''!=cuePoint[BreakCuePoint.AD_ID]?cuePoint[BreakCuePoint.AD_ID]:null,adBreakData.cueTitle=void 0!=cuePoint[BreakCuePoint.CUE_TITLE]&&''!=cuePoint[BreakCuePoint.CUE_TITLE]?cuePoint[BreakCuePoint.CUE_TITLE]:null,adBreakData.duration=void 0!=cuePoint[BreakCuePoint.CUE_TIME_DURATION]&&''!=cuePoint[BreakCuePoint.CUE_TIME_DURATION]?cuePoint[BreakCuePoint.CUE_TIME_DURATION]:null,adBreakData.isVastInStream=!!(void 0!=cuePoint[BreakCuePoint.AD_VAST_URL]&&''!=cuePoint[BreakCuePoint.AD_VAST_URL]||cuePoint[BreakCuePoint.AD_VAST]&&''!=cuePoint[BreakCuePoint.AD_VAST]),adBreakData.url=void 0!=cuePoint[BreakCuePoint.AD_URL]&&''!=cuePoint[BreakCuePoint.AD_URL]?cuePoint[BreakCuePoint.AD_URL]:null,adBreakData.vastUrl=void 0!=cuePoint[BreakCuePoint.AD_VAST_URL]&&''!=cuePoint[BreakCuePoint.AD_VAST_URL]?cuePoint[BreakCuePoint.AD_VAST_URL]:null,setTimeout(()=>{!0==adBreakData.isVastInStream&&(adBreakData.adVast||adBreakData.vastUrl)&&topic.publish('api/request','get-vast-instream',adBreakData),this._onAdBreakCuePoint({adBreakData:adBreakData,cuePoint:cuePoint})},delay)}else window.setTimeout(()=>{this._onTrackCuePoint({cuePoint:cuePoint})},delay)},__onCuePoint:function(data){var cuePoint={parameters:data.parameters,timestamp:data.timestamp,type:data.name};for(var key in data.parameters)this.cuePointMap[key]&&(cuePoint[this.cuePointMap[key]]=data.parameters[key]);return'ad'==cuePoint.type&&(cuePoint.isVastInStream=!!(void 0!=cuePoint[BreakCuePoint.AD_VAST_URL]&&''!=cuePoint[BreakCuePoint.AD_VAST_URL]||cuePoint[BreakCuePoint.AD_VAST]&&''!=cuePoint[BreakCuePoint.AD_VAST])),cuePoint},__isSupportedEvent:function(event){return-1!=array.indexOf(this.SUPPORTED_EVENTS,event.type)},_tdPlayerEvents:function(eventName,data){void 0,void 0;var targetNode=dom.byId(data.id,document);if('_'==this.eventMap[eventName].substr(0,1)){var fn=lang.hitch(this,this.eventMap[eventName]);fn(data,eventName)}else if(targetNode&&this.eventMap[eventName])this.emit(this.eventMap[eventName],data,targetNode);else;},__createMediaTag:function(mediaTagType){if(mediaTagType){var node=domConstruct.create(mediaTagType,{id:'tdplayer_flv_'+mediaTagType+'node',type:mediaTagType},this.flvNode,'first');domAttr.set(node,'height','0%'),domAttr.set(node,'width','0%'),domAttr.set(node,'x-webkit-airplay','allow');var sourceNode=domConstruct.create('source',{id:'tdplayer_flv'+mediaTagType+'source'},node,'first');return domAttr.set(sourceNode,'src',''),domAttr.set(node,'playsinline',''),node}},_createPlayer:function(url){this.player=flvjs.createPlayer({type:'flv',url:url}),this.videoNode.addEventListener('play',lang.hitch(this,this._onPlay)),this.videoNode.addEventListener('abort',lang.hitch(this,this._onStop)),this.videoNode.addEventListener('ended',lang.hitch(this,this._onStop)),this.videoNode.addEventListener('pause',lang.hitch(this,this._onStop)),this.player.attachMediaElement(this.videoNode),this.player.load(),this.player.play(),this.player.on(flvjs.Events.METADATA_ARRIVED,lang.hitch(this,this._onMetadata)),this.player.on(flvjs.Events.STREAMDATA_ARRIVED,lang.hitch(this,this._onStreamData)),this.player.on(flvjs.Events.ERROR,lang.hitch(this,this._onError)),this.player.on(flvjs.Events.MEDIA_INFO,()=>void 0),this.player.on(flvjs.Events.SCRIPTDATA_ARRIVED,lang.hitch(this,this._onScriptData)),this.playerStarted=new Date().getTime()+1},_embedFlash:function(){void 0,window.tdPlayerEvents=lang.hitch(this,this._tdPlayerEvents);var statusMessages=i18n.getLocalization(),corePlugins=[{id:'directLiveStream'}];corePlugins[0].timeshift=this.config.timeShift?{active:this.config.timeShift.active||0,max_listening_time:this.config.timeShift.max_listening_time||30}:{active:0},this.config.plugins!=void 0&&0<this.config.plugins.length&&(corePlugins=corePlugins.concat(this.config.plugins));var playerConfig={playercore:{platform_id:this.config.platformId,plugins:corePlugins}};null!=this.config.moduleDir&&(playerConfig.playercore.module_dir=this.config.moduleDir),void 0,document.getElementById(this.config.playerId).innerHTML='';domConstruct.create('div',{id:'flash_content'},document.getElementById(this.config.playerId)),null==this.flvNode&&(this.flvNode=domConstruct.create('div',{id:'tdplayer_flv'},this.playerNode,'first')),this.videoNode||(this.videoNode=this.__createMediaTag('video')),this._techReady()},toHHMMSS:function(value){var sec_num=parseInt(value,10),hours=Math.floor(sec_num/3600),minutes=Math.floor((sec_num-3600*hours)/60),seconds=sec_num-3600*hours-60*minutes;return 10>hours&&(hours='0'+hours),10>minutes&&(minutes='0'+minutes),10>seconds&&(seconds='0'+seconds),hours+':'+minutes+':'+seconds}
1,_techReady:function(){this.emit('tech-ready',{id:this.playerNode})}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(18),__webpack_require__(11),__webpack_require__(71),__webpack_require__(72),__webpack_require__(41),__webpack_require__(33),__webpack_require__(142),__webpack_require__(73)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,topic,domConstruct,errorCode,techModule,HlsCuePoint,BreakCuePoint,Html5Live,Html5OnDemand){var module=declare([techModule],{constructor:function(config,target){void 0,this.errorCode=new errorCode,this.playbackStatus=null,this.html5CheckerNode=null,this.target=target,this.inherited(arguments)},start:function(){return this._isHTML5Supported()?void(this.inherited(arguments),this.html5Live=new Html5Live(this.playerNode,this.config),this.html5Live.setPlaybackStatusHandler(lang.hitch(this,this._onPlaybackStatus)),this.html5Live.setCuePointHandler(lang.hitch(this,this._onTrackCuePoint)),this.html5Live.setAdBreakHandler(lang.hitch(this,this._onAdBreak)),this.html5Live.setHlsCuePointHandler(lang.hitch(this,this._onHlsCuePoint)),this.html5Live.setSpeechCuePointHandler(lang.hitch(this,this._onSpeechCuePoint)),this.html5Live.setCustomCuePointHandler(lang.hitch(this,this._onCustomCuePoint)),this.html5Live.setStreamStartHandler(lang.hitch(this,this._onStreamStart)),this.html5Live.setStreamStopHandler(lang.hitch(this,this._onStreamStop)),this.html5Live.setStreamFailedHandler(lang.hitch(this,this._onStreamFailed)),this.html5Live.setTimeshiftInfoHandler(lang.hitch(this,this._onTimeshiftInfo)),this.html5OnDemand=new Html5OnDemand(this.playerNode),this._isMediaTagInitialized=!1,this.emit('tech-ready',{id:this.playerNode})):void this.emit('tech-error',{error:this.errorCode.html5ModuleMap.browserNotSupported})},prepare:function(){this.inherited(arguments),this._initMediaTag()},playStream:function(params){this.isLiveStream=!0,this.inherited(arguments),this.params=params,this._isMediaTagInitialized||this._initMediaTag(),this.html5OnDemand.clean(),this.html5Live.play(params)},pauseStream:function(){this.inherited(arguments),this.html5Live.pause()},stopStream:function(){this.inherited(arguments),this.html5Live.stop()},resumeStream:function(){this.inherited(arguments),this.html5Live.resume()},seekStream:function(seconds){this.inherited(arguments),this.html5Live.seekStream(seconds)},seekLive:function(){this.inherited(arguments),this.html5Live.seekLive()},seekFromLive:function(seconds){this.inherited(arguments),this.html5Live.seekFromLive(seconds)},getCloudStreamInfo:function(){this.inherited(arguments),this.html5Live.getCloudStreamInfo()},playProgram:function(programID,offset){this.inherited(arguments),this.html5Live.playProgram(programID,offset)},setVolume:function(volumePercent){this.inherited(arguments),this.html5Live.setVolume(volumePercent),this.html5OnDemand.setVolume(volumePercent)},muteStream:function(){this.inherited(arguments),this.html5Live.mute()},muteMedia:function(){this.inherited(arguments),this.html5OnDemand.mute()},unMuteStream:function(){this.inherited(arguments),this.html5Live.unMute(this.params)},unMuteMedia:function(){this.inherited(arguments),this.html5OnDemand.unMute(this.params)},playMedia:function(params){this.inherited(arguments);void 0==this.html5OnDemand||(0<=params.url.indexOf('live.streamtheworld.com')?this.emit('tech-error',{error:this.errorCode.html5ModuleMap.tritonListenLink}):(this.playbackOnDemandStatushandler=this.html5OnDemand.setPlaybackStatusHandler(lang.hitch(this,this._onMediaPlaybackStatus)),this.html5OnDemand.play({mediaUrl:params.url,mediaFormat:'audio',omnyOrganizationId:params.omnyOrganizationId,omnyClipId:params.omnyClipId,omnySessionId:params.omnySessionId,enableOmnyAnalytics:params.enableOmnyAnalytics})))},pauseMedia:function(){void 0==this.html5OnDemand||(this.inherited(arguments),this.html5OnDemand.pause())},resumeMedia:function(){void 0==this.html5OnDemand||(this.inherited(arguments),this.html5OnDemand.resume())},stopMedia:function(){void 0==this.html5OnDemand||(this.inherited(arguments),this.html5OnDemand.stop())},seekMedia:function(seekOffset){this.inherited(arguments),this.html5OnDemand.seek(seekOffset)},changeHtml5PlayBackRate:function(rate){this.inherited(arguments),this.html5OnDemand.changePlayBackRate(rate)},_initMediaTag:function(){this.html5OnDemand.initMediaTag(),this._isMediaTagInitialized=!0},_onTrackCuePoint:function(data){void 0,void 0,data.cuePoint&&this.connection.mount&&(data.cuePoint.mount=this.connection.mount),this.emit
1('track-cue-point',data)},_onSpeechCuePoint:function(data){void 0,data.cuePoint&&this.connection.mount&&(data.cuePoint.mount=this.connection.mount),this.emit('speech-cue-point',data)},_onCustomCuePoint:function(data){void 0,data.cuePoint&&this.connection.mount&&(data.cuePoint.mount=this.connection.mount),this.emit('custom-cue-point',data)},_onHlsCuePoint:function(data){if(this.emit('hls-cue-point',data),data.cuePoint&&data.cuePoint.hlsTrackId){var audioTracks=this.connection.mountpoint.mediaFormat.audioTracks;audioTracks&&audioTracks.length&&audioTracks.length>=data.cuePoint.hlsTrackId&&this._currentBitrate!=audioTracks[data.cuePoint.hlsTrackId].bitRate&&(this._currentBitrate=audioTracks[data.cuePoint.hlsTrackId].bitRate,this.setCurrentTrack(audioTracks[data.cuePoint.hlsTrackId]),data.cuePoint.audioTrack=audioTracks[data.cuePoint.hlsTrackId],this.emit('stream-track-change',data))}},_onAdBreak:function(data){void 0,void 0,data.cuePoint!=void 0&&(data.adBreakData={},data.adBreakData.adVast=data.cuePoint[BreakCuePoint.AD_VAST]!=void 0&&''!=data.cuePoint[BreakCuePoint.AD_VAST]?data.cuePoint[BreakCuePoint.AD_VAST]:null,data.adBreakData.cueID=data.cuePoint[BreakCuePoint.AD_ID]!=void 0&&''!=data.cuePoint[BreakCuePoint.AD_ID]?data.cuePoint[BreakCuePoint.AD_ID]:null,data.adBreakData.cueTitle=data.cuePoint[BreakCuePoint.CUE_TITLE]!=void 0&&''!=data.cuePoint[BreakCuePoint.CUE_TITLE]?data.cuePoint[BreakCuePoint.CUE_TITLE]:null,data.adBreakData.duration=data.cuePoint[BreakCuePoint.CUE_TIME_DURATION]!=void 0&&''!=data.cuePoint[BreakCuePoint.CUE_TIME_DURATION]?data.cuePoint[BreakCuePoint.CUE_TIME_DURATION]:null,data.adBreakData.isVastInStream=!!(data.cuePoint[BreakCuePoint.AD_VAST_URL]!=void 0&&''!=data.cuePoint[BreakCuePoint.AD_VAST_URL]||data.cuePoint[BreakCuePoint.AD_VAST]&&''!=data.cuePoint[BreakCuePoint.AD_VAST]),data.adBreakData.url=data.cuePoint[BreakCuePoint.AD_URL]!=void 0&&''!=data.cuePoint[BreakCuePoint.AD_URL]?data.cuePoint[BreakCuePoint.AD_URL]:null,data.adBreakData.vastUrl=data.cuePoint[BreakCuePoint.AD_VAST_URL]!=void 0&&''!=data.cuePoint[BreakCuePoint.AD_VAST_URL]?data.cuePoint[BreakCuePoint.AD_VAST_URL]:null),!0==data.adBreakData.isVastInStream&&(data.adBreakData.adVast||data.adBreakData.vastUrl)&&topic.publish('api/request','get-vast-instream',data.adBreakData),this.emit('ad-break-cue-point',data)},_onPlaybackStatus:function(e){this.playbackStatus==e.code||(this.playbackStatus=e.code,this.emit('stream-status',e))},_onMediaPlaybackStatus:function(e){if('Error'==e.type)return void this.emit('media-playback-error',{error:e.type,mediaElement:e.html5Node});if('timeupdate'==e.type)return void this.emit('media-playback-timeupdate',{status:e.type,code:e.code,duration:parseInt(e.html5Node.duration),playedTime:parseInt(e.html5Node.currentTime),remainingTime:parseInt(e.html5Node.duration-e.html5Node.currentTime),percent:(e.html5Node.currentTime/e.html5Node.duration).toFixed(2)});this.emit('media-playback-status',{status:e.type,mediaElement:e.html5Node}),'play'==e.type&&this.emit('media-playback-started');'Ended'==e.type&&this.html5OnDemand.stop()},_onMediaLoadingStatus:function(e){this.emit('media-loading-status',{percent:e.percent,mediaElement:e.html5Node})},_onStreamStart:function(){this._currentBitrate=null,this.setCurrentTrack(null),this.emit('stream-start')},_onStreamStop:function(){this.setCurrentTrack(null),this.emit('stream-stop')},_onStreamFailed:function(){this.setCurrentTrack(null),this.emit('stream-fail')},_onTimeshiftInfo:function(e){this.emit('timeshift-info',e)},_isHTML5Supported:function(){this.html5CheckerNode=domConstruct.create('audio',{id:'testHtml5Node'},this.playerNode,'first');var supported=!!this.html5CheckerNode.canPlayType;return null!=this.html5CheckerNode&&domConstruct.destroy(this.html5CheckerNode),supported}});return module}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3),__webpack_require__(13),__webpack_require__(2),__webpack_require__(65)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on,Evented,lang,NowPlayingApi){var aSyncCuePointDispatcher=declare([],{POLLING_DELAY:5e3,constructor:function(cfg){void 0,this.mount=null,this._cuePoint=[],this._adBreaks=[],this._npChecker=0,this._npTimerId=null,this._init(cfg)},_init:function(cfg){var target=null;this.nowPlayingApi=new NowPlayingApi(cfg,new Evented()),target=this.nowPlayingApi.target,this._onCuePointHandler=lang.hitch(this,this._onCuePoint),this._onEmptyCuePointHandler=lang.hitch(this,this._onEmptyCuePoint),null!=target&&(on(target,'cue-point',this._onCuePointHandler),on(target,'cue-point-empty',this._onEmptyCuePointHandler))},startCuePointsListener:function(mount){this.mount=mount,this._getNowPlaying(this.mount),this._npTimerId=setInterval(lang.hitch(this,function(){lang.hitch(this,this._getNowPlaying(this.mount))}),this.POLLING_DELAY)},stopCuePointsListener:function(){clearInterval(this._npTimerId),0<this._cuePoint.length&&this._cuePoint.pop()},setTrackCuePointCallback:function(callback){this._trackCuePointCallback=callback},setAdBreakCuePointCallback:function(callback){this._adBreakCuePointCallback=callback},_getNowPlaying:function(mount){this.nowPlayingApi.load({mount:mount,hd:!1,numberToFetch:1,eventType:'track',mode:'nowPlaying'})},_onCuePoint:function(e){this.currentCuePoint=e.data.cuePoint,this.currentCuePoint.adUrl=null,this.currentCuePoint.cueTimeDuration=0<parseInt(this.currentCuePoint.cueTimeDuration)?parseInt(this.currentCuePoint.cueTimeDuration):15e3,this.currentMount=e.data.mount;var eventType=this.currentCuePoint.type,eventTimestamp=this.currentCuePoint.timestamp;if('ad'==eventType){if('endbreak'==this.currentCuePoint.adType)return;this._onAdBreak(eventTimestamp)}else{var artist=this.currentCuePoint.artistName,title=this.currentCuePoint.cueTitle;if(0<this._cuePoint.length)for(var i=0;i<this._cuePoint.length;i++)if(this._cuePoint[i].artist==artist&&this._cuePoint[i].title==title)return;artist!=void 0&&title!=void 0&&this._onTrack(artist,title)}},_onTrack:function(artistname,songtitle){1<this._cuePoint.length&&this._cuePoint.shift(),this._cuePoint.push({artist:artistname,title:songtitle}),this._trackCuePointCallback({mount:this.currentMount,cuePoint:this.currentCuePoint})},_onEmptyCuePoint:function(){this._npChecker+=1,3==this._npChecker&&(clearInterval(this._npTimerId),this._npChecker=0)}
1,_onAdBreak:function(adTimestamp){var isAlreadySent=this._adBreakChecker(adTimestamp);!1==isAlreadySent&&this._adBreakCuePointCallback({mount:this.currentMount,cuePoint:this.currentCuePoint})},_adBreakChecker:function(adTimestamp){if(0==this._adBreaks.length)return this._adBreaks.push({timestamp:adTimestamp}),0==this._cuePoint.length;for(var i=0;i<this._adBreaks.length;i++)if(this._adBreaks[i].timestamp==adTimestamp)return!0;return 2<this._adBreaks.length&&this._adBreaks.shift(),this._adBreaks.push({timestamp:adTimestamp}),!1}});return aSyncCuePointDispatcher}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3),__webpack_require__(2),__webpack_require__(22),__webpack_require__(39)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on,lang,PlaybackState,request){var consumptionAnalytics=declare([],{constructor:function(html5Player){var context=this;void 0,this.LocalStorageKeyPrefix='omnyfm:ConsumptionData:',this.pushUrl='https://traffic.omny.fm/api/consumption/events?organizationId=',this.html5Player=html5Player,this.html5Player.on('html5-playback-status',lang.hitch(this,this.__onHTML5PlayerStatus)),this.events=[],this.nextSeqNumber=1,this.position=0,this.lastPosition=0,this.started=!1,this.enabled=!0,this.flushAndSendAnyLocalStorageConsumptionData(),on(window,'beforeunload',function(){context.onPageUnload()})},init:function(organizationId,clipId,sessionId){this.organizationId=organizationId,this.clipId=clipId,this.sessionId=sessionId},__onHTML5PlayerStatus:function(e){var position=e.mediaNode.currentTime;switch(e.type){case PlaybackState.PLAY:this.start(position);break;case PlaybackState.STOP:this.finished();break;case PlaybackState.ENDED:this.finished();break;case PlaybackState.TIME_UPDATE:this.setCurrentPosition(position);default:}},isUsingCompletedOnlyMode:function(){return this.isBeaconSupported()||this.isLocalStorageSupported()},isStorageAvailable:function(type){var storage;try{storage=window[type];const x='__storage_test__';return storage.setItem(x,x),storage.removeItem(x),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||'QuotaExceededError'===e.name||'NS_ERROR_DOM_QUOTA_REACHED'===e.name)&&storage&&0!==storage.length}},isUsingLocalStorageTransmissionMode:function(){return!!this.isUsingCompletedOnlyMode()&&!this.isBeaconSupported()&&!!this.isLocalStorageSupported()},isLocalStorageSupported:function(){return this.isStorageAvailable('localStorage')},onPageUnload:function(){(this.isBeaconSupported()||this.isUsingLocalStorageTransmissionMode())&&(this.started&&this.finished(),this.flushEvents())},isBeaconSupported:function(){return!(navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform))&&!1},pushEvent:function(eventType){this.sessionId&&this.events.push({OrganizationId:this.organizationId,ClipId:this.clipId,SessionId:this.sessionId,Type:eventType,Position:this.position,SeqNumber:this.nextSeqNumber++,Timestamp:Math.floor(Date.now()/1e3)})},start:function(position){this.started||(this.setCurrentPosition(position,!0),this.started=!0,this.pushEvent('Start'))},setCurrentPosition:function(position,force){(this.started||force)&&(this.lastPosition=this.position,this.position=position)},finished:function(){this.pushEvent('Stop'),this.started=!1},flushAndSendAnyLocalStorageConsumptionData:function(){var context=this;if(this.isLocalStorageSupported()){var keys=Object.keys(window.localStorage);keys.forEach(function(key){if(0===key.indexOf(context.LocalStorageKeyPrefix)){const jsonData=window.localStorage.getItem(key);window.localStorage.removeItem(key),context.sendConsumptionPayloadToRemoteService(jsonData)}})}},flushEvents:function(){if(this.enabled&&0!=this.events.length){var jsonData=JSON.stringify({Source:'CustomWeb',Events:this.events,Completed:!0});this.isUsingLocalStorageTransmissionMode()?window.localStorage.setItem(this.LocalStorageKeyPrefix+this.sessionId,jsonData):this.sendConsumptionPayloadToRemoteService(jsonData),this.events=[],this.nextSeqNumber=1}},sendConsumptionPayloadToRemoteService:function(jsonData){var context=this;if(this.organizationId==void 0||null==this.organizationId){var analyticsData=JSON.parse(jsonData);if(analyticsData.Events==void 0||null==analyticsData.Events)return;this.organizationId=analyticsData.Events[0].OrganizationId}this.isBeaconSupported()?navigator.sendBeacon(this.pushUrl+this.organizationId,jsonData):request.post(this.pushUrl+this.organizationId,{data:jsonData,handleAs:'json',headers:{'Content-Type':'application/json'},timeout:1e4}).then(function(data){data.Enabled||(context.started=!1,context.enabled=!1)})}});return consumptionAnalytics}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var i18n=__webpack_require__(19),OsPlatform=__webpack_require__(21),Hls=__webpack_require__(40),Const=__webpack_require__(43),MediaElement=__webpack_require__(25),__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;const{toPlainObject}=__webpack_require__(7);var isCloudStreaming=!1,ltUpdateIntervall=null,switchingSeekTime=null,vid=Math.floor(10001*Math.random());__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(13),__webpack_require__(2),__webpack_require__(22),__webpack_require__(74),__webpack_require__(156),__webpack_require__(140),__webpack_require__(18),__webpack_require__(64),__webpack_require__(9)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,Evented,lang,PlaybackState,Html5Player,SidebandMetadata,ASyncCuePointDispatcher,topic,StreamingMode,XhrProvider){var html5Live=declare([Evented],{statusMap:{abort:{status:'connecting',code:'LIVE_CONNECTING'},canPlay:{status:'buffering',code:'LIVE_BUFFERING'},canPlayThrough:{status:'onAir',code:'LIVE_PLAYING'},dataLoading:{status:'buffering',code:'LIVE_BUFFERING'},emptied:{status:'connecting',code:'LIVE_CONNECTING'},ended:{status:'disconnected',code:'LIVE_STOP'},error:{status:'streamUnavailable',code:'LIVE_FAILED'},geoblocked:{status:'streamGeoBlocked',code:'HLS_STREAM_GEOBLOCKED'},loadStart:{status:'connecting',code:'LIVE_CONNECTING'},pause:{status:'paused',code:'LIVE_PAUSE'},play:{status:'onAir',code:'LIVE_PLAYING'},progress:{status:'onAir',code:'LIVE_PLAYING'},reconnecting:{status:'reconnecting',code:'LIVE_RECONNECTING'},stalled:{status:'disconnected',code:'LIVE_STOP'},stop:{status:'disconnected',code:'LIVE_STOP'},suspend:{status:'connecting',code:'LIVE_CONNECTING'},waiting:{status:'buffering',code:'LIVE_BUFFERING'},playbackNotAllowed:{status:'playbackNotAllowed',code:'PLAY_NOT_ALLOWED'}},constructor:function(node,cfg){void 0,this.playerNode=node,this.cfg=cfg,this.html5Node=null,this.audioNode=null,this.connections=null,this._playbackStatusCallback=null,this._timeshiftInfoCallback-null,this._cuePointCallback=null,this._adBreakCallback=null,this._hlsCuePointCallback=null,this._speechCuePointCallback=null,this._customCuePointCallback=null,this._streamStartCallback=null,this._streamStopCallback=null,this._streamFailedCallback=null,this.isPaused=!1,this.audioEventListenersAttached=!1,this.params=null,this.xhrProv=new XhrProvider},setPlaybackStatusHandler:function(callback){this._playbackStatusCallback=callback},setTimeshiftInfoHandler:function(callback){this._timeshiftInfoCallback=callback},setCuePointHandler:function(callback){this._cuePointCallback=callback},setAdBreakHandler:function(callback){this._adBreakCallback=callback},setHlsCuePointHandler:function(callback){this._hlsCuePointCallback=callback},setSpeechCuePointHandler:function(callback){this._speechCuePointCallback=callback},setCustomCuePointHandler:function(callback){this._customCuePointCallback=callback},setStreamStartHandler:function(callback){this._streamStartCallback=callback},setStreamStopHandler:function(callback){this._streamStopCallback=callback},setStreamFailedHandler:function(callback){this._streamFailedCallback=callback},play:function(params){(params.forceTimeShift||params.isProgram)&&(isCloudStreaming=!0),MediaElement.isStopped()&¶ms&&(this.params=params,void 0,this._liveApiParams=params,this.mount=this._liveApiParams.mount,this.__isSidebandMetadataActivated()?(this.sidebandMetadata&&this.sidebandMetadata.destroy(),this.__activateSidebandMetadata()):this.__isASyncCuePointDispatcherActivated()&&this.__activateAsyncCuePointDispatcher(),void 0,this.__initAudioElement(),Hls.isSupported()&&'iOS'!==OsPlatform.os.family&&(this._liveApiParams.isHLS||this._liveApiParams.isHLSTS)?MediaElement.playAudio(this._liveApiParams.url,!0,!0,this._liveApiParams.timeshiftOffset,this._liveApiParams.timeshiftEnabled):MediaElement.playAudio(this._liveApiParams.url,!1,!0,this._liveApiParams.timeshiftOffset,this._liveApiParams.timeshiftEnabled))},pause:function(){isCloudStreaming||this.cfg.streamWhileMuted?(this.isPaused=!0,this.stopLTInterval(),MediaElement.pause()):(this.isPaused=!1,MediaElement.stop())},stop:function(){MediaElement.stop(),isCloudStreaming=!1},resume:function(){MediaElement.resume()},seekStream:function(seconds){isCloudStreaming?MediaElement.seekStream(seconds):(switchingSeekTime=seconds,topic.publish('streamingModeChange',StreamingMode.CLOUD_STREAMING),isCloudStreaming=!0)},seekLive:function(){this._liveApiParams.forceTimeShift?MediaElement.seekLive():(topic.publish('streamingModeChange',StreamingMode.LIVE_STREAMING),isCloudStreaming=!1)},seekFromLive:function(seconds){isCloudStreaming?MediaElement.seekFromLive(seconds):(switchingSeekTime=seconds,topic.publish('streamingModeChange',StreamingMode.CLOUD_STREAMING),isCloudStreaming=!0)},setVolume:function(volumePercent){0==volumePercent?this.mute():MediaElement.audioNode&&MediaElement.audioNode.muted?this.unMute():MediaElement.setVolume(volumePercent)},mute:function(){!MediaElement.audioNode||MediaElement.audioNode.paused||MediaElement.isStopped()||(isCloudStreaming?(MediaElement.audioNode.muted=!0,this.stopLTInterval()):MediaElement.mute())}
1,unMute:function(params){this.cfg.streamWhileMuted&&MediaElement.audioNode||isCloudStreaming?(MediaElement.audioNode.muted=!1,isCloudStreaming&&MediaElement.audioNode&&!MediaElement.audioNode.paused&&!MediaElement.isStopped()&&this.startLTInterval()):MediaElement.isStopped()&&(MediaElement.unMute(),this.play(params))},startLTInterval:function(){if(null==ltUpdateIntervall){var dist=null!=this.params.trackingParameters&&this.params.trackingParameters.dist||'triton-web',url=`${this._liveApiParams.listenerTrackingURL}?autoplay=0&hasads=0&sid=${this._liveApiParams.wcmStationId}&ctype=timeshifted&dist=${dist}&cb=${new Date().getTime()}&vid=${vid}`;fetch(url).then(response=>{if(!response.ok)throw new Error(`Request failed with status ${reponse.status}`);return response.text()}).then(data=>{var ltParams=data.split(',');pingUrl=`${this._liveApiParams.listenerTrackingURL}?guid=${ltParams[1]}&cb=${new Date().getTime()}`,fetch(pingUrl,function(){}),ltUpdateIntervall=setInterval(function(){fetch(pingUrl,function(){})},1e3*parseInt(ltParams[0]))}).catch(()=>void 0)}},stopLTInterval:function(){null!=ltUpdateIntervall&&(clearInterval(ltUpdateIntervall),ltUpdateIntervall=null,void 0,fetch(pingUrl,function(){}),pingUrl=null)},__initAudioElement:function(){void 0,MediaElement.cfg=this.cfg,!1==this.audioEventListenersAttached&&(MediaElement.on('destroyAudioElement',this.__destroyAudioElement),MediaElement.on('html5-playback-status',lang.hitch(this,this.__onHTML5PlayerStatus)),MediaElement.on('timeshift-info',lang.hitch(this,this._timeshiftInfoCallback)),this.audioEventListenersAttached=!0)},__destroyAudioElement:function(){void 0,MediaElement.removeAllListeners('html5-playback-status'),MediaElement.removeAllListeners('destroyAudioElement'),this.sidebandMetadata&&this.sidebandMetadata.destroy()},_timeshiftInfoCallback:function(e){null!=this._timeshiftInfoCallback&&this._timeshiftInfoCallback(e)},__onHTML5PlayerStatus:function(e){void 0,e.isReconnect=!!(this.params&&this.params.isReconnect),e.type==PlaybackState.CAN_PLAY_THROUGH&&switchingSeekTime&&isCloudStreaming?(this.seekFromLive(switchingSeekTime),switchingSeekTime=null):e.type==PlaybackState.PLAY?(!this.isPaused&&this.__isSidebandMetadataActivated()&&this.sidebandMetadata?this.sidebandMetadata.init(this._liveApiParams):this.aSyncCuePointDispatcher&&this.aSyncCuePointDispatcher.startCuePointsListener(this.mount),this.isPaused=!1,this._streamStartCallback(),isCloudStreaming&&this._liveApiParams.wcmStationId&&this._liveApiParams.listenerTrackingURL&&this.startLTInterval()):(e.type==PlaybackState.STOP||e.type==PlaybackState.PAUSE&&!this.cfg.streamWhileMuted||e.type==PlaybackState.ERROR||e.type==PlaybackState.ABORT||e.type==PlaybackState.ENDED||e.type==PlaybackState.PLAY_NOT_ALLOWED)&&(this.aSyncCuePointDispatcher&&this.aSyncCuePointDispatcher.stopCuePointsListener(),(e.type==PlaybackState.STOP||e.type==PlaybackState.ERROR||e.type==PlaybackState.ABORT||e.type==PlaybackState.PLAY_NOT_ALLOWED)&&(this.__isSidebandMetadataActivated()&&this.sidebandMetadata&&this.sidebandMetadata.destroy(),this.stopLTInterval(),this._streamStopCallback()),(e.type==PlaybackState.ERROR||e.type==PlaybackState.ENDED||e.type==PlaybackState.GEOBLOCKED)&&(e.message='Possible stream errors could include : <br /> - GeoBlocked <br /> - Timed out <br /> - Unsupported format <br /> - Resource Not Found',e.richText=!0,this._streamFailedCallback(),this.stop()),e.type==PlaybackState.PAUSE&&!isCloudStreaming&&MediaElement.stop()),this.__emitPlaybackStatus(e)},__isSidebandMetadataActivated:function(){return this._liveApiParams!=void 0&&this._liveApiParams.sbmConfig!=void 0&&null!==this._liveApiParams.sbmConfig&&this._liveApiParams.sbmConfig.active&&this._liveApiParams.sbmConfig.info.active},__isASyncCuePointDispatcherActivated:function(){return this._liveApiParams!=void 0&&this._liveApiParams.sbmConfig&&this._liveApiParams.sbmConfig.aSyncCuePointFallback},__onCuePoint:function(e){this._cuePointCallback(e)},__onHlsCuePoint:function(e){this._hlsCuePointCallback(e)},__onSpeechCuePoint:function(e){this._speechCuePointCallback(e)},__onCustomCuePoint:function(e){this._customCuePointCallback(e)},__onAdBreak:function(e){this._adBreakCallback(e)},__activateSidebandMetadata:function(){this.sidebandMetadata||(this.sidebandMetadata=new SidebandMetadata(this.audioNode)),this._liveApiParams.url=this.sidebandMetadata.getStreamConnectionUrl(this._liveApiParams.url),this.sidebandMetadata.setTrackCuePointCallback(lang.hitch(this,this.__onCuePoint)),this.sidebandMetadata.setAdBreakCuePointCallback(lang.hitch(this,this.__onAdBreak)),this.sidebandMetadata.setHlsCuePointCallback(lang.hitch(this,this.__onHlsCuePoint)),this.sidebandMetadata.setSpeechCuePointCallback(lang.hitch(this,this.__onSpeechCuePoint)),this.sidebandMetadata.setCustomCuePointCallback(lang.hitch(this,this.__onCustomCuePoint)),this._liveApiParams.sbmConfig.aSyncCuePointFallback&&this.sidebandMetadata.setErrorCallback(lang.hitch(this,this.__onSidebandMetadataError))},__activateAsyncCuePointDispatcher:function(){this.aSyncCuePointDispatcher==void 0&&(this.aSyncCuePointDispatcher=new ASyncCuePointDispatcher(this.cfg),this.aSyncCuePointDispatcher.setTrackCuePointCallback(lang.hitch(this,this.__onCuePoint)),this.aSyncCuePointDispatcher.setAdBreakCuePointCallback(lang.hitch(this,this.__onAdBreak)))},__onSidebandMetadataError:function(){MediaElement.isStopped()||(!this.aSyncCuePointDispatcher&&this.__activateAsyncCuePointDispatcher(),this.aSyncCuePointDispatcher.startCuePointsListener(this.mount))},__emitPlaybackStatus:function(e){if(null!=this._playbackStatusCallback){var statusMessages=i18n.getLocalization();if(statusMessages==void 0)return;var msg=this.statusMap[e.type];msg&&statusMessages[msg.status]&&this._playbackStatusCallback({status:status
1Messages[msg.status],code:msg.code,message:e.message,isReconnect:e.isReconnect})}}});return html5Live}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module){module.exports=function(data){this.index=null,this.codec=null,this.bitRate=null,this.sampleRate=null,this.codec=null,this.channels=null,function(context,data){context.index=parseInt(data._attr.index._value),context.codec=data._attr.codec._value,context.bitRate=parseInt(data._attr.bitrate._value),context.sampleRate=parseInt(data._attr.samplerate._value),context.codec=data._attr.codec._value,context.channels=parseInt(data._attr.channels._value),context.isMP3=-1!==context.codec.indexOf('mp3'),context.isAAC=-1!==context.codec.indexOf('aac')}(this,data)}},function(module,exports,__webpack_require__){var _=__webpack_require__(7);module.exports=function(streamingConnections){if(this.streamingConnections=streamingConnections,this.totalIteration=1,this.first=!1,this.last=!1,this.streamingConnectionIndex=0,_.isEmpty(this.streamingConnections))throw new Error('ConnectionIterator::constructor At least one connection is needed.');this.reset=function(){this.streamingConnectionIndex=0},this.current=function(){return this.streamingConnections[this.streamingConnectionIndex]},this.next=function(){return this.first=!1,this.streamingConnectionIndex++,this.last=_.last(this.streamingConnections)===this.streamingConnections[this.streamingConnectionIndex],this.current()},this.hasLooped=function(){return this.last},this.isLastConnectionByMount=function(){var groupByMount=_.groupBy(this.streamingConnections,'mount'),totalLoop=groupByMount[this.current().mount].length;return this.totalIteration===totalLoop?(this.totalIteration=1,!0):(this.totalIteration++,!1)},this.reset()}},function(module,exports,__webpack_require__){var _=__webpack_require__(7),Platform=__webpack_require__(14),LiveStreamRepository=__webpack_require__(146),MountPoint=__webpack_require__(150),AudioPriority=__webpack_require__(75),ArrayHelper=__webpack_require__(23),LocationHelper=__webpack_require__(24),PROTOCOL=LocationHelper.getProtocol();module.exports=function(platformId,osPlatform,techType,configHls,configAudioAdaptive,forceHls,forceHlsts,playerServicesRegion){function generateUrls(mountpoints,techType,timeshift,isProgram,programID){return _.flatMap(mountpoints,function(mountpoint){return timeshift&&(mountpoint.transports=mountpoint.transports.filter(transport=>!0==transport.timeshift)),_.flatMap(mountpoint.servers,function(server){return mountpoint.transports.map(function(transport){var extension=getExtension(mountpoint),mimeType=getMimeType(mountpoint);return{url:getUrl(timeshift,server,mountpoint,transport,techType,extension,isProgram,programID),mrHost:new URL(server).hostname,mount:mountpoint.mount,isAudioAdaptive:mountpoint.mediaFormat.isAudioAdaptive,mimeType:mimeType,format:mountpoint.format,uuidEnabled:_.some(mountpoint.metrics.tags,function(m){return'uuid'===m.name}),sendPageUrl:mountpoint.sendPageURL,hasVideo:mountpoint.mediaFormat.hasVideo,type:mountpoint.mediaFormat.type,metadata:mountpoint.metadata,tags:mountpoint.metrics.tags,wcmStationId:mountpoint.metrics.wcmStationId,listenerTrackingURL:mountpoint.metrics.listenerTrackingURL,mountpoint:mountpoint,isHLS:!!transport.transport&&('hls'===transport.transport.toLowerCase()||'hlsrw'===transport.transport.toLowerCase()),isHLSTS:!!transport.transport&&'hlsts'===transport.transport.toLowerCase(),isTimeshift:!!transport.timeshift&&transport.timeshift}})})})}function getUrl(timeshift,server,mountpoint,transport,techType,extension,isProgram,programID){return isProgram?'https://'+new URL(server).hostname+'/'+mountpoint.mount+'/CLOUD/HLS/program/'+programID+'/playlist.m3u8':timeshift?server+'/'
1+mountpoint.mount+(transport.mountSuffix?transport.mountSuffix:''):server+'/'+mountpoint.mount+(transport.mountSuffix?transport.mountSuffix:'')+('html5'===techType.toLowerCase()?extension:'')}function getExtension(mountpoint){return mountpoint.mediaFormat.audioTracks[0].isMP3?'.mp3':simpleAAC(mountpoint)}function simpleAAC(mountpoint){return(!mountpoint.mediaFormat.audioTracks[0].isAAC||mountpoint.isAudioAdaptive||mountpoint.hasHLS()||mountpoint.hasHLSTS())&&(!mountpoint.mediaFormat.audioTracks[0].isAAC||forceHls||forceHlsts||'android'!=osPlatform.os.family.toLowerCase())?'':'.aac'}function getMimeType(mountpoint){var mimeType=null;return mountpoint.hasHLS()||mountpoint.mediaFormat.isAudioAdaptive?mimeType='application/x-mpegURL':mountpoint.mediaFormat.audioTracks[0].isAAC?mimeType='audio/mp4':mountpoint.mediaFormat.audioTracks[0].isMP3&&(mimeType='audio/mpeg;codecs=mp3'),mimeType}this.DEFAULT_TRANSPORTS=['http','hls'],this.TIMESHIFT_TRANSPORT=['hls'],this.mountPointsError=[];var platform=new Platform(platformId),endPoint=playerServicesRegion?PROTOCOL+'//'+playerServicesRegion+'-'+platform.endpoint.liveStream:PROTOCOL+'//'+platform.endpoint.liveStream,self=this;this.getStreamingConnections=function(query,mountTags,excludeUntagged,timeshift){var liveStreamRepository=new LiveStreamRepository(endPoint);return liveStreamRepository.getLiveStreamConfig(query).then(function(provisioningData){var mountpoints=ArrayHelper.toSafeArray(provisioningData.mountpoints.mountpoint).filter(function(mountPoint){return 300<=mountPoint.status['status-code']._text&&self.mountPointsError.push(new MountPoint(mountPoint)),300>mountPoint.status['status-code']._text}).map(function(mountPoint){return new MountPoint(mountPoint)});return mountpoints=AudioPriority.filterMountPoints(mountpoints,osPlatform,techType,mountTags,excludeUntagged,!configHls,!configAudioAdaptive,forceHls,forceHlsts,timeshift),generateUrls(mountpoints,techType,timeshift,query.isProgram,query.programID)})}}},function(module,exports,__webpack_require__){function _requestProvisioningData(endPoint,query){return Q.Promise(function(resolve,reject){var xhrProv=new XhrProvider;xhrProv.request(endPoint,query,{handleAs:'xml',preventCache:!0,query:query,headers:{'X-Requested-With':null,'Content-Type':'text/plain; charset=utf-8'}},function(query,data){query.station?void 0:query.mount&&void 0,resolve(data)},function(query,err){query.station?void 0:query.mount&&void 0,reject(err)})})}function getQuery(params){var query=_.assign({},params);if(void 0==query||null==query)throw new Error('liveStreamAPI::getLiveStreamConfig() A query must be provided.');if('string'==typeof query&&(query={station:query}),'object'!=typeof query)throw new Error('liveStreamAPI::getLiveStreamConfig() A query object must be provided.');if(!query.station&&!query.mount)throw new Error('liveStreamAPI::getLiveStreamConfig(): A query must contain at least a station or mount parameter.');return query.transports&&0!=query.transports.length||(query.transports=DEFAULT_TRANSPORTS),query.transports&&(query.transports=query.transports.join(',')),query}var Q=__webpack_require__(102),_=__webpack_require__(7),XmlParser=__webpack_require__(15),XhrProvider=__webpack_require__(9),DEFAULT_TRANSPORTS=['http','hls'];module.exports=function(endPoint){var self=this;this.configs=[],this._requestProvisioningData=_requestProvisioningData,this.getConfig=function(query){var config;return query.station?config=this.configs[query.station]:delete query.station,query.mount?config=this.configs[query.mount+'_MOUNT']:delete query.mount,config},this.getLiveStreamConfig=function(params){return Q.Promise(function(resolve,reject){try{var query=getQuery(params)}catch(err){reject(err)}var config=self.getConfig(query);config&&config.lastRefreshTime+6e4>=new Date().getTime()?resolve(config):(query.version='1.10',self._requestProvisioningData(endPoint,query).then(function(data){var dataToJson=XmlParser.xmlToJson(data);query.station?(self.configs[query.station]=dataToJson,self.configs[query.station].lastRefreshTime=new Date().getTime()):query.mount&&(self.configs[query.mount+'_MOUNT']=dataToJson,self.configs[query.mount+'_MOUNT'].lastRefreshTime=new Date().getTime()),resolve(dataToJson)}))})}}},function(module,exports,__webpack_require__){var _=__webpack_require__(7),ArrayHelper=__webpack_require__(23),AudioTrack=__webpack_require__(143),VideoTrack=__webpack_require__(155),Const=__webpack_require__(43);module.exports=function(data){this.container=null,this.cuePoints=null,this.trackScheme=null,this.audioTracks=null,this.videoTracks=null,this.hasAudio=null,this.hasVideo=null,this.type=null,this.isAudioAdaptive=null,function(context,data){context.container=data._attr.container._value,context.cuePoints=data._attr.cuepoints._value,context.trackScheme=data._attr.trackScheme._value;var audioTracksData=ArrayHelper.toSafeArray(data.audio);context.audioTracks=audioTracksData.map(function(audioTrack){return new AudioTrack(audioTrack)});var videoTracksData=ArrayHelper.toSafeArray(data.video);context.videoTracks=videoTracksData.map(function(videoTrack){return new VideoTrack(videoTrack)}
1),context.isAudioAdaptive=context.trackScheme==='audio-adaptive',context.hasAudio=!_.isEmpty(context.audioTracks),context.hasVideo=!_.isEmpty(context.videoTracks),context.type=context.hasVideo?Const.VIDEO:Const.AUDIO}(this,data)}},function(module){module.exports=function(data){this.shoutcastV1=null,this.shoutcastV2=null,this.sseSideband=null,function(context,data){context.shoutcastV1=data['shoutcast-v1']?{active:data['shoutcast-v1']._attr.enabled._value,mountSuffix:data['shoutcast-v1']._attr.mountSuffix._value}:null,context.shoutcastV2=data['shoutcast-v2']?{active:data['shoutcast-v2']._attr.enabled._value,mountSuffix:data['shoutcast-v2']._attr.mountSuffix._value}:null,context.sseSideband=data['sse-sideband']?{active:data['sse-sideband']._attr.enabled._value,streamSuffix:data['sse-sideband']._attr.streamSuffix._value,metadataSuffix:data['sse-sideband']._attr.metadataSuffix._value}:null}(this,data)}},function(module,exports,__webpack_require__){var ArrayHelper=__webpack_require__(23),Tag=__webpack_require__(76);module.exports=function(data){this.wcmStationId=null,this.listenerTrackingURL=null,this.tags=!1,function(context,data){context.wcmStationId=data['listener-tracking']?data['listener-tracking']._attr['wcm-station-id']._value:0,context.listenerTrackingURL=data['listener-tracking']?data['listener-tracking']._attr.url._value:'',context.tags=ArrayHelper.toSafeArray(data.tag).map(function(metricTag){return new Tag(metricTag)})}(this,data)}},function(module,exports,__webpack_require__){var _=__webpack_require__(7),ArrayHelper=__webpack_require__(23),Status=__webpack_require__(153),Metrics=__webpack_require__(149),Tag=__webpack_require__(76),Transport=__webpack_require__(154),Metadata=__webpack_require__(148),Servers=__webpack_require__(152),MediaFormat=__webpack_require__(147),MountPointHelper=__webpack_require__(151);module.exports=function(mountPointData){MountPointHelper.call(this),function(context,data){context.mount=data.mount._text||null,context.status=new Status(data.status),300>data.status['status-code']._text&&(context.tags=!data._attr||data._attr.tags||''===data._attr.tags._value?[]:data._attr.tags._value.split(',').map(function(tag){return new Tag(tag)}),context.transports=ArrayHelper.toSafeArray(data.transports.transport).map(function(transport){return new Transport(transport)}),context.metadata=new Metadata(data.metadata),context.servers=new Servers(data.servers).servers,context.mediaFormat=new MediaFormat(data['media-format']),context.metrics=!data.metrics||_.isEmpty(data.metrics.tag)?[]:new Metrics(data.metrics),context.format=data.format._text||null,context.bitRate=_.toSafeInteger(data.bitrate._text),context.authentication=!!data.authentication&&!!parseInt(data.authentication._text),context.timeout=data.timeout?_.toSafeInteger(data.timeout._text):0,context.sendPageURL=!!data['send-page-url']&&!!parseInt(data['send-page-url']._text),context.isAvailable=!context.status.isError&&!_.isEmpty(context.servers))}(this,mountPointData),this.hasTag=function(tag){return _.some(this.tags,function(item){return item.name==tag})},this.hasMetric=function(metric){return _.some(this.metrics,function(item){return item.name===metric})}}},function(module,exports,__webpack_require__){var _=__webpack_require__(7);module.exports=function(){this.hasHLS=function(MountPoint){return MountPoint||(MountPoint=this),_.some(MountPoint.transports,function(transport){return'hls'===transport.transport})},this.hasHLSTS=function(MountPoint){return MountPoint||(MountPoint=this),_.some(MountPoint.transports,function(transport){return'hlsts'===transport.transport})},this.isTimeshiftEnabled=function(MountPoint){return MountPoint||(MountPoint=this),_.some(MountPoint.transports,function(transport){return!0===transport.timeshift})}}},function(module,exports,__webpack_require__){var _=__webpack_require__(7),ArrayHelper=__webpack_require__(23);module.exports=function(data){this.servers=null,function(context,data){context.servers=_.flatMap(ArrayHelper.toSafeArray(data.server),function(server){var ip=server.ip._text;return ArrayHelper.toSafeArray(server.ports.port).map(function(port){var type=port._attr.type._value,portNumber=port._text;return type+'://'+ip+':'+portNumber})})}(this,data)}},function(module){module.exports=function(data){this.statusCode=null,this.message=null,this.isError=!1,function(context,data){context.statusCode=data['status-code']?data['status-code']._text:-1,context.message=data['status-message']?data['status-message']._text:null,context.
1isError=300<=context.statusCode||-1===context.statusCode}(this,data)}},function(module){module.exports=function(data){this.mountSuffix=null,this.transport=null,function(context,data){context.mountSuffix=data._attr?data._attr.mountSuffix._value:null,context.transport=data._text||null,context.timeshift=!!(data._attr&&data._attr.timeshift)&&data._attr.timeshift._value}(this,data)}},function(module){module.exports=function(data){this.index=null,this.codec=null,this.bitRate=null,this.frameRate=null,this.width=null,this.height=null,this.aspect=null,this.keyframeInterval=null,function(context,data){context.index=parseInt(data._attr.index._value),context.codec=data._attr.codec._value,context.bitRate=parseInt(data._attr.bitrate._value),context.frameRate=parseFloat(data._attr.framerate._value),context.width=parseInt(data._attr.width._value),context.height=parseInt(data._attr.height._value),context.aspect=parseFloat(data._attr.aspect._value),context.keyframeInterval=parseInt(data._attr['keyframe-interval']._value)}(this,data)}},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3),__webpack_require__(2),__webpack_require__(157)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on,lang,SidebandMetadataConnector){var sidebandMetadata=declare([],{constructor:function(mediaNode){void 0,this._sessionId=null,this._mediaNode=mediaNode,this._streamTimer=null,this._timer=0,this._connectionTime=0,this._onPlayHandler=lang.hitch(this,this.__onTimeUpdate)},init:function(params){this._connectionTime=new Date().getTime(),this._streamTimer=setInterval(this._onPlayHandler,250),this.sidebandMetadataConnector=new SidebandMetadataConnector,this.sidebandMetadataConnector.setSidebandMetadataFallbackCallback(lang.hitch(this,this.__onSidebandMetadataFallback)),this.sidebandMetadataConnector.connect(this.__getMetadataConnectionUrl(params.url,params.mount,params.sbmConfig))},destroy:function(){this.onTimeUpdateListener&&this.onTimeUpdateListener.remove(),clearInterval(this._streamTimer),this._timer=0,this._connectionTime=0,this.sidebandMetadataConnector&&this.sidebandMetadataConnector.destroy(),delete this.sidebandMetadataConnector},getStreamConnectionUrl:function(url){return url+(-1==url.indexOf('?')?'?':'&')+'sbmid='+this.__generateSessionId()},setTrackCuePointCallback:function(callback){this._trackCuePointCallback=callback},setAdBreakCuePointCallback:function(callback){this._adBreakCuePointCallback=callback},setHlsCuePointCallback:function(callback){this._hlsCuePointCallback=callback},setSpeechCuePointCallback:function(callback){this._speechCuePointCallback=callback},setCustomCuePointCallback:function(callback){this._customCuePointCallback=callback},setErrorCallback:function(callback){this._errorCallback=callback},__getMetadataConnectionUrl:function(url,mount,sbmConfig){return url&&mount&&null!==sbmConfig&&null!==sbmConfig.info?url.split('/')[0]+'//'+url.split('/')[2]+'/'+mount+sbmConfig.info.metadataSuffix+'?sbmid='+this._sessionId:null},__generateSessionId:function(){var d=new Date().getTime();return this._sessionId='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){var r=0|(d+16*Math.random())%16;return d=Math.floor(d/16),('x'==c?r:8|7&r).toString(16)}),this._sessionId},__onSidebandMetadataFallback:function(){void 0,this.destroy(),this._errorCallback({})},__onTimeUpdate:function(){this._timer=new Date().getTime()-this._connectionTime;this.isStopped||this.isPaused||this.sidebandMetadataConnector&&this.sidebandMetadataConnector.getCurrentCuePoint()&&this._timer>=this.sidebandMetadataConnector.getCurrentCuePoint().timestamp&&('track'===this.sidebandMetadataConnector.getCurrentCuePoint().type?this._trackCuePointCallback({cuePoint:this.sidebandMetadataConnector.getCurrentCuePoint()}):'ad'===this.sidebandMetadataConnector.getCurrentCuePoint().type?this._adBreakCuePointCallback({cuePoint:this.sidebandMetadataConnector.getCurrentCuePoint()}):'hls'===this.sidebandMetadataConnector.getCurrentCuePoint().type?this._hlsCuePointCallback({cuePoint:this.sidebandMetadataConnector.getCurrentCuePoint()}):'speech'===this.sidebandMetadataConnector.getCurrentCuePoint().type?this._speechCuePointCallback({cuePoint:this.sidebandMetadataConnector.getCurrentCuePoint()}):'custom'===this.sidebandMetadataConnector.getCurrentCuePoint().type&&this._customCuePointCallback({cuePoint:this.sidebandMetadataConnector.getCurrentCuePoint()}),this.sidebandMetadataConnector.shiftCuePointQueue())}});return sidebandMetadata}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(3),__webpack_require__(6),__webpack_require__(2),__webpack_require__(42),__webpack_require__(33),__webpack_require__(41)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,on,array,lang,TrackCuePoint,BreakCuePoint,HlsCuePoint){var sidebandMetadataConnector=declare([],{SUPPORTED_EVENTS:['onMetaData','onCuePoint','onCuePointPreview','onCuePointPreviewExpired'],MAX_BACKOFF_RETRY:3,cuePointMap:{timestamp:'timestamp',type:'name',cue_title:TrackCuePoint.CUE_TITLE,track_artist_name:TrackCuePoint.ARTIST_NAME,track_album_name:TrackCuePoint.ALBUM_NAME,program_id:TrackCuePoint.PROGRAM_ID,cue_time_duration:TrackCuePoint.CUE_TIME_DURATION,cue_time_start:TrackCuePoint.CUE_TIME_START,track_id:TrackCuePoint.TRACK_ID,track_nowplaying_url:TrackCuePoint.NOW_PLAYING_URL,track_cover_url:TrackCuePoint.TRACK_COVER_URL,ad_id:BreakCuePoint.AD_ID,ad_type:BreakCuePoint.AD_TYPE,cue_title:BreakCuePoint.CUE_TITLE,cue_time_duration:BreakCuePoint.CUE_TIME_DURATION,ad_url:BreakCuePoint.AD_URL,ad_vast_url:BreakCuePoint.AD_VAST_URL,ad_vast:BreakCuePoint.AD_VAST,hls_track_id:HlsCuePoint.HLS_TRACK_ID,hls_segment_id:HlsCuePoint.HLS_SEGMENT_ID},constructor:function(){void 0,this._eventSource=null,this._eventQueue=[],this._currentSbmUrl=null,this._backOffRetry=0,this.__onMessageHandler=lang.hitch(this,this.__onMessage),this.__onOpenHandler=lang.hitch(this,this.__onOpen),this.__onErrorHandler=lang.hitch(this,this.__onError)},connect:function(url){void 0,this._currentSbmUrl=url,this.__subscribe(url),this.__resetBackOff()},destroy:function(){void 0,this.__unlisten(),this.__close()},getCurrentCuePoint:function(){return 0<this._eventQueue.length?this._eventQueue[0]:null},shiftCuePointQueue:function(){this._eventQueue.length&&this._eventQueue.shift()},setSidebandMetadataFallbackCallback:function(callback){this._sidebandMetadataFallbackCallback=callback},__subscribe:function(url){if(null!=this._eventSource&&(this._eventSource.close(),this._eventSource=null),'undefined'!=typeof EventSource)this._eventSource=new EventSource(url);else return;this.__listen()},__listen:function(){void 0,this._messageListener=on(this._eventSource,'message',this.__onMessageHandler),this._openListener=on(this._eventSource,'open',this.__onOpenHandler),this._errorListener=on(this._eventSource,'error',this.__onErrorHandler)},__unlisten:function(){void 0,this._messageListener&&this._messageListener.remove(),this._openListener&&this._openListener.remove(),this._errorListener&&this._errorListener.remove()},__close:function(){void 0,this._currentSbmUrl=null,null!=this._eventSource&&(this._eventSource.close(),this._eventSource=null)},__onMessage:function(e){void 0,void 0;var message=JSON.parse(e.data);if(void 0==message.type||this.__isSupportedEvent(message)){var cuePoint={};switch(message.type){case'onMetaData':this.__onMetadata(message);break;case'onCuePoint':cuePoint=this.__onCuePoint(message);break;case'onCuePointPreview':cuePoint=this.__onCuePointPreview(message);break;case'onCuePointPreviewExpired':cuePoint=this.__onCuePointPreviewExpired(message);break;default:}this._eventQueue.push(cuePoint)}},__onCuePoint:function(message){var cuePoint={parameters:message.parameters,timestamp:message.timestamp,type:message.name};for(var key in message.parameters)this.cuePointMap[key]&&(cuePoint[this.cuePointMap[key]]=message.parameters[key]);
1return'ad'==cuePoint.type&&(cuePoint.isVastInStream=!!(void 0!=cuePoint[BreakCuePoint.AD_VAST_URL]&&''!=cuePoint[BreakCuePoint.AD_VAST_URL]||cuePoint[BreakCuePoint.AD_VAST]&&''!=cuePoint[BreakCuePoint.AD_VAST])),cuePoint},__onMetadata:function(){},__onCuePointPreview:function(){},__onCuePointPreviewExpired:function(){},__onOpen:function(){void 0,this.__resetBackOff()},__onError:function(){void 0,void 0,this._backOffRetry==this.MAX_BACKOFF_RETRY?this._sidebandMetadataFallbackCallback():this.__reconnect()},__isSupportedEvent:function(event){return-1!=array.indexOf(this.SUPPORTED_EVENTS,event.type)},__reconnect:function(){this._backOffRetry++,null!=this._currentSbmUrl&&this.__subscribe(this._currentSbmUrl),void 0},__resetBackOff:function(){void 0,this._backOffRetry=0}});return sidebandMetadataConnector}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(2),__webpack_require__(9),__webpack_require__(35),__webpack_require__(6),__webpack_require__(77),__webpack_require__(78),__webpack_require__(3)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,lang,XhrProvider,Inpe,array,Album,Picture,on){var artist=declare([Inpe],{constructor:function(){void 0,this.artistData=null,this.inherited(arguments)},getName:function(){return null==this.artistData?this.data.name:this.artistData.name},getBiography:function(){return this.artistData.biography},getBirthDate:function(){return this.artistData.beginDate},getEndDate:function(){return this.artistData.endDate},getBeginPlace:function(){return this.artistData.beginPlace},getEndPlace:function(){return this.artistData.endPlace},getIsGroup:function(){return this.artistData.isGroup},getCountry:function(){return this.artistData.country},getGenres:function(){for(var genres=[],i=0;i<this.artistData.genres.length;i++)genres.push(this.artistData.genres[i].name);return genres},getSimilar:function(){return this.artistData.similars},getMembers:function(){return this.artistData.members},getWebsite:function(){return this.artistData.website},getTwitterUsername:function(){return this.artistData.twitter},getFacebookUrl:function(){return this.artistData.facebook},getAlbums:function(){if(null==this.albums){this.albums=[];var album;array.forEach(this.artistData.albums,function(item){album=new Album(item,this.platformId),this.albums.push(album)},this)}return this.albums},getAlbumById:function(albumId){var itemIndex=-1;return array.forEach(this.getAlbums(),function(item,index){item.id==albumId&&(itemIndex=index)},this),-1<itemIndex?this.getAlbums()[itemIndex]:null},getPictures:function(){if(null==this.pictures){this.pictures=[];var picture;array.forEach(this.artistData.pictures,function(item){item.artistId=this.id,picture=new Picture(item,this.platformId),this.pictures.push(picture)},this)}return this.pictures},getPictureById:function(pictureId){var itemIndex=-1;return array.forEach(this.getPictures(),function(item,index){item.id==pictureId&&(itemIndex=index)},this),-1<itemIndex?this.getPictures()[itemIndex]:null},fetchData:function(isDynamicCall){if(isDynamicCall=void 0!=isDynamicCall&&isDynamicCall,isDynamicCall&&(this.url=this.getDynamicArtistUrl(this.id)),!1==this.alreadyFetched){var xhrProv=new XhrProvider;xhrProv.request(this.url,{isDynamicCall:isDynamicCall},this.getRequestArgs(),lang.hitch(this,this._onLoadComplete),lang.hitch(this,this._onLoadError))}else this.notify('artist-complete',{artistId:this.id})},fetchAlbumByIds:function(albumIds){void 0,'string'==typeof albumIds&&(albumIds=[albumIds]),this.albumsQueue=lang.clone(albumIds);for(var i=0,album;i<albumIds.length;i++)album=this.getAlbumById(albumIds[i]),album.successCallback&&album.successCallback.remove(),album.errorCallback&&album.errorCallback.remove(),album.successCallback=on(album,'album-complete',lang.hitch(this,this._onAlbumComplete)),album.errorCallback=on(album,'album-error',lang.hitch(this,this._onAlbumComplete)),album.fetchData()},fetchPictureByIds:function(pictureIds){void 0,'string'==typeof pictureIds&&(pictureIds=[pictureIds]),this.picturesQueue=lang.clone(pictureIds);for(var i=0,picture;i<pictureIds.length;i++)picture=this.getPictureById(pictureIds[i]),picture.successCallback&&picture.successCallback.remove(),picture.errorCallback&&picture.errorCallback.remove(),picture.successCallback=on(picture,'picture-complete',lang.hitch(this,this._onPictureComplete)),picture.errorCallback=on(picture,'picture-error',lang.hitch(this,this._onPictureComplete)),picture.fetchData()},_onLoadError:function(requestData){void 0,!1==requestData.isDynamicCall?this.fetchData(!0):this.notify('artist-error',{artistId:this.id})},_onLoadComplete:function(requestData,data){this.artistData=data.artist,this.alreadyFetched=!0,this.notify('artist-complete',{artistId:this.id})},_onAlbumComplete:function(requestData){void 0,this._removeAlbumFromQueue(requestData.albumId),0==this.albumsQueue.length&&this.notify('album-complete',this.albums)},_removeAlbumFromQueue:function(albumId){var spliceStartIndex=-1;array.forEach(this.albumsQueue,function(itemId,index){itemId==albumId&&(spliceStartIndex=index)},this),-1<spliceStartIndex&&this.albumsQueue.splice(spliceStartIndex,1)},_onPictureComplete:function(requestData){void 0,this._removePictureFromQueue(requestData.pictureId),0==this.picturesQueue.length&&this.notify('picture-complete',this.pictures)},_removePictureFromQueue:function(pictureId){var spliceStartIndex=-1;array.forEach(this.picturesQueue,function(itemId,index){itemId==pictureId&&(spliceStartIndex=index)},this),-1<spliceStartIndex&&this.picturesQueue.splice(spliceStartIndex,1)}});return artist}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__(1),__webpack_require__(79),__webpack_require__(158),__webpack_require__(77)],__WEBPACK_AMD_DEFINE_RESULT__=function(declare,Track,Artist,Album){var song=declare([],{constructor:function(data,npeId,platformId){void 0,void 0,this.songData=data,this.npeId=npeId,this.platformId=platformId,this.trackInstance=null,this.albumInstance=null,this.artistInstance=null,this.inherited(arguments)},track:function(){return void 0==this.songData.track?null:(null==this.trackInstance&&(this.trackInstance=new Track(this.songData.track,this.platformId)),this.trackInstance)},artist:function(){return void 0==this.songData.artists?null:(null==this.artistInstance&&(this.artistInstance=new Artist(this.songData.artists[0],this.platformId)),this.artistInstance)},album:function(){return void 0==this.songData.album?null:(null==this.albumInstance&&(this.albumInstance=new Album(this.songData.album,this.platformId)),this.albumInstance)}});return song}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),!(__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}])}); 2//# sourceMappingURL=td-sdk.min.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.