define(["exports"],function(_exports){function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e=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=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;icurrentBw)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=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;imedia&&_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&&0Math.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)),-1levelInfo.frameRate||!upSwitch&&0"+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-1Math.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(0pdtBufferEnd}(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.levelbufferEnd?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.cccc?-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=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;istart&&(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>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>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>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>>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>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)&&(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>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>>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=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;ibuf2end&&(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;_iNumber.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;iNumber.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||0lastIndex)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;iprogramDateTimes.length)for(var i=(programDateTimes[index+1]||fragments[fragments.length-1]).sn-details.startSN;startIndexfragFrom.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||fragStartPtsdetails.endSN)return 0;var fragEndPts=fragStartPts-details.startSN,fragments=details.fragments;for(fragments[fragEndPts]=frag,i=fragEndPts;0refDetails.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.startCCmediaBuffer.end)&&(_this2=_this2config.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 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(-1now.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=-1fragDuration&&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(fragLentargetBufferTime},_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;ipartList.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=bufferEndend.sn||!levelDetails.live&&!loadingParts)&&fragPrevious&&end.level===fragPrevious.level&&(config=fragments[1+bufferEnd],end=end.sn"+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 "+(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"+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>>5}function isHeader$1(data,offset){return offset+1>2&15;if(!(12>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>6&1&&(offset+=HEADER_FOOTER_SIZE),(offset+=HEADER_FOOTER_SIZE)+size);offset+FRAME_SIZEdata.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>>24+shift<>shift,bsid=bsid?bsid<=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+5data.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=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=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);icount||(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>>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>>1},_proto.ebsp2rbsp=function(arr){for(var dst=new Uint8Array(arr.byteLength),dstIdx=0,i=0;i>_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>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(;offsetstream.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>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>24&255,timescale>>16&255,timescale>>8&255,255×cale,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×cale,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>>8&255),sps.push(255&len),sps=sps.concat(Array.prototype.slice.call(data));for(i=0;i>>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>>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>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=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;_ifirstPTS&&isPTSOrderRetained);_i++){var nextSamplePTS,prevPTS=inputSamples[_i].pts;inputSamples[_i].dts-=delta,inputSamples[_i].pts-=delta,_isinf>>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=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.cccc||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),0start||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&&targetBufferTimestart.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)&¤tLevel.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;iprevious.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&&03*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=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":"\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 "+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)=_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_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=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=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||999999999999999bitrate&&(bitrate=_step.bitrate)}return 0 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 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}),0hls.config.fpsDroppedMonitoringThreshold*currentDecoded&&(currentPeriod=hls.currentLevel,hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+currentPeriod),0=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":interstitial.cue.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=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;itimeRange.start&&timelinePos=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_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"+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):"",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=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&&(scheduledItemdetails.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.bufferedPosbufferEnd||(1===items.length&&this.itemsMatch(items[0],bufferingItem)?this.bufferedPos=bufferEnd:(playingItem=this.playingItem,playingIndex=this.findItemIndex(playingItem),schedule=schedule.findItemIndexAtTime(bufferEnd),this.bufferedPos=bufferingItem.end&&(schedule=items),1items.edge-items.targetduration&&nextItemToBuffer.start "+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")+" 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=asset.startOffset&&eventTime=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=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>>=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&&0cues[len].endTime)return-1;var left=0,right=len;for(;left<=right;){var mid=Math.floor((right+left)/2);if(timecues[mid].startTime&&left=start&&cue.endTime<=end)cuesFound.push(cue);else if(cue.startTime>end)return cuesFound}return cuesFound}(track.cues,start,end),i=0;i=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=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 ("+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/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);posstartTime)&&(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,.5frag.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=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&¤tLoader!==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;idateRange.startDate&&(!candidateDateRange||dateRange.startDate(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=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=2config.maxBufferHole||bufferInfo.nextStart&&bufferInfo.nextStart-media1e3*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=currentTimeconfig.maxBufferHole){var fragmentTracker=this.fragmentTracker,bufferStarved=!1;if(!(bufferStarved=0===currentTime&&(bufferInfo=fragmentTracker.getAppendedFrag(0,PlaylistLevelType_MAIN))&&startTimelevels.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=start-config.maxFragLookUpTolerance&¤tTime<=end,null!==liveSyncPosition)&&media.duration>liveSyncPosition&&(currentTimeinitSegment.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":"")+")"),this.started=!0,this.resumeBuffering();for(var i=0;i=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});