KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.4.58 (Win64) OpenSSL/3.1.3 PHP/8.2.12
System : Windows NT SERVER-PC 10.0 build 26200 (Windows 11) AMD64
User : ServerPC ( 0)
PHP Version : 8.2.12
Disable Function : NONE
Directory :  C:/Users/ServerPC/AppData/Roaming/Emby-Server/system/dashboard-ui/modules/hlsjs/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : C:/Users/ServerPC/AppData/Roaming/Emby-Server/system/dashboard-ui/modules/hlsjs/hls.js
define(["exports"],function(_exports){function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _createForOfIteratorHelperLoose(r,e){var o,t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=function(r,a){{var t;if(r)return"string"==typeof r?_arrayLikeToArray(r,a):"Map"===(t="Object"===(t={}.toString.call(r).slice(8,-1))&&r.constructor?r.constructor.name:t)||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r))||e)return t&&(r=t),o=0,function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}};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 _extends(){return(_extends=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var r,t=arguments[e];for(r in t)!{}.hasOwnProperty.call(t,r)||(n[r]=t[r])}return n}).apply(null,arguments)}function _getPrototypeOf(t){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function _inheritsLoose(t,o){t.prototype=Object.create(o.prototype),_setPrototypeOf(t.prototype.constructor=t,o)}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function(){return!!t})()}function ownKeys(e,r){var o,t=Object.keys(e);return Object.getOwnPropertySymbols&&(o=Object.getOwnPropertySymbols(e),r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)),t}function _objectSpread2(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){!function(e,r,t){(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t}(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 _setPrototypeOf(t,e){return(_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function _toPropertyKey(t){t=function(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0===e)return("string"===r?String:Number)(t);if("object"!=typeof(e=e.call(t,r||"default")))return e;throw new TypeError("@@toPrimitive must return a primitive value.")}(t,"string");return"symbol"==typeof t?t:t+""}function _wrapNativeSuper(t){var r="function"==typeof Map?new Map:void 0;return(_wrapNativeSuper=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(n){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,Wrapper)}function Wrapper(){return function(t,e,r){var o;return _isNativeReflectConstruct()?Reflect.construct.apply(null,arguments):((o=[null]).push.apply(o,e),o=new(t.bind.apply(t,o)),r&&_setPrototypeOf(o,r.prototype),o)}(t,arguments,_getPrototypeOf(this).constructor)}return Wrapper.prototype=Object.create(t.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(Wrapper,t)})(t)}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var eventemitter3={exports:{}};!function(module){var has=Object.prototype.hasOwnProperty,prefix="~";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");fn=new EE(fn,context||emitter,once),context=prefix?prefix+event:event;return emitter._events[context]?emitter._events[context].fn?emitter._events[context]=[emitter._events[context],fn]:emitter._events[context].push(fn):(emitter._events[context]=fn,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}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(prefix=!1)),EventEmitter.prototype.eventNames=function(){var events,name,names=[];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 event=prefix?prefix+event:event,handlers=this._events[event];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++)ee[i]=handlers[i].fn;return ee},EventEmitter.prototype.listenerCount=function(event){event=prefix?prefix+event:event,event=this._events[event];return event?event.fn?1:event.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 args,listeners=this._events[evt],len=arguments.length;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=new Array(len-1);i<len;i++)args[i-1]=arguments[i];listeners.fn.apply(listeners.context,args)}else for(var j,length=listeners.length,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=new 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){event=prefix?prefix+event:event;if(this._events[event])if(fn){var listeners=this._events[event];if(listeners.fn)listeners.fn!==fn||once&&!listeners.once||context&&listeners.context!==context||clearEvent(this,event);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[event]=1===events.length?events[0]:events:clearEvent(this,event)}}else clearEvent(this,event);return this},EventEmitter.prototype.removeAllListeners=function(event){return event?(event=prefix?prefix+event:event,this._events[event]&&clearEvent(this,event)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=prefix,module.exports=EventEmitter.EventEmitter=EventEmitter}(eventemitter3);function Logger(label,logger){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0,label="["+label+"]:",this.trace=noop,this.debug=logger.debug.bind(null,label),this.log=logger.log.bind(null,label),this.warn=logger.warn.bind(null,label),this.info=logger.info.bind(null,label),this.error=logger.error.bind(null,label)}function noop(){}var URL_REGEX,FIRST_SEGMENT_REGEX,SLASH_DOT_REGEX,SLASH_DOT_DOT_REGEX,URLToolkit,EventEmitter=getDefaultExportFromCjs(eventemitter3.exports),urlToolkitExports=(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())){if(!opts.alwaysNormalize)return baseURL;var basePartsForNormalise=URLToolkit.parseURL(baseURL);if(basePartsForNormalise)return basePartsForNormalise.path=URLToolkit.normalizePath(basePartsForNormalise.path),URLToolkit.buildURLFromParts(basePartsForNormalise);throw new Error("Error trying to parse base URL.")}basePartsForNormalise=URLToolkit.parseURL(relativeURL);if(!basePartsForNormalise)throw new Error("Error trying to parse relative URL.");if(basePartsForNormalise.scheme)return opts.alwaysNormalize?(basePartsForNormalise.path=URLToolkit.normalizePath(basePartsForNormalise.path),URLToolkit.buildURLFromParts(basePartsForNormalise)):relativeURL;relativeURL=URLToolkit.parseURL(baseURL);if(!relativeURL)throw new Error("Error trying to parse base URL.");!relativeURL.netLoc&&relativeURL.path&&"/"!==relativeURL.path[0]&&(baseURL=FIRST_SEGMENT_REGEX.exec(relativeURL.path),relativeURL.netLoc=baseURL[1],relativeURL.path=baseURL[2]),relativeURL.netLoc&&!relativeURL.path&&(relativeURL.path="/");var baseURLPath,baseURL={scheme:relativeURL.scheme,netLoc:basePartsForNormalise.netLoc,path:null,params:basePartsForNormalise.params,query:basePartsForNormalise.query,fragment:basePartsForNormalise.fragment};return basePartsForNormalise.netLoc||(baseURL.netLoc=relativeURL.netLoc,"/"!==basePartsForNormalise.path[0]&&(basePartsForNormalise.path?(baseURLPath=(baseURLPath=relativeURL.path).substring(0,baseURLPath.lastIndexOf("/")+1)+basePartsForNormalise.path,baseURL.path=URLToolkit.normalizePath(baseURLPath)):(baseURL.path=relativeURL.path,basePartsForNormalise.params||(baseURL.params=relativeURL.params,basePartsForNormalise.query)||(baseURL.query=relativeURL.query)))),null===baseURL.path&&(baseURL.path=opts.alwaysNormalize?URLToolkit.normalizePath(basePartsForNormalise.path):basePartsForNormalise.path),URLToolkit.buildURLFromParts(baseURL)},parseURL:function(url){url=URL_REGEX.exec(url);return url?{scheme:url[1]||"",netLoc:url[2]||"",path:url[3]||"",params:url[4]||"",query:url[5]||"",fragment:url[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}},URLToolkit),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,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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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_ERROR="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.ASSET_LIST_LOAD_ERROR="assetListLoadError",ErrorDetails.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",ErrorDetails.ASSET_LIST_PARSING_ERROR="assetListParsingError",ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",ErrorDetails.INTERNAL_EXCEPTION="internalException",ErrorDetails.INTERNAL_ABORTED="aborted",ErrorDetails.ATTACH_MEDIA_ERROR="attachMediaError",ErrorDetails.UNKNOWN="unknown",ErrorDetails}({}),Events=function(Events){return Events.MEDIA_ATTACHING="hlsMediaAttaching",Events.MEDIA_ATTACHED="hlsMediaAttached",Events.MEDIA_DETACHING="hlsMediaDetaching",Events.MEDIA_DETACHED="hlsMediaDetached",Events.MEDIA_ENDED="hlsMediaEnded",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.ASSET_LIST_LOADING="hlsAssetListLoading",Events.ASSET_LIST_LOADED="hlsAssetListLoaded",Events.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",Events.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",Events.INTERSTITIAL_STARTED="hlsInterstitialStarted",Events.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",Events.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",Events.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",Events.INTERSTITIAL_ENDED="hlsInterstitialEnded",Events.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",Events.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",Events.EVENT_CUE_ENTER="hlsEventCueEnter",Events}({}),PlaylistContextType_MANIFEST="manifest",PlaylistContextType_LEVEL="level",PlaylistContextType_AUDIO_TRACK="audioTrack",PlaylistContextType_SUBTITLE_TRACK="subtitleTrack",PlaylistLevelType_MAIN="main",PlaylistLevelType_AUDIO="audio",PlaylistLevelType_SUBTITLE="subtitle",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_=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=(durationMs=Math.max(durationMs,this.minDelayMs_))/1e3,numBytes=8*numBytes/durationMs;this.fast_.sample(durationMs,numBytes),this.slow_.sample(durationMs,numBytes)},_proto.sampleTTFB=function(ttfb){var seconds=ttfb/1e3,seconds=Math.sqrt(2)*Math.exp(-Math.pow(seconds,2)/2);this.ttfb_.sample(seconds,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(){},_createClass(EwmaBandWidthEstimator,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),fakeLogger={trace:noop,debug:noop,log:noop,warn:noop,info:noop,error:noop};function createLogger(){return _extends({},fakeLogger)}function getLoggerFn(key,debugConfig,id){return debugConfig[key]?debugConfig[key].bind(debugConfig):function(type,id){var func=self.console[type];return func?func.bind(self.console,(id?"["+id+"] ":"")+"["+type+"] >"):noop}(key,id)}var exportedLogger=createLogger();function enableLogs(debugConfig,context,id){var newLogger=createLogger();if("object"==typeof console&&!0===debugConfig||"object"==typeof debugConfig){var keys=["debug","log","info","warn","error"];keys.forEach(function(key){newLogger[key]=getLoggerFn(key,debugConfig,id)});try{newLogger.log('Debug logs enabled for "'+context+'" in hls.js version 1.6.0-beta.2')}catch(e){return createLogger()}keys.forEach(function(key){exportedLogger[key]=getLoggerFn(key,debugConfig)})}else _extends(exportedLogger,newLogger);return newLogger}var logger=exportedLogger;function getMediaSource(preferManagedMediaSource){if(void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),"undefined"!=typeof self)return(preferManagedMediaSource||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function isCompatibleTrackChange(currentTracks,requiredTracks){var currentTracks=Object.keys(currentTracks),requiredTrackNames=Object.keys(requiredTracks),requiredTracks=currentTracks.length,requiredTrackCount=requiredTrackNames.length;return!requiredTracks||!requiredTrackCount||requiredTracks===requiredTrackCount&&!currentTracks.some(function(name){return-1===requiredTrackNames.indexOf(name)})}var 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}};function 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 preferManagedMediaSource=getMediaSource(preferManagedMediaSource=void 0===preferManagedMediaSource?!0:preferManagedMediaSource);return null!=(preferManagedMediaSource=null==preferManagedMediaSource?void 0:preferManagedMediaSource.isTypeSupported(type+"/mp4;codecs="+codec))&&preferManagedMediaSource}function mimeTypeForCodec(codec,type){return type+"/mp4;codecs="+codec}function videoCodecPreferenceValue(videoCodec){return videoCodec?(videoCodec=videoCodec.substring(0,4),sampleEntryCodesISO.video[videoCodec]):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)}var CODEC_COMPATIBLE_NAMES={};var AUDIO_CODEC_REGEXP=/flac|opus|mp4a\.40\.34/i;function getCodecCompatibleName(codec,preferManagedMediaSource){return void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),codec.replace(AUDIO_CODEC_REGEXP,function(m){return function(lowerCaseCodec,preferManagedMediaSource){if(void 0===preferManagedMediaSource&&(preferManagedMediaSource=!0),CODEC_COMPATIBLE_NAMES[lowerCaseCodec])return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];for(var _getMediaSource,codecsToCheck={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[lowerCaseCodec],i=0;i<codecsToCheck.length;i++){if(isCodecMediaSourceSupported(codecsToCheck[i],"audio",preferManagedMediaSource))return CODEC_COMPATIBLE_NAMES[lowerCaseCodec]=codecsToCheck[i],codecsToCheck[i];if("mp3"===codecsToCheck[i]&&null!=(_getMediaSource=getMediaSource(preferManagedMediaSource))&&_getMediaSource.isTypeSupported("audio/mpeg"))return""}return lowerCaseCodec}(m.toLowerCase(),preferManagedMediaSource)})}function pickMostCompleteCodecName(parsedCodec,levelCodec){if(parsedCodec&&(4<parsedCodec.length||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(parsedCodec)))return parsedCodec;if(levelCodec){var levelCodecs=levelCodec.split(",");if(1<levelCodecs.length){if(parsedCodec)for(var i=levelCodecs.length;i--;)if(levelCodecs[i].substring(0,4)===parsedCodec.substring(0,4))return levelCodecs[i];return levelCodecs[0]}}return levelCodec||parsedCodec}function getM2TSSupportedAudioTypes(preferManagedMediaSource){preferManagedMediaSource=getMediaSource(preferManagedMediaSource)||{isTypeSupported:function(){return!1}};return{mpeg:preferManagedMediaSource.isTypeSupported("audio/mpeg"),mp3:preferManagedMediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:preferManagedMediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')}}var SUPPORTED_INFO_DEFAULT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},SUPPORTED_INFO_CACHE={};function getMediaDecodingInfoPromise(level,audioTracksByGroup,mediaCapabilities){var configurations,baseVideoConfiguration,videoRange,videoCodecs=level.videoCodec,audioCodecs=level.audioCodec;return(videoCodecs||audioCodecs)&&mediaCapabilities?(configurations=[],videoCodecs&&(baseVideoConfiguration={width:level.width,height:level.height,bitrate:Math.ceil(Math.max(.9*level.bitrate,level.averageBitrate)),framerate:level.frameRate||30},"SDR"!==(videoRange=level.videoRange)&&(baseVideoConfiguration.transferFunction=videoRange.toLowerCase()),configurations.push.apply(configurations,videoCodecs.split(",").map(function(videoCodec){return{type:"media-source",video:_objectSpread2(_objectSpread2({},baseVideoConfiguration),{},{contentType:mimeTypeForCodec(function(videoCodec){if(videoCodec.startsWith("av01.")){for(var av1params=videoCodec.split("."),placeholders=["0","111","01","01","01","0"],i=av1params.length;4<i&&i<10;i++)av1params[i]=placeholders[i-4];return av1params.join(".")}return videoCodec}(videoCodec),"video")})}}))),audioCodecs&&level.audioGroups&&level.audioGroups.forEach(function(audioGroupId){var _audioTracksByGroup$g;audioGroupId&&null!=(_audioTracksByGroup$g=audioTracksByGroup.groups[audioGroupId])&&_audioTracksByGroup$g.tracks.forEach(function(audioTrack){var channelsNumber;audioTrack.groupId===audioGroupId&&(audioTrack=audioTrack.channels||"",channelsNumber=parseFloat(audioTrack),isFiniteNumber(channelsNumber))&&2<channelsNumber&&configurations.push.apply(configurations,audioCodecs.split(",").map(function(audioCodec){return{type:"media-source",audio:{contentType:"audio/mp4;codecs="+audioCodec,channels:""+channelsNumber}}}))})}),Promise.all(configurations.map(function(configuration){var decodingInfoKey=function(config){var audio=config.audio,config=config.video,mediaConfig=config||audio;if(mediaConfig){mediaConfig=mediaConfig.contentType.split('"')[1];if(config)return"r"+config.height+"x"+config.width+"f"+Math.ceil(config.framerate)+(config.transferFunction||"sd")+"_"+mediaConfig+"_"+Math.ceil(config.bitrate/1e5);if(audio)return"c"+audio.channels+(audio.spatialRendering?"s":"n")+"_"+mediaConfig}return""}(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}})):Promise.resolve(SUPPORTED_INFO_DEFAULT)}var HdcpLevels=["NONE","TYPE-0","TYPE-1",null];var VideoRangeValues=["SDR","PQ","HLG"];var HlsSkip_No="",HlsSkip_Yes="YES",HlsSkip_v2="v2";function getSkipValue(details){var canSkipUntil=details.canSkipUntil,canSkipDateRanges=details.canSkipDateRanges,details=details.age;return canSkipUntil&&details<canSkipUntil/2?canSkipDateRanges?HlsSkip_v2:HlsSkip_Yes:HlsSkip_No}var 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}return HlsUrlParameters.prototype.addDirectives=function(uri){uri=new self.URL(uri);return void 0!==this.msn&&uri.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&uri.searchParams.set("_HLS_part",this.part.toString()),this.skip&&uri.searchParams.set("_HLS_skip",this.skip),uri.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){var audioGroups;groupId&&("audio"===type?-1===(audioGroups=(audioGroups=this._audioGroups)||(this._audioGroups=[])).indexOf(groupId)&&audioGroups.push(groupId):"text"===type&&-1===(audioGroups=(audioGroups=this._subtitleGroups)||(this._subtitleGroups=[])).indexOf(groupId)&&audioGroups.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(value){}},{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]}}])}();function hasGroup(groups,groupId){return!(!groupId||!groups)&&-1!==groups.indexOf(groupId)}function getVideoSelectionOptions(currentVideoRange,videoPreference){var preferHDR=!1,allowedVideoRanges=[];return currentVideoRange&&(preferHDR="SDR"!==currentVideoRange,allowedVideoRanges=[currentVideoRange]),!videoPreference||(currentVideoRange="SDR"!==(allowedVideoRanges=videoPreference.allowedVideoRanges||VideoRangeValues.slice(0)).join("")&&!videoPreference.videoCodec,preferHDR=void 0!==videoPreference.preferHDR?videoPreference.preferHDR:currentVideoRange&&function(){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}())||(allowedVideoRanges=["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,videoCodecPreference=null==videoPreference?void 0:videoPreference.videoCodec,preferStereo=channelsPreference&&2===parseInt(channelsPreference),hasStereo=!1,hasCurrentVideoRange=!1,minHeight=1/0,minFramerate=1/0,minBitrate=1/0,minIndex=1/0,selectedScore=0,videoRanges=[],audioPreference=getVideoSelectionOptions(currentVideoRange,videoPreference),videoPreference=audioPreference.preferHDR,allowedVideoRanges=audioPreference.allowedVideoRanges,i=codecSets.length;i--;)!function(){var tier=codecTiers[codecSets[i]];hasStereo=hasStereo||0<tier.channels[2],minHeight=Math.min(minHeight,tier.minHeight),minFramerate=Math.min(minFramerate,tier.minFramerate),minBitrate=Math.min(minBitrate,tier.minBitrate),0<allowedVideoRanges.filter(function(range){return 0<tier.videoRanges[range]}).length&&(hasCurrentVideoRange=!0)}();var minHeight=isFiniteNumber(minHeight)?minHeight:0,minFramerate=isFiniteNumber(minFramerate)?minFramerate:0,maxHeight=Math.max(1080,minHeight),maxFramerate=Math.max(30,minFramerate),minBitrate=isFiniteNumber(minBitrate)?minBitrate:currentBw,hasMultipleSets=(currentBw=Math.max(minBitrate,currentBw),hasCurrentVideoRange||(currentVideoRange=void 0),1<codecSets.length);return{codecSet:codecSets.reduce(function(selected,candidate){var candidateTier=codecTiers[candidate];if(candidate===selected)return selected;if(videoRanges=hasCurrentVideoRange?allowedVideoRanges.filter(function(range){return 0<candidateTier.videoRanges[range]}):[],hasMultipleSets){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&&candidate.indexOf(audioCodecPreference.substring(0,4))%5!=0)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;if(candidateTier.minHeight>maxHeight)return logStartCodecCandidateIgnored(candidate,"min resolution of "+candidateTier.minHeight+" > maximum of "+maxHeight),selected;if(candidateTier.minFramerate>maxFramerate)return logStartCodecCandidateIgnored(candidate,"min framerate of "+candidateTier.minFramerate+" > maximum of "+maxFramerate),selected;if(!videoRanges.some(function(range){return 0<candidateTier.videoRanges[range]}))return logStartCodecCandidateIgnored(candidate,"no variants with VIDEO-RANGE of "+JSON.stringify(videoRanges)+" found"),selected;if(videoCodecPreference&&candidate.indexOf(videoCodecPreference.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(candidate,'video codec preference "'+videoCodecPreference+'" not found'),selected;if(candidateTier.maxScore<selectedScore)return logStartCodecCandidateIgnored(candidate,"max score of "+candidateTier.maxScore+" < selected max of "+selectedScore),selected}return selected&&(codecsSetSelectionPreferenceValue(candidate)>=codecsSetSelectionPreferenceValue(selected)||candidateTier.fragmentError>codecTiers[selected].fragmentError)?selected:(minIndex=candidateTier.minIndex,selectedScore=candidateTier.maxScore,candidate)},void 0),videoRanges:videoRanges,preferHDR:videoPreference,minFramerate:minFramerate,minBitrate:minBitrate,minIndex:minIndex}}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],channelsKey=((trackGroup=trackGroup||(audioTracksByGroup.groups[track.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1})).tracks.push(track),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 getBasicSelectionOption(option){return option&&{lang:option.lang,assocLang:option.assocLang,characteristics:option.characteristics,channels:option.channels,audioCodec:option.audioCodec}}function findMatchingOption(option,tracks,matchPredicate){if("attrs"in option){var index=tracks.indexOf(option);if(-1!==index)return index}for(var i=0;i<tracks.length;i++)if(matchesOption(option,tracks[i],matchPredicate))return i;return-1}function matchesOption(option,track,matchPredicate){var arrB,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||function(languageA,languageB){void 0===languageB&&(languageB="--");return languageA.length!==languageB.length?languageA.startsWith(languageB)||languageB.startsWith(languageA):languageA===languageB}(lang,track.lang))&&(void 0===lang||track.assocLang===assocLang)&&(void 0===isDefault||track.default===isDefault)&&(void 0===forced||track.forced===forced)&&(void 0===characteristics||(groupId=characteristics,void 0===(name=track.characteristics)&&(name=""),groupId=groupId.split(","),arrB=name.split(","),groupId.length===arrB.length&&!groupId.some(function(el){return-1===arrB.indexOf(el)})))&&(void 0===matchPredicate||matchPredicate(option,track))}function audioMatchPredicate(option,track){var audioCodec=option.audioCodec,option=option.channels;return!(void 0!==audioCodec&&(track.audioCodec||"").substring(0,4)!==audioCodec.substring(0,4)||void 0!==option&&option!==(track.channels||"2"))}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 useAlternateAudio(audioTrackUrl,hls){return!!audioTrackUrl&&audioTrackUrl!==(null==(audioTrackUrl=hls.levels[hls.loadLevel])?void 0:audioTrackUrl.uri)}var eventemitter3=function(_Logger){function AbrController(_hls){var _this=_Logger.call(this,"abr",_hls.logger)||this;return _this.hls=void 0,_this.lastLevelLoadSec=0,_this.lastLoadedFragLevel=-1,_this.firstSelection=-1,_this._nextAutoLevel=-1,_this.nextAutoLevelKey="",_this.audioTracksByGroup=null,_this.codecTiers=null,_this.timer=-1,_this.fragCurrent=null,_this.partCurrent=null,_this.bitrateTestDelay=0,_this.bwEstimator=void 0,_this._abandonRulesCheck=function(){var _this2=_this,frag=_this2.fragCurrent,part=_this2.partCurrent,_this2=_this2.hls,autoLevelEnabled=_this2.autoLevelEnabled,media=_this2.media;if(frag&&media){var now=performance.now(),stats=(part||frag).stats,duration=(part||frag).duration,now=now-stats.loading.start,minAutoLevel=_this2.minAutoLevel;if(stats.aborted||stats.loaded&&stats.loaded===stats.total||frag.level<=minAutoLevel)_this.clearTimer(),_this._nextAutoLevel=-1;else if(autoLevelEnabled&&!media.paused&&media.playbackRate&&media.readyState){autoLevelEnabled=_this2.mainForwardBufferInfo;if(null!==autoLevelEnabled){var ttfbEstimate=_this.bwEstimator.getEstimateTTFB(),media=Math.abs(media.playbackRate);if(!(now<=Math.max(ttfbEstimate,duration/(2*media)*1e3))){var bufferStarvationDelay=autoLevelEnabled.len/media,autoLevelEnabled=stats.loading.first?stats.loading.first-stats.loading.start:-1,media=stats.loaded&&-1<autoLevelEnabled,bwEstimate=_this.getBwEstimate(),levels=_this2.levels,level=levels[frag.level],level=Math.max(stats.loaded,Math.round(duration*(frag.bitrate||level.averageBitrate)/8)),timeStreaming=media?now-autoLevelEnabled:now,timeStreaming=(timeStreaming<1&&media&&(timeStreaming=Math.min(now,8*stats.loaded/bwEstimate)),media?1e3*stats.loaded/timeStreaming:0),ttfbSeconds=ttfbEstimate/1e3,level=timeStreaming?(level-stats.loaded)/timeStreaming:8*level/bwEstimate+ttfbSeconds;if(!(level<=bufferStarvationDelay)){for(var bwe=timeStreaming?8*timeStreaming:bwEstimate,live=!0===(null==(timeStreaming=_this.hls.latestLevelDetails)?void 0:timeStreaming.live),timeStreaming=_this.hls.config.abrBandWidthUpFactor,fragLevelNextLoadedDelay=Number.POSITIVE_INFINITY,nextLoadLevel=frag.level-1;minAutoLevel<nextLoadLevel;nextLoadLevel--){var levelNextBitrate=levels[nextLoadLevel].maxBitrate,requiresLevelLoad=!levels[nextLoadLevel].details||live;if((fragLevelNextLoadedDelay=_this.getTimeToLoadFrag(ttfbSeconds,bwe,duration*levelNextBitrate,requiresLevelLoad))<Math.min(bufferStarvationDelay,duration+ttfbSeconds))break}level<=fragLevelNextLoadedDelay||10*duration<fragLevelNextLoadedDelay||(media?_this.bwEstimator.sample(now-Math.min(ttfbEstimate,autoLevelEnabled),stats.loaded):_this.bwEstimator.sampleTTFB(now),media=levels[nextLoadLevel].maxBitrate,_this.getBwEstimate()*timeStreaming>media&&_this.resetEstimator(media),-1<(ttfbEstimate=_this.findBestLevel(media,minAutoLevel,nextLoadLevel,0,bufferStarvationDelay,1,1))&&(nextLoadLevel=ttfbEstimate),_this.warn("Fragment "+frag.sn+(part?" part "+part.index:"")+" of level "+frag.level+" is loading too slowly;\n      Fragment duration: "+frag.duration.toFixed(3)+"\n      Time to underbuffer: "+bufferStarvationDelay.toFixed(3)+" s\n      Estimated load time for current fragment: "+level.toFixed(3)+" s\n      Estimated load time for down switch fragment: "+fragLevelNextLoadedDelay.toFixed(3)+" s\n      TTFB estimate: "+(0|autoLevelEnabled)+" 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|media)+" bps"),_this2.nextLoadLevel=_this2.nextAutoLevel=nextLoadLevel,_this.clearTimer(),_this.timer=self.setInterval(function(){var _bufferStarvationDelay;_this.clearTimer(),_this.fragCurrent===frag&&_this.hls.loadLevel===nextLoadLevel&&0<nextLoadLevel&&(_bufferStarvationDelay=_this.getStarvationDelay(),_this.warn("Aborting inflight request "+(0<nextLoadLevel?"and switching down":"")+"\n      Fragment duration: "+frag.duration.toFixed(3)+" s\n      Time to underbuffer: "+_bufferStarvationDelay.toFixed(3)+" s"),frag.abortRequests(),_this.fragCurrent=_this.partCurrent=null,minAutoLevel<nextLoadLevel)&&(_bufferStarvationDelay=_this.findBestLevel(_this.hls.levels[minAutoLevel].bitrate,minAutoLevel,nextLoadLevel,0,_bufferStarvationDelay,1,1),_this.hls.nextLoadLevel=_this.hls.nextAutoLevel=_bufferStarvationDelay=-1===_bufferStarvationDelay?minAutoLevel:_bufferStarvationDelay,_this.resetEstimator(_this.hls.levels[_bufferStarvationDelay].bitrate))},1e3*fragLevelNextLoadedDelay),_this2.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:frag,part:part,stats:stats}))}}}}}},_this.hls=_hls,_this.bwEstimator=_this.initEstimator(),_this.registerListeners(),_this}_inheritsLoose(AbrController,_Logger);var _proto=AbrController.prototype;return _proto.resetEstimator=function(abrEwmaDefaultEstimate){abrEwmaDefaultEstimate&&(this.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)},_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(event,data){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;this.ignoreFragment(frag)||(frag.bitrateTest||(this.fragCurrent=frag,this.partCurrent=null!=(frag=data.part)?frag:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},_proto.onLevelSwitching=function(event,data){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 ttfbEstimate,frag=data.frag,fragCurrent=this.fragCurrent,part=this.partCurrent;frag&&fragCurrent&&frag.sn===fragCurrent.sn&&frag.level===fragCurrent.level&&(part=performance.now()-(fragCurrent=(part||frag).stats).loading.start,frag=fragCurrent.loading.first?fragCurrent.loading.first-fragCurrent.loading.start:-1,fragCurrent.loaded&&-1<frag?(ttfbEstimate=this.bwEstimator.getEstimateTTFB(),this.bwEstimator.sample(part-Math.min(ttfbEstimate,frag),fragCurrent.loaded)):this.bwEstimator.sampleTTFB(part))}},_proto.getTimeToLoadFrag=function(timeToFirstByteSec,bandwidth,fragSizeBits,isSwitch){return timeToFirstByteSec+fragSizeBits/bandwidth+(isSwitch?this.lastLevelLoadSec:0)},_proto.onLevelLoaded=function(event,data){var config=this.hls.config,loading=data.stats.loading,loading=loading.end-loading.start;isFiniteNumber(loading)&&(this.lastLevelLoadSec=loading/1e3),data.details.live?this.bwEstimator.update(config.abrEwmaSlowLive,config.abrEwmaFastLive):this.bwEstimator.update(config.abrEwmaSlowVoD,config.abrEwmaFastVoD)},_proto.onFragLoaded=function(event,_ref){var loadedBytes,duration,level,frag=_ref.frag,_ref=_ref.part,stats=(_ref||frag).stats;frag.type===PlaylistLevelType_MAIN&&this.bwEstimator.sampleTTFB(stats.loading.first-stats.loading.start),this.ignoreFragment(frag)||(this.clearTimer(),frag.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate&&(duration=(_ref||frag).duration,loadedBytes=((level=this.hls.levels[frag.level]).loaded?level.loaded.bytes:0)+stats.loaded,duration=(level.loaded?level.loaded.duration:0)+duration,level.loaded={bytes:loadedBytes,duration:duration},level.realBitrate=Math.round(8*loadedBytes/duration)),frag.bitrateTest?(level={stats:stats,frag:frag,part:_ref,id:frag.type},this.onFragBuffered(Events.FRAG_BUFFERED,level),frag.bitrateTest=!1):this.lastLoadedFragLevel=frag.level)},_proto.onFragBuffered=function(event,data){var processingMs,frag=data.frag,data=data.part,data=(null!=data&&data.stats.loaded?data:frag).stats;data.aborted||this.ignoreFragment(frag)||(processingMs=data.parsing.end-data.loading.start-Math.min(data.loading.first-data.loading.start,this.bwEstimator.getEstimateTTFB()),this.bwEstimator.sample(processingMs,data.loaded),data.bwEstimate=this.getBwEstimate(),frag.bitrateTest?this.bitrateTestDelay=processingMs/1e3:this.bitrateTestDelay=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;if(hls.levels.length<=1)return hls.loadLevel;var maxAutoLevel=hls.maxAutoLevel,config=hls.config,minAutoLevel=hls.minAutoLevel,partCurrent=partCurrent?partCurrent.duration:fragCurrent?fragCurrent.duration:0,fragCurrent=this.getBwEstimate(),bufferStarvationDelay=this.getStarvationDelay(),bwFactor=config.abrBandWidthFactor,bwUpFactor=config.abrBandWidthUpFactor;if(bufferStarvationDelay){var _bestLevel=this.findBestLevel(fragCurrent,minAutoLevel,maxAutoLevel,bufferStarvationDelay,0,bwFactor,bwUpFactor);if(0<=_bestLevel)return _bestLevel}var bitrateTestDelay,_bestLevel=partCurrent?Math.min(partCurrent,config.maxStarvationDelay):config.maxStarvationDelay,partCurrent=(bufferStarvationDelay||(bitrateTestDelay=this.bitrateTestDelay)&&(_bestLevel=(partCurrent?Math.min(partCurrent,config.maxLoadingDelay):config.maxLoadingDelay)-bitrateTestDelay,this.info("bitrate test took "+Math.round(1e3*bitrateTestDelay)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*_bestLevel)+" ms"),bwFactor=bwUpFactor=1),this.findBestLevel(fragCurrent,minAutoLevel,maxAutoLevel,bufferStarvationDelay,_bestLevel,bwFactor,bwUpFactor));return this.info((bufferStarvationDelay?"rebuffering expected":"buffer is empty")+", optimal quality level "+partCurrent),-1<partCurrent?partCurrent:(config=hls.levels[minAutoLevel],bitrateTestDelay=hls.levels[hls.loadLevel],(null==config?void 0:config.bitrate)<(null==bitrateTestDelay?void 0:bitrateTestDelay.bitrate)?minAutoLevel:hls.loadLevel)},_proto.getStarvationDelay=function(){var hls=this.hls,media=hls.media;return media?(media=media&&0!==media.playbackRate?Math.abs(media.playbackRate):1,((hls=hls.mainForwardBufferInfo)?hls.len:0)/media):1/0},_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 _this3=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;if(1===levels.length)return 0;var _this$hls=levels[selectionBaseLevel],live=!(null==(_this$hls$latestLevel2=this.hls.latestLevelDetails)||!_this$hls$latestLevel2.live),firstSelection=-1===loadLevel||-1===lastLoadedFragLevel,currentVideoRange="SDR",currentFrameRate=(null==_this$hls?void 0:_this$hls.frameRate)||0,audioPreference=config.audioPreference,_this$hls$latestLevel2=config.videoPreference,audioTracksByGroup=this.audioTracksByGroup||(this.audioTracksByGroup=getAudioTracksByGroup(allAudioTracks)),minStartIndex=-1;if(firstSelection){if(-1!==this.firstSelection)return this.firstSelection;var allAudioTracks=getStartCodecTier(this.codecTiers||(this.codecTiers=function(levels,audioTracksByGroup,minAutoLevel,maxAutoLevel){return levels.slice(minAutoLevel,maxAutoLevel+1).reduce(function(tiers,level,index){var audioGroups,tier,lesserWidthOrHeight;return level.codecSet&&(audioGroups=level.audioGroups,(tier=tiers[level.codecSet])||(tiers[level.codecSet]=tier={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:index,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!audioGroups,fragmentError:0}),tier.minBitrate=Math.min(tier.minBitrate,level.bitrate),lesserWidthOrHeight=Math.min(level.height,level.width),tier.minHeight=Math.min(tier.minHeight,lesserWidthOrHeight),tier.minFramerate=Math.min(tier.minFramerate,level.frameRate),tier.minIndex=Math.min(tier.minIndex,index),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){var audioGroup;audioGroupId&&(audioGroup=audioTracksByGroup.groups[audioGroupId])&&(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},{})}(levels,audioTracksByGroup,minAutoLevel,maxAutoLevel)),currentVideoRange,currentBw,audioPreference,_this$hls$latestLevel2),_this$hls$latestLevel2=allAudioTracks.codecSet,videoRanges=allAudioTracks.videoRanges,minFramerate=allAudioTracks.minFramerate,minBitrate=allAudioTracks.minBitrate,minIndex=allAudioTracks.minIndex,preferHDR=allAudioTracks.preferHDR,minStartIndex=minIndex,currentCodecSet=_this$hls$latestLevel2,currentVideoRange=preferHDR?videoRanges[videoRanges.length-1]:videoRanges[0],currentFrameRate=minFramerate;currentBw=Math.max(currentBw,minBitrate),this.log("picked start tier "+JSON.stringify(allAudioTracks))}else currentCodecSet=null==_this$hls?void 0:_this$hls.codecSet,currentVideoRange=null==_this$hls?void 0:_this$hls.videoRange;function _loop(){var _levelInfo$videoCodec,bitrate,mediaCapabilities,forcedAutoLevel,levelInfo=levels[i],upSwitch=selectionBaseLevel<i;return levelInfo?(!config.useMediaCapabilities||levelInfo.supportedResult||levelInfo.supportedPromise||("function"!=typeof(null==(mediaCapabilities=navigator.mediaCapabilities)?void 0:mediaCapabilities.decodingInfo)||!function(level,audioTracksByGroup,currentVideoRange,currentFrameRate,currentBw,audioPreference){var audioGroups=level.audioCodec?level.audioGroups:null,audioCodecPreference=null==audioPreference?void 0:audioPreference.audioCodec,maxChannels=(audioPreference=null==audioPreference?void 0:audioPreference.channels)?parseInt(audioPreference):audioCodecPreference?1/0:2,audioPreference=null;if(null!=audioGroups&&audioGroups.length)try{audioPreference=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");Object.keys(audioTrackGroup.channels).forEach(function(key){acc[key]=(acc[key]||0)+audioTrackGroup.channels[key]})}return acc},{2:0})}catch(error){return 1}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))||audioPreference&&isFiniteNumber(maxChannels)&&Object.keys(audioPreference).some(function(channels){return parseInt(channels)>maxChannels})}(levelInfo,audioTracksByGroup,currentVideoRange,currentFrameRate,currentBw,audioPreference)&&"hvc1"!==(null==(_levelInfo$videoCodec=levelInfo.videoCodec)?void 0:_levelInfo$videoCodec.substring(0,4))?levelInfo.supportedResult=SUPPORTED_INFO_DEFAULT:(levelInfo.supportedPromise=getMediaDecodingInfoPromise(levelInfo,audioTracksByGroup,mediaCapabilities),levelInfo.supportedPromise.then(function(decodingInfo){var levels,index;_this3.hls&&(levelInfo.supportedResult=decodingInfo,index=(levels=_this3.hls.levels).indexOf(levelInfo),decodingInfo.error?_this3.warn('MediaCapabilities decodingInfo error: "'+decodingInfo.error+'" for level '+index+" "+JSON.stringify(decodingInfo)):decodingInfo.supported||(_this3.warn("Unsupported MediaCapabilities decodingInfo result for level "+index+" "+JSON.stringify(decodingInfo)),-1<index&&1<levels.length&&(_this3.log("Removing unsupported level "+index),_this3.hls.removeLevel(index),-1===_this3.hls.loadLevel)&&(_this3.hls.nextLoadLevel=0)))}))),!(currentCodecSet&&levelInfo.codecSet!==currentCodecSet||currentVideoRange&&levelInfo.videoRange!==currentVideoRange||upSwitch&&currentFrameRate>levelInfo.frameRate||!upSwitch&&0<currentFrameRate&&currentFrameRate<levelInfo.frameRate||levelInfo.supportedResult&&(null==(_levelInfo$videoCodec=levelInfo.supportedResult.decodingInfoResults)||!_levelInfo$videoCodec[0].smooth))||firstSelection&&i===minStartIndex?(mediaCapabilities=levelInfo.details,_levelInfo$videoCodec=(partCurrent?null==mediaCapabilities?void 0:mediaCapabilities.partTarget:null==mediaCapabilities?void 0:mediaCapabilities.averagetargetduration)||currentFragDuration,upSwitch=upSwitch?bwUpFactor*currentBw:bwFactor*currentBw,bitrate=currentFragDuration&&2*currentFragDuration<=bufferStarvationDelay&&0===maxStarvationDelay?levelInfo.averageBitrate:levelInfo.maxBitrate,mediaCapabilities=_this3.getTimeToLoadFrag(ttfbEstimateSec,upSwitch,bitrate*_levelInfo$videoCodec,void 0===mediaCapabilities),bitrate<=upSwitch&&(i===lastLoadedFragLevel||0===levelInfo.loadError&&0===levelInfo.fragmentError)&&(mediaCapabilities<=ttfbEstimateSec||!isFiniteNumber(mediaCapabilities)||live&&!_this3.bitrateTestDelay||mediaCapabilities<maxFetchDuration)?(forcedAutoLevel=_this3.forcedAutoLevel,i===loadLevel||-1!==forcedAutoLevel&&forcedAutoLevel===loadLevel||(levelsSkipped.length&&_this3.trace("Skipped level(s) "+levelsSkipped.join(",")+" of "+maxAutoLevel+' max with CODECS and VIDEO-RANGE:"'+levels[levelsSkipped[0]].codecs+'" '+levels[levelsSkipped[0]].videoRange+'; not compatible with "'+currentCodecSet+'" '+currentVideoRange),_this3.info("switch candidate:"+selectionBaseLevel+"->"+i+" adjustedbw("+Math.round(upSwitch)+")-bitrate="+Math.round(upSwitch-bitrate)+" ttfb:"+ttfbEstimateSec.toFixed(1)+" avgDuration:"+_levelInfo$videoCodec.toFixed(1)+" maxFetchDuration:"+maxFetchDuration.toFixed(1)+" fetchDuration:"+mediaCapabilities.toFixed(1)+" firstSelection:"+firstSelection+" codecSet:"+levelInfo.codecSet+" videoRange:"+levelInfo.videoRange+" hls.loadLevel:"+loadLevel)),firstSelection&&(_this3.firstSelection=i),{v:i}):void 0):(levelsSkipped.push(i),0)):0}for(var _ret,currentFragDuration=partCurrent?partCurrent.duration:fragCurrent?fragCurrent.duration:0,ttfbEstimateSec=this.bwEstimator.getEstimateTTFB()/1e3,levelsSkipped=[],i=maxAutoLevel;minAutoLevel<=i;i--)if(0!==(_ret=_loop())&&_ret)return _ret.v;return-1},_createClass(AbrController,[{key:"firstAutoLevel",get:function(){var _this$hls2=this.hls,maxAutoLevel=_this$hls2.maxAutoLevel,_this$hls2=_this$hls2.minAutoLevel,bwEstimate=this.getBwEstimate(),maxStartDelay=this.hls.config.maxStarvationDelay,bwEstimate=this.findBestLevel(bwEstimate,_this$hls2,maxAutoLevel,0,maxStartDelay,1,1);return-1<bwEstimate||(maxStartDelay=this.hls.firstLevel,bwEstimate=Math.min(Math.max(maxStartDelay,_this$hls2),maxAutoLevel),this.warn("Could not find best starting auto level. Defaulting to first in playlist "+maxStartDelay+" clamped to "+bwEstimate)),bwEstimate}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var forcedAutoLevel=this.forcedAutoLevel,useEstimate=this.bwEstimator.canEstimate(),loadedFirstFrag=-1<this.lastLoadedFragLevel;if(!(-1===forcedAutoLevel||useEstimate&&loadedFirstFrag&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return forcedAutoLevel;useEstimate=useEstimate&&loadedFirstFrag?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==forcedAutoLevel){loadedFirstFrag=this.hls.levels;if(loadedFirstFrag.length>Math.max(forcedAutoLevel,useEstimate)&&loadedFirstFrag[forcedAutoLevel].loadError<=loadedFirstFrag[useEstimate].loadError)return forcedAutoLevel}return this._nextAutoLevel=useEstimate,this.nextAutoLevelKey=this.getAutoLevelKey(),useEstimate},set:function(nextLevel){var _this$hls3=this.hls,maxAutoLevel=_this$hls3.maxAutoLevel,_this$hls3=_this$hls3.minAutoLevel,nextLevel=Math.min(Math.max(nextLevel,_this$hls3),maxAutoLevel);this._nextAutoLevel!==nextLevel&&(this.nextAutoLevelKey="",this._nextAutoLevel=nextLevel)}}])}(Logger),BinarySearch={search:function(list,comparisonFn){for(var minIndex=0,maxIndex=list.length-1;minIndex<=maxIndex;){var currentIndex,currentElement,comparisonResult=comparisonFn(currentElement=list[currentIndex=(minIndex+maxIndex)/2|0]);if(0<comparisonResult)minIndex=1+currentIndex;else{if(!(comparisonResult<0))return currentElement;maxIndex=currentIndex-1}}return null}};function findFragmentByPDT(fragments,PDTValue,maxFragLookUpTolerance){if(null!==PDTValue&&Array.isArray(fragments)&&fragments.length&&isFiniteNumber(PDTValue)){var startPDT=fragments[0].programDateTime;if(!(PDTValue<(startPDT||0))){startPDT=fragments[fragments.length-1].endProgramDateTime;if(!((startPDT||0)<=PDTValue)){maxFragLookUpTolerance=maxFragLookUpTolerance||0;for(var seg=0;seg<fragments.length;++seg){var frag=fragments[seg];if(function(pdtBufferEnd,maxFragLookUpTolerance,candidate){maxFragLookUpTolerance=1e3*Math.min(maxFragLookUpTolerance,candidate.duration+(candidate.deltaPTS||0));return(candidate.endProgramDateTime||0)-maxFragLookUpTolerance>pdtBufferEnd}(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 bufferEdgeError,fragNext=null;return fragPrevious?(fragNext=fragments[1+fragPrevious.sn-fragments[0].sn]||null,0<(bufferEdgeError=fragPrevious.endDTS-bufferEnd)&&bufferEdgeError<15e-7&&(bufferEnd+=15e-7),fragNext&&fragPrevious.level!==fragNext.level&&fragNext.end<=fragPrevious.end&&(fragNext=fragments[2+fragPrevious.sn-fragments[0].sn]||null)):0===bufferEnd&&0===fragments[0].start&&(fragNext=fragments[0]),fragNext&&(!(fragPrevious&&fragPrevious.level!==fragNext.level||0!==fragmentWithinToleranceTest(bufferEnd,maxFragLookUpTolerance,fragNext))||function(fragNext,fragPrevious,nextFragLookupTolerance){if(fragPrevious&&0===fragPrevious.start&&fragPrevious.level<fragNext.level&&0<(fragPrevious.endPTS||0))return fragPrevious=fragPrevious.tagList.reduce(function(duration,tag){return"INF"===tag[0]&&(duration+=parseFloat(tag[1])),duration},nextFragLookupTolerance),fragNext.start<=fragPrevious;return}(fragNext,fragPrevious,Math.min(nextFragLookupTolerance,maxFragLookUpTolerance)))||!(bufferEdgeError=BinarySearch.search(fragments,fragmentWithinToleranceTest.bind(null,bufferEnd,maxFragLookUpTolerance)))||bufferEdgeError===fragPrevious&&fragNext?fragNext:bufferEdgeError}function fragmentWithinToleranceTest(bufferEnd,maxFragLookUpTolerance,candidate){return void 0===maxFragLookUpTolerance&&(maxFragLookUpTolerance=0),candidate.start<=(bufferEnd=void 0===bufferEnd?0:bufferEnd)&&candidate.start+candidate.duration>bufferEnd?0:(maxFragLookUpTolerance=Math.min(maxFragLookUpTolerance,candidate.duration+(candidate.deltaPTS||0)),candidate.start+candidate.duration-maxFragLookUpTolerance<=bufferEnd?1:candidate.start-maxFragLookUpTolerance>bufferEnd&&candidate.start?-1:0)}function findFragWithCC(fragments,cc){return BinarySearch.search(fragments,function(candidate){return candidate.cc<cc?1:candidate.cc>cc?-1:0})}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){error=isTimeoutError(error);return loadPolicy.default[(error?"timeout":"error")+"Retry"]}function getRetryDelay(retryConfig,retryCount){retryCount="linear"===retryConfig.backoff?1:Math.pow(2,retryCount);return Math.min(retryCount*retryConfig.retryDelayMs,retryConfig.maxRetryDelayMs)}function getLoaderConfigWithoutReties(loderConfig){return _objectSpread2(_objectSpread2({},loderConfig),{errorRetry:null,timeoutRetry:null})}function shouldRetry(retryConfig,retryCount,isTimeout,loaderResponse){var httpStatus;return!!retryConfig&&(httpStatus=null==loaderResponse?void 0:loaderResponse.code,httpStatus=retryCount<retryConfig.maxNumRetry&&(function(httpStatus){return 0===httpStatus&&!1===navigator.onLine||!!httpStatus&&(httpStatus<400||499<httpStatus)}(httpStatus)||!!isTimeout),retryConfig.shouldRetry?retryConfig.shouldRetry(retryConfig,retryCount,isTimeout,loaderResponse,httpStatus):httpStatus)}var NetworkErrorAction_DoNothing=0,NetworkErrorAction_SendAlternateToPenaltyBox=2,NetworkErrorAction_RemoveAlternatePermanently=3,NetworkErrorAction_RetryRequest=5,ErrorActionFlags_None=0,ErrorActionFlags_MoveAllAlternatesMatchingHost=1,ErrorActionFlags_MoveAllAlternatesMatchingHDCP=2,ErrorController=function(_Logger){function ErrorController(hls){var _this=_Logger.call(this,"error-controller",hls.logger)||this;return _this.hls=void 0,_this.playlistError=0,_this.penalizedRenditions={},_this.hls=hls,_this.registerListeners(),_this}_inheritsLoose(ErrorController,_Logger);var _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(startPosition){},_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){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=createDoNothingErrorAction());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 _data$frag=data.parent===PlaylistLevelType_MAIN?data.level:hls.loadLevel;return void(data.details===ErrorDetails.LEVEL_EMPTY_ERROR&&null!=(_data$context=data.context)&&null!=(_data$context=_data$context.levelDetails)&&_data$context.live?data.errorAction=this.getPlaylistRetryOrSwitchAction(data,_data$frag):(data.levelRetry=!1,data.errorAction=this.getLevelSwitchAction(data,_data$frag)));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 _data$context=hls.levels[hls.loadLevel];if(_data$context&&(context.type===PlaylistContextType_AUDIO_TRACK&&_data$context.hasAudioGroup(context.groupId)||context.type===PlaylistContextType_SUBTITLE_TRACK&&_data$context.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 _data$frag=hls.levels[hls.loadLevel],_data$context=null==_data$frag?void 0:_data$frag.attrs["HDCP-LEVEL"];return void(_data$context?data.errorAction={action:NetworkErrorAction_SendAlternateToPenaltyBox,flags:ErrorActionFlags_MoveAllAlternatesMatchingHDCP,hdcpLevel:_data$context}:this.keySystemError(data));case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:return void(data.errorAction||(data.errorAction=this.getLevelSwitchAction(data,null!=(_data$frag=data.level)?_data$frag:hls.loadLevel)));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=createDoNothingErrorAction())}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 retryConfig=getRetryConfig(this.hls.config.playlistLoadPolicy,data),retryCount=this.playlistError++;return shouldRetry(retryConfig,retryCount,isTimeoutError(data),data.response)?{action:NetworkErrorAction_RetryRequest,flags:ErrorActionFlags_None,retryConfig:retryConfig,retryCount:retryCount}:(data=this.getLevelSwitchAction(data,levelIndex),retryConfig&&(data.retryConfig=retryConfig,data.retryCount=retryCount),data)},_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,_hls$config=_hls$config.keyLoadPolicy,_hls$config=getRetryConfig(data.details.startsWith("key")?_hls$config:fragLoadPolicy,data),fragLoadPolicy=hls.levels.reduce(function(acc,level){return acc+level.fragmentError},0);if(level&&(data.details!==ErrorDetails.FRAG_GAP&&level.fragmentError++,shouldRetry(_hls$config,fragLoadPolicy,isTimeoutError(data),data.response)))return{action:NetworkErrorAction_RetryRequest,flags:ErrorActionFlags_None,retryConfig:_hls$config,retryCount:fragLoadPolicy};hls=this.getLevelSwitchAction(data,variantLevelIndex);return _hls$config&&(hls.retryConfig=_hls$config,hls.retryCount=fragLoadPolicy),hls},_proto.getLevelSwitchAction=function(data,levelIndex){var hls=this.hls,level=(null==levelIndex&&(levelIndex=hls.loadLevel),this.hls.levels[levelIndex]);if(level){for(var _ret,errorDetails=data.details,nextLevel=(level.loadError++,errorDetails===ErrorDetails.BUFFER_APPEND_ERROR&&level.fragmentError++,-1),levels=hls.levels,loadLevel=hls.loadLevel,minAutoLevel=hls.minAutoLevel,maxAutoLevel=hls.maxAutoLevel,fragErrorType=(hls.autoLevelEnabled||(hls.loadLevel=-1),null==(levelIndex=data.frag)?void 0:levelIndex.type),findAudioCodecAlternate=(fragErrorType===PlaylistLevelType_AUDIO&&errorDetails===ErrorDetails.FRAG_PARSING_ERROR||"audio"===data.sourceBufferName&&(errorDetails===ErrorDetails.BUFFER_ADD_CODEC_ERROR||errorDetails===ErrorDetails.BUFFER_APPEND_ERROR))&&levels.some(function(_ref){_ref=_ref.audioCodec;return level.audioCodec!==_ref}),findVideoCodecAlternate="video"===data.sourceBufferName&&(errorDetails===ErrorDetails.BUFFER_ADD_CODEC_ERROR||errorDetails===ErrorDetails.BUFFER_APPEND_ERROR)&&levels.some(function(_ref2){var codecSet=_ref2.codecSet,_ref2=_ref2.audioCodec;return level.codecSet!==codecSet&&level.audioCodec===_ref2}),levelIndex=null!=(levelIndex=data.context)?levelIndex:{},playlistErrorType=levelIndex.type,playlistErrorGroupId=levelIndex.groupId,i=levels.length;i--&&(0===(_ret=function(){var candidate=(i+loadLevel)%levels.length;if(candidate!==loadLevel&&minAutoLevel<=candidate&&candidate<=maxAutoLevel&&0===levels[candidate].loadError){var levelCandidate=levels[candidate];if(errorDetails===ErrorDetails.FRAG_GAP&&fragErrorType===PlaylistLevelType_MAIN&&data.frag){var levelDetails=levels[candidate].details;if(levelDetails){var levelDetails=findFragmentByPTS(data.frag,levelDetails.fragments,data.frag.start);if(null!=levelDetails&&levelDetails.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!=(levelDetails=level.audioGroups)&&levelDetails.some(function(groupId){return levelCandidate.hasAudioGroup(groupId)})||fragErrorType===PlaylistLevelType_SUBTITLE&&null!=(levelDetails=level.subtitleGroups)&&levelDetails.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}}())||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 recover from media error.'),this.hls.recoverMediaError()):data.fatal=!0}data.fatal&&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;switch(flags){case ErrorActionFlags_None:this.switchLevel(data,nextAutoLevel);break;case 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')}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}(Logger);function createDoNothingErrorAction(resolved){var errorAction={action:NetworkErrorAction_DoNothing,flags:ErrorActionFlags_None};return resolved&&(errorAction.resolved=!0),errorAction}var FragmentState_NOT_LOADED="NOT_LOADED",FragmentState_APPENDING="APPENDING",FragmentState_PARTIAL="PARTIAL",FragmentState_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;return _proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),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.MANIFEST_LOADING,this.onManifestLoading,this),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;i--;){var activePart=activeParts[i];if(!activePart)break;var appendedPTS=activePart.end;if(activePart.start<=position&&null!==appendedPTS&&position<=appendedPTS)return activePart}return this.getBufferedFrag(position,levelType)},_proto.getBufferedFrag=function(position,levelType){return this.getFragAtPos(position,levelType,!0)},_proto.getFragAtPos=function(position,levelType,buffered){for(var fragments=this.fragments,keys=Object.keys(fragments),i=keys.length;i--;){var fragmentEntity=fragments[keys[i]];if((null==fragmentEntity?void 0:fragmentEntity.body.type)===levelType&&(!buffered||fragmentEntity.buffered)){fragmentEntity=fragmentEntity.body;if(fragmentEntity.start<=position&&position<=fragmentEntity.end)return fragmentEntity}}return null},_proto.detectEvictedFragments=function(elementaryStream,timeRange,playlistType,appendedPart,removeAppending){var _this=this,appendedPartSn=(this.timeRanges&&(this.timeRanges[elementaryStream]=timeRange),(null==appendedPart?void 0:appendedPart.fragment.sn)||-1);Object.keys(this.fragments).forEach(function(key){var fragmentEntity=_this.fragments[key];!fragmentEntity||appendedPartSn>=fragmentEntity.body.sn||(fragmentEntity.buffered||fragmentEntity.loaded&&!removeAppending?(key=fragmentEntity.range[elementaryStream])&&(0===key.time.length?_this.removeFragment(fragmentEntity.body):key.time.some(function(time){time=!_this.isTimeBuffered(time.startPTS,time.endPTS,timeRange);return time&&_this.removeFragment(fragmentEntity.body),time})):fragmentEntity.body.type===playlistType&&_this.removeFragment(fragmentEntity.body))})},_proto.detectPartialFragments=function(data){var frag,fragKey,fragmentEntity,isFragHint,_this2=this,timeRanges=this.timeRanges;timeRanges&&"initSegment"!==data.frag.sn&&(fragKey=getFragmentKey(frag=data.frag),!(fragmentEntity=this.fragments[fragKey])||fragmentEntity.buffered&&frag.gap||(isFragHint=!frag.relurl,Object.keys(timeRanges).forEach(function(elementaryStream){var timeRange,streamInfo=frag.elementaryStreams[elementaryStream];streamInfo&&(timeRange=timeRanges[elementaryStream],streamInfo=isFragHint||!0===streamInfo.partial,fragmentEntity.range[elementaryStream]=_this2.getBufferedTimes(frag,data.part,streamInfo,timeRange))}),fragmentEntity.loaded=null,Object.keys(fragmentEntity.range).length?(fragmentEntity.buffered=!0,(fragmentEntity.body.endList=frag.endList||fragmentEntity.body.endList)&&(this.endListFragments[fragmentEntity.body.type]=fragmentEntity),isPartial(fragmentEntity)||this.removeParts(frag.sn-1,frag.type)):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(startTime<=maxStartPTS&&minEndPTS<=endTime){buffered.time.push({startPTS:Math.max(startPTS,timeRange.start(i)),endPTS:Math.min(endPTS,timeRange.end(i))});break}if(startPTS<endTime&&startTime<endPTS){var endTime=Math.max(startPTS,timeRange.start(i)),end=Math.min(endPTS,timeRange.end(i));endTime<end&&(buffered.partial=!0,buffered.time.push({startPTS:endTime,endPTS:end}))}else if(endPTS<=startTime)break}return buffered},_proto.getPartialFragment=function(time){var startTime,endTime,bestFragment=null,bestOverlap=0,bufferPadding=this.bufferPadding,fragments=this.fragments;return Object.keys(fragments).forEach(function(key){key=fragments[key];key&&isPartial(key)&&(startTime=key.body.start-bufferPadding,endTime=key.body.end+bufferPadding,startTime<=time)&&time<=endTime&&(startTime=Math.min(time-startTime,endTime-time),bestOverlap<=startTime)&&(bestFragment=key.body,bestOverlap=startTime)}),bestFragment},_proto.isEndListAppended=function(type){type=this.endListFragments[type];return void 0!==type&&(type.buffered||isPartial(type))},_proto.getState=function(fragment){fragment=getFragmentKey(fragment),fragment=this.fragments[fragment];return fragment?fragment.buffered?isPartial(fragment)?FragmentState_PARTIAL:FragmentState_OK:FragmentState_APPENDING:FragmentState_NOT_LOADED},_proto.isTimeBuffered=function(startPTS,endPTS,timeRange){for(var startTime,endTime,i=0;i<timeRange.length;i++){if(startTime=timeRange.start(i)-this.bufferPadding,endTime=timeRange.end(i)+this.bufferPadding,startTime<=startPTS&&endPTS<=endTime)return!0;if(endPTS<=startTime)return!1}return!1},_proto.onManifestLoading=function(){this.removeAllFragments()},_proto.onFragLoaded=function(event,data){var frag,fragKey;"initSegment"===data.frag.sn||data.frag.bitrateTest||(frag=data.frag,data=data.part?null:data,fragKey=getFragmentKey(frag),this.fragments[fragKey]={body:frag,appendedPTS:null,loaded:data,buffered:!1,range:Object.create(null)})},_proto.onBufferAppended=function(event,data){var activeParts,frag=data.frag,part=data.part,timeRanges=data.timeRanges,data=data.type;"initSegment"!==frag.sn&&(frag=frag.type,part&&((activeParts=this.activePartLists[frag])||(this.activePartLists[frag]=activeParts=[]),activeParts.push(part)),activeParts=(this.timeRanges=timeRanges)[data],this.detectEvictedFragments(data,activeParts,frag,part))},_proto.onFragBuffered=function(event,data){this.detectPartialFragments(data)},_proto.hasFragment=function(fragment){fragment=getFragmentKey(fragment);return!!this.fragments[fragment]},_proto.hasFragments=function(type){var fragments=this.fragments,keys=Object.keys(fragments);if(!type)return 0<keys.length;for(var i=keys.length;i--;){var fragmentEntity=fragments[keys[i]];if((null==fragmentEntity?void 0:fragmentEntity.body.type)===type)return!0}return!1},_proto.hasParts=function(type){return!(null==(type=this.activePartLists[type])||!type.length)},_proto.removeFragmentsInRange=function(start,end,playlistType,withGapOnly,unbufferedOnly){var _this3=this;withGapOnly&&!this.hasGaps||Object.keys(this.fragments).forEach(function(key){var frag,key=_this3.fragments[key];!key||(frag=key.body).type!==playlistType||withGapOnly&&!frag.gap||frag.start<end&&frag.end>start&&(key.buffered||unbufferedOnly)&&_this3.removeFragment(frag)})},_proto.removeFragment=function(fragment){var snToRemove,fragKey=getFragmentKey(fragment),activeParts=(fragment.stats.loaded=0,fragment.clearElementaryStreamInfo(),this.activePartLists[fragment.type]);activeParts&&(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;var _this$hls=null==(_this$hls=this.hls)||null==(_this$hls=_this$hls.latestLevelDetails)?void 0:_this$hls.partList;_this$hls&&_this$hls.forEach(function(part){return part.clearElementaryStreamInfo()})},FragmentTracker}();function isPartial(fragmentEntity){var _fragmentEntity$range;return fragmentEntity.buffered&&(fragmentEntity.body.gap||(null==(_fragmentEntity$range=fragmentEntity.range.video)?void 0:_fragmentEntity$range.partial)||(null==(_fragmentEntity$range=fragmentEntity.range.audio)?void 0:_fragmentEntity$range.partial)||(null==(_fragmentEntity$range=fragmentEntity.range.audiovideo)?void 0:_fragmentEntity$range.partial))}function getFragmentKey(fragment){return fragment.type+"_"+fragment.level+"_"+fragment.sn}var DecrypterAesMode_cbc=0,DecrypterAesMode_ctr=1,AESCrypto=function(){function AESCrypto(subtle,iv,aesMode){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=subtle,this.aesIV=iv,this.aesMode=aesMode}return AESCrypto.prototype.decrypt=function(data,key){switch(this.aesMode){case DecrypterAesMode_cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},key,data);case DecrypterAesMode_ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},key,data);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},AESCrypto}();function sliceUint8(array,start,end){return Uint8Array.prototype.slice?array.slice(start,end):new Uint8Array(Array.prototype.slice.call(array,start,end))}var 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;i<4;i++)newArray[i]=view.getUint32(4*i);return newArray},_proto.initTable=function(){for(var sBox=this.sBox,invSBox=this.invSBox,subMix=this.subMix,subMix0=subMix[0],subMix1=subMix[1],subMix2=subMix[2],subMix3=subMix[3],subMix=this.invSubMix,invSubMix0=subMix[0],invSubMix1=subMix[1],invSubMix2=subMix[2],invSubMix3=subMix[3],d=new Uint32Array(256),x=0,xi=0,i=0,i=0;i<256;i++)d[i]=i<128?i<<1:i<<1^283;for(i=0;i<256;i++){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4,x2=(sBox[x]=sx=sx>>>8^255&sx^99,d[invSBox[sx]=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,invSubMix0[sx]=(t=16843009*x8^65537*x4^257*x2^16843008*x)<<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}},_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);for(var invKsRow,prev,t,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,keyBuffer=this.invSubMix,invSubMix0=keyBuffer[0],invSubMix1=keyBuffer[1],invSubMix2=keyBuffer[2],invSubMix3=keyBuffer[3],ksRow=0;ksRow<ksRows;ksRow++)ksRow<keySize?prev=keySchedule[ksRow]=key[ksRow]:(t=prev,ksRow%keySize==0?(t=sbox[(t=t<<8|t>>>24)>>>24]<<24|sbox[t>>>16&255]<<16|sbox[t>>>8&255]<<8|sbox[255&t],t^=rcon[ksRow/keySize|0]<<24):6<keySize&&ksRow%keySize==4&&(t=sbox[t>>>24]<<24|sbox[t>>>16&255]<<16|sbox[t>>>8&255]<<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]=invKsRow<4||ksRow<=4?t:invSubMix0[sbox[t>>>24]]^invSubMix1[sbox[t>>>16&255]]^invSubMix2[sbox[t>>>8&255]]^invSubMix3[sbox[255&t]],invKeySchedule[invKsRow]=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 t0,t1,t2,t3,s0,s1,s2,s3,inputWords0,inputWords1,inputWords2,inputWords3,ksRow,i,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],invSubMix=this.uint8ArrayToUint32Array_(aesIV),initVector0=invSubMix[0],initVector1=invSubMix[1],initVector2=invSubMix[2],initVector3=invSubMix[3],inputInt32=new Int32Array(inputArrayBuffer),outputInt32=new Int32Array(inputInt32.length),swapWord=this.networkToHostOrderSwap;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[s1>>16&255]^invSubMix2[s2>>8&255]^invSubMix3[255&s3]^invKeySchedule[ksRow],t1=invSubMix0[s1>>>24]^invSubMix1[s2>>16&255]^invSubMix2[s3>>8&255]^invSubMix3[255&s0]^invKeySchedule[ksRow+1],t2=invSubMix0[s2>>>24]^invSubMix1[s3>>16&255]^invSubMix2[s0>>8&255]^invSubMix3[255&s1]^invKeySchedule[ksRow+2],t3=invSubMix0[s3>>>24]^invSubMix1[s0>>16&255]^invSubMix2[s1>>8&255]^invSubMix3[255&s2]^invKeySchedule[ksRow+3],s0=t0,s1=t1,s2=t2,s3=t3,ksRow+=4;t0=invSBOX[s0>>>24]<<24^invSBOX[s1>>16&255]<<16^invSBOX[s2>>8&255]<<8^invSBOX[255&s3]^invKeySchedule[ksRow],t1=invSBOX[s1>>>24]<<24^invSBOX[s2>>16&255]<<16^invSBOX[s3>>8&255]<<8^invSBOX[255&s0]^invKeySchedule[ksRow+1],t2=invSBOX[s2>>>24]<<24^invSBOX[s3>>16&255]<<16^invSBOX[s0>>8&255]<<8^invSBOX[255&s1]^invKeySchedule[ksRow+2],t3=invSBOX[s3>>>24]<<24^invSBOX[s0>>16&255]<<16^invSBOX[s1>>8&255]<<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}(),FastAESKey=function(){function FastAESKey(subtle,key,aesMode){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=subtle,this.key=key,this.aesMode=aesMode}return FastAESKey.prototype.expandKey=function(){var subtleAlgoName=function(aesMode){switch(aesMode){case DecrypterAesMode_cbc:return"AES-CBC";case DecrypterAesMode_ctr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+aesMode)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:subtleAlgoName},!1,["encrypt","decrypt"])},FastAESKey}();function utf8ArrayToStr(array,exitOnNull){var decoded,idx;if(void 0===exitOnNull&&(exitOnNull=!1),"undefined"!=typeof TextDecoder)return decoded=new TextDecoder("utf-8").decode(array),exitOnNull?-1!==(idx=decoded.indexOf("\0"))?decoded.substring(0,idx):decoded:decoded.replace(/\0/g,"");for(var c,char2,char3,len=array.length,out="",i=0;i<len;){if(0===(c=array[i++])&&exitOnNull)return out;if(0!==c&&3!==c)switch(c>>4){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}function LoadStats(){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}}var Hex={hexDump:function(array){for(var str="",i=0;i<array.length;i++){var h=array[i].toString(16);str+=h=h.length<2?"0"+h:h}return str}},ElementaryStreamTypes_AUDIO="audio",ElementaryStreamTypes_VIDEO="video",ElementaryStreamTypes_AUDIOVIDEO="audiovideo",BaseSegment=function(){function BaseSegment(base){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,this.base=base="string"==typeof base?{url:base}:base}var _proto=BaseSegment.prototype;return _proto.setByteRange=function(value,previous){value=value.split("@",2),previous=1===value.length?(null==previous?void 0:previous.byteRangeEndOffset)||0:parseInt(value[1]);this._byteRange=[previous,parseInt(value[0])+previous]},_proto.clearElementaryStreamInfo=function(){var elementaryStreams=this.elementaryStreams;elementaryStreams[ElementaryStreamTypes_AUDIO]=null,elementaryStreams[ElementaryStreamTypes_VIDEO]=null,elementaryStreams[ElementaryStreamTypes_AUDIOVIDEO]=null},_createClass(BaseSegment,[{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){var _this$_streams;return null===this._streams&&(this._streams=((_this$_streams={})[ElementaryStreamTypes_AUDIO]=null,_this$_streams[ElementaryStreamTypes_VIDEO]=null,_this$_streams[ElementaryStreamTypes_AUDIOVIDEO]=null,_this$_streams)),this._streams},set:function(value){this._streams=value}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new LoadStats),this._stats},set:function(value){this._stats=value}},{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}}])}();function isMediaFragment(frag){return"initSegment"!==frag.sn}var Fragment=function(_BaseSegment2){function Fragment(type,base){base=_BaseSegment2.call(this,base)||this;return base._decryptdata=null,base._programDateTime=null,base._ref=null,base._bitrate=void 0,base.rawProgramDateTime=null,base.tagList=[],base.duration=0,base.sn=0,base.levelkeys=void 0,base.type=void 0,base.loader=null,base.keyLoader=null,base.level=-1,base.cc=0,base.startPTS=void 0,base.endPTS=void 0,base.startDTS=void 0,base.endDTS=void 0,base.start=0,base.playlistOffset=0,base.deltaPTS=void 0,base.maxStartPTS=void 0,base.minEndPTS=void 0,base.data=void 0,base.bitrateTest=!1,base.title=null,base.initSegment=null,base.endList=void 0,base.gap=void 0,base.urlId=0,base.type=type,base}_inheritsLoose(Fragment,_BaseSegment2);var _proto2=Fragment.prototype;return _proto2.addStart=function(value){this.setStart(this.start+value)},_proto2.setStart=function(value){this.start=value,this._ref&&(this._ref.start=value)},_proto2.setDuration=function(value){this.duration=value,this._ref&&(this._ref.duration=value)},_proto2.setKeyFormat=function(keyFormat){this.levelkeys&&(keyFormat=this.levelkeys[keyFormat])&&!this._decryptdata&&(this._decryptdata=keyFormat.getDecryptData(this.sn))},_proto2.abortRequests=function(){var _this$loader;null!=(_this$loader=this.loader)&&_this$loader.abort(),null!=(_this$loader=this.keyLoader)&&_this$loader.abort()},_proto2.setElementaryStreamInfo=function(type,startPTS,endPTS,startDTS,endDTS,partial){void 0===partial&&(partial=!1);var elementaryStreams=this.elementaryStreams,info=elementaryStreams[type];info?(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)):elementaryStreams[type]={startPTS:startPTS,endPTS:endPTS,startDTS:startDTS,endDTS:endDTS,partial:partial}},_createClass(Fragment,[{key:"byteLength",get:function(){if(this.hasStats){var total=this.stats.total;if(total)return total}if(this.byteRange){var total=this.byteRange[0],end=this.byteRange[1];if(isFiniteNumber(total)&&isFiniteNumber(end))return end-total}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate||null},set:function(value){this._bitrate=value}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var key=this.levelkeys.identity;if(key)this._decryptdata=key.getDecryptData(this.sn);else{key=Object.keys(this.levelkeys);if(1===key.length)return this._decryptdata=this.levelkeys[key[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){var duration;return null===this.programDateTime?null:(duration=isFiniteNumber(this.duration)?this.duration:0,this.programDateTime+1e3*duration)}},{key:"encrypted",get:function(){if(null!=(_this$_decryptdata=this._decryptdata)&&_this$_decryptdata.encrypted)return!0;if(this.levelkeys){var _this$_decryptdata=Object.keys(this.levelkeys),len=_this$_decryptdata.length;if(1<len||1===len&&this.levelkeys[_this$_decryptdata[0]].encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(value){isFiniteNumber(value)?this._programDateTime=value:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return isMediaFragment(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(BaseSegment),Part=function(_BaseSegment3){function Part(partAttrs,frag,base,index,previous){base=_BaseSegment3.call(this,base)||this,base.fragOffset=0,base.duration=0,base.gap=!1,base.independent=!1,base.relurl=void 0,base.fragment=void 0,base.index=void 0,base.duration=partAttrs.decimalFloatingPoint("DURATION"),base.gap=partAttrs.bool("GAP"),base.independent=partAttrs.bool("INDEPENDENT"),base.relurl=partAttrs.enumeratedString("URI"),base.fragment=frag,base.index=index,frag=partAttrs.enumeratedString("BYTERANGE");return frag&&base.setByteRange(frag,previous),previous&&(base.fragOffset=previous.fragOffset+previous.duration),base}return _inheritsLoose(Part,_BaseSegment3),_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)}}])}(BaseSegment),UINT32_MAX$1=Math.pow(2,32)-1,push=[].push,RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4};function bin2str(data){return String.fromCharCode.apply(null,data)}function readUint16(buffer,offset){buffer=buffer[offset]<<8|buffer[offset+1];return buffer<0?65536+buffer:buffer}function readUint32(buffer,offset){buffer=readSint32(buffer,offset);return buffer<0?4294967296+buffer:buffer}function readUint64(buffer,offset){var result=readUint32(buffer,offset);return(result*=Math.pow(2,32))+readUint32(buffer,offset+4)}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]=value>>16&255,buffer[offset+2]=value>>8&255,buffer[offset+3]=255&value}function findBox(data,path){var results=[];if(path.length)for(var end=data.byteLength,i=0;i<end;){var subresults,size=readUint32(data,i),size=1<size?i+size:end;bin2str(data.subarray(i+4,i+8))===path[0]&&(1===path.length?results.push(data.subarray(i+8,size)):(subresults=findBox(data.subarray(i+8,size),path.slice(1))).length&&push.apply(results,subresults)),i=size}return results}function parseInitSegment(initSegment){for(var result=[],traks=findBox(initSegment,["moov","trak"]),i=0;i<traks.length;i++){var mdhd,hdlr,trak=traks[i],tkhd=findBox(trak,["tkhd"])[0];tkhd&&(tkhd=readUint32(tkhd,0===tkhd[0]?12:20),mdhd=findBox(trak,["mdia","mdhd"])[0])&&(mdhd=readUint32(mdhd,0===mdhd[0]?12:20),hdlr=findBox(trak,["mdia","hdlr"])[0])&&(hdlr=bin2str(hdlr.subarray(8,12)),hdlr={soun:ElementaryStreamTypes_AUDIO,vide:ElementaryStreamTypes_VIDEO}[hdlr])&&(trak=function(stsd){var sampleEntries=stsd.subarray(8),sampleEntriesEnd=sampleEntries.subarray(86),fourCC=bin2str(sampleEntries.subarray(4,8)),codec=fourCC,stsd="enca"===fourCC||"encv"===fourCC;{var encBox;stsd&&(encBox=findBox(sampleEntries,[fourCC])[0],findBox(encBox.subarray("enca"===fourCC?28:78),["sinf"]).forEach(function(sinf){var schm=findBox(sinf,["schm"])[0];!schm||"cbcs"!==(schm=bin2str(schm.subarray(4,8)))&&"cenc"!==schm||(schm=findBox(sinf,["frma"])[0])&&(codec=bin2str(schm))}))}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":avcCBox=findBox(sampleEntries,[fourCC])[0],avcCBox=findBox(avcCBox.subarray(28),["esds"])[0];if(avcCBox&&7<avcCBox.length){var i=4;if(3!==avcCBox[i++])break;i=skipBERInteger(avcCBox,i),i+=2;var flags=avcCBox[i++];if(128&flags&&(i+=2),64&flags&&(i+=avcCBox[i++]),4!==avcCBox[i++])break;i=skipBERInteger(avcCBox,i);flags=avcCBox[i++];if(64!==flags)break;if(codec+="."+toHex(flags),i+=12,5!==avcCBox[i++])break;i=skipBERInteger(avcCBox,i);var flags=avcCBox[i++],audioObjectType=(248&flags)>>3;31===audioObjectType&&(audioObjectType+=1+((7&flags)<<3)+((224&avcCBox[i])>>5)),codec+="."+audioObjectType}break;case"hvc1":case"hev1":for(var flags=findBox(sampleEntriesEnd,["hvcC"])[0],avcCBox=flags[1],i=["","A","B","C"][avcCBox>>6],audioObjectType=31&avcCBox,profileCompat=readUint32(flags,2),avcCBox=(32&avcCBox)>>5?"H":"L",levelIDC=flags[12],constraintIndicator=flags.subarray(6,12),constraintString=(codec=(codec=(codec+="."+i+audioObjectType)+("."+profileCompat.toString(16).toUpperCase()))+("."+avcCBox+levelIDC),""),_i=constraintIndicator.length;_i--;){var _byte=constraintIndicator[_i];(_byte||constraintString)&&(_byte=_byte.toString(16).toUpperCase(),constraintString="."+_byte+constraintString)}codec+=constraintString;break;case"dvh1":case"dvhe":flags=findBox(sampleEntriesEnd,["dvcC"])[0],i=flags[2]>>1&127,audioObjectType=flags[2]<<5&32|flags[3]>>3&31;codec+="."+addLeadingZero(i)+"."+addLeadingZero(audioObjectType);break;case"vp09":profileCompat=findBox(sampleEntriesEnd,["vpcC"])[0],avcCBox=profileCompat[4],levelIDC=profileCompat[5],flags=profileCompat[6]>>4&15;codec+="."+addLeadingZero(avcCBox)+"."+addLeadingZero(levelIDC)+"."+addLeadingZero(flags);break;case"av01":var i=findBox(sampleEntriesEnd,["av1C"])[0],audioObjectType=i[1]>>>5,profileCompat=31&i[1],avcCBox=i[2]>>>7?"H":"M",levelIDC=(64&i[2])>>6,flags=(32&i[2])>>5,flags=2==audioObjectType&&levelIDC?flags?12:10:levelIDC?10:8,levelIDC=(16&i[2])>>4,chromaSubsamplingX=(8&i[2])>>3,chromaSubsamplingY=(4&i[2])>>2,i=3&i[2];codec+="."+audioObjectType+"."+addLeadingZero(profileCompat)+avcCBox+"."+addLeadingZero(flags)+"."+levelIDC+"."+chromaSubsamplingX+chromaSubsamplingY+i+".01.01.01.0"}return{codec:codec,encrypted:stsd}}(findBox(trak,["mdia","minf","stbl","stsd"])[0]),result[tkhd]={timescale:mdhd,type:hdlr},result[hdlr]=_objectSpread2({timescale:mdhd,id:tkhd},trak))}return findBox(initSegment,["moov","mvex","trex"]).forEach(function(trex){var trackId=readUint32(trex,4),trackId=result[trackId];trackId&&(trackId.default={duration:readUint32(trex,12),flags:readUint32(trex,20)})}),result}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(num<10?"0":"")+num}function parseSinf(sinf){var schm=findBox(sinf,["schm"])[0];if(schm){schm=bin2str(schm.subarray(4,8));if("cbcs"===schm||"cenc"===schm)return findBox(sinf,["schi","tenc"])[0]}return 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],track=initData[readUint32(tfhd,4)];if(track)for(var trackDefault=track.default,tfhdFlags=readUint32(tfhd,0)|(null==trackDefault?void 0:trackDefault.flags),sampleDuration=null==trackDefault?void 0:trackDefault.duration,timescale=(8&tfhdFlags&&(sampleDuration=readUint32(tfhd,2&tfhdFlags?12:8)),track.timescale||9e4),truns=findBox(traf,["trun"]),j=0;j<truns.length;j++)!(rawDuration=function(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++){var sampleDuration;256&flags&&(sampleDuration=readUint32(trun,offset),duration+=sampleDuration,offset+=4),512&flags&&(offset+=4),1024&flags&&(offset+=4),2048&flags&&(offset+=4)}return duration}(truns[j]))&&sampleDuration&&(rawDuration=sampleDuration*readUint32(truns[j],4)),track.type===ElementaryStreamTypes_VIDEO?videoDuration+=rawDuration/timescale:track.type===ElementaryStreamTypes_AUDIO&&(audioDuration+=rawDuration/timescale)}if(0===videoDuration&&0===audioDuration){for(var sidxMinStart=1/0,sidxMaxEnd=0,sidxDuration=0,sidxs=findBox(data,["sidx"]),_i2=0;_i2<sidxs.length;_i2++){var subSegmentDuration,sidx=function(sidx){var references=[],version=sidx[0],index=8,timescale=readUint32(sidx,index),earliestPresentationTime=(index+=4,0),firstOffset=0,startByte=(0===version?(earliestPresentationTime=readUint32(sidx,index),firstOffset=readUint32(sidx,index+4),index+=8):(earliestPresentationTime=readUint64(sidx,index),firstOffset=readUint64(sidx,index+8),index+=16),sidx.length+firstOffset),referencesCount=readUint16(sidx,index+=2);index+=2;for(var i=0;i<referencesCount;i++){var referenceIndex=index,referenceInfo=readUint32(sidx,referenceIndex),referenceSize=(referenceIndex+=4,2147483647&referenceInfo);if(1==(2147483648&referenceInfo)>>>31)return logger.warn("SIDX has hierarchical references (not supported)"),null;referenceInfo=readUint32(sidx,referenceIndex);referenceIndex+=4,references.push({referenceSize:referenceSize,subsegmentDuration:referenceInfo,info:{duration:referenceInfo/timescale,start:startByte,end:startByte+referenceSize-1}}),startByte+=referenceSize,index=referenceIndex+=4}return{earliestPresentationTime:earliestPresentationTime,timescale:timescale,version:version,referencesCount:referencesCount,references:references}}(sidxs[_i2]);null!=sidx&&sidx.references&&(sidxMinStart=Math.min(sidxMinStart,sidx.earliestPresentationTime/sidx.timescale),subSegmentDuration=sidx.references.reduce(function(dur,ref){return dur+ref.info.duration||0},0),sidxDuration=(sidxMaxEnd=Math.max(sidxMaxEnd,subSegmentDuration+sidx.earliestPresentationTime/sidx.timescale))-sidxMinStart)}if(sidxDuration&&isFiniteNumber(sidxDuration))return sidxDuration}return videoDuration||audioDuration}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;return findBox(videoData,["moof"]).map(function(moof){var moofOffset=moof.byteOffset-8;findBox(moof,["traf"]).map(function(traf){var baseTime=findBox(traf,["tfdt"]).map(function(tfdt){var version=tfdt[0],result=readUint32(tfdt,4);return(result=1===version?(result*=Math.pow(2,32))+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&&(id=track.codec,isHEVCFlavor=!!id&&("hvc1"===(id=(tfhd=id.indexOf("."))<0?id:id.substring(0,tfhd))||"hev1"===id||"dvh1"===id||"dvhe"===id)),findBox(traf,["trun"]).map(function(trun){for(var version=trun[0],flags=16777215&readUint32(trun,0),dataOffset=0,sampleDurationPresent=0!=(256&flags),sampleDuration=0,sampleSizePresent=0!=(512&flags),sampleSize=0,sampleFlagsPresent=0!=(1024&flags),sampleCompositionOffsetsPresent=0!=(2048&flags),compositionOffset=0,sampleCount=readUint32(trun,4),trunOffset=8,sampleOffset=(0!=(1&flags)&&(dataOffset=readUint32(trun,trunOffset),trunOffset+=4),0!=(4&flags)&&(trunOffset+=4),dataOffset+moofOffset),ix=0;ix<sampleCount;ix++){if(sampleDurationPresent?(sampleDuration=readUint32(trun,trunOffset),trunOffset+=4):sampleDuration=defaultSampleDuration,sampleSizePresent?(sampleSize=readUint32(trun,trunOffset),trunOffset+=4):sampleSize=defaultSampleSize,sampleFlagsPresent&&(trunOffset+=4),sampleCompositionOffsetsPresent&&(compositionOffset=(0===version?readUint32:readSint32)(trun,trunOffset),trunOffset+=4),track.type===ElementaryStreamTypes_VIDEO)for(var naluTotalSize=0;naluTotalSize<sampleSize;){var naluSize=readUint32(videoData,sampleOffset);!function(isHEVCFlavor,naluHeader){return isHEVCFlavor?39==(isHEVCFlavor=naluHeader>>1&63)||40==isHEVCFlavor:6==(31&naluHeader)}(isHEVCFlavor,videoData[sampleOffset+=4])||parseSEIMessageFromNALu(videoData.subarray(sampleOffset,sampleOffset+naluSize),isHEVCFlavor?2:1,timeOffset+compositionOffset/timescale,seiSamples),sampleOffset+=naluSize,naluTotalSize+=naluSize+4}timeOffset+=sampleDuration/timescale}}))})})}),seiSamples}function parseSEIMessageFromNALu(unescapedData,headerSize,pts,samples){for(var data=discardEPB(unescapedData),seiPtr=0,payloadType=(seiPtr+=headerSize,0),payloadSize=0,b=0;seiPtr<data.length;){for(payloadType=0;!(seiPtr>=data.length)&&(payloadType+=b=data[seiPtr++],255===b););for(payloadSize=0;!(seiPtr>=data.length)&&(payloadSize+=b=data[seiPtr++],255===b););var leftOver=data.length-seiPtr,payPtr=seiPtr;if(payloadSize<leftOver)seiPtr+=payloadSize;else if(leftOver<payloadSize){logger.error("Malformed SEI payload. "+payloadSize+" is too small, only "+leftOver+" bytes left to parse.");break}if(4===payloadType){if(181===data[payPtr++]){leftOver=readUint16(data,payPtr);if(payPtr+=2,49===leftOver){leftOver=readUint32(data,payPtr);if(payPtr+=4,1195456820===leftOver){leftOver=data[payPtr++];if(3===leftOver){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:leftOver,payloadType:payloadType,pts:pts,bytes:byteArray})}}}}}else if(5===payloadType&&16<payloadSize){for(var uuidStrArray=[],_i3=0;_i3<16;_i3++){var _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;for(var newLength=length-EPBPositions.length,newData=new Uint8Array(newLength),sourceIndex=0,i=0;i<newLength;sourceIndex++,i++)sourceIndex===EPBPositions[0]&&(sourceIndex++,EPBPositions.shift()),newData[i]=data[sourceIndex];return newData}function mp4pssh(systemId,keyids,data){if(16!==systemId.byteLength)throw new RangeError("Invalid system id");var kids=new Uint8Array,kidCount=new Uint8Array,dataSize=new Uint8Array(4);return data&&0<data.byteLength&&new DataView(dataSize.buffer).setUint32(0,data.byteLength,!1),function(type){for(var _len=arguments.length,payload=new 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]=size>>24&255,result[1]=size>>16&255,result[2]=size>>8&255,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}([112,115,115,104],new Uint8Array([0,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 pssh=function(view){var size=view.getUint32(0),offset=view.byteOffset,length=view.byteLength;if(length<size)return{offset:offset,size:length};if(1886614376!==view.getUint32(4))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,view=null;if(0==version){if(size-32<dataSizeOrKidCount||dataSizeOrKidCount<22)return{offset:offset,size:size};view=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:view,offset:offset,size:size}}(new DataView(initData,offset));results.push(pssh),offset+=pssh.size}return results}var Decrypter=function(){function Decrypter(config,_temp){_temp=(void 0===_temp?{}:_temp).removePKCS7Padding,_temp=void 0===_temp||_temp;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.enableSoftwareAES=void 0,this.enableSoftwareAES=config.enableSoftwareAES,this.removePKCS7Padding=_temp)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 outputBytes,paddingBytes,currentResult=this.currentResult,remainderData=this.remainderData;return!currentResult||remainderData?(this.reset(),null):(remainderData=new Uint8Array(currentResult),this.reset(),this.removePKCS7Padding?(outputBytes=(currentResult=remainderData).byteLength,(paddingBytes=outputBytes&&new DataView(currentResult.buffer).getUint8(outputBytes-1))?sliceUint8(currentResult,0,outputBytes-paddingBytes):currentResult):remainderData)},_proto.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},_proto.decrypt=function(data,key,iv,aesMode){var _this=this;return this.useSoftware?new Promise(function(resolve,reject){var dataView=ArrayBuffer.isView(data)?data:new Uint8Array(data),dataView=(_this.softwareDecrypt(dataView,key,iv,aesMode),_this.flush());dataView?resolve(dataView.buffer):reject(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(data),key,iv,aesMode)},_proto.softwareDecrypt=function(data,key,iv,aesMode){var currentIV=this.currentIV,currentResult=this.currentResult,remainderData=this.remainderData;if(aesMode!==DecrypterAesMode_cbc||16!==key.byteLength)return logger.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),remainderData&&(data=appendUint8Array(remainderData,data),this.remainderData=null);aesMode=this.getValidChunk(data);if(!aesMode.length)return null;currentIV&&(iv=currentIV);remainderData=this.softwareDecrypter,(remainderData=remainderData||(this.softwareDecrypter=new AESDecryptor)).expandKey(key),data=currentResult;return this.currentResult=remainderData.decrypt(aesMode.buffer,0,iv),this.currentIV=sliceUint8(aesMode,-16).buffer,data||null},_proto.webCryptoDecrypt=function(data,key,iv,aesMode){var _this2=this;if(this.key!==key||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(data,key,iv,aesMode));this.key=key,this.fastAesKey=new FastAESKey(this.subtle,key,aesMode)}return this.fastAesKey.expandKey().then(function(aesKey){return _this2.subtle?(_this2.logOnce("WebCrypto AES decrypt"),new AESCrypto(_this2.subtle,new Uint8Array(iv),aesMode).decrypt(data.buffer,aesKey)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(err){return logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+err.name+": "+err.message),_this2.onWebCryptoError(data,key,iv,aesMode)})},_proto.onWebCryptoError=function(data,key,iv,aesMode){var enableSoftwareAES=this.enableSoftwareAES;if(enableSoftwareAES){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(data,key,iv,aesMode);data=this.flush();if(data)return data.buffer}throw new Error("WebCrypto"+(enableSoftwareAES?" 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}(),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=new(FragmentILoader||DefaultILoader)(config),loaderContext=createLoaderContext(frag),loadPolicy=(frag.loader=loader,getLoaderConfigWithoutReties(config.fragLoadPolicy.default)),loaderConfig={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===frag.sn?1/0:MIN_CHUNK_SIZE},loadPolicy=(frag.stats=loader.stats,{onSuccess:function(response,stats,context,networkDetails){_this.resetLoader(frag,loader);response=response.data;context.resetIV&&frag.decryptdata&&(frag.decryptdata.iv=new Uint8Array(response.slice(0,16)),response=response.slice(16)),resolve({frag:frag,part:null,payload:response,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&&(loadPolicy.onProgress=function(stats,context,data,networkDetails){return onProgress({frag:frag,part:null,payload:data,networkDetails:networkDetails})}),loader.load(loaderContext,loaderConfig,loadPolicy)})},_proto.loadPart=function(frag,part,onProgress){var _this2=this,config=(this.abort(),this.config),FragmentILoader=config.fLoader,DefaultILoader=config.loader;return new Promise(function(resolve,reject){var loader,loaderContext,loadPolicy,loaderConfig;_this2.loader&&_this2.loader.destroy(),frag.gap||part.gap?reject(createGapLoadError(frag,part)):(loader=_this2.loader=new(FragmentILoader||DefaultILoader)(config),loaderContext=createLoaderContext(frag,part),frag.loader=loader,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);response={frag:frag,part:part,payload:response.data,networkDetails:networkDetails};onProgress(response),resolve(response)},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,frag=(fragStats.loaded+=partStats.loaded,partTotal?(partTotal=((frag=Math.round(frag.duration/part.duration))-(part=Math.min(Math.round(fragStats.loaded/partTotal),frag)))*Math.round(fragStats.loaded/part),fragStats.total=fragStats.loaded+partTotal):fragStats.total=Math.max(fragStats.loaded,fragStats.total),fragStats.loading),part=partStats.loading;frag.start?frag.first+=part.first-part.start:(frag.start=part.start,frag.first=part.first),frag.end=part.end},_proto.resetLoader=function(frag,loader){frag.loader=null,this.loader===loader&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),loader.destroy()},FragmentLoader}();function createLoaderContext(frag,part){var byteRangeStart,byteRangeEnd,segment=(part=void 0===part?null:part)||frag,part={frag:frag,part:part,responseType:"arraybuffer",url:segment.url,headers:{},rangeStart:0,rangeEnd:0},start=segment.byteRangeStartOffset,segment=segment.byteRangeEndOffset;return isFiniteNumber(start)&&isFiniteNumber(segment)&&(byteRangeStart=start,byteRangeEnd=segment,"initSegment"!==frag.sn||"AES-128"!==(frag=null==(frag=frag.decryptdata)?void 0:frag.method)&&"AES-256"!==frag||((frag=segment-start)%16&&(byteRangeEnd=segment+(16-frag%16)),0!==start&&(part.resetIV=!0,byteRangeStart=start-16)),part.rangeStart=byteRangeStart,part.rangeEnd=byteRangeEnd),part}function createGapLoadError(frag,part){var error=new Error("GAP "+(frag.gap?"tag":"attribute")+" found"),error={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:frag,error:error,networkDetails:null};return part&&(error.part=part),(part||frag).stats.aborted=!0,new LoadError(error)}function ChunkMetadata(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}var LoadError=function(_Error){function LoadError(data){var _this3=_Error.call(this,data.error.message)||this;return _this3.data=void 0,_this3.data=data,_this3}return _inheritsLoose(LoadError,_Error),LoadError}(_wrapNativeSuper(Error)),BaseSegment=function(_Logger){function TaskLoop(label,logger){label=_Logger.call(this,label,logger)||this;return label._boundTick=void 0,label._tickTimer=null,label._tickInterval=null,label._tickCallCount=0,label._boundTick=label.tick.bind(label),label}_inheritsLoose(TaskLoop,_Logger);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))},_proto.clearNextTick=function(){return!(!this._tickTimer||(self.clearTimeout(this._tickTimer),this._tickTimer=null))},_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}(Logger);function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}var noopBuffered={length:0,start:function(){return 0},end:function(){return 0}},BufferHelper=function(){function BufferHelper(){}return BufferHelper.isBuffered=function(media,position){if(media)for(var buffered=BufferHelper.getBuffered(media),i=buffered.length;i--;)if(position>=buffered.start(i)&&position<=buffered.end(i))return!0;return!1},BufferHelper.bufferInfo=function(media,pos,maxHoleDuration){if(media){var vbuffered=BufferHelper.getBuffered(media);if(vbuffered.length){for(var buffered=[],i=0;i<vbuffered.length;i++)buffered.push({start:vbuffered.start(i),end:vbuffered.end(i)});return BufferHelper.bufferedInfo(buffered,pos,maxHoleDuration)}}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){return a.start-b.start||b.end-a.end});var buffered2=[];if(maxHoleDuration)for(var i=0;i<buffered.length;i++){var buf2end,buf2len=buffered2.length;buf2len&&(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=buffered;for(var bufferStartNext,bufferLen=0,bufferStart=pos,bufferEnd=pos,_i=0;_i<buffered2.length;_i++){var start=buffered2[_i].start,end=buffered2[_i].end;if(start<=pos+maxHoleDuration&&pos<end)bufferStart=start,bufferLen=(bufferEnd=end)-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||noopBuffered}catch(e){return logger.log("failed to get media.buffered",e),noopBuffered}},BufferHelper}(),VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(str){return VARIABLE_REPLACEMENT_REGEX.test(str)}function substituteVariables(parsed,value){var variableList;return null!==parsed.variableList||parsed.hasVariableRefs?(variableList=parsed.variableList,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})):value}function addVariableDefinition(parsed,attr,parentUrl){var NAME,VALUE,variableList=parsed.variableList;if(variableList||(parsed.variableList=variableList={}),"QUERYPARAM"in attr){NAME=attr.QUERYPARAM;try{var searchParams=new self.URL(parentUrl).searchParams;if(!searchParams.has(NAME))throw new Error('"'+NAME+'" does not match any query parameter in URI: "'+parentUrl+'"');VALUE=searchParams.get(NAME)}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||""}var DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g,AttrList=function(){function AttrList(attrs,parsed){_extends(this,attrs="string"==typeof attrs?AttrList.parseAttrList(attrs,parsed):attrs)}var _proto=AttrList.prototype;return _proto.decimalInteger=function(attrName){attrName=parseInt(this[attrName],10);return attrName>Number.MAX_SAFE_INTEGER?1/0:attrName},_proto.hexadecimalInteger=function(attrName){if(this[attrName]){for(var stringValue=(1&(stringValue=(this[attrName]||"0x").slice(2)).length?"0":"")+stringValue,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){attrName=parseInt(this[attrName],16);return attrName>Number.MAX_SAFE_INTEGER?1/0:attrName},_proto.decimalFloatingPoint=function(attrName){return parseFloat(this[attrName])},_proto.optionalFloat=function(attrName,defaultValue){attrName=this[attrName];return attrName?parseFloat(attrName):defaultValue},_proto.enumeratedString=function(attrName){return this[attrName]},_proto.enumeratedStringList=function(attrName,dict){attrName=this[attrName];return(attrName?attrName.split(/[ ,]+/):[]).reduce(function(result,identifier){return result[identifier.toLowerCase()]=!0,result},dict)},_proto.bool=function(attrName){return"YES"===this[attrName]},_proto.decimalResolution=function(attrName){attrName=DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);if(null!==attrName)return{width:parseInt(attrName[1],10),height:parseInt(attrName[2],10)}},AttrList.parseAttrList=function(input,parsed){var attrs={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(match=ATTR_LIST_REGEX.exec(input));){var name=match[1].trim(),value=match[2],match=0===value.indexOf('"')&&value.lastIndexOf('"')===value.length-1,hexadecimalSequence=!1;if(match)value=value.slice(1,-1);else switch(name){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":hexadecimalSequence=!0}if(parsed&&(match||hexadecimalSequence))value=substituteVariables(parsed,value);else if(!hexadecimalSequence&&!match)switch(name){case"CLOSED-CAPTIONS":if("NONE"===value)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":logger.warn(input+": attribute "+name+" is missing quotes")}attrs[name]=value}return attrs},_createClass(AttrList,[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(attr){return"X-"===attr.substring(0,2)})}}])}();var DateRange=function(){return _createClass(function(dateRangeAttr,dateRangeWithSameId,tagCount){var _dateRangeWithSameId$;if(void 0===tagCount&&(tagCount=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==dateRangeWithSameId?void 0:dateRangeWithSameId.tagAnchor)||null,this.tagOrder=null!=(_dateRangeWithSameId$=null==dateRangeWithSameId?void 0:dateRangeWithSameId.tagOrder)?_dateRangeWithSameId$:tagCount,dateRangeWithSameId){var key,previousAttr=dateRangeWithSameId.attr;for(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)}this.attr=dateRangeAttr,dateRangeWithSameId?(this._startDate=dateRangeWithSameId._startDate,this._cue=dateRangeWithSameId._cue,this._endDate=dateRangeWithSameId._endDate,this._dateAtEnd=dateRangeWithSameId._dateAtEnd):this._startDate=new Date(dateRangeAttr["START-DATE"]),"END-DATE"in this.attr&&(_dateRangeWithSameId$=(null==dateRangeWithSameId?void 0:dateRangeWithSameId.endDate)||new Date(this.attr["END-DATE"]),isFiniteNumber(_dateRangeWithSameId$.getTime()))&&(this._endDate=_dateRangeWithSameId$)},[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var _cue=this._cue;return void 0===_cue?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):_cue}},{key:"startTime",get:function(){var tagAnchor=this.tagAnchor;return null===tagAnchor||null===tagAnchor.programDateTime?(logger.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+tagAnchor),NaN):tagAnchor.start+(this.startDate.getTime()-tagAnchor.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var dateAtEnd=this._endDate||this._dateAtEnd;return dateAtEnd||(null!==(dateAtEnd=this.duration)?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*dateAtEnd):null)}},{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:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(this.startDate.getTime())&&(null===this.duration||0<=this.duration)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}])}(),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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,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.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=baseUrl}return LevelDetails.prototype.reloaded=function(previous){var partSnDiff,partIndexDiff;previous?(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.updated||this.advanced?this.misses=Math.floor(.6*previous.misses):this.misses=previous.misses+1,this.availabilityDelay=previous.availabilityDelay):(this.advanced=!0,this.updated=!0)},_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.driftStartTime;return 0<runTime?1e3*(this.driftEnd-this.driftStart)/runTime: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:"fragmentStart",get:function(){var _this$fragments2;return null!=(_this$fragments2=this.fragments)&&_this$fragments2.length?this.fragments[0].start: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:"maxPartIndex",get:function(){var partList=this.partList;if(partList){var lastIndex=this.lastPartIndex;if(-1!==lastIndex){for(var i=partList.length;i--;)if(partList[i].index>lastIndex)return partList[i].index;return lastIndex}}return 0}},{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}},{key:"expired",get:function(){var playlistWindowDuration;return!(!this.live||!this.age)&&(playlistWindowDuration=this.partEnd-this.fragmentStart,this.age>Math.max(playlistWindowDuration,this.totalduration)+this.levelTargetDuration)}}])}();function isFullSegmentEncryption(method){return"AES-128"===method||"AES-256"===method||"AES-256-CTR"===method}function getAesModeFromFullSegmentMethod(method){switch(method){case"AES-128":case"AES-256":return DecrypterAesMode_cbc;case"AES-256-CTR":return DecrypterAesMode_ctr;default:throw new Error("invalid full segment method "+method)}}function base64Decode(base64encodedStr){return Uint8Array.from(atob(base64encodedStr),function(c){return c.charCodeAt(0)})}function strToUtf8array(str){return Uint8Array.from(unescape(encodeURIComponent(str)),function(c){return c.charCodeAt(0)})}function changeEndianness(keyId){function swap(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 commasplit,isbase64,uri=uri.split(":"),keydata=null;return"data"===uri[0]&&2===uri.length&&2===(commasplit=(uri=uri[1].split(";"))[uri.length-1].split(",")).length&&(isbase64="base64"===commasplit[0],commasplit=commasplit[1],keydata=isbase64?(uri.splice(-1,1),base64Decode(commasplit)):(isbase64=strToUtf8array(isbase64=commasplit).subarray(0,16),(uri=new Uint8Array(16)).set(isbase64,16-isbase64.length),uri)),keydata}var optionalSelf="undefined"!=typeof self?self:void 0,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"};function keySystemFormatToKeySystemDomain(format){switch(format){case KeySystemFormats.FAIRPLAY:return KeySystems.FAIRPLAY;case KeySystemFormats.PLAYREADY:return KeySystems.PLAYREADY;case KeySystemFormats.WIDEVINE:return KeySystems.WIDEVINE;case KeySystemFormats.CLEARKEY:return KeySystems.CLEARKEY}}var KeySystemIds={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};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){switch(keySystem){case KeySystems.FAIRPLAY:return KeySystemFormats.FAIRPLAY;case KeySystems.PLAYREADY:return KeySystemFormats.PLAYREADY;case KeySystems.WIDEVINE:return KeySystemFormats.WIDEVINE;case KeySystems.CLEARKEY:return KeySystemFormats.CLEARKEY}}function getKeySystemsForConfig(config){var drmSystems=config.drmSystems,config=config.widevineLicenseUrl,keySystemsToAttempt=drmSystems?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter(function(keySystem){return!!drmSystems[keySystem]}):[];return!keySystemsToAttempt[KeySystems.WIDEVINE]&&config&&keySystemsToAttempt.push(KeySystems.WIDEVINE),keySystemsToAttempt}var requestMediaKeySystemAccess=null!=optionalSelf&&null!=(_optionalSelf$navigat=optionalSelf.navigator)&&_optionalSelf$navigat.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function parsePlayReadyWRM(keyBytes){keyBytes=new Uint16Array(keyBytes.buffer,keyBytes.byteOffset,keyBytes.byteLength/2),keyBytes=String.fromCharCode.apply(null,Array.from(keyBytes)),keyBytes=keyBytes.substring(keyBytes.indexOf("<"),keyBytes.length),keyBytes=(new DOMParser).parseFromString(keyBytes,"text/xml").getElementsByTagName("KID")[0];if(keyBytes){var keyBytes=keyBytes.childNodes[0]?keyBytes.childNodes[0].nodeValue:keyBytes.getAttribute("VALUE");if(keyBytes)return changeEndianness(keyBytes=base64Decode(keyBytes).subarray(0,16)),keyBytes}return null}var 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&&!isFullSegmentEncryption(method)}LevelKey.clearKeyUriToKeyIdMap=function(){keyUriToKeyIdMap={}};var _proto=LevelKey.prototype;return _proto.isSupported=function(){if(this.method){if(isFullSegmentEncryption(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.CLEARKEY: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(isFullSegmentEncryption(this.method)&&this.uri&&!this.iv)return"number"!=typeof sn&&(logger.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),sn=0),sn=function(segmentNumber){for(var uint8View=new Uint8Array(16),i=12;i<16;i++)uint8View[i]=segmentNumber>>8*(15-i)&255;return uint8View}(sn),new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,sn);var val,keyBytes=convertDataUriToArrayBytes(this.uri);if(keyBytes)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:22<=(this.pssh=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,0,keyBytes),this.keyId=parsePlayReadyWRM(keyBytes);break;default:var padded,PlayReadyKeySystemUUID=keyBytes.subarray(0,16);16!==PlayReadyKeySystemUUID.length&&((padded=new Uint8Array(16)).set(PlayReadyKeySystemUUID,16-PlayReadyKeySystemUUID.length),PlayReadyKeySystemUUID=padded),this.keyId=PlayReadyKeySystemUUID}return this.keyId&&16===this.keyId.byteLength||((sn=keyUriToKeyIdMap[this.uri])||(val=Object.keys(keyUriToKeyIdMap).length%Number.MAX_SAFE_INTEGER,sn=new Uint8Array(16),new DataView(sn.buffer,12,4).setUint32(0,val),keyUriToKeyIdMap[this.uri]=sn),this.keyId=sn),this},LevelKey}();var 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,/#.*/.source].join("|"),"g"),LEVEL_PLAYLIST_REGEX_SLOW=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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;i<groups.length;i++){var group=groups[i];if(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 result,parsed={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hasVariableReferences(string)},levelsWithKnownCodecs=[];for(MASTER_PLAYLIST_REGEX.lastIndex=0;null!=(result=MASTER_PLAYLIST_REGEX.exec(string));)if(result[1]){var attrs=new AttrList(result[1],parsed),uri=substituteVariables(parsed,result[2]),uri={attrs:attrs,bitrate:attrs.decimalInteger("BANDWIDTH")||attrs.decimalInteger("AVERAGE-BANDWIDTH"),name:attrs.NAME,url:M3U8Parser.resolve(uri,baseurl)},resolution=attrs.decimalResolution("RESOLUTION");resolution&&(uri.width=resolution.width,uri.height=resolution.height),!function(codecsAttributeValue,level){var codecs=(codecsAttributeValue||"").split(/[ ,]+/).filter(function(c){return c});["video","audio","text"].forEach(function(type){var filtered=codecs.filter(function(codec){return function(codec,type){return!!(type=sampleEntryCodesISO[type])&&!!type[codec.slice(0,4)]}(codec,type)});filtered.length&&(level[type+"Codec"]=filtered.join(","),codecs=codecs.filter(function(codec){return-1===filtered.indexOf(codec)}))}),level.unknownCodecs=codecs}(attrs.CODECS,uri),null!=(resolution=uri.unknownCodecs)&&resolution.length||levelsWithKnownCodecs.push(uri),parsed.levels.push(uri)}else if(result[3]){var attrs=result[3],attributes=result[4];switch(attrs){case"SESSION-DATA":var sessionAttrs=new AttrList(attributes,parsed),dataId=sessionAttrs["DATA-ID"];dataId&&(null===parsed.sessionData&&(parsed.sessionData={}),parsed.sessionData[dataId]=sessionAttrs);break;case"SESSION-KEY":dataId=parseKey(attributes,baseurl,parsed);dataId.encrypted&&dataId.isSupported()?(null===parsed.sessionKeys&&(parsed.sessionKeys=[]),parsed.sessionKeys.push(dataId)):logger.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+attributes+'"');break;case"DEFINE":addVariableDefinition(parsed,new AttrList(attributes,parsed),baseurl);break;case"CONTENT-STEERING":sessionAttrs=new AttrList(attributes,parsed);parsed.contentSteering={uri:M3U8Parser.resolve(sessionAttrs["SERVER-URI"],baseurl),pathwayId:sessionAttrs["PATHWAY-ID"]||"."};break;case"START":parsed.startTimeOffset=parseStartTimeOffset(attributes)}}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;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(result=MASTER_PLAYLIST_MEDIA_REGEX.exec(string));){var groups,medias,assocLang,channels,characteristics,instreamId,lang,result=new AttrList(result[1],parsed),type=result.TYPE;type&&(groups=groupsByType[type],medias=results[type]||[],results[type]=medias,lang=result.LANGUAGE,assocLang=result["ASSOC-LANGUAGE"],channels=result.CHANNELS,characteristics=result.CHARACTERISTICS,instreamId=result["INSTREAM-ID"],type={attrs:result,bitrate:0,id:id++,groupId:result["GROUP-ID"]||"",name:result.NAME||lang||"",type:type,default:result.bool("DEFAULT"),autoselect:result.bool("AUTOSELECT"),forced:result.bool("FORCED"),lang:lang,url:result.URI?M3U8Parser.resolve(result.URI,baseurl):""},assocLang&&(type.assocLang=assocLang),channels&&(type.channels=channels),characteristics&&(type.characteristics=characteristics),instreamId&&(type.instreamId=instreamId),null!=groups&&groups.length&&(assignCodec(type,lang=M3U8Parser.findGroup(groups,type.groupId)||groups[0],"audioCodec"),assignCodec(type,lang,"textCodec")),medias.push(type))}return results},M3U8Parser.parseLevelPlaylist=function(string,baseurl,id,type,levelUrlId,multivariantVariableList){var result,i,levelkeys,base={url:baseurl},level=new LevelDetails(baseurl),fragments=level.fragments,programDateTimes=[],currentInitSegment=null,currentSN=0,currentPart=0,totalduration=0,discontinuityCounter=0,currentBitrate=0,prevFrag=null,frag=new Fragment(type,base),firstPdtIndex=-1,createNextFrag=!1,nextByteRange=null;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,base)).playlistOffset=totalduration,frag.start=totalduration,frag.sn=currentSN,frag.cc=discontinuityCounter,currentBitrate&&(frag.bitrate=currentBitrate),frag.level=id,currentInitSegment)&&((frag.initSegment=currentInitSegment).rawProgramDateTime&&(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])isFiniteNumber(frag.duration)&&(frag.playlistOffset=totalduration,frag.start=totalduration,levelkeys&&setFragLevelKeys(frag,levelkeys,level),frag.sn=currentSN,frag.level=id,frag.cc=discontinuityCounter,fragments.push(frag),title=(" "+result[3]).slice(1),frag.relurl=substituteVariables(level,title),assignProgramDateTime(frag,prevFrag,programDateTimes),totalduration+=(prevFrag=frag).duration,currentSN++,createNextFrag=!(currentPart=0));else if(result=result[0].match(LEVEL_PLAYLIST_REGEX_SLOW)){for(i=1;i<result.length&&void 0===result[i];i++);var tag=(" "+result[i]).slice(1),value1=(" "+result[i+1]).slice(1),value2=result[i+2]?(" "+result[i+2]).slice(1):null;switch(tag){case"BYTERANGE":prevFrag?frag.setByteRange(value1,prevFrag):frag.setByteRange(value1);break;case"PROGRAM-DATE-TIME":frag.rawProgramDateTime=value1,frag.tagList.push(["PROGRAM-DATE-TIME",value1]),-1===firstPdtIndex&&(firstPdtIndex=fragments.length);break;case"PLAYLIST-TYPE":level.type=value1.toUpperCase();break;case"MEDIA-SEQUENCE":currentSN=level.startSN=parseInt(value1);break;case"SKIP":level.skippedSegments&&(level.playlistParsingError=new Error("#EXT-X-SKIP MUST NOT appear more than once in a Playlist"));var skipAttrs=new AttrList(value1,level),skippedSegments=skipAttrs.decimalInteger("SKIPPED-SEGMENTS");if(isFiniteNumber(skippedSegments)){level.skippedSegments+=skippedSegments;for(var _i=skippedSegments;_i--;)fragments.push(null);currentSN+=skippedSegments}skippedSegments=skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");skippedSegments&&(level.recentlyRemovedDateranges=(level.recentlyRemovedDateranges||[]).concat(skippedSegments.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]),currentBitrate=1e3*parseInt(value1),isFiniteNumber(currentBitrate)?frag.bitrate=currentBitrate:currentBitrate=0;break;case"DATERANGE":skipAttrs=new AttrList(value1,level),skippedSegments=new DateRange(skipAttrs,level.dateRanges[skipAttrs.ID],level.dateRangeTagCount);level.dateRangeTagCount++,skippedSegments.isValid||level.skippedSegments?level.dateRanges[skippedSegments.id]=skippedSegments:logger.warn('Ignoring invalid DATERANGE tag: "'+value1+'"'),frag.tagList.push(["EXT-X-DATERANGE",value1]);break;case"DEFINE":var variableAttributes=new AttrList(value1,level);"IMPORT"in variableAttributes?(parsed=level,sourceVariableList=multivariantVariableList,variableList=void 0,attr=(attr=variableAttributes).IMPORT,sourceVariableList&&attr in sourceVariableList?((variableList=parsed.variableList)||(parsed.variableList=variableList={}),variableList[attr]=sourceVariableList[attr]):parsed.playlistParsingError||(parsed.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+attr+'"'))):addVariableDefinition(level,variableAttributes,baseurl);break;case"DISCONTINUITY-SEQUENCE":level.startCC=discontinuityCounter=parseInt(value1);break;case"KEY":var variableList=parseKey(value1,baseurl,level);if(variableList.isSupported()){if("NONE"===variableList.method){levelkeys=void 0;break}(levelkeys=(levelkeys=levelkeys||{})[variableList.keyFormat]?_extends({},levelkeys):levelkeys)[variableList.keyFormat]=variableList}else logger.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+value1+'"');break;case"START":level.startTimeOffset=parseStartTimeOffset(value1);break;case"MAP":var parsed,attr,sourceVariableList=new AttrList(value1,level);frag.duration?(setInitSegment(parsed=new Fragment(type,base),sourceVariableList,id,levelkeys),(frag.initSegment=currentInitSegment=parsed).rawProgramDateTime&&!frag.rawProgramDateTime&&(frag.rawProgramDateTime=currentInitSegment.rawProgramDateTime)):(nextByteRange=(attr=frag.byteRangeEndOffset)?attr-(variableAttributes=frag.byteRangeStartOffset)+"@"+variableAttributes:null,setInitSegment(frag,sourceVariableList,id,levelkeys),currentInitSegment=frag,createNextFrag=!0),currentInitSegment.cc=discontinuityCounter;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":serverControlAttrs=new AttrList(value1);level.partTarget=serverControlAttrs.decimalFloatingPoint("PART-TARGET");break;case"PART":var partList=(partList=level.partList)||(level.partList=[]),previousFragmentPart=0<currentPart?partList[partList.length-1]:void 0,index=currentPart++,partAttrs=new AttrList(value1,level),partAttrs=new Part(partAttrs,frag,base,index,previousFragmentPart);partList.push(partAttrs),frag.duration+=partAttrs.duration;break;case"PRELOAD-HINT":index=new AttrList(value1,level);level.preloadHint=index;break;case"RENDITION-REPORT":previousFragmentPart=new AttrList(value1,level);level.renditionReports=level.renditionReports||[],level.renditionReports.push(previousFragmentPart);break;default:logger.warn("line parsed but not handled: "+result)}}else logger.warn("No matches on slow regex match for level playlist!")}prevFrag&&!prevFrag.relurl?(fragments.pop(),totalduration-=prevFrag.duration,level.partList&&(level.fragmentHint=prevFrag)):level.partList&&(assignProgramDateTime(frag,prevFrag,programDateTimes),frag.cc=discontinuityCounter,level.fragmentHint=frag,levelkeys)&&setFragLevelKeys(frag,levelkeys,level);var fragmentLength=fragments.length,firstFragment=fragments[0],lastFragment=fragments[fragmentLength-1];return 0<(totalduration+=level.skippedSegments*level.targetduration)&&fragmentLength&&lastFragment?(level.averagetargetduration=totalduration/fragmentLength,fragmentLength=lastFragment.sn,level.endSN="initSegment"!==fragmentLength?fragmentLength:0,level.live||(lastFragment.endList=!0),firstFragment&&!level.startCC&&(level.startCC=firstFragment.cc),0<firstPdtIndex&&(function(fragments,firstPdtIndex){for(var fragPrev=fragments[firstPdtIndex],i=firstPdtIndex;i--;){var frag=fragments[i];if(!frag)return;frag.programDateTime=fragPrev.programDateTime-1e3*frag.duration,fragPrev=frag}}(fragments,firstPdtIndex),firstFragment)&&programDateTimes.unshift(firstFragment)):(level.endSN=0,level.startCC=0),level.fragmentHint&&(totalduration+=level.fragmentHint.duration),level.totalduration=totalduration,programDateTimes.length&&level.dateRangeTagCount&&firstFragment&&mapDateRanges(programDateTimes,level),level.endCC=discontinuityCounter,level},M3U8Parser}();function mapDateRanges(programDateTimes,details){for(var programDateTimeCount=programDateTimes.length,lastProgramDateTime=programDateTimes[programDateTimeCount-1],playlistEnd=details.live?1/0:details.totalduration,dateRangeIds=Object.keys(details.dateRanges),i=dateRangeIds.length;i--;){var dateRange=details.dateRanges[dateRangeIds[i]],startDateTime=dateRange.startDate.getTime();dateRange.tagAnchor=lastProgramDateTime.ref;for(var j=programDateTimeCount;j--;){var fragIndex=function(details,startDateTime,programDateTimes,index,endTime){var pdtFragment=programDateTimes[index];if(pdtFragment){var pdtStart=pdtFragment.programDateTime;if(pdtStart<=startDateTime||0===index){var _programDateTimes=((null==(_programDateTimes=programDateTimes[index+1])?void 0:_programDateTimes.start)||endTime)-pdtFragment.start;if(startDateTime<=pdtStart+1e3*_programDateTimes){var startIndex=programDateTimes[index].sn-details.startSN,fragments=details.fragments;if(fragments.length>programDateTimes.length)for(var i=(programDateTimes[index+1]||fragments[fragments.length-1]).sn-details.startSN;startIndex<i;i--){var fragStartDateTime=fragments[i].programDateTime;if(fragStartDateTime<=startDateTime&&startDateTime<fragStartDateTime+1e3*fragments[i].duration)return i}return startIndex}}}return-1}(details,startDateTime,programDateTimes,j,playlistEnd);if(-1!==fragIndex){dateRange.tagAnchor=details.fragments[fragIndex].ref;break}}}}function parseKey(keyTagAttributes,baseurl,parsed){var keyTagAttributes=new AttrList(keyTagAttributes,parsed),parsed=null!=(parsed=keyTagAttributes.METHOD)?parsed:"",decrypturi=keyTagAttributes.URI,decryptiv=keyTagAttributes.hexadecimalInteger("IV"),decryptkeyformatversions=keyTagAttributes.KEYFORMATVERSIONS,_keyAttrs$KEYFORMAT=null!=(_keyAttrs$KEYFORMAT=keyTagAttributes.KEYFORMAT)?_keyAttrs$KEYFORMAT:"identity",keyTagAttributes=(decrypturi&&keyTagAttributes.IV&&!decryptiv&&logger.error("Invalid IV: "+keyTagAttributes.IV),decrypturi?M3U8Parser.resolve(decrypturi,baseurl):""),decrypturi=(decryptkeyformatversions||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(parsed,keyTagAttributes,_keyAttrs$KEYFORMAT,decrypturi,decryptiv)}function parseStartTimeOffset(startAttributes){startAttributes=new AttrList(startAttributes).decimalFloatingPoint("TIME-OFFSET");return isFiniteNumber(startAttributes)?startAttributes:null}function assignCodec(media,groupItem,codecProperty){groupItem=groupItem[codecProperty];groupItem&&(media[codecProperty]=groupItem)}function assignProgramDateTime(frag,prevFrag,programDateTimes){frag.rawProgramDateTime?programDateTimes.push(frag):null!=prevFrag&&prevFrag.programDateTime&&(frag.programDateTime=prevFrag.endProgramDateTime)}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;level=level.encryptedFragments;level.length&&level[level.length-1].levelkeys===levelkeys||!Object.keys(levelkeys).some(function(format){return levelkeys[format].isCommonEncryption})||level.push(frag)}function updateFromToPTS(fragFrom,fragTo){var duration,fragToPTS=fragTo.startPTS;isFiniteNumber(fragToPTS)?(duration=0,(fragToPTS=fragTo.sn>fragFrom.sn?(duration=fragToPTS-fragFrom.start,fragFrom):(duration=fragFrom.start-fragToPTS,fragTo)).duration!==duration&&fragToPTS.setDuration(duration)):fragTo.sn>fragFrom.sn?fragFrom.cc===fragTo.cc&&fragFrom.minEndPTS?fragTo.setStart(fragFrom.start+(fragFrom.minEndPTS-fragFrom.start)):fragTo.setStart(fragFrom.start+fragFrom.duration):fragTo.setStart(Math.max(fragFrom.start-fragTo.duration,0))}function updateFragPTSDTS(details,frag,startPTS,endPTS,startDTS,endDTS){endPTS-startPTS<=0&&(logger.warn("Fragment should have a positive duration",frag),endPTS=startPTS+frag.duration,endDTS=startDTS+frag.duration);var i,maxStartPTS=startPTS,minEndPTS=endPTS,fragStartPts=frag.startPTS,fragEndPts=frag.endPTS,deltaPTS=(isFiniteNumber(fragStartPts)&&(deltaPTS=Math.abs(fragStartPts-startPTS),isFiniteNumber(frag.deltaPTS)?frag.deltaPTS=Math.max(deltaPTS,frag.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(endDTS,frag.endDTS)),startPTS-frag.start),fragStartPts=(0!==frag.start&&frag.setStart(startPTS),frag.setDuration(endPTS-frag.start),frag.startPTS=startPTS,frag.maxStartPTS=maxStartPTS,frag.startDTS=startDTS,frag.endPTS=endPTS,frag.minEndPTS=minEndPTS,frag.endDTS=endDTS,frag.sn);if(!details||fragStartPts<details.startSN||fragStartPts>details.endSN)return 0;var fragEndPts=fragStartPts-details.startSN,fragments=details.fragments;for(fragments[fragEndPts]=frag,i=fragEndPts;0<i;i--)updateFromToPTS(fragments[i],fragments[i-1]);for(i=fragEndPts;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,deltaPTS}function mergeDetails(oldDetails,newDetails){for(var currentInitSegment=null,oldFragments=oldDetails.fragments,i=oldFragments.length-1;0<=i;i--){var oldInit=oldFragments[i].initSegment;if(oldInit){currentInitSegment=oldInit;break}}oldDetails.fragmentHint&&delete oldDetails.fragmentHint.endPTS;var PTSFrag,ccOffset=0,fragmentsToCheck=(!function(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&&_oldFrag&&(_newFrag=newDetails.fragments[i]=_oldFrag),_oldFrag&&_newFrag&&intersectionFn(_oldFrag,_newFrag)}}(oldDetails,newDetails,function(oldFrag,newFrag){oldFrag.relurl&&(ccOffset=oldFrag.cc-newFrag.cc),isFiniteNumber(oldFrag.startPTS)&&isFiniteNumber(oldFrag.endPTS)&&(newFrag.setStart(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.setDuration(oldFrag.endPTS-oldFrag.startPTS),newFrag.duration&&(PTSFrag=newFrag),newDetails.PTSKnown=newDetails.alignedSliding=!0),oldFrag.hasStreams&&(newFrag.elementaryStreams=oldFrag.elementaryStreams),newFrag.loader=oldFrag.loader,oldFrag.hasStats&&(newFrag.stats=oldFrag.stats),oldFrag.initSegment&&(newFrag.initSegment=oldFrag.initSegment,currentInitSegment=oldFrag.initSegment)}),newDetails.fragmentHint?newDetails.fragments.concat(newDetails.fragmentHint):newDetails.fragments);if(currentInitSegment&&fragmentsToCheck.forEach(function(frag){!frag||frag.initSegment&&frag.initSegment.relurl!==(null==currentInitSegment?void 0:currentInitSegment.relurl)||(frag.initSegment=currentInitSegment)}),newDetails.skippedSegments)if(newDetails.deltaUpdateFailed=newDetails.fragments.some(function(frag){return!frag}),newDetails.deltaUpdateFailed){logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var _i=newDetails.skippedSegments;_i--;)newDetails.fragments.shift();newDetails.startSN=newDetails.fragments[0].sn,newDetails.startCC||(newDetails.startCC=newDetails.fragments[0].cc)}else{newDetails.canSkipDateRanges&&(newDetails.dateRanges=function(oldDateRanges,newDetails){var deltaDateRanges=newDetails.dateRanges,newDetails=newDetails.recentlyRemovedDateranges,dateRanges=_extends({},oldDateRanges);newDetails&&newDetails.forEach(function(id){delete dateRanges[id]});var mergeCount=Object.keys(dateRanges).length;mergeCount&&Object.keys(deltaDateRanges).forEach(function(id){var mergedDateRange=dateRanges[id],dateRange=new DateRange(deltaDateRanges[id].attr,mergedDateRange);dateRange.isValid?(dateRanges[id]=dateRange,mergedDateRange||(dateRange.tagOrder+=mergeCount)):logger.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+JSON.stringify(deltaDateRanges[id].attr)+'"')});return dateRanges}(oldDetails.dateRanges,newDetails));var programDateTimes=oldDetails.fragments.filter(function(frag){return frag.rawProgramDateTime});if(oldDetails.hasProgramDateTime&&!newDetails.hasProgramDateTime)for(var _i2=1;_i2<fragmentsToCheck.length;_i2++)null===fragmentsToCheck[_i2].programDateTime&&assignProgramDateTime(fragmentsToCheck[_i2],fragmentsToCheck[_i2-1],programDateTimes);mapDateRanges(programDateTimes,newDetails)}var newFragments=newDetails.fragments;if(ccOffset){logger.warn("discontinuity sliding from playlist, take drift into account");for(var _i3=0;_i3<newFragments.length;_i3++)newFragments[_i3].cc+=ccOffset}newDetails.skippedSegments&&(newDetails.startCC=newDetails.fragments[0].cc),function(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--}}(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 edge,advancedDateTime=newDetails.advancedDateTime;newDetails.advanced&&advancedDateTime?(edge=newDetails.edge,newDetails.driftStart||(newDetails.driftStartTime=advancedDateTime,newDetails.driftStart=edge),newDetails.driftEndTime=advancedDateTime,newDetails.driftEnd=edge):(newDetails.driftEndTime=oldDetails.driftEndTime,newDetails.driftEnd=oldDetails.driftEnd,newDetails.advancedDateTime=oldDetails.advancedDateTime),-1===newDetails.requestScheduled&&(newDetails.requestScheduled=oldDetails.requestScheduled)}function adjustSliding(oldDetails,newDetails,matchingStableVariantOrRendition){void 0===matchingStableVariantOrRendition&&(matchingStableVariantOrRendition=!0);var delta=newDetails.startSN+newDetails.skippedSegments-oldDetails.startSN,oldFragments=oldDetails.fragments,advancedOrStable=0<=delta,sliding=0;if(advancedOrStable&&delta<oldFragments.length)sliding=oldFragments[delta].start;else if(advancedOrStable&&newDetails.startSN===oldDetails.endSN+1)sliding=oldDetails.fragmentEnd;else if(advancedOrStable&&matchingStableVariantOrRendition)sliding=oldDetails.fragmentStart+delta*newDetails.levelTargetDuration;else{if(newDetails.skippedSegments||0!==newDetails.fragmentStart)return;sliding=oldDetails.fragmentStart}addSliding(newDetails,sliding)}function addSliding(details,sliding){if(sliding){for(var fragments=details.fragments,i=details.skippedSegments;i<fragments.length;i++)fragments[i].addStart(sliding);details.fragmentHint&&details.fragmentHint.addStart(sliding)}}function computeReloadInterval(newDetails,distanceToLiveEdgeMs){void 0===distanceToLiveEdgeMs&&(distanceToLiveEdgeMs=1/0);var reloadInterval=1e3*newDetails.targetduration;return newDetails.updated?(newDetails=newDetails.fragments).length&&distanceToLiveEdgeMs<4*reloadInterval&&(distanceToLiveEdgeMs=1e3*newDetails[newDetails.length-1].duration)<reloadInterval&&(reloadInterval=distanceToLiveEdgeMs):reloadInterval/=2,Math.round(reloadInterval)}function getPartWith(details,sn,partIndex){return details?findPart(details.partList,sn,partIndex):null}function findPart(partList,sn,partIndex){if(partList)for(var i=partList.length;i--;){var part=partList[i];if(part.index===partIndex&&part.fragment.sn===sn)return part}return null}function reassignFragmentLevelIndexes(levels){levels.forEach(function(level,index){level=null==(level=level.details)?void 0:level.fragments;level&&level.forEach(function(fragment){fragment.level=index,fragment.initSegment&&(fragment.initSegment.level=index)})})}function findFirstFragWithCC(fragments,cc){for(var _fragments$i,i=0,len=fragments.length;i<len;i++)if((null==(_fragments$i=fragments[i])?void 0:_fragments$i.cc)===cc)return fragments[i];return null}function adjustFragmentStart(frag,sliding){frag&&(sliding=frag.start+sliding,frag.start=frag.startPTS=sliding,frag.endPTS=sliding+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 alignDiscontinuities(details,refDetails){var targetCC,frag;(function(refDetails,details){return!!(refDetails&&details.startCC<refDetails.endCC&&details.endCC>refDetails.startCC)})(refDetails,details)&&(targetCC=Math.min(refDetails.endCC,details.endCC),refDetails=findFirstFragWithCC(refDetails.fragments,targetCC),frag=findFirstFragWithCC(details.fragments,targetCC),refDetails)&&frag&&(logger.log("Aligning playlist at start of dicontinuity sequence "+targetCC),adjustSlidingStart(refDetails.start-frag.start,details))}function alignMediaPlaylistByPDT(details,refDetails){var fragments,refFragments,refFrag,frag,targetCC;details.hasProgramDateTime&&refDetails.hasProgramDateTime&&(fragments=details.fragments,refFragments=refDetails.fragments,fragments.length)&&refFragments.length&&(targetCC=Math.min(refDetails.endCC,details.endCC),refDetails.startCC<targetCC&&details.startCC<targetCC&&(refFrag=findFirstFragWithCC(refFragments,targetCC),frag=findFirstFragWithCC(fragments,targetCC)),refFrag&&frag||(frag=findFirstFragWithCC(fragments,(refFrag=refFragments[Math.floor(refFragments.length/2)]).cc)||fragments[Math.floor(fragments.length/2)]),refDetails=refFrag.programDateTime,targetCC=frag.programDateTime,refDetails)&&targetCC&&adjustSlidingStart((targetCC-refDetails)/1e3-(frag.start-refFrag.start),details)}var 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",State_IDLE="IDLE",State_KEY_LOADING="KEY_LOADING",State_FRAG_LOADING="FRAG_LOADING",State_FRAG_LOADING_WAITING_RETRY="FRAG_LOADING_WAITING_RETRY",State_WAITING_TRACK="WAITING_TRACK",State_PARSING="PARSING",State_PARSED="PARSED",State_ENDED="ENDED",State_ERROR="ERROR",State_WAITING_INIT_PTS="WAITING_INIT_PTS",State_WAITING_LEVEL="WAITING_LEVEL",_optionalSelf$navigat=function(_TaskLoop){function BaseStreamController(hls,fragmentTracker,keyLoader,logPrefix,playlistType){var _this=_TaskLoop.call(this,logPrefix,hls.logger)||this;return _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.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.buffering=!0,_this.loadingParts=!1,_this.loopSn=void 0,_this.onMediaSeeking=function(){var _this2=_this,config=_this2.config,fragCurrent=_this2.fragCurrent,media=_this2.media,mediaBuffer=_this2.mediaBuffer,_this2=_this2.state,currentTime=media?media.currentTime:0,mediaBuffer=BufferHelper.bufferInfo(mediaBuffer||media,currentTime,config.maxBufferHole);_this.log("media seeking to "+(isFiniteNumber(currentTime)?currentTime.toFixed(3):currentTime)+", state: "+_this2),_this.state===State_ENDED?_this.resetLoadingState():fragCurrent&&(_this2=config.maxFragLookUpTolerance,config=fragCurrent.start-_this2,_this2=fragCurrent.start+fragCurrent.duration+_this2,!mediaBuffer.len||_this2<mediaBuffer.start||config>mediaBuffer.end)&&(_this2=_this2<currentTime,currentTime<config||_this2)&&(_this2&&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,1/0,_this.playlistType,!0),_this.lastCurrentTime<currentTime&&(_this.lastCurrentTime=currentTime),!_this.loadingParts)&&(config=Math.max(mediaBuffer.end,currentTime),_this2=_this.shouldLoadParts(_this.getLevelDetails(),config))&&(_this.log("LL-Part loading ON after seeking to "+currentTime.toFixed(2)+" with buffer @"+config.toFixed(2)),_this.loadingParts=_this2),_this.hls.hasEnoughToStart||mediaBuffer.len||(_this.log("setting startPosition to "+currentTime+" because of seek before start"),_this.nextLoadPosition=_this.startPosition=currentTime),_this.tickImmediate()},_this.onMediaEnded=function(){_this.log("setting startPosition to 0 because media ended"),_this.startPosition=_this.lastCurrentTime=0,_this.triggerEnded()},_this.playlistType=playlistType,_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),_this}_inheritsLoose(BaseStreamController,_TaskLoop);var _proto=BaseStreamController.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_LOADED,this.onManifestLoaded,this),hls.on(Events.ERROR,this.onError,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_LOADED,this.onManifestLoaded,this),hls.off(Events.ERROR,this.onError,this)},_proto.doTick=function(){this.onTickEnd()},_proto.onTickEnd=function(){},_proto.startLoad=function(startPosition){},_proto.stopLoad=function(){var frag;this.state!==State_STOPPED&&(this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType),null!=(frag=this.fragCurrent)&&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.pauseBuffering=function(){this.buffering=!1},_proto.resumeBuffering=function(){this.buffering=!0},_proto._streamEnded=function(bufferInfo,levelDetails){var hasTimelineOffset=void 0!==this.config.timelineOffset,nextStart=bufferInfo.nextStart,hasTimelineOffset=nextStart&&(!hasTimelineOffset||nextStart<levelDetails.edge);return!(levelDetails.live||hasTimelineOffset||!bufferInfo.end||!this.media)&&(null!=(nextStart=levelDetails.partList)&&nextStart.length?(hasTimelineOffset=nextStart[nextStart.length-1],BufferHelper.isBuffered(this.media,hasTimelineOffset.start+hasTimelineOffset.duration/2)):(bufferInfo=levelDetails.fragments[levelDetails.fragments.length-1].type,this.fragmentTracker.isEndListAppended(bufferInfo)))},_proto.getLevelDetails=function(){var _this$levelLastLoaded;return!this.levels||null===this.levelLastLoaded||null==(_this$levelLastLoaded=this.levelLastLoaded)?void 0:_this$levelLastLoaded.details},_proto.onMediaAttached=function(event,data){data=this.media=this.mediaBuffer=data.media,data.removeEventListener("seeking",this.onMediaSeeking),data.removeEventListener("ended",this.onMediaEnded),data.addEventListener("seeking",this.onMediaSeeking),data.addEventListener("ended",this.onMediaEnded),data=this.config;this.levels&&data.autoStartLoad&&this.state===State_STOPPED&&this.startLoad(data.startPosition)},_proto.onMediaDetaching=function(event,data){var data=!!data.transferMedia,media=this.media;null!==media&&(media.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),media.removeEventListener("seeking",this.onMediaSeeking),media.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!data&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,data?this.resetTransmuxer():(this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()))},_proto.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},_proto.onError=function(event,data){},_proto.triggerEnded=function(){},_proto.onManifestLoaded=function(event,data){this.startTimeOffset=data.startTimeOffset},_proto.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),_TaskLoop.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=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){var config=this.hls.config;if(config.interstitialsController&&!1!==config.enableInterstitialPlayback&&frag.type!==PlaylistLevelType_SUBTITLE){config=this.hls.interstitialsManager,config=null==config?void 0:config.bufferingItem;if(config){var bufferingInterstitial=config.event;if(bufferingInterstitial){if(bufferingInterstitial.appendInPlace||1<Math.abs(frag.start-config.start)||0===config.start)return}else{if(frag.end<=config.start&&!1===(null==(bufferingInterstitial=level.details)?void 0:bufferingInterstitial.live))return;if(frag.start>config.end&&config.nextEvent)return}}}this.startFragRequested=!0,this._loadFragForPlayback(frag,level,targetBufferTime)},_proto._loadFragForPlayback=function(fragment,level,targetBufferTime){var _this3=this;this._doFragLoad(fragment,level,targetBufferTime,function(data){var frag=data.frag;_this3.fragContextChanged(frag)?(_this3.warn(frag.type+" sn: "+frag.sn+(data.part?" part: "+data.part.index:"")+" of "+_this3.fragInfo(frag,!1,data.part)+") was dropped during download."),_this3.fragmentTracker.removeFragment(frag)):(frag.stats.chunkCount++,_this3._handleFragmentLoadProgress(data))}).then(function(data){var state,frag;data&&(state=_this3.state,frag=data.frag,_this3.fragContextChanged(frag)?state!==State_FRAG_LOADING&&(_this3.fragCurrent||state!==State_PARSING)||(_this3.fragmentTracker.removeFragment(frag),_this3.state=State_IDLE):("payload"in data&&(_this3.log("Loaded "+frag.type+" sn: "+frag.sn+" of "+_this3.playlistLabel()+" "+frag.level),_this3.hls.trigger(Events.FRAG_LOADED,data)),_this3._handleFragmentLoadComplete(data)))}).catch(function(reason){_this3.state!==State_STOPPED&&_this3.state!==State_ERROR&&(_this3.warn("Frag error: "+((null==reason?void 0:reason.message)||reason)),_this3.resetFragmentLoading(fragment))})},_proto.clearTrackerIfNeeded=function(frag){var playlistType,backtrackFragment,fragmentTracker=this.fragmentTracker;fragmentTracker.getState(frag)===FragmentState_APPENDING?(playlistType=frag.type,playlistType=this.getFwdBufferInfo(this.mediaBuffer,playlistType),playlistType=Math.max(frag.duration,playlistType?playlistType.len:this.config.maxBufferLength),1!=((backtrackFragment=this.backtrackFragment)?frag.sn-backtrackFragment.sn:0)&&!this.reduceMaxBufferLength(playlistType,frag.duration)||fragmentTracker.removeFragment(frag)):0===(null==(backtrackFragment=this.mediaBuffer)?void 0:backtrackFragment.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){var lastFragment;details.updated&&!details.live&&(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.waitForLive=function(levelInfo){var details=levelInfo.details;return(null==details?void 0:details.live)&&"EVENT"!==details.type&&(this.levelLastLoaded!==levelInfo||details.expired)},_proto.flushMainBuffer=function(startOffset,endOffset,type){void 0===type&&(type=null),startOffset-endOffset&&this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:startOffset,endOffset:endOffset,type:type})},_proto._loadInitSegment=function(fragment,level){var _this4=this;this._doFragLoad(fragment,level).then(function(data){var frag=null==data?void 0:data.frag;if(frag&&!_this4.fragContextChanged(frag)&&_this4.levels)return data;throw new Error("init load aborted")}).then(function(data){var startTime,hls=_this4.hls,frag=data.frag,payload=data.payload,decryptData=frag.decryptdata;return payload&&0<payload.byteLength&&null!=decryptData&&decryptData.key&&decryptData.iv&&isFullSegmentEncryption(decryptData.method)?(startTime=self.performance.now(),_this4.decrypter.decrypt(new Uint8Array(payload),decryptData.key.buffer,decryptData.iv.buffer,getAesModeFromFullSegmentMethod(decryptData.method)).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,_this4.completeInitSegmentLoad(data)})):_this4.completeInitSegmentLoad(data)}).catch(function(reason){_this4.state!==State_STOPPED&&_this4.state!==State_ERROR&&(_this4.warn(reason),_this4.resetFragmentLoading(fragment))})},_proto.completeInitSegmentLoad=function(data){if(!this.levels)throw new Error("init load aborted, missing levels");var stats=data.frag.stats;this.state!==State_STOPPED&&(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.media;if(this.log("Buffered "+frag.type+" sn: "+frag.sn+(part?" part: "+part.index:"")+" of "+this.fragInfo(frag,!1,part)+" > buffer:"+(media?TimeRanges_toString(BufferHelper.getBuffered(media)):"(detached)")+")"),isMediaFragment(frag)){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)}media=null==(part=this.levels)?void 0:part[frag.level];null!=media&&media.fragmentError&&(this.log("Resetting level fragment error count of "+media.fragmentError+" on frag buffered"),media.fragmentError=0)}this.state=State_IDLE},_proto._handleFragmentLoadComplete=function(fragLoadedEndData){var part,frag,transmuxer=this.transmuxer;transmuxer&&(frag=fragLoadedEndData.frag,part=fragLoadedEndData.part,fragLoadedEndData=!(fragLoadedEndData=fragLoadedEndData.partsLoaded)||0===fragLoadedEndData.length||fragLoadedEndData.some(function(fragLoaded){return!fragLoaded}),frag=new ChunkMetadata(frag.level,frag.sn,frag.stats.chunkCount+1,0,part?part.index:-1,!fragLoadedEndData),transmuxer.flush(frag))},_proto._handleFragmentLoadProgress=function(frag){},_proto._doFragLoad=function(frag,level,targetBufferTime,progressCallback){var _this5=this,details=(void 0===targetBufferTime&&(targetBufferTime=null),this.fragCurrent=frag,null==level?void 0:level.details);if(!this.levels||!details)throw new Error("frag load aborted, missing level"+(details?"":" detail")+"s");var keyLoadingPromise=null,_frag$decryptdata=(!frag.encrypted||null!=(_frag$decryptdata=frag.decryptdata)&&_frag$decryptdata.key?!frag.encrypted&&details.encryptedFragments.length&&this.keyLoader.loadClear(frag,details.encryptedFragments):(this.log("Loading key for "+frag.sn+" of ["+details.startSN+"-"+details.endSN+"], "+this.playlistLabel()+" "+frag.level),this.state=State_KEY_LOADING,this.fragCurrent=frag,keyLoadingPromise=this.keyLoader.load(frag).then(function(keyLoadedData){if(!_this5.fragContextChanged(keyLoadedData.frag))return _this5.hls.trigger(Events.KEY_LOADED,keyLoadedData),_this5.state===State_KEY_LOADING&&(_this5.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")))),this.fragPrevious);if(!isMediaFragment(frag)||_frag$decryptdata&&frag.sn===_frag$decryptdata.sn||(shouldLoadParts=this.shouldLoadParts(level.details,frag.end))!==this.loadingParts&&(this.log("LL-Part loading "+(shouldLoadParts?"ON":"OFF")+" loading sn "+(null==_frag$decryptdata?void 0:_frag$decryptdata.sn)+"->"+frag.sn),this.loadingParts=shouldLoadParts),targetBufferTime=Math.max(frag.start,targetBufferTime||0),this.loadingParts&&isMediaFragment(frag)){_frag$decryptdata=details.partList;if(_frag$decryptdata&&progressCallback){targetBufferTime>frag.end&&details.fragmentHint&&(frag=details.fragmentHint);var part,shouldLoadParts=this.getNextPart(_frag$decryptdata,frag,targetBufferTime);if(-1<shouldLoadParts)return part=_frag$decryptdata[shouldLoadParts],frag=this.fragCurrent=part.fragment,this.log("Loading "+frag.type+" sn: "+frag.sn+" part: "+part.index+" ("+shouldLoadParts+"/"+(_frag$decryptdata.length-1)+") of "+this.fragInfo(frag,!1,part)+") cc: "+frag.cc+" ["+details.startSN+"-"+details.endSN+"], target: "+parseFloat(targetBufferTime.toFixed(3))),this.nextLoadPosition=part.start+part.duration,this.state=State_FRAG_LOADING,shouldLoadParts=keyLoadingPromise?keyLoadingPromise.then(function(keyLoadedData){return!keyLoadedData||_this5.fragContextChanged(keyLoadedData.frag)?null:_this5.doFragPartsLoad(frag,part,level,progressCallback)}).catch(function(error){return _this5.handleFragLoadError(error)}):this.doFragPartsLoad(frag,part,level,progressCallback).catch(function(error){return _this5.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")):shouldLoadParts;if(!frag.url||this.loadedEndOfParts(_frag$decryptdata,targetBufferTime))return Promise.resolve(null)}}if(isMediaFragment(frag)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+targetBufferTime.toFixed(2)),this.loadingParts=!1;else if(!frag.url)return Promise.resolve(null);this.log("Loading "+frag.type+" sn: "+frag.sn+" of "+this.fragInfo(frag,!1)+") cc: "+frag.cc+" "+(details?"["+details.startSN+"-"+details.endSN+"]":"")+", 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,shouldLoadParts=dataOnProgress&&keyLoadingPromise?keyLoadingPromise.then(function(keyLoadedData){return!keyLoadedData||_this5.fragContextChanged(null==keyLoadedData?void 0:keyLoadedData.frag)?null:_this5.fragmentLoader.load(frag,progressCallback)}).catch(function(error){return _this5.handleFragLoadError(error)}):Promise.all([this.fragmentLoader.load(frag,dataOnProgress?progressCallback:void 0),keyLoadingPromise]).then(function(_ref){_ref=_ref[0];return!dataOnProgress&&_ref&&progressCallback&&progressCallback(_ref),_ref}).catch(function(error){return _this5.handleFragLoadError(error)});return 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")):shouldLoadParts},_proto.doFragPartsLoad=function(frag,fromPart,level,progressCallback){var _this6=this;return new Promise(function(resolve,reject){function _loadPart(part){_this6.fragmentLoader.loadPart(frag,part,progressCallback).then(function(partLoadedData){var loadedPart=(partsLoaded[part.index]=partLoadedData).part,partLoadedData=(_this6.hls.trigger(Events.FRAG_LOADED,partLoadedData),getPartWith(level.details,frag.sn,part.index+1)||findPart(initialPartList,frag.sn,part.index+1));if(!partLoadedData)return resolve({frag:frag,part:loadedPart,partsLoaded:partsLoaded});_loadPart(partLoadedData)}).catch(reject)}var _level$details2,partsLoaded=[],initialPartList=null==(_level$details2=level.details)?void 0:_level$details2.partList;_loadPart(fromPart)})},_proto.handleFragLoadError=function(error){var data;return"data"in error?(data=error.data,error.data&&data.details===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(data.frag,data.part):this.hls.trigger(Events.ERROR,data)):this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:error,error:error,fatal:!0}),null},_proto._handleTransmuxerFlush=function(chunkMeta){var frag,part,now,context=this.getCurrentContext(chunkMeta);context&&this.state===State_PARSING?(frag=context.frag,part=context.part,context=context.level,now=self.performance.now(),frag.stats.parsing.end=now,part&&(part.stats.parsing.end=now),(now=(now=this.getLevelDetails())&&frag.sn>now.endSN||this.shouldLoadParts(now,frag.end))!==this.loadingParts&&(this.log("LL-Part loading "+(now?"ON":"OFF")+" after parsing segment ending @"+frag.end.toFixed(2)),this.loadingParts=now),this.updateLevelTiming(frag,part,context,chunkMeta.partial)):this.fragCurrent||this.state===State_STOPPED||this.state===State_ERROR||(this.state=State_IDLE)},_proto.shouldLoadParts=function(details,bufferEnd){if(this.config.lowLatencyMode){if(!details)return this.loadingParts;if(null!=details&&details.partList){var firstPart=details.partList[0],details=firstPart.end+((null==(details=details.fragmentHint)?void 0:details.duration)||0);if(details<=bufferEnd)if((this.hls.hasEnoughToStart?(null==(details=this.media)?void 0:details.currentTime)||this.lastCurrentTime:this.getLoadPosition())>firstPart.start-firstPart.fragment.duration)return!0}}return!1},_proto.getCurrentContext=function(chunkMeta){var levelDetails,levels=this.levels,fragCurrent=this.fragCurrent,levelIndex=chunkMeta.level,sn=chunkMeta.sn,chunkMeta=chunkMeta.part;return null!=levels&&levels[levelIndex]?(levelDetails=(levels=levels[levelIndex]).details,(levelDetails=(chunkMeta=-1<chunkMeta?getPartWith(levelDetails,sn,chunkMeta):null)?chunkMeta.fragment:function(details,sn,fragCurrent){var fragment;return details?(fragment=details.fragments[sn-details.startSN])||((fragment=details.fragmentHint)&&fragment.sn===sn?fragment:sn<details.startSN&&fragCurrent&&fragCurrent.sn===sn?fragCurrent:null):null}(levelDetails,sn,fragCurrent))?(fragCurrent&&fragCurrent!==levelDetails&&(levelDetails.stats=fragCurrent.stats),{frag:levelDetails,part:chunkMeta,level:levels}):null):(this.warn("Levels object was unset while buffering fragment "+sn+" of "+this.playlistLabel()+" "+levelIndex+". The current chunk will not be buffered."),null)},_proto.bufferFragmentData=function(data,frag,part,chunkMeta,noBacktracking){var data2,buffer,data1;data&&this.state===State_PARSING&&(data1=data.data1,data2=data.data2,null!=(buffer=(buffer=data1)&&data2?appendUint8Array(data1,data2):buffer))&&buffer.length&&(data1={type:data.type,frag:frag,part:part,chunkMeta:chunkMeta,parent:frag.type,data:buffer},this.hls.trigger(Events.BUFFER_APPENDING,data1),data.dropped)&&data.independent&&!part&&!noBacktracking&&this.flushBufferGap(frag)},_proto.flushBufferGap=function(frag){var currentTime,fragDuration,media=this.media;media&&(BufferHelper.isBuffered(media,media.currentTime)?(currentTime=media.currentTime,media=BufferHelper.bufferInfo(media,currentTime,0),fragDuration=frag.duration,fragDuration=Math.min(2*this.config.maxFragLookUpTolerance,.25*fragDuration),media=Math.max(Math.min(frag.start-fragDuration,media.end-fragDuration),currentTime+fragDuration),frag.start-media>fragDuration&&this.flushMainBuffer(media,frag.start)):this.flushMainBuffer(0,frag.start))},_proto.getFwdBufferInfo=function(bufferable,type){var _this$media2,pos=this.getLoadPosition();return isFiniteNumber(pos)?(_this$media2=this.lastCurrentTime>pos||null!=(_this$media2=this.media)&&_this$media2.paused?0:this.config.maxBufferHole,this.getFwdBufferInfoAtPos(bufferable,pos,type,_this$media2)):null},_proto.getFwdBufferInfoAtPos=function(bufferable,pos,type,maxBufferHole){var bufferInfo=BufferHelper.bufferInfo(bufferable,pos,maxBufferHole);if(0===bufferInfo.len&&void 0!==bufferInfo.nextStart){type=this.fragmentTracker.getBufferedFrag(pos,type);if(type&&(bufferInfo.nextStart<=type.end||type.gap))return BufferHelper.bufferInfo(bufferable,pos,Math.max(bufferInfo.nextStart,maxBufferHole))}return bufferInfo},_proto.getMaxBufferLength=function(levelBitrate){var config=this.config,levelBitrate=levelBitrate?Math.max(8*config.maxBufferSize/levelBitrate,config.maxBufferLength):config.maxBufferLength;return Math.min(levelBitrate,config.maxMaxBufferLength)},_proto.reduceMaxBufferLength=function(threshold,fragDuration){var config=this.config,minLength=Math.max(Math.min(threshold-fragDuration,config.maxBufferLength),fragDuration),threshold=Math.max(threshold-3*fragDuration,config.maxMaxBufferLength/2,minLength);return minLength<=threshold&&(config.maxMaxBufferLength=threshold,this.warn("Reduce max buffer length to "+threshold+"s"),!0)},_proto.getAppendedFrag=function(position,playlistType){void 0===playlistType&&(playlistType=PlaylistLevelType_MAIN);var _this$fragmentTracker=null==(_this$fragmentTracker=this.fragmentTracker)?void 0:_this$fragmentTracker.getAppendedFrag(position,playlistType);return _this$fragmentTracker&&"fragment"in _this$fragmentTracker?_this$fragmentTracker.fragment:_this$fragmentTracker},_proto.getNextFragment=function(pos,levelDetails){var fragments=levelDetails.fragments,fragLen=fragments.length;if(!fragLen)return null;var config=this.config,start=fragments[0].start,canLoadParts=config.lowLatencyMode&&!!levelDetails.partList,frag=null;if(levelDetails.live){var config=config.initialLiveManifestSize;if(fragLen<config)return this.warn("Not enough fragments to start playback (have: "+fragLen+", need: "+config+")"),null;(!levelDetails.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||pos<start)&&(canLoadParts&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),frag=this.getInitialLiveFragment(levelDetails,fragments),fragLen=this.hls.startPosition,config=this.hls.liveSyncPosition,canLoadParts=frag?(-1!==fragLen?fragLen:config)||frag.start:pos,this.log("Setting startPosition to "+canLoadParts+" to match initial live edge. mainStart: "+fragLen+" liveSyncPosition: "+config+" frag.start: "+(null==frag?void 0:frag.start)),this.startPosition=this.nextLoadPosition=canLoadParts)}else pos<=start&&(frag=fragments[0]);return frag||(fragLen=this.loadingParts?levelDetails.partEnd:levelDetails.fragmentEnd,frag=this.getFragmentAtPosition(pos,fragLen,levelDetails)),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 nextFragment=null;if(frag.gap&&(nextFragment=this.getNextFragment(this.nextLoadPosition,levelDetails))&&!nextFragment.gap&&bufferInfo.nextStart){frag=this.getFwdBufferInfoAtPos(this.mediaBuffer||this.media,bufferInfo.nextStart,playlistType,0);if(null!==frag&&bufferInfo.len+frag.len>=maxBufLen)return levelDetails=nextFragment.sn,this.loopSn!==levelDetails&&(this.log('buffer full after gaps in "'+playlistType+'" playlist starting at sn: '+levelDetails),this.loopSn=levelDetails),null}return this.loopSn=void 0,nextFragment},_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;i<len;i++){var part=partList[i],independentAttrOmitted=independentAttrOmitted&&!part.independent;if(-1<nextPart&&targetBufferTime<part.start)break;var loaded=part.loaded;loaded?nextPart=-1:(contiguous||part.independent||independentAttrOmitted)&&part.fragment===frag&&(nextPart=i),contiguous=loaded}return nextPart},_proto.loadedEndOfParts=function(partList,targetBufferTime){partList=partList[partList.length-1];return partList&&targetBufferTime>partList.start&&partList.loaded},_proto.getInitialLiveFragment=function(levelDetails,fragments){var targetSN,fragPrevious=this.fragPrevious,frag=null;return fragPrevious?(levelDetails.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+fragPrevious.programDateTime),frag=findFragmentByPDT(fragments,fragPrevious.endProgramDateTime,this.config.maxFragLookUpTolerance)),frag||((targetSN=fragPrevious.sn+1)>=levelDetails.startSN&&targetSN<=levelDetails.endSN&&(targetSN=fragments[targetSN-levelDetails.startSN],fragPrevious.cc===targetSN.cc)&&this.log("Live playlist, switching playlist, load frag with next SN: "+(frag=targetSN).sn),frag)||(frag=findFragWithCC(fragments,fragPrevious.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+frag.sn)):null!==(targetSN=this.hls.liveSyncPosition)&&(frag=this.getFragmentAtPosition(targetSN,this.bitrateTest?levelDetails.fragmentEnd:levelDetails.edge,levelDetails)),frag},_proto.getFragmentAtPosition=function(bufferEnd,end,levelDetails){var config=this.config,fragPrevious=this.fragPrevious,fragments=levelDetails.fragments,endSN=levelDetails.endSN,fragmentHint=levelDetails.fragmentHint,config=config.maxFragLookUpTolerance,partList=levelDetails.partList,loadingParts=!!(this.loadingParts&&null!=partList&&partList.length&&fragmentHint);return loadingParts&&fragmentHint&&!this.bitrateTest&&partList[partList.length-1].fragment.sn===fragmentHint.sn&&(fragments=fragments.concat(fragmentHint),endSN=fragmentHint.sn),(end=bufferEnd<end?findFragmentByPTS(fragPrevious,fragments,bufferEnd,bufferEnd<this.lastCurrentTime||end-config<bufferEnd||null!=(fragmentHint=this.media)&&fragmentHint.paused||!this.startFragRequested?0:config):fragments[fragments.length-1])&&(bufferEnd=end.sn-levelDetails.startSN,fragPrevious=(fragmentHint=this.fragmentTracker.getState(end))===FragmentState_OK||fragmentHint===FragmentState_PARTIAL&&end.gap?end:fragPrevious)&&end.sn===fragPrevious.sn&&(!loadingParts||partList[0].fragment.sn>end.sn||!levelDetails.live&&!loadingParts)&&fragPrevious&&end.level===fragPrevious.level&&(config=fragments[1+bufferEnd],end=end.sn<endSN&&this.fragmentTracker.getState(config)!==FragmentState_OK?config:null),end},_proto.alignPlaylists=function(details,previousDetails,switchDetails){var slidingStart,aligned,firstLevelLoad,length=details.fragments.length;return length?(slidingStart=details.fragmentStart,firstLevelLoad=!previousDetails,aligned=details.alignedSliding&&isFiniteNumber(slidingStart),firstLevelLoad||!aligned&&!slidingStart?(function(switchDetails,details){switchDetails&&(alignDiscontinuities(details,switchDetails),!details.alignedSliding&&switchDetails&&alignMediaPlaylistByPDT(details,switchDetails),details.alignedSliding||!switchDetails||details.skippedSegments||adjustSliding(switchDetails,details,!1))}(switchDetails,details),firstLevelLoad=details.fragmentStart,this.log("Live playlist sliding: "+firstLevelLoad.toFixed(2)+" start-sn: "+(previousDetails?previousDetails.startSN:"na")+"->"+details.startSN+" fragments: "+length),firstLevelLoad):slidingStart):(this.warn("No fragments in live playlist"),0)},_proto.waitForCdnTuneIn=function(details){return details.live&&details.canBlockReload&&details.partTarget&&details.tuneInGoal>Math.max(details.partHoldBack,3*details.partTarget)},_proto.setStartPosition=function(details,sliding){var offsetInMultivariantPlaylist,startTimeOffset,startPosition=this.startPosition;-1===(startPosition=startPosition<sliding?-1:startPosition)&&(null!==(startTimeOffset=((offsetInMultivariantPlaylist=null!==this.startTimeOffset)?this:details).startTimeOffset)&&isFiniteNumber(startTimeOffset)?(startPosition=sliding+startTimeOffset,startTimeOffset<0&&(startPosition+=details.edge),startPosition=Math.min(Math.max(sliding,startPosition),sliding+details.totalduration),this.log("Setting startPosition to "+startPosition+" for start time offset "+startTimeOffset+" found in "+(offsetInMultivariantPlaylist?"multivariant":"media")+" playlist"),this.startPosition=startPosition):details.live?(startPosition=this.hls.liveSyncPosition||sliding,this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=startPosition=0),this.lastCurrentTime=startPosition),this.nextLoadPosition=startPosition},_proto.getLoadPosition=function(){var _this$hls,media=this.media,pos=0;return null!=(_this$hls=this.hls)&&_this$hls.hasEnoughToStart&&media?pos=media.currentTime:0<=this.nextLoadPosition&&(pos=this.nextLoadPosition),pos},_proto.handleFragLoadAborted=function(frag,part){this.transmuxer&&frag.type===this.playlistType&&isMediaFragment(frag)&&frag.stats.aborted&&(this.warn("Fragment "+frag.sn+(part?" part "+part.index:"")+" of "+this.playlistLabel()+" "+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){data.chunkMeta&&!data.frag&&(context=this.getCurrentContext(data.chunkMeta))&&(data.frag=context.frag);var context=data.frag;if(context&&context.type===filterType&&this.levels)if(this.fragContextChanged(context))this.warn("Frag load error must match current frag to retry "+context.url+" > "+(null==(_this$fragCurrent=this.fragCurrent)?void 0:_this$fragCurrent.url));else{var _this$fragCurrent=data.details===ErrorDetails.FRAG_GAP,errorAction=(_this$fragCurrent&&this.fragmentTracker.fragBuffered(context,!0),data.errorAction),_ref2=errorAction||{},action=_ref2.action,flags=_ref2.flags,_ref2$retryCount=_ref2.retryCount,_ref2$retryCount=void 0===_ref2$retryCount?0:_ref2$retryCount,_ref2=_ref2.retryConfig,couldRetry=!!errorAction&&!!_ref2,retry=couldRetry&&action===NetworkErrorAction_RetryRequest,couldRetry=couldRetry&&!errorAction.resolved&&flags===ErrorActionFlags_MoveAllAlternatesMatchingHost;if(!retry&&couldRetry&&isMediaFragment(context)&&!context.endList)this.resetFragmentErrors(filterType),this.treatAsGap(context),errorAction.resolved=!0;else if((retry||couldRetry)&&_ref2$retryCount<_ref2.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);flags=getRetryDelay(_ref2,_ref2$retryCount);this.warn("Fragment "+context.sn+" of "+filterType+" "+context.level+" errored with "+data.details+", retrying loading "+(_ref2$retryCount+1)+"/"+_ref2.maxNumRetry+" in "+flags+"ms"),errorAction.resolved=!0,this.retryDate=self.performance.now()+flags,this.state=State_FRAG_LOADING_WAITING_RETRY}else if(_ref2&&errorAction){if(this.resetFragmentErrors(filterType),!(_ref2$retryCount<_ref2.maxNumRetry))return void this.warn(data.details+" reached or exceeded max retry ("+_ref2$retryCount+")");_this$fragCurrent||action===NetworkErrorAction_RemoveAlternatePermanently||(errorAction.resolved=!0)}else this.state=action===NetworkErrorAction_SendAlternateToPenaltyBox?State_WAITING_LEVEL:State_ERROR;this.tickImmediate()}},_proto.reduceLengthAndFlushBuffer=function(data){var frag,buffered,bufferedInfo;return(this.state===State_PARSING||this.state===State_PARSED)&&(frag=data.frag,data=data.parent,(buffered=(bufferedInfo=this.getFwdBufferInfo(this.mediaBuffer,data))&&.5<bufferedInfo.len)&&this.reduceMaxBufferLength(bufferedInfo.len,(null==frag?void 0:frag.duration)||10),(bufferedInfo=!buffered)&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+data+" buffer"),frag&&(this.fragmentTracker.removeFragment(frag),this.nextLoadPosition=frag.start),this.resetLoadingState(),bufferedInfo)},_proto.resetFragmentErrors=function(filterType){filterType===PlaylistLevelType_AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==State_STOPPED&&(this.state=State_IDLE)},_proto.afterBufferFlushed=function(media,bufferType,playlistType){media&&(media=BufferHelper.getBuffered(media),this.fragmentTracker.detectEvictedFragments(bufferType,media,playlistType),this.state===State_ENDED)&&this.resetLoadingState()},_proto.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==State_STOPPED&&(this.state=State_IDLE)},_proto.resetStartWhenNotLoaded=function(level){this.hls.hasEnoughToStart||(this.startFragRequested=!1,null!=(level=level?level.details:null)&&level.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(level,level.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition)},_proto.resetWhenMissingContext=function(chunkMeta){this.warn("The loading context changed while buffering fragment "+chunkMeta.sn+" of "+this.playlistLabel()+" "+chunkMeta.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},_proto.removeUnbufferedFrags=function(start){this.fragmentTracker.removeFragmentsInRange(start=void 0===start?0:start,1/0,this.playlistType,!1,!0)},_proto.updateLevelTiming=function(frag,part,level,partial){var _this7=this,details=level.details;if(details){if(!Object.keys(frag.elementaryStreams).reduce(function(result,type){var parsedDuration,info=frag.elementaryStreams[type];return info?(parsedDuration=info.endPTS-info.startPTS)<=0?(_this7.warn("Could not parse fragment "+frag.sn+" "+type+" duration reliably ("+parsedDuration+")"),result||!1):(parsedDuration=partial?0:updateFragPTSDTS(details,frag,info.startPTS,info.endPTS,info.startDTS,info.endDTS),_this7.hls.trigger(Events.LEVEL_PTS_UPDATED,{details:details,level:level,drift:parsedDuration,type:type,frag:frag,start:info.startPTS,end:info.endPTS}),!0):result},!1)&&null===(null==(_this$transmuxer=this.transmuxer)?void 0:_this$transmuxer.error)){var _this$transmuxer=new Error("Found no media in fragment "+frag.sn+" of "+this.playlistLabel()+" "+frag.level+" resetting transmuxer to fallback to playlist timing");if(0===level.fragmentError&&this.treatAsGap(frag,level),this.warn(_this$transmuxer.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:_this$transmuxer,frag:frag,reason:"Found no media in msn "+frag.sn+" of "+this.playlistLabel()+' "'+level.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=State_PARSED,this.log("Parsed "+frag.type+" sn: "+frag.sn+(part?" part: "+part.index:"")+" of "+this.fragInfo(frag,!1,part)+")"),this.hls.trigger(Events.FRAG_PARSED,{frag:frag,part:part})}else this.warn("level.details undefined")},_proto.playlistLabel=function(){return this.playlistType===PlaylistLevelType_MAIN?"level":"track"},_proto.fragInfo=function(frag,pts,part){var _ref3;return void 0===pts&&(pts=!0),this.playlistLabel()+" "+frag.level+" ("+(part?"part":"frag")+":["+(null!=(_ref3=pts&&!part?frag.startPTS:(part||frag).start)?_ref3:NaN).toFixed(3)+"-"+(null!=(_ref3=pts&&!part?frag.endPTS:(part||frag).end)?_ref3:NaN).toFixed(3)+"]"+(part&&"main"===frag.type?"INDEPENDENT="+(part.independent?"YES":"NO"):"")},_proto.treatAsGap=function(frag,level){level&&level.fragmentError++,frag.gap=!0,this.fragmentTracker.removeFragment(frag),this.fragmentTracker.fragBuffered(frag,!0)},_proto.resetTransmuxer=function(){var _this$transmuxer2;null!=(_this$transmuxer2=this.transmuxer)&&_this$transmuxer2.reset()},_proto.recoverWorkerError=function(data){"demuxerWorker"===data.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},_createClass(BaseStreamController,[{key:"startPositionValue",get:function(){var nextLoadPosition=this.nextLoadPosition,startPosition=this.startPosition;return-1===startPosition&&nextLoadPosition?nextLoadPosition:startPosition}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"state",get:function(){return this._state},set:function(nextState){var previousState=this._state;previousState!==nextState&&(this._state=nextState,this.log(previousState+"->"+nextState))}}])}(BaseSegment),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;return chunks.length?(chunks=1===chunks.length?chunks[0]:function(chunks,dataLength){for(var result=new Uint8Array(dataLength),offset=0,i=0;i<chunks.length;i++){var chunk=chunks[i];result.set(chunk,offset),offset+=chunk.length}return result}(chunks,dataLength),this.reset(),chunks):new Uint8Array(0)},_proto.reset=function(){this.chunks.length=0,this.dataLength=0},ChunkCache}();function isId3Footer(data,offset){return offset+10<=data.length&&51===data[offset]&&68===data[offset+1]&&73===data[offset+2]&&data[offset+3]<255&&data[offset+4]<255&&data[offset+6]<128&&data[offset+7]<128&&data[offset+8]<128&&data[offset+9]<128}function isId3Header(data,offset){return offset+10<=data.length&&73===data[offset]&&68===data[offset+1]&&51===data[offset+2]&&data[offset+3]<255&&data[offset+4]<255&&data[offset+6]<128&&data[offset+7]<128&&data[offset+8]<128&&data[offset+9]<128}function readId3Size(data,offset){var size=(127&data[offset])<<21;return(size|=(127&data[offset+1])<<14)|(127&data[offset+2])<<7|127&data[offset+3]}function getId3Data(data,offset){for(var front=offset,length=0;isId3Header(data,offset);){length=(length+=10)+readId3Size(data,offset+6);isId3Footer(data,offset+10)&&(length+=10),offset+=length}if(0<length)return data.subarray(front,front+length)}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 isHeader$1(data,offset){return offset+1<data.length&&isHeaderPattern$1(data,offset)}function initTrackConfig(track,observer,data,offset,audioCodec){track.samplerate||(observer=function(observer,data,offset,manifestCodec){var adtsObjectType,aacSampleIndex,byte2=data[offset+2],adtsSamplingIndex=byte2>>2&15;if(!(12<adtsSamplingIndex))return aacSampleIndex=adtsSamplingIndex,5!=(adtsObjectType=1+(byte2>>6&3))&&29!=adtsObjectType||(aacSampleIndex-=3),data=[adtsObjectType<<3|(14&aacSampleIndex)>>1,(1&aacSampleIndex)<<7|(aacSampleIndex=data[offset+3]>>6&3|(1&byte2)<<2)<<3],logger.log("manifest codec:"+manifestCodec+", parsed codec:"+(offset="mp4a.40."+adtsObjectType)+", channels:"+aacSampleIndex+", rate:"+(byte2=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][adtsSamplingIndex])+" (ADTS object type:"+adtsObjectType+" sampling index:"+adtsSamplingIndex+")"),{config:data,samplerate:byte2,channelCount:aacSampleIndex,codec:offset,parsedCodec:offset,manifestCodec:manifestCodec};adtsObjectType=new Error("invalid ADTS sampling index:"+adtsSamplingIndex),observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,error:adtsObjectType,reason:adtsObjectType.message})}(observer,data,offset,audioCodec))&&_extends(track,observer)}function appendFrame$1(track,data,offset,pts,frameIndex){var frameLength,missing,unit,pts=pts+frameIndex*(9216e4/track.samplerate),frameIndex=function(data,offset){var headerLength=getHeaderLength(data,offset);if(offset+headerLength<=data.length){data=getFullFrameLength(data,offset)-headerLength;if(0<data)return{headerLength:headerLength,frameLength:data}}}(data,offset);return frameIndex?(frameLength=frameIndex.frameLength,frameLength=(frameIndex=frameIndex.headerLength)+frameLength,(missing=Math.max(0,offset+frameLength-data.length))?(unit=new Uint8Array(frameLength-frameIndex)).set(data.subarray(offset+frameIndex,data.length),0):unit=data.subarray(offset+frameIndex,offset+frameLength),frameIndex={unit:unit,pts:pts},missing||track.samples.push(frameIndex),{sample:frameIndex,length:frameLength,missing:missing}):(track=data.length-offset,(unit=new Uint8Array(track)).set(data.subarray(offset,data.length),0),{sample:{unit:unit,pts:pts},length:track,missing:-1})}function toUint8(data,offset,length){return function(data,offset,length,Type){var buffer=function(view){return view instanceof ArrayBuffer?view:view.buffer}(data),bytesPerElement=1;"BYTES_PER_ELEMENT"in Type&&(bytesPerElement=Type.BYTES_PER_ELEMENT);var dataOffset=function(obj){return obj&&obj.buffer instanceof ArrayBuffer&&void 0!==obj.byteLength&&void 0!==obj.byteOffset}(data)?data.byteOffset:0,data=(dataOffset+data.byteLength)/bytesPerElement,dataOffset=(dataOffset+offset)/bytesPerElement,offset=Math.floor(Math.max(0,Math.min(dataOffset,data))),bytesPerElement=Math.floor(Math.min(offset+Math.max(length,0),data));return new Type(buffer,offset,bytesPerElement-offset)}(data,offset=void 0===offset?0:offset,length=void 0===length?1/0:length,Uint8Array)}function decodeId3ImageFrame(frame){var metadataFrame={key:frame.type,description:"",data:"",mimeType:null,pictureType:null};if(!(frame.size<2))if(3!==frame.data[0])console.log("Ignore frame with unrecognized character encoding");else{var mimeTypeEndIndex=frame.data.subarray(1).indexOf(0);if(-1!==mimeTypeEndIndex){var description,mimeType=utf8ArrayToStr(toUint8(frame.data,1,mimeTypeEndIndex)),pictureType=frame.data[2+mimeTypeEndIndex],descriptionEndIndex=frame.data.subarray(3+mimeTypeEndIndex).indexOf(0);if(-1!==descriptionEndIndex)return description=utf8ArrayToStr(toUint8(frame.data,3+mimeTypeEndIndex,descriptionEndIndex)),mimeTypeEndIndex="--\x3e"===mimeType?utf8ArrayToStr(toUint8(frame.data,4+mimeTypeEndIndex+descriptionEndIndex)):(frame=frame.data.subarray(4+mimeTypeEndIndex+descriptionEndIndex))instanceof ArrayBuffer?frame:(0==frame.byteOffset&&frame.byteLength==frame.buffer.byteLength?frame:new Uint8Array(frame)).buffer,metadataFrame.mimeType=mimeType,metadataFrame.pictureType=pictureType,metadataFrame.description=description,metadataFrame.data=mimeTypeEndIndex,metadataFrame}}}function decodeId3Frame(frame){return("PRIV"===frame.type?function(frame){var owner,privateData;if(!(frame.size<2))return owner=utf8ArrayToStr(frame.data,!0),privateData=new Uint8Array(frame.data.subarray(owner.length+1)),{key:frame.type,info:owner,data:privateData.buffer}}:"W"===frame.type[0]?function(frame){var index,description;return"WXXX"===frame.type?frame.size<2?void 0:(index=1,index+=(description=utf8ArrayToStr(frame.data.subarray(1),!0)).length+1,index=utf8ArrayToStr(frame.data.subarray(index)),{key:frame.type,info:description,data:index}):(description=utf8ArrayToStr(frame.data),{key:frame.type,info:"",data:description})}:"APIC"===frame.type?decodeId3ImageFrame:function(frame){var index,description;if(!(frame.size<2))return"TXXX"===frame.type?(index=1,index+=(description=utf8ArrayToStr(frame.data.subarray(1),!0)).length+1,index=utf8ArrayToStr(frame.data.subarray(index)),{key:frame.type,info:description,data:index}):(description=utf8ArrayToStr(frame.data.subarray(1)),{key:frame.type,info:"",data:description})})(frame)}var HEADER_FOOTER_SIZE=10,FRAME_SIZE=10;function getId3Frames(id3Data){for(var offset=0,frames=[];isId3Header(id3Data,offset);){for(var size=readId3Size(id3Data,offset+6),end=(id3Data[offset+5]>>6&1&&(offset+=HEADER_FOOTER_SIZE),(offset+=HEADER_FOOTER_SIZE)+size);offset+FRAME_SIZE<end;){var frameData=function(data){var type=String.fromCharCode(data[0],data[1],data[2],data[3]),size=readId3Size(data,4);return{type:type,size:size,data:data.subarray(10,10+size)}}(id3Data.subarray(offset)),frame=decodeId3Frame(frameData);frame&&frames.push(frame),offset+=frameData.size+HEADER_FOOTER_SIZE}isId3Footer(id3Data,offset)&&(offset+=HEADER_FOOTER_SIZE)}return frames}function isId3TimestampFrame(frame){return frame&&"PRIV"===frame.key&&"com.apple.streaming.transportStreamTimestamp"===frame.info}function getId3Timestamp(data){for(var frames=getId3Frames(data),i=0;i<frames.length;i++){var frame=frames[i];if(isId3TimestampFrame(frame))return function(timeStampFrame){var pts33Bit;if(8===timeStampFrame.data.byteLength)return pts33Bit=1&(timeStampFrame=new Uint8Array(timeStampFrame.data))[3],timeStampFrame=(timeStampFrame[4]<<23)+(timeStampFrame[5]<<15)+(timeStampFrame[6]<<7)+timeStampFrame[7],timeStampFrame/=45,pts33Bit&&(timeStampFrame+=47721858.84),Math.round(timeStampFrame)}(frame)}}var MetadataSchema=function(MetadataSchema){return MetadataSchema.audioId3="org.id3",MetadataSchema.dateRange="com.apple.quicktime.HLS",MetadataSchema.emsg="https://aomedia.org/emsg/ID3",MetadataSchema.misbklv="urn:misb:KLV:bin:1910.1",MetadataSchema}({});function dummyTrack(type,inputTimeScale){return{type:type=void 0===type?"":type,id:-1,pid:-1,inputTimeScale:inputTimeScale=void 0===inputTimeScale?9e4:inputTimeScale,sequenceNumber:-1,samples:[],dropped:0}}var BaseSegment=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(initSegment,audioCodec,videoCodec,trackDuration){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(data,offset){return!1},_proto.appendFrame=function(track,data,offset){},_proto.demux=function(data,timeOffset){this.cachedData&&(data=appendUint8Array(this.cachedData,data),this.cachedData=null);var lastDataIndex,frame,id3Data=getId3Data(data,0),offset=id3Data?id3Data.length:0,track=this._audioTrack,id3Track=this._id3Track,timestamp=id3Data?getId3Timestamp(id3Data):void 0,length=data.length;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;)this.canParse(data,offset)?(frame=this.appendFrame(track,data,offset))?(this.frameIndex++,this.lastPTS=frame.sample.pts,lastDataIndex=offset+=frame.length):offset=length:!function(data,offset){return isId3Header(data,offset)&&readId3Size(data,offset+6)+10<=data.length-offset}(data,offset)?offset++:(id3Data=getId3Data(data,offset),id3Track.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:id3Data,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),lastDataIndex=offset+=id3Data.length),offset===length&&lastDataIndex!==length&&(frame=sliceUint8(data,lastDataIndex),this.cachedData?this.cachedData=appendUint8Array(this.cachedData,frame):this.cachedData=frame);return{audioTrack:track,videoTrack:dummyTrack(),id3Track:id3Track,textTrack:dummyTrack()}},_proto.demuxSampleAes=function(data,keyData,timeOffset){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},_proto.flush=function(timeOffset){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(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},BaseAudioDemuxer}(),initPTSFn=function(timestamp,timeOffset,initPTS){return isFiniteNumber(timestamp)?90*timestamp:9e4*timeOffset+(initPTS?9e4*initPTS.baseTime/initPTS.timescale:0)},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];function appendFrame(track,data,offset,pts,frameIndex){var header;return!(offset+24>data.length)&&(header=parseHeader(data,offset))&&offset+header.frameLength<=data.length?(pts=pts+frameIndex*(9e4*header.samplesPerFrame/header.sampleRate),frameIndex={unit:data.subarray(offset,offset+header.frameLength),pts:pts,dts:pts},track.config=[],track.channelCount=header.channelCount,track.samplerate=header.sampleRate,track.samples.push(frameIndex),{sample:frameIndex,length:header.frameLength,missing:0}):void 0}function parseHeader(data,offset){var channelMode,channelCount,bytesInSlot,samplesPerFrame,paddingBit,mpegVersion=data[offset+1]>>3&3,mpegLayer=data[offset+1]>>1&3,bitRateIndex=data[offset+2]>>4&15,sampleRateIndex=data[offset+2]>>2&3;if(1!=mpegVersion&&0!=bitRateIndex&&15!=bitRateIndex&&3!=sampleRateIndex)return paddingBit=data[offset+2]>>1&1,channelMode=data[offset+3]>>6,bitRateIndex=1e3*BitratesMap[14*(3==mpegVersion?3-mpegLayer:3==mpegLayer?3:4)+bitRateIndex-1],sampleRateIndex=SamplingRateMap[3*(3==mpegVersion?0:2==mpegVersion?1:2)+sampleRateIndex],channelCount=3==channelMode?1:2,samplesPerFrame=8*(mpegVersion=SamplesCoefficients[mpegVersion][mpegLayer])*(bytesInSlot=BytesInSlot[mpegLayer]),mpegVersion=Math.floor(mpegVersion*bitRateIndex/sampleRateIndex+paddingBit)*bytesInSlot,null===chromeVersion$1&&(paddingBit=(navigator.userAgent||"").match(/Chrome\/(\d+)/i),chromeVersion$1=paddingBit?parseInt(paddingBit[1]):0),!!chromeVersion$1&&chromeVersion$1<=87&&2==mpegLayer&&224e3<=bitRateIndex&&0==channelMode&&(data[offset+3]=128|data[offset+3]),{sampleRate:sampleRateIndex,channelCount:channelCount,frameLength:mpegVersion,samplesPerFrame:samplesPerFrame}}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 probe(data,offset){var frameLength;if(offset+1<data.length&&isHeaderPattern(data,offset))return frameLength=4,(offset=offset+(frameLength=null!=(offset=parseHeader(data,offset))&&offset.frameLength?offset.frameLength:frameLength))===data.length||isHeader(data,offset)}function getAudioBSID(data,offset){for(var bsid=0,numBits=5,temp=(offset+=numBits,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}var AACDemuxer=function(_BaseAudioDemuxer){function AACDemuxer(observer,config){var _this=_BaseAudioDemuxer.call(this)||this;return _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,logger){if(data){var id3Data=getId3Data(data,0),offset=(null==id3Data?void 0:id3Data.length)||0;if(!probe(data,offset))for(var length=data.length;offset<length;offset++)if(function(data,offset){var frameLength,headerLength;return!isHeader$1(data,offset)||offset+(headerLength=getHeaderLength(data,offset))>=data.length?void 0:!((frameLength=getFullFrameLength(data,offset))<=headerLength)&&((headerLength=offset+frameLength)===data.length||isHeader$1(data,headerLength))}(data,offset))return logger.log("ADTS sync word found !"),!0}return!1},_proto.canParse=function(data,offset){return offset+5<data.length&&isHeaderPattern$1(data,offset)&&getFullFrameLength(data,offset)<=data.length-offset},_proto.appendFrame=function(track,data,offset){initTrackConfig(track,this.observer,data,offset,track.manifestCodec);track=appendFrame$1(track,data,offset,this.basePTS,this.frameIndex);if(track&&0===track.missing)return track},AACDemuxer}(BaseSegment),AC3Demuxer=function(_BaseAudioDemuxer){function AC3Demuxer(observer){var _this=_BaseAudioDemuxer.call(this)||this;return _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){data=_appendFrame(track,data,offset,this.basePTS,this.frameIndex);if(-1!==data)return{sample:track.samples[track.samples.length-1],length:data,missing:0}},AC3Demuxer.probe=function(data){var id3Data,offset;return!!data&&!!(id3Data=getId3Data(data,0))&&11===data[offset=id3Data.length]&&119===data[offset+1]&&void 0!==getId3Timestamp(id3Data)&&getAudioBSID(data,offset)<16},AC3Demuxer}(BaseSegment);function _appendFrame(track,data,start,pts,frameIndex){var sampleRate,frameSizeCode,frameLength,channelMode,skipCount,channelCount,samplingRateCode,bsid,bsmod;return start+8>data.length||11!==data[start]||119!==data[start+1]||3<=(samplingRateCode=data[start+4]>>6)||(sampleRate=[48e3,44100,32e3][samplingRateCode],start+(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=63&data[start+4])+samplingRateCode])>data.length)?-1:(skipCount=0,(2==(channelMode=data[start+6]>>5)||(1&channelMode&&1!=channelMode&&(skipCount+=2),4&channelMode))&&(skipCount+=2),skipCount=(data[start+6]<<8|data[start+7])>>12-skipCount&1,channelCount=[2,1,2,3,3,4,4,5][channelMode]+skipCount,bsid=data[start+5]>>3,bsmod=7&data[start+5],samplingRateCode=new Uint8Array([samplingRateCode<<6|bsid<<1|bsmod>>2,(3&bsmod)<<6|channelMode<<3|skipCount<<2|frameSizeCode>>4,frameSizeCode<<4&224]),bsid=pts+frameIndex*(1536/sampleRate*9e4),bsmod=data.subarray(start,start+frameLength),track.config=samplingRateCode,track.channelCount=channelCount,track.samplerate=sampleRate,track.samples.push({unit:bsmod,pts:bsid}),frameLength)}var BaseSegment=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){var id3Data=getId3Data(data,0),offset=(null==id3Data?void 0:id3Data.length)||0;if(!(id3Data&&11===data[offset]&&119===data[offset+1]&&void 0!==getId3Timestamp(id3Data)&&getAudioBSID(data,offset)<=16))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 isHeaderPattern(data,offset)&&4<=data.length-offset},_proto.appendFrame=function(track,data,offset){if(null!==this.basePTS)return appendFrame(track,data,offset,this.basePTS,this.frameIndex)},MP3Demuxer}(BaseSegment),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 id,timescale,_initData$video,videoTrack=this.videoTrack=dummyTrack("video",1),audioTrack=this.audioTrack=dummyTrack("audio",1),captionTrack=this.txtTrack=dummyTrack("text",1);this.id3Track=dummyTrack("id3",1),this.timeOffset=0,null!=initSegment&&initSegment.byteLength&&((initSegment=parseInitSegment(initSegment)).video&&(id=(_initData$video=initSegment.video).id,timescale=_initData$video.timescale,_initData$video=_initData$video.codec,videoTrack.id=id,videoTrack.timescale=captionTrack.timescale=timescale,videoTrack.codec=_initData$video),initSegment.audio&&(timescale=(id=initSegment.audio).id,_initData$video=id.timescale,initSegment=id.codec,audioTrack.id=timescale,audioTrack.timescale=_initData$video,audioTrack.codec=initSegment),captionTrack.id=RemuxerTrackIdConfig.text,videoTrack.sampleDuration=0,videoTrack.duration=audioTrack.duration=trackDuration)},_proto.resetContiguity=function(){this.remainderData=null},MP4Demuxer.probe=function(data){for(var end=data.byteLength,i=0;i<end;){var size=readUint32(data,i);if(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},_proto.demux=function(data,timeOffset){this.timeOffset=timeOffset;var videoSamples=data,videoTrack=this.videoTrack,textTrack=this.txtTrack,data=(this.config.progressive?(data=function(data){var segmentedRange={valid:null,remainder:null},moofs=findBox(data,["moof"]);return moofs.length<2?segmentedRange.remainder=data:(moofs=moofs[moofs.length-1],segmentedRange.valid=sliceUint8(data,0,moofs.byteOffset-8),segmentedRange.remainder=sliceUint8(data,moofs.byteOffset-8)),segmentedRange}(videoSamples=this.remainderData?appendUint8Array(this.remainderData,data):videoSamples),this.remainderData=data.remainder,videoTrack.samples=data.valid||new Uint8Array):videoTrack.samples=videoSamples,this.extractID3Track(videoTrack,timeOffset));return textTrack.samples=parseSamples(timeOffset,videoTrack),{videoTrack:videoTrack,audioTrack:this.audioTrack,id3Track:data,textTrack:this.txtTrack}},_proto.flush=function(){var timeOffset=this.timeOffset,videoTrack=this.videoTrack,textTrack=this.txtTrack,id3Track=(videoTrack.samples=this.remainderData||new Uint8Array,this.remainderData=null,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 _this=this,id3Track=this.id3Track;return videoTrack.samples.length&&(videoTrack=findBox(videoTrack.samples,["emsg"]))&&videoTrack.forEach(function(data){var pts,duration,payload,data=function(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){var timeScale=readUint32(data,offset+=4),version=readUint32(data,offset+=4),rightPresentationTime=readUint32(data,offset+=4);for(offset+=4,presentationTime=Math.pow(2,32)*version+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),id=readUint32(data,offset+=4),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}return{schemeIdUri:schemeIdUri,value:value,timeScale:timeScale,presentationTime:presentationTime,presentationTimeDelta:presentationTimeDelta,eventDuration:eventDuration,id:id,payload:data.subarray(offset,data.byteLength)}}(data);emsgSchemePattern.test(data.schemeIdUri)?(pts=getEmsgStartTime(data,timeOffset),(duration=4294967295===data.eventDuration?Number.POSITIVE_INFINITY:data.eventDuration/data.timeScale)<=.001&&(duration=Number.POSITIVE_INFINITY),payload=data.payload,id3Track.samples.push({data:payload,len:payload.byteLength,dts:pts,pts:pts,type:MetadataSchema.emsg,duration:duration})):_this.config.enableEmsgKLVMetadata&&data.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")&&(payload=getEmsgStartTime(data,timeOffset),id3Track.samples.push({data:data.payload,len:data.payload.byteLength,dts:payload,pts:payload,type:MetadataSchema.misbklv,duration:Number.POSITIVE_INFINITY}))}),id3Track},_proto.demuxSampleAes=function(data,keyData,timeOffset){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},_proto.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},MP4Demuxer}();function getEmsgStartTime(emsgInfo,timeOffset){return isFiniteNumber(emsgInfo.presentationTime)?emsgInfo.presentationTime/emsgInfo.timeScale:timeOffset+emsgInfo.presentationTimeDelta/emsgInfo.timeScale}var 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,DecrypterAesMode_cbc)},_proto.decryptAacSample=function(samples,sampleIndex,callback){var encryptedData,_this=this,curUnit=samples[sampleIndex].unit;curUnit.length<=16||(encryptedData=(encryptedData=curUnit.subarray(16,curUnit.length-curUnit.length%16)).buffer.slice(encryptedData.byteOffset,encryptedData.byteOffset+encryptedData.length),this.decryptBuffer(encryptedData).then(function(decryptedBuffer){decryptedBuffer=new Uint8Array(decryptedBuffer);curUnit.set(decryptedBuffer,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(!(samples[sampleIndex].unit.length<32)&&(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>=curUnits.length);unitIndex++){var curUnit=curUnits[unitIndex];if(!(curUnit.data.length<=48||1!==curUnit.type&&5!==curUnit.type||(this.decryptAvcSample(samples,sampleIndex,unitIndex,callback,curUnit),this.decrypter.isSync())))return}}},SampleAesDecrypter}(),BaseVideoParser=function(){function BaseVideoParser(){this.VideoSample=null}var _proto=BaseVideoParser.prototype;return _proto.createVideoSample=function(key,pts,dts){return{key:key,frame:!1,pts:pts,dts:dts,units:[],length:0}},_proto.getLastNalUnit=function(samples){var lastUnit,VideoSample=this.VideoSample;return lastUnit=null!=(VideoSample=VideoSample&&0!==VideoSample.units.length?VideoSample:samples[samples.length-1])&&VideoSample.units?(samples=VideoSample.units)[samples.length-1]: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)return void videoTrack.dropped++;samples=samples[nbSamples-1];VideoSample.pts=samples.pts,VideoSample.dts=samples.dts}videoTrack.samples.push(VideoSample)}},_proto.parseNALu=function(track,array,endOfSegment){var _unit,len=array.byteLength,lastState=state=track.naluState||0,units=[],i=0,lastUnitStart=-1,lastUnitType=0;for(-1===state&&(lastUnitType=this.getNALuType(array,lastUnitStart=0),state=0,i=1);i<len;){var unit,overflow,state,value=array[i++];state?state=1===state?value?0:2:value?1===value?(overflow=i-state-1,0<=lastUnitStart?(unit={data:array.subarray(lastUnitStart,overflow),type:lastUnitType},units.push(unit)):(unit=this.getLastNalUnit(track.samples))&&(lastState&&i<=4-lastState&&unit.state&&(unit.data=unit.data.subarray(0,unit.data.byteLength-lastState)),0<overflow)&&(unit.data=appendUint8Array(unit.data,array.subarray(0,overflow)),unit.state=0),i<len?(lastUnitStart=i,lastUnitType=this.getNALuType(array,i),0):-1):0:3:state=value?0:1}return 0<=lastUnitStart&&0<=state&&(_unit={data:array.subarray(lastUnitStart,len),type:lastUnitType,state:state},units.push(_unit)),0===units.length&&(_unit=this.getLastNalUnit(track.samples))&&(_unit.data=appendUint8Array(_unit.data,array)),track.naluState=state,units},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),bytesAvailable=Math.min(4,bytesAvailable);if(0===bytesAvailable)throw new Error("no bytes available");workingBytes.set(data.subarray(position,position+bytesAvailable)),this.word=new DataView(workingBytes.buffer).getUint32(0),this.bitsAvailable=8*bytesAvailable,this.bytesAvailable-=bytesAvailable},_proto.skipBits=function(count){var skipBytes;count=Math.min(count,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>count||(count=(count-=this.bitsAvailable)-((skipBytes=count>>3)<<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))throw new Error("no bits available");this.loadWord()}return 0<(bits=size-bits)&&this.bitsAvailable?valu<<bits|this.readBits(bits):valu},_proto.skipLZ=function(){for(var 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)},ExpGolomb}(),AvcVideoParser=function(_BaseVideoParser){function AvcVideoParser(){return _BaseVideoParser.apply(this,arguments)||this}_inheritsLoose(AvcVideoParser,_BaseVideoParser);var _proto=AvcVideoParser.prototype;return _proto.parsePES=function(track,textTrack,pes,endOfSegment){var push,_this=this,units=this.parseNALu(track,pes.data,endOfSegment),VideoSample=this.VideoSample,spsfound=!1;pes.data=null,VideoSample&&units.length&&!track.audFound&&(this.pushAccessUnit(VideoSample,track),VideoSample=this.VideoSample=this.createVideoSample(!1,pes.pts,pes.dts)),units.forEach(function(unit){switch(unit.type){case 1:var iskey=!1,data=(push=!0,unit.data);spsfound&&4<data.length&&(2!==(data=_this.readSliceType(data))&&4!==data&&7!==data&&9!==data||(iskey=!0)),iskey&&null!=VideoSample&&VideoSample.frame&&!VideoSample.key&&(_this.pushAccessUnit(VideoSample,track),VideoSample=_this.VideoSample=null),(VideoSample=VideoSample||(_this.VideoSample=_this.createVideoSample(!0,pes.pts,pes.dts))).frame=!0,VideoSample.key=iskey;break;case 5:push=!0,null!=VideoSample&&VideoSample.frame&&!VideoSample.key&&(_this.pushAccessUnit(VideoSample,track),VideoSample=_this.VideoSample=null),(VideoSample=VideoSample||(_this.VideoSample=_this.createVideoSample(!0,pes.pts,pes.dts))).key=!0,VideoSample.frame=!0;break;case 6:push=!0,parseSEIMessageFromNALu(unit.data,1,pes.pts,textTrack.samples);break;case 7:spsfound=push=!0;var _track$pixelRatio,data=unit.data,iskey=_this.readSPS(data);if(!track.sps||track.width!==iskey.width||track.height!==iskey.height||(null==(_track$pixelRatio=track.pixelRatio)?void 0:_track$pixelRatio[0])!==iskey.pixelRatio[0]||(null==(_track$pixelRatio=track.pixelRatio)?void 0:_track$pixelRatio[1])!==iskey.pixelRatio[1]){track.width=iskey.width,track.height=iskey.height,track.pixelRatio=iskey.pixelRatio,track.sps=[data];for(var codecarray=data.subarray(1,4),codecstring="avc1.",i=0;i<3;i++){var h=codecarray[i].toString(16);codecstring+=h=h.length<2?"0"+h:h}track.codec=codecstring}break;case 8:push=!0,track.pps=[unit.data];break;case 9:push=!0,track.audFound=!0,null!=VideoSample&&VideoSample.frame&&(_this.pushAccessUnit(VideoSample,track),VideoSample=null),VideoSample=VideoSample||(_this.VideoSample=_this.createVideoSample(!1,pes.pts,pes.dts));break;case 12:push=!0;break;default:push=!1}VideoSample&&push&&VideoSample.units.push(unit)}),endOfSegment&&VideoSample&&(this.pushAccessUnit(VideoSample,track),this.VideoSample=null)},_proto.getNALuType=function(data,offset){return 31&data[offset]},_proto.readSliceType=function(data){data=new ExpGolomb(data);return data.readUByte(),data.readUEG(),data.readUEG()},_proto.skipScalingList=function(count,reader){for(var lastScale=8,nextScale=8,j=0;j<count;j++)lastScale=0===(nextScale=0!==nextScale?(lastScale+reader.readEG()+256)%256:nextScale)?lastScale:nextScale},_proto.readSPS=function(sps){var numRefFramesInPicOrderCntCycle,scalingListCount,i,eg=new ExpGolomb(sps),sps=0,frameCropRightOffset=0,frameCropTopOffset=0,frameCropBottomOffset=0,readUByte=eg.readUByte.bind(eg),readBits=eg.readBits.bind(eg),readUEG=eg.readUEG.bind(eg),readBoolean=eg.readBoolean.bind(eg),skipBits=eg.skipBits.bind(eg),skipEG=eg.skipEG.bind(eg),skipUEG=eg.skipUEG.bind(eg),skipScalingList=this.skipScalingList.bind(this),profileIdc=(readUByte(),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){profileIdc=readUEG();if(3===profileIdc&&skipBits(1),skipUEG(),skipUEG(),skipBits(1),readBoolean())for(scalingListCount=3!==profileIdc?8:12,i=0;i<scalingListCount;i++)readBoolean()&&skipScalingList(i<6?16:64,eg)}skipUEG();profileIdc=readUEG();if(0===profileIdc)readUEG();else if(1===profileIdc)for(skipBits(1),skipEG(),skipEG(),numRefFramesInPicOrderCntCycle=readUEG(),i=0;i<numRefFramesInPicOrderCntCycle;i++)skipEG();skipUEG(),skipBits(1);var profileIdc=readUEG(),skipUEG=readUEG(),readBits=readBits(1),pixelRatio=(0===readBits&&skipBits(1),skipBits(1),readBoolean()&&(sps=readUEG(),frameCropRightOffset=readUEG(),frameCropTopOffset=readUEG(),frameCropBottomOffset=readUEG()),[1,1]);if(readBoolean()&&readBoolean())switch(readUByte()){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()]}return{width:Math.ceil(16*(profileIdc+1)-2*sps-2*frameCropRightOffset),height:(2-readBits)*(skipUEG+1)*16-(readBits?2:4)*(frameCropTopOffset+frameCropBottomOffset),pixelRatio:pixelRatio}},AvcVideoParser}(BaseVideoParser),HevcVideoParser=function(_BaseVideoParser){function HevcVideoParser(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_BaseVideoParser.call.apply(_BaseVideoParser,[this].concat(args))||this).initVPS=null,_this}_inheritsLoose(HevcVideoParser,_BaseVideoParser);var _proto=HevcVideoParser.prototype;return _proto.parsePES=function(track,textTrack,pes,endOfSegment){var push,_this2=this,units=this.parseNALu(track,pes.data,endOfSegment),VideoSample=this.VideoSample,spsfound=!1;pes.data=null,VideoSample&&units.length&&!track.audFound&&(this.pushAccessUnit(VideoSample,track),VideoSample=this.VideoSample=this.createVideoSample(!1,pes.pts,pes.dts)),units.forEach(function(unit){var config;switch(unit.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:(VideoSample=VideoSample||(_this2.VideoSample=_this2.createVideoSample(!1,pes.pts,pes.dts))).frame=!0,push=!0;break;case 16:case 17:case 18:case 21:push=!0,spsfound&&null!=VideoSample&&VideoSample.frame&&!VideoSample.key&&(_this2.pushAccessUnit(VideoSample,track),VideoSample=_this2.VideoSample=null),(VideoSample=VideoSample||(_this2.VideoSample=_this2.createVideoSample(!0,pes.pts,pes.dts))).key=!0,VideoSample.frame=!0;break;case 19:case 20:push=!0,null!=VideoSample&&VideoSample.frame&&!VideoSample.key&&(_this2.pushAccessUnit(VideoSample,track),VideoSample=_this2.VideoSample=null),(VideoSample=VideoSample||(_this2.VideoSample=_this2.createVideoSample(!0,pes.pts,pes.dts))).key=!0,VideoSample.frame=!0;break;case 39:push=!0,parseSEIMessageFromNALu(unit.data,2,pes.pts,textTrack.samples);break;case 32:push=!0,track.vps||(config=_this2.readVPS(unit.data),track.params=_objectSpread2({},config),_this2.initVPS=unit.data),track.vps=[unit.data];break;case 33:if(spsfound=push=!0,"object"==typeof track.params){if(void 0===track.vps||track.vps[0]===_this2.initVPS||void 0===track.sps||_this2.matchSPS(track.sps[0],unit.data)||(_this2.initVPS=track.vps[0],track.sps=track.pps=void 0),!track.sps){var prop,_config=_this2.readSPS(unit.data);for(prop in track.width=_config.width,track.height=_config.height,track.pixelRatio=_config.pixelRatio,track.codec=_config.codecString,track.sps=[],_config.params)track.params[prop]=_config.params[prop]}void 0!==track.vps&&track.vps[0]===_this2.initVPS&&track.sps.push(unit.data)}(VideoSample=VideoSample||(_this2.VideoSample=_this2.createVideoSample(!0,pes.pts,pes.dts))).key=!0;break;case 34:if(push=!0,"object"==typeof track.params){if(!track.pps){track.pps=[];var _prop,_config2=_this2.readPPS(unit.data);for(_prop in _config2)track.params[_prop]=_config2[_prop]}void 0!==track.vps&&track.vps[0]===_this2.initVPS&&track.pps.push(unit.data)}break;case 35:push=!0,track.audFound=!0,null!=VideoSample&&VideoSample.frame&&(_this2.pushAccessUnit(VideoSample,track),VideoSample=null),VideoSample=VideoSample||(_this2.VideoSample=_this2.createVideoSample(!1,pes.pts,pes.dts));break;default:push=!1}VideoSample&&push&&VideoSample.units.push(unit)}),endOfSegment&&VideoSample&&(this.pushAccessUnit(VideoSample,track),this.VideoSample=null)},_proto.getNALuType=function(data,offset){return(126&data[offset])>>>1},_proto.ebsp2rbsp=function(arr){for(var dst=new Uint8Array(arr.byteLength),dstIdx=0,i=0;i<arr.byteLength;i++)2<=i&&3===arr[i]&&0===arr[i-1]&&0===arr[i-2]||(dst[dstIdx]=arr[i],dstIdx++);return new Uint8Array(dst.buffer,0,dstIdx)},_proto.pushAccessUnit=function(VideoSample,videoTrack){_BaseVideoParser.prototype.pushAccessUnit.call(this,VideoSample,videoTrack),this.initVPS&&(this.initVPS=null)},_proto.readVPS=function(vps){vps=new ExpGolomb(vps);return vps.readUByte(),vps.readUByte(),vps.readBits(4),vps.skipBits(2),vps.readBits(6),{numTemporalLayers:vps.readBits(3)+1,temporalIdNested:vps.readBoolean()}},_proto.readSPS=function(sps){for(var eg=new ExpGolomb(this.ebsp2rbsp(sps)),max_sub_layers_minus1=(eg.readUByte(),eg.readUByte(),eg.readBits(4),eg.readBits(3)),sps=(eg.readBoolean(),eg.readBits(2)),general_tier_flag=eg.readBoolean(),general_profile_idc=eg.readBits(5),general_profile_compatibility_flags_1=eg.readUByte(),general_profile_compatibility_flags_2=eg.readUByte(),general_profile_compatibility_flags_3=eg.readUByte(),general_profile_compatibility_flags_4=eg.readUByte(),general_constraint_indicator_flags_1=eg.readUByte(),general_constraint_indicator_flags_2=eg.readUByte(),general_constraint_indicator_flags_3=eg.readUByte(),general_constraint_indicator_flags_4=eg.readUByte(),general_constraint_indicator_flags_5=eg.readUByte(),general_constraint_indicator_flags_6=eg.readUByte(),general_level_idc=eg.readUByte(),sub_layer_profile_present_flags=[],sub_layer_level_present_flags=[],i=0;i<max_sub_layers_minus1;i++)sub_layer_profile_present_flags.push(eg.readBoolean()),sub_layer_level_present_flags.push(eg.readBoolean());if(0<max_sub_layers_minus1)for(var _i=max_sub_layers_minus1;_i<8;_i++)eg.readBits(2);for(var _i2=0;_i2<max_sub_layers_minus1;_i2++)sub_layer_profile_present_flags[_i2]&&(eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte(),eg.readUByte()),sub_layer_level_present_flags[_i2]&&eg.readUByte();eg.readUEG();for(var chroma_format_idc=eg.readUEG(),pic_width_in_luma_samples=(3==chroma_format_idc&&eg.skipBits(1),eg.readUEG()),pic_height_in_luma_samples=eg.readUEG(),conformance_window_flag=eg.readBoolean(),pic_left_offset=0,pic_right_offset=0,pic_top_offset=0,pic_bottom_offset=0,bit_depth_luma_minus8=(conformance_window_flag&&(pic_left_offset+=eg.readUEG(),pic_right_offset+=eg.readUEG(),pic_top_offset+=eg.readUEG(),pic_bottom_offset+=eg.readUEG()),eg.readUEG()),bit_depth_chroma_minus8=eg.readUEG(),log2_max_pic_order_cnt_lsb_minus4=eg.readUEG(),_i3=eg.readBoolean()?0:max_sub_layers_minus1;_i3<=max_sub_layers_minus1;_i3++)eg.skipUEG(),eg.skipUEG(),eg.skipUEG();eg.skipUEG(),eg.skipUEG(),eg.skipUEG(),eg.skipUEG(),eg.skipUEG(),eg.skipUEG();var scaling_list_enabled_flag=eg.readBoolean();if(scaling_list_enabled_flag&&eg.readBoolean())for(var sizeId=0;sizeId<4;sizeId++)for(var matrixId=0;matrixId<(3===sizeId?2:6);matrixId++)if(eg.readBoolean()){var coefNum=Math.min(64,1<<4+(sizeId<<1));1<sizeId&&eg.readEG();for(var _i4=0;_i4<coefNum;_i4++)eg.readEG()}else eg.readUEG();eg.readBoolean(),eg.readBoolean();eg.readBoolean()&&(eg.readUByte(),eg.skipUEG(),eg.skipUEG(),eg.readBoolean());for(var num_short_term_ref_pic_sets=eg.readUEG(),num_delta_pocs=0,_i5=0;_i5<num_short_term_ref_pic_sets;_i5++){var inter_ref_pic_set_prediction_flag=!1;if(inter_ref_pic_set_prediction_flag=0!==_i5?eg.readBoolean():inter_ref_pic_set_prediction_flag){_i5===num_short_term_ref_pic_sets&&eg.readUEG(),eg.readBoolean(),eg.readUEG();for(var next_num_delta_pocs=0,j=0;j<=num_delta_pocs;j++){var used_by_curr_pic_flag=eg.readBoolean(),use_delta_flag=!1;used_by_curr_pic_flag||(use_delta_flag=eg.readBoolean()),(used_by_curr_pic_flag||use_delta_flag)&&next_num_delta_pocs++}num_delta_pocs=next_num_delta_pocs}else{for(var num_negative_pics=eg.readUEG(),num_positive_pics=eg.readUEG(),num_delta_pocs=num_negative_pics+num_positive_pics,_j=0;_j<num_negative_pics;_j++)eg.readUEG(),eg.readBoolean();for(var _j2=0;_j2<num_positive_pics;_j2++)eg.readUEG(),eg.readBoolean()}}if(eg.readBoolean())for(var num_long_term_ref_pics_sps=eg.readUEG(),_i6=0;_i6<num_long_term_ref_pics_sps;_i6++){for(var _j3=0;_j3<log2_max_pic_order_cnt_lsb_minus4+4;_j3++)eg.readBits(1);eg.readBits(1)}var scaling_list_enabled_flag=0,sar_width=1,sar_height=1,fps_fixed=!0,fps_den=1,fps_num=0,default_display_window_flag=(eg.readBoolean(),eg.readBoolean(),!1);if(eg.readBoolean()){if(eg.readBoolean()&&(0<(aspect_ratio_idc=eg.readUByte())&&aspect_ratio_idc<16?(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=eg.readBits(16),sar_height=eg.readBits(16))),eg.readBoolean()&&eg.readBoolean(),eg.readBoolean()&&(eg.readBits(3),eg.readBoolean(),eg.readBoolean())&&(eg.readUByte(),eg.readUByte(),eg.readUByte()),eg.readBoolean()&&(eg.readUEG(),eg.readUEG()),eg.readBoolean(),eg.readBoolean(),eg.readBoolean(),(default_display_window_flag=eg.readBoolean())&&(pic_left_offset+=eg.readUEG(),pic_right_offset+=eg.readUEG(),pic_top_offset+=eg.readUEG(),pic_bottom_offset+=eg.readUEG()),eg.readBoolean()){fps_den=eg.readBits(32),fps_num=eg.readBits(32);if(eg.readBoolean()&&eg.readUEG(),eg.readBoolean()){var nal_hrd_parameters_present_flag=eg.readBoolean(),vcl_hrd_parameters_present_flag=eg.readBoolean(),sub_pic_hrd_params_present_flag=!1;(nal_hrd_parameters_present_flag||vcl_hrd_parameters_present_flag)&&((sub_pic_hrd_params_present_flag=eg.readBoolean())&&(eg.readUByte(),eg.readBits(5),eg.readBoolean(),eg.readBits(5)),eg.readBits(4),eg.readBits(4),sub_pic_hrd_params_present_flag&&eg.readBits(4),eg.readBits(5),eg.readBits(5),eg.readBits(5));for(var _i7=0;_i7<=max_sub_layers_minus1;_i7++){var low_delay_hrd_flag=!1,cpb_cnt=((fps_fixed=eg.readBoolean())||eg.readBoolean()?eg.readEG():low_delay_hrd_flag=eg.readBoolean(),low_delay_hrd_flag?1:eg.readUEG()+1);if(nal_hrd_parameters_present_flag)for(var _j4=0;_j4<cpb_cnt;_j4++)eg.readUEG(),eg.readUEG(),sub_pic_hrd_params_present_flag&&(eg.readUEG(),eg.readUEG()),eg.skipBits(1);if(vcl_hrd_parameters_present_flag)for(var _j5=0;_j5<cpb_cnt;_j5++)eg.readUEG(),eg.readUEG(),sub_pic_hrd_params_present_flag&&(eg.readUEG(),eg.readUEG()),eg.skipBits(1)}}}eg.readBoolean()&&(eg.readBoolean(),eg.readBoolean(),eg.readBoolean(),scaling_list_enabled_flag=eg.readUEG())}for(var aspect_ratio_idc=pic_width_in_luma_samples,height=pic_height_in_luma_samples,pic_width_in_luma_samples=((conformance_window_flag||default_display_window_flag)&&((default_display_window_flag=conformance_window_flag=1)===chroma_format_idc?conformance_window_flag=default_display_window_flag=2:2==chroma_format_idc&&(conformance_window_flag=2),aspect_ratio_idc=pic_width_in_luma_samples-conformance_window_flag*pic_right_offset-conformance_window_flag*pic_left_offset,height=pic_height_in_luma_samples-default_display_window_flag*pic_bottom_offset-default_display_window_flag*pic_top_offset),sps?["A","B","C"][sps]:""),profile_compatibility_buf=general_profile_compatibility_flags_1<<24|general_profile_compatibility_flags_2<<16|general_profile_compatibility_flags_3<<8|general_profile_compatibility_flags_4,profile_compatibility_rev=0,_i8=0;_i8<32;_i8++)profile_compatibility_rev=(profile_compatibility_rev|(profile_compatibility_buf>>_i8&1)<<31-_i8)>>>0;pic_right_offset=profile_compatibility_rev.toString(16);return{codecString:"hvc1."+pic_width_in_luma_samples+general_profile_idc+"."+(pic_right_offset=1===general_profile_idc&&"2"===pic_right_offset?"6":pic_right_offset)+"."+(general_tier_flag?"H":"L")+general_level_idc+".B0",params:{general_tier_flag:general_tier_flag,general_profile_idc:general_profile_idc,general_profile_space:sps,general_profile_compatibility_flags:[general_profile_compatibility_flags_1,general_profile_compatibility_flags_2,general_profile_compatibility_flags_3,general_profile_compatibility_flags_4],general_constraint_indicator_flags:[general_constraint_indicator_flags_1,general_constraint_indicator_flags_2,general_constraint_indicator_flags_3,general_constraint_indicator_flags_4,general_constraint_indicator_flags_5,general_constraint_indicator_flags_6],general_level_idc:general_level_idc,bit_depth:bit_depth_luma_minus8+8,bit_depth_luma_minus8:bit_depth_luma_minus8,bit_depth_chroma_minus8:bit_depth_chroma_minus8,min_spatial_segmentation_idc:scaling_list_enabled_flag,chroma_format_idc:chroma_format_idc,frame_rate:{fixed:fps_fixed,fps:fps_num/fps_den}},width:aspect_ratio_idc,height:height,pixelRatio:[sar_width,sar_height]}},_proto.readPPS=function(pps){pps=new ExpGolomb(this.ebsp2rbsp(pps));pps.readUByte(),pps.readUByte(),pps.skipUEG(),pps.skipUEG(),pps.skipBits(2),pps.skipBits(3),pps.skipBits(2),pps.skipUEG(),pps.skipUEG(),pps.skipEG(),pps.skipBits(2);pps.readBoolean()&&pps.skipUEG(),pps.skipEG(),pps.skipEG(),pps.skipBits(4);var tiles_enabled_flag=pps.readBoolean(),pps=pps.readBoolean(),parallelismType=1;return pps&&tiles_enabled_flag?parallelismType=0:pps?parallelismType=3:tiles_enabled_flag&&(parallelismType=2),{parallelismType:parallelismType}},_proto.matchSPS=function(sps1,sps2){return String.fromCharCode.apply(null,sps1).substr(3)===String.fromCharCode.apply(null,sps2).substr(3)},HevcVideoParser}(BaseVideoParser),BaseVideoParser=function(){function TSDemuxer(observer,config,typeSupported,logger){this.logger=void 0,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._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.logger=logger,this.videoParser=null}TSDemuxer.probe=function(data,logger){data=TSDemuxer.syncOffset(data);return 0<data&&logger.warn("MPEG2-TS detected but first sync word found @ offset "+data),-1!==data},TSDemuxer.syncOffset=function(data){for(var length=data.length,scanwindow=Math.min(940,length-188)+1,i=0;i<scanwindow;){for(var foundPat=!1,packetStart=-1,tsPackets=0,j=i;j<length;j+=188){if(71!==data[j]||length-j!=188&&71!==data[j+188]){if(tsPackets)return-1;break}if(tsPackets++,-1===packetStart&&0!==(packetStart=j)&&(scanwindow=Math.min(packetStart+18612,data.length-188)+1),(foundPat=foundPat||0===parsePID(data,j))&&1<tsPackets&&(0===packetStart&&2<tsPackets||scanwindow<j+188))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._videoTrack.duration=trackDuration,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},_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===flush&&(flush=!1),(isSampleAes=void 0===isSampleAes?!1:isSampleAes)||(this.sampleAes=null);var pes,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;if(this.remainderData&&(len=(data=appendUint8Array(this.remainderData,data)).length,this.remainderData=null),len<188&&!flush)return this.remainderData=data,{audioTrack:audioTrack,videoTrack:videoTrack,id3Track:id3Track,textTrack:textTrack};for(var syncOffset=Math.max(0,TSDemuxer.syncOffset(data)),tsPacketErrors=((len-=(len-syncOffset)%188)<data.byteLength&&!flush&&(this.remainderData=new Uint8Array(data.buffer,len,data.buffer.byteLength-len)),0),start=syncOffset;start<len;start+=188)if(71===data[start]){var stt=!!(64&data[start+1]),pid=parsePID(data,start),offset=void 0;if(1<(48&data[start+3])>>4){if((offset=start+5+data[start+4])===start+188)continue}else offset=start+4;switch(pid){case videoPid:if(stt){if(videoData&&(pes=parsePES(videoData,this.logger))){if(null===this.videoParser)switch(videoTrack.segmentCodec){case"avc":this.videoParser=new AvcVideoParser;break;case"hevc":this.videoParser=new HevcVideoParser}null!==this.videoParser&&this.videoParser.parsePES(videoTrack,textTrack,pes,!1)}videoData={data:[],size:0}}videoData&&(videoData.data.push(data.subarray(offset,start+188)),videoData.size+=start+188-offset);break;case audioPid:if(stt){if(audioData&&(pes=parsePES(audioData,this.logger)))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+188)),audioData.size+=start+188-offset);break;case id3Pid:stt&&(id3Data&&(pes=parsePES(id3Data,this.logger))&&this.parseID3PES(id3Track,pes),id3Data={data:[],size:0}),id3Data&&(id3Data.data.push(data.subarray(offset,start+188)),id3Data.size+=start+188-offset);break;case 0:stt&&(offset+=data[offset]+1),pmtId=this._pmtId=function(data,offset){return(31&data[offset+10])<<8|data[offset+11]}(data,offset);break;case pmtId:stt&&(offset+=data[offset]+1);var parsedPIDs=function(data,offset,typeSupported,isSampleAes,observer,logger){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,sectionLength=(15&data[offset+10])<<8|data[offset+11];offset+=12+sectionLength;for(;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",logger);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",logger);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",logger);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;2<remaining;){106===data[parsePos]&&(!0!==typeSupported.ac3?logger.log("AC-3 audio found, not supported in this browser for now"):(result.audioPid=pid,result.segmentAudioCodec="ac3"));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"),void 0,logger),result;case 36:-1===result.videoPid&&(result.videoPid=pid,result.segmentVideoCodec="hevc",logger.log("HEVC in M2TS found"))}offset+=5+esInfoLength}return result}(data,offset,this.typeSupported,isSampleAes,this.observer,this.logger);0<(videoPid=parsedPIDs.videoPid)&&(videoTrack.pid=videoPid,videoTrack.segmentCodec=parsedPIDs.segmentVideoCodec),0<(audioPid=parsedPIDs.audioPid)&&(audioTrack.pid=audioPid,audioTrack.segmentCodec=parsedPIDs.segmentAudioCodec),0<(id3Pid=parsedPIDs.id3Pid)&&(id3Track.pid=id3Pid),null===unknownPID||pmtParsed||(this.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"),void 0,this.logger),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;return this.remainderData=null,remainderData=remainderData?this.demux(remainderData,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(remainderData),this.sampleAes?this.decrypt(remainderData,this.sampleAes):remainderData},_proto.extractRemainingSamples=function(demuxResult){var pes,audioTrack=demuxResult.audioTrack,videoTrack=demuxResult.videoTrack,id3Track=demuxResult.id3Track,demuxResult=demuxResult.textTrack,videoData=videoTrack.pesData,audioData=audioTrack.pesData,id3Data=id3Track.pesData;if(videoData&&(pes=parsePES(videoData,this.logger))){if(null===this.videoParser)switch(videoTrack.segmentCodec){case"avc":this.videoParser=new AvcVideoParser;break;case"hevc":this.videoParser=new HevcVideoParser}null!==this.videoParser&&(this.videoParser.parsePES(videoTrack,demuxResult,pes,!0),videoTrack.pesData=null)}else videoTrack.pesData=videoData;if(audioData&&(pes=parsePES(audioData,this.logger))){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&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),audioTrack.pesData=audioData;id3Data&&(pes=parsePES(id3Data,this.logger))?(this.parseID3PES(id3Track,pes),id3Track.pesData=null):id3Track.pesData=id3Data},_proto.demuxSampleAes=function(data,keyData,timeOffset){data=this.demux(data,timeOffset,!0,!this.config.progressive),timeOffset=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,keyData);return this.decrypt(data,timeOffset)},_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.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},_proto.parseAACPES=function(track,pes){var offset,len,startOffset=0,aacOverFlow=this.aacOverFlow,data=pes.data;for(aacOverFlow&&(this.aacOverFlow=null,frameMissingBytes=aacOverFlow.missing,sampleLength=aacOverFlow.sample.unit.byteLength,-1===frameMissingBytes?data=appendUint8Array(aacOverFlow.sample.unit,data):(sampleLength=sampleLength-frameMissingBytes,aacOverFlow.sample.unit.set(data.subarray(0,frameMissingBytes),sampleLength),track.samples.push(aacOverFlow.sample),startOffset=aacOverFlow.missing)),offset=startOffset,len=data.length;offset<len-1&&!isHeader$1(data,offset);offset++);if(offset!==startOffset){var frameMissingBytes=offset<len-1,sampleLength=frameMissingBytes?"AAC PES did not start with ADTS header,offset:"+offset:"No ADTS header found in AAC PES";if(emitParsingError(this.observer,new Error(sampleLength),frameMissingBytes,this.logger),!frameMissingBytes)return}if(initTrackConfig(track,this.observer,data,offset,this.audioCodec),void 0!==pes.pts)pts=pes.pts;else{if(!aacOverFlow)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var startOffset=9216e4/track.samplerate,pts=aacOverFlow.sample.pts+startOffset}for(var frame,frameIndex=0;offset<len;){if(offset+=(frame=appendFrame$1(track,data,offset,pts,frameIndex)).length,frame.missing){this.aacOverFlow=frame;break}for(frameIndex++;offset<len-1&&!isHeader$1(data,offset);offset++);}},_proto.parseMPEGPES=function(track,pes){var data=pes.data,length=data.length,frameIndex=0,offset=0,pts=pes.pts;if(void 0===pts)this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");else for(;offset<length;)if(isHeader(data,offset)){var frame=appendFrame(track,data,offset,pts,frameIndex);if(!frame)break;offset+=frame.length,frameIndex++}else offset++},_proto.parseAC3PES=function(track,pes){var data=pes.data,pts=pes.pts;if(void 0===pts)this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");else for(var parsed,length=data.length,frameIndex=0,offset=0;offset<length&&0<(parsed=_appendFrame(track,data,offset,pts,frameIndex++));)offset+=parsed},_proto.parseID3PES=function(id3Track,pes){void 0===pes.pts?this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS"):(pes=_extends({},pes,{type:this._videoTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),id3Track.samples.push(pes))},TSDemuxer}();function parsePID(data,offset){return((31&data[offset+1])<<8)+data[offset+2]}function emitParsingError(observer,error,levelRetry,logger){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){logger.log(type+" with AES-128-CBC encryption found in unencrypted stream")}function parsePES(stream,logger){var pesLen,pesPts,pesDts,i=0,data=stream.data;if(!stream||0===stream.size)return null;for(;data[0].length<19&&1<data.length;)data[0]=appendUint8Array(data[0],data[1]),data.splice(1,1);if(1!==((frag=data[0])[0]<<16)+(frag[1]<<8)+frag[2])return null;if((pesLen=(frag[4]<<8)+frag[5])&&pesLen>stream.size-6)return null;var pesFlags=frag[7],payloadStartOffset=(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?54e5<pesPts-(pesDts=536870912*(14&frag[14])+4194304*(255&frag[15])+16384*(254&frag[16])+128*(255&frag[17])+(254&frag[18])/2)&&(logger.warn(Math.round((pesPts-pesDts)/9e4)+"s delta between PTS and DTS, align them"),pesPts=pesDts):pesDts=pesPts),(pesFlags=frag[8])+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++){var frag,len=(frag=data[j]).byteLength;if(payloadStartOffset){if(len<payloadStartOffset){payloadStartOffset-=len;continue}frag=frag.subarray(payloadStartOffset),len-=payloadStartOffset,payloadStartOffset=0}pesData.set(frag,i),i+=len}return pesLen&&(pesLen-=pesFlags+3),{data:pesData,pts:pesPts,dts:pesDts,len:pesLen}}var AAC=function(){function AAC(){}return AAC.getSilentFrame=function(codec,channelCount){if("mp4a.40.2"===codec){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])}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])}},AAC}(),UINT32_MAX=Math.pow(2,32)-1,MP4=function(){function MP4(){}return MP4.init=function(){for(var i in MP4.types={avc1:[],avcC:[],hvc1:[],hvcC:[],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:[]})MP4.types.hasOwnProperty(i)&&(MP4.types[i]=[i.charCodeAt(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]),videoHdlr=(MP4.HDLR_TYPES={video:videoHdlr,audio:audioHdlr},new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])),audioHdlr=new Uint8Array([0,0,0,0,0,0,0,0]),audioHdlr=(MP4.STTS=MP4.STSC=MP4.STCO=audioHdlr,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]),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,audioHdlr,minorVersion,audioHdlr,avc1Brand),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,videoHdlr))},MP4.box=function(type){for(var size=8,_len=arguments.length,payload=new 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]=size>>24&255,result[1]=size>>16&255,result[2]=size>>8&255,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/(1+UINT32_MAX)),duration=Math.floor(duration%(1+UINT32_MAX));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,timescale>>24&255,timescale>>16&255,timescale>>8&255,255&timescale,upperWordDuration>>24,upperWordDuration>>16&255,upperWordDuration>>8&255,255&upperWordDuration,duration>>24,duration>>16&255,duration>>8&255,255&duration,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,sequenceNumber>>16&255,sequenceNumber>>8&255,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/(1+UINT32_MAX)),duration=Math.floor(duration%(1+UINT32_MAX)),timescale=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,timescale>>24&255,timescale>>16&255,timescale>>8&255,255&timescale,upperWordDuration>>24,upperWordDuration>>16&255,upperWordDuration>>8&255,255&upperWordDuration,duration>>24,duration>>16&255,duration>>8&255,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]);return MP4.box(MP4.types.mvhd,timescale)},MP4.sdtp=function(track){for(var flags,samples=track.samples||[],bytes=new Uint8Array(4+samples.length),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){for(var data,len,sps=[],pps=[],i=0;i<track.sps.length;i++)len=(data=track.sps[i]).byteLength,sps.push(len>>>8&255),sps.push(255&len),sps=sps.concat(Array.prototype.slice.call(data));for(i=0;i<track.pps.length;i++)len=(data=track.pps[i]).byteLength,pps.push(len>>>8&255),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).concat([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,width>>8&255,255&width,height>>8&255,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,hSpacing>>16&255,hSpacing>>8&255,255&hSpacing,vSpacing>>24,vSpacing>>16&255,vSpacing>>8&255,255&vSpacing])))},MP4.esds=function(track){track=track.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(track,[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,samplerate>>8&255,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)):"avc"===track.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(track)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.hvc1(track))},MP4.tkhd=function(track){var id=track.id,duration=track.duration*track.timescale,width=track.width,track=track.height,upperWordDuration=Math.floor(duration/(1+UINT32_MAX)),duration=Math.floor(duration%(1+UINT32_MAX));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,id>>24&255,id>>16&255,id>>8&255,255&id,0,0,0,0,upperWordDuration>>24,upperWordDuration>>16&255,upperWordDuration>>8&255,255&upperWordDuration,duration>>24,duration>>16&255,duration>>8&255,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,width>>8&255,255&width,0,0,track>>8&255,255&track,0,0]))},MP4.traf=function(track,baseMediaDecodeTime){var sampleDependencyTable=MP4.sdtp(track),id=track.id,upperWordBaseMediaDecodeTime=Math.floor(baseMediaDecodeTime/(1+UINT32_MAX)),baseMediaDecodeTime=Math.floor(baseMediaDecodeTime%(1+UINT32_MAX));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,id>>24,id>>16&255,id>>8&255,255&id])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,upperWordBaseMediaDecodeTime>>24,upperWordBaseMediaDecodeTime>>16&255,upperWordBaseMediaDecodeTime>>8&255,255&upperWordBaseMediaDecodeTime,baseMediaDecodeTime>>24,baseMediaDecodeTime>>16&255,baseMediaDecodeTime>>8&255,255&baseMediaDecodeTime])),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){track=track.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,track>>24,track>>16&255,track>>8&255,255&track,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},MP4.trun=function(track,offset){var i,duration,size,flags,sample,samples=track.samples||[],len=samples.length,arraylen=12+16*len,array=new Uint8Array(arraylen);for(array.set(["video"===track.type?1:0,0,15,1,len>>>24&255,len>>>16&255,len>>>8&255,255&len,(offset+=8+arraylen)>>>24&255,offset>>>16&255,offset>>>8&255,255&offset],0),i=0;i<len;i++)duration=(sample=samples[i]).duration,size=sample.size,flags=sample.flags,sample=sample.cts,array.set([duration>>>24&255,duration>>>16&255,duration>>>8&255,255&duration,size>>>24&255,size>>>16&255,size>>>8&255,255&size,flags.isLeading<<2|flags.dependsOn,flags.isDependedOn<<6|flags.hasRedundancy<<4|flags.paddingValue<<1|flags.isNonSync,61440&flags.degradPrio,15&flags.degradPrio,sample>>>24&255,sample>>>16&255,sample>>>8&255,255&sample],12+16*i);return MP4.box(MP4.types.trun,array)},MP4.initSegment=function(tracks){MP4.types||MP4.init();tracks=MP4.moov(tracks);return appendUint8Array(MP4.FTYP,tracks)},MP4.hvc1=function(track){for(var ps=track.params,units=[track.vps,track.sps,track.pps],ps=new Uint8Array([1,ps.general_profile_space<<6|(ps.general_tier_flag?32:0)|ps.general_profile_idc,ps.general_profile_compatibility_flags[0],ps.general_profile_compatibility_flags[1],ps.general_profile_compatibility_flags[2],ps.general_profile_compatibility_flags[3],ps.general_constraint_indicator_flags[0],ps.general_constraint_indicator_flags[1],ps.general_constraint_indicator_flags[2],ps.general_constraint_indicator_flags[3],ps.general_constraint_indicator_flags[4],ps.general_constraint_indicator_flags[5],ps.general_level_idc,240|ps.min_spatial_segmentation_idc>>8,255&ps.min_spatial_segmentation_idc,252|ps.parallelismType,252|ps.chroma_format_idc,248|ps.bit_depth_luma_minus8,248|ps.bit_depth_chroma_minus8,0,parseInt(ps.frame_rate.fps),3|ps.temporal_id_nested<<2|ps.num_temporal_layers<<3|(ps.frame_rate.fixed?64:0),units.length]),length=ps.length,i=0;i<units.length;i+=1){length+=3;for(var j=0;j<units[i].length;j+=1)length+=2+units[i][j].length}for(var hvcC=new Uint8Array(length),iMax=(hvcC.set(ps,0),length=ps.length,units.length-1),_i=0;_i<units.length;_i+=1){hvcC.set(new Uint8Array([32+_i|(_i===iMax?128:0),0,units[_i].length]),length),length+=3;for(var _j=0;_j<units[_i].length;_j+=1)hvcC.set(new Uint8Array([units[_i][_j].length>>8,255&units[_i][_j].length]),length),length+=2,hvcC.set(units[_i][_j],length),length+=units[_i][_j].length}var ps=MP4.box(MP4.types.hvcC,hvcC),width=track.width,height=track.height,hSpacing=track.pixelRatio[0],track=track.pixelRatio[1];return MP4.box(MP4.types.hvc1,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,width>>8&255,255&width,height>>8&255,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]),ps,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,hSpacing>>16&255,hSpacing>>8&255,255&hSpacing,track>>24,track>>16&255,track>>8&255,255&track])))},MP4}(),MPEG_TS_CLOCK_FREQ_HZ=(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,9e4);function toTimescaleFromBase(baseTime,destScale,srcBase,round){baseTime=baseTime*destScale*(srcBase=void 0===srcBase?1:srcBase);return(round=void 0===round?!1:round)?Math.round(baseTime):baseTime}function toMsFromMpegTsClock(baseTime,round){return toTimescaleFromBase(baseTime,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,round)}var chromeVersion=null,safariWebkitVersion=null,MP4Remuxer=function(){function MP4Remuxer(observer,config,typeSupported,logger){this.logger=void 0,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.logger=logger,this.ISGenerated=!1,null===chromeVersion&&(observer=(navigator.userAgent||"").match(/Chrome\/(\d+)/i),chromeVersion=observer?parseInt(observer[1]):0),null===safariWebkitVersion&&(config=navigator.userAgent.match(/Safari\/(\d+)/i),safariWebkitVersion=config?parseInt(config[1]):0)}var _proto=MP4Remuxer.prototype;return _proto.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},_proto.resetTimeStamp=function(defaultTimeStamp){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=defaultTimeStamp},_proto.resetNextTimestamp=function(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},_proto.resetInitSegment=function(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},_proto.getVideoStartPts=function(videoSamples){var rolloverDetected=!1,firstPts=videoSamples[0].pts,videoSamples=videoSamples.reduce(function(minPTS,sample){var sample=sample.pts,delta=sample-minPTS;return delta<-4294967296&&(rolloverDetected=!0,delta=(sample=normalizePts(sample,firstPts))-minPTS),0<delta?minPTS:sample},firstPts);return rolloverDetected&&this.logger.debug("PTS rollover detected"),videoSamples},_proto.remux=function(audioTrack,videoTrack,id3Track,textTrack,timeOffset,accurateTimeOffset,flush,playlistType){var video,audio,initSegment,text,id3,startPTS,independent,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;return((!hasAudio||enoughAudioSamples)&&(!hasVideo||enoughVideoSamples)||this.ISGenerated||flush)&&(this.ISGenerated&&((hasAudio=this.videoTrackConfig)&&(videoTrack.width!==hasAudio.width||videoTrack.height!==hasAudio.height||(null==(flush=videoTrack.pixelRatio)?void 0:flush[0])!==(null==(flush=hasAudio.pixelRatio)?void 0:flush[0])||(null==(flush=videoTrack.pixelRatio)?void 0:flush[1])!==(null==(flush=hasAudio.pixelRatio)?void 0:flush[1]))||!hasAudio&&enoughVideoSamples||null===this.nextAudioPts&&enoughAudioSamples)&&this.resetInitSegment(),this.ISGenerated||(initSegment=this.generateIS(audioTrack,videoTrack,timeOffset,accurateTimeOffset)),flush=this.isVideoContiguous,hasAudio=-1,enoughVideoSamples&&(hasAudio=function(samples){for(var i=0;i<samples.length;i++)if(samples[i].key)return i;return-1}(videoTrack.samples),!flush)&&this.config.forceKeyFrameOnDiscontinuity&&(independent=!0,0<hasAudio?(this.logger.warn("[mp4-remuxer]: Dropped "+hasAudio+" out of "+length+" video samples due to a missing keyframe"),startPTS=this.getVideoStartPts(videoTrack.samples),videoTrack.samples=videoTrack.samples.slice(hasAudio),videoTrack.dropped+=hasAudio,startPTS=videoTimeOffset+=(videoTrack.samples[0].pts-startPTS)/videoTrack.inputTimeScale):-1===hasAudio&&(this.logger.warn("[mp4-remuxer]: No keyframe found out of "+length+" video samples"),independent=!1)),this.ISGenerated)&&(enoughAudioSamples&&enoughVideoSamples&&(length=this.getVideoStartPts(videoTrack.samples),length=(normalizePts(audioTrack.samples[0].pts,length)-length)/videoTrack.inputTimeScale,audioTimeOffset+=Math.max(0,length),videoTimeOffset+=Math.max(0,-length)),enoughAudioSamples?(audioTrack.samplerate||(this.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&&(length=audio?audio.endPTS-audio.startPTS:0,videoTrack.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),initSegment=this.generateIS(audioTrack,videoTrack,timeOffset,accurateTimeOffset)),video=this.remuxVideo(videoTrack,videoTimeOffset,flush,length))):enoughVideoSamples&&(video=this.remuxVideo(videoTrack,videoTimeOffset,flush,0)),video)&&(video.firstKeyFrame=hasAudio,video.independent=-1!==hasAudio,video.firstKeyFramePTS=startPTS),{audio:audio,video:video,initSegment:initSegment,independent:independent,text:text=this.ISGenerated&&this._initPTS&&this._initDTS&&(id3Track.samples.length&&(id3=flushTextTrackMetadataCueSamples(id3Track,timeOffset,this._initPTS,this._initDTS)),textTrack.samples.length)?flushTextTrackUserdataCueSamples(textTrack,timeOffset,this._initPTS):text,id3:id3}},_proto.generateIS=function(audioTrack,videoTrack,timeOffset,accurateTimeOffset){var initDTS,initPTS,timescale,audioSamples=audioTrack.samples,videoSamples=videoTrack.samples,typeSupported=this.typeSupported,tracks={},_initPTS=this._initPTS,accurateTimeOffset=!_initPTS||accurateTimeOffset,container="audio/mp4";if(accurateTimeOffset&&(initPTS=initDTS=1/0),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}},accurateTimeOffset&&(timescale=audioTrack.inputTimeScale,_initPTS&&timescale===_initPTS.timescale?accurateTimeOffset=!1:initPTS=initDTS=audioSamples[0].pts-Math.round(timescale*timeOffset))}if(videoTrack.sps&&videoTrack.pps&&videoSamples.length&&(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}},accurateTimeOffset&&(timescale=videoTrack.inputTimeScale,_initPTS&&timescale===_initPTS.timescale?accurateTimeOffset=!1:(audioSamples=this.getVideoStartPts(videoSamples),_initPTS=Math.round(timescale*timeOffset),initDTS=Math.min(initDTS,normalizePts(videoSamples[0].dts,audioSamples)-_initPTS),initPTS=Math.min(initPTS,audioSamples-_initPTS))),this.videoTrackConfig={width:videoTrack.width,height:videoTrack.height,pixelRatio:videoTrack.pixelRatio}),Object.keys(tracks).length)return this.ISGenerated=!0,accurateTimeOffset?(this._initPTS={baseTime:initPTS,timescale:timescale},this._initDTS={baseTime:initDTS,timescale:timescale}):initPTS=timescale=void 0,{tracks:tracks,initPTS:initPTS,timescale:timescale}},_proto.remuxVideo=function(track,timeOffset,contiguous,audioTrackLength){for(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,initTime=(contiguous&&null!==nextAvcDts||(pts=timeOffset*timeScale,cts=inputSamples[0].pts-normalizePts(inputSamples[0].dts,inputSamples[0].pts),chromeVersion&&null!==nextAvcDts&&Math.abs(pts-cts-nextAvcDts)<15e3?contiguous=!0:nextAvcDts=pts-cts),initPTS.baseTime*timeScale/initPTS.timescale),i=0;i<nbSamples;i++){var 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,a=a.pts-b.pts;return deltadts||a}),pts=inputSamples[0].dts;var cts=inputSamples[inputSamples.length-1].dts-pts,averageSampleDuration=cts?Math.round(cts/(nbSamples-1)):mp4SampleDuration||track.inputTimeScale/30;if(contiguous){var delta=pts-nextAvcDts,initPTS=averageSampleDuration<delta,cts=delta<-1;if((initPTS||cts)&&(initPTS?this.logger.warn((track.segmentCodec||"").toUpperCase()+": "+toMsFromMpegTsClock(delta,!0)+" ms ("+delta+"dts) hole between fragments detected at "+timeOffset.toFixed(3)):this.logger.warn((track.segmentCodec||"").toUpperCase()+": "+toMsFromMpegTsClock(-delta,!0)+" ms ("+delta+"dts) overlapping between fragments detected at "+timeOffset.toFixed(3)),!cts||nextAvcDts>=inputSamples[0].pts||chromeVersion)){var pts=nextAvcDts,firstPTS=inputSamples[0].pts-delta;if(initPTS)inputSamples[0].dts=pts,inputSamples[0].pts=firstPTS;else for(var isPTSOrderRetained=!0,_i=0;_i<inputSamples.length&&!(inputSamples[_i].dts>firstPTS&&isPTSOrderRetained);_i++){var nextSamplePTS,prevPTS=inputSamples[_i].pts;inputSamples[_i].dts-=delta,inputSamples[_i].pts-=delta,_i<inputSamples.length-1&&(isPTSOrderRetained=(nextSamplePTS=inputSamples[_i+1].pts)<=inputSamples[_i].pts==nextSamplePTS<=prevPTS)}this.logger.log("Video: Initial PTS/DTS adjusted: "+toMsFromMpegTsClock(firstPTS,!0)+"/"+toMsFromMpegTsClock(pts,!0)+", delta: "+toMsFromMpegTsClock(delta,!0)+" ms")}}for(var nbNalu=0,naluLen=0,dtsStep=pts=Math.max(0,pts),_i2=0;_i2<nbSamples;_i2++){for(var _sample=inputSamples[_i2],units=_sample.units,nbUnits=units.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+=averageSampleDuration/4|0||1):dtsStep=_sample.dts,minPTS=Math.min(_sample.pts,minPTS),maxPTS=Math.max(_sample.pts,maxPTS)}contiguous=inputSamples[nbSamples-1].dts;var mdat,timeOffset=naluLen+4*nbNalu+8;try{mdat=new Uint8Array(timeOffset)}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:timeOffset,reason:"fail allocating video mdat "+timeOffset})}for(var view=new DataView(mdat.buffer),stretchedLastFrame=(view.setUint32(0,timeOffset),mdat.set(MP4.types.mdat,4),!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,unit=unit.data.byteLength;view.setUint32(offset,unit),offset+=4,mdat.set(unitData,offset),offset+=unit,mp4SampleLength+=4+unit}var lastFrameDuration,ptsDelta=void 0,config=(_i3<nbSamples-1?(mp4SampleDuration=inputSamples[_i3+1].dts-VideoSample.dts,ptsDelta=inputSamples[_i3+1].pts-VideoSample.pts):(config=this.config,lastFrameDuration=0<_i3?VideoSample.dts-inputSamples[_i3-1].dts:averageSampleDuration,ptsDelta=0<_i3?VideoSample.pts-inputSamples[_i3-1].pts:averageSampleDuration,config.stretchShortVideoTrack&&null!==this.nextAudioPts&&Math.floor(config.maxBufferHole*timeScale)<(config=(audioTrackLength?minPTS+audioTrackLength*timeScale:this.nextAudioPts)-VideoSample.pts)?((mp4SampleDuration=config-lastFrameDuration)<0?mp4SampleDuration=lastFrameDuration:stretchedLastFrame=!0,this.logger.log("[mp4-remuxer]: It is approximately "+config/90+" ms to the next segment; using duration "+mp4SampleDuration/90+" ms for the last video frame.")):mp4SampleDuration=lastFrameDuration),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,config))}if(outputSamples.length)if(chromeVersion)chromeVersion<70&&((cts=outputSamples[0].flags).dependsOn=2,cts.isNonSync=0);else if(safariWebkitVersion&&maxPtsDelta-minPtsDelta<maxDtsDelta-minDtsDelta&&averageSampleDuration/maxDtsDelta<.025&&0===outputSamples[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var dts=pts,_i4=0,len=outputSamples.length;_i4<len;_i4++){var nextPts,nextDts=dts+outputSamples[_i4].duration,_pts=dts+outputSamples[_i4].cts;_i4<len-1?(nextPts=nextDts+outputSamples[_i4+1].cts,outputSamples[_i4].duration=nextPts-_pts):outputSamples[_i4].duration=_i4?outputSamples[_i4-1].duration:averageSampleDuration,outputSamples[_i4].cts=0,dts=nextDts}}this.nextAvcDts=nextAvcDts=contiguous+(mp4SampleDuration=stretchedLastFrame||!mp4SampleDuration?averageSampleDuration:mp4SampleDuration),this.videoSampleDuration=mp4SampleDuration,this.isVideoContiguous=!0;initPTS={data1:MP4.moof(track.sequenceNumber++,pts,_extends({},track,{samples:outputSamples})),data2:mdat,startPTS:minPTS/timeScale,endPTS:(maxPTS+mp4SampleDuration)/timeScale,startDTS:pts/timeScale,endDTS:nextAvcDts/timeScale,type:"video",hasAudio:!1,hasVideo:!0,nb:outputSamples.length,dropped:track.dropped};return track.samples=[],track.dropped=0,initPTS},_proto.getSamplesPerFrame=function(track){switch(track.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}},_proto.remuxAudio=function(track,timeOffset,contiguous,accurateTimeOffset,videoTimeOffset){var inputTimeScale=track.inputTimeScale,scaleFactor=inputTimeScale/(track.samplerate||inputTimeScale),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&&Math.abs(timeOffsetMpegTS-nextAudioPts)<9e3||Math.abs(normalizePts(inputSamples[0].pts-initTime,timeOffsetMpegTS)-nextAudioPts)<20*inputSampleDuration),inputSamples.forEach(function(sample){sample.pts=normalizePts(sample.pts-initTime,timeOffsetMpegTS)}),!contiguous||nextAudioPts<0){if(!(inputSamples=inputSamples.filter(function(sample){return 0<=sample.pts})).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&&(this.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(maxAudioFramesDrift*inputSampleDuration<=delta&&duration<1e4&&alignedWithVideo){var missing=Math.round(delta/inputSampleDuration);(nextPts=pts-missing*inputSampleDuration)<0&&(missing--,nextPts+=inputSampleDuration),0===i&&(this.nextAudioPts=nextAudioPts=nextPts),this.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.parsedCodec||track.manifestCodec||track.codec,track.channelCount);fillFrame||(this.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 mdat,firstPTS=null,lastPTS=null,mdatSize=0,sampleLength=inputSamples.length;sampleLength--;)mdatSize+=inputSamples[sampleLength].unit.byteLength;for(var _j2=0,_nbSamples=inputSamples.length;_j2<_nbSamples;_j2++){var audioSample=inputSamples[_j2],unit=audioSample.unit,audioSample=audioSample.pts;if(null!==lastPTS)outputSamples[_j2-1].duration=Math.round((audioSample-lastPTS)/scaleFactor);else{if(firstPTS=audioSample=contiguous&&"aac"===track.segmentCodec?nextAudioPts:audioSample,!(0<mdatSize))return;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})}rawMPEG||(new DataView(mdat.buffer).setUint32(0,mdatSize),mdat.set(MP4.types.mdat,4))}mdat.set(unit,offset);unit=unit.byteLength;offset+=unit,outputSamples.push(new Mp4Sample(!0,mp4SampleDuration,unit,0)),lastPTS=audioSample}timeOffset=outputSamples.length;if(timeOffset)return initPTS=outputSamples[outputSamples.length-1],this.nextAudioPts=nextAudioPts=lastPTS+scaleFactor*initPTS.duration,initPTS={data1:rawMPEG?new Uint8Array(0):MP4.moof(track.sequenceNumber++,firstPTS/scaleFactor,_extends({},track,{samples:outputSamples})),data2:mdat,startPTS:videoTimeOffset=firstPTS/inputTimeScale,endPTS:accurateTimeOffset=nextAudioPts/inputTimeScale,startDTS:videoTimeOffset,endDTS:accurateTimeOffset,type:"audio",hasAudio:!0,hasVideo:!(track.samples=[]),nb:timeOffset},this.isAudioContiguous=!0,initPTS},MP4Remuxer}();function normalizePts(value,reference){var offset;if(null!==reference)for(offset=reference<value?-8589934592:8589934592;4294967296<Math.abs(value-reference);)value+=offset;return value}function flushTextTrackMetadataCueSamples(track,timeOffset,initPTS,initDTS){var length=track.samples.length;if(length){for(var inputTimeScale=track.inputTimeScale,index=0;index<length;index++){var 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;index<length;index++){var 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}}}var now,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(observer,config,typeSupported,logger){this.logger=void 0,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,this.logger=logger}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(function(initSegment,decryptdata){var keyId;return initSegment&&decryptdata&&(keyId=decryptdata.keyId)&&decryptdata.isCommonEncryption&&findBox(initSegment,["moov","trak"]).forEach(function(trak){var trak=findBox(trak,["mdia","minf","stbl","stsd"])[0].subarray(8),encBoxes=findBox(trak,["enca"]),isAudio=0<encBoxes.length;(encBoxes=isAudio?encBoxes:findBox(trak,["encv"])).forEach(function(enc){findBox(isAudio?enc.subarray(28):enc.subarray(78),["sinf"]).forEach(function(sinf){var tencKeyId,sinf=parseSinf(sinf);sinf&&!(tencKeyId=sinf.subarray(8,24)).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)),sinf.set(keyId,8))})})}),initSegment}(initSegment,decryptdata)),this.emitInitSegment=!0},_proto.generateInitSegment=function(initSegment){var initData,tracks,audioCodec=this.audioCodec,videoCodec=this.videoCodec;null!=initSegment&&initSegment.byteLength?((initData=this.initData=parseInitSegment(initSegment)).audio&&(audioCodec=getParsedTrackCodec(initData.audio,ElementaryStreamTypes_AUDIO)),initData.video&&(videoCodec=getParsedTrackCodec(initData.video,ElementaryStreamTypes_VIDEO)),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"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=tracks):(this.initTracks=void 0,this.initData=void 0)},_proto.remux=function(audioTrack,videoTrack,id3Track,textTrack,timeOffset,accurateTimeOffset){var initSegment,duration,startDTS,initData,initPTS=this.initPTS,lastEndTime=this.lastEndTime,result={audio:void 0,video:void 0,text:textTrack,id3:id3Track,initSegment:void 0},videoTrack=(isFiniteNumber(lastEndTime)||(lastEndTime=this.lastEndTime=timeOffset||0),videoTrack.samples);return null!=videoTrack&&videoTrack.length&&(initSegment={initPTS:void 0,timescale:1},null!=(initData=this.initData)&&initData.length||(this.generateInitSegment(videoTrack),initData=this.initData),null!=initData&&initData.length?(this.emitInitSegment&&(initSegment.tracks=this.initTracks,this.emitInitSegment=!1),duration=getDuration(videoTrack,initData),(function(initPTS,startDTS,timeOffset,duration){if(null===initPTS)return 1;duration=Math.max(duration,1),startDTS-=initPTS.baseTime/initPTS.timescale;return Math.abs(startDTS-timeOffset)>duration}(initPTS,startDTS=null===(startDTS=function(initData,fmp4){return findBox(fmp4,["moof","traf"]).reduce(function(result,traf){var tfdt=findBox(traf,["tfdt"])[0],version=tfdt[0],traf=findBox(traf,["tfhd"]).reduce(function(result,tfhd){tfhd=readUint32(tfhd,4),tfhd=initData[tfhd];if(tfhd){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=baseTime*(1+UINT32_MAX$1)+readUint32(tfdt,8)}baseTime=baseTime/(tfhd.timescale||9e4);if(isFiniteNumber(baseTime)&&(null===result||baseTime<result))return baseTime}return result},null);return null!==traf&&isFiniteNumber(traf)&&(null===result||traf<result)?traf:result},null)}(initData,videoTrack))?timeOffset:startDTS,timeOffset,duration)||initSegment.timescale!==initPTS.timescale&&accurateTimeOffset)&&(initSegment.initPTS=startDTS-timeOffset,initPTS&&1===initPTS.timescale&&this.logger.warn("Adjusting initPTS @"+timeOffset+" from "+initPTS.baseTime/initPTS.timescale+" to "+initSegment.initPTS),this.initPTS=initPTS={baseTime:initSegment.initPTS,timescale:1}),audioTrack=(accurateTimeOffset=audioTrack?startDTS-initPTS.baseTime/initPTS.timescale:lastEndTime)+duration,function(initData,fmp4,timeOffset){findBox(fmp4,["moof","traf"]).forEach(function(traf){findBox(traf,["tfhd"]).forEach(function(tfhd){var timescale,tfhd=readUint32(tfhd,4),tfhd=initData[tfhd];tfhd&&(timescale=tfhd.timescale||9e4,findBox(traf,["tfdt"]).forEach(function(tfdt){var baseMediaDecodeTime,version=tfdt[0],offset=timeOffset*timescale;offset&&(baseMediaDecodeTime=readUint32(tfdt,4),0===version?(baseMediaDecodeTime-=offset,writeUint32(tfdt,4,baseMediaDecodeTime=Math.max(baseMediaDecodeTime,0))):(baseMediaDecodeTime=(baseMediaDecodeTime*=Math.pow(2,32))+readUint32(tfdt,8)-offset,baseMediaDecodeTime=Math.max(baseMediaDecodeTime,0),version=Math.floor(baseMediaDecodeTime/(1+UINT32_MAX$1)),offset=Math.floor(baseMediaDecodeTime%(1+UINT32_MAX$1)),writeUint32(tfdt,4,version),writeUint32(tfdt,8,offset)))}))})})}(initData,videoTrack,initPTS.baseTime/initPTS.timescale),0<duration?this.lastEndTime=audioTrack:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp()),startDTS="",(lastEndTime=!!initData.audio)&&(startDTS+="audio"),(duration=!!initData.video)&&(startDTS+="video"),result.audio="audio"===(initData={data1:videoTrack,startPTS:accurateTimeOffset,startDTS:accurateTimeOffset,endPTS:audioTrack,endDTS:audioTrack,type:startDTS,hasAudio:lastEndTime,hasVideo:duration,nb:1,dropped:0}).type?initData:void 0,result.video="audio"!==initData.type?initData:void 0,result.initSegment=initSegment,result.id3=flushTextTrackMetadataCueSamples(id3Track,timeOffset,initPTS,initPTS),textTrack.samples.length&&(result.text=flushTextTrackUserdataCueSamples(textTrack,timeOffset,initPTS))):this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment.")),result},PassThroughRemuxer}();function getParsedTrackCodec(track,type){track=null==track?void 0:track.codec;return track&&4<track.length?track:type===ElementaryStreamTypes_AUDIO?"ec-3"===track||"ac-3"===track||"alac"===track?track:"fLaC"===track||"Opus"===track?getCodecCompatibleName(track,!1):(logger.warn('Unhandled audio codec "'+track+'" in mp4 MAP'),track||"mp4a"):(logger.warn('Unhandled video codec "'+track+'" in mp4 MAP'),track||"avc1")}try{now=self.performance.now.bind(self.performance)}catch(err){now=Date.now}var muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:BaseVideoParser,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:BaseSegment,remux:MP4Remuxer}],Transmuxer=(muxConfig.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer}),function(){function Transmuxer(observer,typeSupported,config,vendor,id,logger){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.id=id,this.logger=logger}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,data=(stats.executeStart=now(),new Uint8Array(data)),currentTransmuxState=this.currentTransmuxState,transmuxConfig=this.transmuxConfig,state=(state&&(this.currentTransmuxState=state),state||currentTransmuxState),currentTransmuxState=state.contiguous,discontinuity=state.discontinuity,trackSwitch=state.trackSwitch,accurateTimeOffset=state.accurateTimeOffset,timeOffset=state.timeOffset,state=state.initSegmentChange,audioCodec=transmuxConfig.audioCodec,videoCodec=transmuxConfig.videoCodec,defaultInitPts=transmuxConfig.defaultInitPts,duration=transmuxConfig.duration,transmuxConfig=transmuxConfig.initSegmentData,keyData=function(data,decryptData){var encryptionType=null;0<data.byteLength&&null!=(null==decryptData?void 0:decryptData.key)&&null!==decryptData.iv&&null!=decryptData.method&&(encryptionType=decryptData);return encryptionType}(data,decryptdata);if(keyData&&isFullSegmentEncryption(keyData.method)){var decrypter=this.getDecrypter(),aesMode=getAesModeFromFullSegmentMethod(keyData.method);if(!decrypter.isSync())return this.asyncResult=!0,this.decryptionPromise=decrypter.webCryptoDecrypt(data,keyData.key.buffer,keyData.iv.buffer,aesMode).then(function(decryptedData){decryptedData=_this.push(decryptedData,null,chunkMeta);return _this.decryptionPromise=null,decryptedData}),this.decryptionPromise;aesMode=decrypter.softwareDecrypt(data,keyData.key.buffer,keyData.iv.buffer,aesMode);if(!(aesMode=-1<chunkMeta.part?(decrypter=decrypter.flush())&&decrypter.buffer:aesMode))return stats.executeEnd=now(),emptyResult(chunkMeta);data=new Uint8Array(aesMode)}decrypter=this.needsProbing(discontinuity,trackSwitch);if(decrypter){aesMode=this.configureTransmuxer(data);if(aesMode)return this.logger.warn("[transmuxer] "+aesMode.message),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:aesMode,reason:aesMode.message}),stats.executeEnd=now(),emptyResult(chunkMeta)}(discontinuity||trackSwitch||state||decrypter)&&this.resetInitSegment(transmuxConfig,audioCodec,videoCodec,duration,decryptdata),(discontinuity||state||decrypter)&&this.resetInitialTimestamp(defaultInitPts),currentTransmuxState||this.resetContiguity();aesMode=this.transmux(data,keyData,timeOffset,accurateTimeOffset,chunkMeta),this.asyncResult=isPromise(aesMode),trackSwitch=this.currentTransmuxState;return trackSwitch.contiguous=!0,trackSwitch.discontinuity=!1,trackSwitch.trackSwitch=!1,stats.executeEnd=now(),aesMode},_proto.flush=function(chunkMeta){var transmuxResults,_this2=this,stats=chunkMeta.transmuxing,decrypter=(stats.executeStart=now(),this.decrypter),currentTransmuxState=this.currentTransmuxState,decryptionPromise=this.decryptionPromise;return decryptionPromise?(this.asyncResult=!0,decryptionPromise.then(function(){return _this2.flush(chunkMeta)})):(transmuxResults=[],decryptionPromise=currentTransmuxState.timeOffset,decrypter&&(currentTransmuxState=decrypter.flush())&&transmuxResults.push(this.push(currentTransmuxState.buffer,null,chunkMeta)),decrypter=this.demuxer,currentTransmuxState=this.remuxer,decrypter&&currentTransmuxState?isPromise(currentTransmuxState=decrypter.flush(decryptionPromise))?(this.asyncResult=!0,currentTransmuxState.then(function(demuxResult){return _this2.flushRemux(transmuxResults,demuxResult,chunkMeta),transmuxResults})):(this.flushRemux(transmuxResults,currentTransmuxState,chunkMeta),this.asyncResult?Promise.resolve(transmuxResults):transmuxResults):(stats.executeEnd=now(),decrypter=[emptyResult(chunkMeta)],this.asyncResult?Promise.resolve(decrypter):decrypter))},_proto.flushRemux=function(transmuxResults,demuxResult,chunkMeta){var audioTrack=demuxResult.audioTrack,videoTrack=demuxResult.videoTrack,id3Track=demuxResult.id3Track,demuxResult=demuxResult.textTrack,_this$currentTransmux=this.currentTransmuxState,accurateTimeOffset=_this$currentTransmux.accurateTimeOffset,_this$currentTransmux=_this$currentTransmux.timeOffset,audioTrack=(this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+chunkMeta.sn+(-1<chunkMeta.part?" part: "+chunkMeta.part:"")+" of "+(this.id===PlaylistLevelType_MAIN?"level":"track")+" "+chunkMeta.level),this.remuxer.remux(audioTrack,videoTrack,id3Track,demuxResult,_this$currentTransmux,accurateTimeOffset,!0,this.id));transmuxResults.push({remuxResult:audioTrack,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){keyData=keyData&&"SAMPLE-AES"===keyData.method?this.transmuxSampleAes(data,keyData,timeOffset,accurateTimeOffset,chunkMeta):this.transmuxUnencrypted(data,timeOffset,accurateTimeOffset,chunkMeta);return keyData},_proto.transmuxUnencrypted=function(data,timeOffset,accurateTimeOffset,chunkMeta){var data=this.demuxer.demux(data,timeOffset,!1,!this.config.progressive),audioTrack=data.audioTrack,videoTrack=data.videoTrack,id3Track=data.id3Track,data=data.textTrack;return{remuxResult:this.remuxer.remux(audioTrack,videoTrack,id3Track,data,timeOffset,accurateTimeOffset,!1,this.id),chunkMeta:chunkMeta}},_proto.transmuxSampleAes=function(data,decryptData,timeOffset,accurateTimeOffset,chunkMeta){var _this3=this;return this.demuxer.demuxSampleAes(data,decryptData,timeOffset).then(function(demuxResult){return{remuxResult:_this3.remuxer.remux(demuxResult.audioTrack,demuxResult.videoTrack,demuxResult.id3Track,demuxResult.textTrack,timeOffset,accurateTimeOffset,!1,_this3.id),chunkMeta:chunkMeta}})},_proto.configureTransmuxer=function(data){for(var mux,_muxConfig$i$demux,config=this.config,observer=this.observer,typeSupported=this.typeSupported,i=0,len=muxConfig.length;i<len;i++)if(null!=(_muxConfig$i$demux=muxConfig[i].demux)&&_muxConfig$i$demux.probe(data,this.logger)){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,this.logger)),demuxer&&demuxer instanceof Demuxer||(this.demuxer=new Demuxer(observer,config,typeSupported,this.logger),this.probe=Demuxer.probe)},_proto.needsProbing=function(discontinuity,trackSwitch){return!this.demuxer||!this.remuxer||discontinuity||trackSwitch},_proto.getDecrypter=function(){return this.decrypter||(this.decrypter=new Decrypter(this.config))},Transmuxer}());var emptyResult=function(chunkMeta){return{remuxResult:{},chunkMeta:chunkMeta}};function isPromise(p){return"then"in p&&p.then instanceof Function}function TransmuxConfig(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}function TransmuxState(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.accurateTimeOffset=accurateTimeOffset,this.trackSwitch=trackSwitch,this.timeOffset=timeOffset,this.initSegmentChange=initSegmentChange}var transmuxers=[];function emitTransmuxComplete(self,transmuxResult,instanceNo){var remuxResult,audio,_transmuxResult$remux;return!!((remuxResult=transmuxResult.remuxResult).audio||remuxResult.video||remuxResult.text||remuxResult.id3||remuxResult.initSegment)&&(remuxResult=[],audio=(_transmuxResult$remux=transmuxResult.remuxResult).audio,_transmuxResult$remux=_transmuxResult$remux.video,audio&&addToTransferable(remuxResult,audio),_transmuxResult$remux&&addToTransferable(remuxResult,_transmuxResult$remux),self.postMessage({event:"transmuxComplete",data:transmuxResult,instanceNo:instanceNo},remuxResult),!0)}function addToTransferable(transferable,track){track.data1&&transferable.push(track.data1.buffer),track.data2&&transferable.push(track.data2.buffer)}function handleFlushResult(self,results,chunkMeta,instanceNo){results.reduce(function(parsed,result){return emitTransmuxComplete(self,result,instanceNo)||parsed},!1)||self.postMessage({event:"transmuxComplete",data:results[0],instanceNo:instanceNo}),self.postMessage({event:"flush",data:chunkMeta,instanceNo:instanceNo})}function forwardMessage(event,data,instanceNo){self.postMessage({event:event,data:data,instanceNo:instanceNo})}"undefined"!=typeof __IN_WORKER__&&__IN_WORKER__&&self.addEventListener("message",function(ev){var data=ev.data,instanceNo=data.instanceNo;if(void 0!==instanceNo){var observer,logger,transmuxer=transmuxers[instanceNo];if("reset"===data.cmd&&(delete transmuxers[data.resetNo],transmuxer&&transmuxer.destroy(),data.cmd="init"),"init"===data.cmd)ev=JSON.parse(data.config),(observer=new EventEmitter).on(Events.FRAG_DECRYPTED,forwardMessage),observer.on(Events.ERROR,forwardMessage),function(logger,instanceNo){for(var logFn in logger)!function(logFn){logger[logFn]=function(message){forwardMessage("workerLog",{logType:logFn,message:message},instanceNo)}}(logFn)}(logger=enableLogs(ev.debug,data.id),instanceNo),transmuxers[instanceNo]=new Transmuxer(observer,data.typeSupported,ev,"",data.id,logger),forwardMessage("init",null,instanceNo);else if(transmuxer)switch(data.cmd){case"configure":transmuxer.configure(data.config);break;case"demux":var transmuxResult=transmuxer.push(data.data,data.decryptdata,data.chunkMeta,data.state);isPromise(transmuxResult)?transmuxResult.then(function(data){emitTransmuxComplete(self,data,instanceNo)}).catch(function(error){forwardMessage(Events.ERROR,{instanceNo:instanceNo,type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:data.chunkMeta,fatal:!1,error:error,err:error,reason:"transmuxer-worker push error"},instanceNo)}):emitTransmuxComplete(self,transmuxResult,instanceNo);break;case"flush":var chunkMeta=data.chunkMeta,transmuxResult=transmuxer.flush(chunkMeta);isPromise(transmuxResult)?transmuxResult.then(function(results){handleFlushResult(self,results,chunkMeta,instanceNo)}).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"},instanceNo)}):handleFlushResult(self,transmuxResult,chunkMeta,instanceNo)}}});var version="1.6.0-beta.2",workerStore={};var transmuxerInstanceCount=0,TransmuxerInterface=function(){function TransmuxerInterface(_hls,id,onTransmuxComplete,onFlush){function forwardMessage(ev,data){(data=data||{}).frag=_this.frag||void 0,ev===Events.ERROR&&(data.parent=_this.id,data.part=_this.part,_this.error=data.error),_this.hls.trigger(ev,data)}var path,workerContext,_this=this,config=(this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=transmuxerInstanceCount++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(event){var data=event.data,hls=_this.hls;if(hls&&null!=data&&data.event&&data.instanceNo===_this.instanceNo)switch(data.event){case"init":var _this$workerContext=null==(_this$workerContext=_this.workerContext)?void 0:_this$workerContext.objectURL;_this$workerContext&&self.URL.revokeObjectURL(_this$workerContext);break;case"transmuxComplete":_this.handleTransmuxComplete(data.data);break;case"flush":_this.onFlush(data.data);break;case"workerLog":hls.logger[data.data.logType]&&hls.logger[data.data.logType](data.data.message);break;default:data.data=data.data||{},data.data.frag=_this.frag,data.data.part=_this.part,data.data.id=_this.id,hls.trigger(data.event,data.data)}},this.onWorkerError=function(event){_this.hls&&(event=new Error(event.message+"  ("+event.filename+":"+event.lineno+")"),_this.hls.config.enableWorker=!1,_this.hls.logger.warn('Error in "'+_this.id+'" Web Worker, fallback to inline'),_this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:event}))},_hls.config),onTransmuxComplete=(this.hls=_hls,this.id=id,this.useWorker=!!config.enableWorker,this.onTransmuxComplete=onTransmuxComplete,this.onFlush=onFlush,this.observer=new EventEmitter,this.observer.on(Events.FRAG_DECRYPTED,forwardMessage),this.observer.on(Events.ERROR,forwardMessage),getM2TSSupportedAudioTypes(config.preferManagedMediaSource));if(this.useWorker&&"undefined"!=typeof Worker){onFlush=this.hls.logger;if(config.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{config.workerPath?(onFlush.log("loading Web Worker "+config.workerPath+' for "'+id+'"'),this.workerContext=(path=config.workerPath,(workerContext=workerStore[path])?(workerContext.clientCount++,workerContext):(workerContext=new self.URL(path,self.location.href).href,workerContext={worker:new self.Worker(workerContext),scriptURL:workerContext,clientCount:1},workerStore[path]=workerContext))):(onFlush.log('injecting Web Worker for "'+id+'"'),this.workerContext=function(){var workerContext=workerStore[version];return workerContext?(workerContext.clientCount++,workerContext):(workerContext=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+__HLS_WORKER_BUNDLE__.toString()+")(true);"],{type:"text/javascript"}),workerContext=self.URL.createObjectURL(workerContext),workerContext={worker:new self.Worker(workerContext),objectURL:workerContext,clientCount:1},workerStore[version]=workerContext)}());var worker=this.workerContext.worker;worker.addEventListener("message",this.onWorkerMessage),worker.addEventListener("error",this.onWorkerError),worker.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:onTransmuxComplete,id:id,config:JSON.stringify(config)})}catch(err){onFlush.warn('Error setting up "'+id+'" Web Worker, fallback to inline',err),this.terminateWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,onTransmuxComplete,config,"",id,_hls.logger)}return}}this.transmuxer=new Transmuxer(this.observer,onTransmuxComplete,config,"",id,_hls.logger)}var _proto=TransmuxerInterface.prototype;return _proto.reset=function(){var instanceNo,config,m2tsTypeSupported;this.frag=null,this.part=null,this.workerContext&&(instanceNo=this.instanceNo,this.instanceNo=transmuxerInstanceCount++,m2tsTypeSupported=getM2TSSupportedAudioTypes((config=this.hls.config).preferManagedMediaSource),this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:instanceNo,typeSupported:m2tsTypeSupported,id:this.id,config:JSON.stringify(config)}))},_proto.terminateWorker=function(){var worker;this.workerContext&&(worker=this.workerContext.worker,this.workerContext=null,worker.removeEventListener("message",this.onWorkerMessage),worker.removeEventListener("error",this.onWorkerError),function(path){var worker,workerContext=workerStore[path||version];workerContext&&1==workerContext.clientCount--&&(worker=workerContext.worker,workerContext=workerContext.objectURL,delete workerStore[path||version],workerContext&&self.URL.revokeObjectURL(workerContext),worker.terminate())}(this.hls.config.workerPath))},_proto.destroy=function(){this.workerContext?(this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null):(transmuxer=this.transmuxer)&&(transmuxer.destroy(),this.transmuxer=null);var transmuxer=this.observer;transmuxer&&transmuxer.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},_proto.push=function(data,initSegmentData,audioCodec,videoCodec,frag,part,duration,accurateTimeOffset,chunkMeta,defaultInitPTS){var _this2=this,instanceNo=(chunkMeta.transmuxing.start=self.performance.now(),this.instanceNo),transmuxer=this.transmuxer,timeOffset=(part||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),progressive=!trackSwitch&&(1==snDiff||0==snDiff&&(1==partDiff||progressive&&partDiff<=0)),now=self.performance.now(),now=((trackSwitch||snDiff||0===frag.stats.parsing.start)&&(frag.stats.parsing.start=now),!part||!partDiff&&progressive||(part.stats.parsing.start=now),!(lastFrag&&(null==(snDiff=frag.initSegment)?void 0:snDiff.url)===(null==(partDiff=lastFrag.initSegment)?void 0:partDiff.url))),snDiff=new TransmuxState(discontinuity,progressive,accurateTimeOffset,trackSwitch,timeOffset,now);progressive&&!discontinuity&&!now||(this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+frag.type+" sn: "+chunkMeta.sn+(-1<chunkMeta.part?" part: "+chunkMeta.part:"")+" "+(this.id===PlaylistLevelType_MAIN?"level":"track")+": "+chunkMeta.level+" id: "+chunkMeta.id+"\n        discontinuity: "+discontinuity+"\n        trackSwitch: "+trackSwitch+"\n        contiguous: "+progressive+"\n        accurateTimeOffset: "+accurateTimeOffset+"\n        timeOffset: "+timeOffset+"\n        initSegmentChange: "+now),lastFrag=new TransmuxConfig(audioCodec,videoCodec,initSegmentData,duration,defaultInitPTS),this.configureTransmuxer(lastFrag)),this.frag=frag,this.part=part,this.workerContext?this.workerContext.worker.postMessage({instanceNo:instanceNo,cmd:"demux",data:data,decryptdata:decryptdata,chunkMeta:chunkMeta,state:snDiff},data instanceof ArrayBuffer?[data]:[]):transmuxer&&(isPromise(partDiff=transmuxer.push(data,decryptdata,chunkMeta,snDiff))?partDiff.then(function(data){_this2.handleTransmuxComplete(data)}).catch(function(error){_this2.transmuxerError(error,chunkMeta,"transmuxer-interface push error")}):this.handleTransmuxComplete(partDiff))},_proto.flush=function(chunkMeta){var _this3=this,instanceNo=(chunkMeta.transmuxing.start=self.performance.now(),this.instanceNo),transmuxer=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:instanceNo,cmd:"flush",chunkMeta:chunkMeta}):transmuxer&&(isPromise(instanceNo=transmuxer.flush(chunkMeta))?instanceNo.then(function(data){_this3.handleFlushResult(data,chunkMeta)}).catch(function(error){_this3.transmuxerError(error,chunkMeta,"transmuxer-interface flush error")}):this.handleFlushResult(instanceNo,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,part:this.part||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.configureTransmuxer=function(config){var instanceNo=this.instanceNo,transmuxer=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:instanceNo,cmd:"configure",config:config}):transmuxer&&transmuxer.configure(config)},_proto.handleTransmuxComplete=function(result){result.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(result)},TransmuxerInterface}();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[subtitleAttribute]})}function subtitleTrackMatchesTextTrack(subtitleTrack,textTrack){return textTrack.label.toLowerCase()===subtitleTrack.name.toLowerCase()&&(!textTrack.language||textTrack.language.toLowerCase()===(subtitleTrack.lang||"").toLowerCase())}var MP4Demuxer=function(_BaseStreamController){function AudioStreamController(hls,fragmentTracker,keyLoader){hls=_BaseStreamController.call(this,hls,fragmentTracker,keyLoader,"audio-stream-controller",PlaylistLevelType_AUDIO)||this;return hls.mainAnchor=null,hls.mainFragLoading=null,hls.audioOnly=!1,hls.bufferedTrack=null,hls.switchingTrack=null,hls.trackId=-1,hls.waitingData=null,hls.mainDetails=null,hls.flushing=!1,hls.bufferFlushed=!1,hls.cachedTrackLoadedData=null,hls.registerListeners(),hls}_inheritsLoose(AudioStreamController,_BaseStreamController);var _proto=AudioStreamController.prototype;return _proto.onHandlerDestroying=function(){this.unregisterListeners(),_BaseStreamController.prototype.onHandlerDestroying.call(this),this.resetItem()},_proto.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},_proto.registerListeners=function(){_BaseStreamController.prototype.registerListeners.call(this);var hls=this.hls;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.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_LOADING,this.onFragLoading,this),hls.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls&&(_BaseStreamController.prototype.unregisterListeners.call(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.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_LOADING,this.onFragLoading,this),hls.off(Events.FRAG_BUFFERED,this.onFragBuffered,this))},_proto.onInitPtsFound=function(event,_ref){var inFlightFrag,frag=_ref.frag,id=_ref.id,initPTS=_ref.initPTS,_ref=_ref.timescale;id===PlaylistLevelType_MAIN&&(id=frag.cc,inFlightFrag=this.fragCurrent,this.initPTS[id]={baseTime:initPTS,timescale:_ref},this.log("InitPTS for cc: "+id+" found from main: "+initPTS+"/"+_ref),this.mainAnchor=frag,this.state===State_WAITING_INIT_PTS?((!(initPTS=this.waitingData)&&!this.loadingParts||initPTS&&initPTS.frag.cc!==id)&&(this.nextLoadPosition=this.findSyncFrag(frag).start),this.tick()):!this.hls.hasEnoughToStart&&inFlightFrag&&inFlightFrag.cc!==id?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(frag).start,inFlightFrag.abortRequests(),this.resetLoadingState()):this.state===State_IDLE&&this.tick())},_proto.findSyncFrag=function(mainFrag){var trackDetails=this.getLevelDetails(),cc=mainFrag.cc;return function(details,cc,fragment){var start,end,fragments;return details&&details.startCC<=cc&&details.endCC>=cc?(start=fragment.start,end=fragment.end,fragments=details.fragments,fragment.relurl||(fragment=details.fragmentHint)&&(fragments=fragments.concat(fragment)),BinarySearch.search(fragments,function(candidate){return candidate.cc<cc||candidate.end<=start?1:candidate.cc>cc||candidate.start>=end?-1:0})):null}(trackDetails,cc,mainFrag)||trackDetails&&findFragWithCC(trackDetails.fragments,cc)||mainFrag},_proto.startLoad=function(startPosition){var lastCurrentTime;this.levels?(lastCurrentTime=this.lastCurrentTime,this.stopLoad(),this.setInterval(100),0<lastCurrentTime&&-1===startPosition?(this.log("Override startPosition with lastCurrentTime @"+lastCurrentTime.toFixed(3)),startPosition=lastCurrentTime,this.state=State_IDLE):this.state=State_WAITING_TRACK,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=startPosition,this.tick()):(this.startPosition=startPosition,this.state=State_STOPPED)},_proto.doTick=function(){switch(this.state){case State_IDLE:this.doTickIdle();break;case State_WAITING_TRACK:var levels=this.levels,trackId=this.trackId,levels=null==levels?void 0:levels[trackId],trackId=null==levels?void 0:levels.details;if(trackId&&!this.waitForLive(levels)){if(this.waitForCdnTuneIn(trackId))break;this.state=State_WAITING_INIT_PTS}break;case State_FRAG_LOADING_WAITING_RETRY:var levels=performance.now(),trackId=this.retryDate;(!trackId||trackId<=levels||null!=(trackId=this.media)&&trackId.seeking)&&(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 cache,complete,mainAnchor,part,levels=this.waitingData;levels?(trackId=levels.frag,part=levels.part,cache=levels.cache,complete=levels.complete,mainAnchor=this.mainAnchor,void 0!==this.initPTS[trackId.cc]?(this.waitingData=null,this.state=State_FRAG_LOADING,part={frag:trackId,part:part,payload:cache.flush().buffer,networkDetails:null},this._handleFragmentLoadProgress(part),complete&&_BaseStreamController.prototype._handleFragmentLoadComplete.call(this,part)):mainAnchor&&mainAnchor.cc!==levels.frag.cc&&(this.log("Waiting fragment cc ("+trackId.cc+") cancelled because video is at cc "+mainAnchor.cc),this.nextLoadPosition=this.findSyncFrag(mainAnchor).start,this.clearWaitingFragment())):this.state=State_IDLE}this.onTickEnd()},_proto.clearWaitingFragment=function(){var waitingData=this.waitingData;waitingData&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(waitingData.frag),this.waitingData=null,this.state!==State_STOPPED)&&(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)},_proto.doTickIdle=function(){var hls=this.hls,levels=this.levels,media=this.media,trackId=this.trackId,config=hls.config;if(this.buffering&&(media||!this.startFragRequested&&config.startFragPrefetch)&&null!=levels&&levels[trackId]){config=levels[trackId],levels=config.details;if(!levels||this.waitForLive(config)||this.waitForCdnTuneIn(levels))this.state=State_WAITING_TRACK,this.startFragRequested=!1;else{trackId=this.mediaBuffer||this.media,trackId=(this.bufferFlushed&&trackId&&(this.bufferFlushed=!1,this.afterBufferFlushed(trackId,ElementaryStreamTypes_AUDIO,PlaylistLevelType_AUDIO)),this.getFwdBufferInfo(trackId,PlaylistLevelType_AUDIO));if(null!==trackId){var bufferedTrack=this.bufferedTrack,switchingTrack=this.switchingTrack;if(!switchingTrack&&this._streamEnded(trackId,levels))hls.trigger(Events.BUFFER_EOS,{type:"audio"}),this.state=State_ENDED;else{var bufferLen=trackId.len,hls=hls.maxBufferLength,fragments=levels.fragments,start=fragments[0].start,loadPosition=this.getLoadPosition(),targetBufferTime=this.flushing?loadPosition:trackId.end;if(switchingTrack&&media&&(loadPosition=loadPosition,bufferedTrack&&!mediaAttributesIdentical(switchingTrack.attrs,bufferedTrack.attrs)&&(targetBufferTime=loadPosition),levels.PTSKnown)&&loadPosition<start&&(trackId.end>start||trackId.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),media.currentTime=start+.05),!(hls<=bufferLen&&!switchingTrack&&targetBufferTime<fragments[fragments.length-1].start)){bufferedTrack=this.getNextFragment(targetBufferTime,levels);if(bufferedTrack=bufferedTrack&&this.isLoopLoading(bufferedTrack,targetBufferTime)?this.getNextFragmentLoopLoading(bufferedTrack,levels,trackId,PlaylistLevelType_MAIN,hls):bufferedTrack){media=null==(loadPosition=this.mainFragLoading)?void 0:loadPosition.frag;if(!this.audioOnly&&this.startFragRequested&&media&&isMediaFragment(media)&&isMediaFragment(bufferedTrack)&&!bufferedTrack.endList&&(!levels.live||!this.loadingParts&&targetBufferTime<this.hls.liveSyncPosition)){start=media;if(bufferedTrack.start>start.end&&(bufferLen=this.fragmentTracker.getFragAtPos(targetBufferTime,PlaylistLevelType_MAIN))&&bufferLen.end>media.end&&(this.mainFragLoading={frag:start=bufferLen,targetBufferTime:null}),bufferedTrack.start>start.end)return}this.loadFragment(bufferedTrack,config,targetBufferTime)}else this.bufferFlushed=!0}}}}}},_proto.onMediaDetaching=function(event,data){this.bufferFlushed=this.flushing=!1,_BaseStreamController.prototype.onMediaDetaching.call(this,event,data)},_proto.onAudioTracksUpdated=function(event,_ref2){_ref2=_ref2.audioTracks;this.resetTransmuxer(),this.levels=_ref2.map(function(mediaPlaylist){return new Level(mediaPlaylist)})},_proto.onAudioTrackSwitching=function(event,data){var altAudio=!!data.url,fragCurrent=(this.trackId=data.id,this.fragCurrent);fragCurrent&&(fragCurrent.abortRequests(),this.removeUnbufferedFrags(fragCurrent.start)),this.resetLoadingState(),altAudio?(this.switchingTrack=data,this.flushAudioIfNeeded(data),this.state!==State_STOPPED&&(this.setInterval(100),this.state=State_IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=data,this.clearInterval())},_proto.onManifestLoading=function(){_BaseStreamController.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},_proto.onLevelLoaded=function(event,data){this.mainDetails=data.details;data=this.cachedTrackLoadedData;data&&(this.cachedTrackLoadedData=null,this.hls.trigger(Events.AUDIO_TRACK_LOADED,data))},_proto.onAudioTrackLoaded=function(event,data){var levels=this.levels,newDetails=data.details,trackId=data.id,mainDetails=this.mainDetails;if(!mainDetails||mainDetails.expired||newDetails.endCC>mainDetails.endCC)this.cachedTrackLoadedData=data,this.state!==State_STOPPED&&(this.state=State_WAITING_TRACK);else if(levels){this.log("Audio track "+trackId+" loaded ["+newDetails.startSN+","+newDetails.endSN+"]"+(newDetails.lastPartSn?"[part-"+newDetails.lastPartSn+"-"+newDetails.lastPartIndex+"]":"")+",duration:"+newDetails.totalduration);var _track$details,levels=levels[trackId],sliding=0;if(newDetails.live||null!=(_track$details=levels.details)&&_track$details.live){if(this.checkLiveUpdate(newDetails),newDetails.deltaUpdateFailed)return;levels.details&&(sliding=this.alignPlaylists(newDetails,levels.details,null==(_track$details=this.levelLastLoaded)?void 0:_track$details.details)),newDetails.alignedSliding||(alignDiscontinuities(newDetails,mainDetails),newDetails.alignedSliding||alignMediaPlaylistByPDT(newDetails,mainDetails),sliding=newDetails.fragmentStart)}levels.details=newDetails,this.levelLastLoaded=levels,this.startFragRequested||this.setStartPosition(mainDetails,sliding),this.hls.trigger(Events.AUDIO_TRACK_UPDATED,{details:newDetails,id:trackId,groupId:data.groupId}),this.state!==State_WAITING_TRACK||this.waitForCdnTuneIn(newDetails)||(this.state=State_IDLE),this.tick()}else this.warn("Audio tracks were reset while loading level "+trackId)},_proto._handleFragmentLoadProgress=function(data){var details,initPTS,_frag$initSegment,partIndex,frag=data.frag,part=data.part,data=data.payload,config=this.config,trackId=this.trackId,levels=this.levels;levels?(levels=levels[trackId])?(details=levels.details)?(config=config.defaultAudioCodec||levels.audioCodec||"mp4a.40.2",levels=(levels=this.transmuxer)||(this.transmuxer=new TransmuxerInterface(this.hls,PlaylistLevelType_AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this))),initPTS=this.initPTS[frag.cc],_frag$initSegment=null==(_frag$initSegment=frag.initSegment)?void 0:_frag$initSegment.data,void 0!==initPTS?(partIndex=part?part.index:-1,partIndex=new ChunkMetadata(frag.level,frag.sn,frag.stats.chunkCount,data.byteLength,partIndex,-1!==partIndex),levels.push(data,_frag$initSegment,config,"",frag,part,details.totalduration,!1,partIndex,initPTS)):(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),(this.waitingData=this.waitingData||{frag:frag,part:part,cache:new ChunkCache,complete:!1}).cache.push(new Uint8Array(data)),this.state!==State_STOPPED&&(this.state=State_WAITING_INIT_PTS))):(this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(frag.start)):this.warn("Audio track is undefined on fragment load progress"):this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+frag.sn+" of level "+frag.level+" will not be buffered")},_proto._handleFragmentLoadComplete=function(fragLoadedData){this.waitingData?this.waitingData.complete=!0:_BaseStreamController.prototype._handleFragmentLoadComplete.call(this,fragLoadedData)},_proto.onBufferReset=function(){this.mediaBuffer=null},_proto.onBufferCreated=function(event,data){this.bufferFlushed=this.flushing=!1;data=data.tracks.audio;data&&(this.mediaBuffer=data.buffer||null)},_proto.onFragLoading=function(event,data){!this.audioOnly&&data.frag.type===PlaylistLevelType_MAIN&&isMediaFragment(data.frag)&&(this.mainFragLoading=data,this.state===State_IDLE)&&this.tick()},_proto.onFragBuffered=function(event,data){var track,frag=data.frag,data=data.part;frag.type!==PlaylistLevelType_AUDIO?this.audioOnly||frag.type!==PlaylistLevelType_MAIN||frag.elementaryStreams.video||frag.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null):this.fragContextChanged(frag)?this.warn("Fragment "+frag.sn+(data?" p: "+data.index:"")+" of level "+frag.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false")):(isMediaFragment(frag)&&(this.fragPrevious=frag,track=this.switchingTrack)&&(this.bufferedTrack=track,this.switchingTrack=null,this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},track))),this.fragBufferedComplete(frag,data),this.media&&this.tick())},_proto.onError=function(event,data){var _data$context;if(data.fatal)this.state=State_ERROR;else 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:data.parent&&"audio"===data.parent&&(data.details===ErrorDetails.BUFFER_APPEND_ERROR?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){_ref3.type!==ElementaryStreamTypes_VIDEO&&(this.flushing=!0)},_proto.onBufferFlushed=function(event,_ref4){var mediaBuffer,_ref4=_ref4.type;_ref4!==ElementaryStreamTypes_VIDEO&&(this.flushing=!1,this.bufferFlushed=!0,this.state===State_ENDED&&(this.state=State_IDLE),mediaBuffer=this.mediaBuffer||this.media)&&(this.afterBufferFlushed(mediaBuffer,_ref4,PlaylistLevelType_AUDIO),this.tick())},_proto._handleTransmuxComplete=function(transmuxResult){var frag,part,details,audio,text,id3,endDTS,mapFragment,id="audio",hls=this.hls,remuxResult=transmuxResult.remuxResult,transmuxResult=transmuxResult.chunkMeta,context=this.getCurrentContext(transmuxResult);context?(frag=context.frag,part=context.part,details=(context=context.level).details,audio=remuxResult.audio,text=remuxResult.text,id3=remuxResult.id3,remuxResult=remuxResult.initSegment,this.fragContextChanged(frag)||!details?this.fragmentTracker.removeFragment(frag):(this.state=State_PARSING,this.switchingTrack&&audio&&this.completeAudioSwitch(this.switchingTrack),null!=remuxResult&&remuxResult.tracks&&(mapFragment=frag.initSegment||frag,this._bufferInitSegment(context,remuxResult.tracks,mapFragment,transmuxResult),hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:mapFragment,id:id,tracks:remuxResult.tracks})),audio&&(context=audio.startPTS,mapFragment=audio.endPTS,remuxResult=audio.startDTS,endDTS=audio.endDTS,part&&(part.elementaryStreams[ElementaryStreamTypes_AUDIO]={startPTS:context,endPTS:mapFragment,startDTS:remuxResult,endDTS:endDTS}),frag.setElementaryStreamInfo(ElementaryStreamTypes_AUDIO,context,mapFragment,remuxResult,endDTS),this.bufferFragmentData(audio,frag,part,transmuxResult)),null!=id3&&null!=(context=id3.samples)&&context.length&&(mapFragment=_extends({id:id,frag:frag,details:details},id3),hls.trigger(Events.FRAG_PARSING_METADATA,mapFragment)),text&&(remuxResult=_extends({id:id,frag:frag,details:details},text),hls.trigger(Events.FRAG_PARSING_USERDATA,remuxResult)))):this.resetWhenMissingContext(transmuxResult)},_proto._bufferInitSegment=function(currentLevel,tracks,frag,chunkMeta){var track;this.state===State_PARSING&&(tracks.video&&delete tracks.video,tracks.audiovideo&&delete tracks.audiovideo,tracks.audio)&&((track=tracks.audio).id="audio",currentLevel=currentLevel.audioCodec,this.log("Init audio buffer, container:"+track.container+", codecs[level/parsed]=["+currentLevel+"/"+track.codec+"]"),currentLevel&&1===currentLevel.split(",").length&&(track.levelCodec=currentLevel),this.hls.trigger(Events.BUFFER_CODECS,tracks),null!=(currentLevel=track.initSegment)&&currentLevel.byteLength&&(tracks={type:"audio",frag:frag,part:null,chunkMeta:chunkMeta,parent:frag.type,data:currentLevel},this.hls.trigger(Events.BUFFER_APPENDING,tracks)),this.tickImmediate())},_proto.loadFragment=function(frag,track,targetBufferTime){var fragState=this.fragmentTracker.getState(frag);this.switchingTrack||fragState===FragmentState_NOT_LOADED||fragState===FragmentState_PARTIAL?isMediaFragment(frag)?null!=(fragState=track.details)&&fragState.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,(fragState=this.mainDetails)&&fragState.fragmentStart!==track.details.fragmentStart&&alignMediaPlaylistByPDT(track.details,fragState)):_BaseStreamController.prototype.loadFragment.call(this,frag,track,targetBufferTime):this._loadInitSegment(frag,track):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}(_optionalSelf$navigat),PassThroughRemuxer=function(_Logger){function BasePlaylistController(hls,logPrefix){logPrefix=_Logger.call(this,logPrefix,hls.logger)||this;return logPrefix.hls=void 0,logPrefix.canLoad=!1,logPrefix.timer=-1,logPrefix.hls=hls,logPrefix}_inheritsLoose(BasePlaylistController,_Logger);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.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 msn,_attr,currentGoal,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){this.warn("Could not construct new URL for Rendition Report: "+error),uri=attr.URI||""}if(uri===playlistUri){foundIndex=i;break}uri===playlistUri.substring(0,uri.length)&&(foundIndex=i)}if(-1!==foundIndex)return _attr=renditionReports[foundIndex],msn=parseInt(_attr["LAST-MSN"])||(null==previous?void 0:previous.lastPartSn),_attr=parseInt(_attr["LAST-PART"])||(null==previous?void 0:previous.lastPartIndex),this.hls.config.lowLatencyMode&&(currentGoal=Math.min(previous.age-previous.partTarget,previous.targetduration),0<=_attr)&&currentGoal>previous.partTarget&&(_attr+=1),currentGoal=current&&getSkipValue(current),new HlsUrlParameters(msn,0<=_attr?_attr:void 0,currentGoal)}},_proto.loadPlaylist=function(hlsUrlParameters){this.clearTimer()},_proto.loadingPlaylist=function(playlist,hlsUrlParameters){this.clearTimer()},_proto.shouldLoadPlaylist=function(playlist){return this.canLoad&&!!playlist&&!!playlist.url&&(!playlist.details||playlist.details.live)},_proto.getUrlWithDirectives=function(uri,hlsUrlParameters){if(hlsUrlParameters)try{return hlsUrlParameters.addDirectives(uri)}catch(error){this.warn("Could not construct new URL with HLS Delivery Directives: "+error)}return uri},_proto.playlistLoaded=function(index,data,previousDetails){var offset,details=data.details,stats=data.stats,now=self.performance.now(),elapsed=stats.loading.first?Math.max(0,now-stats.loading.first):0,timelineOffset=(details.advancedDateTime=Date.now()-elapsed,this.hls.config.timelineOffset);if(timelineOffset!==details.appliedTimelineOffset&&(offset=Math.max(timelineOffset||0,0),details.appliedTimelineOffset=offset,details.fragments.forEach(function(frag){frag.start=frag.playlistOffset+offset})),details.live||null!=previousDetails&&previousDetails.live){var timelineOffset="levelInfo"in data?data.levelInfo:data.track,bufferInfo=(details.reloaded(previousDetails),previousDetails&&0<details.fragments.length&&mergeDetails(previousDetails,details),-1===details.requestScheduled&&(details.requestScheduled=stats.loading.start),this.hls.mainForwardBufferInfo),bufferInfo=bufferInfo?bufferInfo.end-bufferInfo.len:0,bufferInfo=computeReloadInterval(details,1e3*(details.edge-bufferInfo));if(details.requestScheduled+bufferInfo<now?details.requestScheduled=now:details.requestScheduled+=bufferInfo,this.log("live playlist "+index+" "+(details.advanced?"REFRESHED "+details.lastPartSn+"-"+details.lastPartIndex:details.updated?"UPDATED":"MISSED")),this.canLoad&&details.live){var index=void 0,part=void 0;if(details.canBlockReload&&details.endSN&&details.advanced){var lowLatencyMode=this.hls.config.lowLatencyMode,lastPartSn=details.lastPartSn,endSn=details.endSN,lastPartIndex=details.lastPartIndex,atLastPartOfSegment=lastPartSn===endSn,lastPartSn=(-1!==lastPartIndex?part=atLastPartOfSegment?(index=endSn+1,lowLatencyMode?0:lastPartIndex):(index=lastPartSn,lowLatencyMode?lastPartIndex+1:details.maxPartIndex):index=endSn+1,details.age),lastPartIndex=lastPartSn+details.ageHeader,endSn=Math.min(lastPartIndex-details.partTarget,1.5*details.targetduration);if(0<endSn&&(lastPartIndex>3*details.targetduration?(this.log("Playlist last advanced "+lastPartSn.toFixed(2)+"s ago. Omitting segment and part directives."),part=index=void 0):null!=previousDetails&&previousDetails.tuneInGoal&&lastPartIndex-details.partTarget>previousDetails.tuneInGoal?(this.warn("CDN Tune-in goal increased from: "+previousDetails.tuneInGoal+" to: "+endSn+" with playlist age: "+details.age),endSn=0):(index+=lastPartIndex=Math.floor(endSn/details.targetduration),void 0!==part&&(part+=Math.round(endSn%details.targetduration/details.partTarget)),this.log("CDN Tune-in age: "+details.ageHeader+"s last advanced "+lastPartSn.toFixed(2)+"s goal: "+endSn+" skip sn "+lastPartIndex+" to part "+part)),details.tuneInGoal=endSn),lastPartSn=this.getDeliveryDirectives(details,data.deliveryDirectives,index,part),lowLatencyMode||!atLastPartOfSegment)return details.requestScheduled=now,void this.loadingPlaylist(timelineOffset,lastPartSn)}else(details.canBlockReload||details.canSkipUntil)&&(lastPartSn=this.getDeliveryDirectives(details,data.deliveryDirectives,index,part));lastPartSn&&void 0!==index&&details.canBlockReload&&(details.requestScheduled=stats.loading.first+Math.max(bufferInfo-2*elapsed,bufferInfo/2)),this.scheduleLoading(timelineOffset,lastPartSn,details)}}else this.clearTimer()},_proto.scheduleLoading=function(levelOrTrack,deliveryDirectives,updatedDetails){var now,_this2=this,updatedDetails=updatedDetails||levelOrTrack.details;!updatedDetails||(now=self.performance.now(),(updatedDetails=updatedDetails.requestScheduled)<=now)?this.loadingPlaylist(levelOrTrack,deliveryDirectives):(updatedDetails=updatedDetails-now,this.log("reload live playlist "+(levelOrTrack.name||levelOrTrack.bitrate+"bps")+" in "+Math.round(updatedDetails)+" ms"),this.clearTimer(),this.timer=self.setTimeout(function(){return _this2.loadingPlaylist(levelOrTrack,deliveryDirectives)},updatedDetails))},_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 _this3=this,errorDetails=errorEvent.details,isTimeout=isTimeoutError(errorEvent),errorAction=errorEvent.errorAction,_ref=errorAction||{},action=_ref.action,_ref$retryCount=_ref.retryCount,_ref$retryCount=void 0===_ref$retryCount?0:_ref$retryCount,_ref=_ref.retryConfig,action=!!errorAction&&!!_ref&&(action===NetworkErrorAction_RetryRequest||!errorAction.resolved&&action===NetworkErrorAction_SendAlternateToPenaltyBox);if(action){if(_ref$retryCount>=_ref.maxNumRetry)return!1;isTimeout&&null!=(isTimeout=errorEvent.context)&&isTimeout.deliveryDirectives?(this.warn("Retrying playlist loading "+(_ref$retryCount+1)+"/"+_ref.maxNumRetry+' after "'+errorDetails+'" without delivery-directives'),this.loadPlaylist()):(isTimeout=getRetryDelay(_ref,_ref$retryCount),this.clearTimer(),this.timer=self.setTimeout(function(){return _this3.loadPlaylist()},isTimeout),this.warn("Retrying playlist loading "+(_ref$retryCount+1)+"/"+_ref.maxNumRetry+' after "'+errorDetails+'" in '+isTimeout+"ms")),errorEvent.levelRetry=!0,errorAction.resolved=!0}return action},BasePlaylistController}(Logger),BaseVideoParser=function(_BasePlaylistControll){function AudioTrackController(hls){hls=_BasePlaylistControll.call(this,hls,"audio-track-controller")||this;return hls.tracks=[],hls.groupIds=null,hls.tracksInGroup=[],hls.trackId=-1,hls.currentTrack=null,hls.selectDefaultTrack=!0,hls.registerListeners(),hls}_inheritsLoose(AudioTrackController,_BasePlaylistControll);var _proto=AudioTrackController.prototype;return _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 curDetails,id=data.id,groupId=data.groupId,details=data.details,trackInActiveGroup=this.tracksInGroup[id];trackInActiveGroup&&trackInActiveGroup.groupId===groupId?(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)):this.warn("Audio track with id:"+id+" and group:"+groupId+" not found in active group "+(null==trackInActiveGroup?void 0:trackInActiveGroup.groupId))},_proto.onLevelLoading=function(event,data){this.switchLevel(data.level)},_proto.onLevelSwitching=function(event,data){this.switchLevel(data.level)},_proto.switchLevel=function(levelIndex){levelIndex=this.hls.levels[levelIndex];if(levelIndex){var audioGroups=levelIndex.audioGroups||null,currentGroups=this.groupIds,levelIndex=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(!levelIndex&&!this.tracksInGroup.length)return;this.tracksInGroup=audioTracks;var audioPreference=this.hls.config.audioPreference,audioPreference=(!levelIndex&&audioPreference&&(levelIndex=-1<(groupIndex=findMatchingOption(audioPreference,audioTracks,audioMatchPredicate))?audioTracks[groupIndex]:(groupIndex=findMatchingOption(audioPreference,this.tracks),this.tracks[groupIndex])),this.findTrackId(levelIndex)),groupIndex=(-1===audioPreference&&levelIndex&&(audioPreference=this.findTrackId(null)),{audioTracks:audioTracks}),levelIndex=(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,groupIndex),this.trackId);-1!==audioPreference&&-1===levelIndex?this.setAudioTrack(audioPreference):audioTracks.length&&-1===levelIndex&&(audioPreference=new Error("No audio track selected for current audio group-ID(s): "+(null==(groupIndex=this.groupIds)?void 0:groupIndex.join(","))+" track count: "+audioTracks.length),this.warn(audioPreference.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:audioPreference}))}}},_proto.onError=function(event,data){data.fatal||!data.context||data.context.type!==PlaylistContextType_AUDIO_TRACK||data.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(data.context.groupId)||this.checkRetry(data)},_proto.setAudioOption=function(audioOption){var hls=this.hls;if(hls.config.audioPreference=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)return track=this.tracksInGroup[groupIndex],this.setAudioTrack(groupIndex),track;if(currentTrack){var groupIndex=hls.loadLevel,track=(-1===groupIndex&&(groupIndex=hls.firstAutoLevel),function(option,levels,allAudioTracks,searchIndex,matchPredicate){var currentLevel=levels[searchIndex],renditions=levels.reduce(function(variantMap,level,index){level=level.uri;return(variantMap[level]||(variantMap[level]=[])).push(index),variantMap},{})[currentLevel.uri],currentVideoRange=(1<renditions.length&&(searchIndex=Math.max.apply(Math,renditions)),currentLevel.videoRange),currentFrameRate=currentLevel.frameRate,currentVideoCodec=currentLevel.codecSet.substring(0,4);return-1<(renditions=searchDownAndUpList(levels,searchIndex,function(level){var audioGroups;if(level.videoRange===currentVideoRange&&level.frameRate===currentFrameRate&&level.codecSet.substring(0,4)===currentVideoCodec)return audioGroups=level.audioGroups,level=allAudioTracks.filter(function(track){return!audioGroups||-1!==audioGroups.indexOf(track.groupId)}),-1<findMatchingOption(option,level,matchPredicate)}))?renditions:searchDownAndUpList(levels,searchIndex,function(level){var audioGroups=level.audioGroups,level=allAudioTracks.filter(function(track){return!audioGroups||-1!==audioGroups.indexOf(track.groupId)});return-1<findMatchingOption(option,level,matchPredicate)})}(audioOption,hls.levels,allAudioTracks,groupIndex,audioMatchPredicate));if(-1===track)return null;hls.nextLoadLevel=track}if(audioOption.channels||audioOption.audioCodec){currentTrack=findMatchingOption(audioOption,allAudioTracks);if(-1<currentTrack)return allAudioTracks[currentTrack]}}}return null},_proto.setAudioTrack=function(newId){var lastTrack,trackLoaded,tracks=this.tracksInGroup;newId<0||newId>=tracks.length?this.warn("Invalid audio track id: "+newId):(this.selectDefaultTrack=!1,lastTrack=this.currentTrack,trackLoaded=(tracks=tracks[newId]).details&&!tracks.details.live,newId===this.trackId&&tracks===lastTrack&&trackLoaded||(this.log("Switching to audio-track "+newId+' "'+tracks.name+'" lang:'+tracks.lang+" group:"+tracks.groupId+" channels:"+tracks.channels),this.trackId=newId,this.currentTrack=tracks,this.hls.trigger(Events.AUDIO_TRACK_SWITCHING,_objectSpread2({},tracks)),trackLoaded)||(newId=this.switchParams(tracks.url,null==lastTrack?void 0:lastTrack.details,tracks.details),this.loadPlaylist(newId)))},_proto.findTrackId=function(currentTrack){for(var audioTracks=this.tracksInGroup,i=0;i<audioTracks.length;i++){var track=audioTracks[i];if((!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;_i<audioTracks.length;_i++)if(matchesOption({name:name,lang:lang,assocLang:assocLang,characteristics:characteristics,audioCodec:audioCodec,channels:channels},audioTracks[_i],audioMatchPredicate))return _i;for(var _i2=0;_i2<audioTracks.length;_i2++){var _track2=audioTracks[_i2];if(mediaAttributesIdentical(currentTrack.attrs,_track2.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return _i2}for(var _i3=0;_i3<audioTracks.length;_i3++){var _track3=audioTracks[_i3];if(mediaAttributesIdentical(currentTrack.attrs,_track3.attrs,["LANGUAGE"]))return _i3}}return-1},_proto.loadPlaylist=function(hlsUrlParameters){_BasePlaylistControll.prototype.loadPlaylist.call(this);var audioTrack=this.currentTrack;this.shouldLoadPlaylist(audioTrack)&&useAlternateAudio(audioTrack.url,this.hls)&&this.scheduleLoading(audioTrack,hlsUrlParameters)},_proto.loadingPlaylist=function(audioTrack,hlsUrlParameters){_BasePlaylistControll.prototype.loadingPlaylist.call(this,audioTrack,hlsUrlParameters);var id=audioTrack.id,groupId=audioTrack.groupId,url=this.getUrlWithDirectives(audioTrack.url,hlsUrlParameters),details=audioTrack.details,age=null==details?void 0:details.age;this.log("Loading audio-track "+id+' "'+audioTrack.name+'" lang:'+audioTrack.lang+" group:"+groupId+(void 0!==(null==hlsUrlParameters?void 0:hlsUrlParameters.msn)?" at sn "+hlsUrlParameters.msn+" part "+hlsUrlParameters.part:"")+(age&&details.live?" age "+age.toFixed(1)+(details.type&&" "+details.type||""):"")+" "+url),this.hls.trigger(Events.AUDIO_TRACK_LOADING,{url:url,id:id,groupId:groupId,deliveryDirectives:hlsUrlParameters||null,track:audioTrack})},_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)}}])}(PassThroughRemuxer),BufferOperationQueue=function(){function BufferOperationQueue(sourceBufferReference){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=sourceBufferReference}var _proto=BufferOperationQueue.prototype;return _proto.destroy=function(){this.tracks=this.queues=null},_proto.append=function(operation,type,pending){var queue;null===this.queues||null===this.tracks||((queue=this.queues[type]).push(operation),1!==queue.length)||pending||this.executeNext(type)},_proto.appendBlocker=function(type){var _this=this;return new Promise(function(resolve){_this.append({label:"async-blocker",execute:resolve,onStart:function(){},onComplete:function(){},onError:function(){}},type)})},_proto.prependBlocker=function(type){var _this2=this;return new Promise(function(resolve){_this2.queues&&_this2.queues[type].unshift({label:"async-blocker-prepend",execute:resolve,onStart:function(){},onComplete:function(){},onError:function(){}})})},_proto.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(queue){var _queue$=null==(_queue$=queue[0])?void 0:_queue$.label;"async-blocker"!==_queue$&&"async-blocker-prepend"!==_queue$||(queue[0].execute(),queue.splice(0,1))})},_proto.unblockAudio=function(op){null!==this.queues&&this.queues.audio[0]===op&&this.shiftAndExecuteNext("audio")},_proto.executeNext=function(type){if(null!==this.queues&&null!==this.tracks){var queue=this.queues[type];if(queue.length){var queue=queue[0];try{queue.execute()}catch(error){queue.onError(error),null===this.queues||null===this.tracks||null!=(queue=null==(queue=this.tracks[type])?void 0:queue.buffer)&&queue.updating||this.shiftAndExecuteNext(type)}}}},_proto.shiftAndExecuteNext=function(type){null!==this.queues&&(this.queues[type].shift(),this.executeNext(type))},_proto.current=function(type){var _this$queues;return(null==(_this$queues=this.queues)?void 0:_this$queues[type][0])||null},_proto.toString=function(){var queues=this.queues,tracks=this.tracks;return null===queues||null===tracks?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},_proto.list=function(type){var _this$queues2;return null!=(_this$queues2=this.queues)&&_this$queues2[type]||null!=(_this$queues2=this.tracks)&&_this$queues2[type]?type+": ("+this.listSbInfo(type)+") "+this.listOps(type):""},_proto.listSbInfo=function(type){var _this$tracks2=null==(_this$tracks2=this.tracks)?void 0:_this$tracks2[type],type=null==_this$tracks2?void 0:_this$tracks2.buffer;return type?"SourceBuffer"+(type.updating?" updating":"")+(_this$tracks2.ended?" ended":"")+(_this$tracks2.ending?" ending":""):"none"},_proto.listOps=function(type){var _this$queues3;return(null==(_this$queues3=this.queues)?void 0:_this$queues3[type].map(function(op){return op.label}).join(", "))||""},BufferOperationQueue}(),VIDEO_CODEC_PROFILE_REPLACE=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,HlsJsTrackRemovedError=function(_Error){function HlsJsTrackRemovedError(message){message=_Error.call(this,message)||this;return message.name="HlsJsTrackRemovedError",message}return _inheritsLoose(HlsJsTrackRemovedError,_Error),HlsJsTrackRemovedError}(_wrapNativeSuper(Error)),AACDemuxer=function(_Logger){function BufferController(hls,fragmentTracker){var _this2=_Logger.call(this,"buffer-controller",hls.logger)||this;return _this2.hls=void 0,_this2.fragmentTracker=void 0,_this2.details=null,_this2._objectUrl=null,_this2.operationQueue=null,_this2.bufferCodecEventsTotal=0,_this2.media=null,_this2.mediaSource=null,_this2.lastMpegAudioChunk=null,_this2.blockedAudioAppend=null,_this2.lastVideoAppendEnd=0,_this2.appendSource=void 0,_this2.transferData=void 0,_this2.overrides=void 0,_this2.appendErrors={audio:0,video:0,audiovideo:0},_this2.tracks={},_this2.sourceBuffers=[[null,null],[null,null]],_this2._onEndStreaming=function(event){var _this2$mediaSource;_this2.hls&&"open"===(null==(_this2$mediaSource=_this2.mediaSource)?void 0:_this2$mediaSource.readyState)&&_this2.hls.pauseBuffering()},_this2._onStartStreaming=function(event){_this2.hls&&_this2.hls.resumeBuffering()},_this2._onMediaSourceOpen=function(e){var _this3=_this2,media=_this3.media,_this3=_this3.mediaSource;e&&_this2.log("Media source opened"),media&&_this3&&(media.removeEventListener("emptied",_this2._onMediaEmptied),_this2.updateDuration(),_this2.hls.trigger(Events.MEDIA_ATTACHED,{media:media,mediaSource:_this3}),_this3.removeEventListener("sourceopen",_this2._onMediaSourceOpen),null!==_this2.mediaSource)&&_this2.checkPendingTracks()},_this2._onMediaSourceClose=function(){_this2.log("Media source closed")},_this2._onMediaSourceEnded=function(){_this2.log("Media source ended")},_this2._onMediaEmptied=function(){var _this4=_this2,mediaSrc=_this4.mediaSrc,_this4=_this4._objectUrl;mediaSrc!==_this4&&_this2.error("Media element src was set while attaching MediaSource ("+_this4+" > "+mediaSrc+")")},_this2.hls=hls,_this2.fragmentTracker=fragmentTracker,_this2.appendSource=(fragmentTracker=getMediaSource(hls.config.preferManagedMediaSource),"undefined"!=typeof self&&fragmentTracker===self.ManagedMediaSource),_this2.initTracks(),_this2.registerListeners(),_this2}_inheritsLoose(BufferController,_Logger);var _proto=BufferController.prototype;return _proto.hasSourceTypes=function(){return 0<Object.keys(this.tracks).length},_proto.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},_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),hls.on(Events.ERROR,this.onError,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),hls.off(Events.ERROR,this.onError,this)},_proto.transferMedia=function(){var tracks,updating,queued,_this5=this,media=this.media,mediaSource=this.mediaSource;return media?(tracks={},this.operationQueue&&((updating=this.isUpdating())||this.operationQueue.removeBlockers(),queued=this.isQueued(),(updating||queued)&&this.warn("Transfering MediaSource with"+(queued?" operations in queue":"")+(updating?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()),queued=this.transferData,!this.sourceBufferCount&&queued&&queued.mediaSource===mediaSource?_extends(tracks,queued.tracks):this.sourceBuffers.forEach(function(tuple){var type=tuple[0];type&&(tracks[type]=_extends({},_this5.tracks[type]),_this5.removeBuffer(type)),tuple[0]=tuple[1]=null}),{media:media,mediaSource:mediaSource,tracks:tracks}):null},_proto.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},_proto.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},_proto.onManifestParsed=function(event,data){var codecEvents=2;(!data.audio||data.video)&&data.altAudio||(codecEvents=1),this.bufferCodecEventsTotal=codecEvents,this.log(codecEvents+" bufferCodec event(s) expected."),null!=(data=this.transferData)&&data.mediaSource&&this.sourceBufferCount&&codecEvents&&this.bufferCreated()},_proto.onMediaAttaching=function(event,data){var media=this.media=data.media,MediaSource=getMediaSource(this.appendSource);if(this.transferData=this.overrides=void 0,media&&MediaSource){var transferringMedia=!!data.mediaSource,data=((transferringMedia||data.overrides)&&(this.transferData=data,this.overrides=data.overrides),this.mediaSource=data.mediaSource||new MediaSource);if(this.assignMediaSource(data),transferringMedia)this._objectUrl=media.src,this.attachTransferred();else{MediaSource=this._objectUrl=self.URL.createObjectURL(data);if(this.appendSource)try{media.removeAttribute("src");var MMS=self.ManagedMediaSource;media.disableRemotePlayback=media.disableRemotePlayback||MMS&&data instanceof MMS,removeSourceChildren(media),!function(media,url){var source=self.document.createElement("source");source.type="video/mp4",source.src=url,media.appendChild(source)}(media,MediaSource),media.load()}catch(error){media.src=MediaSource}else media.src=MediaSource}media.addEventListener("emptied",this._onMediaEmptied)}},_proto.assignMediaSource=function(ms){var _this$transferData2;this.log(((null==(_this$transferData2=this.transferData)?void 0:_this$transferData2.mediaSource)===ms?"transferred":"created")+" media source: "+(null==(_this$transferData2=ms.constructor)?void 0:_this$transferData2.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))},_proto.attachTransferred=function(){var _this6=this,media=this.media,data=this.transferData;if(data&&media){function mediaSourceOpenCallback(){_this6.media&&_this6.mediaSourceOpenOrEnded&&_this6._onMediaSourceOpen()}var details,requiredTracks=this.tracks,transferredTracks=data.tracks,trackNames=transferredTracks?Object.keys(transferredTracks):null,trackCount=trackNames?trackNames.length:0;if(transferredTracks&&trackNames&&trackCount)if(this.tracksReady){if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+JSON.stringify(requiredTracks,function(key,value){return"initSegment"===key?void 0:value})+";\ntransfer tracks: "+JSON.stringify(transferredTracks,function(key,value){return"initSegment"===key?void 0:value})+"}"),!isCompatibleTrackChange(transferredTracks,requiredTracks))return data.mediaSource=null,data.tracks=void 0,trackCount=media.currentTime,details=this.details,1<(details=Math.max(trackCount,(null==details?void 0:details.fragments[0].start)||0))-trackCount?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+trackCount+" -> "+details):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(transferredTracks)+'"->"'+Object.keys(requiredTracks)+'") start time: '+details+" currentTime: "+trackCount),this.onMediaDetaching(Events.MEDIA_DETACHING,{}),this.onMediaAttaching(Events.MEDIA_ATTACHING,data),void(media.currentTime=details));this.transferData=void 0,trackNames.forEach(function(trackName){var sb,fragmentTracker,playlistType,bufferedTimeRanges,track=transferredTracks[trackName];track&&(sb=track.buffer)&&(fragmentTracker=_this6.fragmentTracker,playlistType=track.id,(fragmentTracker.hasFragments(playlistType)||fragmentTracker.hasParts(playlistType))&&(bufferedTimeRanges=BufferHelper.getBuffered(sb),fragmentTracker.detectEvictedFragments(trackName,bufferedTimeRanges,playlistType,null,!0)),_this6.sourceBuffers["audio"===trackName?1:0]=[trackName,sb],sb.updating&&_this6.operationQueue&&_this6.operationQueue.prependBlocker(trackName),_this6.trackSourceBuffer(trackName,track))}),mediaSourceOpenCallback(),this.bufferCreated()}else this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");else this.log("attachTransferred: MediaSource w/o SourceBuffers"),mediaSourceOpenCallback()}},_proto.onMediaDetaching=function(event,data){var _this7=this,transferringMedia=!!data.transferMedia,media=(this.transferData=this.overrides=void 0,this.media),mediaSource=this.mediaSource,_objectUrl=this._objectUrl;if(mediaSource){if(this.log("media source "+(transferringMedia?"transferring":"detaching")),transferringMedia)this.sourceBuffers.forEach(function(_ref){_ref=_ref[0];_ref&&_this7.removeBuffer(_ref)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var open="open"===mediaSource.readyState;try{for(var sourceBuffers=mediaSource.sourceBuffers,i=sourceBuffers.length;i--;)open&&sourceBuffers[i].abort(),mediaSource.removeSourceBuffer(sourceBuffers[i]);open&&mediaSource.endOfStream()}catch(err){this.warn("onMediaDetaching: "+err.message+" while calling endOfStream")}}this.sourceBufferCount&&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)),this.mediaSource=null,this._objectUrl=null}media&&(media.removeEventListener("emptied",this._onMediaEmptied),transferringMedia||(_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.media=null),this.hls.trigger(Events.MEDIA_DETACHED,data)},_proto.onBufferReset=function(){var _this8=this;this.sourceBuffers.forEach(function(_ref2){_ref2=_ref2[0];_ref2&&_this8.resetBuffer(_ref2)}),this.initTracks()},_proto.resetBuffer=function(type){var _this$mediaSource,_this$tracks$type=null==(_this$tracks$type=this.tracks[type])?void 0:_this$tracks$type.buffer;if(this.removeBuffer(type),_this$tracks$type)try{null!=(_this$mediaSource=this.mediaSource)&&_this$mediaSource.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(_this$tracks$type)}catch(err){this.warn("onBufferReset "+type,err)}delete this.tracks[type]},_proto.removeBuffer=function(type){this.removeBufferListeners(type),this.sourceBuffers["audio"===type?1:0]=[null,null];type=this.tracks[type];type&&(type.buffer=void 0)},_proto.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BufferOperationQueue(this.tracks)},_proto.onBufferCodecs=function(event,data){var _this9=this,tracks=this.tracks,trackNames=Object.keys(data),unmuxedToMuxed=(this.log('BUFFER_CODECS: "'+trackNames+'" (current SB count '+this.sourceBufferCount+")"),"audiovideo"in data&&(tracks.audio||tracks.video)||tracks.audiovideo&&("audio"in data||"video"in data)),muxedToUnmuxed=!unmuxedToMuxed&&this.sourceBufferCount&&this.media&&trackNames.some(function(sbName){return!tracks[sbName]});unmuxedToMuxed||muxedToUnmuxed?this.warn('Unsupported transition between "'+Object.keys(tracks)+'" and "'+trackNames+'" SourceBuffers'):(trackNames.forEach(function(trackName){var parsedTrack=data[trackName],id=parsedTrack.id,codec=parsedTrack.codec,levelCodec=parsedTrack.levelCodec,container=parsedTrack.container,parsedTrack=parsedTrack.metadata,track=tracks[trackName],_this9$transferData=null==(_this9$transferData=_this9.transferData)||null==(_this9$transferData=_this9$transferData.tracks)?void 0:_this9$transferData[trackName],_this9$transferData=null!=_this9$transferData&&_this9$transferData.buffer?_this9$transferData:track,sbCodec=(null==_this9$transferData?void 0:_this9$transferData.pendingCodec)||(null==_this9$transferData?void 0:_this9$transferData.codec),trackLevelCodec=null==_this9$transferData?void 0:_this9$transferData.levelCodec,_this9$transferData=!_this9$transferData||!!_this9.hls.config.assetPlayerId,track=track||(tracks[trackName]={buffer:void 0,listeners:[],codec:codec,container:container,levelCodec:levelCodec,metadata:parsedTrack,id:id}),parsedTrack=pickMostCompleteCodecName(sbCodec,trackLevelCodec),id=null==parsedTrack?void 0:parsedTrack.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1"),trackLevelCodec=pickMostCompleteCodecName(codec,levelCodec),parsedTrack=null==trackLevelCodec?void 0:trackLevelCodec.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");trackLevelCodec&&(id!==parsedTrack||_this9$transferData)&&("audio"===trackName.slice(0,5)&&(trackLevelCodec=getCodecCompatibleName(trackLevelCodec,_this9.appendSource)),_this9.log("switching codec "+sbCodec+" to "+trackLevelCodec),trackLevelCodec!==(track.pendingCodec||track.codec)&&(track.pendingCodec=trackLevelCodec),track.container=container,_this9.appendChangeType(trackName,container,trackLevelCodec))}),(this.tracksReady||this.sourceBufferCount)&&(data.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},_proto.appendChangeType=function(type,container,codec){var _this10=this,mimeType=container+";codecs="+codec;this.append({label:"change-type="+mimeType,execute:function(){var sb,track=_this10.tracks[type];track&&null!=(sb=track.buffer)&&sb.changeType&&(_this10.log("changing "+type+" sourceBuffer type to "+mimeType),sb.changeType(mimeType),track.codec=codec,track.container=container),_this10.shiftAndExecuteNext(type)},onStart:function(){},onComplete:function(){},onError:function(error){_this10.warn("Failed to change "+type+" SourceBuffer type",error)}},type,this.isPending(this.tracks[type]))},_proto.blockAudio=function(partOrFrag){var _this11=this,pStart=partOrFrag.start,pTime=pStart+.05*partOrFrag.duration;!0!==(null==(pStart=this.fragmentTracker.getAppendedFrag(pStart,PlaylistLevelType_MAIN))?void 0:pStart.gap)&&(this.blockedAudioAppend={op:pStart={label:"block-audio",execute:function(){var videoTrack=_this11.tracks.video;(_this11.lastVideoAppendEnd>pTime||null!=videoTrack&&videoTrack.buffer&&BufferHelper.isBuffered(videoTrack.buffer,pTime)||!0===(null==(videoTrack=_this11.fragmentTracker.getAppendedFrag(pTime,PlaylistLevelType_MAIN))?void 0:videoTrack.gap))&&(_this11.blockedAudioAppend=null,_this11.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(error){_this11.warn("Error executing block-audio operation",error)}},frag:partOrFrag},this.append(pStart,"audio",!0))},_proto.unblockAudio=function(){var blockedAudioAppend=this.blockedAudioAppend,operationQueue=this.operationQueue;blockedAudioAppend&&operationQueue&&(this.blockedAudioAppend=null,operationQueue.unblockAudio(blockedAudioAppend.op))},_proto.onBufferAppending=function(event,eventData){var blockedAudioAppend,vappending,_this12=this,tracks=this.tracks,data=eventData.data,type=eventData.type,parent=eventData.parent,frag=eventData.frag,part=eventData.part,chunkMeta=eventData.chunkMeta,chunkStats=chunkMeta.buffering[type],sn=frag.sn,eventData=self.performance.now(),fragBuffering=(chunkStats.start=eventData,frag.stats.buffering),partBuffering=part?part.stats.buffering:null,eventData=(0===fragBuffering.start&&(fragBuffering.start=eventData),partBuffering&&0===partBuffering.start&&(partBuffering.start=eventData),tracks.audio),checkTimestampOffset=!1,tracks=("audio"===type&&"audio/mpeg"===(null==eventData?void 0:eventData.container)&&(checkTimestampOffset=!this.lastMpegAudioChunk||1===chunkMeta.id||this.lastMpegAudioChunk.sn!==chunkMeta.sn,this.lastMpegAudioChunk=chunkMeta),this.tracks.video),eventData=null==tracks?void 0:tracks.buffer,fragStart=(eventData&&"initSegment"!==sn&&(tracks=part||frag,blockedAudioAppend=this.blockedAudioAppend,"audio"!==type||"main"===parent||this.blockedAudioAppend?"video"===type&&(parent=tracks.end,blockedAudioAppend&&((blockedAudioAppend=blockedAudioAppend.frag.start)<parent||parent<this.lastVideoAppendEnd||BufferHelper.isBuffered(eventData,blockedAudioAppend))&&this.unblockAudio(),this.lastVideoAppendEnd=parent):(blockedAudioAppend=tracks.start+.05*tracks.duration,parent=eventData.buffered,vappending=this.currentOp("video"),(!parent.length&&!vappending||!vappending&&!BufferHelper.isBuffered(eventData,blockedAudioAppend)&&this.lastVideoAppendEnd<blockedAudioAppend)&&this.blockAudio(tracks))),(part||frag).start);this.append({label:"append-"+type,execute:function(){var track,delta;chunkStats.executeStart=self.performance.now(),checkTimestampOffset&&(track=_this12.tracks[type])&&(track=track.buffer)&&(delta=fragStart-track.timestampOffset,.1<=Math.abs(delta))&&(_this12.log("Updating audio SourceBuffer timestampOffset to "+fragStart+" (delta: "+delta+") sn: "+sn+")"),track.timestampOffset=fragStart),_this12.appendExecutor(data,type)},onStart:function(){},onComplete:function(){var end=self.performance.now(),timeRanges=(chunkStats.executeEnd=chunkStats.end=end,0===fragBuffering.first&&(fragBuffering.first=end),partBuffering&&0===partBuffering.first&&(partBuffering.first=end),{});_this12.sourceBuffers.forEach(function(_ref3){var type=_ref3[0],_ref3=_ref3[1];type&&(timeRanges[type]=BufferHelper.getBuffered(_ref3))}),_this12.appendErrors[type]=0,"audio"===type||"video"===type?_this12.appendErrors.audiovideo=0:(_this12.appendErrors.audio=0,_this12.appendErrors.video=0),_this12.hls.trigger(Events.BUFFER_APPENDED,{type:type,frag:frag,part:part,chunkMeta:chunkMeta,parent:frag.type,timeRanges:timeRanges})},onError:function(error){var _this12$media,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};error.code===DOMException.QUOTA_EXCEEDED_ERR?event.details=ErrorDetails.BUFFER_FULL_ERROR:error.code!==DOMException.INVALID_STATE_ERR||!_this12.mediaSourceOpenOrEnded||null!=(_this12$media=_this12.media)&&_this12$media.error?"HlsJsTrackRemovedError"===error.name?0===_this12.sourceBufferCount?event.errorAction=createDoNothingErrorAction(!0):++_this12.appendErrors[type]:(_this12$media=++_this12.appendErrors[type],_this12.warn("Failed "+_this12$media+"/"+_this12.hls.config.appendErrorMaxRetry+' times to append segment in "'+type+'" sourceBuffer'),_this12$media>=_this12.hls.config.appendErrorMaxRetry&&(event.fatal=!0)):event.errorAction=createDoNothingErrorAction(!0),_this12.hls.trigger(Events.ERROR,event)}},type,this.isPending(this.tracks[type]))},_proto.getFlushOp=function(type,start,end){var _this13=this;return this.log('queuing "'+type+'" remove '+start+"-"+end),{label:"remove",execute:function(){_this13.removeExecutor(type,start,end)},onStart:function(){},onComplete:function(){_this13.hls.trigger(Events.BUFFER_FLUSHED,{type:type})},onError:function(error){_this13.warn("Failed to remove "+start+"-"+end+' from "'+type+'" SourceBuffer',error)}}},_proto.onBufferFlushing=function(event,data){var _this14=this,type=data.type,startOffset=data.startOffset,endOffset=data.endOffset;type?this.append(this.getFlushOp(type,startOffset,endOffset),type):this.sourceBuffers.forEach(function(_ref4){_ref4=_ref4[0];_ref4&&_this14.append(_this14.getFlushOp(_ref4,startOffset,endOffset),_ref4)})},_proto.onFragParsed=function(event,data){var _this15=this,frag=data.frag,part=data.part,data=[],elementaryStreams=(part||frag).elementaryStreams;elementaryStreams[ElementaryStreamTypes_AUDIOVIDEO]?data.push("audiovideo"):(elementaryStreams[ElementaryStreamTypes_AUDIO]&&data.push("audio"),elementaryStreams[ElementaryStreamTypes_VIDEO]&&data.push("video"));0===data.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+frag.type+" level: "+frag.level+" sn: "+frag.sn),this.blockBuffers(function(){var now=self.performance.now(),now=(frag.stats.buffering.end=now,part&&(part.stats.buffering.end=now),(part||frag).stats);_this15.hls.trigger(Events.FRAG_BUFFERED,{frag:frag,part:part,stats:now,id:frag.type})},data)},_proto.onFragChanged=function(event,data){this.trimBuffers()},_proto.onBufferEos=function(event,data){var _this$overrides,_this16=this,allowEndOfStream=(this.sourceBuffers.forEach(function(_ref5){var track,_ref5=_ref5[0];_ref5&&(track=_this16.tracks[_ref5],data.type&&data.type!==_ref5||(track.ending=!0,track.ended)||(track.ended=!0,_this16.log(_ref5+" buffer reached EOS")))}),!1!==(null==(_this$overrides=this.overrides)?void 0:_this$overrides.endOfStream));0<this.sourceBufferCount&&!this.sourceBuffers.some(function(_ref6){var _ref6=_ref6[0];return _ref6&&!(null!=(_ref6=_this16.tracks[_ref6])&&_ref6.ended)})&&(this.log("Queueing EOS"),this.blockUntilOpen(function(){if(_this16.sourceBuffers.forEach(function(_ref7){var _ref7=_ref7[0];null!==_ref7&&(_ref7=_this16.tracks[_ref7])&&(_ref7.ending=!1)}),allowEndOfStream){var mediaSource=_this16.mediaSource;if(!mediaSource||"open"!==mediaSource.readyState)return void(mediaSource&&_this16.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+mediaSource.readyState));_this16.log("Calling mediaSource.endOfStream()"),mediaSource.endOfStream()}_this16.hls.trigger(Events.BUFFERED_TO_END,void 0)}))},_proto.onLevelUpdated=function(event,_ref8){_ref8=_ref8.details;_ref8.fragments.length&&(this.details=_ref8,this.updateDuration())},_proto.updateDuration=function(){var _this17=this,durationAndRange=this.getDurationAndRange();durationAndRange&&this.blockUntilOpen(function(){return _this17.updateMediaSource(durationAndRange)})},_proto.onError=function(event,data){var _data$errorAction;data.details===ErrorDetails.BUFFER_APPEND_ERROR&&data.frag&&(_data$errorAction=null==(_data$errorAction=data.errorAction)?void 0:_data$errorAction.nextAutoLevel,isFiniteNumber(_data$errorAction))&&_data$errorAction!==data.frag.level&&this.resetAppendErrors()},_proto.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},_proto.trimBuffers=function(){var targetDuration,hls=this.hls,details=this.details,media=this.media;media&&null!==details&&this.sourceBufferCount&&(hls=hls.config,media=media.currentTime,targetDuration=details.levelTargetDuration,details=details.live&&null!==hls.liveBackBufferLength?hls.liveBackBufferLength:hls.backBufferLength,isFiniteNumber(details)&&0<=details&&(details=Math.max(details,targetDuration),details=Math.floor(media/targetDuration)*targetDuration-details,this.flushBackBuffer(media,targetDuration,details)),isFiniteNumber(hls.frontBufferFlushThreshold))&&0<hls.frontBufferFlushThreshold&&(details=Math.max(hls.maxBufferLength,hls.frontBufferFlushThreshold),hls=Math.max(details,targetDuration),details=Math.floor(media/targetDuration)*targetDuration+hls,this.flushFrontBuffer(media,targetDuration,details))},_proto.flushBackBuffer=function(currentTime,targetDuration,targetBackBufferPosition){var _this18=this;this.sourceBuffers.forEach(function(_ref9){var type=_ref9[0],_ref9=_ref9[1];if(_ref9){_ref9=BufferHelper.getBuffered(_ref9);if(0<_ref9.length&&targetBackBufferPosition>_ref9.start(0)){_this18.hls.trigger(Events.BACK_BUFFER_REACHED,{bufferEnd:targetBackBufferPosition});var _this18$details,track=_this18.tracks[type];if(null!=(_this18$details=_this18.details)&&_this18$details.live)_this18.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:targetBackBufferPosition});else if(null!=track&&track.ended&&_ref9.end(_ref9.length-1)-currentTime<2*targetDuration)return void _this18.log("Cannot flush "+type+" back buffer while SourceBuffer is in ended state");_this18.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:targetBackBufferPosition,type:type})}}})},_proto.flushFrontBuffer=function(currentTime,targetDuration,targetFrontBufferPosition){var _this19=this;this.sourceBuffers.forEach(function(_ref10){var bufferStart,numBufferedRanges,type=_ref10[0],_ref10=_ref10[1];!_ref10||(numBufferedRanges=(_ref10=BufferHelper.getBuffered(_ref10)).length)<2||(bufferStart=_ref10.start(numBufferedRanges-1),_ref10=_ref10.end(numBufferedRanges-1),numBufferedRanges=_this19.tracks[type],bufferStart<targetFrontBufferPosition)||bufferStart<=currentTime&&currentTime<=_ref10||(null!=numBufferedRanges&&numBufferedRanges.ended&&currentTime-_ref10<2*targetDuration?_this19.log("Cannot flush "+type+" front buffer while SourceBuffer is in ended state"):_this19.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:bufferStart,endOffset:1/0,type:type}))})},_proto.getDurationAndRange=function(){var playlistEnd,details=this.details,mediaSource=this.mediaSource;return details&&this.media&&"open"===(null==mediaSource?void 0:mediaSource.readyState)?(playlistEnd=details.edge,details.live&&this.hls.config.liveDurationInfinity?(mediaSource.duration=1/0,details.fragments.length&&details.live&&mediaSource.setLiveSeekableRange?{duration:1/0,start:details=Math.max(0,details.fragmentStart),end:Math.max(details,playlistEnd)}:{duration:1/0}):(details=null==(details=this.overrides)?void 0:details.duration)?{duration:details}:(details=this.media.duration,(isFiniteNumber(mediaSource.duration)?mediaSource.duration:0)<playlistEnd&&details<playlistEnd||!isFiniteNumber(details)?{duration:playlistEnd}:null)):null},_proto.updateMediaSource=function(_ref11){var duration=_ref11.duration,start=_ref11.start,_ref11=_ref11.end,mediaSource=this.mediaSource;this.media&&mediaSource&&"open"===mediaSource.readyState&&(mediaSource.duration!==duration&&(isFiniteNumber(duration)&&this.log("Updating MediaSource duration to "+duration.toFixed(3)),mediaSource.duration=duration),void 0!==start)&&void 0!==_ref11&&(this.log("MediaSource duration is set to "+mediaSource.duration+". Setting seekable range to "+start+"-"+_ref11+"."),mediaSource.setLiveSeekableRange(start,_ref11))},_proto.checkPendingTracks=function(){var bufferCodecEventsTotal=this.bufferCodecEventsTotal,pendingTrackCount=this.pendingTrackCount,tracks=this.tracks;this.log("checkPendingTracks (pending: "+pendingTrackCount+" codec events expected: "+bufferCodecEventsTotal+") "+JSON.stringify(tracks)),this.tracksReady&&((bufferCodecEventsTotal=null==(pendingTrackCount=this.transferData)?void 0:pendingTrackCount.tracks)&&Object.keys(bufferCodecEventsTotal).length?this.attachTransferred():(this.createSourceBuffers(),this.bufferCreated()))},_proto.bufferCreated=function(){var tracks,error,_this20=this;this.sourceBufferCount?(tracks={},this.sourceBuffers.forEach(function(_ref12){var track,type=_ref12[0],_ref12=_ref12[1];type&&(track=_this20.tracks[type],tracks[type]={buffer:_ref12,container:track.container,codec:track.codec,levelCodec:track.levelCodec,id:track.id,metadata:track.metadata})}),this.hls.trigger(Events.BUFFER_CREATED,{tracks:tracks}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach(function(_ref13){_ref13=_ref13[0];_this20.executeNext(_ref13)})):(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(){var trackName,tracks=this.tracks,sourceBuffers=this.sourceBuffers,mediaSource=this.mediaSource;if(!mediaSource)throw new Error("createSourceBuffers called when mediaSource was null");for(trackName in tracks){var type=trackName,track=tracks[type];if(this.isPending(track)){var codec=this.getTrackCodec(track,type),mimeType=track.container+";codecs="+codec;track.codec=codec,this.log("creating sourceBuffer("+mimeType+")"+(this.currentOp(type)?" Queued":"")+" "+JSON.stringify(track));try{var sb=mediaSource.addSourceBuffer(mimeType),sbTuple=[type,sb];sourceBuffers["audio"===type?1:0]=sbTuple,track.buffer=sb}catch(error){this.error("error while trying to add sourceBuffer: "+error.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:error,sourceBufferName:type,mimeType:mimeType});break}this.trackSourceBuffer(type,track)}}},_proto.getTrackCodec=function(track,trackName){track=pickMostCompleteCodecName(track.codec,track.levelCodec);return track?"audio"===trackName.slice(0,5)?getCodecCompatibleName(track,this.appendSource):track:""},_proto.trackSourceBuffer=function(type,track){var codec,_this21=this,buffer=track.buffer;buffer&&(codec=this.getTrackCodec(track,type),this.tracks[type]={buffer:buffer,codec:codec,container:track.container,levelCodec:track.levelCodec,metadata:track.metadata,id:track.id,listeners:[]},this.addBufferListener(type,"updatestart",this.onSBUpdateStart),this.addBufferListener(type,"updateend",this.onSBUpdateEnd),this.addBufferListener(type,"error",this.onSBUpdateError),this.appendSource)&&this.addBufferListener(type,"bufferedchange",function(type,event){event=event.removedRanges;null!=event&&event.length&&_this21.hls.trigger(Events.BUFFER_FLUSHED,{type:type})})},_proto.onSBUpdateStart=function(type){type=this.currentOp(type);type&&type.onStart()},_proto.onSBUpdateEnd=function(type){var _this$mediaSource2;"closed"===(null==(_this$mediaSource2=this.mediaSource)?void 0:_this$mediaSource2.readyState)?this.resetBuffer(type):(_this$mediaSource2=this.currentOp(type))&&(_this$mediaSource2.onComplete(),this.shiftAndExecuteNext(type))},_proto.onSBUpdateError=function(type,event){var _this$mediaSource3=new Error(type+" SourceBuffer error. MediaSource readyState: "+(null==(_this$mediaSource3=this.mediaSource)?void 0:_this$mediaSource3.readyState)),event=(this.error(""+_this$mediaSource3,event),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,sourceBufferName:type,error:_this$mediaSource3,fatal:!1}),this.currentOp(type));event&&event.onError(_this$mediaSource3)},_proto.removeExecutor=function(type,startOffset,endOffset){var media=this.media,mediaSource=this.mediaSource,track=this.tracks[type],sb=null==track?void 0:track.buffer;media&&mediaSource&&sb?(media=isFiniteNumber(media.duration)?media.duration:1/0,mediaSource=isFiniteNumber(mediaSource.duration)?mediaSource.duration:1/0,(startOffset=Math.max(0,startOffset))<(endOffset=Math.min(endOffset,media,mediaSource))&&(!track.ending||track.ended)?(track.ended=!1,this.log("Removing ["+startOffset+","+endOffset+"] from the "+type+" SourceBuffer"),sb.remove(startOffset,endOffset)):this.shiftAndExecuteNext(type)):(this.warn("Attempting to remove from the "+type+" SourceBuffer, but it does not exist"),this.shiftAndExecuteNext(type))},_proto.appendExecutor=function(data,type){var track=this.tracks[type],sb=null==track?void 0:track.buffer;if(!sb)throw new HlsJsTrackRemovedError("Attempting to append to the "+type+" SourceBuffer, but it does not exist");track.ending=!1,track.ended=!1,sb.appendBuffer(data)},_proto.blockUntilOpen=function(callback){this.isUpdating()||this.isQueued()?this.blockBuffers(callback):callback()},_proto.isUpdating=function(){return this.sourceBuffers.some(function(_ref14){var type=_ref14[0],_ref14=_ref14[1];return type&&_ref14.updating})},_proto.isQueued=function(){var _this22=this;return this.sourceBuffers.some(function(_ref15){_ref15=_ref15[0];return _ref15&&!!_this22.currentOp(_ref15)})},_proto.isPending=function(track){return!!track&&!track.buffer},_proto.blockBuffers=function(onUnblocked,bufferNames){var operationQueue,blockingOperations,_this23=this;(bufferNames=void 0===bufferNames?this.sourceBufferTypes:bufferNames).length?(operationQueue=this.operationQueue,blockingOperations=bufferNames.map(function(type){return _this23.appendBlocker(type)}),1<bufferNames.length&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(blockingOperations).then(function(result){operationQueue===_this23.operationQueue&&(onUnblocked(),_this23.stepOperationQueue(bufferNames))})):(this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(onUnblocked))},_proto.stepOperationQueue=function(bufferNames){var _this24=this;bufferNames.forEach(function(type){var _this24$tracks$type=null==(_this24$tracks$type=_this24.tracks[type])?void 0:_this24$tracks$type.buffer;_this24$tracks$type&&!_this24$tracks$type.updating&&_this24.shiftAndExecuteNext(type)})},_proto.append=function(operation,type,pending){this.operationQueue&&this.operationQueue.append(operation,type,pending)},_proto.appendBlocker=function(type){if(this.operationQueue)return this.operationQueue.appendBlocker(type)},_proto.currentOp=function(type){return this.operationQueue?this.operationQueue.current(type):null},_proto.executeNext=function(type){type&&this.operationQueue&&this.operationQueue.executeNext(type)},_proto.shiftAndExecuteNext=function(type){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(type)},_proto.addBufferListener=function(type,event,fn){var buffer,track=this.tracks[type];track&&(buffer=track.buffer)&&(fn=fn.bind(this,type),track.listeners.push({event:event,listener:fn}),buffer.addEventListener(event,fn))},_proto.removeBufferListeners=function(type){var buffer,type=this.tracks[type];type&&(buffer=type.buffer)&&(type.listeners.forEach(function(l){buffer.removeEventListener(l.event,l.listener)}),type.listeners.length=0)},_createClass(BufferController,[{key:"mediaSourceOpenOrEnded",get:function(){var _this$mediaSource4=null==(_this$mediaSource4=this.mediaSource)?void 0:_this$mediaSource4.readyState;return"open"===_this$mediaSource4||"ended"===_this$mediaSource4}},{key:"sourceBufferTracks",get:function(){var _this25=this;return Object.keys(this.tracks).reduce(function(baseTracks,type){var track=_this25.tracks[type];return baseTracks[type]={id:track.id,container:track.container,codec:track.codec,levelCodec:track.levelCodec},baseTracks},{})}},{key:"bufferedToEnd",get:function(){var _this26=this;return 0<this.sourceBufferCount&&!this.sourceBuffers.some(function(_ref16){var _this26$tracks$type,_ref16=_ref16[0];return _ref16&&(!(null!=(_this26$tracks$type=_this26.tracks[_ref16])&&_this26$tracks$type.ended)||(null==(_this26$tracks$type=_this26.tracks[_ref16])?void 0:_this26$tracks$type.ending))})}},{key:"tracksReady",get:function(){var pendingTrackCount=this.pendingTrackCount;return 0<pendingTrackCount&&(pendingTrackCount>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var _this$media,_this$media$querySele=(null==(_this$media=this.media)||null==(_this$media$querySele=_this$media.querySelector)?void 0:_this$media$querySele.call(_this$media,"source"))||this.media;return null==_this$media$querySele?void 0:_this$media$querySele.src}},{key:"pendingTrackCount",get:function(){var _this27=this;return Object.keys(this.tracks).reduce(function(acc,type){return acc+(_this27.isPending(_this27.tracks[type])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(acc,_ref17){return acc+(_ref17[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(_ref18){return _ref18[0]}).filter(function(type){return!!type})}}])}(Logger);function removeSourceChildren(node){var sourceChildren=node.querySelectorAll("source");[].slice.call(sourceChildren).forEach(function(source){node.removeChild(source)})}function SfItem(value,params){Array.isArray(value)&&(value=value.map(function(v){return v instanceof SfItem?v:new SfItem(v)})),this.value=value,this.params=params}var BaseSegment=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){data=this.hls.levels[data.droppedLevel];this.isLevelAllowed(data)&&this.restrictedLevels.push({bitrate:data.bitrate,height:data.height,width:data.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(event,data){this.timer&&isFiniteNumber(this.autoLevelCapping)&&this.detectPlayerSize()},_proto.onBufferCodecs=function(event,data){this.hls.config.capLevelToPlayerSize&&data.video&&this.startCapping()},_proto.onMediaDetaching=function(){this.stopCapping(),this.media=null},_proto.detectPlayerSize=function(){var levels,hls,maxLevel;this.media&&(this.mediaHeight<=0||this.mediaWidth<=0?this.clientRect=null:(levels=this.hls.levels).length&&(hls=this.hls,(maxLevel=this.getMaxLevel(levels.length-1))!==this.autoLevelCapping&&hls.logger.log("Setting autoLevelCapping to "+maxLevel+": "+levels[maxLevel].height+"p@"+levels[maxLevel].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),hls.autoLevelCapping=maxLevel,hls.autoLevelEnabled&&hls.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=hls.autoLevelCapping))},_proto.getMaxLevel=function(capLevelIndex){var _this=this,levels=this.hls.levels;return levels.length?(levels=levels.filter(function(level,index){return _this.isLevelAllowed(level)&&index<=capLevelIndex}),this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(levels,this.mediaWidth,this.mediaHeight)):-1},_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(){var media,boundsRect,clientRect;return this.clientRect||(boundsRect={width:0,height:0},(media=this.media)&&(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)),this.clientRect=boundsRect)},_proto.isLevelAllowed=function(level){return!this.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 nextLevel,maxLevelIndex=levels.length-1,squareSize=Math.max(width,height),i=0;i<levels.length;i+=1){var level=levels[i];if((level.width>=squareSize||level.height>=squareSize)&&(level=level,!(nextLevel=levels[i+1])||level.width!==nextLevel.width||level.height!==nextLevel.height)){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 Math.min(pixelRatio,this.hls.config.maxDevicePixelRatio)}}])}(),CmcdObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},CmcdStreamingFormat={DASH:"d",HLS:"h",SMOOTH:"s",OTHER:"o"},CmcdHeaderField={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},CmcdHeaderMap=((AC3Demuxer={})[CmcdHeaderField.OBJECT]=["br","d","ot","tb"],AC3Demuxer[CmcdHeaderField.REQUEST]=["bl","dl","mtp","nor","nrr","su"],AC3Demuxer[CmcdHeaderField.SESSION]=["cid","pr","sf","sid","st","v"],AC3Demuxer[CmcdHeaderField.STATUS]=["bs","rtp"],AC3Demuxer);function throwError(action,src,type,cause){return new Error("failed to "+action+' "'+(action=src,Array.isArray(action)?JSON.stringify(action):action instanceof Map?"Map{}":action instanceof Set?"Set{}":"object"==typeof action?JSON.stringify(action):String(action))+'" as '+type,{cause:cause})}function serializeError(src,type,cause){return throwError("serialize",src,type,cause)}function SfToken(description){this.description=description}function serializeByteSequence(value){if(!1===ArrayBuffer.isView(value))throw serializeError(value,"Byte Sequence");return":"+btoa(String.fromCharCode.apply(String,value))+":"}function serializeInteger(value){if(function(value){return value<-999999999999999||999999999999999<value}(value))throw serializeError(value,"Integer");return value.toString()}function serializeDecimal(value){var roundedValue=function roundToEven(value,precision){var flooredValue;return value<0?-roundToEven(-value,precision):(precision=Math.pow(10,precision),Math.abs(value*precision%1-.5)<Number.EPSILON?((flooredValue=Math.floor(value*precision))%2==0?flooredValue:flooredValue+1)/precision:Math.round(value*precision)/precision)}(value,3);if(12<Math.floor(Math.abs(roundedValue)).toString().length)throw serializeError(value,"Decimal");value=roundedValue.toString();return value.includes(".")?value:value+".0"}var STRING_REGEX=/[\x00-\x1f\x7f]+/;function serializeToken(token){token=(token=token).description||token.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(token))throw serializeError(token,"Token");return token}function serializeBareItem(value){switch(typeof value){case"number":if(isFiniteNumber(value))return(Number.isInteger(value)?serializeInteger:serializeDecimal)(value);throw serializeError(value,"Bare Item");case"string":return function(value){if(STRING_REGEX.test(value))throw serializeError(value,"String");return'"'+value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(value);case"symbol":return serializeToken(value);case"boolean":return function(value){if("boolean"!=typeof value)throw serializeError(value,"Boolean");return value?"?1":"?0"}(value);case"object":if(value instanceof Date)return function(value){return"@"+serializeInteger(value.getTime()/1e3)}(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],_ref=_ref[1];return!0===_ref?";"+serializeKey(key):";"+serializeKey(key)+"="+serializeBareItem(_ref)}).join("")}function serializeItem(value){return value instanceof SfItem?""+serializeBareItem(value.value)+serializeParams(value.params):serializeBareItem(value)}function serializeDict(dict,options){if(void 0===options&&(options={whitespace:!0}),"object"!=typeof dict)throw serializeError(dict,"Dict");dict=dict instanceof Map?dict.entries():Object.entries(dict),options=null!=options&&options.whitespace?" ":"";return Array.from(dict).map(function(_ref){var value,key=_ref[0],_ref=_ref[1],key=(_ref instanceof SfItem==!1&&(_ref=new SfItem(_ref)),serializeKey(key));return!0===_ref.value?key+=serializeParams(_ref.params):(key+="=",Array.isArray(_ref.value)?key+="("+(value=_ref).value.map(serializeItem).join(" ")+")"+serializeParams(value.params):key+=serializeItem(_ref)),key}).join(","+options)}function toRounded(value){return Math.round(value)}function toHundred(value){return 100*toRounded(value/100)}var CmcdFormatters={br:toRounded,d:toRounded,bl:toHundred,dl:toHundred,mtp:toHundred,nor:function(value,options){return null!=options&&options.baseUrl&&(value=function(url,base){var to=new URL(url),base=new URL(base);if(to.origin!==base.origin)return url;for(var toPath=to.pathname.split("/").slice(1),fromPath=base.pathname.split("/").slice(1,-1);toPath[0]===fromPath[0];)toPath.shift(),fromPath.shift();for(;fromPath.length;)fromPath.shift(),toPath.unshift("..");return toPath.join("/")}(value,options.baseUrl)),encodeURIComponent(value)},rtp:toHundred,tb:toRounded};function processCmcd(obj,options){var keys,formatters,filter,results={};return null!=obj&&"object"==typeof obj&&(keys=Object.keys(obj).sort(),formatters=_extends({},CmcdFormatters,null==options?void 0:options.formatters),filter=null==options?void 0:options.filter,keys.forEach(function(key){var value,formatter;null!=filter&&filter(key)||(value=obj[key],(formatter=formatters[key])&&(value=formatter(value,options)),"v"===key&&1===value)||"pr"==key&&1===value||!function(value){return"number"==typeof value?isFiniteNumber(value):null!=value&&""!==value&&!1!==value}(value)||(!function(key){return"ot"===key||"sf"===key||"st"===key}(key)||"string"!=typeof value||(value=new SfToken(value)),results[key]=value)})),results}function encodeCmcd(cmcd,options){return void 0===options&&(options={}),cmcd?serializeDict(processCmcd(cmcd,options),_extends({whitespace:!1},options)):""}function appendCmcdHeaders(headers,cmcd,options){_extends(headers,function(cmcd,options){void 0===options&&(options={});var headerMap,result={};return cmcd?(cmcd=Object.entries(cmcd),headerMap=Object.entries(CmcdHeaderMap).concat(Object.entries((null==options?void 0:options.customHeaderMap)||{})),cmcd=cmcd.reduce(function(acc,entry){var key=entry[0],entry=entry[1],_a=(null==(_a=headerMap.find(function(entry){return entry[1].includes(key)}))?void 0:_a[0])||CmcdHeaderField.REQUEST;return null==acc[_a]&&(acc[_a]={}),acc[_a][key]=entry,acc},{}),Object.entries(cmcd).reduce(function(acc,_ref){var field=_ref[0],_ref=_ref[1];return acc[field]=encodeCmcd(_ref,options),acc},result)):result}(cmcd,options))}var CMCD_PARAM="CMCD";var REGEX=/CMCD=[^&#]+/;function appendCmcdQuery(url,cmcd,options){cmcd=function(cmcd,options){return void 0===options&&(options={}),cmcd?(cmcd=encodeCmcd(cmcd,options),CMCD_PARAM+"="+encodeURIComponent(cmcd)):""}(cmcd,options);return cmcd?REGEX.test(url)?url.replace(REGEX,cmcd):(options=url.includes("?")?"&":"?",url+options+cmcd):url}MP4Remuxer=function(){function CMCDController(hls){var _this=this,config=(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:CmcdObjectType.MANIFEST,su:!_this.initialized})}catch(error){_this.hls.logger.warn("Could not generate manifest CMCD data.",error)}},this.applyFragmentData=function(context){try{var frag=context.frag,part=context.part,level=_this.hls.levels[frag.level],ot=_this.getObjectType(frag),data={d:1e3*(part||frag).duration,ot:ot},next=(ot!==CmcdObjectType.VIDEO&&ot!==CmcdObjectType.AUDIO&&ot!=CmcdObjectType.MUXED||(data.br=level.bitrate/1e3,data.tb=_this.getTopBandwidth(ot)/1e3,data.bl=_this.getBufferLength(ot)),part?_this.getNextPart(part):_this.getNextFrag(frag));null!=next&&next.url&&next.url!==frag.url&&(data.nor=next.url),_this.apply(context,data)}catch(error){_this.hls.logger.warn("Could not generate segment CMCD data.",error)}},this.hls=hls,this.config=hls.config),cmcd=config.cmcd;null!=cmcd&&(config.pLoader=this.createPlaylistLoader(),config.fLoader=this.createFragmentLoader(),this.sid=cmcd.sessionId||hls.sessionId,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=this.media=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;this.audioBuffer=null==(_data$tracks$audio=data.tracks.audio)?void 0:_data$tracks$audio.buffer,this.videoBuffer=null==(_data$tracks$audio=data.tracks.video)?void 0:_data$tracks$audio.buffer},_proto.createData=function(){var _this$media;return{v:1,sf:CmcdStreamingFormat.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){_extends(data=void 0===data?{}:data,this.createData());var isVideo=data.ot===CmcdObjectType.INIT||data.ot===CmcdObjectType.VIDEO||data.ot===CmcdObjectType.MUXED,includeKeys=(this.starved&&isVideo&&(data.bs=!0,data.su=!0,this.starved=!1),null==data.su&&(data.su=this.buffering),this.includeKeys),isVideo=(includeKeys&&(data=Object.keys(data).reduce(function(acc,key){return includeKeys.includes(key)&&(acc[key]=data[key]),acc},{})),{baseUrl:context.url});this.useHeaders?(context.headers||(context.headers={}),appendCmcdHeaders(context.headers,data,isVideo)):context.url=appendCmcdQuery(context.url,data,isVideo)},_proto.getNextFrag=function(fragment){var _this$hls$levels$frag=null==(_this$hls$levels$frag=this.hls.levels[fragment.level])?void 0:_this$hls$levels$frag.details;if(_this$hls$levels$frag)return fragment=fragment.sn-_this$hls$levels$frag.startSN,_this$hls$levels$frag.fragments[1+fragment]},_proto.getNextPart=function(part){var _this$hls$levels$frag2,index=part.index,part=part.fragment,partList=null==(_this$hls$levels$frag2=this.hls.levels[part.level])||null==(_this$hls$levels$frag2=_this$hls$levels$frag2.details)?void 0:_this$hls$levels$frag2.partList;if(partList)for(var sn=part.sn,i=partList.length-1;0<=i;i--){var p=partList[i];if(p.index===index&&p.fragment.sn===sn)return partList[i+1]}},_proto.getObjectType=function(fragment){var type=fragment.type;return"subtitle"===type?CmcdObjectType.TIMED_TEXT:"initSegment"===fragment.sn?CmcdObjectType.INIT:"audio"===type?CmcdObjectType.AUDIO:"main"===type?this.hls.audioTracks.length?CmcdObjectType.VIDEO:CmcdObjectType.MUXED:void 0},_proto.getTopBandwidth=function(type){for(var bitrate=0,hls=this.hls,_iterator=_createForOfIteratorHelperLoose(type===CmcdObjectType.AUDIO?hls.audioTracks:(type=-1<(type=hls.maxAutoLevel)?type+1:hls.levels.length,hls.levels.slice(0,type)));!(_step=_iterator()).done;){var _step=_step.value;_step.bitrate>bitrate&&(bitrate=_step.bitrate)}return 0<bitrate?bitrate:NaN},_proto.getBufferLength=function(type){var media=this.media,type=type===CmcdObjectType.AUDIO?this.audioBuffer:this.videoBuffer;return type&&media?1e3*BufferHelper.bufferInfo(type,media.currentTime,this.config.maxBufferHole).len:NaN},_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}}])}()},_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)}var _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}}])}()},CMCDController}(),AC3Demuxer=function(_Logger){function ContentSteeringController(hls){var _this=_Logger.call(this,"content-steering",hls.logger)||this;return _this.hls=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.registerListeners(),_this}_inheritsLoose(ContentSteeringController,_Logger);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.pathways=function(){return(this.levels||[]).reduce(function(pathways,level){return-1===pathways.indexOf(level.pathwayId)&&pathways.push(level.pathwayId),pathways},[])},_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){data=data.contentSteering;null!==data&&(this.pathwayId=data.pathwayId,this.uri=data.uri,this.started)&&this.startLoad()},_proto.onManifestParsed=function(event,data){this.audioTracks=data.audioTracks,this.subtitleTracks=data.subtitleTracks},_proto.onError=function(event,data){var levels,pathwayPriority,errorPathway,groupId,pathwayId,_data$context,errorAction=data.errorAction;(null==errorAction?void 0:errorAction.action)===NetworkErrorAction_SendAlternateToPenaltyBox&&errorAction.flags===ErrorActionFlags_MoveAllAlternatesMatchingHost&&(levels=this.levels,pathwayPriority=this._pathwayPriority,errorPathway=this.pathwayId,data.context&&(groupId=(_data$context=data.context).groupId,pathwayId=_data$context.pathwayId,_data$context=_data$context.type,groupId&&levels?errorPathway=this.getPathwayForGroupId(groupId,_data$context,errorPathway):pathwayId&&(errorPathway=pathwayId)),errorPathway in this.penalizedPathways||(this.penalizedPathways[errorPathway]=performance.now()),(pathwayPriority=!pathwayPriority&&levels?this.pathways():pathwayPriority)&&1<pathwayPriority.length&&(this.updatePathwayPriority(pathwayPriority),errorAction.resolved=this.pathwayId!==errorPathway),errorAction.resolved||this.warn("Could not resolve "+data.details+' ("'+data.error.message+'") with content-steering for Pathway: '+errorPathway+" levels: "+(levels&&levels.length)+" priorities: "+JSON.stringify(pathwayPriority)+" penalized: "+JSON.stringify(this.penalizedPathways)))},_proto.filterParsedLevels=function(levels){this.levels=levels;var pathwayId,pathwayLevels=this.getLevelsForPathway(this.pathwayId);return 0===pathwayLevels.length&&(pathwayId=levels[0].pathwayId,this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+pathwayId+'"'),pathwayLevels=this.getLevelsForPathway(pathwayId),this.pathwayId=pathwayId),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();Object.keys(penalizedPathways).forEach(function(pathwayId){3e5<now-penalizedPathways[pathwayId]&&delete penalizedPathways[pathwayId]});for(var i=0;i<pathwayPriority.length;i++){var pathwayId=pathwayPriority[i];if(!(pathwayId in penalizedPathways)){if(pathwayId===this.pathwayId)return;var levels,selectedIndex=this.hls.nextLoadLevel,selectedLevel=this.hls.levels[selectedIndex];if(0<(levels=this.getLevelsForPathway(pathwayId)).length){this.log('Setting Pathway to "'+pathwayId+'"'),this.pathwayId=pathwayId,reassignFragmentLevelIndexes(levels),this.hls.trigger(Events.LEVELS_UPDATED,{levels:levels});pathwayId=this.hls.levels[selectedIndex];selectedLevel&&pathwayId&&this.levels&&(pathwayId.attrs["STABLE-VARIANT-ID"]!==selectedLevel.attrs["STABLE-VARIANT-ID"]&&pathwayId.bitrate!==selectedLevel.bitrate&&this.log("Unstable Pathways change from bitrate "+selectedLevel.bitrate+" to "+pathwayId.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 audioGroupCloneMap,subtitleGroupCloneMap,_this2=this,levels=this.levels;levels&&(audioGroupCloneMap={},subtitleGroupCloneMap={},pathwayClones.forEach(function(pathwayClone){var cloneId=pathwayClone.ID,baseId=pathwayClone["BASE-ID"],uriReplacement=pathwayClone["URI-REPLACEMENT"];levels.some(function(level){return level.pathwayId===cloneId})||(pathwayClone=_this2.getLevelsForPathway(baseId).map(function(baseLevel){var attributes=new AttrList(baseLevel.attrs),clonedAudioGroupId=(attributes["PATHWAY-ID"]=cloneId,attributes.AUDIO&&attributes.AUDIO+"_clone_"+cloneId),clonedSubtitleGroupId=attributes.SUBTITLES&&attributes.SUBTITLES+"_clone_"+cloneId,clonedAudioGroupId=(clonedAudioGroupId&&(audioGroupCloneMap[attributes.AUDIO]=clonedAudioGroupId,attributes.AUDIO=clonedAudioGroupId),clonedSubtitleGroupId&&(subtitleGroupCloneMap[attributes.SUBTITLES]=clonedSubtitleGroupId,attributes.SUBTITLES=clonedSubtitleGroupId),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:clonedAudioGroupId,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,pathwayClone),cloneRenditionGroups(_this2.audioTracks,audioGroupCloneMap,uriReplacement,cloneId),cloneRenditionGroups(_this2.subtitleTracks,subtitleGroupCloneMap,uriReplacement,cloneId))}))},_proto.loadSteeringManifest=function(uri){var url,_this3=this,config=this.hls.config,Loader=config.loader;this.loader&&this.loader.destroy(),this.loader=new Loader(config);try{url=new self.URL(uri)}catch(error){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+uri)}"data:"!==url.protocol&&(Loader=0|(this.hls.bandwidthEstimate||config.abrEwmaDefaultEstimate),url.searchParams.set("_HLS_pathway",this.pathwayId),url.searchParams.set("_HLS_throughput",""+Loader));uri={responseType:"json",url:url.href},Loader=config.steeringManifestLoadPolicy.default,config=Loader.errorRetry||Loader.timeoutRetry||{},Loader={loadPolicy:Loader,timeout:Loader.maxLoadTimeMs,maxRetry:config.maxNumRetry||0,retryDelay:config.retryDelayMs||0,maxRetryDelay:config.maxRetryDelayMs||0},config={onSuccess:function(response,stats,context,networkDetails){_this3.log('Loaded steering manifest: "'+url+'"');response=response.data;if(1!==(null==response?void 0:response.VERSION))_this3.log("Steering VERSION "+response.VERSION+" not supported!");else{_this3.updated=performance.now(),_this3.timeToLoad=response.TTL;var reloadUri=response["RELOAD-URI"],pathwayClones=response["PATHWAY-CLONES"],pathwayPriority=response["PATHWAY-PRIORITY"];if(reloadUri)try{_this3.uri=new self.URL(reloadUri,url).href}catch(error){return _this3.enabled=!1,void _this3.log("Failed to parse Steering Manifest RELOAD-URI: "+reloadUri)}_this3.scheduleRefresh(_this3.uri||context.url),pathwayClones&&_this3.clonePathways(pathwayClones);reloadUri={steeringManifest:response,url:url.toString()};_this3.hls.trigger(Events.STEERING_MANIFEST_LOADED,reloadUri),pathwayPriority&&_this3.updatePathwayPriority(pathwayPriority)}},onError:function(error,context,networkDetails,stats){var ttl;_this3.log("Error loading steering manifest: "+error.code+" "+error.text+" ("+context.url+")"),_this3.stopLoad(),410===error.code?(_this3.enabled=!1,_this3.log("Steering manifest "+context.url+" no longer available")):(ttl=1e3*_this3.timeToLoad,429===error.code?("function"==typeof(null==(error=_this3.loader)?void 0:error.getResponseHeader)&&(error=error.getResponseHeader("Retry-After"))&&(ttl=1e3*parseFloat(error)),_this3.log("Steering manifest "+context.url+" rate limited")):_this3.scheduleRefresh(_this3.uri||context.url,ttl))},onTimeout:function(stats,context,networkDetails){_this3.log("Timeout loading steering manifest ("+context.url+")"),_this3.scheduleRefresh(_this3.uri||context.url)}};this.log("Requesting steering manifest: "+url),this.loader.load(uri,Loader,config)},_proto.scheduleRefresh=function(uri,ttlMs){var _this4=this;void 0===ttlMs&&(ttlMs=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var _this4$hls=null==(_this4$hls=_this4.hls)?void 0:_this4$hls.media;_this4$hls&&!_this4$hls.ended?_this4.loadSteeringManifest(uri):_this4.scheduleRefresh(uri,1e3*_this4.timeToLoad)},ttlMs)},_createClass(ContentSteeringController,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(pathwayPriority){this.updatePathwayPriority(pathwayPriority)}}])}(Logger);function cloneRenditionGroups(tracks,groupCloneMap,uriReplacement,cloneId){tracks&&Object.keys(groupCloneMap).forEach(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 perVariantUri,host=uriReplacement.HOST,params=uriReplacement.PARAMS,uriReplacement=uriReplacement[perOptionKey],url=(stableId&&(perVariantUri=null==uriReplacement?void 0:uriReplacement[stableId])&&(uri=perVariantUri),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}var EMEController=function(_Logger){function EMEController(hls){var _this=_Logger.call(this,"eme",hls.logger)||this;return _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=function(event){var keySystemDomain,initDataType=event.initDataType,initData=event.initData,event='"'+event.type+'" event: init data type: "'+initDataType+'"';if(_this.debug(event),null!==initData){if("sinf"===initDataType&&_this.getLicenseServerUrl(KeySystems.FAIRPLAY)){var json=bin2str(new Uint8Array(initData));try{var tenc=parseSinf(base64Decode(JSON.parse(json).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(event+" Failed to parse sinf: "+error)}}else if(_this.getLicenseServerUrl(KeySystems.WIDEVINE)){var keyId,json=parseMultiPssh(initData),keySystems=Object.keys(_this.keySystemAccessPromises),tenc=(keySystems.length||(keySystems=getKeySystemsForConfig(_this.config)),json.filter(function(pssh){pssh=pssh.systemId?keySystemIdToKeySystemDomain(pssh.systemId):null;return!!pssh&&-1<keySystems.indexOf(pssh)})[0]);if(!tenc)return void(0===json.length||json.some(function(pssh){return!pssh.systemId})?_this.warn(event+" contains incomplete or invalid pssh data"):_this.log("ignoring "+event+" for "+json.map(function(pssh){return keySystemIdToKeySystemDomain(pssh.systemId)}).join(",")+" pssh data in favor of playlist keys"));keySystemDomain=keySystemIdToKeySystemDomain(tenc.systemId),0===tenc.version&&tenc.data&&(keySystemDomain===KeySystems.WIDEVINE?(event=tenc.data.length-22,keyId=tenc.data.subarray(event,16+event)):keySystemDomain===KeySystems.PLAYREADY&&(keyId=parsePlayReadyWRM(tenc.data)))}if(keySystemDomain&&keyId){for(var _ret,keyIdHex=Hex.hexDump(keyId),json=_this,keyIdToKeySessionPromise=json.keyIdToKeySessionPromise,mediaKeySessions=json.mediaKeySessions,keySessionContextPromise=keyIdToKeySessionPromise[keyIdHex],i=0;i<mediaKeySessions.length&&(0===(_ret=function(){var oldKeyIdHex,keyContext=mediaKeySessions[i],decryptdata=keyContext.decryptdata;return decryptdata.keyId?(oldKeyIdHex=Hex.hexDump(decryptdata.keyId),keyIdHex===oldKeyIdHex||-1!==decryptdata.uri.replace(/-/g,"").indexOf(keyIdHex)?(keySessionContextPromise=keyIdToKeySessionPromise[oldKeyIdHex],decryptdata.pssh||(delete keyIdToKeySessionPromise[oldKeyIdHex],decryptdata.pssh=new Uint8Array(initData),decryptdata.keyId=keyId,(keySessionContextPromise=keyIdToKeySessionPromise[keyIdHex]=keySessionContextPromise.then(function(){return _this.generateRequestWithPreferredKeySession(keyContext,initDataType,initData,"encrypted-event-key-match")})).catch(function(error){return _this.handleError(error)})),1):void 0):0}())||1!==_ret);i++);keySessionContextPromise||(keySessionContextPromise=keyIdToKeySessionPromise[keyIdHex]=_this.getKeySystemSelectionPromise([keySystemDomain]).then(function(_ref){var keySystem=_ref.keySystem,mediaKeys=_ref.mediaKeys,decryptdata=(_this.throwIfDestroyed(),new LevelKey("ISO-23001-7",keyIdHex,null!=(_ref=keySystemDomainToKeySystemFormat(keySystem))?_ref:""));return decryptdata.pssh=new Uint8Array(initData),decryptdata.keyId=keyId,_this.attemptSetMediaKeys(keySystem,mediaKeys).then(function(){_this.throwIfDestroyed();var keySessionContext=_this.createMediaKeySessionContext({decryptdata:decryptdata,keySystem:keySystem,mediaKeys:mediaKeys});return _this.generateRequestWithPreferredKeySession(keySessionContext,initDataType,initData,"encrypted-event-no-match")})})).catch(function(error){return _this.handleError(error)})}}},_this.onWaitingForKey=function(event){_this.log('"'+event.type+'" event')},_this.hls=hls,_this.config=hls.config,_this.registerListeners(),_this}_inheritsLoose(EMEController,_Logger);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.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=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,_this$config=_this$config.widevineLicenseUrl,drmSystems=drmSystems[keySystem];return drmSystems?drmSystems.licenseUrl:keySystem===KeySystems.WIDEVINE&&_this$config?_this$config:void 0},_proto.getLicenseServerUrlOrThrow=function(keySystem){var url=this.getLicenseServerUrl(keySystem);if(void 0===url)throw new Error('no license server URL configured for key-system "'+keySystem+'"');return url},_proto.getServerCertificateUrl=function(keySystem){var keySystemConfiguration=this.config.drmSystems[keySystem];if(keySystemConfiguration)return keySystemConfiguration.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+keySystem+'"]')},_proto.attemptKeySystemAccess=function(keySystemsToAttempt){function uniqueCodec(value,i,a){return!!value&&a.indexOf(value)===i}var _this3=this,levels=this.hls.levels,audioCodecs=levels.map(function(level){return level.audioCodec}).filter(uniqueCodec),videoCodecs=levels.map(function(level){return level.videoCodec}).filter(uniqueCodec);return audioCodecs.length+videoCodecs.length===0&&videoCodecs.push("avc1.42e01e"),new Promise(function(resolve,reject){function _attempt(keySystems){var keySystem=keySystems.shift();_this3.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))})}_attempt(keySystemsToAttempt)})},_proto.requestMediaKeySystemAccess=function(keySystem,supportedConfigurations){var errMessage,requestMediaKeySystemAccessFunc=this.config.requestMediaKeySystemAccessFunc;return"function"!=typeof requestMediaKeySystemAccessFunc?(errMessage="Configured requestMediaKeySystemAccess is not a function "+requestMediaKeySystemAccessFunc,null===requestMediaKeySystemAccess&&"http:"===self.location.protocol&&(errMessage="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(errMessage))):requestMediaKeySystemAccessFunc(keySystem,supportedConfigurations)},_proto.getMediaKeysPromise=function(keySystem,audioCodecs,videoCodecs){var _keySystemAccessPromises,_this4=this,audioCodecs=function(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 function(initDataTypes,audioCodecs,videoCodecs,drmSystemOptions){return[{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}})}]}(initDataTypes,audioCodecs,videoCodecs,drmSystemOptions)}(keySystem,audioCodecs,videoCodecs,this.config.drmSystemOptions),keySystemAccessPromises=this.keySystemAccessPromises[keySystem],videoCodecs=null==keySystemAccessPromises?void 0:keySystemAccessPromises.keySystemAccess;return videoCodecs?videoCodecs.then(function(){return keySystemAccessPromises.mediaKeys}):(this.log('Requesting encrypted media "'+keySystem+'" key-system access with config: '+JSON.stringify(audioCodecs)),videoCodecs=this.requestMediaKeySystemAccess(keySystem,audioCodecs),_keySystemAccessPromises=this.keySystemAccessPromises[keySystem]={keySystemAccess:videoCodecs},videoCodecs.catch(function(error){_this4.log('Failed to obtain access to key-system "'+keySystem+'": '+error)}),videoCodecs.then(function(mediaKeySystemAccess){_this4.log('Access for key-system "'+mediaKeySystemAccess.keySystem+'" obtained');var certificateRequest=_this4.fetchServerCertificate(keySystem);return _this4.log('Create media-keys for "'+keySystem+'"'),_keySystemAccessPromises.mediaKeys=mediaKeySystemAccess.createMediaKeys().then(function(mediaKeys){return _this4.log('Media-keys created for "'+keySystem+'"'),certificateRequest.then(function(certificate){return certificate?_this4.setMediaKeysServerCertificate(mediaKeys,keySystem,certificate):mediaKeys})}),_keySystemAccessPromises.mediaKeys.catch(function(error){_this4.error('Failed to create media-keys for "'+keySystem+'"}: '+error)}),_keySystemAccessPromises.mediaKeys}))},_proto.createMediaKeySessionContext=function(_ref2){var decryptdata=_ref2.decryptdata,keySystem=_ref2.keySystem,_ref2=_ref2.mediaKeys,mediaKeysSession=(this.log('Creating key-system session "'+keySystem+'" keyId: '+Hex.hexDump(decryptdata.keyId||[])),_ref2.createSession()),decryptdata={decryptdata:decryptdata,keySystem:keySystem,mediaKeys:_ref2,mediaKeysSession:mediaKeysSession,keyStatus:"status-pending"};return this.mediaKeySessions.push(decryptdata),decryptdata},_proto.renewKeySession=function(mediaKeySessionContext){var keySessionContext,keyId,decryptdata=mediaKeySessionContext.decryptdata;decryptdata.pssh?(keySessionContext=this.createMediaKeySessionContext(mediaKeySessionContext),keyId=this.getKeyIdString(decryptdata),this.keyIdToKeySessionPromise[keyId]=this.generateRequestWithPreferredKeySession(keySessionContext,"cenc",decryptdata.pssh.buffer,"expired")):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;return this.log('Updating key-session "'+keySession.sessionId+'" for keyID '+Hex.hexDump((null==(mediaKeySessionContext=mediaKeySessionContext.decryptdata)?void 0:mediaKeySessionContext.keyId)||[])+"\n      } (data length: "+(data&&data.byteLength)+")"),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+") key formats "+keyFormats.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(keyFormats)),this.keyFormatPromise},_proto.getKeyFormatPromise=function(keyFormats){var _this5=this;return new Promise(function(resolve,reject){var keySystemsInConfig=getKeySystemsForConfig(_this5.config),keySystemsToAttempt=keyFormats.map(keySystemFormatToKeySystemDomain).filter(function(value){return!!value&&-1!==keySystemsInConfig.indexOf(value)});return _this5.getKeySystemSelectionPromise(keySystemsToAttempt).then(function(_ref3){var _ref3=_ref3.keySystem,keySystemFormat=keySystemDomainToKeySystemFormat(_ref3);keySystemFormat?resolve(keySystemFormat):reject(new Error('Unable to find format for key-system "'+_ref3+'"'))}).catch(reject)})},_proto.loadKey=function(data){var _this6=this,decryptdata=data.keyInfo.decryptdata,keyId=this.getKeyIdString(decryptdata),keyDetails="(keyId: "+keyId+' format: "'+decryptdata.keyFormat+'" method: '+decryptdata.method+" uri: "+decryptdata.uri+")",keyContextPromise=(this.log("Starting session for key "+keyDetails),this.keyIdToKeySessionPromise[keyId]);return keyContextPromise||(keyContextPromise=this.getKeySystemForKeyPromise(decryptdata).then(function(_ref4){var keySystem=_ref4.keySystem,mediaKeys=_ref4.mediaKeys;return _this6.throwIfDestroyed(),_this6.log("Handle encrypted media sn: "+data.frag.sn+" "+data.frag.type+": "+data.frag.level+" using key "+keyDetails),_this6.attemptSetMediaKeys(keySystem,mediaKeys).then(function(){return _this6.throwIfDestroyed(),_this6.createMediaKeySessionContext({keySystem:keySystem,mediaKeys:mediaKeys,decryptdata:decryptdata})})}),(this.keyIdToKeySessionPromise[keyId]=keyContextPromise.then(function(keySessionContext){var initData=decryptdata.pssh?decryptdata.pssh.buffer:null;return _this6.generateRequestWithPreferredKeySession(keySessionContext,"cenc",initData,"playlist-key")})).catch(function(error){return _this6.handleError(error)})),keyContextPromise},_proto.throwIfDestroyed=function(message){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),keyId=this.keyIdToKeySessionPromise[keyId];return keyId||(decryptdata=(keyId=keySystemFormatToKeySystemDomain(decryptdata.keyFormat))?[keyId]:getKeySystemsForConfig(this.config),this.attemptKeySystemAccess(decryptdata))},_proto.getKeySystemSelectionPromise=function(keySystemsToAttempt){if(0===(keySystemsToAttempt=keySystemsToAttempt.length?keySystemsToAttempt:getKeySystemsForConfig(this.config)).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.attemptSetMediaKeys=function(keySystem,mediaKeys){var _this7=this,queue=this.setMediaKeysQueue.slice(),setMediaKeysPromise=(this.log('Setting media-keys for "'+keySystem+'"'),Promise.all(queue).then(function(){if(_this7.media)return _this7.media.setMediaKeys(mediaKeys);throw new Error("Attempted to set mediaKeys without media element attached")}));return this.setMediaKeysQueue.push(setMediaKeysPromise),setMediaKeysPromise.then(function(){_this7.log('Media-keys set for "'+keySystem+'"'),queue.push(setMediaKeysPromise),_this7.setMediaKeysQueue=_this7.setMediaKeysQueue.filter(function(p){return-1===queue.indexOf(p)})})},_proto.generateRequestWithPreferredKeySession=function(context,initDataType,initData,reason){var keyId,licenseStatus,keyUsablePromise,_this8=this,_this$config$drmSyste=null==(_this$config$drmSyste=this.config.drmSystems)||null==(_this$config$drmSyste=_this$config$drmSyste[context.keySystem])?void 0:_this$config$drmSyste.generateRequest;if(_this$config$drmSyste)try{var mappedInitData=_this$config$drmSyste.call(this.hls,initDataType,initData,context);if(!mappedInitData)throw new Error("Invalid response from configured generateRequest filter");initDataType=mappedInitData.initDataType,initData=mappedInitData.initData||null,context.decryptdata.pssh=initData?new Uint8Array(initData):null}catch(error){if(this.warn(error.message),null!=(_this$config$drmSyste=this.hls)&&_this$config$drmSyste.config.debug)throw error}return null===initData?(this.log('Skipping key-session request for "'+reason+'" (no initData)'),Promise.resolve(context)):(keyId=this.getKeyIdString(context.decryptdata),this.log('Generating key-session request for "'+reason+'": '+keyId+" (init data type: "+initDataType+" length: "+(initData?initData.byteLength:null)+")"),licenseStatus=new EventEmitter,mappedInitData=context._onmessage=function(event){var messageType,keySession=context.mediaKeysSession;keySession?(messageType=event.messageType,event=event.message,_this8.log('"'+messageType+'" message event for session "'+keySession.sessionId+'" message size: '+event.byteLength),"license-request"===messageType||"license-renewal"===messageType?_this8.renewLicense(context,event).catch(function(error){licenseStatus.eventNames().length?licenseStatus.emit("error",error):_this8.handleError(error)}):"license-release"===messageType?context.keySystem===KeySystems.FAIRPLAY&&(_this8.updateKeySession(context,strToUtf8array("acknowledged")),_this8.removeSession(context)):_this8.warn('unhandled media key message type "'+messageType+'"')):licenseStatus.emit("error",new Error("invalid state"))},_this$config$drmSyste=context._onkeystatuseschange=function(event){var keyStatus;context.mediaKeysSession?(_this8.onKeyStatusChange(context),keyStatus=context.keyStatus,licenseStatus.emit("keyStatus",keyStatus),"expired"===keyStatus&&(_this8.warn(context.keySystem+" expired for key "+keyId),_this8.renewKeySession(context))):licenseStatus.emit("error",new Error("invalid state"))},context.mediaKeysSession.addEventListener("message",mappedInitData),context.mediaKeysSession.addEventListener("keystatuseschange",_this$config$drmSyste),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")):_this8.warn('unhandled key status change "'+keyStatus+'"')})}),context.mediaKeysSession.generateRequest(initDataType,initData).then(function(){var _context$mediaKeysSes;_this8.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(),_this8.removeSession(context),error}).then(function(){return licenseStatus.removeAllListeners(),context}))},_proto.onKeyStatusChange=function(mediaKeySessionContext){var _this9=this;mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach(function(status,keyId){_this9.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,certLoader=new config.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,loadPolicy={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};certLoader.load(loaderContext,loadPolicy,{onSuccess:function(response,stats,context,networkDetails){resolve(response.data)},onError:function(response,contex,networkDetails,stats){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(stats,context,networkDetails){reject(new Error("aborted"))}})})):Promise.resolve()},_proto.setMediaKeysServerCertificate=function(mediaKeys,keySystem,cert){var _this10=this;return new Promise(function(resolve,reject){mediaKeys.setServerCertificate(cert).then(function(success){_this10.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 _this11=this;return this.requestLicense(context,new Uint8Array(keyMessage)).then(function(data){return _this11.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;var licenseChallenge=(new DOMParser).parseFromString(xmlString,"application/xml"),headers=licenseChallenge.querySelectorAll("HttpHeader");if(0<headers.length)for(var i=0,len=headers.length;i<len;i++){var _header$querySelector=null==(_header$querySelector=(header=headers[i]).querySelector("name"))?void 0:_header$querySelector.textContent,header=null==(header=header.querySelector("value"))?void 0:header.textContent;_header$querySelector&&header&&xhr.setRequestHeader(_header$querySelector,header)}xmlString=licenseChallenge.querySelector("Challenge"),licenseChallenge=null==xmlString?void 0:xmlString.textContent;if(licenseChallenge)return strToUtf8array(atob(licenseChallenge));throw new Error("Cannot find <Challenge> in key message")},_proto.setupLicenseXHR=function(xhr,url,keysListItem,licenseChallenge){var _this12=this,licenseXhrSetup=this.config.licenseXhrSetup;return licenseXhrSetup?Promise.resolve().then(function(){if(keysListItem.decryptdata)return licenseXhrSetup.call(_this12.hls,xhr,url,keysListItem,licenseChallenge);throw new Error("Key removed")}).catch(function(error){if(keysListItem.decryptdata)return xhr.open("POST",url,!0),licenseXhrSetup.call(_this12.hls,xhr,url,keysListItem,licenseChallenge);throw error}).then(function(licenseXhrSetupResult){return xhr.readyState||xhr.open("POST",url,!0),{xhr:xhr,licenseChallenge:licenseXhrSetupResult||licenseChallenge}}):(xhr.open("POST",url,!0),Promise.resolve({xhr:xhr,licenseChallenge:licenseChallenge}))},_proto.requestLicense=function(keySessionContext,licenseChallenge){var _this13=this,keyLoadPolicy=this.config.keyLoadPolicy.default;return new Promise(function(resolve,reject){var url=_this13.getLicenseServerUrlOrThrow(keySessionContext.keySystem),xhr=(_this13.log("Sending license request to URL: "+url),new XMLHttpRequest);xhr.responseType="arraybuffer",xhr.onreadystatechange=function(){if(!_this13.hls||!keySessionContext.mediaKeysSession)return reject(new Error("invalid state"));if(4===xhr.readyState)if(200===xhr.status){_this13._requestLicenseFailureCount=0;var data=xhr.response,licenseResponseCallback=(_this13.log("License received "+(data instanceof ArrayBuffer?data.byteLength:data)),_this13.config.licenseResponseCallback);if(licenseResponseCallback)try{data=licenseResponseCallback.call(_this13.hls,xhr,url,keySessionContext)}catch(error){_this13.error(error)}resolve(data)}else{var licenseResponseCallback=keyLoadPolicy.errorRetry,data=licenseResponseCallback?licenseResponseCallback.maxNumRetry:0;_this13._requestLicenseFailureCount++,_this13._requestLicenseFailureCount>data||400<=xhr.status&&xhr.status<500?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+")")):(licenseResponseCallback=data-_this13._requestLicenseFailureCount+1,_this13.warn("Retrying license request, "+licenseResponseCallback+" attempts left"),_this13.requestLicense(keySessionContext,licenseChallenge).then(resolve,reject))}},keySessionContext.licenseXhr&&keySessionContext.licenseXhr.readyState!==XMLHttpRequest.DONE&&keySessionContext.licenseXhr.abort(),keySessionContext.licenseXhr=xhr,_this13.setupLicenseXHR(xhr,url,keySessionContext,licenseChallenge).then(function(_ref5){var xhr=_ref5.xhr,_ref5=_ref5.licenseChallenge;keySessionContext.keySystem==KeySystems.PLAYREADY&&(_ref5=_this13.unpackPlayReadyKeyMessage(xhr,_ref5)),xhr.send(_ref5)})})},_proto.onMediaAttached=function(event,data){this.config.emeEnabled&&(data=data.media,(this.media=data).removeEventListener("encrypted",this.onMediaEncrypted),data.removeEventListener("waitingforkey",this.onWaitingForKey),data.addEventListener("encrypted",this.onMediaEncrypted),data.addEventListener("waitingforkey",this.onWaitingForKey))},_proto.onMediaDetached=function(){var _this14=this,media=this.media,mediaKeysList=this.mediaKeySessions,keySessionCount=(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(),mediaKeysList.length);EMEController.CDMCleanupPromise=Promise.all(mediaKeysList.map(function(mediaKeySessionContext){return _this14.removeSession(mediaKeySessionContext)}).concat(null==media||null==(media=media.setMediaKeys(null))?void 0:media.catch(function(error){var _this14$hls;_this14.log("Could not clear media keys: "+error),null!=(_this14$hls=_this14.hls)&&_this14$hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+error)})}))).then(function(){keySessionCount&&(_this14.log("finished closing key sessions and clearing media keys"),mediaKeysList.length=0)}).catch(function(error){var _this14$hls2;_this14.log("Could not close sessions and clear media keys: "+error),null!=(_this14$hls2=_this14.hls)&&_this14$hls2.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+error)})})},_proto.onManifestLoading=function(){this.keyFormatPromise=null},_proto.onManifestLoaded=function(event,_ref6){var _ref6=_ref6.sessionKeys;_ref6&&this.config.emeEnabled&&(this.keyFormatPromise||(_ref6=_ref6.reduce(function(formats,sessionKey){return-1===formats.indexOf(sessionKey.keyFormat)&&formats.push(sessionKey.keyFormat),formats},[]),this.log("Selecting key-system from session-keys "+_ref6.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(_ref6)))},_proto.removeSession=function(mediaKeySessionContext){var _this15=this,mediaKeysSession=mediaKeySessionContext.mediaKeysSession,licenseXhr=mediaKeySessionContext.licenseXhr;if(mediaKeysSession)return 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,-1<(licenseXhr=this.mediaKeySessions.indexOf(mediaKeySessionContext))&&this.mediaKeySessions.splice(licenseXhr,1),mediaKeysSession.remove().catch(function(error){var _this15$hls;_this15.log("Could not remove session: "+error),null!=(_this15$hls=_this15.hls)&&_this15$hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+error)})}).then(function(){return mediaKeysSession.close()}).catch(function(error){var _this15$hls2;_this15.log("Could not close session: "+error),null!=(_this15$hls2=_this15.hls)&&_this15$hls2.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+error)})})},EMEController}(Logger),EMEKeyError=(EMEController.CDMCleanupPromise=void 0,function(_Error){function EMEKeyError(data,message){var _this16=_Error.call(this,message)||this;return _this16.data=void 0,data.error||(data.error=new Error(message)),(_this16.data=data).err=data.error,_this16}return _inheritsLoose(EMEKeyError,_Error),EMEKeyError}(_wrapNativeSuper(Error))),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_ATTACHING,this.onMediaAttaching,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)},_proto.unregisterListeners=function(){this.hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,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;config.capLevelOnFPSDrop&&(data=data.media instanceof self.HTMLVideoElement?data.media:null,(this.media=data)&&"function"==typeof data.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),config.fpsDroppedMonitoringPeriod))},_proto.onMediaDetaching=function(){this.media=null},_proto.checkFPS=function(video,decodedFrames,droppedFrames){var currentDropped,currentDecoded,hls,currentPeriod,currentTime=performance.now();decodedFrames&&(this.lastTime&&(currentPeriod=currentTime-this.lastTime,currentDropped=droppedFrames-this.lastDroppedFrames,currentDecoded=decodedFrames-this.lastDecodedFrames,currentPeriod=1e3*currentDropped/currentPeriod,(hls=this.hls).trigger(Events.FPS_DROP,{currentDropped:currentDropped,currentDecoded:currentDecoded,totalDroppedFrames:droppedFrames}),0<currentPeriod)&&currentDropped>hls.config.fpsDroppedMonitoringThreshold*currentDecoded&&(currentPeriod=hls.currentLevel,hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+currentPeriod),0<currentPeriod)&&(-1===hls.autoLevelCapping||hls.autoLevelCapping>=currentPeriod)&&(hls.trigger(Events.FPS_DROP_LEVEL_CAPPING,{level:currentPeriod-=1,droppedLevel:hls.currentLevel}),hls.autoLevelCapping=currentPeriod,this.streamController.nextLevelSwitch()),this.lastTime=currentTime,this.lastDroppedFrames=droppedFrames,this.lastDecodedFrames=decodedFrames)},_proto.checkFPSInterval=function(){var videoPlaybackQuality,video=this.media;video&&(this.isVideoPlaybackQualityAvailable?(videoPlaybackQuality=video.getVideoPlaybackQuality(),this.checkFPS(video,videoPlaybackQuality.totalVideoFrames,videoPlaybackQuality.droppedVideoFrames)):this.checkFPS(video,video.webkitDecodedFrameCount,video.webkitDroppedFrameCount))},FPSController}();function hash(text){for(var hash=5381,i=text.length;i;)hash=33*hash^text.charCodeAt(--i);return(hash>>>0).toString()}var TimelineOccupancy=function(TimelineOccupancy){return TimelineOccupancy[TimelineOccupancy.Point=0]="Point",TimelineOccupancy[TimelineOccupancy.Range=1]="Range",TimelineOccupancy}({});var InterstitialEvent=function(){function InterstitialEvent(dateRange,base){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.base=base,this.dateRange=dateRange,this.setDateRange(dateRange)}var _proto=InterstitialEvent.prototype;return _proto.setDateRange=function(dateRange){this.dateRange=dateRange,this.resumeOffset=dateRange.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=dateRange.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=dateRange.attr.enumeratedStringList("X-SNAP",this.snapOptions)},_proto.reset=function(){var _this$assetListLoader;null!=(_this$assetListLoader=this.assetListLoader)&&_this$assetListLoader.destroy(),this.assetListLoader=this.error=void 0},_proto.isAssetPastPlayoutLimit=function(assetIndex){var playoutLimit;return assetIndex>=this.assetList.length||(playoutLimit=this.playoutLimit,!(assetIndex<=0||isNaN(playoutLimit))&&playoutLimit<this.assetList[assetIndex].startOffset)},_proto.findAssetIndex=function(asset){return this.assetList.indexOf(asset)},_proto.toString=function(){return'["'+(interstitial=this).identifier+'" '+(interstitial.cue.pre?"<pre>":interstitial.cue.post?"<post>":"")+interstitial.timelineStart.toFixed(2)+"-"+interstitial.resumeTime.toFixed(2)+"]";var interstitial},_createClass(InterstitialEvent,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var startTime=this.dateRange.startTime;if(this.snapOptions.out){var frag=this.dateRange.tagAnchor;if(frag)return getSnapToFragmentTime(startTime,frag)}return startTime}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"resumptionOffset",get:function(){var resumeOffset=this.resumeOffset,resumeOffset=isFiniteNumber(resumeOffset)?resumeOffset:this.duration;return this.cumulativeDuration+resumeOffset}},{key:"resumeTime",get:function(){var resumeTime=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var frag=this.resumeAnchor;if(frag)return getSnapToFragmentTime(resumeTime,frag)}return resumeTime}},{key:"appendInPlace",get:function(){return!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||0!==this.startTime&&!this.snapOptions.out||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<.02))},set:function(value){this.appendInPlaceStarted||(this.appendInPlaceDisabled=!value)}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(value){this._timelineStart=value}},{key:"duration",get:function(){var playoutLimit=this.playoutLimit,duration=this._duration||this.dateRange.duration||this.dateRange.plannedDuration||0;return duration=!isNaN(playoutLimit)&&playoutLimit<duration?playoutLimit:duration},set:function(value){this._duration=value}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?TimelineOccupancy.Range:TimelineOccupancy.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}}])}();function getSnapToFragmentTime(time,frag){return time-frag.start<frag.duration/2&&!(Math.abs(time-(frag.start+frag.duration))<.02)?frag.start:frag.start+frag.duration}function getInterstitialUrl(uri,sessionId,baseUrl){uri=new self.URL(uri,baseUrl);return"data:"!==uri.protocol&&uri.searchParams.set("_HLS_primary_id",sessionId),uri}function eventAssetToString(asset){var start=asset.timelineStart,duration=asset.duration||0;return'["'+asset.identifier+'" '+start.toFixed(2)+"-"+(start+duration).toFixed(2)+"]"}var HlsAssetPlayer=function(){function HlsAssetPlayer(HlsPlayerClass,userConfig,_interstitial,assetItem){var _this=this,HlsPlayerClass=(this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this.playoutOffset=0,this.checkPlayout=function(){var playoutLimit=_this.interstitial.playoutLimit;_this.playoutOffset+_this.currentTime>=playoutLimit&&_this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED,{})},this.hls=new HlsPlayerClass(userConfig)),userConfig=(this.interstitial=_interstitial,(this.assetItem=assetItem).uri);try{userConfig=getInterstitialUrl(userConfig,HlsPlayerClass.sessionId).href}catch(error){}HlsPlayerClass.loadSource(userConfig);function detailsLoaded(){_this.hasDetails=!0}HlsPlayerClass.once(Events.LEVEL_LOADED,detailsLoaded),HlsPlayerClass.once(Events.AUDIO_TRACK_LOADED,detailsLoaded),HlsPlayerClass.once(Events.SUBTITLE_TRACK_LOADED,detailsLoaded),HlsPlayerClass.on(Events.MEDIA_ATTACHING,function(name,_ref){var _ref=_ref.media,event=(_this.removeMediaListeners(),_this.mediaAttached=_ref,_this.interstitial);event.playoutLimit&&(_this.playoutOffset=(null==(event=event.assetList[event.assetList.indexOf(assetItem)])?void 0:event.startOffset)||0,_ref.addEventListener("timeupdate",_this.checkPlayout))})}var _proto=HlsAssetPlayer.prototype;return _proto.getAssetTime=function(time){var timelineOffset=this.timelineOffset,duration=this.duration;return Math.min(Math.max(0,time-timelineOffset),duration)},_proto.removeMediaListeners=function(){var media=this.mediaAttached;media&&media.removeEventListener("timeupdate",this.checkPlayout)},_proto.destroy=function(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null},_proto.attachMedia=function(data){this.hls.attachMedia(data)},_proto.detachMedia=function(){this.removeMediaListeners(),this.hls.detachMedia()},_proto.resumeBuffering=function(){this.hls.resumeBuffering()},_proto.pauseBuffering=function(){this.hls.pauseBuffering()},_proto.transferMedia=function(){return this.hls.transferMedia()},_proto.on=function(event,listener,context){this.hls.on(event,listener)},_proto.once=function(event,listener,context){this.hls.once(event,listener)},_proto.off=function(event,listener,context){this.hls.off(event,listener)},_proto.toString=function(){return"HlsAssetPlayer: "+eventAssetToString(this.assetItem)+" "+this.hls.sessionId+" "+(this.interstitial.appendInPlace?"append-in-place":"")},_createClass(HlsAssetPlayer,[{key:"destroyed",get:function(){var _this$hls;return!(null!=(_this$hls=this.hls)&&_this$hls.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){return this.hls.media}},{key:"bufferedEnd",get:function(){var media=this.media||this.mediaAttached;return media?(media=BufferHelper.bufferInfo(media,media.currentTime,.001),this.getAssetTime(media.end)):0}},{key:"currentTime",get:function(){var media=this.media||this.mediaAttached;return media?this.getAssetTime(media.currentTime):0}},{key:"duration",get:function(){var _this$assetItem=null==(_this$assetItem=this.assetItem)?void 0:_this$assetItem.duration;return _this$assetItem||0}},{key:"remaining",get:function(){var duration=this.duration;return duration?Math.max(0,duration-this.currentTime):0}},{key:"timelineOffset",get:function(){return this.hls.config.timelineOffset||0},set:function(value){var timelineOffset=this.timelineOffset;if(value!==timelineOffset&&Math.abs(value-timelineOffset)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=value}}}])}(),InterstitialsSchedule=function(_Logger){function InterstitialsSchedule(onScheduleUpdate,logger){logger=_Logger.call(this,"interstitials-sched",logger)||this;return logger.onScheduleUpdate=void 0,logger.eventMap={},logger.events=null,logger.items=null,logger.durations={primary:0,playout:0,integrated:0},logger.onScheduleUpdate=onScheduleUpdate,logger}_inheritsLoose(InterstitialsSchedule,_Logger);var _proto=InterstitialsSchedule.prototype;return _proto.destroy=function(){this.reset(),this.onScheduleUpdate=null},_proto.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(interstitial){return interstitial.reset()}),this.events=this.items=null},_proto.getEvent=function(identifier){return identifier&&this.eventMap[identifier]||null},_proto.hasEvent=function(identifier){return identifier in this.eventMap},_proto.findItemIndex=function(item,time){if(item.event)return this.findEventIndex(item.event.identifier);var _items$index,index=-1,items=(item.nextEvent?index=this.findEventIndex(item.nextEvent.identifier)-1:item.previousEvent&&(index=this.findEventIndex(item.previousEvent.identifier)+1),this.items);if(items)for(items[index]||(void 0===time&&(time=item.start),index=this.findItemIndexAtTime(time));0<=index&&null!=(_items$index=items[index])&&_items$index.event;)index--;return index},_proto.findItemIndexAtTime=function(timelinePos,timelineType){var items=this.items;if(items)for(var i=0;i<items.length;i++){var timeRange=items[i];if(timelinePos===(timeRange=timelineType&&"primary"!==timelineType?timeRange[timelineType]:timeRange).start||timelinePos>timeRange.start&&timelinePos<timeRange.end)return i}return-1},_proto.findJumpRestrictedIndex=function(startIndex,endIndex){var items=this.items;if(items)for(var i=startIndex;i<=endIndex&&items[i];i++){var event=items[i].event;if(null!=event&&event.restrictions.jump&&!event.appendInPlace)return i}return-1},_proto.findEventIndex=function(identifier){var items=this.items;if(items)for(var _items$i$event,i=items.length;i--;)if((null==(_items$i$event=items[i].event)?void 0:_items$i$event.identifier)===identifier)return i;return-1},_proto.findAssetIndex=function(event,timelinePos){var assetList=event.assetList,length=assetList.length;if(1<length)for(var i=0;i<length;i++){var asset=assetList[i];if(!asset.error){var timelineStart=asset.timelineStart;if(timelinePos===timelineStart||timelineStart<timelinePos&&timelinePos<timelineStart+(asset.duration||0))return i}}return 0},_proto.parseInterstitialDateRanges=function(mediaSelection){var _this2=this,details=mediaSelection.main.details,dateRanges=details.dateRanges,previousInterstitialEvents=this.events,details=this.parseDateRanges(dateRanges,{url:details.url}),ids=Object.keys(dateRanges),dateRanges=previousInterstitialEvents?previousInterstitialEvents.filter(function(event){return!ids.includes(event.identifier)}):[];details.length&&details.sort(function(a,b){var aPre=a.cue.pre,aPost=a.cue.post,bPre=b.cue.pre,bPost=b.cue.post;if(aPre&&!bPre)return-1;if(bPre&&!aPre)return 1;if(aPost&&!bPost)return 1;if(bPost&&!aPost)return-1;if(!(aPre||bPre||aPost||bPost)){aPre=a.startTime,bPre=b.startTime;if(aPre!==bPre)return aPre-bPre}return a.dateRange.tagOrder-b.dateRange.tagOrder}),this.events=details,dateRanges.forEach(function(interstitial){_this2.removeEvent(interstitial)}),this.updateSchedule(mediaSelection,dateRanges)},_proto.updateSchedule=function(mediaSelection,removedInterstitials){void 0===removedInterstitials&&(removedInterstitials=[]);var currentItems,events=this.events||[];(events.length||removedInterstitials.length||this.length<2)&&(currentItems=this.items,events=this.parseSchedule(events,mediaSelection),removedInterstitials.length||(null==currentItems?void 0:currentItems.length)!==events.length||events.some(function(item,i){return.005<Math.abs(item.playout.start-currentItems[i].playout.start)||.005<Math.abs(item.playout.end-currentItems[i].playout.end)}))&&(this.items=events,this.onScheduleUpdate(removedInterstitials,currentItems))},_proto.parseDateRanges=function(dateRanges,baseData){for(var interstitialEvents=[],ids=Object.keys(dateRanges),i=0;i<ids.length;i++){var interstitial,id=ids[i],dateRange=dateRanges[id];dateRange.isInterstitial&&((interstitial=this.eventMap[id])?interstitial.setDateRange(dateRange):(interstitial=new InterstitialEvent(dateRange,baseData),this.eventMap[id]=interstitial),interstitialEvents.push(interstitial))}return interstitialEvents},_proto.parseSchedule=function(interstitialEvents,mediaSelection){var primaryPosition,integratedTime,_schedule,segmentDuration,playoutStart,schedule=[],details=mediaSelection.main.details,primaryDuration=details.live?1/0:details.edge,playoutDuration=0;return(interstitialEvents=interstitialEvents.filter(function(event){return!(event.error||event.cue.once&&event.hasPlayed)})).length?(this.resolveOffsets(interstitialEvents,mediaSelection),integratedTime=primaryPosition=0,interstitialEvents.forEach(function(interstitial,i){var preroll=interstitial.cue.pre,postroll=interstitial.cue.post,previousEvent=interstitialEvents[i-1]||null,appendInPlace=interstitial.appendInPlace,eventStart=postroll?primaryDuration:interstitial.startOffset,interstitialDuration=interstitial.duration,timelineDuration=interstitial.timelineOccupancy===TimelineOccupancy.Range?interstitialDuration:0,resumptionOffset=interstitial.resumptionOffset,inSameStartTimeSequence=(null==previousEvent?void 0:previousEvent.startTime)===eventStart,start=eventStart+interstitial.cumulativeDuration,appendInPlace=appendInPlace?start+interstitialDuration:eventStart+resumptionOffset;if(preroll||!postroll&&eventStart<=0){resumptionOffset=integratedTime,preroll=(integratedTime+=timelineDuration,interstitial.timelineStart=start,playoutDuration);playoutDuration+=interstitialDuration,schedule.push({event:interstitial,start:start,end:appendInPlace,playout:{start:preroll,end:playoutDuration},integrated:{start:resumptionOffset,end:integratedTime}})}else{if(!(eventStart<=primaryDuration))return;inSameStartTimeSequence||(.033<(preroll=eventStart-primaryPosition)?(resumptionOffset=primaryPosition,inSameStartTimeSequence=integratedTime,integratedTime+=preroll,_playoutStart=playoutDuration,playoutDuration+=preroll,i={previousEvent:interstitialEvents[i-1]||null,nextEvent:interstitial,start:resumptionOffset,end:resumptionOffset+preroll,playout:{start:_playoutStart,end:playoutDuration},integrated:{start:inSameStartTimeSequence,end:integratedTime}},schedule.push(i)):0<preroll&&previousEvent&&(previousEvent.cumulativeDuration+=preroll,schedule[schedule.length-1].end=eventStart)),postroll&&(appendInPlace=start),interstitial.timelineStart=start;var resumptionOffset=integratedTime,_playoutStart=(integratedTime+=timelineDuration,playoutDuration);playoutDuration+=interstitialDuration,schedule.push({event:interstitial,start:start,end:appendInPlace,playout:{start:_playoutStart,end:playoutDuration},integrated:{start:resumptionOffset,end:integratedTime}})}inSameStartTimeSequence=interstitial.resumeTime;primaryPosition=postroll||primaryDuration<inSameStartTimeSequence?primaryDuration:inSameStartTimeSequence}),primaryPosition<primaryDuration&&(details=integratedTime,integratedTime+=segmentDuration=primaryDuration-(mediaSelection=primaryPosition),playoutStart=playoutDuration,playoutDuration+=segmentDuration,schedule.push({previousEvent:(null==(_schedule=schedule[schedule.length-1])?void 0:_schedule.event)||null,nextEvent:null,start:primaryPosition,end:mediaSelection+segmentDuration,playout:{start:playoutStart,end:playoutDuration},integrated:{start:details,end:integratedTime}})),this.setDurations(primaryDuration,playoutDuration,integratedTime)):(schedule.push({previousEvent:null,nextEvent:null,start:0,end:primaryDuration,playout:{start:0,end:primaryDuration},integrated:{start:0,end:primaryDuration}}),this.setDurations(primaryDuration,primaryDuration,primaryDuration)),schedule},_proto.setDurations=function(primary,playout,integrated){this.durations={primary:primary,playout:playout,integrated:integrated}},_proto.resolveOffsets=function(interstitialEvents,mediaSelection){var _this3=this,details=mediaSelection.main.details,primaryDuration=details.live?1/0:details.edge,cumulativeDuration=0,lastScheduledStart=-1;interstitialEvents.forEach(function(interstitial,i){var preroll=interstitial.cue.pre,postroll=interstitial.cue.post,preroll=preroll?0:postroll?primaryDuration:interstitial.startTime;if(_this3.updateAssetDurations(interstitial),lastScheduledStart===preroll?interstitial.cumulativeDuration=cumulativeDuration:(cumulativeDuration=0,lastScheduledStart=preroll),!postroll&&interstitial.snapOptions.in&&(interstitial.resumeAnchor=findFragmentByPTS(null,details.fragments,interstitial.startOffset+interstitial.resumptionOffset,0,0)||void 0),!interstitial.appendInPlace||interstitial.appendInPlaceStarted||_this3.primaryCanResumeInPlaceAt(interstitial,mediaSelection)||(interstitial.appendInPlace=!1),!interstitial.appendInPlace)for(var j=i-1;i--;)interstitialEvents[1+j].startTime-interstitialEvents[j].resumeTime<.033&&(interstitialEvents[j].appendInPlace=!1);preroll=isFiniteNumber(interstitial.resumeOffset)?interstitial.resumeOffset:interstitial.duration;cumulativeDuration+=preroll})},_proto.primaryCanResumeInPlaceAt=function(interstitial,mediaSelection){var _this4=this,resumeTime=interstitial.resumeTime,resumesInPlaceAt=interstitial.startTime+interstitial.resumptionOffset;return.02<Math.abs(resumeTime-resumesInPlaceAt)?(this.log('"'+interstitial.identifier+'" resumption '+resumeTime+" not aligned with estimated timeline end "+resumesInPlaceAt),!1):mediaSelection?!Object.keys(mediaSelection).some(function(playlistType){var details=mediaSelection[playlistType].details,playlistEnd=details.edge;return playlistEnd<resumeTime?(_this4.log('"'+interstitial.identifier+'" resumption '+resumeTime+" past "+playlistType+" playlist end "+playlistEnd),!0):(playlistEnd=findFragmentByPTS(null,details.fragments,resumeTime))?(details="audio"===playlistType?.175:0,!(Math.abs(playlistEnd.start-resumeTime)<.02||Math.abs(playlistEnd.end-resumeTime)<.02+details||(_this4.log('"'+interstitial.identifier+'" resumption '+resumeTime+" not aligned with "+playlistType+" fragment bounds ("+playlistEnd.start+"-"+playlistEnd.end+" sn: "+playlistEnd.sn+" cc: "+playlistEnd.cc+")"),0))):(_this4.log('"'+interstitial.identifier+'" resumption '+resumeTime+" does not align with any fragments in "+playlistType+" playlist"),!0)}):(this.log('"'+interstitial.identifier+'" resumption '+resumeTime+" can not be aligned with media (none selected)"),!1)},_proto.updateAssetDurations=function(interstitial){var eventStart=interstitial.timelineStart,sumDuration=0,hasUnknownDuration=!1,hasErrors=!1;interstitial.assetList.forEach(function(asset,i){var timelineStart=eventStart+sumDuration,timelineStart=(asset.startOffset=sumDuration,asset.timelineStart=timelineStart,hasUnknownDuration=hasUnknownDuration||null===asset.duration,hasErrors=hasErrors||!!asset.error,!asset.error&&asset.duration||0);sumDuration+=timelineStart}),interstitial.duration=hasUnknownDuration&&!hasErrors?Math.max(sumDuration,interstitial.duration):sumDuration},_proto.removeEvent=function(interstitial){interstitial.reset(),delete this.eventMap[interstitial.identifier]},_createClass(InterstitialsSchedule,[{key:"duration",get:function(){var items=this.items;return items?items[items.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var _this$items=null==(_this$items=this.items)||null==(_this$items=_this$items[this.length-1])?void 0:_this$items.event;if(_this$items){_this$items=_this$items.assetList,_this$items=_this$items[_this$items.length-1];if(_this$items)return _this$items.identifier}return null}}])}(Logger);function segmentToString(segment){return"["+(segment.event?'"'+segment.event.identifier+'"':"primary")+": "+segment.start.toFixed(2)+"-"+segment.end.toFixed(2)+"]"}var AssetListLoader=function(){function AssetListLoader(hls){this.hls=void 0,this.hls=hls}var _proto=AssetListLoader.prototype;return _proto.destroy=function(){this.hls=null},_proto.loadAssetList=function(interstitial,liveStartPosition){var _this=this,assetListUrl=interstitial.assetListUrl;try{url=getInterstitialUrl(assetListUrl,this.hls.sessionId,interstitial.baseUrl)}catch(error){var assetListUrl=this.assignAssetListError(interstitial,ErrorDetails.ASSET_LIST_LOAD_ERROR,error,assetListUrl);return void this.hls.trigger(Events.ERROR,assetListUrl)}!liveStartPosition||interstitial.cue.pre||interstitial.cue.post||"data:"===url.protocol||0<(assetListUrl=liveStartPosition-interstitial.startTime)&&url.searchParams.set("_HLS_start_offset",""+Math.round(1e3*assetListUrl)/1e3);var liveStartPosition=this.hls.config,assetListUrl=new liveStartPosition.loader(liveStartPosition),url={responseType:"json",url:url.href},liveStartPosition=liveStartPosition.interstitialAssetListLoadPolicy.default,liveStartPosition={loadPolicy:liveStartPosition,timeout:liveStartPosition.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return assetListUrl.load(url,liveStartPosition,{onSuccess:function(response,stats,context,networkDetails){var response=response.data,assets=null==response?void 0:response.ASSETS;Array.isArray(assets)?(interstitial.assetListResponse=response,_this.hls.trigger(Events.ASSET_LIST_LOADED,{event:interstitial,assetListResponse:response,networkDetails:networkDetails})):(assets=_this.assignAssetListError(interstitial,ErrorDetails.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),context.url,stats,networkDetails),_this.hls.trigger(Events.ERROR,assets))},onError:function(error,context,networkDetails,stats){error=_this.assignAssetListError(interstitial,ErrorDetails.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+error.code+" "+error.text+" ("+context.url+")"),context.url,stats,networkDetails);_this.hls.trigger(Events.ERROR,error)},onTimeout:function(stats,context,networkDetails){context=_this.assignAssetListError(interstitial,ErrorDetails.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+context.url+")"),context.url,stats,networkDetails);_this.hls.trigger(Events.ERROR,context)}}),this.hls.trigger(Events.ASSET_LIST_LOADING,{event:interstitial}),assetListUrl},_proto.assignAssetListError=function(interstitial,details,error,url,stats,networkDetails){return interstitial.error=error,{type:ErrorTypes.NETWORK_ERROR,details:details,fatal:!1,interstitial:interstitial,url:url,error:error,networkDetails:networkDetails,stats:stats}},AssetListLoader}();function playWithCatch(media){null!=media&&media.play().catch()}var InterstitialsController=function(_Logger){function InterstitialsController(hls,HlsPlayerClass){var _this=_Logger.call(this,"interstitials",hls.logger)||this;return _this.HlsPlayerClass=void 0,_this.hls=void 0,_this.assetListLoader=void 0,_this.mediaSelection=null,_this.altSelection=null,_this.media=null,_this.detachedData=null,_this.requiredTracks=null,_this.manager=null,_this.playerQueue=[],_this.bufferedPos=-1,_this.timelinePos=-1,_this.schedule=void 0,_this.playingItem=null,_this.bufferingItem=null,_this.waitingItem=null,_this.playingAsset=null,_this.bufferingAsset=null,_this.shouldPlay=!1,_this.onPlay=function(){_this.shouldPlay=!0},_this.onPause=function(){_this.shouldPlay=!1},_this.onSeeking=function(){var currentTime=_this.currentTime;if(void 0!==currentTime&&!_this.playbackDisabled){var diff=currentTime-_this.timelinePos,roundingError=Math.abs(diff)<1/7056e5;if(!roundingError){roundingError=diff<=-.01,diff=(_this.timelinePos=currentTime,_this.bufferedPos=currentTime,_this.checkBuffer(),_this.playingItem);if(diff)if(roundingError&&currentTime<diff.start||currentTime>=diff.end){var scheduleIndex=_this.schedule.findItemIndexAtTime(_this.timelinePos);if(!_this.isInterstitial(diff)&&null!=(_this$media=_this.media)&&_this$media.paused&&(_this.shouldPlay=!1),!roundingError){var _this$media=_this.findItemIndex(diff);if(_this$media<scheduleIndex){var jumpIndex=_this.schedule.findJumpRestrictedIndex(_this$media+1,scheduleIndex);if(_this$media<jumpIndex)return void _this.setSchedulePosition(jumpIndex)}}_this.setSchedulePosition(scheduleIndex)}else{_this$media=_this.playingAsset;_this$media?(jumpIndex=_this$media.timelineStart,scheduleIndex=_this$media.duration||0,(roundingError&&currentTime<jumpIndex||jumpIndex+scheduleIndex<=currentTime)&&_this.setScheduleToAssetAtTime(currentTime,_this$media)):_this.playingLastItem&&_this.isInterstitial(diff)&&(roundingError=diff.event.assetList[0])&&(_this.playingItem=null,_this.setScheduleToAssetAtTime(currentTime,roundingError))}}}},_this.onTimeupdate=function(){var playingItem,currentTime=_this.currentTime;void 0===currentTime||_this.playbackDisabled||currentTime>_this.timelinePos&&(currentTime>_this.bufferedPos&&_this.checkBuffer(),_this.timelinePos=currentTime,playingItem=_this.playingItem)&&!_this.playingLastItem&&(currentTime>=playingItem.end&&(_this.timelinePos=playingItem.end,playingItem=_this.findItemIndex(playingItem),_this.setSchedulePosition(playingItem+1)),playingItem=_this.playingAsset)&&playingItem.timelineStart+(playingItem.duration||0)<=currentTime&&_this.setScheduleToAssetAtTime(currentTime,playingItem)},_this.onScheduleUpdate=function(removedInterstitials,previousItems){var schedule=_this.schedule,playingItem=_this.playingItem,interstitialEvents=schedule.events||[],scheduleItems=schedule.items||[],schedule=schedule.durations,removedIds=removedInterstitials.map(function(interstitial){return interstitial.identifier}),interstitialsUpdated=!(!interstitialEvents.length&&!removedIds.length),bufferingItem=(interstitialsUpdated&&(!1===_this.hls.config.interstitialAppendInPlace&&interstitialEvents.forEach(function(event){return event.appendInPlace=!1}),_this.log("INTERSTITIALS_UPDATED ("+interstitialEvents.length+"): "+interstitialEvents+"\nSchedule: "+scheduleItems.map(segmentToString))),removedIds.length&&_this.log("Removed events "+removedIds),_this.playerQueue.forEach(function(player){if(player.interstitial.appendInPlace){var timelineStart=player.assetItem.timelineStart,diff=player.timelineOffset-timelineStart;if(diff)try{player.timelineOffset=timelineStart}catch(e){.02<Math.abs(diff)&&_this.warn(e+' ("'+player.assetId+'" '+player.timelineOffset+"->"+timelineStart+")")}}}),playingItem&&!playingItem.event&&(_this.playingItem=_this.updateItem(playingItem,_this.timelinePos)),_this.bufferingItem);bufferingItem&&(bufferingItem.event?_this.updateItem(bufferingItem)||(_this.bufferingItem=null,_this.clearInterstitial(bufferingItem.event,null)):_this.bufferingItem=_this.updateItem(bufferingItem,_this.bufferedPos)),_this.waitingItem=_this.updateItem(_this.waitingItem),removedInterstitials.forEach(function(interstitial){interstitial.assetList.forEach(function(asset){_this.clearAssetPlayer(asset.identifier,null)})}),(interstitialsUpdated||previousItems)&&(_this.hls.trigger(Events.INTERSTITIALS_UPDATED,{events:interstitialEvents.slice(0),schedule:scheduleItems.slice(0),durations:schedule,removedIds:removedIds}),_this.isInterstitial(playingItem)&&removedIds.includes(playingItem.event.identifier)?(_this.warn('Interstitial "'+playingItem.event.identifier+'" removed while playing'),_this.primaryFallback(playingItem.event)):_this.checkBuffer())},_this.hls=hls,_this.HlsPlayerClass=HlsPlayerClass,_this.assetListLoader=new AssetListLoader(hls),_this.schedule=new InterstitialsSchedule(_this.onScheduleUpdate,hls.logger),_this.registerListeners(),_this}_inheritsLoose(InterstitialsController,_Logger);var _proto=InterstitialsController.prototype;return _proto.registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),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_UPDATED,this.onLevelUpdated,this),hls.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),hls.on(Events.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),hls.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),hls.on(Events.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),hls.on(Events.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),hls.on(Events.ASSET_LIST_LOADED,this.onAssetListLoaded,this),hls.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),hls.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),hls.on(Events.BUFFERED_TO_END,this.onBufferedToEnd,this),hls.on(Events.MEDIA_ENDED,this.onMediaEnded,this),hls.on(Events.ERROR,this.onError,this),hls.on(Events.DESTROYING,this.onDestroying,this)},_proto.unregisterListeners=function(){var hls=this.hls;hls&&(hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),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_UPDATED,this.onLevelUpdated,this),hls.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),hls.off(Events.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),hls.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),hls.off(Events.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),hls.off(Events.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),hls.off(Events.ASSET_LIST_LOADED,this.onAssetListLoaded,this),hls.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),hls.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),hls.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),hls.off(Events.BUFFERED_TO_END,this.onBufferedToEnd,this),hls.off(Events.MEDIA_ENDED,this.onMediaEnded,this),hls.off(Events.ERROR,this.onError,this),hls.off(Events.DESTROYING,this.onDestroying,this))},_proto.startLoad=function(){this.resumeBuffering()},_proto.stopLoad=function(){this.pauseBuffering()},_proto.resumeBuffering=function(){this.playerQueue.forEach(function(player){return player.resumeBuffering()})},_proto.pauseBuffering=function(){this.playerQueue.forEach(function(player){return player.pauseBuffering()})},_proto.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},_proto.onDestroying=function(){var media=this.primaryMedia;media&&this.removeMediaListeners(media)},_proto.removeMediaListeners=function(media){media.removeEventListener("play",this.onPlay),media.removeEventListener("pause",this.onPause),media.removeEventListener("seeking",this.onSeeking),media.removeEventListener("timeupdate",this.onTimeupdate)},_proto.onMediaAttaching=function(event,data){data=this.media=data.media;this.removeMediaListeners(data),data.addEventListener("seeking",this.onSeeking),data.addEventListener("timeupdate",this.onTimeupdate),data.addEventListener("play",this.onPlay),data.addEventListener("pause",this.onPause)},_proto.onMediaAttached=function(event,data){var playingItem=this.playingItem,detachedMedia=this.detachedData;(this.detachedData=null)===playingItem?this.checkStart():detachedMedia||(this.clearScheduleState(),detachedMedia=this.findItemIndex(playingItem),this.setSchedulePosition(detachedMedia))},_proto.clearScheduleState=function(){this.playingItem=this.bufferingItem=this.waitingItem=this.playingAsset=this.bufferingAsset=null},_proto.onMediaDetaching=function(event,data){var data=!!data.transferMedia,media=this.media;this.media=null,data||(media&&this.removeMediaListeners(media),this.detachedData&&((data=this.getBufferingPlayer())&&(this.playingAsset=null,this.bufferingAsset=null,this.bufferingItem=null,this.waitingItem=null,this.detachedData=null,data.detachMedia()),this.shouldPlay=!1))},_proto.isInterstitial=function(item){return!(null==item||!item.event)},_proto.retreiveMediaSource=function(assetId,toSegment){assetId=this.getAssetPlayer(assetId);assetId&&this.transferMediaFromPlayer(assetId,toSegment)},_proto.transferMediaFromPlayer=function(player,toSegment){var appendInPlace=player.interstitial.appendInPlace,playerMedia=player.media;appendInPlace&&playerMedia===this.primaryMedia?!toSegment||this.isInterstitial(toSegment)&&!toSegment.event.appendInPlace?toSegment&&playerMedia&&(this.detachedData={media:playerMedia}):(appendInPlace=player.transferMedia(),this.log("transfer MediaSource from "+player+" "+JSON.stringify(appendInPlace)),this.bufferingAsset=null,this.detachedData=appendInPlace):toSegment&&playerMedia&&(this.shouldPlay||(this.shouldPlay=!playerMedia.paused))},_proto.transferMediaTo=function(player,media){var attachMediaSourceData=null,primaryPlayer=this.hls,isAssetPlayer=player!==primaryPlayer,appendInPlace=isAssetPlayer&&player.interstitial.appendInPlace,_this$detachedData=null==(_this$detachedData=this.detachedData)?void 0:_this$detachedData.mediaSource,primaryPlayer=primaryPlayer.media&&appendInPlace?(attachMediaSourceData=primaryPlayer.transferMedia(),this.detachedData=attachMediaSourceData,"Primary"):_this$detachedData?((appendInPlace=this.getBufferingPlayer())&&(attachMediaSourceData=appendInPlace.transferMedia()),""+appendInPlace):"<unknown>",primaryPlayer=(this.log("transferring to "+(isAssetPlayer?player:"Primary")+"\nMediaSource "+JSON.stringify(attachMediaSourceData)+" from "+primaryPlayer),attachMediaSourceData||(_this$detachedData?(attachMediaSourceData=this.detachedData,this.log("using detachedData: MediaSource "+JSON.stringify(attachMediaSourceData))):this.detachedData&&this.hls.media!==media||(this.hls.detachMedia(),this.detachedData={media:media})),attachMediaSourceData&&"mediaSource"in attachMediaSourceData&&"closed"!==(null==(appendInPlace=attachMediaSourceData.mediaSource)?void 0:appendInPlace.readyState)),_this$detachedData=primaryPlayer&&attachMediaSourceData?attachMediaSourceData:media;this.log((primaryPlayer?"transfering MediaSource":"attaching media")+" to "+(isAssetPlayer?player:"Primary")),_this$detachedData===attachMediaSourceData&&(appendInPlace=isAssetPlayer&&player.assetId===this.schedule.assetIdAtEnd,_this$detachedData.overrides={duration:this.schedule.duration,endOfStream:!isAssetPlayer||appendInPlace,cueRemoval:!1}),player.attachMedia(_this$detachedData)},_proto.onInterstitialCueEnter=function(){this.onTimeupdate()},_proto.checkStart=function(){var waitingItem,timelinePos,schedule=this.schedule,interstitialEvents=schedule.events;interstitialEvents&&!this.playbackDisabled&&(-1===this.bufferedPos&&(this.bufferedPos=0),timelinePos=this.timelinePos,waitingItem=this.waitingItem,-1===timelinePos?(timelinePos=this.hls.startPosition,this.timelinePos=timelinePos,interstitialEvents.length&&interstitialEvents[0].cue.pre?(interstitialEvents=schedule.findEventIndex(interstitialEvents[0].identifier),this.setSchedulePosition(interstitialEvents)):(0<=timelinePos||!this.primaryLive)&&(interstitialEvents=this.timelinePos=0<timelinePos?timelinePos:0,timelinePos=schedule.findItemIndexAtTime(interstitialEvents),this.setSchedulePosition(timelinePos))):waitingItem&&!this.playingItem&&(interstitialEvents=schedule.findItemIndex(waitingItem),this.setSchedulePosition(interstitialEvents)))},_proto.advanceAfterAssetEnded=function(interstitial,index,assetListIndex){assetListIndex+=1;interstitial.isAssetPastPlayoutLimit(assetListIndex)||interstitial.assetList[assetListIndex].error?(interstitial=this.schedule.items)&&(interstitial.length<=(interstitial=index+1)?this.setSchedulePosition(-1):this.setSchedulePosition(interstitial)):this.setSchedulePosition(index,assetListIndex)},_proto.setScheduleToAssetAtTime=function(time,playingAsset){var schedule=this.schedule,playingAsset=playingAsset.parentIdentifier,interstitial=schedule.getEvent(playingAsset);interstitial&&(playingAsset=schedule.findEventIndex(playingAsset),schedule=schedule.findAssetIndex(interstitial,time),this.setSchedulePosition(playingAsset,schedule))},_proto.setSchedulePosition=function(index,assetListIndex){var _this2=this,scheduleItems=this.schedule.items;if(scheduleItems&&!this.playbackDisabled){this.log("setSchedulePosition "+index+", "+assetListIndex);var scheduledItem=0<=index?scheduleItems[index]:null,media=this.primaryMedia,currentItem=this.playingItem,playingLastItem=this.playingLastItem;if(this.isInterstitial(currentItem)){var interstitial=currentItem.event,playingAsset=this.playingAsset,assetId=null==playingAsset?void 0:playingAsset.identifier,player=assetId?this.getAssetPlayer(assetId):null;if(player&&assetId&&(!this.eventItemsMatch(currentItem,scheduledItem)||void 0!==assetListIndex&&assetId!==(null==(_interstitial$assetLi=interstitial.assetList)?void 0:_interstitial$assetLi[assetListIndex].identifier))&&(this.playingAsset=null,_interstitial$assetLi=interstitial.findAssetIndex(playingAsset),this.log("INTERSTITIAL_ASSET_ENDED "+(_interstitial$assetLi+1)+"/"+interstitial.assetList.length+" "+eventAssetToString(playingAsset)),this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED,{asset:playingAsset,assetListIndex:_interstitial$assetLi,event:interstitial,schedule:scheduleItems.slice(0),scheduleIndex:index,player:player}),this.retreiveMediaSource(assetId,scheduledItem),player.media&&!this.detachedData&&player.detachMedia(),this.clearAssetPlayer(assetId,scheduledItem)),!this.eventItemsMatch(currentItem,scheduledItem))if(this.playingItem=null,this.log("INTERSTITIAL_ENDED "+interstitial+" "+segmentToString(currentItem)),interstitial.hasPlayed=!0,this.hls.trigger(Events.INTERSTITIAL_ENDED,{event:interstitial,schedule:scheduleItems.slice(0),scheduleIndex:index}),this.clearInterstitial(interstitial,scheduledItem),interstitial.cue.once)return this.updateSchedule(),void(scheduledItem&&(playingAsset=this.schedule.findItemIndex(scheduledItem),this.setSchedulePosition(playingAsset,assetListIndex)))}var _interstitial$assetLi=this.playerQueue;_interstitial$assetLi.length&&_interstitial$assetLi.forEach(function(player){var player=player.interstitial,queuedIndex=_this2.schedule.findEventIndex(player.identifier);(queuedIndex<index||index+1<queuedIndex)&&_this2.clearInterstitial(player,scheduledItem)}),this.isInterstitial(scheduledItem)?(this.timelinePos=Math.min(Math.max(this.timelinePos,scheduledItem.start),scheduledItem.end),player=scheduledItem.event,void 0===assetListIndex&&(assetListIndex=this.schedule.findAssetIndex(player,this.timelinePos)),assetId=this.waitingItem,(interstitial=this.preloadAssets(player,assetListIndex))||this.setBufferingItem(scheduledItem),this.eventItemsMatch(scheduledItem,currentItem||assetId)||(this.waitingItem=scheduledItem,this.log("INTERSTITIAL_STARTED "+segmentToString(scheduledItem)+" "+(player.appendInPlace?"append in place":"")),this.hls.trigger(Events.INTERSTITIAL_STARTED,{event:player,schedule:scheduleItems.slice(0),scheduleIndex:index})),0!==(playingAsset=player.assetList.length)||player.assetListResponse?(player.assetListLoader&&(player.assetListLoader.destroy(),player.assetListLoader=void 0),media?(this.waitingItem=null,this.playingItem=scheduledItem,(_interstitial$assetLi=player.assetList[assetListIndex])?(null!==(interstitial=interstitial||this.getAssetPlayer(_interstitial$assetLi.identifier))&&!interstitial.destroyed||(this.warn("asset "+(assetListIndex+1)+"/"+playingAsset+" player destroyed "+player),interstitial=this.createAssetPlayer(player,_interstitial$assetLi,assetListIndex)),!this.eventItemsMatch(scheduledItem,this.bufferingItem)&&player.appendInPlace&&this.isAssetBuffered(_interstitial$assetLi)||(this.startAssetPlayer(interstitial,assetListIndex,scheduleItems,index,media),this.shouldPlay&&playWithCatch(interstitial.media))):(assetId=scheduleItems[index+1],playingAsset=this.media,assetId&&playingAsset&&!this.isInterstitial(assetId)&&playingAsset.currentTime<assetId.start&&(playingAsset.currentTime=this.timelinePos=assetId.start),this.advanceAfterAssetEnded(player,index,assetListIndex||0))):this.log("Waiting for attachMedia to start Interstitial "+player)):this.log("Waiting for ASSET-LIST to complete loading "+player)):null!==scheduledItem?(this.resumePrimary(scheduledItem,index,currentItem),this.shouldPlay&&playWithCatch(this.hls.media)):playingLastItem&&this.isInterstitial(currentItem)&&((this.playingItem=currentItem).event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}},_proto.resumePrimary=function(scheduledItem,index,fromItem){var _this$detachedData2;this.playingItem=scheduledItem,this.playingAsset=null,this.waitingItem=null,this.bufferedToItem(scheduledItem),this.log("resuming "+segmentToString(scheduledItem)),null!=(_this$detachedData2=this.detachedData)&&_this$detachedData2.mediaSource||(((_this$detachedData2=this.timelinePos)<scheduledItem.start||_this$detachedData2>=scheduledItem.end)&&(_this$detachedData2=this.getPrimaryResumption(scheduledItem,index),this.timelinePos=_this$detachedData2),this.attachPrimary(_this$detachedData2,scheduledItem)),fromItem&&(_this$detachedData2=this.schedule.items)&&(this.log("resumed "+segmentToString(scheduledItem)),this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED,{schedule:_this$detachedData2.slice(0),scheduleIndex:index}),this.checkBuffer())},_proto.getPrimaryResumption=function(scheduledItem,index){scheduledItem=scheduledItem.start;if(this.primaryLive){var details=this.primaryDetails;if(0===index)return this.hls.startPosition;if(details&&(scheduledItem<details.fragmentStart||scheduledItem>details.edge))return this.hls.liveSyncPosition||-1}return scheduledItem},_proto.isAssetBuffered=function(asset){var player=this.getAssetPlayer(asset.identifier);return null!=player&&player.hls?player.hls.bufferedToEnd:BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=asset.timelineStart+(asset.duration||0)},_proto.attachPrimary=function(timelinePos,item,skipSeekToStartPosition){item?this.setBufferingItem(item):this.bufferingItem=null,this.bufferingAsset=null;var hls,item=this.primaryMedia;item&&((hls=this.hls).media?this.checkBuffer():(this.transferMediaTo(hls,item),skipSeekToStartPosition&&this.startLoadingPrimaryAt(timelinePos,skipSeekToStartPosition)),skipSeekToStartPosition||(this.timelinePos=timelinePos,this.startLoadingPrimaryAt(timelinePos,skipSeekToStartPosition)))},_proto.startLoadingPrimaryAt=function(timelinePos,skipSeekToStartPosition){this.hls.loadingEnabled&&this.hls.startLoad(timelinePos,skipSeekToStartPosition)},_proto.onManifestLoading=function(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Events.BUFFER_CODECS,this.onBufferCodecs,this)},_proto.onLevelUpdated=function(event,data){-1!==data.level&&(data=this.hls.levels[data.level],data=_objectSpread2(_objectSpread2({},this.mediaSelection||this.altSelection),{},{main:data}),this.mediaSelection=data,this.schedule.parseInterstitialDateRanges(data),!this.playingItem)&&this.schedule.items&&this.checkStart()},_proto.onAudioTrackUpdated=function(event,data){var data=this.hls.audioTracks[data.id],previousSelection=this.mediaSelection;previousSelection?(previousSelection=_objectSpread2(_objectSpread2({},previousSelection),{},{audio:data}),this.mediaSelection=previousSelection):this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{audio:data})},_proto.onSubtitleTrackUpdated=function(event,data){var data=this.hls.subtitleTracks[data.id],previousSelection=this.mediaSelection;previousSelection?(previousSelection=_objectSpread2(_objectSpread2({},previousSelection),{},{subtitles:data}),this.mediaSelection=previousSelection):this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{subtitles:data})},_proto.onAudioTrackSwitching=function(event,data){var audioOption=getBasicSelectionOption(data);this.playerQueue.forEach(function(player){return player.hls.setAudioOption(data)||player.hls.setAudioOption(audioOption)})},_proto.onSubtitleTrackSwitch=function(event,data){var subtitleOption=getBasicSelectionOption(data);this.playerQueue.forEach(function(player){return player.hls.setSubtitleOption(data)||-1!==data.id&&player.hls.setSubtitleOption(subtitleOption)})},_proto.onBufferCodecs=function(event,data){data=data.tracks;data&&(this.requiredTracks=data)},_proto.onBufferAppended=function(event,data){this.checkBuffer()},_proto.onBufferFlushed=function(event,data){var timelinePos,playingItem=this.playingItem;playingItem&&playingItem!==this.bufferingItem&&!this.isInterstitial(playingItem)&&(timelinePos=this.timelinePos,this.bufferedPos=timelinePos,this.setBufferingItem(playingItem))},_proto.onBufferedToEnd=function(event){var interstitialEvents=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&interstitialEvents){for(var i=0;i<interstitialEvents.length;i++){var interstitial=interstitialEvents[i];if(interstitial.cue.post){var interstitial=this.schedule.findEventIndex(interstitial.identifier),_this$schedule$items=null==(_this$schedule$items=this.schedule.items)?void 0:_this$schedule$items[interstitial];this.isInterstitial(_this$schedule$items)&&this.eventItemsMatch(_this$schedule$items,this.bufferingItem)&&this.bufferedToItem(_this$schedule$items,0);break}}this.bufferedPos=Number.MAX_VALUE}},_proto.onMediaEnded=function(event){var playingItem=this.playingItem;!this.playingLastItem&&playingItem&&(playingItem=this.findItemIndex(playingItem),this.setSchedulePosition(playingItem+1))},_proto.updateItem=function(previousItem,time){var items=this.schedule.items;return previousItem&&items&&items[this.findItemIndex(previousItem,time)]||null},_proto.itemsMatch=function(a,b){return!!b&&(a===b||a.event&&b.event&&this.eventItemsMatch(a,b)||!a.event&&!b.event&&(null==(a=a.nextEvent)?void 0:a.identifier)===(null==(a=b.nextEvent)?void 0:a.identifier))},_proto.eventItemsMatch=function(a,b){return!!b&&(a===b||a.event.identifier===(null==(a=b.event)?void 0:a.identifier))},_proto.findItemIndex=function(item,time){return item?this.schedule.findItemIndex(item,time):-1},_proto.updateSchedule=function(){var mediaSelection=this.mediaSelection;mediaSelection&&this.schedule.updateSchedule(mediaSelection,[])},_proto.checkBuffer=function(){var bufferInfo,items=this.schedule.items;items&&(bufferInfo=BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0),this.updateBufferedPos(bufferInfo.end,items,0===bufferInfo.len))},_proto.updateBufferedPos=function(bufferEnd,items,bufferIsEmpty){var playingItem,playingIndex,bufferingIndex,nextItemToBuffer,schedule=this.schedule,bufferingItem=this.bufferingItem;this.bufferedPos>bufferEnd||(1===items.length&&this.itemsMatch(items[0],bufferingItem)?this.bufferedPos=bufferEnd:(playingItem=this.playingItem,playingIndex=this.findItemIndex(playingItem),schedule=schedule.findItemIndexAtTime(bufferEnd),this.bufferedPos<bufferEnd?(bufferingIndex=this.findItemIndex(bufferingItem),nextItemToBuffer=items[items=Math.min(bufferingIndex+1,items.length-1)],-1===schedule&&bufferingItem&&bufferEnd>=bufferingItem.end&&(schedule=items),1<items-playingIndex&&!1===(null==bufferingItem||null==(items=bufferingItem.event)?void 0:items.appendInPlace)||(this.bufferedPos=bufferEnd,bufferingIndex<schedule&&playingIndex<schedule?this.bufferedToItem(nextItemToBuffer):(items=this.primaryDetails,this.primaryLive&&items&&bufferEnd>items.edge-items.targetduration&&nextItemToBuffer.start<items.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(nextItemToBuffer)&&this.preloadAssets(nextItemToBuffer.event,0)))):bufferIsEmpty&&playingItem&&bufferingItem!==playingItem&&schedule===playingIndex&&this.bufferedToItem(playingItem)))},_proto.setBufferingItem=function(item){var bufferingPlayer,bufferingLast=this.bufferingItem,schedule=this.schedule,items=schedule.items,events=schedule.events;return!items||!events||bufferingLast&&schedule.findItemIndex(bufferingLast)===schedule.findItemIndex(item)||(schedule=this.isInterstitial(item),bufferingPlayer=(bufferingPlayer=this.getBufferingPlayer())?bufferingPlayer.remaining:bufferingLast?bufferingLast.end-this.timelinePos:0,this.log("buffered to boundary "+segmentToString(item)+(bufferingLast?" ("+bufferingPlayer.toFixed(2)+" remaining)":"")),this.bufferingItem=item,this.bufferedPos=item.start,this.playbackDisabled||(schedule?this.playerQueue.forEach(function(player){return player.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(function(player){return player.pauseBuffering()}))),this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:events.slice(0),schedule:items.slice(0),bufferingIndex:this.findItemIndex(item),playingIndex:this.findItemIndex(this.playingItem)})),bufferingLast},_proto.bufferedToItem=function(item,assetListIndex){void 0===assetListIndex&&(assetListIndex=0);var bufferingLast=this.setBufferingItem(item);this.playbackDisabled||(this.isInterstitial(item)?this.bufferedToEvent(item,assetListIndex):null!==bufferingLast&&(this.bufferingAsset=null,(assetListIndex=this.detachedData)&&assetListIndex.mediaSource?this.attachPrimary(item.start,item,!0):this.preloadPrimary(item)))},_proto.preloadPrimary=function(item){var index=this.findItemIndex(item),item=this.getPrimaryResumption(item,index);this.startLoadingPrimaryAt(item)},_proto.bufferedToEvent=function(item,assetListIndex){var item=item.event,neverLoaded=0===item.assetList.length&&!item.assetListLoader,playOnce=item.cue.once;!neverLoaded&&playOnce||null!=(neverLoaded=this.preloadAssets(item,assetListIndex))&&neverLoaded.interstitial.appendInPlace&&(playOnce=item.assetList[assetListIndex],item=this.primaryMedia,playOnce)&&item&&this.bufferAssetPlayer(neverLoaded,item)},_proto.preloadAssets=function(interstitial,assetListIndex){var assetListLength=interstitial.assetList.length,neverLoaded=0===assetListLength&&!interstitial.assetListLoader,playOnce=interstitial.cue.once;if(neverLoaded){this.log("Load interstitial asset "+(assetListIndex+1)+"/"+assetListLength+" "+interstitial);var neverLoaded=interstitial.timelineStart,uri=(interstitial.appendInPlace&&this.flushFrontBuffer(neverLoaded),interstitial.assetUrl);if(uri)return this.createAsset(interstitial,0,0,neverLoaded,interstitial.duration,uri);neverLoaded=0,uri=(!this.playingItem&&this.primaryLive&&-1===(neverLoaded=this.hls.startPosition)&&(neverLoaded=this.hls.liveSyncPosition||0),this.assetListLoader.loadAssetList(interstitial,neverLoaded));uri&&(interstitial.assetListLoader=uri)}else if(!playOnce&&assetListLength){for(var i=assetListIndex;i<assetListLength;i++){var asset=interstitial.assetList[i],playerIndex=this.getAssetPlayerQueueIndex(asset.identifier);-1!==playerIndex&&!this.playerQueue[playerIndex].destroyed||asset.error||this.createAssetPlayer(interstitial,asset,i)}return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier)}return null},_proto.flushFrontBuffer=function(startOffset){var _this3=this,requiredTracks=this.requiredTracks;requiredTracks&&Object.keys(requiredTracks).forEach(function(type){_this3.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:startOffset,endOffset:1/0,type:type})})},_proto.getAssetPlayerQueueIndex=function(assetId){for(var playerQueue=this.playerQueue,i=0;i<playerQueue.length;i++)if(assetId===playerQueue[i].assetId)return i;return-1},_proto.getAssetPlayer=function(assetId){assetId=this.getAssetPlayerQueueIndex(assetId);return this.playerQueue[assetId]||null},_proto.getBufferingPlayer=function(){var playerQueue=this.playerQueue,primaryMedia=this.primaryMedia;if(primaryMedia)for(var i=0;i<playerQueue.length;i++)if(playerQueue[i].media===primaryMedia)return playerQueue[i];return null},_proto.createAsset=function(interstitial,assetListIndex,startOffset,timelineStart,duration,uri){duration={parentIdentifier:interstitial.identifier,identifier:function(interstitial,uri,assetListIndex){return interstitial.identifier+"-"+(assetListIndex+1)+"-"+hash(uri)}(interstitial,uri,assetListIndex),duration:duration,startOffset:startOffset,timelineStart:timelineStart,uri:uri};return this.createAssetPlayer(interstitial,duration,assetListIndex)},_proto.createAssetPlayer=function(interstitial,assetItem,assetListIndex){function updateAssetPlayerDetails(details){var errorData,error;details.live?(error=new Error("Interstitials MUST be VOD assets "+interstitial),errorData={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:error},_this4.handleAssetItemError(errorData,interstitial,_this4.schedule.findEventIndex(interstitial.identifier),assetListIndex,error.message)):(errorData=details.edge-details.fragmentStart,(null===(error=assetItem.duration)||error<errorData)&&(_this4.log('Interstitial asset "'+assetId+'" duration change '+error+" > "+errorData),assetItem.duration=errorData,_this4.updateSchedule()))}function endedWithAssetIndex(assetIndex){return function(){var scheduleIndex;_this4.getAssetPlayer(assetId)&&(_this4.shouldPlay=!0,scheduleIndex=_this4.schedule.findEventIndex(interstitial.identifier),_this4.advanceAfterAssetEnded(interstitial,scheduleIndex,assetIndex))}}var _this4=this,primary=(this.log("create HLSAssetPlayer for "+eventAssetToString(assetItem)),this.hls),userConfig=primary.userConfig,videoPreference=userConfig.videoPreference,currentLevel=primary.levels[primary.loadLevel]||primary.levels[primary.currentLevel],currentLevel=((videoPreference||currentLevel)&&(videoPreference=_extends({},videoPreference),currentLevel.videoCodec&&(videoPreference.videoCodec=currentLevel.videoCodec),currentLevel.videoRange)&&(videoPreference.allowedVideoRanges=[currentLevel.videoRange]),primary.audioTracks[primary.audioTrack]),selectedSubtitle=primary.subtitleTracks[primary.subtitleTrack],startPosition=0,duration=(this.primaryLive&&1<(timePastStart=this.timelinePos-assetItem.timelineStart)&&(duration=assetItem.duration)&&timePastStart<duration&&(startPosition=timePastStart),_objectSpread2(_objectSpread2({},userConfig),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:primary.sessionId,assetPlayerId:assetItem.identifier,abrEwmaDefaultEstimate:primary.bandwidthEstimate,interstitialsController:void 0,startPosition:startPosition,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:videoPreference,audioPreference:currentLevel||userConfig.audioPreference,subtitlePreference:selectedSubtitle||userConfig.subtitlePreference})),timePastStart=(interstitial.appendInPlace&&(interstitial.appendInPlaceStarted=!0,assetItem.timelineStart)&&(duration.timelineOffset=assetItem.timelineStart),duration.cmcd),primary=(null!=timePastStart&&timePastStart.sessionId&&timePastStart.contentId&&(duration.cmcd=_extends({},timePastStart,{contentId:hash(assetItem.uri)})),new HlsAssetPlayer(this.HlsPlayerClass,duration,interstitial,assetItem)),assetId=(this.playerQueue.push(primary),(interstitial.assetList[assetListIndex]=assetItem).identifier),_onBufferCodecs=(primary.on(Events.LEVEL_UPDATED,function(event,_ref){_ref=_ref.details;return updateAssetPlayerDetails(_ref)}),primary.on(Events.LEVEL_PTS_UPDATED,function(event,_ref2){_ref2=_ref2.details;return updateAssetPlayerDetails(_ref2)}),function(event,data){var inQueuPlayer=_this4.getAssetPlayer(assetId);inQueuPlayer&&data.tracks&&(inQueuPlayer.off(Events.BUFFER_CODECS,_onBufferCodecs),inQueuPlayer.tracks=data.tracks,data=_this4.primaryMedia,_this4.bufferingAsset===inQueuPlayer.assetItem)&&data&&!inQueuPlayer.media&&_this4.bufferAssetPlayer(inQueuPlayer,data)}),_bufferedToEnd=(primary.on(Events.BUFFER_CODECS,_onBufferCodecs),function(name){var assetListIndex,_this4$schedule$items,nextAssetIndex,inQueuPlayer=_this4.getAssetPlayer(assetId);_this4.log("buffered to end of asset "+inQueuPlayer),inQueuPlayer&&(inQueuPlayer.off(Events.BUFFERED_TO_END,_bufferedToEnd),inQueuPlayer=_this4.schedule.findEventIndex(interstitial.identifier),nextAssetIndex=(assetListIndex=interstitial.findAssetIndex(assetItem))+1,_this4$schedule$items=null==(_this4$schedule$items=_this4.schedule.items)?void 0:_this4$schedule$items[inQueuPlayer],_this4.isInterstitial(_this4$schedule$items))&&(-1===assetListIndex||interstitial.isAssetPastPlayoutLimit(nextAssetIndex)||interstitial.assetList[nextAssetIndex].error?(nextAssetIndex=null==(nextAssetIndex=_this4.schedule.items)?void 0:nextAssetIndex[inQueuPlayer+1])&&_this4.bufferedToItem(nextAssetIndex):_this4.bufferedToItem(_this4$schedule$items,assetListIndex+1))});primary.on(Events.BUFFERED_TO_END,_bufferedToEnd);return primary.once(Events.MEDIA_ENDED,endedWithAssetIndex(assetListIndex)),primary.once(Events.PLAYOUT_LIMIT_REACHED,endedWithAssetIndex(1/0)),primary.on(Events.ERROR,function(event,data){_this4.handleAssetItemError(data,interstitial,_this4.schedule.findEventIndex(interstitial.identifier),assetListIndex,"Asset player error "+data.error+" "+interstitial)}),primary.on(Events.DESTROYING,function(){var error,errorData;_this4.getAssetPlayer(assetId)&&(error=new Error("Asset player destroyed unexpectedly "+assetId),errorData={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:error},_this4.handleAssetItemError(errorData,interstitial,_this4.schedule.findEventIndex(interstitial.identifier),assetListIndex,error.message))}),this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:assetItem,assetListIndex:assetListIndex,event:interstitial,player:primary}),primary},_proto.clearInterstitial=function(interstitial,toSegment){var _this5=this;interstitial.assetList.forEach(function(asset){_this5.clearAssetPlayer(asset.identifier,toSegment)}),interstitial.appendInPlaceStarted=!1},_proto.clearAssetPlayer=function(assetId,toSegment){var playerIndex;null!==toSegment&&-1!==(playerIndex=this.getAssetPlayerQueueIndex(assetId))&&(this.log('clearAssetPlayer "'+assetId+'" toSegment: '+(toSegment&&segmentToString(toSegment))),assetId=this.playerQueue[playerIndex],this.transferMediaFromPlayer(assetId,toSegment),this.playerQueue.splice(playerIndex,1),assetId.destroy())},_proto.emptyPlayerQueue=function(){for(var player;player=this.playerQueue.pop();)player.destroy();this.playerQueue=[]},_proto.startAssetPlayer=function(player,assetListIndex,scheduleItems,scheduleIndex,media){var interstitial=player.interstitial,assetItem=player.assetItem,assetId=player.assetId,assetListLength=interstitial.assetList.length,playingAsset=this.playingAsset;this.playingAsset=assetItem,playingAsset&&playingAsset.identifier===assetId||(playingAsset&&(this.clearAssetPlayer(playingAsset.identifier,scheduleItems[scheduleIndex]),delete playingAsset.error),this.log("INTERSTITIAL_ASSET_STARTED "+(assetListIndex+1)+"/"+assetListLength+" "+player),this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED,{asset:assetItem,assetListIndex:assetListIndex,event:interstitial,schedule:scheduleItems.slice(0),scheduleIndex:scheduleIndex,player:player})),player.media||this.bufferAssetPlayer(player,media)},_proto.bufferAssetPlayer=function(player,media){var interstitial=player.interstitial,assetItem=player.assetItem,assetId=player.assetId,scheduleIndex=this.schedule.findEventIndex(interstitial.identifier),_this$schedule$items2=null==(_this$schedule$items2=this.schedule.items)?void 0:_this$schedule$items2[scheduleIndex];if(_this$schedule$items2){this.setBufferingItem(_this$schedule$items2),this.bufferingAsset=assetItem;var _this$schedule$items2=this.getBufferingPlayer();if(_this$schedule$items2!==player){_this$schedule$items2=(null==_this$schedule$items2?void 0:_this$schedule$items2.tracks)||(null==(_this$schedule$items2=this.detachedData)?void 0:_this$schedule$items2.tracks)||this.requiredTracks;if(interstitial.appendInPlace&&assetItem!==this.playingAsset){if(!player.tracks)return;if(_this$schedule$items2&&!isCompatibleTrackChange(_this$schedule$items2,player.tracks))return assetId=new Error('Asset "'+assetId+"\" SourceBuffer tracks ('"+Object.keys(player.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(_this$schedule$items2)+"')"),_this$schedule$items2={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:assetId},assetItem=interstitial.findAssetIndex(assetItem),void this.handleAssetItemError(_this$schedule$items2,interstitial,scheduleIndex,assetItem,assetId.message)}this.transferMediaTo(player,media)}}},_proto.handleAssetItemError=function(data,interstitial,scheduleIndex,assetListIndex,errorMessage){var assetItem,player,playerIndex;data.details!==ErrorDetails.BUFFER_STALLED_ERROR&&(player=null,(assetItem=interstitial.assetList[assetListIndex]||null)&&(playerIndex=this.getAssetPlayerQueueIndex(assetItem.identifier),player=this.playerQueue[playerIndex]||null),playerIndex=this.schedule.items,assetListIndex=_extends({},data,{fatal:!1,errorAction:createDoNothingErrorAction(!0),asset:assetItem,assetListIndex:assetListIndex,event:interstitial,schedule:playerIndex,scheduleIndex:scheduleIndex,player:player}),this.warn("Asset item error: "+data.error),this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR,assetListIndex),data.fatal)&&(playerIndex=new Error(errorMessage),assetItem&&(this.playingAsset!==assetItem&&this.clearAssetPlayer(assetItem.identifier,null),assetItem.error=playerIndex),interstitial.assetList.some(function(asset){return!asset.error})&&!interstitial.appendInPlace||(interstitial.error=playerIndex),this.primaryFallback(interstitial))},_proto.primaryFallback=function(interstitial){var flushStart=interstitial.timelineStart,playingItem=this.playingItem||this.waitingItem;this.updateSchedule(),playingItem?(this.log('Fallback to primary from event "'+interstitial.identifier+'" start: '+flushStart+" pos: "+this.timelinePos+" playing: "+(playingItem?segmentToString(playingItem):"<none>")+" error: "+interstitial.error),interstitial.appendInPlace&&(interstitial.appendInPlace=!1,this.attachPrimary(flushStart,null),this.flushFrontBuffer(flushStart)),-1===(interstitial=this.timelinePos)&&(interstitial=this.hls.startPosition),flushStart=this.updateItem(playingItem,interstitial),this.itemsMatch(playingItem,flushStart)||(playingItem=this.schedule.findItemIndexAtTime(interstitial),this.setSchedulePosition(playingItem))):this.checkStart()},_proto.onAssetListLoaded=function(event,data){var eventStart,sumDuration,_this$bufferingItem,_this$schedule$items3,_this6=this,interstitial=data.event,interstitialId=interstitial.identifier,data=data.assetListResponse.ASSETS;this.schedule.hasEvent(interstitialId)&&(eventStart=interstitial.timelineStart,sumDuration=0,data.forEach(function(asset,assetListIndex){var duration=parseFloat(asset.DURATION);_this6.createAsset(interstitial,assetListIndex,sumDuration,eventStart+sumDuration,duration,asset.URI),sumDuration+=duration}),interstitial.duration=sumDuration,data=(null==(data=this.waitingItem)?void 0:data.event.identifier)===interstitialId,this.updateSchedule(),_this$bufferingItem=null==(_this$bufferingItem=this.bufferingItem)?void 0:_this$bufferingItem.event,data?(data=this.schedule.findEventIndex(interstitialId),(_this$schedule$items3=null==(_this$schedule$items3=this.schedule.items)?void 0:_this$schedule$items3[data])&&this.setBufferingItem(_this$schedule$items3),this.setSchedulePosition(data)):(null==_this$bufferingItem?void 0:_this$bufferingItem.identifier)===interstitialId&&_this$bufferingItem.appendInPlace&&(_this$schedule$items3=interstitial.assetList[0],data=this.getAssetPlayer(_this$schedule$items3.identifier),interstitialId=this.primaryMedia,_this$schedule$items3)&&data&&interstitialId&&this.bufferAssetPlayer(data,interstitialId))},_proto.onError=function(event,data){switch(data.details){case ErrorDetails.ASSET_LIST_PARSING_ERROR:case ErrorDetails.ASSET_LIST_LOAD_ERROR:case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:var interstitial=data.interstitial;interstitial&&this.primaryFallback(interstitial)}},_createClass(InterstitialsController,[{key:"interstitialsManager",get:function(){if(!this.manager){if(!this.hls||!this.schedule.events)return null;function effectiveBufferingItem(){return c.bufferingItem||c.waitingItem}function effectivePlayingItem(){return c.playingItem||c.waitingItem}function getMappedTime(item,timelineType,asset,controllerField,assetPlayerField){var time,interstitial;return item?(time=item[timelineType].start,(interstitial=item.event)?"playout"!==timelineType&&interstitial.timelineOccupancy===TimelineOccupancy.Point||(null==(timelineType=getAssetPlayer(asset))?void 0:timelineType.interstitial)===interstitial&&(time+=timelineType.assetItem.startOffset+timelineType[assetPlayerField]):time+=("bufferedPos"===controllerField?getBufferedEnd():c[controllerField])-item.start,time):0}function findMappedTime(primaryTime,timelineType){if(0!==primaryTime&&"primary"!==timelineType&&c.schedule.length){var index=c.schedule.findItemIndexAtTime(primaryTime),_c$schedule$items=null==(_c$schedule$items=c.schedule.items)?void 0:_c$schedule$items[index];if(_c$schedule$items)return primaryTime+(_c$schedule$items[timelineType].start-_c$schedule$items.start)}return primaryTime}function getMappedDuration(timelineType){var _c$primaryDetails;return null!=(_c$primaryDetails=c.primaryDetails)&&_c$primaryDetails.live?c.primaryDetails.edge:c.schedule.durations[timelineType]}function _seekTo(time,timelineType){var item=effectivePlayingItem();if(null==item||null==(item=item.event)||!item.restrictions.skip){c.log("seek to "+time+' "'+timelineType+'"');var item=effectivePlayingItem(),targetIndex=c.schedule.findItemIndexAtTime(time,timelineType),_c$schedule$items2=null==(_c$schedule$items2=c.schedule.items)?void 0:_c$schedule$items2[targetIndex],playingInterstitial=null==item?void 0:item.event,playingInterstitial=null==playingInterstitial?void 0:playingInterstitial.appendInPlace,seekInItem=item&&c.itemsMatch(item,_c$schedule$items2);if(item&&(playingInterstitial||seekInItem)){var seekInItem=getAssetPlayer(c.playingAsset),media=(null==seekInItem?void 0:seekInItem.media)||c.hls.media;if(media){var currentTime="primary"===timelineType?media.currentTime:getMappedTime(item,timelineType,c.playingAsset,"timelinePos","currentTime"),currentTime=media.currentTime+(time-currentTime);if(0<=currentTime&&(!seekInItem||playingInterstitial||currentTime<=seekInItem.duration))return void(media.currentTime=currentTime)}}if(_c$schedule$items2){playingInterstitial=time,media=("primary"!==timelineType&&(seekInItem=_c$schedule$items2[timelineType].start,playingInterstitial=_c$schedule$items2.start+(time-seekInItem)),!c.isInterstitial(_c$schedule$items2));if(c.isInterstitial(item)||!media&&!_c$schedule$items2.event.appendInPlace){if(item){currentTime=c.findItemIndex(item);if(currentTime<targetIndex){seekInItem=c.schedule.findJumpRestrictedIndex(currentTime+1,targetIndex);if(currentTime<seekInItem)return void c.setSchedulePosition(seekInItem)}var assetIndex=0;if(media)c.timelinePos=playingInterstitial;else{var assetList=null==_c$schedule$items2||null==(item=_c$schedule$items2.event)?void 0:item.assetList;if(assetList)for(var eventTime=time-(_c$schedule$items2[timelineType]||_c$schedule$items2).start,i=assetList.length;i--;){var asset=assetList[i];if(asset.duration&&eventTime>=asset.startOffset&&eventTime<asset.startOffset+asset.duration){assetIndex=i;break}}}c.setSchedulePosition(targetIndex,assetIndex)}}else{currentTime=c.hls.media;currentTime&&(currentTime.currentTime=playingInterstitial)}}}}var c=this,getAssetPlayer=function(asset){return asset&&c.getAssetPlayer(asset.identifier)},getBufferedEnd=function(){var value=c.bufferedPos;return value===Number.MAX_VALUE?getMappedDuration("primary"):value};this.manager={get events(){var _c$schedule;return(null==(_c$schedule=c.schedule)||null==(_c$schedule=_c$schedule.events)?void 0:_c$schedule.slice(0))||[]},get schedule(){var _c$schedule2;return(null==(_c$schedule2=c.schedule)||null==(_c$schedule2=_c$schedule2.items)?void 0:_c$schedule2.slice(0))||[]},get playerQueue(){return c.playerQueue.slice(0)},get bufferingPlayer(){return c.getBufferingPlayer()},get bufferingAsset(){return c.bufferingAsset},get bufferingItem(){return c.bufferingItem},get playingAsset(){return c.playingAsset},get playingItem(){return c.playingItem},get bufferingIndex(){var item=effectiveBufferingItem();return c.findItemIndex(item)},get playingIndex(){var item=effectivePlayingItem();return c.findItemIndex(item)},get waitingIndex(){return c.findItemIndex(c.waitingItem)},primary:{get bufferedEnd(){return getBufferedEnd()},get currentTime(){var timelinePos=c.timelinePos;return 0<timelinePos?timelinePos:0},get duration(){return getMappedDuration("primary")},get seekableStart(){var _c$primaryDetails2;return(null==(_c$primaryDetails2=c.primaryDetails)?void 0:_c$primaryDetails2.fragmentStart)||0},seekTo:function(time){return _seekTo(time,"primary")}},playout:{get bufferedEnd(){return getMappedTime(effectiveBufferingItem(),"playout",c.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return getMappedTime(effectivePlayingItem(),"playout",c.playingAsset,"timelinePos","currentTime")},get duration(){return getMappedDuration("playout")},get seekableStart(){var _c$primaryDetails3;return findMappedTime((null==(_c$primaryDetails3=c.primaryDetails)?void 0:_c$primaryDetails3.fragmentStart)||0,"playout")},seekTo:function(time){return _seekTo(time,"playout")}},integrated:{get bufferedEnd(){return getMappedTime(effectiveBufferingItem(),"integrated",c.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return getMappedTime(effectivePlayingItem(),"integrated",c.playingAsset,"timelinePos","currentTime")},get duration(){return getMappedDuration("integrated")},get seekableStart(){var _c$primaryDetails4;return findMappedTime((null==(_c$primaryDetails4=c.primaryDetails)?void 0:_c$primaryDetails4.fragmentStart)||0,"integrated")},seekTo:function(time){return _seekTo(time,"integrated")}},skip:function(){var index,item=effectivePlayingItem(),event=null==item?void 0:item.event;event&&!event.restrictions.skip&&(index=c.findItemIndex(item),event.appendInPlace?(item=item.playout.start+item.event.duration,_seekTo(item+.001,"playout")):c.advanceAfterAssetEnded(event,index,1/0))}}}return this.manager}},{key:"playingLastItem",get:function(){var _this$schedule,playingItem=this.playingItem;return!(!this.playbackStarted||!playingItem)&&(_this$schedule=null==(_this$schedule=this.schedule)?void 0:_this$schedule.items,this.itemsMatch(playingItem,_this$schedule?_this$schedule[_this$schedule.length-1]:null))}},{key:"playbackStarted",get:function(){return null!==this.playingItem}},{key:"currentTime",get:function(){if(null!==this.mediaSelection){var queuedForPlayback=this.waitingItem||this.playingItem;if(!this.isInterstitial(queuedForPlayback)||queuedForPlayback.event.appendInPlace){var queuedForPlayback=this.media,_this$bufferingItem2=null==(queuedForPlayback=!queuedForPlayback&&null!=(_this$bufferingItem2=this.bufferingItem)&&null!=(_this$bufferingItem2=_this$bufferingItem2.event)&&_this$bufferingItem2.appendInPlace?this.primaryMedia:queuedForPlayback)?void 0:queuedForPlayback.currentTime;if(void 0!==_this$bufferingItem2&&isFiniteNumber(_this$bufferingItem2))return _this$bufferingItem2}}}},{key:"primaryMedia",get:function(){var _this$detachedData4;return this.media||(null==(_this$detachedData4=this.detachedData)?void 0:_this$detachedData4.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var _this$mediaSelection;return null==(_this$mediaSelection=this.mediaSelection)||null==(_this$mediaSelection=_this$mediaSelection.main)?void 0:_this$mediaSelection.details}},{key:"primaryLive",get:function(){var _this$primaryDetails;return!(null==(_this$primaryDetails=this.primaryDetails)||!_this$primaryDetails.live)}}])}(Logger),SubtitleStreamController=function(_BaseStreamController){function SubtitleStreamController(hls,fragmentTracker,keyLoader){hls=_BaseStreamController.call(this,hls,fragmentTracker,keyLoader,"subtitle-stream-controller",PlaylistLevelType_SUBTITLE)||this;return hls.currentTrackId=-1,hls.tracksBuffered=[],hls.mainDetails=null,hls.registerListeners(),hls}_inheritsLoose(SubtitleStreamController,_BaseStreamController);var _proto=SubtitleStreamController.prototype;return _proto.onHandlerDestroying=function(){this.unregisterListeners(),_BaseStreamController.prototype.onHandlerDestroying.call(this),this.mainDetails=null},_proto.registerListeners=function(){_BaseStreamController.prototype.registerListeners.call(this);var hls=this.hls;hls.on(Events.LEVEL_LOADED,this.onLevelLoaded,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)},_proto.unregisterListeners=function(){_BaseStreamController.prototype.unregisterListeners.call(this);var hls=this.hls;hls.off(Events.LEVEL_LOADED,this.onLevelLoaded,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)},_proto.startLoad=function(startPosition){this.stopLoad(),this.state=State_IDLE,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=startPosition,this.tick()},_proto.onManifestLoading=function(){_BaseStreamController.prototype.onManifestLoading.call(this),this.mainDetails=null},_proto.onMediaDetaching=function(event,data){this.tracksBuffered=[],_BaseStreamController.prototype.onMediaDetaching.call(this,event,data)},_proto.onLevelLoaded=function(event,data){this.mainDetails=data.details},_proto.onSubtitleFragProcessed=function(event,data){var frag=data.frag,data=data.success;if(isMediaFragment(frag)&&(this.fragPrevious=frag),this.state=State_IDLE,data){var buffered=this.tracksBuffered[this.currentTrackId];if(buffered){for(var timeRange,fragStart=frag.start,i=0;i<buffered.length;i++)if(fragStart>=buffered[i].start&&fragStart<=buffered[i].end){timeRange=buffered[i];break}data=frag.start+frag.duration;timeRange?timeRange.end=data:buffered.push(timeRange={start:fragStart,end:data}),this.fragmentTracker.fragBuffered(frag),this.fragBufferedComplete(frag,null),this.media&&this.tick()}}},_proto.onBufferFlushing=function(event,data){var endOffsetSubtitles,startOffset=data.startOffset,endOffset=data.endOffset;0!==startOffset||endOffset===Number.POSITIVE_INFINITY||(endOffsetSubtitles=endOffset-1)<=0||(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();else{if(!(buffered[i].start<endOffsetSubtitles))break;buffered[i].start=endOffsetSubtitles,i++}}),this.fragmentTracker.removeFragmentsInRange(startOffset,endOffsetSubtitles,PlaylistLevelType_SUBTITLE))},_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)},_proto.onSubtitleTracksUpdated=function(event,_ref){var _this2=this,_ref=_ref.subtitleTracks;this.levels&&subtitleOptionsIdentical(this.levels,_ref)?this.levels=_ref.map(function(mediaPlaylist){return new Level(mediaPlaylist)}):(this.tracksBuffered=[],this.levels=_ref.map(function(mediaPlaylist){mediaPlaylist=new Level(mediaPlaylist);return _this2.tracksBuffered[mediaPlaylist.id]=[],mediaPlaylist}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType_SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)},_proto.onSubtitleTrackSwitch=function(event,data){this.currentTrackId=data.id,null!=(data=this.levels)&&data.length&&-1!==this.currentTrackId?(null!=(data=this.levels[this.currentTrackId])&&data.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,data&&this.state!==State_STOPPED&&this.setInterval(500)):this.clearInterval()},_proto.onSubtitleTrackLoaded=function(event,data){var currentTrackId=this.currentTrackId,levels=this.levels,newDetails=data.details,trackId=data.id;if(levels){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;if(newDetails.live||null!=(levels=track.details)&&levels.live){levels=this.mainDetails;if(newDetails.deltaUpdateFailed||!levels)return;var _this$levelLastLoaded,mainSlidingStartFragment=levels.fragments[0];track.details?0===this.alignPlaylists(newDetails,track.details,null==(_this$levelLastLoaded=this.levelLastLoaded)?void 0:_this$levelLastLoaded.details)&&mainSlidingStartFragment&&addSliding(newDetails,mainSlidingStartFragment.start):newDetails.hasProgramDateTime&&levels.hasProgramDateTime?(alignMediaPlaylistByPDT(newDetails,levels),newDetails.fragmentStart):mainSlidingStartFragment&&addSliding(newDetails,mainSlidingStartFragment.start)}track.details=newDetails,this.levelLastLoaded=track,trackId===currentTrackId&&(this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED,{details:newDetails,id:trackId,groupId:data.groupId}),this.tick(),newDetails.live)&&!this.fragCurrent&&this.media&&this.state===State_IDLE&&!findFragmentByPTS(null,newDetails.fragments,this.media.currentTime,0)&&(this.warn("Subtitle playlist not aligned with playback"),track.details=void 0)}}else this.warn("Subtitle tracks were reset while loading level "+trackId)},_proto._handleFragmentLoadComplete=function(fragLoadedData){var startTime,_this3=this,frag=fragLoadedData.frag,fragLoadedData=fragLoadedData.payload,decryptData=frag.decryptdata,hls=this.hls;this.fragContextChanged(frag)||fragLoadedData&&0<fragLoadedData.byteLength&&null!=decryptData&&decryptData.key&&decryptData.iv&&isFullSegmentEncryption(decryptData.method)&&(startTime=performance.now(),this.decrypter.decrypt(new Uint8Array(fragLoadedData),decryptData.key.buffer,decryptData.iv.buffer,getAesModeFromFullSegmentMethod(decryptData.method)).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(){var currentTrackId,targetBufferTime,trackDetails,currentTime,fragLen,fragPrevious,levels,foundFrag,end;this.media?this.state===State_IDLE&&(currentTrackId=this.currentTrackId,currentTrackId=null==(levels=this.levels)?void 0:levels[currentTrackId])&&levels.length&&currentTrackId.details&&(this.waitForLive(currentTrackId)||(levels=this.config,currentTime=this.getLoadPosition(),targetBufferTime=(currentTime=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],currentTime,levels.maxBufferHole)).end,currentTime=currentTime.len,trackDetails=currentTrackId.details,this.hls.maxBufferLength+trackDetails.levelTargetDuration<currentTime)||(fragLen=(currentTime=trackDetails.fragments).length,end=trackDetails.edge,foundFrag=null,fragPrevious=this.fragPrevious,targetBufferTime<end?(levels=end-(end=levels.maxFragLookUpTolerance)<targetBufferTime?0:end,!(foundFrag=findFragmentByPTS(fragPrevious,currentTime,Math.max(currentTime[0].start,targetBufferTime),levels))&&fragPrevious&&fragPrevious.start<currentTime[0].start&&(foundFrag=currentTime[0])):foundFrag=currentTime[fragLen-1],foundFrag&&(isMediaFragment(foundFrag=this.mapToInitFragWhenRequired(foundFrag))&&(end=currentTime[foundFrag.sn-trackDetails.startSN-1])&&end.cc===foundFrag.cc&&this.fragmentTracker.getState(end)===FragmentState_NOT_LOADED&&(foundFrag=end),this.fragmentTracker.getState(foundFrag)===FragmentState_NOT_LOADED)&&this.loadFragment(foundFrag,currentTrackId,targetBufferTime))):this.state=State_IDLE},_proto.loadFragment=function(frag,level,targetBufferTime){isMediaFragment(frag)?_BaseStreamController.prototype.loadFragment.call(this,frag,level,targetBufferTime):this._loadInitSegment(frag,level)},_createClass(SubtitleStreamController,[{key:"mediaBufferTimeRanges",get:function(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}])}(_optionalSelf$navigat),BufferableInstance=function(timeranges){this.buffered=void 0;function getRange(name,index,length){if(length-1<(index>>>=0))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)}}};function sendAddTrackEvent(track,videoEl){var event;try{event=new Event("addtrack")}catch(err){(event=document.createEvent("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(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,enterHandler){var mode=track.mode;if("disabled"===mode&&(track.mode="hidden"),track.cues)for(var i=track.cues.length;i--;)enterHandler&&track.cues[i].removeEventListener("enter",enterHandler),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=function(cues,start,end){var cuesFound=[],firstCueInRange=function(cues,time){if(time<cues[0].startTime)return 0;var len=cues.length-1;if(time>cues[len].endTime)return-1;var left=0,right=len;for(;left<=right;){var mid=Math.floor((right+left)/2);if(time<cues[mid].startTime)right=mid-1;else{if(!(time>cues[mid].startTime&&left<len))return mid;left=mid+1}}return cues[left].startTime-time<time-cues[right].startTime?left:right}(cues,start);if(-1<firstCueInRange)for(var i=firstCueInRange,len=cues.length;i<len;i++){var cue=cues[i];if(cue.startTime>=start&&cue.endTime<=end)cuesFound.push(cue);else if(cue.startTime>end)return cuesFound}return cuesFound}(track.cues,start,end),i=0;i<cues.length;i++)predicate&&!predicate(cues[i])||track.removeCue(cues[i]);"disabled"===mode&&(track.mode=mode)}function filterSubtitleTracks(textTrackList){for(var tracks=[],i=0;i<textTrackList.length;i++){var track=textTrackList[i];"subtitles"!==track.kind&&"captions"!==track.kind||!track.label||tracks.push(textTrackList[i])}return tracks}function getCharForByte(_byte){return String.fromCharCode(specialCea608CharsCodes[_byte]||_byte)}function numArrayToHexArray(numArray){for(var hexArray=[],j=0;j<numArray.length;j++)hexArray.push(numArray[j].toString(16));return hexArray}var SubtitleTrackController=function(_BasePlaylistControll){function SubtitleTrackController(hls){var _this=_BasePlaylistControll.call(this,hls,"subtitle-track-controller")||this;return _this.media=null,_this.tracks=[],_this.groupIds=null,_this.tracksInGroup=[],_this.trackId=-1,_this.currentTrack=null,_this.selectDefaultTrack=!0,_this.queuedDefaultTrack=-1,_this.useTextTrackPolling=!1,_this.subtitlePollingInterval=-1,_this._subtitleDisplay=!0,_this.asyncPollTrackChange=function(){return _this.pollTrackChange(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)},_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(event,data){var media=this.media;media&&(data=!!data.transferMedia,self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||media.textTracks.removeEventListener("change",this.asyncPollTrackChange),-1<this.trackId&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,data||filterSubtitleTracks(media.textTracks).forEach(function(track){clearCurrentCues(track)}))},_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 curDetails,id=data.id,groupId=data.groupId,details=data.details,trackInActiveGroup=this.tracksInGroup[id];trackInActiveGroup&&trackInActiveGroup.groupId===groupId?(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)):this.warn("Subtitle track with id:"+id+" and group:"+groupId+" not found in active group "+(null==trackInActiveGroup?void 0:trackInActiveGroup.groupId))},_proto.onLevelLoading=function(event,data){this.switchLevel(data.level)},_proto.onLevelSwitching=function(event,data){this.switchLevel(data.level)},_proto.switchLevel=function(levelIndex){levelIndex=this.hls.levels[levelIndex];if(levelIndex){var subtitleGroups=levelIndex.subtitleGroups||null,currentGroups=this.groupIds,levelIndex=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(!levelIndex&&!this.tracksInGroup.length)return;this.tracksInGroup=subtitleTracks;var subtitlePreference=this.hls.config.subtitlePreference,subtitlePreference=(!levelIndex&&subtitlePreference&&(this.selectDefaultTrack=!1,levelIndex=-1<(groupIndex=findMatchingOption(subtitlePreference,subtitleTracks))?subtitleTracks[groupIndex]:(groupIndex=findMatchingOption(subtitlePreference,this.tracks),this.tracks[groupIndex])),this.findTrackId(levelIndex)),groupIndex=(-1===subtitlePreference&&levelIndex&&(subtitlePreference=this.findTrackId(null)),{subtitleTracks:subtitleTracks});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,groupIndex),-1!==subtitlePreference&&-1===this.trackId&&this.setSubtitleTrack(subtitlePreference)}}},_proto.findTrackId=function(currentTrack){for(var tracks=this.tracksInGroup,selectDefault=this.selectDefaultTrack,i=0;i<tracks.length;i++){var track=tracks[i];if((!selectDefault||track.default)&&(selectDefault||currentTrack)&&(!currentTrack||matchesOption(track,currentTrack)))return i}if(currentTrack){for(var _i=0;_i<tracks.length;_i++){var _track=tracks[_i];if(mediaAttributesIdentical(currentTrack.attrs,_track.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return _i}for(var _i2=0;_i2<tracks.length;_i2++){var _track2=tracks[_i2];if(mediaAttributesIdentical(currentTrack.attrs,_track2.attrs,["LANGUAGE"]))return _i2}}return-1},_proto.findTrackForTextTrack=function(textTrack){if(textTrack)for(var tracks=this.tracksInGroup,i=0;i<tracks.length;i++)if(subtitleTrackMatchesTextTrack(tracks[i],textTrack))return i;return-1},_proto.onError=function(event,data){data.fatal||!data.context||data.context.type!==PlaylistContextType_SUBTITLE_TRACK||data.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(data.context.groupId)||this.checkRetry(data)},_proto.setSubtitleOption=function(subtitleOption){if(this.hls.config.subtitlePreference=subtitleOption){if(-1===subtitleOption.id)return this.setSubtitleTrack(-1),null;var allSubtitleTracks=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,allSubtitleTracks.length){var currentTrack=this.currentTrack;if(currentTrack&&matchesOption(subtitleOption,currentTrack))return currentTrack;var track,groupIndex=findMatchingOption(subtitleOption,this.tracksInGroup);if(-1<groupIndex)return track=this.tracksInGroup[groupIndex],this.setSubtitleTrack(groupIndex),track;if(currentTrack)return null;groupIndex=findMatchingOption(subtitleOption,allSubtitleTracks);if(-1<groupIndex)return allSubtitleTracks[groupIndex]}}return null},_proto.loadPlaylist=function(hlsUrlParameters){_BasePlaylistControll.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,hlsUrlParameters)},_proto.loadingPlaylist=function(currentTrack,hlsUrlParameters){_BasePlaylistControll.prototype.loadingPlaylist.call(this,currentTrack,hlsUrlParameters);var id=currentTrack.id,groupId=currentTrack.groupId,url=this.getUrlWithDirectives(currentTrack.url,hlsUrlParameters),details=currentTrack.details,age=null==details?void 0:details.age;this.log("Loading subtitle "+id+' "'+currentTrack.name+'" lang:'+currentTrack.lang+" group:"+groupId+(void 0!==(null==hlsUrlParameters?void 0:hlsUrlParameters.msn)?" at sn "+hlsUrlParameters.msn+" part "+hlsUrlParameters.part:"")+(age&&details.live?" age "+age.toFixed(1)+(details.type&&" "+details.type||""):"")+" "+url),this.hls.trigger(Events.SUBTITLE_TRACK_LOADING,{url:url,id:id,groupId:groupId,deliveryDirectives:hlsUrlParameters||null,track:currentTrack})},_proto.toggleTrackModes=function(){var currentTrack,nextTrack,media=this.media;media&&(media=filterSubtitleTracks(media.textTracks),(currentTrack=this.currentTrack)&&!(nextTrack=media.filter(function(textTrack){return subtitleTrackMatchesTextTrack(currentTrack,textTrack)})[0])&&this.warn('Unable to find subtitle TextTrack with name "'+currentTrack.name+'" and language "'+currentTrack.lang+'"'),[].slice.call(media).forEach(function(track){"disabled"!==track.mode&&track!==nextTrack&&(track.mode="disabled")}),nextTrack)&&(media=this.subtitleDisplay?"showing":"hidden",nextTrack.mode!==media)&&(nextTrack.mode=media)},_proto.setSubtitleTrack=function(newId){var lastTrack,_track$groupId,name,type,url,trackLoaded,tracks=this.tracksInGroup;this.media?newId<-1||newId>=tracks.length||!isFiniteNumber(newId)?this.warn("Invalid subtitle track id: "+newId):(this.selectDefaultTrack=!1,lastTrack=this.currentTrack,tracks=tracks[newId]||null,this.trackId=newId,this.currentTrack=tracks,this.toggleTrackModes(),tracks?(trackLoaded=!!tracks.details&&!tracks.details.live,newId===this.trackId&&tracks===lastTrack&&trackLoaded||(this.log("Switching to subtitle-track "+newId+(tracks?' "'+tracks.name+'" lang:'+tracks.lang+" group:"+tracks.groupId:"")),trackLoaded=tracks.id,_track$groupId=tracks.groupId,name=tracks.name,type=tracks.type,url=tracks.url,this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:trackLoaded,groupId:void 0===_track$groupId?"":_track$groupId,name:name,type:type,url:url}),trackLoaded=this.switchParams(tracks.url,null==lastTrack?void 0:lastTrack.details,tracks.details),this.loadPlaylist(trackLoaded))):this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:newId})):this.queuedDefaultTrack=newId},_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)}}])}(PassThroughRemuxer),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},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}return CaptionsLogger.prototype.log=function(severity,msg){this.verboseLevel>=severity&&(msg="function"==typeof msg?msg():msg,logger.log(this.time+" ["+severity+"] "+msg))},CaptionsLogger}(),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;i<attribs.length;i++){var 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<100;i++)this.chars.push(new StyledUnicodeChar);this.logger=logger}var _proto4=Row.prototype;return _proto4.equals=function(other){for(var i=0;i<100;i++)if(!this.chars[i].equals(other.chars[i]))return!1;return!0},_proto4.copy=function(other){for(var i=0;i<100;i++)this.chars[i].copy(other.chars[i])},_proto4.isEmpty=function(){for(var empty=!0,i=0;i<100;i++)if(!this.chars[i].isEmpty()){empty=!1;break}return empty},_proto4.setCursor=function(absPos){this.pos!==absPos&&(this.pos=absPos),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):100<this.pos&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)},_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,_char=(144<=_byte2&&this.backSpace(),getCharForByte(_byte2));100<=this.pos?this.logger.log(0,function(){return"Cannot insert "+_byte2.toString(16)+" ("+_char+") at position "+_this.pos+". Skipping it!"}):(this.chars[this.pos].setChar(_char,this.currPenState),this.moveCursor(1))},_proto4.clearFromPos=function(startPos){for(var i=startPos;i<100;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;i<100;i++){var _char2=this.chars[i].uchar;" "!==_char2&&(empty=!1),chars.push(_char2)}return empty?"":chars.join("")},_proto4.setPenStyles=function(styles){this.currPenState.setStyles(styles),this.chars[this.pos].setPenState(this.currPenState)},Row}(),CaptionScreen=function(){function CaptionScreen(logger){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var i=0;i<15;i++)this.rows.push(new Row(logger));this.logger=logger}var _proto5=CaptionScreen.prototype;return _proto5.reset=function(){for(var i=0;i<15;i++)this.rows[i].clear();this.currRow=14},_proto5.equals=function(other){for(var equal=!0,i=0;i<15;i++)if(!this.rows[i].equals(other.rows[i])){equal=!1;break}return equal},_proto5.copy=function(other){for(var i=0;i<15;i++)this.rows[i].copy(other.rows[i])},_proto5.isEmpty=function(){for(var empty=!0,i=0;i<15;i++)if(!this.rows[i].isEmpty()){empty=!1;break}return empty},_proto5.backSpace=function(){this.rows[this.currRow].backSpace()},_proto5.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},_proto5.insertChar=function(_char3){this.rows[this.currRow].insertChar(_char3)},_proto5.setPen=function(styles){this.rows[this.currRow].setPenStyles(styles)},_proto5.moveCursor=function(relPos){this.rows[this.currRow].moveCursor(relPos)},_proto5.setCursor=function(absPos){this.logger.log(2,"setCursor: "+absPos),this.rows[this.currRow].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<15;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;prevLineTime=this.rows[this.currRow],null!==pacData.indent&&(time=pacData.indent,time=Math.max(time-1,0),prevLineTime.setCursor(pacData.indent),pacData.color=prevLineTime.chars[time].penState.foreground),prevLineTime={foreground:pacData.color,underline:pacData.underline,italics:pacData.italics,background:"black",flash:!1};this.setPen(prevLineTime)},_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 topRowIndex,_this2=this;null===this.nrRollUpRows?this.logger.log(3,"roll_up but nrRollUpRows not set yet"):(this.logger.log(1,function(){return _this2.getDisplayText()}),topRowIndex=this.currRow+1-this.nrRollUpRows,(topRowIndex=this.rows.splice(topRowIndex,1)[0]).clear(),this.rows.splice(this.currRow,0,topRowIndex),this.logger.log(2,"Rolling up"))},_proto5.getDisplayText=function(asOneRow){asOneRow=asOneRow||!1;for(var displayText=[],text="",i=0;i<15;i++){var rowText=this.rows[i].getTextString();rowText&&displayText.push(asOneRow?"Row "+(i+1)+": '"+rowText+"'":rowText.trim())}return text=0<displayText.length?asOneRow?"["+displayText.join(" | ")+"]":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[14],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[14],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 tmp,_this4=this;this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode&&(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};styles.underline=secondByte%2==1,styles.italics=46<=secondByte,styles.italics?styles.foreground="white":(secondByte=Math.floor(secondByte/2)-16,styles.foreground=["white","green","blue","cyan","red","yellow","magenta"][secondByte]),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={a:null,b:null},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){for(var _this5=this,i=(this.logger.time=time,0);i<byteList.length;i+=2)(function(i){var a=127&byteList[i],b=127&byteList[i+1],cmdFound=!1,charsFound=null;if(0==a&&0==b)return;_this5.logger.log(3,function(){return"["+numArrayToHexArray([byteList[i],byteList[i+1]])+"] -> ("+numArrayToHexArray([a,b])+")"});var cmdHistory=_this5.cmdHistory;if(16<=a&&a<=31){if(function(a,b,cmdHistory){return cmdHistory.a===a&&cmdHistory.b===b}(a,b,cmdHistory))return setLastCmd(null,null,cmdHistory),_this5.logger.log(3,function(){return"Repeated command ("+numArrayToHexArray([a,b])+") is dropped"});setLastCmd(a,b,_this5.cmdHistory),cmdFound=(cmdFound=(cmdFound=(cmdFound=_this5.parseCmd(a,b))||_this5.parseMidrow(a,b))||_this5.parsePAC(a,b))||_this5.parseBackgroundAttributes(a,b)}else setLastCmd(null,null,cmdHistory);cmdFound||(charsFound=_this5.parseChars(a,b))&&((cmdHistory=_this5.currentChannel)&&0<cmdHistory?_this5.channels[cmdHistory].insertChars(charsFound):_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)},_proto7.parseCmd=function(a,b){var chNr,channel;return((20===a||28===a||21===a||29===a)&&32<=b&&b<=47||(23===a||31===a)&&33<=b&&b<=35)&&(channel=this.channels[chNr=20===a||21===a||23===a?1:2],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;return(17===a||25===a)&&32<=b&&b<=47&&((chNr=17===a?1:2)!==this.currentChannel?(this.logger.log(0,"Mismatch channel in midrow parsing"),!1):!!(chNr=this.channels[chNr])&&(chNr.ccMIDROW(b),this.logger.log(3,function(){return"MIDROW ("+numArrayToHexArray([a,b])+")"}),!0))},_proto7.parsePAC=function(a,b){var chNr,channel;return((17<=a&&a<=23||25<=a&&a<=31)&&64<=b&&b<=127||(16===a||24===a)&&64<=b&&b<=95)&&(chNr=a<=23?1:2,a=(64<=b&&b<=95?1==chNr?rowsLowCh1:rowsLowCh2:1==chNr?rowsHighCh1:rowsHighCh2)[a],!!(channel=this.channels[chNr]))&&(channel.setPAC(this.interpretPAC(a,b)),this.currentChannel=chNr,!0)},_proto7.interpretPAC=function(row,_byte3){row={color:null,italics:!1,indent:null,underline:!1,row:row},_byte3=95<_byte3?_byte3-96:_byte3-64;return row.underline=1==(1&_byte3),_byte3<=13?row.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(_byte3/2)]:_byte3<=15?(row.italics=!0,row.color="white"):row.indent=4*Math.floor((_byte3-16)/2),row},_proto7.parseChars=function(a,b){var channelNr,oneCode,charCodes=null,charCode1=null;return 17<=(charCode1=25<=a?(channelNr=2,a-8):(channelNr=1,a))&&charCode1<=19?(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]):32<=a&&a<=127&&(charCodes=0===b?[a]:[a,b]),charCodes&&this.logger.log(3,function(){return"Char codes =  "+numArrayToHexArray(charCodes).join(",")}),charCodes},_proto7.parseBackgroundAttributes=function(a,b){var index,bkgData;return((16===a||24===a)&&32<=b&&b<=47||(23===a||31===a)&&45<=b&&b<=47)&&(bkgData={},16===a||24===a?(index=Math.floor((b-32)/2),bkgData.background=backgroundColors[index],b%2==1&&(bkgData.background=bkgData.background+"_semi")):45===b?bkgData.background="transparent":(bkgData.foreground="black",47===b&&(bkgData.underline=!0)),this.channels[a<=23?1:2].setBkgData(bkgData),!0)},_proto7.reset=function(){for(var i=0;i<Object.keys(this.channels).length;i++){var channel=this.channels[i];channel&&channel.reset()}setLastCmd(null,null,this.cmdHistory)},_proto7.cueSplitAtTime=function(t){for(var i=0;i<this.channels.length;i++){var channel=this.channels[i];channel&&channel.cueSplitAtTime(t)}},Cea608Parser}();function setLastCmd(a,b,cmdHistory){cmdHistory.a=a,cmdHistory.b=b}var VTTCue=function(){var AllowedDirections,AllowedAlignments;return null!=optionalSelf&&optionalSelf.VTTCue?self.VTTCue:(AllowedDirections=["","lr","rl"],AllowedAlignments=["start","middle","end","left","right"],VTTCue.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},VTTCue);function isAllowedValue(allowed,value){return"string"==typeof value&&!!Array.isArray(allowed)&&(value=value.toLowerCase(),!!~allowed.indexOf(value))&&value}function findAlignSetting(value){return isAllowedValue(AllowedAlignments,value)}function extend(obj){for(var _len=arguments.length,rest=new Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)rest[_key-1]=arguments[_key];for(var i=1;i<arguments.length;i++){var p,cobj=arguments[i];for(p in cobj)obj[p]=cobj[p]}return obj}function VTTCue(startTime,endTime,text){var cue=this,baseObj={enumerable:!0},_id=(cue.hasBeenReset=!1,""),_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){value=function(value){return isAllowedValue(AllowedDirections,value)}(value);if(!1===value)throw new SyntaxError("An invalid or illegal string was specified.");_vertical=value,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){value=findAlignSetting(value);if(!value)throw new SyntaxError("An invalid or illegal string was specified.");_lineAlign=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,"position",extend({},baseObj,{get:function(){return _position},set:function(value){if(value<0||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){value=findAlignSetting(value);if(!value)throw new SyntaxError("An invalid or illegal string was specified.");_positionAlign=value,this.hasBeenReset=!0}})),Object.defineProperty(cue,"size",extend({},baseObj,{get:function(){return _size},set:function(value){if(value<0||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){value=findAlignSetting(value);if(!value)throw new SyntaxError("An invalid or illegal string was specified.");_align=value,this.hasBeenReset=!0}})),cue.displayState=void 0}}(),StringDecoder=function(){function StringDecoder(){}return StringDecoder.prototype.decode=function(data,options){if(!data)return"";if("string"!=typeof data)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(data))},StringDecoder}();function parseTimeStamp(input){function computeSeconds(h,m,s,f){return 3600*(0|h)+60*(0|m)+(0|s)+parseFloat(f||0)}input=input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return input?59<parseFloat(input[2])?computeSeconds(input[2],input[3],0,input[4]):computeSeconds(input[1],input[2],input[3],input[4]):null}var 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)){v=parseFloat(v);if(0<=v&&v<=100)return this.set(k,v),!0}return!1},Settings}();function parseOptions(input,callback,keyValueDelim,groupDelim){var i,kv,groups=groupDelim?input.split(groupDelim):[input];for(i in groups)"string"==typeof groups[i]&&2===(kv=groups[i].split(keyValueDelim)).length&&callback(kv[0],kv[1])}var defaults=new VTTCue(0,0,""),center="middle"===defaults.align?"middle":"center";function parseCue(input,cue,regionList){var oInput=input;function consumeTimeStamp(){var ts=parseTimeStamp(input);if(null===ts)throw new Error("Malformed timestamp: "+oInput);return input=input.replace(/^[^\sa-zA-Z-]+/,""),ts}function skipWhitespace(){input=input.replace(/^\s+/,"")}if(skipWhitespace(),cue.startTime=consumeTimeStamp(),skipWhitespace(),"--\x3e"!==input.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+oInput);input=input.slice(3),skipWhitespace(),cue.endTime=consumeTimeStamp(),skipWhitespace(),function(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",""),"auto"===(input=settings.get("line","auto"))&&-1===defaults.line&&(input=-1),cue.line=input,cue.lineAlign=settings.get("lineAlign","start"),cue.snapToLines=settings.get("snapToLines",!0),cue.size=settings.get("size",100),cue.align=settings.get("align",center),"auto"===(input=settings.get("position","auto"))&&50===defaults.position&&(input="start"===cue.align||"left"===cue.align?0:"end"===cue.align||"right"===cue.align?100:50),cue.position=input}(input,cue)}function fixLineBreaks(input){return input.replace(/<br(?: \/)?>/gi,"\n")}function startsWith(inputString,searchString,position){return inputString.slice(position=void 0===position?0:position,position+searchString.length)===searchString}var 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){var _this=this;function collectNextLine(){for(var pos=0,buffer=fixLineBreaks(buffer=_this.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}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;var m=(line=collectNextLine()).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)?parseOptions(line,function(k,v){},/:/):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("--\x3e")){_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("--\x3e");if(!line||hasSubstring&&(alreadyCollectedLine=!0)){_this.oncue&&_this.cue&&_this.oncue(_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(){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;function generateCueId(startTime,endTime,text){return hash(startTime.toString())+hash(endTime.toString())+hash(text)}function parseWebVTT(vttByteArray,initPTS,vttCCs,cc,timeOffset,callBack,errorCallBack){var baseTime,srcScale,parsingError,parser=new VTTParser,vttByteArray=utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS,"\n").split("\n"),cues=[],init90kHz=initPTS?(baseTime=initPTS.baseTime,srcScale=initPTS.timescale,toTimescaleFromBase(baseTime,MPEG_TS_CLOCK_FREQ_HZ,1/(srcScale=void 0===srcScale?1:srcScale))):0,cueTime="00:00.000",timestampMapMPEGTS=0,timestampMapLOCAL=0,inHeader=!0;parser.oncue=function(cue){var currCC=vttCCs[cc],cueOffset=vttCCs.ccOffset,webVttMpegTsMapOffset=(timestampMapMPEGTS-init90kHz)/9e4;if(null!=currCC&&currCC.new&&(void 0!==timestampMapLOCAL?cueOffset=vttCCs.ccOffset=currCC.start:function(vttCCs,cc,presentationTime){var currCC=vttCCs[cc],prevCC=vttCCs[currCC.prevCC];if(!prevCC||!prevCC.new&&currCC.new)vttCCs.ccOffset=vttCCs.presentationOffset=currCC.start,currCC.new=!1;else{for(;null!=prevCC&&prevCC.new;)vttCCs.ccOffset+=currCC.start-prevCC.start,currCC.new=!1,prevCC=vttCCs[(currCC=prevCC).prevCC];vttCCs.presentationOffset=presentationTime}}(vttCCs,cc,webVttMpegTsMapOffset)),webVttMpegTsMapOffset){if(!initPTS)return void(parsingError=new Error("Missing initPTS for VTT MPEGTS"));cueOffset=webVttMpegTsMapOffset-vttCCs.presentationOffset}currCC=cue.endTime-cue.startTime,webVttMpegTsMapOffset=normalizePts(9e4*(cue.startTime+cueOffset-timestampMapLOCAL),9e4*timeOffset)/9e4,cue.startTime=Math.max(webVttMpegTsMapOffset,0),cue.endTime=Math.max(webVttMpegTsMapOffset+currCC,0),cueOffset=cue.text.trim();cue.text=decodeURIComponent(encodeURIComponent(cueOffset)),cue.id||(cue.id=generateCueId(cue.startTime,cue.endTime,cueOffset)),0<cue.endTime&&cues.push(cue)},parser.onparsingerror=function(error){parsingError=error},parser.onflush=function(){parsingError?errorCallBack(parsingError):callBack(cues)},vttByteArray.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=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))return(ts+=1e3*secs)+6e4*mins+36e5*hours;throw Error("Malformed X-TIMESTAMP-MAP: Local:"+timeString)}(cueTime)/1e3}catch(error){parsingError=error}return}""===line&&(inHeader=!1)}parser.parse(line+"\n")}),parser.flush()}var 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"};function parseIMSC1(payload,initPTS,callBack,errorCallBack){payload=findBox(new Uint8Array(payload),["mdat"]);if(0===payload.length)errorCallBack(new Error("Could not parse IMSC1 mdat"));else{var baseTime,destScale,round,payload=payload.map(function(mdat){return utf8ArrayToStr(mdat)}),syncTime=(baseTime=initPTS.baseTime,destScale=1,initPTS=initPTS.timescale,toTimescaleFromBase(baseTime,destScale,1/(initPTS=void 0===initPTS?1:initPTS),round=void 0===round?!1:round));try{payload.forEach(function(ttml){return callBack(function(ttml,syncTime){var defaultRateInfo,rateInfo,trim,styleElements,regionElements,tt=(new DOMParser).parseFromString(ttml,"text/xml").getElementsByTagName("tt")[0];if(tt)return 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")),ttml=getElementCollection(tt,"body","[begin]"),[].map.call(ttml,function(cueElement){var cueText=function getTextContent(element,trim){return[].slice.call(element.childNodes).reduce(function(str,node,i){return"br"===node.nodeName&&i?str+"\n":null!=(i=node.childNodes)&&i.length?getTextContent(node,trim):trim?str+node.textContent.trim().replace(/\s+/g," "):str+node.textContent},"")}(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}duration=new VTTCue(startTime-syncTime,endTime-syncTime,cueText);duration.id=generateCueId(duration.startTime,duration.endTime,duration.text);startTime=function(region,style,styleElements){var ttsNs="http://www.w3.org/ns/ttml#styling",regionStyle=null,regionStyleName=null!=region&&region.hasAttribute("style")?region.getAttribute("style"):null;regionStyleName&&styleElements.hasOwnProperty(regionStyleName)&&(regionStyle=styleElements[regionStyleName]);return["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(function(styles,name){var value=getAttributeNS(style,ttsNs,name)||getAttributeNS(region,ttsNs,name)||getAttributeNS(regionStyle,ttsNs,name);return value&&(styles[name]=value),styles},{})}(regionElements[cueElement.getAttribute("region")],styleElements[cueElement.getAttribute("style")],styleElements),endTime=startTime.textAlign;return endTime&&((cueText=textAlignToLineAlign[endTime])&&(duration.lineAlign=cueText),duration.align=endTime),_extends(duration,startTime),duration}).filter(function(cue){return null!==cue});throw new Error("Invalid ttml")}(ttml,syncTime))})}catch(error){errorCallBack(error)}}}function getElementCollection(fromElement,parentName,childName){fromElement=fromElement.getElementsByTagName(parentName)[0];return fromElement?[].slice.call(fromElement.querySelectorAll(childName)):[]}function collectionToDictionary(elementsWithId){return elementsWithId.reduce(function(dict,element){var id=element.getAttribute("xml:id");return id&&(dict[id]=element),dict},{})}function getAttributeNS(element,ns,name){return element&&element.hasAttributeNS(ns,name)?element.getAttributeNS(ns,name):null}function timestampParsingError(node){return new Error("Could not parse ttml timestamp "+node)}function parseTtmlTime(timeAttributeValue,rateInfo){var seconds;return timeAttributeValue?(null===(seconds=parseTimeStamp(timeAttributeValue))&&(HMSF_REGEX.test(timeAttributeValue)?seconds=function(timeAttributeValue,rateInfo){var timeAttributeValue=HMSF_REGEX.exec(timeAttributeValue),frames=(0|timeAttributeValue[4])+(0|timeAttributeValue[5])/rateInfo.subFrameRate;return 3600*(0|timeAttributeValue[1])+60*(0|timeAttributeValue[2])+(0|timeAttributeValue[3])+frames/rateInfo.frameRate}(timeAttributeValue,rateInfo):TIME_UNIT_REGEX.test(timeAttributeValue)&&(seconds=function(timeAttributeValue,rateInfo){var timeAttributeValue=TIME_UNIT_REGEX.exec(timeAttributeValue),value=Number(timeAttributeValue[1]);switch(timeAttributeValue[2]){case"h":return 3600*value;case"m":return 60*value;case"ms":return 1e3*value;case"f":return value/rateInfo.frameRate;case"t":return value/rateInfo.tickRate}return value}(timeAttributeValue,rateInfo))),seconds):null}var 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}(),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.onSubtitleTracksUpdated,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=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},_proto.initCea608Parsers=function(){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 x1,y1,track,merged=!1,i=cueRanges.length;i--;){var cueRange=cueRanges[i],x2=(x1=cueRange[0],x2=cueRange[1],y1=startTime,Math.min(x2,endTime)-Math.max(x1,y1));if(0<=x2&&(cueRange[0]=Math.min(cueRange[0],startTime),cueRange[1]=Math.max(cueRange[1],endTime),merged=!0,.5<x2/(endTime-startTime)))return}merged||cueRanges.push([startTime,endTime]),this.config.renderTextTracksNatively?(track=this.captionsTracks[trackName],this.Cues.newCue(track,startTime,endTime,screen)):(track=this.Cues.newCue(null,startTime,endTime,screen),this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:track,track:trackName}))},_proto.onInitPtsFound=function(event,_ref){var _this=this,frag=_ref.frag,id=_ref.id,initPTS=_ref.initPTS,_ref=_ref.timescale,unparsedVttFrags=this.unparsedVttFrags;id===PlaylistLevelType_MAIN&&(this.initPTS[frag.cc]={baseTime:initPTS,timescale:_ref}),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;i<media.textTracks.length;i++){var textTrack=media.textTracks[i];if(canReuseVttTextTrack(textTrack,{name:label,lang:language,characteristics:"transcribes-spoken-dialog,describes-music-and-sound",attrs:{}}))return textTrack}return null},_proto.createCaptionsTrack=function(trackName){this.config.renderTextTracksNatively?this.createNativeTrack(trackName):this.createNonNativeTrack(trackName)},_proto.createNativeTrack=function(trackName){var captionsTracks,media,label,captionsProperties,existingTrack;this.captionsTracks[trackName]||(captionsProperties=this.captionsProperties,captionsTracks=this.captionsTracks,media=this.media,label=(captionsProperties=captionsProperties[trackName]).label,captionsProperties=captionsProperties.languageCode,(existingTrack=this.getExistingTrack(label,captionsProperties))?(captionsTracks[trackName]=existingTrack,clearCurrentCues(captionsTracks[trackName]),sendAddTrackEvent(captionsTracks[trackName],media)):(existingTrack=this.createTextTrack("captions",label,captionsProperties))&&(existingTrack[trackName]=!0,captionsTracks[trackName]=existingTrack))},_proto.createNonNativeTrack=function(trackName){var trackProperties;this.nonNativeCaptionsTracks[trackName]||(trackProperties=this.captionsProperties[trackName])&&(trackProperties={_id:trackName,label:trackProperties.label,kind:"captions",default:!!trackProperties.media&&!!trackProperties.media.default,closedCaptions:trackProperties.media},this.nonNativeCaptionsTracks[trackName]=trackProperties,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[trackProperties]}))},_proto.createTextTrack=function(kind,label,lang){var media=this.media;if(media)return media.addTextTrack(kind,label,lang)},_proto.onMediaAttaching=function(event,data){this.media=data.media,data.mediaSource||this._cleanTracks()},_proto.onMediaDetaching=function(event,data){var captionsTracks,data=!!data.transferMedia;this.media=null,data||(captionsTracks=this.captionsTracks,Object.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 inUseTracks,_this2=this,data=data.subtitleTracks||[],hasIMSC1=data.some(function(track){return"stpp.ttml.im1t"===track.textCodec});(this.config.enableWebVTT||hasIMSC1&&this.config.enableIMSC1)&&(subtitleOptionsIdentical(this.tracks,data)?this.tracks=data:(this.textTracks=[],this.tracks=data,this.config.renderTextTracksNatively?(hasIMSC1=this.media,inUseTracks=hasIMSC1?filterSubtitleTracks(hasIMSC1.textTracks):null,this.tracks.forEach(function(track,index){var textTrackKind,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)}textTrack?clearCurrentCues(textTrack):(textTrackKind=captionsOrSubtitlesFromCharacteristics(track),(textTrack=_this2.createTextTrack(textTrackKind,track.name,track.lang))&&(textTrack.mode="disabled")),textTrack&&_this2.textTracks.push(textTrack)}),null!=inUseTracks&&inUseTracks.length&&(data=inUseTracks.filter(function(t){return null!==t}).map(function(t){return t.label})).length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+data.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")):this.tracks.length&&(hasIMSC1=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:hasIMSC1}))))},_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);instreamIdMatch&&(instreamIdMatch="textTrack"+instreamIdMatch[1],instreamIdMatch=_this3.captionsProperties[instreamIdMatch])&&(instreamIdMatch.label=captionsTrack.name,captionsTrack.lang&&(instreamIdMatch.languageCode=captionsTrack.lang),instreamIdMatch.media=captionsTrack)})},_proto.closedCaptionsForLevel=function(frag){frag=this.hls.levels[frag.level];return null==frag?void 0:frag.attrs["CLOSED-CAPTIONS"]},_proto.onFragLoading=function(event,data){var cea608Parser1,cea608Parser2,lastSn,cc,_data$frag;this.enabled&&data.frag.type===PlaylistLevelType_MAIN&&(cea608Parser1=this.cea608Parser1,cea608Parser2=this.cea608Parser2,lastSn=this.lastSn,cc=(_data$frag=data.frag).cc,_data$frag=_data$frag.sn,data=null!=(data=null==(data=data.part)?void 0:data.index)?data:-1,cea608Parser1&&cea608Parser2&&(_data$frag!==lastSn+1||_data$frag===lastSn&&data!==this.lastPartIndex+1||cc!==this.lastCc)&&(cea608Parser1.reset(),cea608Parser2.reset()),this.lastCc=cc,this.lastSn=_data$frag,this.lastPartIndex=data)},_proto.onFragLoaded=function(event,data){var decryptData,decrypted,frag=data.frag,payload=data.payload;frag.type===PlaylistLevelType_SUBTITLE&&(payload.byteLength?(decryptData=frag.decryptdata,decrypted="stats"in data,null!=decryptData&&decryptData.encrypted&&!decrypted||(decryptData=this.tracks[frag.level],(decrypted=this.vttCCs)[frag.cc]||(decrypted[frag.cc]={start:frag.start,prevCC:this.prevCC,new:!0},this.prevCC=frag.cc),decryptData&&"stpp.ttml.im1t"===decryptData.textCodec?this._parseIMSC1(frag,payload):this._parseVTTs(data))):this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:frag,error:new Error("Empty subtitle 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){hls.logger.log("Failed to parse IMSC1: "+error),hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:frag,error:error})})},_proto._parseVTTs=function(data){var hls,_this5=this,frag=data.frag,payload=data.payload,initPTS=this.initPTS,unparsedVttFrags=this.unparsedVttFrags,maxAvCC=initPTS.length-1;initPTS[frag.cc]||-1!=maxAvCC?(hls=this.hls,parseWebVTT(null!=(initPTS=frag.initSegment)&&initPTS.data?appendUint8Array(frag.initSegment.data,new Uint8Array(payload)).buffer:payload,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),hls.logger.log("Failed to parse VTT cue: "+error),missingInitPTS&&maxAvCC>frag.cc||hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:frag,error:error})})):unparsedVttFrags.push(data)},_proto._fallbackToIMSC1=function(frag,payload){var _this6=this,trackPlaylistMedia=this.tracks[frag.level];trackPlaylistMedia.textCodec||parseIMSC1(payload,this.initPTS[frag.cc],function(){trackPlaylistMedia.textCodec="stpp.ttml.im1t",_this6._parseIMSC1(frag,payload)},function(){trackPlaylistMedia.textCodec="wvtt"})},_proto._appendCues=function(cues,fragLevel){var textTrack,currentTrack,hls=this.hls;this.config.renderTextTracksNatively?(textTrack=this.textTracks[fragLevel])&&"disabled"!==textTrack.mode&&cues.forEach(function(cue){return addCueToTrack(textTrack,cue)}):(currentTrack=this.tracks[fragLevel])&&(currentTrack=currentTrack.default?"default":"subtitles"+fragLevel,hls.trigger(Events.CUES_PARSED,{type:"subtitles",cues:cues,track:currentTrack}))},_proto.onFragDecrypted=function(event,data){data.frag.type===PlaylistLevelType_SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,data)},_proto.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},_proto.onFragParsingUserdata=function(event,data){if(this.enabled&&this.config.enableCEA708Captions){var frag=data.frag,samples=data.samples;if(frag.type!==PlaylistLevelType_MAIN||"NONE"!==this.closedCaptionsForLevel(frag))for(var i=0;i<samples.length;i++){var ccBytes=samples[i].bytes;ccBytes&&(this.cea608Parser1||this.initCea608Parsers(),ccBytes=this.extractCea608Data(ccBytes),this.cea608Parser1.addData(samples[i].pts,ccBytes[0]),this.cea608Parser2.addData(samples[i].pts,ccBytes[1]))}}},_proto.onBufferFlushing=function(event,_ref2){var captionsTracks,textTracks,startOffset=_ref2.startOffset,endOffset=_ref2.endOffset,endOffsetSubtitles=_ref2.endOffsetSubtitles,_ref2=_ref2.type,media=this.media;!media||media.currentTime<endOffset||(_ref2&&"video"!==_ref2||(captionsTracks=this.captionsTracks,Object.keys(captionsTracks).forEach(function(trackName){return removeCuesInRange(captionsTracks[trackName],startOffset,endOffset)})),this.config.renderTextTracksNatively&&0===startOffset&&void 0!==endOffsetSubtitles&&(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++];0==ccbyte1&&0==ccbyte2||!(0!=(4&tmpByte))||0!=(tmpByte=3&tmpByte)&&1!=tmpByte||(actualCCBytes[tmpByte].push(ccbyte1),actualCCBytes[tmpByte].push(ccbyte2))}return actualCCBytes},TimelineController}();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 newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var WHITESPACE_CHAR=/\s/,Cues={newCue:function(track,startTime,endTime,captionScreen){for(var row,indenting,indent,text,result=[],Cue=self.VTTCue||self.TextTrackCue,r=0;r<captionScreen.rows.length;r++)if(indenting=!0,indent=0,text="",!(row=captionScreen.rows[r]).isEmpty()){for(var _track$cues,c=0;c<row.chars.length;c++)WHITESPACE_CHAR.test(row.chars[c].uchar)&&indenting?indent++:(text+=row.chars[c].uchar,indenting=!1);(row.cueStartTime=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)||((_track$cues=new Cue(startTime,endTime,cueText)).id=id,_track$cues.line=r+1,_track$cues.align="left",_track$cues.position=10+Math.min(80,10*Math.floor(8*indent/32)),result.push(_track$cues))}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}};var 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=function(context,signal){signal={method:"GET",mode:"cors",credentials:"same-origin",signal:signal,headers:new self.Headers(_extends({},context.headers))};context.rangeEnd&&signal.headers.set("Range","bytes="+context.rangeStart+"-"+String(context.rangeEnd-1));return signal}(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),(isPromise(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(response){_this.response=_this.loader=response;var statusText,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)return stats.loading.first=first,stats.total=function(headers){var contentRange=headers.get("Content-Range");if(contentRange){contentRange=function(byteRangeHeader){byteRangeHeader=BYTERANGE.exec(byteRangeHeader);if(byteRangeHeader)return parseInt(byteRangeHeader[2])-parseInt(byteRangeHeader[1])+1}(contentRange);if(isFiniteNumber(contentRange))return contentRange}contentRange=headers.get("Content-Length");if(contentRange)return parseInt(contentRange)}(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();throw first=response.status,statusText=response.statusText,new FetchError(statusText||"fetch, bad network response",first,response)}).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=(total&&(stats.loaded=stats.total=total),{url:response.url,data:responseData,code:response.status});onProgress&&!isFiniteNumber(config.highWaterMark)&&onProgress(stats,context,responseData,response),callbacks.onSuccess(total,stats,context,response)}).catch(function(error){var code,text;self.clearTimeout(_this.requestTimeout),stats.aborted||(code=error&&error.code||0,text=error?error.message:null,callbacks.onError({code:code,text:text},context,error?error.details:null,stats))})},_proto.getCacheAge=function(){var ageHeader,result=null;return result=this.response?(ageHeader=this.response.headers.get("age"))?parseFloat(ageHeader):null: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);function _pump(){return reader.read().then(function(data){var len;return data.done?(chunkCache.dataLength&&onProgress(stats,context,chunkCache.flush().buffer,response),Promise.resolve(new ArrayBuffer(0))):(len=(data=data.value).length,stats.loaded+=len,len<highWaterMark||chunkCache.dataLength?(chunkCache.push(data),chunkCache.dataLength>=highWaterMark&&onProgress(stats,context,chunkCache.flush().buffer,response)):onProgress(stats,context,data.buffer,response),_pump())}).catch(function(){return Promise.reject()})}var chunkCache=new ChunkCache,reader=response.body.getReader();return _pump()},FetchLoader}();function getRequest(context,initParams){return new self.Request(context.url,initParams)}var FetchError=function(_Error){function FetchError(message,code,details){message=_Error.call(this,message)||this;return message.code=void 0,message.details=void 0,message.code=code,message.details=details,message}return _inheritsLoose(FetchError,_Error),FetchError}(_wrapNativeSuper(Error)),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,this.stats=new LoadStats,this.retryDelay=0}var _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 xhr,stats,xhrSetup,_this=this,config=this.config,context=this.context;config&&context&&(xhr=this.loader=new self.XMLHttpRequest,(stats=this.stats).loading.first=0,stats.loaded=0,stats.aborted=!1,(xhrSetup=this.xhrSetup)?Promise.resolve().then(function(){if(_this.loader===xhr&&!_this.stats.aborted)return xhrSetup(xhr,context.url)}).catch(function(error){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,_config$loadPolicy=_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:_config$loadPolicy,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 readyState=xhr.status,useResponseText="text"===xhr.responseType?xhr.responseText:null;if(200<=readyState&&readyState<300){var len,useResponseText=null!=useResponseText?useResponseText:xhr.response;if(null!=useResponseText)return stats.loading.end=Math.max(self.performance.now(),stats.loading.first),len="arraybuffer"===xhr.responseType?useResponseText.byteLength:useResponseText.length,stats.loaded=stats.total=len,stats.bwEstimate=8e3*stats.total/(stats.loading.end-stats.loading.first),this.callbacks&&((len=this.callbacks.onProgress)&&len(stats,context,useResponseText,xhr),this.callbacks)?(len={url:xhr.responseURL,data:useResponseText,code:readyState},void this.callbacks.onSuccess(len,stats,context,xhr)):void 0}useResponseText=config.loadPolicy.errorRetry;shouldRetry(useResponseText,stats.retry,!1,{url:context.url,data:void 0,code:readyState})?this.retry(useResponseText):(logger.error(readyState+" while loading "+context.url),this.callbacks.onError({code:readyState,text:xhr.statusText},context,xhr,stats))}}},_proto.loadtimeout=function(){var retryConfig;this.config&&(shouldRetry(retryConfig=this.config.loadPolicy.timeoutRetry,this.stats.retry,!0)?this.retry(retryConfig):(logger.warn("timeout while loading "+(null==(retryConfig=this.context)?void 0:retryConfig.url)),(retryConfig=this.callbacks)&&(this.abortInternal(),retryConfig.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 ageHeader,result=null;return result=this.loader&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())?(ageHeader=this.loader.getResponseHeader("age"))?parseFloat(ageHeader):null: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}(),hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,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:eventemitter3,bufferController:AACDemuxer,capLevelController:BaseSegment,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,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{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:1/0,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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},{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:MP4Demuxer,audioTrackController:BaseVideoParser,emeController:EMEController,cmcdController:MP4Remuxer,contentSteeringController:AC3Demuxer,interstitialsController:InterstitialsController});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,logger){var currentLoader=config.loader;currentLoader!==FetchLoader&&currentLoader!==XhrLoader?(logger.log("[config]: Custom loader detected, cannot enable progressive streaming"),config.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(config.loader=FetchLoader,config.progressive=!0,config.enableSoftwareAES=!0,logger.log("[config]: Progressive streaming enabled, using FetchLoader"))}function getCueClass(){if("undefined"!=typeof self)return 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}var 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}();var ID3TrackController=function(){function ID3TrackController(hls){var _this=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=function(){_this.hls&&_this.hls.trigger(Events.EVENT_CUE_ENTER,{})},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=this.onEventCueEnter=null},_proto._registerListeners=function(){var hls=this.hls;hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),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),hls.on(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},_proto._unregisterListeners=function(){var hls=this.hls;hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),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),hls.off(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},_proto.onMediaAttaching=function(event,data){this.media=data.media,!1===(null==(data=data.overrides)?void 0:data.cueRemoval)&&(this.removeCues=!1)},_proto.onMediaAttached=function(){var details=this.hls.latestLevelDetails;details&&this.updateDateRangeCues(details)},_proto.onMediaDetaching=function(event,data){this.media=null,!data.transferMedia&&(this.id3Track&&(this.removeCues&&clearCurrentCues(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},_proto.onManifestLoading=function(){this.dateRangeCuesAppended={}},_proto.createTrack=function(media){media=this.getID3Track(media.textTracks);return media.mode="hidden",media},_proto.getID3Track=function(textTracks){if(this.media){for(var i=0;i<textTracks.length;i++){var textTrack=textTracks[i];if("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,Cue=(this.id3Track||(this.id3Track=this.createTrack(this.media)),getCueClass());if(Cue)for(var i=0;i<samples.length;i++){var type=samples[i].type;if((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:endTime)-startTime<=0&&(endTime=startTime+.25);for(var j=0;j<frames.length;j++){var frame=frames[j];!isId3TimestampFrame(frame)&&(this.updateId3CueEnds(startTime,type),frame=createCueWithDataFields(Cue,startTime,endTime,frame,type))&&this.id3Track.addCue(frame)}}}}}}},_proto.updateId3CueEnds=function(startTime,type){var _this$id3Track,cues=null==(_this$id3Track=this.id3Track)?void 0:_this$id3Track.cues;if(cues)for(var i=cues.length;i--;){var cue=cues[i];cue.type===type&&cue.startTime<startTime&&cue.endTime===MAX_CUE_ENDTIME&&(cue.endTime=startTime)}},_proto.onBufferFlushing=function(event,_ref){var enableEmsgMetadataCues,enableID3MetadataCues,startOffset=_ref.startOffset,endOffset=_ref.endOffset,_ref=_ref.type,id3Track=this.id3Track,hls=this.hls;hls&&(hls=hls.config,enableEmsgMetadataCues=hls.enableEmsgMetadataCues,enableID3MetadataCues=hls.enableID3MetadataCues,id3Track)&&(enableEmsgMetadataCues||enableID3MetadataCues)&&removeCuesInRange(id3Track,startOffset,endOffset,"audio"===_ref?function(cue){return cue.type===MetadataSchema.audioId3&&enableID3MetadataCues}:"video"===_ref?function(cue){return cue.type===MetadataSchema.emsg&&enableEmsgMetadataCues}:function(cue){return cue.type===MetadataSchema.audioId3&&enableID3MetadataCues||cue.type===MetadataSchema.emsg&&enableEmsgMetadataCues})},_proto.onLevelUpdated=function(event,_ref2){_ref2=_ref2.details;this.updateDateRangeCues(_ref2,!0)},_proto.onLevelPtsUpdated=function(event,data){.01<Math.abs(data.drift)&&this.updateDateRangeCues(data.details)},_proto.updateDateRangeCues=function(details,removeOldCues){var _this2=this;if(this.media&&details.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var id3Track=this.id3Track,dateRanges=details.dateRanges,ids=Object.keys(dateRanges),dateRangeCuesAppended=this.dateRangeCuesAppended;if(id3Track&&removeOldCues)if(null!=(removeOldCues=id3Track.cues)&&removeOldCues.length)for(var idsToRemove=Object.keys(dateRangeCuesAppended).filter(function(id){return!ids.includes(id)}),i=idsToRemove.length;i--;)!function(){var id=idsToRemove[i],cues=dateRangeCuesAppended[id].cues;delete dateRangeCuesAppended[id],Object.keys(cues).forEach(function(key){try{var cue=cues[key];cue.removeEventListener("enter",_this2.onEventCueEnter),id3Track.removeCue(cue)}catch(e){}})}();else dateRangeCuesAppended=this.dateRangeCuesAppended={};removeOldCues=details.fragments[details.fragments.length-1];if(0!==ids.length&&isFiniteNumber(null==removeOldCues?void 0:removeOldCues.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));function _loop2(){for(var id=ids[_i],dateRange=dateRanges[id],startTime=dateRange.startTime,appendedDateRangeCues=dateRangeCuesAppended[id],cues=(null==appendedDateRangeCues?void 0:appendedDateRangeCues.cues)||{},durationKnown=(null==appendedDateRangeCues?void 0:appendedDateRangeCues.durationKnown)||!1,endTime=MAX_CUE_ENDTIME,duration=dateRange.duration,attributes=(dateRange.endDate&&null!==duration?(endTime=startTime+duration,durationKnown=!0):dateRange.endOnNext&&!durationKnown&&(duration=ids.reduce(function(candidateDateRange,id){if(id!==dateRange.id){id=dateRanges[id];if(id.class===dateRange.class&&id.startDate>dateRange.startDate&&(!candidateDateRange||dateRange.startDate<candidateDateRange.startDate))return id}return candidateDateRange},null))&&(endTime=duration.startTime,durationKnown=!0),Object.keys(dateRange.attr)),j=0;j<attributes.length;j++){var attrName,str,key=attributes[j];"ID"!==(attrName=key)&&"CLASS"!==attrName&&"CUE"!==attrName&&"START-DATE"!==attrName&&"DURATION"!==attrName&&"END-DATE"!==attrName&&"END-ON-NEXT"!==attrName&&((attrName=cues[key])?durationKnown&&!appendedDateRangeCues.durationKnown?attrName.endTime=endTime:.01<Math.abs(attrName.startTime-startTime)&&(attrName.startTime=startTime,attrName.endTime=endTime):Cue&&(attrName=dateRange.attr[key],function(attrName){return"SCTE35-OUT"===attrName||"SCTE35-IN"===attrName||"SCTE35-CMD"===attrName}(key)&&(str=attrName,attrName=Uint8Array.from(str.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),str=createCueWithDataFields(Cue,startTime,endTime,{key:key,data:attrName},MetadataSchema.dateRange))&&(str.id=id,_this2.id3Track.addCue(str),cues[key]=str,!_this2.hls.config.interstitialsController||"X-ASSET-LIST"!==key&&"X-ASSET-URL"!==key||str.addEventListener("enter",_this2.onEventCueEnter)))}dateRangeCuesAppended[id]={cues:cues,dateRange:dateRange,durationKnown:durationKnown}}for(var Cue=getCueClass(),_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.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var _this$config,latency,lowLatencyMode,media=_this.media,levelDetails=_this.hls.latestLevelDetails;media&&levelDetails&&(_this.currentTime=media.currentTime,null!==(latency=_this.computeLatency()))&&(_this._latency=latency,lowLatencyMode=(_this$config=_this.config).lowLatencyMode,_this$config=_this$config.maxLiveSyncPlaybackRate,lowLatencyMode)&&1!==_this$config&&levelDetails.live&&null!==(lowLatencyMode=_this.targetLatency)&&((latency=latency-lowLatencyMode)<Math.min(_this.maxLatency,lowLatencyMode+levelDetails.targetduration)&&.05<latency&&1<_this.forwardBufferLength?(lowLatencyMode=Math.min(2,Math.max(1,_this$config)),levelDetails=Math.round(2/(1+Math.exp(-.75*latency-_this.edgeStalled))*20)/20,media.playbackRate=Math.min(lowLatencyMode,Math.max(1,levelDetails))):1!==media.playbackRate&&0!==media.playbackRate&&(media.playbackRate=1))},this.hls=hls,this.config=hls.config,this.registerListeners()}var _proto=LatencyController.prototype;return _proto.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},_proto.registerListeners=function(){this.hls.on(Events.MEDIA_ATTACHED,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.onTimeupdate)},_proto.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},_proto.onManifestLoading=function(){this._latency=null,this.stallCount=0},_proto.onLevelUpdated=function(event,_ref){_ref=_ref.details;_ref.advanced&&this.onTimeupdate(),!_ref.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},_proto.onError=function(event,data){data.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(data=this.hls.latestLevelDetails))&&data.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency")},_proto.estimateLiveEdge=function(){var levelDetails=this.hls.latestLevelDetails;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 _this$hls,config=this.config;return void 0!==config.liveMaxLatencyDuration?config.liveMaxLatencyDuration:(_this$hls=null==(_this$hls=this.hls)?void 0:_this$hls.latestLevelDetails)?config.liveMaxLatencyDurationCount*_this$hls.targetduration:0}},{key:"targetLatency",get:function(){var holdBack,partHoldBack,liveSyncDuration,liveSyncDurationCount,userConfig,_this$config2,levelDetails=this.hls.latestLevelDetails;return null===levelDetails?null:(holdBack=levelDetails.holdBack,partHoldBack=levelDetails.partHoldBack,levelDetails=levelDetails.targetduration,liveSyncDuration=(_this$config2=this.config).liveSyncDuration,liveSyncDurationCount=_this$config2.liveSyncDurationCount,_this$config2=_this$config2.lowLatencyMode,userConfig=this.hls.userConfig,_this$config2=_this$config2&&partHoldBack||holdBack,(_this$config2=this._targetLatencyUpdated||userConfig.liveSyncDuration||userConfig.liveSyncDurationCount||0===_this$config2?void 0!==liveSyncDuration?liveSyncDuration:liveSyncDurationCount*levelDetails:_this$config2)+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,levelDetails))},set:function(latency){this.stallCount=0,this.config.liveSyncDuration=latency,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var levelDetails,edge,liveEdge=this.estimateLiveEdge(),targetLatency=this.targetLatency;return null===liveEdge||null===targetLatency||null===(levelDetails=this.hls.latestLevelDetails)?null:(edge=levelDetails.edge,liveEdge=liveEdge-targetLatency-this.edgeStalled,targetLatency=edge-levelDetails.totalduration,edge=edge-(this.config.lowLatencyMode&&levelDetails.partTarget||levelDetails.targetduration),Math.min(Math.max(targetLatency,liveEdge),edge))}},{key:"drift",get:function(){var levelDetails=this.hls.latestLevelDetails;return null===levelDetails?1:levelDetails.drift}},{key:"edgeStalled",get:function(){var maxLevelUpdateAge,levelDetails=this.hls.latestLevelDetails;return null===levelDetails?0:(maxLevelUpdateAge=3*(this.config.lowLatencyMode&&levelDetails.partTarget||levelDetails.targetduration),Math.max(levelDetails.age-maxLevelUpdateAge,0))}},{key:"forwardBufferLength",get:function(){var bufferedRanges,media=this.media,levelDetails=this.hls.latestLevelDetails;return media&&levelDetails?((bufferedRanges=media.buffered.length)?media.buffered.end(bufferedRanges-1):levelDetails.edge)-this.currentTime:0}}])}(),LevelController=function(_BasePlaylistControll){function LevelController(hls,contentSteeringController){hls=_BasePlaylistControll.call(this,hls,"level-controller")||this;return hls._levels=[],hls._firstLevel=-1,hls._maxAutoLevel=-1,hls._startLevel=void 0,hls.currentLevel=null,hls.currentLevelIndex=-1,hls.manualLevelIndex=-1,hls.steering=void 0,hls.onParsedComplete=void 0,hls.steering=contentSteeringController,hls._registerListeners(),hls}_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(){this._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(event,data){this.resetLevels()},_proto.onManifestLoaded=function(event,data){var _this2=this,preferManagedMediaSource=this.hls.config.preferManagedMediaSource,levels=[],redundantSet={},generatePathwaySet={},resolutionFound=!1,videoCodecFound=!1,audioCodecFound=!1;data.levels.forEach(function(levelParsed){var HDCP,VIDEO_RANGE,PATHWAY,RESOLUTION,attributes=levelParsed.attrs,audioCodec=levelParsed.audioCodec,videoCodec=levelParsed.videoCodec,width=(audioCodec&&(levelParsed.audioCodec=audioCodec=getCodecCompatibleName(audioCodec,preferManagedMediaSource)||void 0),0===(null==videoCodec?void 0:videoCodec.indexOf("avc1"))&&(videoCodec=levelParsed.videoCodec=function(videoCodecs){for(var codecs=videoCodecs.split(","),i=0;i<codecs.length;i++){var result,avcdata=codecs[i].split(".");2<avcdata.length&&(result=avcdata.shift()+".",result=(result+=parseInt(avcdata.shift()).toString(16))+("000"+parseInt(avcdata.shift()).toString(16)).slice(-4),codecs[i]=result)}return codecs.join(",")}(videoCodec)),levelParsed.width),height=levelParsed.height,unknownCodecs=levelParsed.unknownCodecs,unknownUnsupportedCodecCount=unknownCodecs?unknownCodecs.length:0;if(unknownCodecs)for(var i=unknownUnsupportedCodecCount;i--;){var unknownCodec=unknownCodecs[i];_this2.isAudioSupported(unknownCodec)?(levelParsed.audioCodec=audioCodec=audioCodec?audioCodec+","+unknownCodec:unknownCodec,unknownUnsupportedCodecCount--,sampleEntryCodesISO.audio[audioCodec.substring(0,4)]=2):_this2.isVideoSupported(unknownCodec)&&(levelParsed.videoCodec=videoCodec=videoCodec?videoCodec+","+unknownCodec:unknownCodec,unknownUnsupportedCodecCount--,sampleEntryCodesISO.video[videoCodec.substring(0,4)]=2)}resolutionFound=resolutionFound||!(!width||!height),videoCodecFound=videoCodecFound||!!videoCodec,audioCodecFound=audioCodecFound||!!audioCodec,unknownUnsupportedCodecCount||audioCodec&&!_this2.isAudioSupported(audioCodec)||videoCodec&&!_this2.isVideoSupported(videoCodec)||(width=attributes.CODECS,height=attributes["FRAME-RATE"],HDCP=attributes["HDCP-LEVEL"],PATHWAY=attributes["PATHWAY-ID"],RESOLUTION=attributes.RESOLUTION,VIDEO_RANGE=attributes["VIDEO-RANGE"],PATHWAY=(PATHWAY||".")+"-"+levelParsed.bitrate+"-"+RESOLUTION+"-"+height+"-"+width+"-"+VIDEO_RANGE+"-"+HDCP,redundantSet[PATHWAY]?redundantSet[PATHWAY].uri===levelParsed.url||levelParsed.attrs["PATHWAY-ID"]?(redundantSet[PATHWAY].addGroupId("audio",attributes.AUDIO),redundantSet[PATHWAY].addGroupId("text",attributes.SUBTITLES)):(RESOLUTION=generatePathwaySet[PATHWAY]+=1,levelParsed.attrs["PATHWAY-ID"]=new Array(RESOLUTION+1).join("."),height=new Level(levelParsed),levels.push(redundantSet[PATHWAY]=height)):(width=new Level(levelParsed),redundantSet[PATHWAY]=width,generatePathwaySet[PATHWAY]=1,levels.push(width)))}),this.filterAndSortMediaOptions(levels,data,resolutionFound,videoCodecFound,audioCodecFound)},_proto.isAudioSupported=function(codec){return areCodecsMediaSourceSupported(codec,"audio",this.hls.config.preferManagedMediaSource)},_proto.isVideoSupported=function(codec){return areCodecsMediaSourceSupported(codec,"video",this.hls.config.preferManagedMediaSource)},_proto.filterAndSortMediaOptions=function(filteredLevels,data,resolutionFound,videoCodecFound,audioCodecFound){var _this3=this,audioTracks=[],subtitleTracks=[],levels=filteredLevels;if(0===(levels=(resolutionFound||videoCodecFound)&&audioCodecFound?levels.filter(function(_ref){var videoCodec=_ref.videoCodec,videoRange=_ref.videoRange,width=_ref.width,_ref=_ref.height;return!!((videoCodec||width&&_ref)&&videoRange)}):levels).length)Promise.resolve().then(function(){var error;_this3.hls&&(data.levels.length&&_this3.warn("One or more CODECS in variant not supported: "+JSON.stringify(data.levels[0].attrs)),error=new Error("no level with compatible codecs found in manifest"),_this3.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:data.url,error:error,reason:error.message}))});else{data.audioTracks&&assignTrackIdsByGroup(audioTracks=data.audioTracks.filter(function(track){return!track.audioCodec||_this3.isAudioSupported(track.audioCodec)})),data.subtitles&&assignTrackIdsByGroup(subtitleTracks=data.subtitles);var unsortedLevels=levels.slice(0),firstLevelInPlaylist=(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){valueB=codecsSetSelectionPreferenceValue(a.codecSet),valueA=codecsSetSelectionPreferenceValue(b.codecSet);if(valueB!==valueA)return valueA-valueB}return a.averageBitrate!==b.averageBitrate?a.averageBitrate-b.averageBitrate:0}),unsortedLevels[0]);if(this.steering&&(levels=this.steering.filterParsedLevels(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){this._firstLevel=_i;var _this$hls$userConfig,firstLevelBitrate=firstLevelInPlaylist.bitrate,bandwidthEstimate=this.hls.bandwidthEstimate;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)&&bandwidthEstimate<(_this$hls$userConfig=Math.min(firstLevelBitrate,this.hls.config.abrEwmaDefaultEstimateMax))&&bandwidthEstimate===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=_this$hls$userConfig);break}filteredLevels={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,filteredLevels)}},_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 el,_ref2=_ref2.frag;void 0!==_ref2&&_ref2.type===PlaylistLevelType_MAIN&&(el=_ref2.elementaryStreams,Object.keys(el).some(function(type){return!!el[type]}))&&null!=(_ref2=this._levels[_ref2.level])&&_ref2.loadError&&(this.log("Resetting level error count of "+_ref2.loadError+" on frag buffered"),_ref2.loadError=0)},_proto.onLevelLoaded=function(event,data){var level=data.level,details=data.details,curLevel=data.levelInfo;curLevel?curLevel===this.currentLevel||data.withoutMultiVariant?(0===curLevel.fragmentError&&(curLevel.loadError=0),(curLevel=curLevel.details)===data.details&&curLevel.advanced&&(curLevel=void 0),this.playlistLoaded(level,data,curLevel)):null!=(curLevel=data.deliveryDirectives)&&curLevel.skip&&(details.deltaUpdateFailed=!0):(this.warn("Invalid level index "+level),null!=(curLevel=data.deliveryDirectives)&&curLevel.skip&&(details.deltaUpdateFailed=!0))},_proto.loadPlaylist=function(hlsUrlParameters){_BasePlaylistControll.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,hlsUrlParameters)},_proto.loadingPlaylist=function(currentLevel,hlsUrlParameters){_BasePlaylistControll.prototype.loadingPlaylist.call(this,currentLevel,hlsUrlParameters);var url=this.getUrlWithDirectives(currentLevel.uri,hlsUrlParameters),currentLevelIndex=this.currentLevelIndex,pathwayId=currentLevel.attrs["PATHWAY-ID"],details=currentLevel.details,age=null==details?void 0:details.age;this.log("Loading level index "+currentLevelIndex+(void 0!==(null==hlsUrlParameters?void 0:hlsUrlParameters.msn)?" at sn "+hlsUrlParameters.msn+" part "+hlsUrlParameters.part:"")+(pathwayId?" Pathway "+pathwayId:"")+(age&&details.live?" age "+age.toFixed(1)+(details.type&&" "+details.type||""):"")+" "+url),this.hls.trigger(Events.LEVEL_LOADING,{url:url,level:currentLevelIndex,levelInfo:currentLevel,pathwayId:currentLevel.attrs["PATHWAY-ID"],id:0,deliveryDirectives:hlsUrlParameters||null})},_proto.removeLevel=function(levelIndex){var levels,_this$currentLevel,_this4=this;1!==this._levels.length&&(reassignFragmentLevelIndexes(levels=this._levels.filter(function(level,index){return index!==levelIndex||(_this4.steering&&_this4.steering.removeLevel(level),level===_this4.currentLevel&&(_this4.currentLevel=null,_this4.currentLevelIndex=-1,level.details)&&level.details.fragments.forEach(function(f){return f.level=-1}),!1)})),this._levels=levels,-1<this.currentLevelIndex&&null!=(_this$currentLevel=this.currentLevel)&&_this$currentLevel.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),-1<this.manualLevelIndex&&(this.manualLevelIndex=this.currentLevelIndex),_this$currentLevel=levels.length-1,this._firstLevel=Math.min(this._firstLevel,_this$currentLevel),this._startLevel&&(this._startLevel=Math.min(this._startLevel,_this$currentLevel)),this.hls.trigger(Events.LEVELS_UPDATED,{levels:levels}))},_proto.onLevelsUpdated=function(event,_ref3){_ref3=_ref3.levels;this._levels=_ref3},_proto.checkMaxAutoUpdated=function(){var _this$hls=this.hls,autoLevelCapping=_this$hls.autoLevelCapping,maxAutoLevel=_this$hls.maxAutoLevel,_this$hls=_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:_this$hls}))},_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(newLevel<0||newLevel>=levels.length){var error=new Error("invalid level idx"),fatal=newLevel<0;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 error=this.currentLevelIndex,fatal=this.currentLevel,lastPathwayId=fatal?fatal.attrs["PATHWAY-ID"]:void 0,levels=levels[newLevel],pathwayId=levels.attrs["PATHWAY-ID"];this.currentLevelIndex=newLevel,this.currentLevel=levels,error===newLevel&&fatal&&lastPathwayId===pathwayId||(this.log("Switching to level "+newLevel+" ("+(levels.height?levels.height+"p ":"")+(levels.videoRange?levels.videoRange+" ":"")+(levels.codecSet?levels.codecSet+" ":"")+"@"+levels.bitrate+")"+(pathwayId?" with Pathway "+pathwayId:"")+" from level "+error+(lastPathwayId?" with Pathway "+lastPathwayId:"")),pathwayId={level:newLevel,attrs:levels.attrs,details:levels.details,bitrate:levels.bitrate,averageBitrate:levels.averageBitrate,maxBitrate:levels.maxBitrate,realBitrate:levels.realBitrate,width:levels.width,height:levels.height,codecSet:levels.codecSet,audioCodec:levels.audioCodec,videoCodec:levels.videoCodec,audioGroups:levels.audioGroups,subtitleGroups:levels.subtitleGroups,loaded:levels.loaded,loadError:levels.loadError,fragmentError:levels.fragmentError,name:levels.name,id:levels.id,uri:levels.uri,url:levels.url,urlId:0,audioGroupIds:levels.audioGroupIds,textGroupIds:levels.textGroupIds},this.hls.trigger(Events.LEVEL_SWITCHING,pathwayId),(error=levels.details)&&!error.live)||(lastPathwayId=this.switchParams(levels.uri,null==fatal?void 0:fatal.details,error),this.loadPlaylist(lastPathwayId))}}},{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(){var configStartLevel;return void 0===this._startLevel?void 0!==(configStartLevel=this.hls.config.startLevel)?configStartLevel:this.hls.firstAutoLevel:this._startLevel},set:function(newLevel){this._startLevel=newLevel}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(pathwayPriority){var pathwaysList,filteredPathwayPriority;this.steering&&(pathwaysList=this.steering.pathways(),filteredPathwayPriority=pathwayPriority.filter(function(pathwayId){return-1!==pathwaysList.indexOf(pathwayId)}),pathwayPriority.length<1?this.warn("pathwayPriority "+pathwayPriority+" should contain at least one pathway from list: "+pathwaysList):this.steering.pathwayPriority=filteredPathwayPriority)}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(nextLevel){this.level=nextLevel,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=nextLevel)}}])}(PassThroughRemuxer);function assignTrackIdsByGroup(tracks){var groups={};tracks.forEach(function(track){var groupId=track.groupId||"";track.id=groups[groupId]=groups[groupId]||0,groups[groupId]++})}var GapController=function(_Logger){function GapController(config,media,fragmentTracker,hls){var _this=_Logger.call(this,"gap-controller",hls.logger)||this;return _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.ended=0,_this.config=config,_this.media=media,_this.fragmentTracker=fragmentTracker,_this.hls=hls,_this}_inheritsLoose(GapController,_Logger);var _proto=GapController.prototype;return _proto.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},_proto.poll=function(lastCurrentTime,activeFrag,levelDetails,state){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)lastCurrentTime&&(this.ended=0),this.moved=!0,seeking||(this.nudgeRetry=0),null!==stalled&&(this.stallReported&&(lastCurrentTime=self.performance.now()-stalled,this.warn("playback not stuck anymore @"+currentTime+", after "+Math.round(lastCurrentTime)+"ms"),this.stallReported=!1),this.stalled=null);else if(beginSeek||seeked)this.stalled=null;else if(media.paused&&!seeking||media.ended||0===media.playbackRate||!BufferHelper.getBuffered(media).length)!this.ended&&media.ended&&(this.ended=currentTime||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})),this.nudgeRetry=0;else{lastCurrentTime=BufferHelper.bufferInfo(media,currentTime,0),beginSeek=lastCurrentTime.nextStart||0;if(seeking){seeked=2<lastCurrentTime.len,activeFrag=!beginSeek||activeFrag&&activeFrag.start<=currentTime||2<beginSeek-currentTime&&!this.fragmentTracker.getPartialFragment(currentTime);if(seeked||activeFrag)return;this.moved=!1}if(!this.moved&&null!==this.stalled){if(!(0<lastCurrentTime.len)&&!beginSeek)return;seeked=Math.max(beginSeek,lastCurrentTime.start||0)-currentTime,activeFrag=!(null==levelDetails||!levelDetails.live)?2*levelDetails.targetduration:2,beginSeek=this.fragmentTracker.getPartialFragment(currentTime);if(0<seeked&&(seeked<=activeFrag||beginSeek))return void(media.paused||this._trySkipBufferHole(beginSeek))}seeked=self.performance.now();if(null===stalled)this.stalled=seeked;else{activeFrag=seeked-stalled;if(!seeking&&250<=activeFrag){if(state===State_ENDED&&(null==levelDetails||!levelDetails.live)&&Math.abs(currentTime-((null==levelDetails?void 0:levelDetails.edge)||0))<1)return activeFrag<1e3||this.ended?void 0:(this.ended=currentTime||1,void this.hls.trigger(Events.MEDIA_ENDED,{stalled:!0}));if(this._reportStall(lastCurrentTime),!this.media)return}beginSeek=BufferHelper.bufferInfo(media,currentTime,config.maxBufferHole);this._tryFixBufferStall(beginSeek,activeFrag)}}}},_proto._tryFixBufferStall=function(bufferInfo,stalledDurationMs){var config=this.config,fragmentTracker=this.fragmentTracker,media=this.media;if(null!==media){media=media.currentTime,fragmentTracker=fragmentTracker.getPartialFragment(media);if(fragmentTracker)if(this._trySkipBufferHole(fragmentTracker)||!this.media)return;(bufferInfo.len>config.maxBufferHole||bufferInfo.nextStart&&bufferInfo.nextStart-media<config.maxBufferHole)&&stalledDurationMs>1e3*config.highBufferWatchdogPeriod&&(this.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},_proto._reportStall=function(bufferInfo){var hls=this.hls,media=this.media;!this.stallReported&&media&&(this.stallReported=!0,media=new Error("Playback stalling at @"+media.currentTime+" due to low buffer ("+JSON.stringify(bufferInfo)+")"),this.warn(media.message),hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:media,buffer:bufferInfo.len}))},_proto._trySkipBufferHole=function(partial){var config=this.config,hls=this.hls,media=this.media;if(null!==media){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,bufferInfo=0<bufferInfo.len&&bufferInfo.len<1&&media.readyState<3,gapLength=startTime-currentTime;if(0<gapLength&&(bufferStarved||bufferInfo)){if(gapLength>config.maxBufferHole){var fragmentTracker=this.fragmentTracker,bufferStarved=!1;if(!(bufferStarved=0===currentTime&&(bufferInfo=fragmentTracker.getAppendedFrag(0,PlaylistLevelType_MAIN))&&startTime<bufferInfo.end?!0:bufferStarved)){gapLength=partial||fragmentTracker.getAppendedFrag(currentTime,PlaylistLevelType_MAIN);if(gapLength){for(var moreToLoad=!1,pos=gapLength.end;pos<startTime;){var provisioned=fragmentTracker.getPartialFragment(pos);if(!provisioned){moreToLoad=!0;break}pos+=provisioned.duration}if(moreToLoad)return 0}}}config=Math.max(startTime+.05,currentTime+.1);return this.warn("skipping hole, adjusting currentTime from "+currentTime+" to "+config),this.moved=!0,this.stalled=null,media.currentTime=config,partial&&!partial.gap&&(bufferInfo=new Error("fragment loaded with buffer holes, seeking from "+currentTime+" to "+config),hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:bufferInfo,reason:bufferInfo.message,frag:partial})),config}}}return 0},_proto._tryNudgeBuffer=function(){var currentTime,error,config=this.config,hls=this.hls,media=this.media,nudgeRetry=this.nudgeRetry;null!==media&&(currentTime=media.currentTime,this.nudgeRetry++,nudgeRetry<config.nudgeMaxRetry?(nudgeRetry=currentTime+(nudgeRetry+1)*config.nudgeOffset,error=new Error("Nudging 'currentTime' from "+currentTime+" to "+nudgeRetry),this.warn(error.message),media.currentTime=nudgeRetry,hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:error,fatal:!1})):(media=new Error("Playhead still not moving while enough data buffered @"+currentTime+" after "+config.nudgeMaxRetry+" nudges"),this.error(media.message),hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:media,fatal:!0})))},GapController}(Logger);function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){var sourceBuffer;return!!getMediaSource()&&(!(sourceBuffer=getSourceBuffer())||sourceBuffer.prototype&&"function"==typeof sourceBuffer.prototype.appendBuffer&&"function"==typeof sourceBuffer.prototype.remove)}var StreamController=function(_BaseStreamController){function StreamController(hls,fragmentTracker,keyLoader){var _this=_BaseStreamController.call(this,hls,fragmentTracker,keyLoader,"stream-controller",PlaylistLevelType_MAIN)||this;return _this.audioCodecSwap=!1,_this.gapController=null,_this.level=-1,_this._forceStartLoad=!1,_this._hasEnoughToStart=!1,_this.altAudio=0,_this.audioOnly=!1,_this.fragPlaying=null,_this.fragLastKbps=0,_this.couldBacktrack=!1,_this.backtrackFragment=null,_this.audioCodecSwitch=!1,_this.videoBuffer=null,_this.onMediaPlaying=function(){var gapController=_this.gapController;gapController&&(gapController.ended=0),_this.tick()},_this.onMediaSeeked=function(){var media=_this.media,media=media?media.currentTime:null,media=(isFiniteNumber(media)&&_this.log("Media seeked to "+media.toFixed(3)),_this.getMainFwdBufferInfo());null===media||0===media.len?_this.warn('Main forward buffer length on "seeked" event '+(media?media.len:"empty")+")"):_this.tick()},_this.registerListeners(),_this}_inheritsLoose(StreamController,_BaseStreamController);var _proto=StreamController.prototype;return _proto.registerListeners=function(){_BaseStreamController.prototype.registerListeners.call(this);var hls=this.hls;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.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(){_BaseStreamController.prototype.unregisterListeners.call(this);var hls=this.hls;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.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.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),_BaseStreamController.prototype.onHandlerDestroying.call(this)},_proto.startLoad=function(startPosition,skipSeekToStartPosition){var lastCurrentTime,hls,startLevel;this.levels?(lastCurrentTime=this.lastCurrentTime,hls=this.hls,this.stopLoad(),this.setInterval(100),this.level=-1,this.startFragRequested||(-1===(startLevel=hls.startLevel)&&(hls.config.testBandwidth&&1<this.levels.length?this.bitrateTest=!(startLevel=0):startLevel=hls.firstAutoLevel),hls.nextLoadLevel=startLevel,this.level=hls.loadLevel,this._hasEnoughToStart=!1),0<lastCurrentTime&&-1===startPosition&&!skipSeekToStartPosition&&(this.log("Override startPosition with lastCurrentTime @"+lastCurrentTime.toFixed(3)),startPosition=lastCurrentTime),this.state=State_IDLE,this.nextLoadPosition=this.lastCurrentTime=startPosition,this.startPosition=skipSeekToStartPosition?-1:startPosition,this.tick()):(this._forceStartLoad=!0,this.state=State_STOPPED)},_proto.stopLoad=function(){this._forceStartLoad=!1,_BaseStreamController.prototype.stopLoad.call(this)},_proto.doTick=function(){switch(this.state){case State_WAITING_LEVEL:var levels=this.levels,level=this.level,levels=null==levels?void 0:levels[level],level=null==levels?void 0:levels.details;if(!level||level.live&&(this.levelLastLoaded!==levels||this.waitForLive(levels)))this.hls.nextLoadLevel!==this.level&&(this.state=State_IDLE);else{if(this.waitForCdnTuneIn(level))break;this.state=State_IDLE}break;case State_FRAG_LOADING_WAITING_RETRY:var levels=self.performance.now(),level=this.retryDate;(!level||level<=levels||null!=(level=this.media)&&level.seeking)&&(levels=this.levels,level=this.level,levels=null==levels?void 0:levels[level],this.resetStartWhenNotLoaded(levels||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 lastDetails,frag,_this$backtrackFragme,mediaBuffer,hls=this.hls,levelLastLoaded=this.levelLastLoaded,levels=this.levels,media=this.media;null===levelLastLoaded||!(media||!this.startFragRequested&&hls.config.startFragPrefetch)||this.altAudio&&this.audioOnly||(levelLastLoaded=this.buffering?hls.nextLoadLevel:hls.loadLevel,null!=levels&&levels[levelLastLoaded]&&(media=levels[levelLastLoaded],null!==(levels=this.getMainFwdBufferInfo()))&&((lastDetails=this.getLevelDetails())&&this._streamEnded(levels,lastDetails)?(lastDetails={},2===this.altAudio&&(lastDetails.type="video"),this.hls.trigger(Events.BUFFER_EOS,lastDetails),this.state=State_ENDED):this.buffering&&(hls.loadLevel!==levelLastLoaded&&-1===hls.manualLevel&&this.log("Adapting to level "+levelLastLoaded+" from level "+this.level),this.level=hls.nextLoadLevel=levelLastLoaded,!(lastDetails=media.details)||this.state===State_WAITING_LEVEL||this.waitForLive(media)?(this.level=levelLastLoaded,this.state=State_WAITING_LEVEL,this.startFragRequested=!1):(hls=levels.len,(levelLastLoaded=this.getMaxBufferLength(media.maxBitrate))<=hls||(this.backtrackFragment&&this.backtrackFragment.start>levels.end&&(this.backtrackFragment=null),hls=this.backtrackFragment?this.backtrackFragment.start:levels.end,frag=this.getNextFragment(hls,lastDetails),this.couldBacktrack&&!this.fragPrevious&&frag&&isMediaFragment(frag)&&this.fragmentTracker.getState(frag)!==FragmentState_OK?(_this$backtrackFragme=(null!=(_this$backtrackFragme=this.backtrackFragment)?_this$backtrackFragme:frag).sn-lastDetails.startSN,(_this$backtrackFragme=lastDetails.fragments[_this$backtrackFragme-1])&&frag.cc===_this$backtrackFragme.cc&&this.fragmentTracker.removeFragment(frag=_this$backtrackFragme)):this.backtrackFragment&&levels.len&&(this.backtrackFragment=null),frag&&this.isLoopLoading(frag,hls)&&(frag.gap||(mediaBuffer=((_this$backtrackFragme=this.audioOnly&&!this.altAudio?ElementaryStreamTypes_AUDIO:ElementaryStreamTypes_VIDEO)===ElementaryStreamTypes_VIDEO?this.videoBuffer:this.mediaBuffer)||this.media)&&this.afterBufferFlushed(mediaBuffer,_this$backtrackFragme,PlaylistLevelType_MAIN),frag=this.getNextFragmentLoopLoading(frag,lastDetails,levels,PlaylistLevelType_MAIN,levelLastLoaded)),frag&&(!frag.initSegment||frag.initSegment.data||this.bitrateTest||(frag=frag.initSegment),this.loadFragment(frag,media,hls)))))))},_proto.loadFragment=function(frag,level,targetBufferTime){var fragState=this.fragmentTracker.getState(frag);fragState===FragmentState_NOT_LOADED||fragState===FragmentState_PARTIAL?isMediaFragment(frag)?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)):_BaseStreamController.prototype.loadFragment.call(this,frag,level,targetBufferTime):this._loadInitSegment(frag,level):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),fragPlayingCurrent=(fragPlayingCurrent&&1<fragPlayingCurrent.start&&this.flushMainBuffer(0,fragPlayingCurrent.start-1),this.getLevelDetails());if(null!=fragPlayingCurrent&&fragPlayingCurrent.live){var bufferInfo=this.getMainFwdBufferInfo();if(!bufferInfo||bufferInfo.len<2*fragPlayingCurrent.targetduration)return}levels=!media.paused&&levels&&(bufferInfo=levels[this.hls.nextLoadLevel],fragPlayingCurrent=this.fragLastKbps)&&this.fragCurrent?this.fragCurrent.duration*bufferInfo.maxBitrate/(1e3*fragPlayingCurrent)+1:0;bufferInfo=this.getBufferedFrag(media.currentTime+levels);bufferInfo&&(fragPlayingCurrent=this.followingBufferedFrag(bufferInfo))&&(this.abortCurrentFrag(),media=fragPlayingCurrent.maxStartPTS||fragPlayingCurrent.start,levels=fragPlayingCurrent.duration,fragPlayingCurrent=Math.max(bufferInfo.end,media+Math.min(Math.max(levels-this.config.maxFragLookUpTolerance,levels*(this.couldBacktrack?.5:.125)),levels*(this.couldBacktrack?.75:.25))),this.flushMainBuffer(fragPlayingCurrent,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,2===this.altAudio?"video":null)},_proto.onMediaAttached=function(event,data){_BaseStreamController.prototype.onMediaAttached.call(this,event,data);event=data.media;event.removeEventListener("playing",this.onMediaPlaying),event.removeEventListener("seeked",this.onMediaSeeked),event.addEventListener("playing",this.onMediaPlaying),event.addEventListener("seeked",this.onMediaSeeked),this.gapController=new GapController(this.config,event,this.fragmentTracker,this.hls)},_proto.onMediaDetaching=function(event,data){var media=this.media;media&&(media.removeEventListener("playing",this.onMediaPlaying),media.removeEventListener("seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),_BaseStreamController.prototype.onMediaDetaching.call(this,event,data),!data.transferMedia&&(this._hasEnoughToStart=!1)},_proto.triggerEnded=function(){var gapController=this.gapController;if(gapController){if(gapController.ended)return;gapController.ended=(null==(gapController=this.media)?void 0:gapController.currentTime)||1}this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})},_proto.onManifestLoading=function(){_BaseStreamController.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},_proto.onManifestParsed=function(event,data){var sourceBuffer,aac=!1,heaac=!1;data.levels.forEach(function(level){level=level.audioCodec;level&&(aac=aac||-1!==level.indexOf("mp4a.40.2"),heaac=heaac||-1!==level.indexOf("mp4a.40.5"))}),this.audioCodecSwitch=aac&&heaac&&!("function"==typeof(null==(sourceBuffer=getSourceBuffer())||null==(sourceBuffer=sourceBuffer.prototype)?void 0:sourceBuffer.changeType)),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){this.levels&&this.state===State_IDLE&&(!(data=data.levelInfo).details||data.details.live&&(this.levelLastLoaded!==data||data.details.expired)||this.waitForCdnTuneIn(data.details))&&(this.state=State_WAITING_LEVEL)},_proto.onLevelLoaded=function(event,data){var levels=this.levels,startFragRequested=this.startFragRequested,newLevelId=data.level,newDetails=data.details,duration=newDetails.totalduration;if(levels){this.log("Level "+newLevelId+" loaded ["+newDetails.startSN+","+newDetails.endSN+"]"+(newDetails.lastPartSn?"[part-"+newDetails.lastPartSn+"-"+newDetails.lastPartIndex+"]":"")+", cc ["+newDetails.startCC+", "+newDetails.endCC+"] duration:"+duration);var levels=data.levelInfo,duration=this.fragCurrent,data=(!duration||this.state!==State_FRAG_LOADING&&this.state!==State_FRAG_LOADING_WAITING_RETRY||duration.level!==data.level&&duration.loader&&this.abortCurrentFrag(),0);if(newDetails.live||null!=(duration=levels.details)&&duration.live){if(this.checkLiveUpdate(newDetails),newDetails.deltaUpdateFailed)return;data=this.alignPlaylists(newDetails,levels.details,null==(duration=this.levelLastLoaded)?void 0:duration.details)}if(levels.details=newDetails,this.levelLastLoaded=levels,startFragRequested||this.setStartPosition(newDetails,data),this.hls.trigger(Events.LEVEL_UPDATED,{details:newDetails,level:newLevelId}),this.state===State_WAITING_LEVEL){if(this.waitForCdnTuneIn(newDetails))return;this.state=State_IDLE}startFragRequested&&newDetails.live&&this.synchronizeToLiveEdge(newDetails),this.tick()}else this.warn("Levels were reset while loading level "+newLevelId)},_proto.synchronizeToLiveEdge=function(levelDetails){var liveSyncPosition,currentTime,end,start,config=this.config,media=this.media;media&&(liveSyncPosition=this.hls.liveSyncPosition,currentTime=media.currentTime,start=levelDetails.fragmentStart,end=levelDetails.edge,start=currentTime>=start-config.maxFragLookUpTolerance&&currentTime<=end,null!==liveSyncPosition)&&media.duration>liveSyncPosition&&(currentTime<liveSyncPosition||!start)&&(config=void 0!==config.liveMaxLatencyDuration?config.liveMaxLatencyDuration:config.liveMaxLatencyDurationCount*levelDetails.targetduration,!start&&media.readyState<4||currentTime<end-config)&&(this._hasEnoughToStart||(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._handleFragmentLoadProgress=function(data){var details,videoCodec,accurateTimeOffset,_frag$initSegment,transmuxer,partIndex,initPTS,frag=data.frag,part=data.part,data=data.payload,levels=this.levels;levels?(levels=levels[frag.level])?(details=levels.details)?(videoCodec=levels.videoCodec,accurateTimeOffset=details.PTSKnown||!details.live,_frag$initSegment=null==(_frag$initSegment=frag.initSegment)?void 0:_frag$initSegment.data,levels=this._getAudioCodec(levels),transmuxer=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType_MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),partIndex=part?part.index:-1,partIndex=new ChunkMetadata(frag.level,frag.sn,frag.stats.chunkCount,data.byteLength,partIndex,-1!==partIndex),initPTS=this.initPTS[frag.cc],transmuxer.push(data,_frag$initSegment,levels,videoCodec,frag,part,details.totalduration,accurateTimeOffset,partIndex,initPTS)):(this.warn("Dropping fragment "+frag.sn+" of level "+frag.level+" after level details were reset"),this.fragmentTracker.removeFragment(frag)):this.warn("Level "+frag.level+" not found on progress"):this.warn("Levels were reset while fragment load was in progress. Fragment "+frag.sn+" of level "+frag.level+" will not be buffered")},_proto.onAudioTrackSwitching=function(event,data){var fragCurrent,hls=this.hls,fromAltAudio=2===this.altAudio;useAlternateAudio(data.url,hls)?this.altAudio=1:(this.mediaBuffer!==this.media?(this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media,(fragCurrent=this.fragCurrent)&&(this.log("Switching to main audio track, cancel main fragment load"),fragCurrent.abortRequests(),this.fragmentTracker.removeFragment(fragCurrent)),this.resetTransmuxer(),this.resetLoadingState()):this.audioOnly&&this.resetTransmuxer(),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 videoBuffer,data=useAlternateAudio(data.url,this.hls);data&&(videoBuffer=this.videoBuffer)&&this.mediaBuffer!==videoBuffer&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=videoBuffer),this.altAudio=data?2:0,this.tick()},_proto.onBufferCreated=function(event,data){var type,tracks=data.tracks,alternate=!1;for(type in tracks){var name,mediaTrack,track=tracks[type];"main"===track.id?(mediaTrack=track,"video"===(name=type)&&(track=tracks[type])&&(this.videoBuffer=track.buffer)):alternate=!0}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,data=data.part,bufferedMainFragment=frag.type===PlaylistLevelType_MAIN;if(bufferedMainFragment){if(this.fragContextChanged(frag))return this.warn("Fragment "+frag.sn+(data?" p: "+data.index:"")+" of level "+frag.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===State_PARSED&&(this.state=State_IDLE));var stats=(data||frag).stats;this.fragLastKbps=Math.round(8*stats.total/(stats.buffering.end-stats.loading.first)),isMediaFragment(frag)&&(this.fragPrevious=frag),this.fragBufferedComplete(frag,data)}stats=this.media;stats&&(!this._hasEnoughToStart&&stats.buffered.length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),bufferedMainFragment)&&this.tick()},_proto.onError=function(event,data){var _data$context;if(data.fatal)this.state=State_ERROR;else 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:data.parent&&"main"===data.parent&&(data.details===ErrorDetails.BUFFER_APPEND_ERROR?this.resetLoadingState():this.reduceLengthAndFlushBuffer(data)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(data)}},_proto.checkBuffer=function(){var state,activeFrag,levelDetails,media=this.media,gapController=this.gapController;media&&gapController&&media.readyState&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(media).length||(activeFrag=(state=this.state)!==State_IDLE?this.fragCurrent:null,levelDetails=this.getLevelDetails(),gapController.poll(this.lastCurrentTime,activeFrag,levelDetails,state)),this.lastCurrentTime=media.currentTime)},_proto.onFragLoadEmergencyAborted=function(){this.state=State_IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},_proto.onBufferFlushed=function(event,_ref){var mediaBuffer,_ref=_ref.type;(_ref!==ElementaryStreamTypes_AUDIO||this.audioOnly&&!this.altAudio)&&(mediaBuffer=(_ref===ElementaryStreamTypes_VIDEO?this.videoBuffer:this.mediaBuffer)||this.media,this.afterBufferFlushed(mediaBuffer,_ref,PlaylistLevelType_MAIN),this.tick())},_proto.onLevelsUpdated=function(event,data){-1<this.level&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level)&&this.resetWhenMissingContext(this.fragCurrent),this.levels=data.levels},_proto.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},_proto.seekToStartPos=function(){var currentTime,startPosition,details,configuredTimelineOffset,delta,skipTolerance,media=this.media;media&&(currentTime=media.currentTime,0<=(startPosition=this.startPosition))&&(media.seeking?this.log("could not seek to "+startPosition+", already seeking at "+currentTime):(details=this.getLevelDetails(),(configuredTimelineOffset=this.config.timelineOffset)&&startPosition&&(startPosition+=(null==details?void 0:details.appliedTimelineOffset)||configuredTimelineOffset),delta=(configuredTimelineOffset=(configuredTimelineOffset=BufferHelper.getBuffered(media)).length?configuredTimelineOffset.start(0):0)-startPosition,skipTolerance=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance),0<delta&&(delta<skipTolerance||this.loadingParts&&delta<2*((null==details?void 0:details.partTarget)||0))&&(this.log("adjusting start position by "+delta+" to match buffer start"),this.startPosition=startPosition+=delta),currentTime<startPosition&&(this.log("seek to target start position "+startPosition+" from current time "+currentTime+" buffer start "+configuredTimelineOffset),media.currentTime=startPosition)))},_proto._getAudioCodec=function(currentLevel){currentLevel=this.config.defaultAudioCodec||currentLevel.audioCodec;return this.audioCodecSwap&&currentLevel&&(this.log("Swapping audio codec"),currentLevel=-1!==currentLevel.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),currentLevel},_proto._loadBitrateTestFrag=function(fragment,level){var _this2=this;fragment.bitrateTest=!0,this._doFragLoad(fragment,level).then(function(data){var stats,hls=_this2.hls,frag=null==data?void 0:data.frag;frag&&!_this2.fragContextChanged(frag)&&(level.fragmentError=0,_this2.state=State_IDLE,_this2.startFragRequested=!1,_this2.bitrateTest=!1,(stats=frag.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=this.playlistType,hls=this.hls,remuxResult=transmuxResult.remuxResult,transmuxResult=transmuxResult.chunkMeta,context=this.getCurrentContext(transmuxResult);if(context){var frag=context.frag,part=context.part,context=context.level,video=remuxResult.video,text=remuxResult.text,id3=remuxResult.id3,initSegment=remuxResult.initSegment,details=context.details,audio=this.altAudio?void 0:remuxResult.audio;if(this.fragContextChanged(frag))this.fragmentTracker.removeFragment(frag);else{if(this.state=State_PARSING,initSegment&&(null!=initSegment&&initSegment.tracks&&(mapFragment=frag.initSegment||frag,this._bufferInitSegment(context,initSegment.tracks,mapFragment,transmuxResult),hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:mapFragment,id:id,tracks:initSegment.tracks})),context=initSegment.initPTS,mapFragment=initSegment.timescale,isFiniteNumber(context))&&(this.initPTS[frag.cc]={baseTime:context,timescale:mapFragment},hls.trigger(Events.INIT_PTS_FOUND,{frag:frag,id:id,initPTS:context,timescale:mapFragment})),video&&details){var initSegment=details.fragments[frag.sn-1-details.startSN],context=frag.sn===details.startSN,mapFragment=!initSegment||frag.cc>initSegment.cc;if(!1!==remuxResult.independent){var initSegment=video.startPTS,remuxResult=video.endPTS,startDTS=video.startDTS,endDTS=video.endDTS;if(part)part.elementaryStreams[video.type]={startPTS:initSegment,endPTS:remuxResult,startDTS:startDTS,endDTS:endDTS};else if(video.firstKeyFrame&&video.independent&&1===transmuxResult.id&&!mapFragment&&(this.couldBacktrack=!0),video.dropped&&video.independent){var bufferInfo=this.getMainFwdBufferInfo(),bufferInfo=(bufferInfo?bufferInfo.end:this.getLoadPosition())+this.config.maxBufferHole,startTime=video.firstKeyFramePTS||initSegment;if(!context&&bufferInfo<startTime-this.config.maxBufferHole&&!mapFragment)return void this.backtrack(frag);mapFragment&&(frag.gap=!0),frag.setElementaryStreamInfo(video.type,frag.start,remuxResult,frag.start,endDTS,!0)}else context&&2<initSegment-(details.appliedTimelineOffset||0)&&(frag.gap=!0);frag.setElementaryStreamInfo(video.type,initSegment,remuxResult,startDTS,endDTS),this.backtrackFragment&&(this.backtrackFragment=frag),this.bufferFragmentData(video,frag,part,transmuxResult,context||mapFragment)}else{if(!context&&!mapFragment)return void this.backtrack(frag);frag.gap=!0}}audio&&(bufferInfo=audio.startPTS,startTime=audio.endPTS,initSegment=audio.startDTS,remuxResult=audio.endDTS,part&&(part.elementaryStreams[ElementaryStreamTypes_AUDIO]={startPTS:bufferInfo,endPTS:startTime,startDTS:initSegment,endDTS:remuxResult}),frag.setElementaryStreamInfo(ElementaryStreamTypes_AUDIO,bufferInfo,startTime,initSegment,remuxResult),this.bufferFragmentData(audio,frag,part,transmuxResult)),details&&null!=id3&&null!=(startDTS=id3.samples)&&startDTS.length&&(endDTS={id:id,frag:frag,details:details,samples:id3.samples},hls.trigger(Events.FRAG_PARSING_METADATA,endDTS)),details&&text&&(video={id:id,frag:frag,details:details,samples:text.samples},hls.trigger(Events.FRAG_PARSING_USERDATA,video))}}else this.resetWhenMissingContext(transmuxResult)},_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 audioCodec,audio=tracks.audio,video=tracks.video,audiovideo=tracks.audiovideo;if(audio&&("mp4a"===(audioCodec=pickMostCompleteCodecName(audio.codec,currentLevel.audioCodec))&&(audioCodec="mp4a.40.5"),ua=navigator.userAgent.toLowerCase(),(audioCodec=this.audioCodecSwitch&&(audioCodec=audioCodec&&(-1!==audioCodec.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),audioMetadata=audio.metadata)&&"channelCount"in audioMetadata&&1!==(audioMetadata.channelCount||1)&&-1===ua.indexOf("firefox")?"mp4a.40.5":audioCodec)&&-1!==audioCodec.indexOf("mp4a.40.5")&&-1!==ua.indexOf("android")&&"audio/mpeg"!==audio.container&&this.log("Android: force audio codec to "+(audioCodec="mp4a.40.2")),currentLevel.audioCodec&&currentLevel.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+"]"),delete tracks.audiovideo),video){video.levelCodec=currentLevel.videoCodec,video.id="main";var audioMetadata=video.codec;if(4===(null==audioMetadata?void 0:audioMetadata.length))switch(audioMetadata){case"hvc1":case"hev1":video.codec="hvc1.1.6.L120.90";break;case"av01":video.codec="av01.0.04M.08";break;case"avc1":video.codec="avc1.42e01e"}this.log("Init video buffer, container:"+video.container+", codecs[level/parsed]=["+(currentLevel.videoCodec||"")+"/"+audioMetadata+(video.codec!==audioMetadata?" parsed-corrected="+video.codec:"")+"}]"),delete tracks.audiovideo}audiovideo&&(this.log("Init audiovideo buffer, container:"+audiovideo.container+", codecs[level/parsed]=["+currentLevel.codecs+"/"+audiovideo.codec+"]"),delete tracks.video,delete tracks.audio);var ua=Object.keys(tracks);if(ua.length){if(this.hls.trigger(Events.BUFFER_CODECS,tracks),!this.hls)return;ua.forEach(function(trackName){var initSegment=tracks[trackName].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.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 currentTime,video=this.media,fragPlayingCurrent=null;video&&1<video.readyState&&!1===video.seeking&&(currentTime=video.currentTime,BufferHelper.isBuffered(video,currentTime)?fragPlayingCurrent=this.getAppendedFrag(currentTime):BufferHelper.isBuffered(video,currentTime+.1)&&(fragPlayingCurrent=this.getAppendedFrag(currentTime+.1)),fragPlayingCurrent)&&(this.backtrackFragment=null,video=this.fragPlaying,currentTime=fragPlayingCurrent.level,video&&fragPlayingCurrent.sn===video.sn&&video.level===currentTime||(this.fragPlaying=fragPlayingCurrent,this.hls.trigger(Events.FRAG_CHANGED,{frag:fragPlayingCurrent}),video&&video.level===currentTime)||this.hls.trigger(Events.LEVEL_SWITCHED,{level:currentTime}))},_createClass(StreamController,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var levels=this.levels,level=this.level,levels=null==levels?void 0:levels[level];return levels?this.getMaxBufferLength(levels.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var frag=this.nextBufferedFrag;return frag?frag.level:-1}},{key:"currentFrag",get:function(){var _this$media3;return this.fragPlaying||(_this$media3=(null==(_this$media3=this.media)?void 0:_this$media3.currentTime)||this.lastCurrentTime,isFiniteNumber(_this$media3)?this.getAppendedFrag(_this$media3):null)}},{key:"currentProgramDateTime",get:function(){var _this$media4=(null==(_this$media4=this.media)?void 0:_this$media4.currentTime)||this.lastCurrentTime;if(isFiniteNumber(_this$media4)){var details=this.getLevelDetails(),details=this.currentFrag||(details?findFragmentByPTS(null,details.fragments,_this$media4):null);if(details){var programDateTime=details.programDateTime;if(null!==programDateTime)return programDateTime=programDateTime+1e3*(_this$media4-details.start),new Date(programDateTime)}}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}}])}(_optionalSelf$navigat),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$context,uri=this.keyUriToKeyInfo[uri].loader;if(uri){if(type&&type!==(null==(_loader$context=uri.context)?void 0:_loader$context.frag.type))return;uri.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){uri=this.keyUriToKeyInfo[uri].loader;uri&&uri.destroy()}this.keyUriToKeyInfo={}},_proto.createKeyLoadError=function(frag,details,error,networkDetails,response){return void 0===details&&(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,i=0;i<encryptedFragments.length&&!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++);},_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){keySystemFormat&&frag.setKeyFormat(keySystemFormat);var decryptdata=frag.decryptdata;if(!decryptdata)return keySystemFormat=new Error(keySystemFormat?"Expected frag.decryptdata to be defined after setting format "+keySystemFormat:"Missing decryption data on fragment in onKeyLoading"),Promise.reject(this.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,keySystemFormat));keySystemFormat=decryptdata.uri;if(!keySystemFormat)return Promise.reject(this.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+keySystemFormat+'"')));var _keyInfo$mediaKeySess,keyInfo=this.keyUriToKeyInfo[keySystemFormat];if(null!=keyInfo&&keyInfo.decryptdata.key)return decryptdata.key=keyInfo.decryptdata.key,Promise.resolve({frag:frag,keyInfo:keyInfo});if(null!=keyInfo&&keyInfo.keyLoadPromise)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[keySystemFormat]={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":case"AES-256":case"AES-256-CTR":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){frag=this.emeController.loadKey(keyLoadedData);if(frag)return(keyInfo.keyLoadPromise=frag.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,keyLoader=new config.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,loadPolicy={loadPolicy:loadPolicy,timeout:loadPolicy.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};keyLoader.load(loaderContext,loadPolicy,{onSuccess:function(response,stats,context,networkDetails){var frag=context.frag,keyInfo=context.keyInfo,context=context.url;if(!frag.decryptdata||keyInfo!==_this3.keyUriToKeyInfo[context])return reject(_this3.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),networkDetails));keyInfo.decryptdata.key=frag.decryptdata.key=new Uint8Array(response.data),frag.keyLoader=null,keyInfo.loader=null,resolve({frag:frag,keyInfo:keyInfo})},onError:function(response,context,networkDetails,stats){_this3.resetLoader(context),reject(_this3.createKeyLoadError(frag,ErrorDetails.KEY_LOAD_ERROR,new Error("HTTP Error "+response.code+" loading key "+response.text),networkDetails,_objectSpread2({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,context=context.url,loader=keyInfo.loader;frag.keyLoader===loader&&(frag.keyLoader=null,keyInfo.loader=null),delete this.keyUriToKeyInfo[context],loader&&loader.destroy()},KeyLoader}();function mapContextToLevelType(context){switch(context.type){case PlaylistContextType_AUDIO_TRACK:return PlaylistLevelType_AUDIO;case PlaylistContextType_SUBTITLE_TRACK:return PlaylistLevelType_SUBTITLE;default:return PlaylistLevelType_MAIN}}function getResponseUrl(response,context){response=response.url;return response=void 0!==response&&0!==response.indexOf("data:")?response:context.url}var PlaylistLoader=function(){function PlaylistLoader(hls){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=hls,this.registerListeners()}var _proto=PlaylistLoader.prototype;return _proto.startLoad=function(startPosition){},_proto.stopLoad=function(){this.destroyInternalLoaders()},_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),hls.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,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),hls.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)},_proto.createInternalLoader=function(context){var config=this.hls.config,PLoader=config.pLoader,Loader=config.loader,PLoader=new(PLoader||Loader)(config);return this.loaders[context.type]=PLoader},_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){data=data.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType_MANIFEST,url:data,deliveryDirectives:null,levelOrTrack:null})},_proto.onLevelLoading=function(event,data){var id=data.id,level=data.level,pathwayId=data.pathwayId,url=data.url,deliveryDirectives=data.deliveryDirectives,data=data.levelInfo;this.load({id:id,level:level,pathwayId:pathwayId,responseType:"text",type:PlaylistContextType_LEVEL,url:url,deliveryDirectives:deliveryDirectives,levelOrTrack:data})},_proto.onAudioTrackLoading=function(event,data){var id=data.id,groupId=data.groupId,url=data.url,deliveryDirectives=data.deliveryDirectives,data=data.track;this.load({id:id,groupId:groupId,level:null,responseType:"text",type:PlaylistContextType_AUDIO_TRACK,url:url,deliveryDirectives:deliveryDirectives,levelOrTrack:data})},_proto.onSubtitleTrackLoading=function(event,data){var id=data.id,groupId=data.groupId,url=data.url,deliveryDirectives=data.deliveryDirectives,data=data.track;this.load({id:id,groupId:groupId,level:null,responseType:"text",type:PlaylistContextType_SUBTITLE_TRACK,url:url,deliveryDirectives:deliveryDirectives,levelOrTrack:data})},_proto.onLevelsUpdated=function(event,data){var context,loader=this.loaders[PlaylistContextType_LEVEL];loader&&(context=loader.context)&&!data.levels.some(function(lvl){return lvl===context.levelOrTrack})&&(loader.abort(),delete this.loaders[PlaylistContextType_LEVEL])},_proto.load=function(context){var levelDetails,_this=this,config=this.hls.config,loader=this.getInternalLoader(context);if(loader){var logger=this.hls.logger,loaderContext=loader.context;if(loaderContext&&loaderContext.levelOrTrack===context.levelOrTrack&&(loaderContext.url===context.url||loaderContext.deliveryDirectives&&!context.deliveryDirectives))return void(loaderContext.url===context.url?logger.log("[playlist-loader]: ignore "+context.url+" ongoing request"):logger.log("[playlist-loader]: ignore "+context.url+" in favor of "+loaderContext.url));logger.log("[playlist-loader]: aborting previous loader for type: "+context.type),loader.abort()}loaderContext=context.type===PlaylistContextType_MANIFEST?config.manifestLoadPolicy.default:_extends({},config.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),loader=this.createInternalLoader(context),isFiniteNumber(null==(logger=context.deliveryDirectives)?void 0:logger.part)&&(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)&&(config=levelDetails.partTarget,logger=levelDetails.targetduration,config)&&logger&&(levelDetails=1e3*Math.max(3*config,.8*logger),loaderContext=_extends({},loaderContext,{maxTimeToFirstByteMs:Math.min(levelDetails,loaderContext.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(levelDetails,loaderContext.maxTimeToFirstByteMs)}));config=loaderContext.errorRetry||loaderContext.timeoutRetry||{},logger={loadPolicy:loaderContext,timeout:loaderContext.maxLoadTimeMs,maxRetry:config.maxNumRetry||0,retryDelay:config.retryDelayMs||0,maxRetryDelay:config.maxRetryDelayMs||0};loader.load(context,logger,{onSuccess:function(response,stats,context,networkDetails){var loader=_this.getInternalLoader(context),string=(_this.resetInternalLoader(context.type),response.data);0!==string.indexOf("#EXTM3U")?_this.handleManifestParsingError(response,context,new Error("no EXTM3U delimiter"),networkDetails||null,stats):(stats.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(string)||context.type!==PlaylistContextType_MANIFEST?_this.handleTrackOrLevelPlaylist(response,stats,context,networkDetails||null,loader):_this.handleMasterPlaylist(response,stats,context,networkDetails))},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.checkAutostartLoad=function(){var autoStartLoad,_this$hls$config,_this$hls;this.hls&&(autoStartLoad=(_this$hls$config=(_this$hls=this.hls).config).autoStartLoad,_this$hls$config=_this$hls$config.startPosition,_this$hls=_this$hls.forceStartLoad,autoStartLoad||_this$hls)&&(this.hls.logger.log((autoStartLoad?"auto":"force")+" startLoad with configured startPosition "+_this$hls$config),this.hls.startLoad(_this$hls$config))},_proto.handleMasterPlaylist=function(response,stats,context,networkDetails){var sessionData,sessionKeys,startTimeOffset,variableList,subtitles,hls=this.hls,string=response.data,url=getResponseUrl(response,context),parsedResult=M3U8Parser.parseMasterPlaylist(string,url);parsedResult.playlistParsingError?this.handleManifestParsingError(response,context,parsedResult.playlistParsingError,networkDetails,stats):(response=parsedResult.contentSteering,context=parsedResult.levels,sessionData=parsedResult.sessionData,sessionKeys=parsedResult.sessionKeys,startTimeOffset=parsedResult.startTimeOffset,variableList=parsedResult.variableList,this.variableList=variableList,parsedResult=(string=M3U8Parser.parseMasterPlaylistMedia(string,url,parsedResult)).AUDIO,subtitles=string.SUBTITLES,string=string["CLOSED-CAPTIONS"],(parsedResult=void 0===parsedResult?[]:parsedResult).length&&!parsedResult.some(function(audioTrack){return!audioTrack.url})&&context[0].audioCodec&&!context[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),parsedResult.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:context,audioTracks:parsedResult,subtitles:subtitles,captions:string,contentSteering:response,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),level=isFiniteNumber(level)?level:isFiniteNumber(id)?id:0,id=mapContextToLevelType(context),level=M3U8Parser.parseLevelPlaylist(response.data,url,level,id,0,this.variableList);type===PlaylistContextType_MANIFEST&&(id={attrs:new AttrList({}),bitrate:0,details:level,name:"",url:url},level.requestScheduled=stats.loading.start+computeReloadInterval(level,0),hls.trigger(Events.MANIFEST_LOADED,{levels:[id],audioTracks:[],url:url,stats:stats,networkDetails:networkDetails,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})),stats.parsing.end=performance.now(),context.levelDetails=level,this.handlePlaylistLoaded(level,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){var message="A network "+((timeout=void 0===timeout?!1:timeout)?"timeout":"error"+(response?" (status "+response.code+")":""))+" occurred while loading "+context.type,error=(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+'"'),new Error(message)),details=(this.hls.logger.warn("[playlist-loader]: "+message),ErrorDetails.UNKNOWN),fatal=!1,message=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}message&&this.resetInternalLoader(context.type);message={type:ErrorTypes.NETWORK_ERROR,details:details,fatal:fatal,url:context.url,loader:message,context:context,error:error,networkDetails:networkDetails,stats:stats};response&&(error=(null==networkDetails?void 0:networkDetails.url)||context.url,message.response=_objectSpread2({url:error,data:void 0},response)),this.hls.trigger(Events.ERROR,message)},_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){levelDetails.targetduration||(levelDetails.playlistParsingError=new Error("Missing Target Duration"));var level=levelDetails.playlistParsingError;if(level)hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:url,error:level,reason:level.message,response:response,context:context,level:levelIndex,parent:parent,networkDetails:networkDetails,stats:stats});else switch(levelDetails.live&&loader&&(loader.getCacheAge&&(levelDetails.ageHeader=loader.getCacheAge()||0),loader.getCacheAge&&!isNaN(levelDetails.ageHeader)||(levelDetails.ageHeader=0)),type){case PlaylistContextType_MANIFEST:case PlaylistContextType_LEVEL:hls.trigger(Events.LEVEL_LOADED,{details:levelDetails,levelInfo:context.levelOrTrack||hls.levels[0],level:levelIndex||0,id:id||0,stats:stats,networkDetails:networkDetails,deliveryDirectives:deliveryDirectives,withoutMultiVariant:type===PlaylistContextType_MANIFEST});break;case PlaylistContextType_AUDIO_TRACK:hls.trigger(Events.AUDIO_TRACK_LOADED,{details:levelDetails,track:context.levelOrTrack,id:id||0,groupId:groupId||"",stats:stats,networkDetails:networkDetails,deliveryDirectives:deliveryDirectives});break;case PlaylistContextType_SUBTITLE_TRACK:hls.trigger(Events.SUBTITLE_TRACK_LOADED,{details:levelDetails,track:context.levelOrTrack,id:id||0,groupId:groupId||"",stats:stats,networkDetails:networkDetails,deliveryDirectives:deliveryDirectives})}}else level=levelDetails.playlistParsingError=new Error("No Segments found in Playlist"),hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:url,error:level,reason:level.message,response:response,context:context,level:levelIndex,parent:parent,networkDetails:networkDetails,stats:stats})},PlaylistLoader}(),eventemitter3=function(){function Hls(userConfig){void 0===userConfig&&(userConfig={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,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.interstitialsController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var logger=this.logger=enableLogs(userConfig.debug||!1,"Hls instance",userConfig.assetPlayerId),config=this.config=function(defaultConfig,userConfig,logger){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;switch(userConfig[policyName]={default:settings},setting){case"TimeOut":settings.maxLoadTimeMs=value,settings.maxTimeToFirstByteMs=value;break;case"MaxRetry":settings.errorRetry.maxNumRetry=value,settings.timeoutRetry.maxNumRetry=value;break;case"RetryDelay":settings.errorRetry.retryDelayMs=value,settings.timeoutRetry.retryDelayMs=value;break;case"MaxRetryTimeout":settings.errorRetry.maxRetryDelayMs=value,settings.timeoutRetry.maxRetryDelayMs=value}}}),report.length&&logger.warn('hls.js config: "'+report.join('", "')+'" setting(s) are deprecated, use "'+policyName+'": '+JSON.stringify(userConfig[policyName]))}),_objectSpread2(_objectSpread2({},defaultsCopy),userConfig)}(Hls.DefaultConfig,userConfig,logger),userConfig=(this.userConfig=userConfig,config.progressive&&enableStreamingMode(config,logger),config.abrController),logger=config.bufferController,_CapLevelController=config.capLevelController,_ErrorController=config.errorController,_FpsController=config.fpsController,_ErrorController=new _ErrorController(this),userConfig=this.abrController=new userConfig(this),fragmentTracker=new FragmentTracker(this),_InterstitialsController=config.interstitialsController,_InterstitialsController=_InterstitialsController?this.interstitialsController=new _InterstitialsController(this,Hls):null,logger=this.bufferController=new logger(this,fragmentTracker),_CapLevelController=this.capLevelController=new _CapLevelController(this),_FpsController=new _FpsController(this),playListLoader=new PlaylistLoader(this),_ContentSteeringController=config.contentSteeringController,_ContentSteeringController=_ContentSteeringController?new _ContentSteeringController(this):null,levelController=this.levelController=new LevelController(this,_ContentSteeringController),id3TrackController=new ID3TrackController(this),keyLoader=new KeyLoader(this.config),streamController=this.streamController=new StreamController(this,fragmentTracker,keyLoader),levelController=(_CapLevelController.setStreamController(streamController),_FpsController.setStreamController(streamController),[playListLoader,levelController,streamController]),streamController=(_InterstitialsController&&levelController.splice(1,0,_InterstitialsController),_ContentSteeringController&&levelController.splice(1,0,_ContentSteeringController),this.networkControllers=levelController,[userConfig,logger,_CapLevelController,_FpsController,id3TrackController,fragmentTracker]),_InterstitialsController=(this.audioTrackController=this.createController(config.audioTrackController,levelController),config.audioStreamController),_ContentSteeringController=(_InterstitialsController&&levelController.push(new _InterstitialsController(this,fragmentTracker,keyLoader)),this.subtitleTrackController=this.createController(config.subtitleTrackController,levelController),config.subtitleStreamController),userConfig=(_ContentSteeringController&&levelController.push(new _ContentSteeringController(this,fragmentTracker,keyLoader)),this.createController(config.timelineController,streamController),keyLoader.emeController=this.emeController=this.createController(config.emeController,streamController),this.cmcdController=this.createController(config.cmcdController,streamController),this.latencyController=this.createController(LatencyController,streamController),this.coreComponents=streamController,levelController.push(_ErrorController),_ErrorController.onErrorOut);"function"==typeof userConfig&&this.on(Events.ERROR,userConfig,_ErrorController),this.on(Events.MANIFEST_LOADED,playListLoader.onManifestLoaded,playListLoader)}Hls.isMSESupported=isMSESupported,Hls.isSupported=function(){return!!isMSESupported()&&"function"==typeof(null==(mediaSource=getMediaSource())?void 0:mediaSource.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(function(codecsForVideoContainer){return mediaSource.isTypeSupported("video/mp4;codecs="+codecsForVideoContainer)})||["mp4a.40.2","fLaC"].some(function(codecForAudioContainer){return mediaSource.isTypeSupported("audio/mp4;codecs="+codecForAudioContainer)}));var mediaSource},Hls.getMediaSource=function(){return getMediaSource()};var _proto=Hls.prototype;return _proto.createController=function(ControllerClass,components){return ControllerClass?(ControllerClass=new ControllerClass(this),components&&components.push(ControllerClass),ControllerClass):null},_proto.on=function(event,listener,context){this._emitter.on(event,listener,context=void 0===context?this:context)},_proto.once=function(event,listener,context){this._emitter.once(event,listener,context=void 0===context?this:context)},_proto.removeAllListeners=function(event){this._emitter.removeAllListeners(event)},_proto.off=function(event,listener,context,once){this._emitter.off(event,listener,context=void 0===context?this: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){this.logger.error("An internal error happened while handling event "+event+'. Error message: "'+error.message+'". Here is a stacktrace:',error),this.triggeringException||(this.triggeringException=!0,eventObject=event===Events.ERROR,this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:eventObject,event:event,error:error}),this.triggeringException=!1)}return!1},_proto.listenerCount=function(event){return this._emitter.listenerCount(event)},_proto.destroy=function(){this.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(data){var media,error;!data||"media"in data&&!data.media?(error=new Error("attachMedia failed: invalid argument ("+data+")"),this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.ATTACH_MEDIA_ERROR,fatal:!0,error:error})):(this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia()),media=(error="media"in data)?data.media:data,error=error?data:{media:media},this._media=media,this.trigger(Events.MEDIA_ATTACHING,error))},_proto.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(Events.MEDIA_DETACHING,{}),this._media=null},_proto.transferMedia=function(){this._media=null;var transferMedia=this.bufferController.transferMedia();return this.trigger(Events.MEDIA_DETACHING,{transferMedia:transferMedia}),transferMedia},_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,this.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,skipSeekToStartPosition){this.logger.log("startLoad("+(startPosition=void 0===startPosition?-1:startPosition)+(skipSeekToStartPosition?", <skip seek to start>":"")+")"),this.started=!0,this.resumeBuffering();for(var i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(startPosition,skipSeekToStartPosition),this.started&&this.networkControllers);i++);},_proto.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var i=0;i<this.networkControllers.length&&(this.networkControllers[i].stopLoad(),!this.started&&this.networkControllers);i++);},_proto.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(function(controller){controller.resumeBuffering&&controller.resumeBuffering()}))},_proto.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(function(controller){controller.pauseBuffering&&controller.pauseBuffering()}))},_proto.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},_proto.recoverMediaError=function(){this.logger.log("recoverMediaError");var media=this._media,time=null==media?void 0:media.currentTime;this.detachMedia(),media&&(this.attachMedia(media),time)&&this.startLoad(time)},_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))||null},_proto.setSubtitleOption=function(subtitleOption){var _this$subtitleTrackCo;return(null==(_this$subtitleTrackCo=this.subtitleTrackController)?void 0:_this$subtitleTrackCo.setSubtitleOption(subtitleOption))||null},_proto.getMediaDecodingInfo=function(level,audioTracks){return getMediaDecodingInfoPromise(level,getAudioTracksByGroup(audioTracks=void 0===audioTracks?this.allAudioTracks:audioTracks),navigator.mediaCapabilities)},_createClass(Hls,[{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"sessionId",get:function(){return this._sessionId||(this._sessionId=function(){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();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(dt+16*Math.random())%16|0;return dt=Math.floor(dt/16),("x"==c?r:3&r|8).toString(16)})}}}())}},{key:"levels",get:function(){var levels=this.levelController.levels;return levels||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(newLevel){this.logger.log("set currentLevel:"+newLevel),this.levelController.manualLevel=newLevel,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(newLevel){this.logger.log("set nextLevel:"+newLevel),this.levelController.manualLevel=newLevel,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(newLevel){this.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){this.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){this.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){shouldStartCapping=!!shouldStartCapping;shouldStartCapping!==this.config.capLevelToPlayerSize&&(shouldStartCapping?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=shouldStartCapping)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(newLevel){this._autoLevelCapping!==newLevel&&(this.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:"abrEwmaDefaultEstimate",get:function(){var bwEstimator=this.abrController.bwEstimator;return bwEstimator?bwEstimator.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var bwEstimator=this.abrController.bwEstimator;return bwEstimator?bwEstimator.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(value){!function(value){return-1<HdcpLevels.indexOf(value)}(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)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,autoLevelCapping=-1===autoLevelCapping&&null!=levels&&levels.length?levels.length-1:autoLevelCapping;if(maxHdcpLevel)for(var i=autoLevelCapping;i--;){var hdcpLevel=levels[i].attrs["HDCP-LEVEL"];if(hdcpLevel&&hdcpLevel<=maxHdcpLevel)return i}return autoLevelCapping}},{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:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{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},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},set:function(latency){this.latencyController.targetLatency=latency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(pathwayPriority){this.levelController.pathwayPriority=pathwayPriority}},{key:"bufferedToEnd",get:function(){var _this$bufferControlle;return!(null==(_this$bufferControlle=this.bufferController)||!_this$bufferControlle.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var _this$interstitialsCo;return(null==(_this$interstitialsCo=this.interstitialsController)?void 0:_this$interstitialsCo.interstitialsManager)||null}}],[{key:"version",get:function(){return version}},{key:"Events",get:function(){return Events}},{key:"MetadataSchema",get:function(){return MetadataSchema}},{key:"ErrorTypes",get:function(){return ErrorTypes}},{key:"ErrorDetails",get:function(){return ErrorDetails}},{key:"DefaultConfig",get:function(){return Hls.defaultConfig||hlsDefaultConfig},set:function(defaultConfig){Hls.defaultConfig=defaultConfig}}])}();eventemitter3.defaultConfig=void 0,_exports.default=eventemitter3});

Anon7 - 2021