0&&(e.$video.volume=e._options.volume)}),1e3)})),e.event.emit("parsed")}))}))}else if(this.$video.canPlayType("application/vnd.apple.mpegurl")){this.logger.log("Browser support application/vnd.apple.mpegurl : ",this.$video.canPlayType("application/vnd.apple.mpegurl")),this.$video.src=this._options.url;var n=!1;this.$video.addEventListener("canplay",(function(){!n&&e._options.autoPlay&&setTimeout((function(){e.$video.play().then((function(){e.logger.log("autoPlay video!"),setTimeout((function(){e._options.volume>0&&e.setVolume(e._options.volume)}),1e3),n=!0}))}),200)}))}else this.logger.warn("Browser not support hls")},n.isPlayingState=function(){return!this.$video.paused},n.play=function(){if(this.isPlayingState())return Promise.resolve();if(this._options.isLive&&(this.$video.buffered.length>=1&&this.$video.buffered.end(0)>1)){var e=this.$video.buffered.end(0)-1;this.$video.currentTime=e}return this.$video.play()},n.pause=function(){this.$video.pause()},n.setVolume=function(e){this.$video.muted&&(this.$video.muted=!1),this._volume=+(e||0),0===this._volume&&(this.$video.muted=!0),this.$video.volume=this._volume},n.destroy=function(){this.$video&&this.$video.pause(),this._hls&&(this._hls.destroy(),this._hls=null),e.prototype.destroy.call(this)},n._onEvent=function(){var e;(e=this).$video&&(e.$video.addEventListener("canplay",(function(){e.event.emit("canplay")})),e.$video.addEventListener("loadeddata",(function(){e.event.emit("loadeddata")})),e.$video.addEventListener("volumechange",(function(){e.event.emit("volumechange",{data:e.$video.volume})})),e.$video.addEventListener("waiting",(function(){e.event.emit("waiting")})),e.$video.addEventListener("timeupdate",(function(){var t;null==(t=e.event)||t.emit("timeupdate")})),e.$video.addEventListener("seeking",(function(){e.event.emit("seeking",{data:e.$video.currentTime})})),e.$video.addEventListener("seeked",(function(){e.event.emit("seeked")})),e.$video.addEventListener("abort",(function(){e.event.emit("abort")})),e.$video.addEventListener("error",(function(){var t;null==(t=e.event)||t.emit("error",{data:e.$video.error})})),e.$video.addEventListener("ended",(function(){e.event.emit("ended")})))},_e(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(te);var Ce="wasm_loaded",xe="wasm_failed",Se="init";function Le(e,t){return Le=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Le(e,t)}var be=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=n.addVc(null==t?void 0:t.url,["h264","h265"]),function(e,t){if(((null==t?void 0:t.volume)||0)>1?e._volume=1:((null==t?void 0:t.volume)||0)<=0?e._volume=0:e._volume=+((null==t?void 0:t.volume)||0),t.volume=e._volume,e.options=r.merge({},Z,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=s(e.options.loggerOptions),e.event=new o,e.logger.log("HlsPlayer version: ",ke.version),e.logger.log("HlsPlayer options: ",e.options),e.options.logger=e.logger}(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),t),i._containerClassName=K+"-container",i._render(),i}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Le(e,t)}(t,e);var i=t.prototype;return i._render=function(){this.$container.classList.add(this._containerClassName)},i.destroy=function(){this.$container&&(this.$container.classList.remove(this._containerClassName),this.$container.innerHTML="",this.$container=null)},t}(e);function Re(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e=!0),this.playParam={durationMs:0,fps:0,sampleRate:0,size:{width:0,height:0},audioNone:e,videoCodec:L},!M())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(pe.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===L){var e={seekPos:0,isLive:this.options.isLive,accurateSeek:!0,seekEvent:!1,realPlay:!0};return this.player.play(e)}return this.player.play()},i.pause=function(){return pe.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return pe.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===L&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage($(X)),this._decoderWorker.terminate(),this._decoderWorker=null),this.logger.log("destroy"),null==(i=this.event)||null==(t=i.emit)||t.call(i,"destroy"),this.player=null,e.prototype.destroy.call(this),!0)},i.isPlaying=function(){return null!==this.player&&this.player.isPlayingState()},i.setVolume=function(e){var t;(e=+e)>1||e<0?this.logger.warn("volume volume value 0.0 ~ 1.0!"):((t=this).player||(t.event.emit("playerIsNull"),t.logger.warn("Player instance does not exist!"),0))&&(this.player.setVolume(e),this.event.emit("volumeChange",{data:e}))},i.getVersion=function(){return pe.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new ye({logger:this.logger,decoderWorker:this._decoderWorker,event:this.event}),this._m3u8Obj.bindReady(this),this._m3u8Obj.onFinished=function(e,t){},this._m3u8Obj.onCacheProcess=function(t){e.options.isLive||null==e.onCacheProcess||e.onCacheProcess.call(e,t)},this._m3u8Obj.onDemuxed=this._checkPlayer.bind(this),this._m3u8Obj.onSamples=this._hlsOnSamples.bind(this),this._m3u8Obj.demux(this.url)},i._checkPlayer=function(e,t){var i=this;if(null==i.player){var n,s,r;if(!(null==i||null==(n=i._m3u8Obj)?void 0:n.isHevcParam)||t)return null==i||null==(r=i._m3u8Obj)||null==(s=r.destroy)||s.call(r),i._m3u8Obj=null,this._decoderWorker.terminate(),this._decoderWorker=null,void(i.player=new we(De({},this.options,{event:this.event,logger:this.logger})));var o=i._m3u8Obj.getACodec(),a=i._m3u8Obj.getFPS(),l=i._m3u8Obj.getSampleRate(),u=i._m3u8Obj.getSize(),h=!1;h=i._m3u8Obj.getSampleChannel()<=0||""===o,i._softPlayer(0,a,l,u,h)}},i._hlsOnSamples=function(e,t){var i,n,s,r=this;if(t.video)null==(s=r.player)||null==(n=s.appendHevcFrame)||n.call(s,t);else if(!(null==(i=r._m3u8Obj)?void 0:i.audioNone)){var o,a;null==(a=r.player)||null==(o=a.appendAACFrame)||o.call(a,t)}},i._onWorkerMessage=function(){var e=this,i=this;this._decoderWorker.onmessage=function(n){var s=n.data;switch(s.cmd){case W:t.__HLS_WASM_DecoderState__=0;break;case V:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(Ce),i._decoderWorker.postMessage($("registerWasmPlayer")),i._m3u8Entry();break;case j:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(xe,s),pe.send("wasm",{name:"wasm loading failed"}),i._checkPlayer(!0)}}},i._softPlayer=function(e,t,i,n,s,r){var o,a,l=this;void 0===s&&(s=!1),void 0===r&&(r=null);var u,h=this;(this.playParam.durationMs=e,this.playParam.fps=t,this.playParam.sampleRate=i,this.playParam.size=n,this.playParam.audioNone=s,this.playParam.videoCodec=r||L,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new re(De({},h.options,{sampleRate:i,fps:t,appendHevcType:v,fixed:!1,id:this.options.id,audioNone:s,videoCodec:r,logger:this.logger,event:this.event,decoderWorker:this._decoderWorker})),this.player.onPlayingTime=function(e){var t;null==h||null==(t=h.onPlayTime)||t.call(h,e)},this.player.onPlayingFinish=function(){var e,t;(l.pause(),null!=l.onPlayFinish)&&(null==(t=l)||null==(e=t.onPlayFinish)||e.call(t))},this.player.onLoadCache=function(){var e,t;null==(t=l)||null==(e=t.onLoadCache)||e.call(t)},this.player.onLoadCacheFinished=function(){var e,t;null==(t=l)||null==(e=t.onLoadCacheFinished)||e.call(t)},null==(o=h.player)||o.setDurationMs(e),null==(a=h.player)||a.setFrameRate(t),null!=h.onReadyShowDone)&&(null==h||null==(u=h.onReadyShowDone)||u.call(h));this.event.emit("parsed"),this.player&&this.options.autoPlay&&this.play()},t.supportType=function(e){if(pe.send(1,{name:"supportType",options:e}),"hls"===e.type)return!0;if(e.url){var t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.m3u8$/i.test(new URL(t).pathname)}catch(e){}}return!1},Re(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(be);ke.__HLS_WASM_DecoderState__=0,ke.version="0.1.0",module.exports=ke;
diff --git a/dist/index.umd.js b/dist/index.umd.js
new file mode 100644
index 0000000..b67e92b
--- /dev/null
+++ b/dist/index.umd.js
@@ -0,0 +1,60 @@
+/*
+*
+* HlsPlayer.js v0.1.0
+* Copyright (c) 2024-8-1 Ezviz-OpenBiz
+* .
+*
+*/
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).HlsPlayer=t()}(this,(function(){"use strict";var e=1,t=2,i=3,r="aac",s="h265",n="hevc",a="m3u8",o="hls",l=0,h=1,c=600,d=400,u=30,f=40,g=!1,m=44100,p=20,v="ONCE",y="SWAP",T=0,E=265,S=1001,b=1002,L=1003;var w,A=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function R(){return(new Date).getTime()}var k=window.AudioContext||(null==(w=window)?void 0:w.webkitAudioContext),_=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||m,appendType:e.appendType||l,playMode:e.playMode||y,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new k({latencyHint:"interactive",sampleRate:e.sampleRate}),this.gainNode=null,this.sourceList=[],this.startStatus=!1,this.sampleQueue=[],this.nextBuffer=null,this.playTimestamp=0,this.playStartTime=0,this.durationMs=-1,this.volume=e.volume||0,this.onLoadCache=null,this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList[0].onended=function(){t.swapSource(0,1)},this.sourceList[1].onended=function(){t.swapSource(1,0)},this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.audioCtx.destination),this.runNextBuffer()}var t=e.prototype;return t.resetStartParam=function(){this.playTimestamp=0,this.playStartTime=0},t.setOnLoadCache=function(e){this.onLoadCache=e},t.setDurationMs=function(e){void 0===e&&(e=-1),this.durationMs=e},t.setVolume=function(e){void 0===e&&(e=0),this.volume=e,this.gainNode.gain.value=e},t.getAlignVPTS=function(){return this.playTimestamp+(R()-this.playStartTime)/1e3},t.swapSource=function(e,t){if(void 0===e&&(e=-1),void 0===t&&(t=-1),!this.startStatus)return null;if(e<0||e>=this.sourceList.length)return null;if(t<0||t>=this.sourceList.length)return null;try{this.sourceChannel===e&&null!==this.sourceList[e]&&(this.sourceList[e].disconnect(this.gainNode),this.sourceList[e]=null)}catch(t){this.logger.error("[DEFINE ERROR] this audioCore disconnect source Index:"+e+" error happened!",t)}(this.sourceChannel=t,-2===this.decodeSample(t,e)&&this.options.isLive)&&(this.getAlignVPTS()>=this.durationMs/1e3-.04?this.pause():null==this||this.onLoadCache());return null},t.addSample=function(e){return void 0===e&&(e=null),!(null==e||!e||void 0===e)&&(0===this.sampleQueue.length&&(this.seekPos=null==e?void 0:e.pts),this.sampleQueue.push(e),!0)},t.runNextBuffer=function(){var e=this;window.setInterval((function(){if(!(null!=e.nextBuffer||e.sampleQueue.length=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){s.swapSource(e,t)}),0===this.sampleQueue.length)return this.options.isLive?(this.sourceList[e].connect(this.gainNode),this.sourceList[e].startState||null==(r=this.sourceList[e])||null==(i=r.start)||i.call(r),this.sourceList[e].onended=function(){s.swapSource(e,t)},this.sourceList[e].stop(),0):-2;if(this.sourceList[e].buffer)return this.swapSource(e,t),0;if(null==this.nextBuffer||this.nextBuffer.data.length<1){var n,a,o=this.sourceList[e];return o.connect(this.gainNode),(null==o?void 0:o.startState)||null==(a=this.sourceList[e])||null==(n=a.start)||n.call(a),o.startState=!0,o.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=R();try{this.audioCtx.decodeAudioData(l,(function(t){var i,r;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(r=s.sourceList[e])||null==(i=r.start)||i.call(r),s.sourceList[e].startState=!0)}),(function(e){s.logger.error("Error audioCore with decoding audio data",e)}))}catch(e){return this.nextBuffer=null,this.logger.log("decodeAudioData error",e),-3}return this.nextBuffer=null,0},t.decodeWholeSamples=function(e){var t=this;if(void 0===e&&(e=-1),this.sourceChannel=e,e<0||e>=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){}),0===this.sampleQueue.length)return-2;for(var i=null,r=null,s=0;s",e)}},e}(),D=function(){function r(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var s=r.prototype;return s.appendCacheByCacheYuv=function(i){return this.yuvCache.push(i),this.yuvCache.length>=this.limit?(this.shiftYuv(),t):e},s.getState=function(){return this.yuvCache.length<=0?i:this.yuvCache.length>=this.limit?t:e},s.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},s.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},r}(),x=function(){function e(e,t,i,r,s,n){this.pts=e,this.width=t,this.height=i,this.imageBufferY=r,this.imageBufferB=s,this.imageBufferR=n}return e.prototype.setYuv=function(e,t,i,r,s,n){this.pts=e,this.width=t,this.height=i,this.imageBufferY=r,this.imageBufferB=s,this.imageBufferR=n},e}(),C=function(){function e(e){this.gl=e,this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}var t=e.prototype;return t.bind=function(e,t,i){var r=this.gl;r.activeTexture([r.TEXTURE0,r.TEXTURE1,r.TEXTURE2][e]),r.bindTexture(r.TEXTURE_2D,this.texture),r.uniform1i(r.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var r=this.gl;r.bindTexture(r.TEXTURE_2D,this.texture),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,i)},e}(),I=function(){function e(e,t){this.gl=null,this.gl=e.getContext("webgl")||e.getContext("experimental-webgl"),this.program=this.gl.createProgram();var i=["attribute highp vec4 aVertexPosition;","attribute vec2 aTextureCoord;","varying highp vec2 vTextureCoord;","void main(void) {"," gl_Position = aVertexPosition;"," vTextureCoord = aTextureCoord;","}"].join("\n"),r=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(r,i),this.gl.compileShader(r);var s=["precision highp float;","varying lowp vec2 vTextureCoord;","uniform sampler2D YTexture;","uniform sampler2D UTexture;","uniform sampler2D VTexture;","const mat4 YUV2RGB = mat4","("," 1.1643828125, 0, 1.59602734375, -.87078515625,"," 1.1643828125, -.39176171875, -.81296875, .52959375,"," 1.1643828125, 2.017234375, 0, -1.081390625,"," 0, 0, 0, 1",");","void main(void) {"," gl_FragColor = vec4( texture2D(YTexture, vTextureCoord).x, texture2D(UTexture, vTextureCoord).x, texture2D(VTexture, vTextureCoord).x, 1) * YUV2RGB;","}"].join("\n"),n=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(n,s),this.gl.compileShader(n),this.gl.attachShader(this.program,r),this.gl.attachShader(this.program,n),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var a=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(a);var o=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(o),this.verticesBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.verticesBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(a,3,this.gl.FLOAT,!1,0,0),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,0,0),this.gl.y=new C(this.gl),this.gl.u=new C(this.gl),this.gl.v=new C(this.gl),this.gl.y.bind(0,this.program,"YTexture"),this.gl.u.bind(1,this.program,"UTexture"),this.gl.v.bind(2,this.program,"VTexture")}var t=e.prototype;return t.renderFrame=function(e,t,i,r,s){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.y.fill(r,s,e),this.gl.u.fill(r>>1,s>>1,t),this.gl.v.fill(r>>1,s>>1,i),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)},t.destroyContext=function(){try{this.gl.deleteProgram(this.program),this.gl.deleteBuffer(this.verticesBuffer),this.gl.deleteBuffer(this.texCoordBuffer),this.gl.deleteTexture(this.gl.y.texture),this.gl.deleteTexture(this.gl.u.texture),this.gl.deleteTexture(this.gl.v.texture),this.gl=null,this.program=null,this.verticesBuffer=null,this.texCoordBuffer=null}catch(e){}},e}(),P=function(e,t){return{cmd:e,data:t}},O="wasmLoading",M="wasmLoaded",F="wasmFailed",N="videoCallback",U="decodeCodecContext",B="destroy",$="demuxTsStream",G="demuxCoreReceive",K="readPacket",V="readPacketEnd",H="mediaInfo",j={info:"",log:"background: #4096ff; color: #FFF;",warn:"background: yellow; color: #FFF;",error:"background: red; color: #FFF;"},W=function(){function e(e){void 0===e&&(e={}),this._options={level:"INFO",showTime:!1},this._levelNum=3,this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0),this.setOptions(e)}var t=e.prototype;return t.setOptions=function(e){var t;this._options=Object.assign({},this._options,e),this._levelNum=this._matchLevel(null!=(t=this._options.level)?t:"INFO"),this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0)},t._matchLevel=function(e){var t=3;switch(e){case"INFO":t=3;break;case"LOG":t=2;break;case"WARN":t=1;break;case"ERROR":t=0}return t},t._loggerFactory=function(t,i){var r=console[t];if(i&&r){var s,n=this._options.name?"%c["+this._options.name+"]%c %c["+t.toUpperCase()+"]":"%c["+t.toUpperCase()+"]",a=[this._options.name?"background: green;color: #fff":null,this._options.name?"":null,j[t]].filter((function(e){return null!=e}));return(s=r).bind.apply(s,[].concat([console,n],a))}return e.noop},t.getOptions=function(){return this._options},t.getVersion=function(){return"1.0.1"},e}();function Y(e){return(e=+e)<10&&(e="0"+e),e+""}W.noop=function(){};var q=["info","log","warn","error"];function z(e){var t=new W(e);return new Proxy(t,{get:function(e,t){if(q.includes(t)){var i;if(null==(i=e._options)?void 0:i.showTime){var r=(n=(s=new Date(Date.now())).getFullYear(),a=s.getMonth()+1,o=s.getDate(),l=s.getHours(),h=s.getMinutes(),c=s.getSeconds(),d=s.getMilliseconds(),n+"/"+Y(a)+"/"+Y(o)+" "+Y(l)+":"+Y(h)+":"+Y(c)+":"+d);return e[t].bind(console,"["+r+"]")}return e[t].bind(console)}var s,n,a,o,l,h,c,d;return Reflect.get(e,t)}})}var X="object"==typeof global&&global&&global.Object===Object&&global,Q="object"==typeof self&&self&&self.Object===Object&&self,J=X||Q||Function("return this")(),Z=J.Symbol,ee=Object.prototype,te=ee.hasOwnProperty,ie=ee.toString,re=Z?Z.toStringTag:void 0;var se=Object.prototype.toString;var ne="[object Null]",ae="[object Undefined]",oe=Z?Z.toStringTag:void 0;function le(e){return null==e?void 0===e?ae:ne:oe&&oe in Object(e)?function(e){var t=te.call(e,re),i=e[re];try{e[re]=void 0;var r=!0}catch(e){}var s=ie.call(e);return r&&(t?e[re]=i:delete e[re]),s}(e):function(e){return se.call(e)}(e)}function he(e){return null!=e&&"object"==typeof e}var ce=Array.isArray;function de(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ue(e){return e}var fe="[object AsyncFunction]",ge="[object Function]",me="[object GeneratorFunction]",pe="[object Proxy]";function ve(e){if(!de(e))return!1;var t=le(e);return t==ge||t==me||t==fe||t==pe}var ye,Te=J["__core-js_shared__"],Ee=(ye=/[^.]+$/.exec(Te&&Te.keys&&Te.keys.IE_PROTO||""))?"Symbol(src)_1."+ye:"";var Se=Function.prototype.toString;var be=/^\[object .+?Constructor\]$/,Le=Function.prototype,we=Object.prototype,Ae=Le.toString,Re=we.hasOwnProperty,ke=RegExp("^"+Ae.call(Re).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _e(e){return!(!de(e)||(t=e,Ee&&Ee in t))&&(ve(e)?ke:be).test(function(e){if(null!=e){try{return Se.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e));var t}function De(e,t){var i=function(e,t){return null==e?void 0:e[t]}(e,t);return _e(i)?i:void 0}var xe=Object.create,Ce=function(){function e(){}return function(t){if(!de(t))return{};if(xe)return xe(t);e.prototype=t;var i=new e;return e.prototype=void 0,i}}();var Ie=Date.now;var Pe,Oe,Me,Fe=function(){try{var e=De(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),Ne=Fe?function(e,t){return Fe(e,"toString",{configurable:!0,enumerable:!1,value:(i=t,function(){return i}),writable:!0});var i}:ue,Ue=(Pe=Ne,Oe=0,Me=0,function(){var e=Ie(),t=16-(e-Me);if(Me=e,t>0){if(++Oe>=800)return arguments[0]}else Oe=0;return Pe.apply(void 0,arguments)}),Be=9007199254740991,$e=/^(?:0|[1-9]\d*)$/;function Ge(e,t){var i=typeof e;return!!(t=null==t?Be:t)&&("number"==i||"symbol"!=i&&$e.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=qe}function Xe(e){return null!=e&&ze(e.length)&&!ve(e)}var Qe=Object.prototype;function Je(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Qe)}function Ze(e){return he(e)&&"[object Arguments]"==le(e)}var et=Object.prototype,tt=et.hasOwnProperty,it=et.propertyIsEnumerable,rt=Ze(function(){return arguments}())?Ze:function(e){return he(e)&&tt.call(e,"callee")&&!it.call(e,"callee")};var st="object"==typeof exports&&exports&&!exports.nodeType&&exports,nt=st&&"object"==typeof module&&module&&!module.nodeType&&module,at=nt&&nt.exports===st?J.Buffer:void 0,ot=(at?at.isBuffer:void 0)||function(){return!1},lt={};lt["[object Float32Array]"]=lt["[object Float64Array]"]=lt["[object Int8Array]"]=lt["[object Int16Array]"]=lt["[object Int32Array]"]=lt["[object Uint8Array]"]=lt["[object Uint8ClampedArray]"]=lt["[object Uint16Array]"]=lt["[object Uint32Array]"]=!0,lt["[object Arguments]"]=lt["[object Array]"]=lt["[object ArrayBuffer]"]=lt["[object Boolean]"]=lt["[object DataView]"]=lt["[object Date]"]=lt["[object Error]"]=lt["[object Function]"]=lt["[object Map]"]=lt["[object Number]"]=lt["[object Object]"]=lt["[object RegExp]"]=lt["[object Set]"]=lt["[object String]"]=lt["[object WeakMap]"]=!1;var ht="object"==typeof exports&&exports&&!exports.nodeType&&exports,ct=ht&&"object"==typeof module&&module&&!module.nodeType&&module,dt=ct&&ct.exports===ht&&X.process,ut=function(){try{var e=ct&&ct.require&&ct.require("util").types;return e||dt&&dt.binding&&dt.binding("util")}catch(e){}}(),ft=ut&&ut.isTypedArray,gt=ft?function(e){return function(t){return e(t)}}(ft):function(e){return he(e)&&ze(e.length)&&!!lt[le(e)]};function mt(e,t){var i=ce(e),r=!i&&rt(e),s=!i&&!r&&ot(e),n=!i&&!r&&!s&>(e),a=i||r||s||n,o=a?function(e,t){for(var i=-1,r=Array(e);++i-1},At.prototype.set=function(e,t){var i=this.__data__,r=Lt(i,e);return r<0?(++this.size,i.push([e,t])):i[r][1]=t,this};var Rt=De(J,"Map");function kt(e,t){var i,r,s=e.__data__;return("string"==(r=typeof(i=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==i:null===i)?s["string"==typeof t?"string":"hash"]:s.map}function _t(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t1?t[r-1]:void 0,n=r>2?t[2]:void 0;for(s=qt.length>3&&"function"==typeof s?(r--,s):void 0,n&&function(e,t,i){if(!de(i))return!1;var r=typeof t;return!!("number"==r?Xe(i)&&Ge(t,i.length):"string"==r&&t in i)&&Ve(i[t],e)}(t[0],t[1],n)&&(s=r<3?void 0:s,r=1),e=Object(e);++i{if("undefined"==typeof document)return!1;const e=ti[0],t={};for(const i of ti){const r=i?.[1];if(r in document){for(const[r,s]of i.entries())t[e[r]]=s;return t}}return!1})(),ri={change:ii.fullscreenchange,error:ii.fullscreenerror};let si={request:(e=document.documentElement,t)=>new Promise(((i,r)=>{const s=()=>{si.off("change",s),i()};si.on("change",s);const n=e[ii.requestFullscreen](t);n instanceof Promise&&n.then(s).catch(r)})),exit:()=>new Promise(((e,t)=>{if(!si.isFullscreen)return void e();const i=()=>{si.off("change",i),e()};si.on("change",i);const r=document[ii.exitFullscreen]();r instanceof Promise&&r.then(i).catch(t)})),toggle:(e,t)=>si.isFullscreen?si.exit():si.request(e,t),onchange(e){si.on("change",e)},onerror(e){si.on("error",e)},on(e,t){const i=ri[e];i&&document.addEventListener(i,t,!1)},off(e,t){const i=ri[e];i&&document.removeEventListener(i,t,!1)},raw:ii};Object.defineProperties(si,{isFullscreen:{get:()=>Boolean(document[ii.fullscreenElement])},element:{enumerable:!0,get:()=>document[ii.fullscreenElement]??void 0},isEnabled:{enumerable:!0,get:()=>Boolean(document[ii.fullscreenEnabled])}}),ii||(si={isEnabled:!1});var ni=si,ai={exports:{}};!function(e,t){function i(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}!function(r,s){var n="function",a="undefined",o="object",l="string",h="major",c="model",d="name",u="type",f="vendor",g="version",m="architecture",p="console",v="mobile",y="tablet",T="smarttv",E="wearable",S="embedded",b="Amazon",L="Apple",w="ASUS",A="BlackBerry",R="Browser",k="Chrome",_="Firefox",D="Google",x="Huawei",C="LG",I="Microsoft",P="Motorola",O="Opera",M="Samsung",F="Sharp",N="Sony",U="Xiaomi",B="Zebra",$="Facebook",G="Chromium OS",K="Mac OS",V=function(e){for(var t={},i=0;i0?2===h.length?i(h[1])==n?this[h[0]]=h[1].call(this,d):this[h[0]]=h[1]:3===h.length?i(h[1])!==n||h[1].exec&&h[1].test?this[h[0]]=d?d.replace(h[1],h[2]):s:this[h[0]]=d?h[1].call(this,d,h[2]):s:4===h.length&&(this[h[0]]=d?h[3].call(this,d.replace(h[1],h[2])):s):this[h]=d||s;u+=2}},q=function(e,t){for(var r in t)if(i(t[r])===o&&t[r].length>0){for(var n=0;n2&&(e[c]="iPad",e[u]=y),e},this.getEngine=function(){var e={};return e[d]=s,e[g]=s,Y.call(e,S,L.engine),e},this.getOS=function(){var e={};return e[d]=s,e[g]=s,Y.call(e,S,L.os),w&&!e[d]&&b&&"Unknown"!=b.platform&&(e[d]=b.platform.replace(/chrome os/i,G).replace(/macos/i,K)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=(void 0===e?"undefined":i(e))===l&&e.length>500?W(e,500):e,this},this.setUA(S),this};Q.VERSION="1.0.37",Q.BROWSER=V([d,g,h]),Q.CPU=V([m]),Q.DEVICE=V([c,f,u,p,v,T,y,E,S]),Q.ENGINE=Q.OS=V([d,g]),i(t)!==a?(i(e)!==a&&e.exports&&(t=e.exports=Q),t.UAParser=Q):(void 0===r?"undefined":i(r))!==a&&(r.UAParser=Q);var J=(void 0===r?"undefined":i(r))!==a&&(r.jQuery||r.Zepto);if(J&&!J.ua){var Z=new Q;J.ua=Z.getResult(),J.ua.get=function(){return Z.getUA()},J.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)J.ua[i]=t[i]}}}("object"===("undefined"==typeof window?"undefined":i(window))?window:Qt)}(ai,ai.exports);var oi,li,hi,ci,di=Jt(ai.exports),ui=(oi="undefined"!=typeof self?self:window,li={navigator:void 0!==oi.navigator?oi.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},hi={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var t,i=(null==(t=li.navigator)?void 0:t.userAgent)||"",r=hi.getMatchMap(i);for(var s in li.infoMap)for(var n=0;n36&&oi.showModalDialog?s=!0:+n>45&&(s=i("type","application/vnd.chromium.remoting-viewer"))}if(r.Baidu&&r.Opera&&(r.Baidu=!1),r.Mobile&&(r.Mobile=!t.includes("iPad")),s&&(i("type","application/gameplugin")||li.navigator&&void 0===li.navigator.connection.saveData?r["360SE"]=!0:r["360EE"]=!0),r.IE||r.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:r["360EE"]=!0;break;case 104:r["360SE"]=!0}var a={Safari:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return t.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return t.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return t.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return t.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return t.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return t.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return t.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return t.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return t.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return t.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return t.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return t.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return t.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return t.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return t.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return t.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return t.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return t.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return t.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return t.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return t.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return t.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return t.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return t.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return t.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return t.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return t.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return t.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return t.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return t.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return t.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return t.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return t.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return t.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return t.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return t.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return t.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",a[e.browser]&&(e.browserVersion=a[e.browser](),e.browserVersion==t&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},ci={DeviceInfoObj:function(e){var t,i=function(t){var i;null==(i=e.info)||i.forEach((function(e){e.toLowerCase()===t.toLowerCase()&&(s[t]=r[t])}))};e=e||{domain:""};var r={deviceType:hi.getDeviceType(),OS:hi.getOS(),OSVersion:hi.getOSVersion(),sh:oi.screen.height,sw:oi.screen.width,lang:hi.getLanguage(),netWork:hi.getNetwork(),orientation:hi.getOrientationStatu(),browserInfo:hi.getBrowserInfo(),fingerprint:hi.createFingerprint(e.domain),userAgent:null==(t=li.navigator)?void 0:t.userAgent};if(!e.info||0===e.info.length)return r;var s={};for(var n in r)i(n);return s}},{getDeviceInfo:function(e){return ci.DeviceInfoObj(e)}}),fi=function(){function e(){}return e.add=function(t,i){e.queues.push({url:t,data:i})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var t=e.queues[0];t.url&&e.api.report(t.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();fi.isStop=!0,fi.queues=[];var gi=function(){function e(e){this.url=e}var t=e.prototype;return t.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},t.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},t.sendImage=function(e,t){var i=this.changeJSON2Query(t),r=new Image;r.onload=r.onerror=function(){r=null},r.src=e+"?"+i+"&random="+Math.random()},t.sendBeacon=function(e,t){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(t))}catch(e){}},t.formatParamsByURLSearchParams=function(e){var t=new URLSearchParams;for(var i in e)"object"==typeof e[i]&&(e[i]=JSON.stringify(e[i])),t.append(i,e[i]);return t},t.changeJSON2Query=function(e){var t="";for(var i in e){""!=t&&(t+="&");var r=e[i];t+=i+"="+encodeURIComponent("object"==typeof r?JSON.stringify(r):r)}return t},t.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function mi(){return mi=Object.assign||function(e){for(var t=1;t0&&t>0))throw new Error("width value "+e+" or height value "+t+" unqualified!");this.width=e,this.height=t},i.play=function(e){throw new Error("Method play not implemented.")},i.pause=function(){throw new Error("Method pause not implemented.")},i.fullscreen=function(){var e,t,i,r;return null==(t=this.logger)||null==(e=t.log)||e.call(t,"[fullscreen]"),null==(r=this.event)||null==(i=r.emit)||i.call(r,"fullscreen"),Ti.send(1,{name:"fullscreen"}),ni.isEnabled&&!this.isMobile?ni.request(this.$container):(this.logger.warn("Not support fullscreen"),Promise.resolve())},i.exitFullscreen=function(){var e,t,i,r;return null==(t=this.logger)||null==(e=t.log)||e.call(t,"[exitFullscreen]"),null==(r=this.event)||null==(i=r.emit)||i.call(r,"exitFullscreen"),Ti.send(1,{name:"exitFullscreen"}),ni.isEnabled&&!this.isMobile?ni.exit():(this.logger.warn("Not support exitFullscreen"),Promise.resolve())},i.setVolume=function(e){throw new Error("Method setVolume not implemented.")},i.resize=function(e,t){Ti.send(1,{name:"resize"});try{var i,r,s,n;this._checkSize(e,t),this.$container.style.width=e+"px",this.$container.style.height=t+"px",null==(r=this.logger)||null==(i=r.log)||i.call(r,"[resize] width: "+e+", height: "+t),null==(n=this.event)||null==(s=n.emit)||s.call(n,"resize",{data:{width:e,height:t}})}catch(e){}},i.destroy=function(){var e,t=this;this.browser&&(this.browser=null),ni.isEnabled&&this._screenfullChange&&(null==ni||null==(e=ni.off)||e.call(ni,"change",this._screenfullChange),this._screenfullChange=null),this.logger&&(this.logger=null),this.event&&setTimeout((function(){t.event.removeAllListeners(),t.event=null}),100)},i.setLogger=function(e){Ti.send(1,{name:"setLogger"}),this.options=zt(this.options,{loggerOptions:e}),this.logger.setOptions(this.options.loggerOptions)},i.getVersion=function(){throw new Error("Method getVersion not implemented.")},i.getOptions=function(){return Ti.send(1,{name:"getOptions"}),this.options},t.supportType=function(e){return!1},t}(ei),bi=function(){function e(e,t){if(this._$container=e,"string"==typeof e&&(this._$container=document.getElementById(e)),!this._$container)throw new Error("VideoCanvas create fail!");this._options=t,this._createDom()}return e.prototype._createDom=function(){var e,t,i,r,s,n,a=this;this.$video||(this.$video=document.createElement("video"),this._options.autoPlay&&(this.$video.muted=!(null==(e=window)?void 0:e.___HUMAN_TOUCH_SCREEN___),this.$video.autoplay=!0,"object"==((s=null==(t=window)?void 0:t.WeixinJSBridge)&&"undefined"!=typeof Symbol&&s.constructor===Symbol?"symbol":typeof s)&&"function"==typeof(null==(r=window)||null==(i=r.WeixinJSBridge)?void 0:i.invoke)&&document.addEventListener("WeixinJSBridgeReady",(function(){a.$video.play(),a.$video.pause()}),!1),this.$video.addEventListener("loadeddata",(function(){setTimeout((function(){a.$video.play()}),10)}))),this.$video.volume=+this._options.volume||0,this.$video.controls=!!this._options.controls,this.$video.preload=this._options.preload||"auto",this.$video.disablePictureInPicture=!0,this.$video.setAttribute("playsInline","true"),this.$video.setAttribute("webkit-playsinline","true"),this.$video.setAttribute("controlsList",this._options.controlsList||""),(this._options.isMobile&&navigator.userAgent.includes("MQQBrowser")||navigator.userAgent.includes("QQTheme"))&&(this.$video.setAttribute("x5-video-player-type","h5"),this.$video.setAttribute("x5-video-player-fullscreen","false"),this.$video.setAttribute("x5-video-orientation","portraint")),this._options.loop&&this.$video.setAttribute("loop","true"),this.$video.style.cssText+="width: 100%; height: 100%; object-fit: contain; position: absolute; z-index: 1; outline: none;",this._$container.innerHTML="",this._$container.appendChild(this.$video),this._options.disableContextmenu&&(null==(n=this.$video)||n.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}))))},e}(),Li="ezui-hls",wi={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},Ai={disableContextmenu:!0},Ri=function(){function e(e){void 0===e&&(e={}),this.options=Object.assign({},Ai,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=Li+"-video",this._$container=document.getElementById(this.options.id),this._render()}var t=e.prototype;return t._render=function(){var e,t;if("video"===this.options.nodeName)this.$video=new bi(this._$container,this.options).$video;else{var i;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(i=this.$video)||i.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}));this.$video.classList.add(this._classVideo),this.$video.style.cssText+="object-fit: contain; z-index:1;"}null==(t=this.event)||null==(e=t.emit)||e.call(t,"rendered")},t._isVideo=function(){return"VIDEO"===this.$video.nodeName},t.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},e}();function ki(e,t,i){return t&&function(e,t){for(var i=0;i=1&&(null==(i=e)||null==(t=i.onLoadCacheFinished)||t.call(i),window.clearInterval(e.cacheInterval),e.cacheInterval=null,e.isCaching===b&&e.play(e.playParams),e.isCaching=S)}),40))}},r._playFunc=function(){var e=!1;if(R()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=R(),this.options.audioNone)this.playFrameYUV(t);else{this.fix_poc_err_skip>0&&(this.fix_poc_err_skip--,t=!1);var i=this.videoPTS-this.audio.getAlignVPTS();if(i>0)return void(this.playParams.seekEvent&&!this.options.audioNone&&this.audio.setVolume(0));if(t){if(!(t=-1*i<=1*this.frameTimeSec)){for(var r=parseInt(i/this.frameTimeSec+""),s=0;s",e,r,i),r>=i&&(t.playFrameYUV(!0),i+=1)}),this.frameTime||5)}else(this.videoPTS>=this.playParams.seekPos&&!this.isNewSeek||0===this.playParams.seekPos||0===this.playParams.seekPos)&&(this.frameTime=1e3/this.options.fps,this.frameTimeSec=this.frameTime/1e3,this.options.audioNone||this.audio.play(),this._volume=this.options.audioNone?0:this.audio.volume,this.loop=window.setInterval((function(){var e=R();t._playFunc(),t.preCostTime=R()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},r.stop=function(){this.destroy(),this.stream=new Uint8Array},r.destroy=function(){return void 0!==this.gl&&null!==this.gl&&(this.gl.destroyContext(),this.gl=null),this.endAudio(),this.cacheLoop&&window.clearInterval(this.cacheLoop),this.cacheLoop=null,this.loop&&window.clearInterval(this.loop),this.loop=null,this.pause(),this.decoderWorker.postMessage(P(B)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},r.nextNalu=function(e){if(void 0===e&&(e=1),this.stream.length<=4)return!1;for(var t=-1,i=0;i=this.stream.length){if(-1===t)return!1;var r=this.stream.subarray(t);return this.stream=new Uint8Array,r}var s="0 0 1"===this.stream.slice(0,3).join(" "),n="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||n){if(-1===t)t=i;else{if(e<=1){var a=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),a}e-=1}i+=3}}return!1},r.playFrameYUV=function(e){void 0===e&&(e=!1);var t=this.cacheYuvBuf.shiftYuv();if(!t)return this.noCacheFrame+=1,e&&!this.playParams.seekEvent&&this.loadCache(),!1;this.noCacheFrame=0;var i=t.pts;return this.videoPTS=i,this.drawImage(t.width,t.height,t.imageBufferY,t.imageBufferB,t.imageBufferR),t=null,e&&!this.playParams.seekEvent&&this.isPlaying&&this.loadCache(),!0},r.drawImage=function(e,t,i,r,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var n=e*t,a=e/2*(t/2),o=new Uint8Array(n+2*a);o.set(i,0),o.set(r,n),o.set(s,n+a),this.gl.renderFrame(i,r,s,e,t),o=null},r.checkDisplaySize=function(e,t){var i,r=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),n=+(this.options.height/t).toFixed(2),a=r?s:n,o=this.options.fixed,l=o?this.options.width:parseInt(e*a+""),h=o?this.options.height:parseInt(t*a+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/h>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,h]},r._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===N){var r=i.data,s=r.ptsSec,n=r.strideY,a=r.height;r.width;var o=r.bufY,l=r.bufU,h=r.bufV,c=new x(s,n,a,o,l,h);e.cacheYuvBuf.appendCacheByCacheYuv(c),c=null}}},r.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new I(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new _({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},ki(i,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),i}(Ri),Ci=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],Ii={lineDelimiter:/\r?\n/,extensionHeader:"#EXTM3U",tagPrefix:"#EXT",segmentPrefix:"#EXTINF",segmentParse:/^#EXTINF: *([0-9.]+)(, *(.+?)?)?$/,tagParse:/^#EXT-X-([A-Z-]+)(:(.+))?$/,version:"VERSION",allowCache:"ALLOW-CACHE",combined:"COMBINED",endList:"ENDLIST",targetDuration:"TARGETDURATION",mediaSequence:"MEDIA-SEQUENCE",discontinuity:"DISCONTINUITY",streamInf:"STREAM-INF",isComment:function(e){return e&&"#"===e[0]&&!e.startsWith(Ii.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return Ii.isBlank(e)||Ii.isComment(e)},defaultMinDur:99999},Pi=function(){function e(e){this._retry=10,this.logger=null==e?void 0:e.logger,this.initState=!0,this.controller=new AbortController,this._slices=[],this._type=o,this._preURI="",this.duration=-1,this.onTransportStream=null,this.onFinished=null}var t=e.prototype;return t.destroy=function(){this.initState=!1},t.fetchM3u8=function(e){var t=this,i=this;if(this.initState){var r=function(t){return new Promise((function(i,r){var s=new XMLHttpRequest;s.open("GET",t),s.onload=function(){this.status>=200&&this.status<300&&(t!==this.responseURL?(e=this.responseURL,i(this.responseURL)):i(""))},s.onreadystatechange=function(){4===s.readyState&&200===s.status&&i(s.responseText)},s.onerror=function(){r(new Error("Network error."))},s.send()}))};r(e).then((function(s){if(t._retry=10,i._uriParse(e)){var n=i._m3u8Parse(s);if("number"==typeof n&&n>=0)var a=setTimeout((function(){i.fetchM3u8(e),clearTimeout(a)}),200*n)}return r=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),r=null,t._retry>=1)var n=setTimeout((function(){i.fetchM3u8(e),clearTimeout(n)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,r=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],r=t[1].split("/"),this._preURI=i+"://"):r=t[0].split("/");for(var s=0;su&&(s=u);var f,g=r[o+=1],m=null;if(g.includes("http"))m=g;else{if("/"===g[0]){var p=this._preURI.split("//"),v=p[p.length-1].split("/");this._preURI=p[0]+"//"+v[0]}m=this._preURI+g}if(!this._slices.includes(m))this._slices.push(m),null==this||null==(f=this.onTransportStream)||f.call(this,m,u)}}}this._slices.length>500&&(this._slices=this._slices.slice(-500));var y={type:this._type,duration:-1};return null==this||null==(t=this.onFinished)||t.call(this,y),s},t._readTag=function(e){var t=Ii.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),Oi=function(){function e(e){this.sampleRate=e.sampleRate,this.frameDurMs=Math.floor(1024e3/this.sampleRate),this.frameDurSec=this.frameDurMs/1e3}var t=e.prototype;return t.updateOptions=function(e){this.sampleRate=e.sampleRate,this.frameDurMs=1024e3/this.sampleRate,this.frameDurSec=this.frameDurMs/1e3},t._getPktLen=function(e,t,i){return((3&e)<<11)+(t<<3)+((224&i)>>5)},t.sliceAACFrames=function(e,t){for(var i=[],r=e,s=0;s>4==15){var n=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(n<=0)continue;var a=t.subarray(s,s+n),o=new Uint8Array(n);o.set(a,0),i.push({ptime:r,data:o}),r+=this.frameDurSec,s+=n}else s+=1;return i},e}(),Mi="M3U8",Fi="TS",Ni="FETCH",Ui=function(){function e(){}return e.init=function(t){e.collect=new pi(t)},e.send=function(t,i){var r,s;null==(s=e.collect)||null==(r=s.send)||r.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function Bi(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(r){var s,n,a,o;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",r),null==(n=t.event)||null==(s=n.emit)||s.call(n,Fi,{data:r}),null==(o=t.event)||null==(a=o.emit)||a.call(o,Ni,{data:r,type:Fi}),null==i||i.onDemuxedFailed(r,e),Ui.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage(P($,{buff:e,tsUrl:t}))},t.readMediaInfo=function(){return this.mediaInfo},t.readAudioNone=function(){var e;return null==(e=this.mediaInfo)?void 0:e.audioNone},t.isHEVC=function(){return this.mediaInfo.vCodec===n||this.mediaInfo.vCodec===s},t.destroy=function(){this.controller&&this.controller.abort(),this.controller=null,this.mediaInfo=null,this.aacDec=null},t._onWorkerMessage=function(){var e=this;e.logger.log("[demuxer] register _onWorkerMessage"),e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case H:var r,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(r=s.emit)||r.call(s,"mediaInfo",e.mediaInfo);break;case G:var n;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new Oi(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(n=e.onDemuxed)||n.call(e)}}))},Bi(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),Ki=function(){function e(e,t,i,r){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=r}return e.prototype.setFrame=function(e,t,i,r){this.pts=e,this.isKey=t,this.data=i,this.video=r},e}(),Vi=function(){function e(e){this.logger=null==e?void 0:e.logger,this.event=null==e?void 0:e.event,this.decoderWorker=e.decoderWorker,this.m3u8Base=new Pi(e),this.mpegTsDemux=new Gi(e),this.tsList=[],this._startTime=0,this._aStartTime=0,this.lockWait={state:!1,lockMember:{dur:0}},this._timerFeed=null,this.seekPos=-1,this.vPreFramePTS=0,this.aPreFramePTS=0,this.audioNone=!1,this.isHevcParam=!1,this.vCodec="",this.aCodec=null,this.aChannel=0,this.durationMs=-1,this.fps=-1,this.sampleRate=-1,this.size={width:-1,height:-1},this.mediaInfo=null,this._onWorkerMessage(),this.onReadyOBJ=null,this.onFinished=null,this.onDemuxed=null,this.onSamples=null,this.onCacheProcess=null}var t=e.prototype;return t.getCachePTS=function(){return Math.max(this.vPreFramePTS,this.aPreFramePTS)},t.demux=function(e){var t=this,i=this;this.vPreFramePTS=0,this.aPreFramePTS=0,this.m3u8Base.onTransportStream=function(e,t){i.tsList.push({streamURI:e,streamDur:t}),i.lockWait.state=!1},this.m3u8Base.onFinished=function(e){var t;e.type===a?i.durationMs=1e3*e.duration:i.durationMs=-1,null==i||null==(t=i.onFinished)||t.call(i,i.onReadyOBJ,e)},this.mpegTsDemux.onDemuxedFailed=function(e,r){t.logger.error("[M3u8] onDemuxedFailed: ",e,r),i.lockWait.state=!1},this.mpegTsDemux.onDemuxed=function(){var e;t.logger.log("[M3u8] onDemuxed"),null==i.mediaInfo&&(i.mediaInfo=i.mpegTsDemux.readMediaInfo(),t.logger.log("[M3u8] mediaInfo: ",i.mediaInfo),i.isHevcParam=i.mpegTsDemux.isHEVC(),i.vCodec=i.mpegTsDemux.vCodec,i.aCodec=i.mediaInfo.aCodec,i.aChannel=i.mediaInfo.sampleChannel,i.fps=i.mediaInfo.fps,i.sampleRate=i.mediaInfo.sampleRate,(null===i.aCodec||""===i.aCodec||i.aChannel<=0)&&(i.audioNone=!0),i.mediaInfo.width>0&&i.mediaInfo.height>0&&(t.size.width=t.mediaInfo.width,t.size.height=t.mediaInfo.height)),null==i||null==(e=i.onDemuxed)||e.call(i,i.onReadyOBJ),i.mpegTsDemux&&t.decoderWorker.postMessage(P(K))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===Uc.__HLS_WASM_DecoderState__&&(i._fetchM3u8AndIntervalTs(e),window.clearInterval(i._timerTsWasm),i._timerTsWasm=null)}),500)},t._fetchM3u8AndIntervalTs=function(e){var t=this,i=this;this.logger.log("[M3u8] start fetch m3u8 url"),i.m3u8Base.fetchM3u8(e),i._timerFeed=window.setInterval((function(){if(i.tsList.length>0&&!i.lockWait.state)try{var e=i.tsList.shift();if(null!=e){var r=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(r)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var n,a,o,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(a=t.event)||null==(n=a.emit)||n.call(a,Mi,{data:e}),null==(l=t.event)||null==(o=l.emit)||o.call(l,Ni,{data:e,type:Mi}),i.lockWait.state=!1}}),50)},t.destroy=function(){var e;this.m3u8Base&&(null==(e=this.m3u8Base)||e.destroy(),this.m3u8Base=null);this._timerFeed&&(window.clearInterval(this._timerFeed),this._timerFeed=null),this.mpegTsDemux&&(this.mpegTsDemux.destroy(),this.mpegTsDemux=null)},t.bindReady=function(e){this.onReadyOBJ=e},t.getACodec=function(){return this.aCodec},t.getVCodec=function(){return this.vCodec},t.getDurationMs=function(){return this.durationMs},t.getFPS=function(){return this.fps},t.getSampleRate=function(){return this.sampleRate},t.getSampleChannel=function(){return this.aChannel},t.getSize=function(){return this.size},t._onWorkerMessage=function(){this.logger.log("[M3U8] register _onWorkerMessage");var e=this;e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case K:var s,n=i.data,a=n.type,o=n.pts,l=n.ptime,h=n.keyframe,c=n.data,d=n.layer;if(c=new Uint8Array(c),1===a&&e.mpegTsDemux.mediaInfo.aCodec===r&&(c=e.mpegTsDemux.aacDec.sliceAACFrames(l,c)),0===a){var u=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var r=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return r.set(t.vps,0),r.set(t.sps,t.vps.length),r.set(t.pps,t.vps.length+t.sps.length),r.set(t.sei,t.vps.length+t.sps.length+t.pps.length),r.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),r}(d),f=o,g=new Ki(f,1===h,u,!0);e.vPreFramePTS=f,null==e||e.onSamples(e.onReadyOBJ,g)}else if(1===a){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var p=c,v=0;v`):sr}(t)}))}const lr=ar,hr=/^(\d+)x(\d+)$/,cr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class dr{constructor(e){"string"==typeof e&&(e=dr.parseAttrList(e)),Qi(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;eNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=hr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={};for(cr.lastIndex=0;null!==(t=cr.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));i[t[1].trim()]=e}return i}}function ur(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class fr{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){lr.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Qi(new dr({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);Ji(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ji(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Ji(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class gr{constructor(){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 mr="audio",pr="video",vr="audiovideo";class yr{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[mr]:null,[pr]:null,[vr]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let r;r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Wi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Tr extends yr{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new gr,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!Ji(this.programDateTime))return null;const e=Ji(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[mr]=null,e[pr]=null,e[vr]=null}}class Er extends yr{constructor(e,t,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new gr,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class Sr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.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.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Ji(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function br(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function Lr(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=br(s)):i=function(e){const t=wr(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}function wr(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}const Ar="undefined"!=typeof self?self:void 0;var Rr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},kr="org.w3.clearkey",_r="com.apple.streamingkeydelivery",Dr="com.microsoft.playready",xr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Cr(e){switch(e){case _r:return Rr.FAIRPLAY;case Dr:return Rr.PLAYREADY;case xr:return Rr.WIDEVINE;case kr:return Rr.CLEARKEY}}var Ir="edef8ba979d64acea3c827dcd51d21ed";function Pr(e){switch(e){case Rr.FAIRPLAY:return _r;case Rr.PLAYREADY:return Dr;case Rr.WIDEVINE:return xr;case Rr.CLEARKEY:return kr}}function Or(e){const{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[Rr.FAIRPLAY,Rr.WIDEVINE,Rr.PLAYREADY,Rr.CLEARKEY].filter((e=>!!t[e])):[];return!r[Rr.WIDEVINE]&&i&&r.push(Rr.WIDEVINE),r}const Mr=null!=Ar&&null!=(Fr=Ar.navigator)&&Fr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Fr;function Nr(e,t,i){return Uint8Array.prototype.slice?e.slice(t,i):new Uint8Array(Array.prototype.slice.call(e,t,i))}const Ur=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,Br=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,$r=(e,t)=>{const i=t;let r=0;for(;Ur(e,t);){r+=10;r+=Gr(e,t+6),Br(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)},Gr=(e,t)=>{let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i},Kr=(e,t)=>Ur(e,t)&&Gr(e,t+6)+10<=e.length-t,Vr=e=>{const t=Wr(e);for(let e=0;ee&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,jr=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Gr(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}},Wr=e=>{let t=0;const i=[];for(;Ur(e,t);){const r=Gr(e,t+6);t+=10;const s=t+r;for(;t+8"PRIV"===e.type?qr(e):"W"===e.type[0]?Xr(e):zr(e),qr=e=>{if(e.size<2)return;const t=Jr(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}},zr=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=Jr(e.data.subarray(t),!0);t+=i.length+1;const r=Jr(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=Jr(e.data.subarray(1));return{key:e.type,data:t}},Xr=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=Jr(e.data.subarray(t),!0);t+=i.length+1;const r=Jr(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=Jr(e.data);return{key:e.type,data:t}},Qr=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},Jr=(e,t=!1)=>{const i=es();if(i){const r=i.decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let s,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=e[l++],o+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return o};let Zr;function es(){if(!navigator.userAgent.includes("PlayStation 4"))return Zr||void 0===self.TextDecoder||(Zr=new self.TextDecoder("utf-8")),Zr}const ts=function(e){let t="";for(let i=0;i>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ds(e,t){const i=[];if(!t.length)return i;const r=e.byteLength;for(let s=0;s1?s+n:r;if(ns(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{const r=ds(e.subarray(s+8,a),t.slice(1));r.length&&rs.apply(i,r)}s=a}return i}function us(e){const t=[],i=e[0];let r=8;const s=os(e,r);r+=4;let n=0,a=0;0===i?(n=os(e,r),a=os(e,r+4),r+=8):(n=ls(e,r),a=ls(e,r+8),r+=16),r+=2;let o=e.length+a;const l=as(e,r);r+=2;for(let i=0;i>>31)return lr.warn("SIDX has hierarchical references (not supported)"),null;const l=os(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function fs(e){const t=[],i=ds(e,["moov","trak"]);for(let e=0;e{const i=os(e,4),r=t[i];r&&(r.default={duration:os(e,12),flags:os(e,20)})})),t}function gs(e){const t=e.subarray(8),i=t.subarray(86),r=ns(t.subarray(4,8));let s=r;const n="enca"===r||"encv"===r;if(n){const e=ds(t,[r])[0];ds(e.subarray("enca"===r?28:78),["sinf"]).forEach((e=>{const t=ds(e,["schm"])[0];if(t){const i=ns(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=ds(e,["frma"])[0];t&&(s=ns(t))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const e=ds(i,["avcC"])[0];s+="."+ps(e[1])+ps(e[2])+ps(e[3]);break}case"mp4a":{const e=ds(t,[r])[0],i=ds(e.subarray(28),["esds"])[0];if(i&&i.length>12){let e=4;if(3!==i[e++])break;e=ms(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=ms(i,e);const r=i[e++];if(64!==r)break;if(s+="."+ps(r),e+=12,5!==i[e++])break;e=ms(i,e);const n=i[e++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const e=ds(i,["hvcC"])[0],t=e[1],r=["","A","B","C"][t>>6],n=31&t,a=os(e,2),o=(32&t)>>5?"H":"L",l=e[12],h=e.subarray(6,12);s+="."+r+n,s+="."+a.toString(16).toUpperCase(),s+="."+o+l;let c="";for(let e=h.length;e--;){const t=h[e];if(t||c){c="."+t.toString(16).toUpperCase()+c}}s+=c;break}case"dvh1":case"dvhe":{const e=ds(i,["dvcC"])[0],t=e[2]>>1&127,r=e[2]<<5&32|e[3]>>3&31;s+="."+vs(t)+"."+vs(r);break}case"vp09":{const e=ds(i,["vpcC"])[0],t=e[4],r=e[5],n=e[6]>>4&15;s+="."+vs(t)+"."+vs(r)+"."+vs(n);break}case"av01":{const e=ds(i,["av1C"])[0],t=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",a=(64&e[2])>>6,o=(32&e[2])>>5,l=2===t&&a?o?12:10:a?10:8,h=(16&e[2])>>4,c=(8&e[2])>>3,d=(4&e[2])>>2,u=3&e[2],f=1,g=1,m=1,p=0;s+="."+t+"."+vs(r)+n+"."+vs(l)+"."+h+"."+c+d+u+"."+vs(f)+"."+vs(g)+"."+vs(m)+"."+p;break}}return{codec:s,encrypted:n}}function ms(e,t){const i=t+5;for(;128&e[t++]&&t{const l=o.byteOffset-8;ds(o,["traf"]).map((o=>{const h=ds(o,["tfdt"]).map((e=>{const t=e[0];let i=os(e,4);return 1===t&&(i*=Math.pow(2,32),i+=os(e,8)),i/s}))[0];return void 0!==h&&(e=h),ds(o,["tfhd"]).map((h=>{const c=os(h,4),d=16777215&os(h,0);let u=0;const f=!!(16&d);let g=0;const m=!!(32&d);let p=8;c===n&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(u=os(h,p),p+=4),f&&(g=os(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),i=t<0?e:e.substring(0,t);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(t.codec)),ds(o,["trun"]).map((n=>{const o=n[0],h=16777215&os(n,0),c=!!(1&h);let d=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const T=!!(1024&h),E=!!(2048&h);let S=0;const b=os(n,4);let L=8;c&&(d=os(n,L),L+=4),f&&(L+=4);let w=d+l;for(let l=0;l>1&63;return 39===e||40===e}return 6===(31&t)}function Ls(e,t,i,r){const s=ws(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const e=s.length-n;let t=n;if(oe){lr.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){const e=as(s,t);if(t+=2,49===e){const e=os(s,t);if(t+=4,1195456820===e){const e=s[t++];if(3===e){const n=s[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e16){const e=[];for(let i=0;i<16;i++){const r=s[t++].toString(16);e.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let r=8,s=i;for(;s--;)r+=t[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),s=0,r=8;s>8*(15-i)&255;return t}(e);return new ks(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=Lr(this.uri);if(t)switch(this.keyFormat){case xr:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Dr:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=As(e,0,t);const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),s=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const e=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(e){const t=br(e).subarray(0,16);!function(e){const t=function(e,t,i){const r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=Rs[this.uri];if(!e){const t=Object.keys(Rs).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Rs[this.uri]=e}this.keyId=e}return this}}const _s=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ds(e){return _s.test(e)}function xs(e,t,i){if(null!==e.variableList||e.hasVariableRefs)for(let r=i.length;r--;){const s=i[r],n=t[s];n&&(t[s]=Cs(e,n))}}function Cs(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(_s,(t=>{const r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function Is(e,t,i){let r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function Ps(e,t,i){const r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function Os(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Ms={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 Fs(e,t,i=!0){return!e.split(",").some((e=>!Ns(e,t,i)))}function Ns(e,t,i=!0){var r;const s=Os(i);return null!=(r=null==s?void 0:s.isTypeSupported(Us(e,t)))&&r}function Us(e,t){return`${t}/mp4;codecs="${e}"`}function Bs(e){if(e){const t=e.substring(0,4);return Ms.video[t]}return 2}function $s(e){return e.split(",").reduce(((e,t)=>{const i=Ms.video[t];return i?(2*i+e)/(e?3:2):(Ms.audio[t]+e)/(e?2:1)}),0)}const Gs={};const Ks=/flac|opus/i;function Vs(e,t=!0){return e.replace(Ks,(e=>function(e,t=!0){if(Gs[e])return Gs[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[e];for(let r=0;r0&&r.length({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ws.lastIndex=0;null!==(r=Ws.exec(e));){const e=new dr(r[1]),n=e.TYPE;if(n){const r=a[n],l=s[n]||[];s[n]=l,xs(i,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=e.LANGUAGE,c=e["ASSOC-LANGUAGE"],d=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||h||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:h,url:e.URI?Xs.resolve(e.URI,t):""};if(c&&(g.assocLang=c),d&&(g.channels=d),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=r&&r.length){const e=Xs.findGroup(r,g.groupId)||r[0];en(g,e,"audioCodec"),en(g,e,"textCodec")}l.push(g)}}return s}static parseLevelPlaylist(e,t,i,r,s,n){const a=new Sr(t),o=a.fragments;let l,h,c,d=null,u=0,f=0,g=0,m=0,p=null,v=new Tr(r,t),y=-1,T=!1,E=null;for(qs.lastIndex=0,a.m3u8=e,a.hasVariableRefs=Ds(e);null!==(l=qs.exec(e));){T&&(T=!1,v=new Tr(r,t),v.start=g,v.sn=u,v.cc=m,v.level=i,d&&(v.initSegment=d,v.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null,E&&(v.setByteRange(E),E=null)));const e=l[1];if(e){v.duration=parseFloat(e);const t=(" "+l[2]).slice(1);v.title=t||null,v.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(Ji(v.duration)){v.start=g,c&&sn(v,c,a),v.sn=u,v.level=i,v.cc=m,o.push(v);const e=(" "+l[3]).slice(1);v.relurl=Cs(a,e),tn(v,p),p=v,g+=v.duration,u++,f=0,T=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);p?v.setByteRange(e,p):v.setByteRange(e)}else if(l[5])v.rawProgramDateTime=(" "+l[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===y&&(y=o.length);else{if(l=l[0].match(zs),!l){lr.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new dr(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const i=f>0?e[e.length-1]:void 0,r=f++,n=new dr(s);xs(a,n,["BYTERANGE","URI"]);const o=new Er(n,v,t,r,i);e.push(o),v.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new dr(s);xs(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new dr(s);xs(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:lr.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(tn(v,p),v.cc=m,a.fragmentHint=v,c&&sn(v,c,a));const S=o.length,b=o[0],L=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&L){a.averagetargetduration=g/S;const e=L.sn;a.endSN="initSegment"!==e?e:0,a.live||(L.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,y>0&&function(e,t){let i=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(o,y),a}}function Qs(e,t,i){var r,s;const n=new dr(e);xs(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,c=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&lr.error(`Invalid IV: ${n.IV}`);const d=o?Xs.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ks(a,d,c,u,l)}function Js(e){const t=new dr(e).decimalFloatingPoint("TIME-OFFSET");return Ji(t)?t:null}function Zs(e,t){let i=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const r=i.filter((t=>function(e,t){const i=Ms[t];return!!i&&!!i[e.slice(0,4)]}(t,e)));r.length&&(t[`${e}Codec`]=r.join(","),i=i.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=i}function en(e,t,i){const r=t[i];r&&(e[i]=r)}function tn(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Ji(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function rn(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function sn(e,t,i){e.levelkeys=t;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}var nn="manifest",an="level",on="audioTrack",ln="subtitleTrack",hn="main",cn="audio",dn="subtitle";function un(e){const{type:t}=e;switch(t){case on:return cn;case ln:return dn;default:return hn}}function fn(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class gn{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(tr.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(tr.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:nn,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:an,url:n,deliveryDirectives:a})}onAudioTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:on,url:s,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ln,url:s,deliveryDirectives:n})}load(e){var t;const i=this.hls.config;let r,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url&&t.level===e.level)return void lr.trace("[playlist-loader]: playlist request ongoing");lr.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===nn?i.manifestLoadPolicy.default:Qi({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),Ji(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===an&&null!==e.level?t=this.hls.levels[e.level].details:e.type===on&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ln&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);r=Qi({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Xs.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,i,r){const s=this.hls,n=e.data,a=fn(e,i),o=Xs.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,i,o.playlistParsingError,r,t);const{contentSteering:l,levels:h,sessionData:c,sessionKeys:d,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Xs.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(lr.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new dr({}),bitrate:0,url:""}))}s.trigger(tr.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:c,sessionKeys:d,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,r,s){const n=this.hls,{id:a,level:o,type:l}=i,h=fn(e,i),c=Ji(o)?o:Ji(a)?a:0,d=un(i),u=Xs.parseLevelPlaylist(e.data,h,c,d,0,this.variableList);if(l===nn){const e={attrs:new dr({}),bitrate:0,details:u,name:"",url:h};n.trigger(tr.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.MANIFEST_PARSING_ERROR,fatal:t.type===nn,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===an?n+=`: ${e.level} id: ${e.id}`:e.type!==on&&e.type!==ln||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);lr.warn(`[playlist-loader]: ${n}`);let o=rr.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case nn:o=i?rr.MANIFEST_LOAD_TIMEOUT:rr.MANIFEST_LOAD_ERROR,l=!0;break;case an:o=i?rr.LEVEL_LOAD_TIMEOUT:rr.LEVEL_LOAD_ERROR,l=!1;break;case on:o=i?rr.AUDIO_TRACK_LOAD_TIMEOUT:rr.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ln:o=i?rr.SUBTITLE_TRACK_LOAD_TIMEOUT:rr.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const c={type:ir.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){const i=(null==t?void 0:t.url)||e.url;c.response=qi({url:i,data:void 0},r)}this.hls.trigger(tr.ERROR,c)}handlePlaylistLoaded(e,t,i,r,s,n){const a=this.hls,{type:o,level:l,id:h,groupId:c,deliveryDirectives:d}=r,u=fn(t,r),f=un(r),g="number"==typeof r.level&&f===hn?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:e,reason:e.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m)a.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case nn:case an:a.trigger(tr.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:d});break;case on:a.trigger(tr.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:d});break;case ln:a.trigger(tr.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:d})}}}function mn(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function pn(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){lr.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){lr.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function vn(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function yn(e,t,i,r){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,i){const r=[],s=function(e,t){if(te[i].endTime)return-1;let r=0,s=i;for(;r<=s;){const n=Math.floor((s+r)/2);if(te[n].startTime&&r-1)for(let n=s,a=e.length;n=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(e.cues,t,i);for(let t=0;t{const e=Ln();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Rn(e,t){return e.getTime()/1e3-t}class kn{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(vn(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tAn&&(r=An);r-i<=0&&(r=i+.25);for(let e=0;ee.type===En&&o:"video"===r?e=>e.type===bn&&a:e=>e.type===En&&o||e.type===bn&&a,yn(s,t,i,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:s}=t,n=Object.keys(s);if(r){const e=Object.keys(i).filter((e=>!n.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(i[s].cues).forEach((e=>{r.removeCue(i[s].cues[e])})),delete i[s]}}const a=t.fragments[t.fragments.length-1];if(0===n.length||!Ji(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Ln();for(let e=0;e{if(t!==r.id){const i=s[t];if(i.class===r.class&&i.startDate>r.startDate&&(!e||r.startDatethis.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(null===e||null===t||null===i)return null;const r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(tr.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(tr.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===rr.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&lr.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,i))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const Dn=["NONE","TYPE-0","TYPE-1",null];const xn=["SDR","PQ","HLG"];var Cn="",In="YES",Pn="v2";function On(e){const{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r!!e)).map((e=>e.substring(0,4))).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Nn(this._audioGroups,e)}hasSubtitleGroup(e){return Nn(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Nn(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Un(e,t){const i=t.startPTS;if(Ji(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&(r.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function Bn(e,t,i,r,s,n){r-i<=0&&(lr.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);let a=i,o=r;const l=t.startPTS,h=t.endPTS;if(Ji(l)){const e=Math.abs(l-i);Ji(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,t.endDTS)}const c=i-t.start;0!==t.start&&(t.start=i),t.duration=r-t.start,t.startPTS=i,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;const d=t.sn;if(!e||de.endSN)return 0;let u;const f=d-e.startSN,g=e.fragments;for(g[f]=t,u=f;u>0;u--)Un(g[u],g[u-1]);for(u=f;u=0;e--){const t=r[e].initSegment;if(t){i=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,n=0;if(function(e,t,i){const r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=n;e++){const s=l[a+e];let n=o[e];r&&!n&&e{e.relurl&&(n=e.cc-r.cc),Ji(e.startPTS)&&Ji(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,e.initSegment&&(r.initSegment=e.initSegment,i=e.initSegment)})),i){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){lr.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){const r=Qi({},e);i&&i.forEach((e=>{delete r[e]}));return Object.keys(t).forEach((e=>{const i=new fr(t[e].attr,r[e]);i.isValid?r[e]=i:lr.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(n){lr.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?Bn(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Gn(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function Gn(e,t){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;i<0||i>=r.length||Kn(t,r[i].start)}function Kn(e,t){if(t){const i=e.fragments;for(let r=e.skippedSegments;r{const{details:i}=e;null!=i&&i.fragments&&i.fragments.forEach((e=>{e.level=t}))}))}function Wn(e){switch(e.details){case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_TIMEOUT:case rr.LEVEL_LOAD_TIMEOUT:case rr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Yn(e,t){const i=Wn(t);return e.default[(i?"timeout":"error")+"Retry"]}function qn(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function zn(e){return qi(qi({},e),{errorRetry:null,timeoutRetry:null})}function Xn(e,t,i,r){if(!e)return!1;const s=null==r?void 0:r.code,n=t499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}const Qn=function(e,t){let i=0,r=e.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=e[s];const a=t(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function Jn(e,t,i=0,r=0,s=.005){let n=null;if(e){n=t[e.sn-t[0].sn+1]||null;const r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Zn(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level0){const r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;const a=Qn(t,Zn.bind(null,i,r));return!a||a===e&&n?n:a}function Zn(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function ea(e,t,i){const r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}var ta=0,ia=2,ra=3,sa=5,na=0,aa=1,oa=2;class la{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=lr.log.bind(lr,`${t}:`),this.warn=lr.warn.bind(lr,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let i=0;i=0&&e>t.partTarget&&(a+=1)}const o=i&&On(i);return new Mn(n,a>=0?a:void 0,o)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:r,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=i&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&$n(i,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,c=s===n;-1!==h?(o=c?n+1:s,l=c?e?0:h:h+1):o=n+1;const d=r.age,u=d+r.ageHeader;let f=Math.min(u-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{const e=Math.floor(f/r.targetduration);if(o+=e,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${f} skip sn ${e} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l),e||!c)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,c=h?h.end-h.len:0,d=function(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const r=e.fragments,s=4;if(r.length&&i*s>t){const e=1e3*r[r.length-1].duration;ethis.requestScheduled+d&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+d-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+dthis.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let s=On(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=Cn),new Mn(i,r,s)}checkRetry(e){const t=e.details,i=Wn(e),r=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===sa||!r.resolved&&s===ia);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=qn(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}class ha{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ca{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ha(e),this.fast_=new ha(t),this.defaultTTFB_=r,this.ttfb_=new ha(e)}update(e,t){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new ha(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new ha(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new ha(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const da={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},ua={};function fa(e,t,i,r,s,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let c=null;if(null!=a&&a.length)try{c=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,i)=>{if(i){const r=t.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!c&&Ji(h)&&Object.keys(c).some((e=>parseInt(e)>h))}function ga(e,t,i){const r=e.videoCodec,s=e.audioCodec;if(!r||!s||!i)return Promise.resolve(da);const n={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},a=e.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=r.split(",").map((e=>({type:"media-source",video:qi(qi({},n),{},{contentType:Us(e,"video")})})));return s&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",i=parseFloat(e);Ji(i)&&i>2&&o.push.apply(o,s.split(",").map((e=>({type:"media-source",audio:{contentType:Us(e,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((e=>{const t=function(e){const{audio:t,video:i}=e,r=i||t;if(r){const e=r.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return ua[t]||(ua[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:o,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:o,decodingInfoResults:[],error:e})))}function ma(e,t){let i=!1,r=[];return e&&(i="SDR"!==e,r=[e]),t&&(r=t.allowedVideoRanges||xn.slice(0),i=void 0!==t.preferHDR?t.preferHDR:function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r=i?r.filter((e=>"SDR"!==e)):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function pa(e,t){lr.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function va(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r-1===r.indexOf(e)))}(o,t.characteristics))&&(void 0===i||i(e,t))}function Ta(e,t){const{audioCodec:i,channels:r}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function Ea(e,t,i){for(let r=t;r;r--)if(i(e[r]))return r;for(let r=t+1;r1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var ba="NOT_LOADED",La="APPENDING",wa="PARTIAL",Aa="OK";class Ra{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(tr.BUFFER_APPENDED,this.onBufferAppended,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.BUFFER_APPENDED,this.onBufferAppended,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let t=i.length;t--;){const r=i[t];if(!r)break;const s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,r=Object.keys(i);for(let s=r.length;s--;){const n=i[r[s]];if((null==n?void 0:n.body.type)===t&&n.buffered){const t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const n=this.fragments[r];if(!n)return;if(s>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===i&&this.removeFragment(n.body));const a=n.range[e];a&&a.time.some((e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:r}=e;if(!t||"initSegment"===i.sn)return;const s=_a(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const a=!i.relurl;if(Object.keys(t).forEach((e=>{const s=i.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;n.range[e]=this.getBufferedTimes(i,r,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ka(n)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const i=_a(e);let r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){const s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e=t&&o<=i){s.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(nt){const t=Math.max(n,r.start(e)),i=Math.min(a,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&ka(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||ka(t))}getState(e){const t=_a(e),i=this.fragments[t];return i?i.buffered?ka(i)?wa:Aa:La:ba}isTimeBuffered(e,t,i){let r,s;for(let n=0;n=r&&t<=s)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:r}=t;if("initSegment"===i.sn||i.bitrateTest)return;const s=r?null:t,n=_a(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:r,timeRanges:s}=t;if("initSegment"===i.sn)return;const n=i.type;if(r){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(r)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,n,r)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_a(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.starte&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=_a(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=i.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function ka(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function _a(e){return`${e.type}_${e.level}_${e.sn}`}const Da={length:0,start:()=>0,end:()=>0};class xa{static isBuffered(e,t){try{if(e){const i=xa.getBuffered(e);for(let e=0;e=i.start(e)&&t<=i.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,i){try{if(e){const r=xa.getBuffered(e),s=[];let n;for(n=0;nn&&(r[s-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let s,n=0,a=t,o=t;for(let e=0;e=l&&ti.startCC||e&&e.cc{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o($a(e));e.gap=!1}const l=this.loader=e.loader=s?new s(r):new n(r),h=Ba(e),c=zn(r.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Na};e.stats=l.stats,l.load(h,d,{onSuccess:(t,i,r,s)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,r,s,n)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:qi({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,i,r)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(i,r,s,n)=>{t&&t({frag:e,part:null,payload:s,networkDetails:n})}})}))}loadPart(e,t,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o($a(e,t));const l=this.loader=e.loader=s?new s(r):new n(r),h=Ba(e,t),c=zn(r.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Na};t.stats=l.stats,l.load(h,d,{onSuccess:(r,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:qi({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(e,t){const i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Ba(e,t=null){const i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(Ji(s)&&Ji(n)){var a;let t=s,i=n;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=n-s;e%16&&(i=n+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}return r}function $a(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:ir.MEDIA_ERROR,details:rr.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Ga(r)}class Ga extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ka{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class Va{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Ha{constructor(){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()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],c=o[2],d=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,d[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,r=0;for(;r{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ka(this.subtle,new Uint8Array(i)).decrypt(e.buffer,t)})).catch((r=>(lr.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i))))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=Nr(e,0,i),this.remainderData=Nr(e,i)),t}logOnce(e){this.logEnabled&&(lr.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Wa=function(e){let t="";const i=e.length;for(let r=0;ra.end){const e=n>s;(n{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const i=this.state;this.fragContextChanged(e)?(i===Xa||!this.fragCurrent&&i===Za)&&(this.fragmentTracker.removeFragment(e),this.state=qa):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(tr.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==Ya&&this.state!==io&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===La){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(s))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===wa&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:i};this.hls.trigger(tr.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:i}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((t=>{throw i.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{const s=self.performance.now();return i.trigger(tr.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:n,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((t=>{this.state!==Ya&&this.state!==io&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=qa,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,s,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===hn?"level":"track"} ${e.level} (frag:[${(null!=(i=e.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?Wa(xa.getBuffered(a)):"(detached)"})`),"initSegment"!==e.sn){var o;if(e.type!==dn){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=qa)}const t=null==(o=this.levels)?void 0:o[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=qa,a&&(!this.loadedmetadata&&e.type==hn&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:r,partsLoaded:s}=e,n=!s||0===s.length||s.some((e=>!e)),a=new Ca(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=za,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(tr.KEY_LOADED,e),this.state===za&&(this.state=qa),e})),this.hls.trigger(tr.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=n.partList;if(s&&r){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(s,e,i);if(o>-1){const l=s[o];let h;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Xa,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(tr.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),Ji(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Xa;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?r:void 0),a]).then((([e])=>(!o&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(tr.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,i,r){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const n=r.part;this.hls.trigger(tr.FRAG_LOADED,r);const a=Vn(i,e.sn,t.index+1)||Hn(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===rr.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(tr.ERROR,t)}else this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Za)return void(this.fragCurrent||this.state===Ya||this.state===io||(this.state=qa));const{frag:i,part:r,level:s}=t,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(i,r,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=n>-1?Vn(a,s,n):null,l=o?o.fragment:function(e,t,i){if(null==e||!e.details)return null;const r=e.details;let s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===t?s:tn&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return Ji(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:r}}=this,s=xa.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&s.nextStart=i&&(t.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=hn){const i=this.fragmentTracker.getAppendedFrag(e,hn);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start;let a;if(t.live){const o=s.initialLiveManifestSize;if(rt}getNextFragmentLoopLoading(e,t,i,r,s){const n=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,n&&e&&!e.gap&&i.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==t&&i.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,n=!0;for(let a=0,o=e.length;a-1&&ii.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!Ji(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r=e.startSN&&s<=e.endSN){const n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(e,t){return Qn(e,(e=>e.cct?-1:0))}(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,h=i.partList,c=!!(r.lowLatencyMode&&null!=h&&h.length&&o);let d;if(c&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),et-l?0:l)}else d=n[n.length-1];if(d){const e=d.sn-i.startSN,t=this.fragmentTracker.getState(d);if((t===Aa||t===wa&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!c||h[0].fragment.sn>d.sn)){if(s&&d.level===s.level){const t=n[e+1];d=d.sn=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${r}`),n}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;if(i ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=t.details===rr.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const n=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===sa&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=qn(l,o);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Qa}else if(l&&n){if(this.resetFragmentErrors(e),!(o.5;r&&this.reduceMaxBufferLength(i.len);const s=!r;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===cn&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Ya&&(this.state=qa)}afterBufferFlushed(e,t,i){if(!e)return;const r=xa.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===to&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=qa}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var s;const n=i.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=r?0:Bn(n,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(tr.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=eo,this.hls.trigger(tr.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class ao{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let r=0;for(let t=0;t0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:En,duration:Number.POSITIVE_INFINITY});s{if(Ji(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};function co(e,t){return 255===e[t]&&240==(246&e[t+1])}function uo(e,t){return 1&e[t+1]?7:9}function fo(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function go(e,t){return t+1=e.length)return!1;const r=fo(e,t);if(r<=i)return!1;const s=t+r;return s===e.length||go(e,s)}return!1}function po(e,t,i,r,s){if(!e.samplerate){const n=function(e,t,i,r){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=r,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[i+2])>>>6);const d=(60&t[i+2])>>>2;if(!(d>c.length-1))return a=(1&t[i+2])<<2,a|=(192&t[i+3])>>>6,lr.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,o=new Array(4),n=d-3):(s=2,o=new Array(2),n=d):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=d):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&d>=6?n=d-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(d>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),n=d)),o[0]=s<<3,o[0]|=(14&d)>>1,o[1]|=(1&d)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h};{const t=new Error(`invalid ADTS sampling index:${d}`);e.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}}(t,i,r,s);if(!n)return;e.config=n.config,e.samplerate=n.samplerate,e.channelCount=n.channelCount,e.codec=n.codec,e.manifestCodec=n.manifestCodec,lr.log(`parsed codec:${e.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function vo(e){return 9216e4/e}function yo(e,t,i,r,s){const n=r+s*vo(e.samplerate),a=function(e,t){const i=uo(e,t);if(t+i<=e.length){const r=fo(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,h=Math.max(0,i+l-t.length);h?(o=new Uint8Array(l-s),o.set(t.subarray(i+s,t.length),0)):o=t.subarray(i+s,i+l);const c={unit:o,pts:n};return h||e.samples.push(c),{sample:c,length:l,missing:h}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let To=null;const Eo=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],So=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],bo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Lo=[0,1,1,4];function wo(e,t,i,r,s){if(i+24>t.length)return;const n=Ao(t,i);if(n&&i+n.frameLength<=t.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Ao(e,t){const i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Eo[14*(3===i?3-r:3===r?3:4)+s-1],h=So[3*(3===i?0:2===i?1:2)+n],c=3===o?1:2,d=bo[i][r],u=Lo[r],f=8*d*u,g=Math.floor(d*l/h+a)*u;if(null===To){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);To=e?parseInt(e[1]):0}return!!To&&To<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Ro(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function ko(e,t){return t+1{let i=0,r=5;t+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<>l,i=i?i<t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=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*o+n];if(i+l>t.length)return-1;const h=t[i+6]>>5;let c=0;2===h?c+=2:(1&h&&1!==h&&(c+=2),4&h&&(c+=2));const d=(t[i+6]<<8|t[i+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}class Po{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,r=i.length;if(!r)return void t.dropped++;{const t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&lr.log(e.pts+"/"+e.dts+":"+e.debug)}}class Oo{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&lr.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,i=8,r=8;for(let s=0;s{var n;switch(r.type){case 1:{let t=!1;a=!0;const s=r.data;if(l&&s.length>4){const e=new Oo(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=t;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Ls(r.data,1,i.pts,t.samples);break;case 7:{var c,d;a=!0,l=!0;const t=r.data,i=new Oo(t).readSPS();if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(c=e.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(d=e.pixelRatio)?void 0:d[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t],e.duration=s;const r=t.subarray(1,4);let n="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break}case 8:a=!0,e.pps=[r.data];break;case 9:a=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let r=e.naluState||0;const s=r,n=[];let a,o,l,h=0,c=-1,d=0;for(-1===r&&(c=0,d=31&t[0],r=0,h=1);h=0){const e={data:t.subarray(c,o),type:d};n.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(s&&h<=4-s&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-s)),o>0&&(i.data=Es(i.data,t.subarray(0,o)),i.state=0))}h=0&&r>=0){const e={data:t.subarray(c,i),type:d,state:r};n.push(e)}if(0===n.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=Es(i.data,t))}return e.naluState=r,n}}class Fo{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ja(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let r=0;for(let t=32;t{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}))}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();const s=e[t].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}}}const No=188;class Uo{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new Mo}static probe(e){const t=Uo.syncOffset(e);return t>0&&lr.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let i=Math.min(940,t-No)+1,r=0;for(;r1&&(0===n&&a>2||o+No>i))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ss[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Uo.createTrack("video"),this._audioTrack=Uo.createTrack("audio",r),this._id3Track=Uo.createTrack("id3"),this._txtTrack=Uo.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,c=n.pesData,d=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Es(this.remainderData,e)).length,this.remainderData=null),y>4>1){if(E=t+5+e[t+4],E===t+No)continue}else E=t+4;switch(y){case h:r&&(c&&(s=Ho(c))&&this.videoParser.parseAVCPES(n,l,s,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,t+No)),c.size+=t+No-E);break;case d:if(r){if(f&&(s=Ho(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+No)),f.size+=t+No-E);break;case u:r&&(g&&(s=Ho(g))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+No)),g.size+=t+No-E);break;case 0:r&&(E+=e[E]+1),v=this._pmtId=$o(e,E);break;case v:{r&&(E+=e[E]+1);const s=Go(e,E,this.typeSupported,i,this.observer);h=s.videoPid,h>0&&(n.pid=h,n.segmentCodec=s.segmentVideoCodec),d=s.audioPid,d>0&&(a.pid=d,a.segmentCodec=s.segmentAudioCodec),u=s.id3Pid,u>0&&(o.pid=u),null===m||p||(lr.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,t=T-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else E++;E>0&&Ko(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`)),n.pesData=c,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:r,textTrack:s}=e,n=i.pesData,a=t.pesData,o=r.pesData;let l;if(n&&(l=Ho(n))?(this.videoParser.parseAVCPES(i,s,l,!0,this._duration),i.pesData=null):i.pesData=n,a&&(l=Ho(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&lr.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Ho(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,i){const r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new Fo(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)}))}))}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const r=this.aacOverFlow;let s,n,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t)o=Es(r.sample.unit,o);else{const n=s-t;r.sample.unit.set(o.subarray(0,t),n),e.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void lr.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=Qi({},t,{type:this._videoTrack?bn:En,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Bo(e,t){return((31&e[t+1])<<8)+e[t+2]}function $o(e,t){return(31&e[t+10])<<8|e[t+11]}function Go(e,t,i,r,s){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0){let r=t+5,s=o;for(;s>2;){if(106===e[r])!0!==i.ac3?lr.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return Ko(s,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return Ko(s,new Error("Unsupported HEVC in M2TS found")),n}t+=o+5}return n}function Ko(e,t,i){lr.warn(`parsing error: ${t.message}`),e.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function Vo(e){lr.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ho(e){let t,i,r,s,n,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Es(o[0],o[1]),o.splice(1,1);t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(i=(t[4]<<8)+t[5],i&&i>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-n>54e5&&(lr.warn(`${Math.round((s-n)/9e4)}s delta between PTS and DTS, align them`),s=n)):n=s),r=t[8];let h=r+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,i=o.length;ei){h-=i;continue}t=t.subarray(h),i-=h,h=0}c.set(t,a),a+=i}return i&&(i-=r+3),{data:c,pts:s,dts:n,len:i}}return null}class jo{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Wo=Math.pow(2,32)-1;class Yo{static init(){let e;for(e in Yo.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Yo.types)Yo.types.hasOwnProperty(e)&&(Yo.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Yo.HDLR_TYPES={video:t,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Yo.STTS=Yo.STSC=Yo.STCO=s,Yo.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Yo.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Yo.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Yo.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Yo.FTYP=Yo.box(Yo.types.ftyp,n,o,n,a),Yo.DINF=Yo.box(Yo.types.dinf,Yo.box(Yo.types.dref,r))}static box(e,...t){let i=8,r=t.length;const s=r;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return Yo.box(Yo.types.mdia,Yo.mdhd(e.timescale,e.duration),Yo.hdlr(e.type),Yo.minf(e))}static mfhd(e){return Yo.box(Yo.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Yo.box(Yo.types.minf,Yo.box(Yo.types.smhd,Yo.SMHD),Yo.DINF,Yo.stbl(e)):Yo.box(Yo.types.minf,Yo.box(Yo.types.vmhd,Yo.VMHD),Yo.DINF,Yo.stbl(e))}static moof(e,t,i){return Yo.box(Yo.types.moof,Yo.mfhd(e),Yo.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Yo.trak(e[t]);return Yo.box.apply(null,[Yo.types.moov,Yo.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(Yo.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Yo.trex(e[t]);return Yo.box.apply(null,[Yo.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Wo+1)),r=Math.floor(t%(Wo+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Yo.box(Yo.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let r,s;for(r=0;r>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=Yo.box(Yo.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return Yo.box(Yo.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,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Yo.box(Yo.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yo.box(Yo.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Yo.box(Yo.types.mp4a,Yo.audioStsd(e),Yo.box(Yo.types.esds,Yo.esds(e)))}static mp3(e){return Yo.box(Yo.types[".mp3"],Yo.audioStsd(e))}static ac3(e){return Yo.box(Yo.types["ac-3"],Yo.audioStsd(e),Yo.box(Yo.types.dac3,e.config))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?Yo.box(Yo.types.stsd,Yo.STSD,Yo.mp3(e)):"ac3"===e.segmentCodec?Yo.box(Yo.types.stsd,Yo.STSD,Yo.ac3(e)):Yo.box(Yo.types.stsd,Yo.STSD,Yo.mp4a(e)):Yo.box(Yo.types.stsd,Yo.STSD,Yo.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,r=e.width,s=e.height,n=Math.floor(i/(Wo+1)),a=Math.floor(i%(Wo+1));return Yo.box(Yo.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const i=Yo.sdtp(e),r=e.id,s=Math.floor(t/(Wo+1)),n=Math.floor(t%(Wo+1));return Yo.box(Yo.types.traf,Yo.box(Yo.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Yo.box(Yo.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),Yo.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Yo.box(Yo.types.trak,Yo.tkhd(e),Yo.mdia(e))}static trex(e){const t=e.id;return Yo.box(Yo.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,h,c,d;for(t+=8+s,n.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*a);return Yo.box(Yo.types.trun,n)}static initSegment(e){Yo.types||Yo.init();const t=Yo.moov(e);return Es(Yo.FTYP,t)}}Yo.types=void 0,Yo.HDLR_TYPES=void 0,Yo.STTS=void 0,Yo.STSC=void 0,Yo.STCO=void 0,Yo.STSZ=void 0,Yo.VMHD=void 0,Yo.SMHD=void 0,Yo.STSD=void 0,Yo.FTYP=void 0,Yo.DINF=void 0;const qo=9e4;function zo(e,t,i=1,r=!1){const s=e*t*i;return r?Math.round(s):s}function Xo(e,t=!1){return zo(e,1e3,1/qo,t)}let Qo,Jo=null,Zo=null;class el{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===Jo){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jo=e?parseInt(e[1]):0}if(null===Zo){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Zo=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){lr.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){lr.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){lr.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce(((e,i)=>{const r=i.pts-e;return r<-4294967296?(t=!0,tl(e,i.pts)):r>0?e:i.pts}),e[0].pts);return t&&lr.debug("PTS rollover detected"),i}remux(e,t,i,r,s,n,a,o){let l,h,c,d,u,f,g=s,m=s;const p=e.pid>-1,v=t.pid>-1,y=t.samples.length,T=e.samples.length>0,E=a&&y>0||y>1;if((!p||T)&&(!v||E)||this.ISGenerated||a){if(this.ISGenerated){var S,b,L,w;const e=this.videoTrackConfig;!e||t.width===e.width&&t.height===e.height&&(null==(S=t.pixelRatio)?void 0:S[0])===(null==(b=e.pixelRatio)?void 0:b[0])&&(null==(L=t.pixelRatio)?void 0:L[1])===(null==(w=e.pixelRatio)?void 0:w[1])||this.resetInitSegment()}else c=this.generateIS(e,t,s,n);const i=this.isVideoContiguous;let r,a=-1;if(E&&(a=function(e){for(let t=0;t0){lr.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,r=m}else-1===a&&(lr.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const i=this.getVideoStartPts(t.samples),r=(tl(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(e.samplerate||(lr.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||E||o===cn?m:void 0),E){const r=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(lr.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,i,r)}}else E&&(l=this.remuxVideo(t,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=il(i,s,this._initPTS,this._initDTS)),r.samples.length&&(d=rl(r,s,this._initPTS))),{audio:h,video:l,initSegment:c,independent:f,text:d,id3:u}}generateIS(e,t,i,r){const s=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,c,d,u=!l||r,f="audio/mp4";if(u&&(h=c=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Yo.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(d=e.inputTimeScale,l&&d===l.timescale?u=!1:h=c=s[0].pts-Math.round(d*i))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Yo.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(d=t.inputTimeScale,l&&d===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Math.round(d*i);c=Math.min(c,tl(n[0].dts,e)-t),h=Math.min(h,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:d},this._initDTS={baseTime:c,timescale:d}):h=d=void 0,{tracks:o,initPTS:h,timescale:d}}remuxVideo(e,t,i,r){const s=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let h,c,d=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||null===d){const e=t*s,r=n[0].pts-tl(n[0].dts,n[0].pts);Jo&&null!==d&&Math.abs(e-r-d)<15e3?i=!0:d=e-r}const v=l.baseTime*s/l.timescale;for(let e=0;e0?e-1:e].dts&&(p=!0)}p&&n.sort((function(e,t){const i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),h=n[0].dts,c=n[n.length-1].dts;const y=c-h,T=y?Math.round(y/(o-1)):f||e.inputTimeScale/30;if(i){const e=h-d,i=e>T,r=e<-1;if((i||r)&&(i?lr.warn(`AVC: ${Xo(e,!0)} ms (${e}dts) hole between fragments detected at ${t.toFixed(3)}`):lr.warn(`AVC: ${Xo(-e,!0)} ms (${e}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||d>=n[0].pts||Jo)){h=d;const t=n[0].pts-e;if(i)n[0].dts=h,n[0].pts=t;else for(let i=0;it);i++)n[i].dts-=e,n[i].pts-=e;lr.log(`Video: Initial PTS/DTS adjusted: ${Xo(t,!0)}/${Xo(h,!0)}, delta: ${Xo(e,!0)} ms`)}}h=Math.max(0,h);let E=0,S=0,b=h;for(let e=0;e0?t.dts-n[e-1].dts:T;if(l=e>0?t.pts-n[e-1].pts:T,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(i.maxBufferHole*s),n=(r?g+r*s:this.nextAudioPts)-t.pts;n>e?(f=n-a,f<0?f=a:R=!0,lr.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const c=Math.round(t.pts-t.dts);k=Math.min(k,f),D=Math.max(D,f),_=Math.min(_,l),x=Math.max(x,l),a.push(new sl(t.key,f,h,c))}if(a.length)if(Jo){if(Jo<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Zo&&x-_0&&(r&&Math.abs(p-m)<9e3||Math.abs(tl(f[0].pts-v,p)-m)<20*l),f.forEach((function(e){e.pts=tl(e.pts-v,p)})),!i||m<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;m=0===s?0:r&&!u?Math.max(0,p):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,r=m;i=t*l&&h<1e4&&u){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===i&&(this.nextAudioPts=m=r),lr.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;S+=g;try{y=new Uint8Array(S)}catch(e){return void this.observer.emit(tr.ERROR,tr.ERROR,{type:ir.MUX_ERROR,details:rr.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!c){new DataView(y.buffer).setUint32(0,S),y.set(Yo.types.mdat,4)}}y.set(s,g);const l=s.byteLength;g+=l,d.push(new sl(!0,o,l,0)),E=n}const L=d.length;if(!L)return;const w=d[d.length-1];this.nextAudioPts=m=E+a*w.duration;const A=c?new Uint8Array(0):Yo.moof(e.sequenceNumber++,T/a,Qi({},e,{samples:d}));e.samples=[];const R=T/n,k=m/n,_={data1:A,data2:y,startPTS:R,endPTS:k,startDTS:R,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,_}remuxEmptyAudio(e,t,i,r){const s=e.inputTimeScale,n=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*s)+l,c=r.endDTS*s+l,d=1024*n,u=Math.ceil((c-h)/d),f=jo.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(lr.warn("[mp4-remuxer]: remux empty Audio"),!f)return void lr.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let e=0;e4294967296;)e+=i;return e}function il(e,t,i,r){const s=e.samples.length;if(!s)return;const n=e.inputTimeScale;for(let a=0;ae.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}class sl{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}function nl(e,t){const i=null==e?void 0:e.codec;if(i&&i.length>4)return i;if(t===mr){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Vs(i,!1)}const e="mp4a.40.5";return lr.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${e}"`),e}return lr.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{Qo=self.performance.now.bind(self.performance)}catch(e){lr.debug("Unable to use Performance API on this environment"),Qo=null==Ar?void 0:Ar.Date.now}const al=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){const s=this.videoTrack=oo("video",1),n=this.audioTrack=oo("audio",1),a=this.txtTrack=oo("text",1);if(this.id3Track=oo("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=fs(e);if(o.video){const{id:e,timescale:t,codec:i}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=i}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=ss.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Es(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=ds(e,["moof"]);if(i.length<2)return t.remainder=e,t;const r=i[i.length-1];return t.valid=Nr(e,0,r.byteOffset-8),t.remainder=Nr(e,r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,t);return s.samples=Ss(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return i.samples=Ss(e,t),{videoTrack:t,audioTrack:oo(),id3Track:r,textTrack:oo()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const r=ds(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==ns(e.subarray(h,h+1));)i+=ns(e.subarray(h,h+1)),h+=1;for(i+=ns(e.subarray(h,h+1)),h+=1;"\0"!==ns(e.subarray(h,h+1));)r+=ns(e.subarray(h,h+1)),h+=1;r+=ns(e.subarray(h,h+1)),h+=1,s=os(e,12),n=os(e,16),o=os(e,20),l=os(e,24),h=28}else if(1===t){h+=4,s=os(e,h),h+=4;const t=os(e,h);h+=4;const n=os(e,h);for(h+=4,a=2**32*t+n,Zi(a)||(a=Number.MAX_SAFE_INTEGER,lr.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=os(e,h),h+=4,l=os(e,h),h+=4;"\0"!==ns(e.subarray(h,h+1));)i+=ns(e.subarray(h,h+1)),h+=1;for(i+=ns(e.subarray(h,h+1)),h+=1;"\0"!==ns(e.subarray(h,h+1));)r+=ns(e.subarray(h,h+1)),h+=1;r+=ns(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Do.test(r.schemeIdUri)){const e=Ji(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale;let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:bn,duration:s})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;const i=t.keyId;i&&t.isCommonEncryption&&ds(e,["moov","trak"]).forEach((e=>{const t=ds(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=ds(t,["enca"]);const s=r.length>0;s||(r=ds(t,["encv"])),r.forEach((e=>{ds(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=ys(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(lr.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${ts(e)} -> ${ts(i)}`),t.set(i,8))}}))}))}));return e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=fs(e);r.audio&&(t=nl(r.audio,mr)),r.video&&(i=nl(r.video,pr));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:lr.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,r,s,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};Ji(h)||(h=this.lastEndTime=s||0);const d=t.samples;if(null==d||!d.length)return c;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return lr.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t){let i=0,r=0,s=0;const n=ds(e,["moof","traf"]);for(let e=0;ee+t.info.duration||0),0);i=Math.max(i,e+n.earliestPresentationTime/n.timescale),r=i-t}}if(r&&Ji(r))return r}return r||s}(d,f),m=function(e,t){return ds(t,["moof","traf"]).reduce(((t,i)=>{const r=ds(i,["tfdt"])[0],s=r[0],n=ds(i,["tfhd"]).reduce(((t,i)=>{const n=os(i,4),a=e[n];if(a){let e=os(r,4);if(1===s){if(e===is)return lr.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=is+1,e+=os(r,8)}const i=e/(a.timescale||9e4);if(Ji(i)&&(null===t||is}(l,p,s,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-s,l&&1===l.timescale&&lr.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const v=e?p-l.baseTime/l.timescale:h,y=v+g;!function(e,t,i){ds(t,["moof","traf"]).forEach((t=>{ds(t,["tfhd"]).forEach((r=>{const s=os(r,4),n=e[s];if(!n)return;const a=n.timescale||9e4;ds(t,["tfdt"]).forEach((e=>{const t=e[0],r=i*a;if(r){let i=os(e,4);if(0===t)i-=r,i=Math.max(i,0),cs(e,4,i);else{i*=Math.pow(2,32),i+=os(e,8),i-=r,i=Math.max(i,0);const t=Math.floor(i/(is+1)),s=Math.floor(i%(is+1));cs(e,4,t),cs(e,8,s)}}}))}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(lr.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!f.audio,E=!!f.video;let S="";T&&(S+="audio"),E&&(S+="video");const b={data1:d,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:T,hasVideo:E,nb:1,dropped:0};return c.audio="audio"===b.type?b:void 0,c.video="audio"!==b.type?b:void 0,c.initSegment=u,c.id3=il(i,s,l,l),r.samples.length&&(c.text=rl(r,s,l)),c}}},{demux:Uo,remux:el},{demux:class extends lo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=$r(e,0);let i=(null==t?void 0:t.length)||0;if(_o(e,i))return!1;for(let t=e.length;i0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(T&&"AES-128"===T.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer).then((e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(n,T.key.buffer,T.iv.buffer);if(i.part>-1&&(t=e.flush()),!t)return s.executeEnd=Qo(),ll(i);n=new Uint8Array(t)}}const E=this.needsProbing(h,c);if(E){const e=this.configureTransmuxer(n);if(e)return lr.warn(`[transmuxer] ${e.message}`),this.observer.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=Qo(),ll(i)}(h||c||f||E)&&this.resetInitSegment(y,g,m,v,t),(h||f||E)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,T,u,d,i),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,s.executeEnd=Qo(),S}flush(e){const t=e.transmuxing;t.executeStart=Qo();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const n=[],{timeOffset:a}=r;if(i){const t=i.flush();t&&n.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=Qo(),[ll(e)];const h=o.flush(a);return hl(h)?h.then((t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),n)}flushRemux(e,t,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;lr.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Qo()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s),n}transmuxUnencrypted(e,t,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:r,vendor:s}=this;let n;for(let t=0,i=al.length;t({remuxResult:{},chunkMeta:e});function hl(e){return"then"in e&&e.then instanceof Function}class cl{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class dl{constructor(e,t,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}var ul={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s{(t=t||{}).frag=this.frag,t.id=this.id,e===tr.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new fl,this.observer.on(tr.FRAG_DECRYPTED,n),this.observer.on(tr.ERROR,n);const a=Os(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(lr.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(lr.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const i=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,lr.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},e.postMessage({cmd:"init",typeSupported:o,vendor:"",id:t,config:JSON.stringify(s)})}catch(e){lr.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new ol(this.observer,o,s,"",t)}return}}this.transmuxer=new ol(this.observer,o,s,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,s,n,a,o,l,h){var c,d;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:s.start,g=s.decryptdata,m=this.frag,p=!(m&&s.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,E=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===T||E&&T<=0)),b=self.performance.now();(v||y||0===s.stats.parsing.start)&&(s.stats.parsing.start=b),!n||!T&&S||(n.stats.parsing.start=b);const L=!(m&&(null==(c=s.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),w=new dl(p,S,o,v,f,L);if(!S||p||L){lr.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${L}`);const e=new cl(i,r,t,a,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:w},e instanceof ArrayBuffer?[e]:[]);else if(u){const t=u.push(e,g,l,w);hl(t)?(u.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);hl(i)||t.async?(hl(i)||(i=Promise.resolve(i)),i.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(null==t||!t.event)return void lr.warn("worker message received with no "+(t?"event name":"data"));const i=this.hls;if(this.hls)switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":lr[t.data.logType]&&lr[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function ml(e,t){if(e.length!==t.length)return!1;for(let i=0;ie[i]!==t[i]))}function vl(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class yl{constructor(e){this.buffered=void 0;const t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}class Tl{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise((e=>{t=e})),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){lr.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${t}`),i.onError(t);const r=this.buffers[e];null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const El=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Sl(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}
+/**
+ *
+ * This code was ported from the dash.js project at:
+ * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
+ * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
+ *
+ * The original copyright appears below:
+ *
+ * The copyright in this software is being made available under the BSD License,
+ * included below. This software may be subject to other third party and contributor
+ * rights, including patent rights, and no such rights are granted under this license.
+ *
+ * Copyright (c) 2015-2016, DASH Industry Forum.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation and/or
+ * other materials provided with the distribution.
+ * 2. Neither the name of Dash Industry Forum nor the names of its
+ * contributors may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+const bl={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ll=e=>String.fromCharCode(bl[e]||e),wl=15,Al=100,Rl={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},kl={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_l={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Dl={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Cl{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;lr.log(`${this.time} [${e}] ${i}`)}}}const Il=function(e){const t=[];for(let i=0;iAl&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Al)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e=144&&this.backSpace();const t=Ll(e);this.pos>=Al?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",r=-1;for(let i=0;i0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class Nl{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Fl(i),this.nonDisplayedMemory=new Fl(i),this.lastOutputScreen=new Fl(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;tt+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Ul{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Cl;this.channels=[null,new Nl(e,t,r),new Nl(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e"["+Il([t[e],t[e+1]])+"] -> ("+Il([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if($l(i,r,a)){Bl(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Il([i,r])+") is dropped"));continue}Bl(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else Bl(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Il([i,r])+" orig: "+Il([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+Il([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;i=t>=64&&t<=95?1===r?Rl[e]:_l[e]:1===r?kl[e]:Dl[e];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(()=>"Special char '"+Ll(e)+"' in channel "+i)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes = "+Il(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=xl[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Kl=function(){if(null!=Ar&&Ar.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e,...t){let i=1;for(;i100)throw new Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return E},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return b},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Vl{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Hl(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class jl{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r=0&&i<=100)return this.set(e,i),!0}return!1}}function Wl(e,t,i,r){const s=r?e.split(r):[e];for(const e in s){if("string"!=typeof s[e])continue;const r=s[e].split(i);if(2!==r.length)continue;t(r[0],r[1])}}const Yl=new Kl(0,0,""),ql="middle"===Yl.align?"middle":"center";function zl(e,t,i){const r=e;function s(){const t=Hl(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){const r=new jl;Wl(e,(function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",ql,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",ql,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",ql,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===Yl.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",ql);let n=r.get("position","auto");"auto"===n&&50===Yl.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Xl(e){return e.replace(/
/gi,"\n")}class Ql{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Vl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Xl(e);i>>0).toString()};function th(e,t,i){return eh(e.toString())+eh(t.toString())+eh(i)}function ih(e,t,i,r,s,n,a){const o=new Ql,l=Jr(new Uint8Array(e)).trim().replace(Jl,"\n").split("\n"),h=[],c=t?function(e,t=1){return zo(e,qo,1/t)}(t.baseTime,t.timescale):0;let d,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=i[r];let a=i.ccOffset;const o=(f-c)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,u=tl(9e4*(e.startTime+a-g),9e4*s)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=th(e.startTime,e.endTime,m)),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){d=e},o.onflush=function(){d?a(d):n(h)},l.forEach((e=>{if(m){if(Zl(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{Zl(e,"LOCAL:")?u=e.slice(6):Zl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Ji(t)&&Ji(i)&&Ji(r)&&Ji(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s,t}(u)/1e3}catch(e){d=e}return}""===e&&(m=!1)}o.parse(e+"\n")})),o.flush()}const rh="stpp.ttml.im1t",sh=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ah={left:"start",center:"center",right:"end",start:"start",end:"end"};function oh(e,t,i,r){const s=ds(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((e=>Jr(e))),a=function(e,t,i=1,r=!1){return zo(e,t,1/i,r)}(t.baseTime,1,t.timescale);try{n.forEach((e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==r.getAttribute("xml:space"),o=hh(lh(r,"styling","style")),l=hh(lh(r,"layout","region")),h=lh(r,"body","[begin]");return[].map.call(h,(e=>{const i=ch(e,a);if(!i||!e.hasAttribute("begin"))return null;const r=fh(e.getAttribute("begin"),n),s=fh(e.getAttribute("dur"),n);let h=fh(e.getAttribute("end"),n);if(null===r)throw uh(e);if(null===h){if(null===s)throw uh(e);h=r+s}const c=new Kl(r-t,h-t,i);c.id=th(c.startTime,c.endTime,c.text);const d=function(e,t,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=dh(t,r,n)||dh(e,r,n)||dh(s,r,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=d;if(u){const e=ah[u];e&&(c.lineAlign=e),c.align=u}return Qi(c,d),c})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function lh(e,t,i){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function hh(e){return e.reduce(((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function ch(e,t){return[].slice.call(e.childNodes).reduce(((e,i,r)=>{var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?ch(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function dh(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function uh(e){return new Error(`Could not parse ttml timestamp ${e}`)}function fh(e,t){if(!e)return null;let i=Hl(e);return null===i&&(sh.test(e)?i=function(e,t){const i=sh.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):nh.test(e)&&(i=function(e,t){const i=nh.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}function gh(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function mh(e,t){return!!e&&e.kind===gh(t)&&vl(t,e)}class ph{constructor(e){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=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(tr.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(tr.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Ji(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&lr.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter(((t,i)=>this.isLevelAllowed(t)&&i<=e));return this.clientRect=null,ph.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let r=e.length-1;const s=Math.max(t,i);for(let t=0;t=s||i.height>=s)&&(n=i,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){r=t;break}}var n,a;return r}}const vh="[eme]";class yh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=yh.CDMCleanupPromise?[yh.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=lr.debug.bind(lr,vh),this.log=lr.log.bind(lr,vh),this.warn=lr.warn.bind(lr,vh),this.error=lr.error.bind(lr,vh),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(tr.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(tr.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===Rr.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(i),s=t.map((e=>e.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):i(t instanceof Th?t:new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Mr&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){const r=function(e,t,i,r){let s;switch(e){case Rr.FAIRPLAY:s=["cenc","sinf"];break;case Rr.WIDEVINE:case Rr.PLAYREADY:s=["cenc"];break;case Rr.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ts(e.keyId||[])}`);const r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return ts(e.keyId)}updateKeySession(e,t){var i;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${ts((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,i)=>{const r=Or(this.config),s=e.map(Cr).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=Pr(e);r?t(r):i(new Error(`Unable to find format for key-system "${e}"`))})).catch(i)}))}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Th?this.hls.trigger(tr.ERROR,e.data):this.hls.trigger(tr.ERROR,{type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Cr(e.keyFormat),i=t?[t]:Or(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Or(this.config)),0===e.length)throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===i)return;let r,s;if("sinf"===t&&this.config.drmSystems[Rr.FAIRPLAY]){const e=ns(new Uint8Array(i));try{const t=br(JSON.parse(e).sinf),i=ys(new Uint8Array(t));if(!i)return;r=i.subarray(8,24),s=Rr.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},i=new DataView(e),r=i.getUint32(0);if(e.byteLength!==r&&r>44)return null;if(1886614376!==i.getUint32(4))return null;if(t.version=i.getUint32(8)>>>24,t.version>1)return null;t.systemId=ts(new Uint8Array(e,12,16));const s=i.getUint32(28);if(0===t.version){if(r-32this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new ks("ISO-23001-7",n,null!=(a=Pr(e))?a:"");return o.pssh=new Uint8Array(i),o.keyId=r,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;const a=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,t,i,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const h=new fl,c=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{this.handleError(e),h.emit("error",e)})):"license-release"===r?e.keySystem===Rr.FAIRPLAY&&(this.updateKeySession(e,wr("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",d);const u=new Promise(((e,t)=>{h.on("error",t),h.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).catch((t=>{throw h.removeAllListeners(),this.removeSession(e),t})).then((()=>(h.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${ts("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ts(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,o)=>{n(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:qi({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{n(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((r,s)=>{e.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i in key message");return wr(atob(l))}setupLicenseXHR(e,t,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)})).then((i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==Rr.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ks.clearKeyUriToKeyIdMap();const i=t.length;yh.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((e=>{this.log(`Could not clear media keys: ${e}`)})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((e=>{this.log(`Could not close sessions and clear media keys: ${e}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}yh.CDMCleanupPromise=void 0;class Th extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var Eh,Sh,bh;!function(e){e.MANIFEST="m",e.AUDIO="a",e.VIDEO="v",e.MUXED="av",e.INIT="i",e.CAPTION="c",e.TIMED_TEXT="tt",e.KEY="k",e.OTHER="o"}(Eh||(Eh={})),function(e){e.DASH="d",e.HLS="h",e.SMOOTH="s",e.OTHER="o"}(Sh||(Sh={})),function(e){e.OBJECT="CMCD-Object",e.REQUEST="CMCD-Request",e.SESSION="CMCD-Session",e.STATUS="CMCD-Status"}(bh||(bh={}));const Lh={[bh.OBJECT]:["br","d","ot","tb"],[bh.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[bh.SESSION]:["cid","pr","sf","sid","st","v"],[bh.STATUS]:["bs","rtp"]};class wh{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map((e=>e instanceof wh?e:new wh(e)))),this.value=e,this.params=t}}class Ah{constructor(e){this.description=void 0,this.description=e}}const Rh="Dict";function kh(e,t,i,r){return new Error(`failed to ${e} "${s=t,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}const _h="Bare Item",Dh="Boolean",xh="Byte Sequence",Ch="Decimal",Ih="Integer";const Ph=/[\x00-\x1f\x7f]+/,Oh="Token",Mh="Key";function Fh(e,t,i){return kh("serialize",e,t,i)}function Nh(e){if(!1===ArrayBuffer.isView(e))throw Fh(e,xh);return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function Uh(e){if(function(e){return e<-999999999999999||99999999999999912)throw Fh(e,Ch);const i=t.toString();return i.includes(".")?i:`${i}.0`}const Gh="String";function Kh(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Fh(t,Oh);return t}function Vh(e){switch(typeof e){case"number":if(!Ji(e))throw Fh(e,_h);return Number.isInteger(e)?Uh(e):$h(e);case"string":return function(e){if(Ph.test(e))throw Fh(e,Gh);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Kh(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fh(e,Dh);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Uh(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Nh(e);if(e instanceof Ah)return Kh(e);default:throw Fh(e,_h)}}function Hh(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fh(e,Mh);return e}function jh(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${Hh(e)}`:`;${Hh(e)}=${Vh(t)}`)).join("")}function Wh(e){return e instanceof wh?`${Vh(e.value)}${jh(e.params)}`:Vh(e)}function Yh(e,t={whitespace:!0}){if("object"!=typeof e)throw Fh(e,Rh);const i=e instanceof Map?e.entries():Object.entries(e),r=null!=t&&t.whitespace?" ":"";return Array.from(i).map((([e,t])=>{t instanceof wh==!1&&(t=new wh(t));let i=Hh(e);var r;return!0===t.value?i+=jh(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(r=t).value.map(Wh).join(" ")})${jh(r.params)}`:i+=Wh(t)),i})).join(`,${r}`)}const qh=e=>"ot"===e||"sf"===e||"st"===e,zh=e=>"number"==typeof e?Ji(e):null!=e&&""!==e&&!1!==e;const Xh=e=>Math.round(e),Qh=e=>100*Xh(e/100),Jh={br:Xh,d:Xh,bl:Qh,dl:Qh,mtp:Qh,nor:(e,t)=>(null!=t&&t.baseUrl&&(e=function(e,t){const i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:Qh,tb:Xh};function Zh(e,t={}){return e?function(e,t){return Yh(e,t)}(function(e,t){const i={};if(null==e||"object"!=typeof e)return i;const r=Object.keys(e).sort(),s=Qi({},Jh,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return r.forEach((r=>{if(null!=n&&n(r))return;let a=e[r];const o=s[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||zh(a)&&(qh(r)&&"string"==typeof a&&(a=new Ah(a)),i[r]=a)})),i}(e,t),Qi({whitespace:!1},t)):""}function ec(e,t,i){return Qi(e,function(e,t={}){if(!e)return{};const i=Object.entries(e),r=Object.entries(Lh).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),s=i.reduce(((e,t)=>{var i;const[s,n]=t,a=(null==(i=r.find((e=>e[1].includes(s))))?void 0:i[0])||bh.REQUEST;return null!=e[a]||(e[a]={}),e[a][s]=n,e}),{});return Object.entries(s).reduce(((e,[i,r])=>(e[i]=Zh(r,t),e)),{})}(t,i))}const tc="CMCD";const ic=/CMCD=[^]+/;function rc(e,t,i){const r=function(e,t={}){if(!e)return"";const i=Zh(e,t);return`${tc}=${encodeURIComponent(i)}`}(t,i);if(!r)return e;if(ic.test(e))return e.replace(ic,r);const s=e.includes("?")?"&":"?";return`${e}${s}${r}`}function sc(e,t,i,r){e&&Object.keys(t).forEach((s=>{const n=e.filter((e=>e.groupId===s)).map((e=>{const n=Qi({},e);return n.details=void 0,n.attrs=new dr(n.attrs),n.url=n.attrs.URI=nc(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function nc(e,t,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}const ac=/^age:\s*[\d.]+\s*$/im;class oc{constructor(e){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=e&&e.xhrSetup||null,this.stats=new gr,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&Ji(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,n="text"!==t.responseType;if(r>=200&&r<300&&(n&&t.response||null!==t.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const s=n?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(i,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,i,e,t)}else{const n=s.loadPolicy.errorRetry;Xn(n,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(n):(lr.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Xn(e,this.stats.retry,!0))this.retry(e);else{var t;lr.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=qn(e,i.retry),i.retry++,lr.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ac.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const lc=/(\d+)-(\d+)\/(\d+)/;class hc{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||cc,this.controller=new self.AbortController,this.stats=new gr}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Qi({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n=i.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&Ji(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),h-(o-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new dc(t||"fetch, bad network response",e,s)}return r.loading.first=o,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=lc.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ji(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total,n&&Ji(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,n):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[o];l&&(r.loaded=r.total=l);const h={url:a.url,data:s,code:a.status};n&&!Ji(t.highWaterMark)&&n(r,e,s,a),i.onSuccess(h,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,n=t?t.message:null;i.onError({code:s,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){const n=new ao,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h=r&&s(t,i,n.flush(),e)):s(t,i,l,e),o()})).catch((()=>Promise.reject()));return o()}}function cc(e,t){return new self.Request(e.url,t)}class dc extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const uc=/\s/,fc={newCue(e,t,i,r){const s=[];let n,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const r=Xl(h.trim()),f=th(t,i,r);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(a=new c(t,i,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>pn(e,t)))),s}},gc=qi(qi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,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,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:oc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:r,media:s}=i;if(!e||!s)return;const n=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=n-a.loading.start,h=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||e.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;const c=i.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const f=c.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),v=i.levels,y=v[e.level],T=a.total||Math.max(a.loaded,Math.round(o*y.averageBitrate/8));let E=m?l-g:l;E<1&&m&&(E=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/E:0,b=S?(T-a.loaded)/S:8*T/p+d/1e3;if(b<=f)return;const L=S?8*S:p;let w,A=Number.POSITIVE_INFINITY;for(w=e.level-1;w>h;w--){const e=v[w].maxBitrate;if(A=this.getTimeToLoadFrag(d/1e3,L,o*e,!v[w].details),A=b)return;if(A>10*o)return;i.nextLoadLevel=i.nextAutoLevel=w,m?this.bwEstimator.sample(l-Math.min(d,g),a.loaded):this.bwEstimator.sampleTTFB(l);const R=v[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>R&&this.resetEstimator(R),this.clearTimer(),lr.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${A.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${Ji(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${w} @ ${0|R} bps`),i.trigger(tr.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(lr.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ca(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.FRAG_LOADING,this.onFragLoading,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.FRAG_LOADING,this.onFragLoading,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(tr.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case rr.BUFFER_ADD_CODEC_ERROR:case rr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case rr.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,i,r){return e+i/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:r}=t.stats,s=r.end-r.start;Ji(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const r=i?i.stats:t.stats;if(t.type===hn&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(tr.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==hn||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return lr.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,r,l,0,h,c);if(e>=0)return e}let d=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){d=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,lr.info(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=c=1}}const u=this.findBestLevel(o,n,r,l,d,h,c);if(lr.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=i.levels[n],g=i.levels[i.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,s,n,a){var o;const l=r+s,h=this.lastLoadedFragLevel,c=-1===h?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==v||null==(o=v.details)||!o.live),T=-1===m||-1===h;let E,S="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:w}=p,A=this.audioTracksByGroup||(this.audioTracksByGroup=function(e){return e.reduce(((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(((e,i)=>{if(!i.codecSet)return e;const r=i.audioGroups;let s=e[i.codecSet];s||(e[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);const n=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach((e=>{if(!e)return;const i=t.groups[e];i&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{s.channels[e]=(s.channels[e]||0)+i.channels[e]})))})),e}),{})}(f,A,t,i)),s=function(e,t,i,r,s){const n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=a&&2===parseInt(a);let h=!0,c=!1,d=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=ma(t,s);for(let t=n.length;t--;){const i=e[n[t]];h=i.channels[2]>0,d=Math.min(d,i.minHeight),u=Math.min(u,i.minFramerate),f=Math.min(f,i.minBitrate);const r=v.filter((e=>i.videoRanges[e]>0));r.length>0&&(c=!0,m=r)}d=Ji(d)?d:0,u=Ji(u)?u:0;const y=Math.max(1080,d),T=Math.max(30,u);return f=Ji(f)?f:i,i=Math.max(f,i),c||(t=void 0,m=[]),{codecSet:n.reduce(((t,r)=>{const s=e[r];if(r===t)return t;if(s.minBitrate>i)return pa(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return pa(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return pa(r,`audio codec preference "${o}" not found`),t;if(a&&!l){if(!s.channels[a])return pa(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||l)&&h&&0===s.channels[2])return pa(r,"no renditions with stereo sound found"),t;return s.minHeight>y?(pa(r,`min resolution of ${s.minHeight} > maximum of ${y}`),t):s.minFramerate>T?(pa(r,`min framerate of ${s.minFramerate} > maximum of ${T}`),t):m.some((e=>s.videoRanges[e]>0))?s.maxScore=$s(t)||s.fragmentError>e[t].fragmentError)?t:(g=s.maxScore,r):(pa(r,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),t)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}(r,S,e,L,w),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=s;E=n,S=h?a[a.length-1]:a[0],b=o,e=Math.max(e,l),lr.log(`[abr] picked start tier ${JSON.stringify(s)}`)}else E=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const R=u?u.duration:d?d.duration:0,k=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let o=i;o>=t;o--){var D;const t=f[o],d=o>c;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&fa(t,A,S,b,e,L)?(t.supportedPromise=ga(t,A,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,r=i.indexOf(t);e.error?lr.warn(`[abr] MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${JSON.stringify(e)}`):e.supported||(lr.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(e)}`),r>-1&&i.length>1&&(lr.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))}))):t.supportedResult=da}if(E&&t.codecSet!==E||S&&t.videoRange!==S||d&&b>t.frameRate||!d&&b>0&&b=2*R&&0===s?f[o].averageBitrate:f[o].maxBitrate,I=this.getTimeToLoadFrag(k,x,C*w,void 0===g);if(x>=C&&(o===h||0===t.loadError&&0===t.fragmentError)&&(I<=k||!Ji(I)||y&&!this.bitrateTestDelay||I${o} adjustedbw(${Math.round(x)})-bitrate=${Math.round(x-C)} ttfb:${k.toFixed(1)} avgDuration:${w.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${I.toFixed(1)} firstSelection:${T} codecSet:${E} videoRange:${S} hls.loadLevel:${m}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=e=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;this.log("Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(tr.MEDIA_ATTACHED,{media:e,mediaSource:t})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&lr.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e;const t="[buffer-controller]";var i;this.appendSource=(i=Os(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.log=lr.log.bind(lr,t),this.warn=lr.warn.bind(lr,t),this.error=lr.error.bind(lr,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.BUFFER_RESET,this.onBufferReset,this),e.on(tr.BUFFER_APPENDING,this.onBufferAppending,this),e.on(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.on(tr.BUFFER_EOS,this.onBufferEos,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(tr.FRAG_PARSED,this.onFragParsed,this),e.on(tr.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.BUFFER_RESET,this.onBufferReset,this),e.off(tr.BUFFER_APPENDING,this.onBufferAppending,this),e.off(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.off(tr.BUFFER_EOS,this.onBufferEos,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(tr.FRAG_PARSED,this.onFragParsed,this),e.off(tr.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Tl(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,r=Os(this.appendSource);if(i&&r){var s;const e=this.mediaSource=new r;this.log(`created media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));const t=this._objectUrl=self.URL.createObjectURL(e);if(this.appendSource)try{i.removeAttribute("src");const r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&e instanceof r,Sl(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Sl(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(tr.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{this.resetBuffer(e)})),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{var i;if(t)this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach((e=>{if(i){const i=this.tracks[e];if(i&&"function"==typeof i.buffer.changeType){var r;const{id:s,codec:n,levelCodec:a,container:o,metadata:l}=t[e],h=Hs(i.codec,i.levelCodec),c=null==h?void 0:h.replace(El,"$1");let d=Hs(n,a);const u=null==(r=d)?void 0:r.replace(El,"$1");if(d&&c!==u){"audio"===e.slice(0,5)&&(d=Vs(d,this.appendSource));const t=`${o};codecs=${d}`;this.appendChangeType(e,t),this.log(`switching codec ${h} to ${d}`),this.tracks[e]={buffer:i.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:s}}}}else this.pendingTracks[e]=t[e]})),i)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,r={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:r,tracks:s}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=t,c=h.buffering[a],d=self.performance.now();c.start=d;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=d),f&&0===f.start&&(f.start=d);const g=s.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,v={execute:()=>{if(c.executeStart=self.performance.now(),m){const e=this.sourceBuffer[a];if(e){const t=p-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===u.first&&(u.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,i={};for(const e in t)i[e]=xa.getBuffered(t[e]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(tr.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:i})},onError:e=>{const t={type:ir.MEDIA_ERROR,parent:o.type,details:rr.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=rr.BUFFER_FULL_ERROR;else{const e=++this.appendErrors[a];t.details=rr.BUFFER_APPEND_ERROR,this.warn(`Failed ${e}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),e>=i.config.appendErrorMaxRetry&&(t.fatal=!0)}i.trigger(tr.ERROR,t)}};r.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(e,t){const{operationQueue:i}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(tr.BUFFER_FLUSHED,{type:e})},onError:t=>{this.warn(`Failed to remove from ${e} SourceBuffer`,t)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{i.append(r(e),e)}))}onFragParsed(e,t){const{frag:i,part:r}=t,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[vr]?s.push("audiovideo"):(n[mr]&&s.push("audio"),n[pr]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:i.stats;this.hls.trigger(tr.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})}),s)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,i)=>{const r=this.sourceBuffer[i];return!r||t.type&&t.type!==i||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${i} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.getSourceBufferTypes().length)return;const r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(Ji(a)&&a>0){const e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}if(Ji(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const e=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),t=Math.max(e,n),i=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(e,t,i){const{details:r,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((n=>{const a=s[n];if(a){const s=xa.getBuffered(a);if(s.length>0&&i>s.start(0)){if(this.hls.trigger(tr.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=r&&r.live)this.hls.trigger(tr.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&s.end(s.length-1)-e<2*t)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(tr.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}}))}flushFrontBuffer(e,t,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((s=>{const n=r[s];if(n){const r=xa.getBuffered(n),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(i>o||e>=o&&e<=l)return;if(n.ended&&e-l<2*t)return void this.log(`Cannot flush ${s} front buffer while SourceBuffer is in ended state`);this.hls.trigger(tr.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:i,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,n=i.duration,a=Ji(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>n||!Ji(n))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&null!=t&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),s=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${s}.`),t.setLiveSeekableRange(r,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(tr.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!t[s]){var r;const n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===s.slice(0,5)&&(a=Vs(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const e=t[s]=i.addSourceBuffer(o),r=s;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",((e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(tr.BUFFER_FLUSHED,{type:s})})),this.tracks[s]={buffer:e,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(e){this.error(`error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o})}}}get mediaSrc(){var e;const t=(null==(e=this.media)?void 0:e.firstChild)||this.media;return null==t?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(r)}removeExecutor(e,t,i){const{media:r,mediaSource:s,operationQueue:n,sourceBuffer:a}=this,o=a[e];if(!r||!s||!o)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(e);const l=Ji(r.duration)?r.duration:1/0,h=Ji(s.duration)?s.duration:1/0,c=Math.max(0,t),d=Math.min(i,l,h);d>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${d}] from the ${e} SourceBuffer`),o.remove(c,d)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(i)i.ended=!1,i.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:i}=this,r=t.map((e=>i.appendBlocker(e)));Promise.all(r).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const r=this.sourceBuffer[e];if(!r)return;const s=i.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:ph,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=lr.log.bind(lr,"[info]:"),this.warn=lr.warn.bind(lr,"[warning]:"),this.error=lr.error.bind(lr,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(tr.ERROR,this.onError,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(tr.ERROR,this.onError,this),e.off(tr.ERROR,this.onErrorOut,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===hn?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case rr.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction={action:ta,flags:na});case rr.FRAG_GAP:case rr.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ia);case rr.LEVEL_EMPTY_ERROR:case rr.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===hn?t.level:s.loadLevel;t.details===rr.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case rr.LEVEL_LOAD_ERROR:case rr.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case rr.AUDIO_TRACK_LOAD_ERROR:case rr.AUDIO_TRACK_LOAD_TIMEOUT:case rr.SUBTITLE_LOAD_ERROR:case rr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const e=s.levels[s.loadLevel];if(e&&(n.type===on&&e.hasAudioGroup(n.groupId)||n.type===ln&&e.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=ia,void(t.errorAction.flags=aa)}return;case rr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],i=null==e?void 0:e.attrs["HDCP-LEVEL"];i?t.errorAction={action:ia,flags:oa,hdcpLevel:i}:this.keySystemError(t)}return;case rr.BUFFER_ADD_CODEC_ERROR:case rr.REMUX_ALLOC_ERROR:case rr.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case rr.INTERNAL_EXCEPTION:case rr.BUFFER_APPENDING_ERROR:case rr.BUFFER_FULL_ERROR:case rr.LEVEL_SWITCH_ERROR:case rr.BUFFER_STALLED_ERROR:case rr.BUFFER_SEEK_OVER_HOLE:case rr.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:ta,flags:na})}t.type===ir.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=Yn(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Xn(i,r,Wn(e),e.response))return{action:sa,flags:na,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=Yn(e.details.startsWith("key")?n:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){e.details!==rr.FRAG_GAP&&r.fragmentError++;if(Xn(a,o,Wn(e),e.response))return{action:sa,flags:na,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const r=this.hls.levels[t];if(r){var s,n;const t=e.details;r.loadError++,t===rr.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:c,minAutoLevel:d,maxAutoLevel:u}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(s=e.frag)?void 0:s.type,g=(f===cn&&t===rr.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===rr.BUFFER_ADD_CODEC_ERROR||t===rr.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>r.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===rr.BUFFER_ADD_CODEC_ERROR||t===rr.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let i=h.length;i--;){const s=(i+c)%h.length;if(s!==c&&s>=d&&s<=u&&0===h[s].loadError){var a,o;const i=h[s];if(t===rr.FRAG_GAP&&f===hn&&e.frag){const t=h[s].details;if(t){const i=Jn(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(p===on&&i.hasAudioGroup(v)||p===ln&&i.hasSubtitleGroup(v))continue;if(f===cn&&null!=(a=r.audioGroups)&&a.some((e=>i.hasAudioGroup(e)))||f===dn&&null!=(o=r.subtitleGroups)&&o.some((e=>i.hasSubtitleGroup(e)))||g&&r.audioCodec===i.audioCodec||!g&&r.audioCodec!==i.audioCodec||m&&r.codecSet===i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:ia,flags:na,nextAutoLevel:l}}return{action:ia,flags:aa}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case ta:break;case ia:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===rr.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case na:this.switchLevel(e,n);break;case oa:s&&(t.maxHdcpLevel=Dn[Dn.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(e){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=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,s=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(tr.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;lr.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(tr.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},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:Mr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,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}}},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:fc,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:class extends no{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",dn),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.ERROR,this.onError,this),e.on(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(tr.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(tr.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.ERROR,this.onError,this),e.off(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(tr.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(tr.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=qa,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:r}=t;if(this.fragPrevious=i,this.state=qa,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let e=0;e=s[e].start&&a<=s[e].end){n=s[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:r}=t;if(0===i&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;inew Fn(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Fn(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,dn),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=t;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,Kn(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Fa(n,e),l=n.fragments[0].start):t&&(l=t.start,Kn(n,l))}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===qa)){Jn(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=performance.now();s.trigger(tr.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=qa}))}}doTick(){if(this.media){if(this.state===qa){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:r}=this,s=this.getLoadPosition(),n=xa.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,hn),h=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const c=h.fragments,d=c.length,u=h.edge;let f=null;const g=this.fragPrevious;if(au-e?0:e;f=Jn(g,c,Math.max(c[0].start,a),t),!f&&g&&g.startthis.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=Tn(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(tr.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Tn(this.media.textTracks).forEach((e=>{vn(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;const i=va(t,e);if(i>-1)s=e[i];else{const e=va(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(tr.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r-1){const e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(i)return null;{const i=va(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(tr.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Tn(e.textTracks),i=this.currentTrack;let r;if(i&&(r=t.filter((e=>vl(i,e)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==r&&(e.mode="disabled")})),r){const e=this.subtitleDisplay?"showing":"hidden";r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!Ji(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(tr.SUBTITLE_TRACK_SWITCH,{id:e});const s=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=r;this.hls.trigger(tr.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const c=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(c)}},timelineController:class{constructor(e){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={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.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}},e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(tr.FRAG_LOADING,this.onFragLoading,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this),e.on(tr.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(tr.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(tr.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(tr.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(tr.FRAG_LOADING,this.onFragLoading,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this),e.off(tr.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(tr.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(tr.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(tr.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Gl(this,"textTrack1"),t=new Gl(this,"textTrack2"),i=new Gl(this,"textTrack3"),r=new Gl(this,"textTrack4");this.cea608Parser1=new Ul(1,e,t),this.cea608Parser2=new Ul(3,i,r)}}addCues(e,t,i,r,s){let n=!1;for(let e=s.length;e--;){const r=s[e],c=(a=r[0],o=r[1],l=t,h=i,Math.min(o,h)-Math.max(a,l));if(c>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),n=!0,c/(i-t)>.5))return}var a,o,l,h;if(n||s.push([t,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{const s=this.Cues.newCue(null,t,i,r);this.hls.trigger(tr.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){const{unparsedVttFrags:n}=this;"main"===i&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(tr.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let r=0;r{vn(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;ee.textCodec===rh));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(ml(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Tn(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let r;if(t){let i=null;for(let r=0;rnull!==e)).map((e=>e.label));e.length&&lr.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(tr.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===hn){var i,r;const{cea608Parser1:e,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:r}=t;if(i.type===dn)if(r.byteLength){const e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===rh?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;oh(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{lr.log(`Failed to parse IMSC1: ${t}`),i.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(e);const o=this.hls;ih(null!=(t=i.initSegment)&&t.data?Es(i.initSegment.data,new Uint8Array(r)):r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),o.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?n.push(e):this._fallbackToIMSC1(i,r),lr.log(`Failed to parse VTT cue: ${t}`),s&&a>i.cc||o.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||oh(t,this.initPTS[e.cc],(()=>{i.textCodec=rh,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>pn(i,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;i.trigger(tr.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===dn&&this.onFragLoaded(tr.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:s,samples:n}=t;if(s.type!==hn||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;eyn(e[r],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((i=>yn(e[i],t,r)))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let r=2;for(let s=0;s0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=qa):(this.loadedmetadata=!1,this.state=Ja),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case qa:this.doTickIdle();break;case Ja:{var e;const{levels:t,trackId:i}=this,r=null==t||null==(e=t[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=ro}break}case Qa:{var t;const e=performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=qa}break}case ro:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Xa;const e={frag:t,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),i=xa.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Zn(i.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=qa}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=qa)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:r}=this,s=e.config;if(!i&&(this.startFragRequested||!s.startFragPrefetch)||null==t||!t[r])return;const n=t[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Ja);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,mr,cn));const l=this.getFwdBufferInfo(o,cn);if(null===l)return;const{bufferedTrack:h,switchingTrack:c}=this;if(!c&&this._streamEnded(l,a))return e.trigger(tr.BUFFER_EOS,{type:"audio"}),void(this.state=to);const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,hn),u=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(c&&i){const e=this.getLoadPosition();h&&!pl(c.attrs,h.attrs)&&(p=e),a.PTSKnown&&em||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(u>=f&&!c&&pd.end+a.targetduration;if(T||(null==d||!d.len)&&l.len){const e=this.getAppendedFrag(v.start,hn);if(null===e)return;if(y||(y=!!e.gap||!!T&&0===d.len),T&&!y||y&&l.nextStart&&l.nextStartnew Fn(e)))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=qa,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Ya),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(tr.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:r}=this,{details:s,id:n}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=r[n];let o=0;if(s.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(s);const e=this.mainDetails;if(s.deltaUpdateFailed||!e)return;var l;if(!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime)Fa(s,e),o=s.fragments[0].start;else o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,o),this.state!==Ja||this.waitForCdnTuneIn(s)||(this.state=qa),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:s}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new gl(this.hls,cn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=r?r.index:-1,n=-1!==t,a=new Ca(i.level,i.sn,i.stats.chunkCount,s.byteLength,t,n);d.push(s,f,c,"",i,r,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new ao,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=ro}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i.type===cn)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(tr.AUDIO_TRACK_SWITCHED,qi({},e)))}this.fragBufferedComplete(i,r)}else if(!this.loadedmetadata&&i.type===hn){const e=this.videoBuffer||this.media;if(e){xa.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var i;if(t.fatal)this.state=io;else switch(t.details){case rr.FRAG_GAP:case rr.FRAG_PARSING_ERROR:case rr.FRAG_DECRYPT_ERROR:case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(cn,t);break;case rr.AUDIO_TRACK_LOAD_ERROR:case rr.AUDIO_TRACK_LOAD_TIMEOUT:case rr.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Ja||(null==(i=t.context)?void 0:i.type)!==on||(this.state=qa);break;case rr.BUFFER_APPEND_ERROR:case rr.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===rr.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case rr.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==pr&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==pr){this.flushing=!1,this.bufferFlushed=!0,this.state===to&&(this.state=qa);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,cn),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:c}=h,{audio:d,text:u,id3:f,initSegment:g}=s;if(!this.fragContextChanged(o)&&c){if(this.state=Za,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,g.tracks,e,n),r.trigger(tr.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=d;l&&(l.elementaryStreams[mr]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(mr,e,t,i,r),this.bufferFragmentData(d,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=Qi({id:i,frag:o,details:c},f);r.trigger(tr.FRAG_PARSING_METADATA,e)}if(u){const e=Qi({id:i,frag:o,details:c},u);r.trigger(tr.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,r){if(this.state!==Za)return;t.video&&delete t.video;const s=t.audio;if(!s)return;s.id="audio";const n=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(tr.BUFFER_CODECS,t);const a=s.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(tr.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);var s;if(this.fragCurrent=e,this.switchingTrack||r===ba||r===wa)if("initSegment"===e.sn)this._loadInitSegment(e,t);else if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ro;const i=this.mainDetails;i&&i.fragments[0].start!==t.details.fragments[0].start&&Fa(t.details,i)}else this.startFragRequested=!0,super.loadFragment(e,t,i);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,r=null==i?void 0:i.attrs,s=e.attrs;t&&r&&(r.CHANNELS!==s.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(tr.AUDIO_TRACK_SWITCHED,qi({},e))}},audioTrackController:class extends la{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(tr.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!s&&t){const i=va(t,e,Ta);if(i>-1)s=e[i];else{const e=va(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(tr.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&(t.context.type!==on||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||(this.requestScheduled=-1,this.checkRetry(t)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&ya(e,r,Ta))return r;const s=va(e,this.tracksInGroup,Ta);if(s>-1){const e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);const s=function(e,t,i,r,s){const n=t[r],a=t.reduce(((e,t,i)=>{const r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),c=Ea(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return va(e,n,s)>-1}));return c>-1?c:Ea(t,r,(t=>{const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return va(e,n,s)>-1}))}(e,t.levels,i,r,Ta);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){const t=va(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(tr.AUDIO_TRACK_SWITCHING,qi({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Eh.MANIFEST,su:!this.initialized})}catch(e){lr.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,i=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};r!==Eh.VIDEO&&r!==Eh.AUDIO&&r!=Eh.MUXED||(s.br=i.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){lr.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();const i="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}));return i}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHED,this.onMediaDetached,this),e.on(tr.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHED,this.onMediaDetached,this),e.off(tr.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:Sh.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Qi(t,this.createData());const i=t.ot===Eh.INIT||t.ot===Eh.VIDEO||t.ot===Eh.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,i)=>(r.includes(i)&&(e[i]=t[i]),e)),{})),this.useHeaders?(e.headers||(e.headers={}),ec(e.headers,t)):e.url=rc(e.url,t)}getObjectType(e){const{type:t}=e;return"subtitle"===t?Eh.TIMED_TEXT:"initSegment"===e.sn?Eh.INIT:"audio"===t?Eh.AUDIO:"main"===t?this.hls.audioTracks.length?Eh.VIDEO:Eh.MUXED:void 0}getTopBandwidth(e){let t,i=0;const r=this.hls;if(e===Eh.AUDIO)t=r.audioTracks;else{const e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}for(const e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){const t=this.hls.media,i=e===Eh.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*xa.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}},contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=lr.log.bind(lr,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((null==i?void 0:i.action)===ia&&i.flags===aa){const e=this.levels;let r=this.pathwayPriority,s=this.pathwayId;if(t.context){const{groupId:i,pathwayId:r,type:n}=t.context;i&&e?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=e.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),i.resolved||lr.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((e=>{r-i[e]>3e5&&delete i[e]}));for(let r=0;r0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,jn(t),this.hls.trigger(tr.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new dr(e.attrs);t["PATHWAY-ID"]=s;const n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);const l=nc(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Fn({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t{this.log(`Loaded steering manifest: "${r}"`);const n=e.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(tr.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}});function mc(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(mc):Object.keys(e).reduce(((t,i)=>(t[i]=mc(e[i]),t)),{}):e}function pc(e){const t=e.loader;if(t!==hc&&t!==oc)lr.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=hc,e.progressive=!0,e.enableSoftwareAES=!0,lr.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let vc;class yc extends la{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t,h;const c=e.attrs;let{audioCodec:d,videoCodec:u}=e;-1!==(null==(t=d)?void 0:t.indexOf("mp4a.40.34"))&&(vc||(vc=/chrome|firefox/i.test(navigator.userAgent)),vc&&(e.audioCodec=d=void 0)),d&&(e.audioCodec=d=Vs(d,i)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=e.videoCodec=function(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}(u));const{width:f,height:g,unknownCodecs:m}=e;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!d),null!=m&&m.length||d&&!Fs(d,"audio",i)||u&&!Fs(u,"video",i))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":T,RESOLUTION:E,"VIDEO-RANGE":S}=c,b=`${`${T||"."}-`}${e.bitrate}-${E}-${v}-${p}-${S}-${y}`;if(s[b])if(s[b].uri===e.url||e.attrs["PATHWAY-ID"])s[b].addGroupId("audio",c.AUDIO),s[b].addGroupId("text",c.SUBTITLES);else{const t=n[b]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=new Fn(e);s[b]=i,r.push(i)}else{const t=new Fn(e);s[b]=t,n[b]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}filterAndSortMediaOptions(e,t,i,r,s){let n=[],a=[],o=e;if((i||r)&&s&&(o=o.filter((({videoCodec:e,videoRange:t,width:i,height:r})=>{return(!!e||!(!i||!r))&&(!!(s=t)&&xn.indexOf(s)>-1);var s}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));if(t.audioTracks){const{preferManagedMediaSource:e}=this.hls.config;n=t.audioTracks.filter((t=>!t.audioCodec||Fs(t.audioCodec,"audio",e))),Tc(n)}t.subtitles&&(a=t.subtitles,Tc(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return xn.indexOf(e.videoRange)-xn.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Bs(e.videoCodec),r=Bs(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=$s(e.codecSet),r=$s(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;ei&&i===gc.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const d=s&&!r,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:!d&&n.some((e=>!!e.url))};this.hls.trigger(tr.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&n.details&&r&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${s?" with Pathway "+s:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(tr.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===an&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===hn){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:r,details:s}=t,n=this._levels[r];var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,t,n.details)):null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const s=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${s?" Pathway "+s:""} ${r}`),this.clearTimer(),this.hls.trigger(tr.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));jn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(tr.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(tr.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Tc(e){const t={};e.forEach((e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}class Ec{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=rr.KEY_LOAD_ERROR,i,r,s){return new Ga({type:ir.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let e=0;e{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=new(0,i.loader)(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,rr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,qi({url:a.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}function Sc(){return self.SourceBuffer||self.WebKitSourceBuffer}function bc(){if(!Os())return!1;const e=Sc();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Lc{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:s}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==e){if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){const e=self.performance.now()-s;lr.warn(`playback not stuck anymore @${n}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!xa.getBuffered(r).length)return void(this.nudgeRetry=0);const h=xa.bufferInfo(r,n,0),c=h.nextStart||0;if(a){const e=h.len>2,i=!c||t&&t.start<=n||c-n>2&&!this.fragmentTracker.getPartialFragment(n);if(e||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var d;if(!(h.len>0)&&!c)return;const e=Math.max(c,h.start||0)-n,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==t||null==(d=t.details)?void 0:d.live)?2*t.details.targetduration:2,s=this.fragmentTracker.getPartialFragment(n);if(e>0&&(e<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const u=self.performance.now();if(null===s)return void(this.stalled=u);const f=u-s;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=xa.bufferInfo(r,n,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:s}=this;if(null===s)return;const n=s.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-n1e3*i.highBufferWatchdogPeriod&&(lr.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);lr.warn(r.message),t.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(null===r)return 0;const s=r.currentTime,n=xa.bufferInfo(r,s,0),a=s0&&n.len<1&&r.readyState<3,h=a-s;if(h>0&&(o||l)){if(h>t.maxBufferHole){const{fragmentTracker:t}=this;let i=!1;if(0===s){const e=t.getAppendedFrag(0,hn);e&&a1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=qa,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Ya}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case so:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=qa;break}if(this.hls.nextLoadLevel!==this.level){this.state=qa;break}break}case Qa:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,i=null==e?void 0:e[t];this.resetStartWhenNotLoaded(i||null),this.state=qa}}}this.state===qa&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=e.nextLoadLevel;if(null==i||!i[s])return;const n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(tr.BUFFER_EOS,e),void(this.state=to)}e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=n.details;if(!l||this.state===so||l.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=so);const h=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==Aa){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,d)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?mr:pr,t=(e===pr?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,hn)}u=this.getNextFragmentLoopLoading(u,l,a,hn,c)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===ba||r===wa?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,hn)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case za:case Xa:case Qa:case Za:case eo:this.state=qa}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Lc(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;Ji(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(tr.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var e;const t=Sc();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==qa)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=so)}onLevelLoaded(e,t){var i;const{levels:r}=this,s=t.level,n=t.details,a=n.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=r[s],l=this.fragCurrent;!l||this.state!==Xa&&this.state!==Qa||l.level!==t.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(i=o.details)&&i.live){var c;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(tr.LEVEL_UPDATED,{details:n,level:s}),this.state===so){if(this.waitForCdnTuneIn(n))return;this.state=qa}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,c=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new gl(this.hls,hn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Ca(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];u.push(s,c,d,l,i,r,o.totalduration,h,m,p)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;i&&(e.trigger(tr.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(tr.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,s,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(s=e,r=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i&&i.type!==hn)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===eo&&(this.state=qa));const s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal)this.state=io;else switch(t.details){case rr.FRAG_GAP:case rr.FRAG_PARSING_ERROR:case rr.FRAG_DECRYPT_ERROR:case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(hn,t);break;case rr.LEVEL_LOAD_ERROR:case rr.LEVEL_LOAD_TIMEOUT:case rr.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==so||(null==(i=t.context)?void 0:i.type)!==an||(this.state=qa);break;case rr.BUFFER_APPEND_ERROR:case rr.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===rr.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case rr.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!xa.getBuffered(e).length){const e=this.state!==qa?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=qa,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==mr||this.audioOnly&&!this.altAudio){const e=(t===pr?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,hn),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(s{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=qa,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(tr.FRAG_LOADED,i),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:c,text:d,id3:u,initSegment:f}=s,{details:g}=h,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Za,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,f.tracks,e,n),r.trigger(tr.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;Ji(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(tr.INIT_PTS_FOUND,{frag:o,id:i,initPTS:e,timescale:t}))}if(c&&g&&"initSegment"!==o.sn){const e=g.fragments[o.sn-1-g.startSN],t=o.sn===g.startSN,i=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=c;if(l)l.elementaryStreams[c.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=c.firstKeyFramePTS?c.firstKeyFramePTS:e;if(!t&&n2&&(o.gap=!0);o.setElementaryStreamInfo(c.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,t||i)}else{if(!t&&!i)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;l&&(l.elementaryStreams[mr]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(mr,e,t,i,r),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(t=u.samples)&&t.length){const e={id:i,frag:o,details:g,samples:u.samples};r.trigger(tr.FRAG_PARSING_METADATA,e)}if(g&&d){const e={id:i,frag:o,details:g,samples:d.samples};r.trigger(tr.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,i,r){if(this.state!==Za)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:n,audiovideo:a}=t;if(s){let t=e.audioCodec;const i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===i.indexOf("firefox")&&(t="mp4a.40.5")}t&&-1!==t.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),this.hls.trigger(tr.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(tr.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,hn)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=qa}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(xa.isBuffered(e,i)?t=this.getAppendedFrag(i):xa.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(tr.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(tr.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&Ji(t)&&Ji(i.programDateTime)){const e=i.programDateTime+1e3*(t-i.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ac{static get version(){return"1.5.11"}static isMSESupported(){return bc()}static isSupported(){return function(){if(!bc())return!1;const e=Os();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Us(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Us(t,"audio")))))}()}static getMediaSource(){return Os()}static get Events(){return tr}static get ErrorTypes(){return ir}static get ErrorDetails(){return rr}static get DefaultConfig(){return Ac.defaultConfig?Ac.defaultConfig:gc}static set DefaultConfig(e){Ac.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new fl,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(e,t){if("object"==typeof console&&!0===e||"object"==typeof e){or(e,"debug","log","info","warn","error");try{ar.log(`Debug logs enabled for "${t}" in hls.js version 1.5.11`)}catch(e){ar=nr}}else ar=nr}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=mc(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[s],a=[];r.forEach((r=>{const o=`${e}Loading${r}`,l=t[o];if(void 0!==l&&n){a.push(o);const e=i[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&lr.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),qi(qi({},i),t)}(Ac.DefaultConfig,e);this.userConfig=e,t.progressive&&pc(t);const{abrController:i,bufferController:r,capLevelController:s,errorController:n,fpsController:a}=t,o=new n(this),l=this.abrController=new i(this),h=this.bufferController=new r(this),c=this.capLevelController=new s(this),d=new a(this),u=new gn(this),f=new kn(this),g=t.contentSteeringController,m=g?new g(this):null,p=this.levelController=new yc(this,m),v=new Ra(this),y=new Ec(this.config),T=this.streamController=new wc(this,v,y);c.setStreamController(T),d.setStreamController(T);const E=[u,p,T];m&&E.splice(1,0,m),this.networkControllers=E;const S=[l,h,c,d,f,v];this.audioTrackController=this.createController(t.audioTrackController,E);const b=t.audioStreamController;b&&E.push(new b(this,v,y)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const L=t.subtitleStreamController;L&&E.push(new L(this,v,y)),this.createController(t.timelineController,S),y.emeController=this.emeController=this.createController(t.emeController,S),this.cmcdController=this.createController(t.cmcdController,S),this.latencyController=this.createController(_n,S),this.coreComponents=S,E.push(o);const w=o.onErrorOut;"function"==typeof w&&this.on(tr.ERROR,w,o)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(lr.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===tr.ERROR;this.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){lr.log("destroy"),this.trigger(tr.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){lr.log("attachMedia"),this._media=e,this.trigger(tr.MEDIA_ATTACHING,{media:e})}detachMedia(){lr.log("detachMedia"),this.trigger(tr.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=Wi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,lr.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(tr.MANIFEST_LOADING,{url:e})}startLoad(e=-1){lr.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){lr.log("stopLoad"),this.started=!1,this.networkControllers.forEach((e=>{e.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.stopLoad()}))}swapAudioCodec(){lr.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){lr.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){lr.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){lr.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){lr.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){lr.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){lr.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(lr.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Dn.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let r=0;r=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(r=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=i)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}function Rc(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e.$video.volume=e._options.volume)}),1e3)})),e.event.emit("parsed")}))}))}else if(this.$video.canPlayType("application/vnd.apple.mpegurl")){this.logger.log("Browser support application/vnd.apple.mpegurl : ",this.$video.canPlayType("application/vnd.apple.mpegurl")),this.$video.src=this._options.url;var i=!1;this.$video.addEventListener("canplay",(function(){!i&&e._options.autoPlay&&setTimeout((function(){e.$video.play().then((function(){e.logger.log("autoPlay video!"),setTimeout((function(){e._options.volume>0&&e.setVolume(e._options.volume)}),1e3),i=!0}))}),200)}))}else this.logger.warn("Browser not support hls")},i.isPlayingState=function(){return!this.$video.paused},i.play=function(){if(this.isPlayingState())return Promise.resolve();if(this._options.isLive&&(this.$video.buffered.length>=1&&this.$video.buffered.end(0)>1)){var e=this.$video.buffered.end(0)-1;this.$video.currentTime=e}return this.$video.play()},i.pause=function(){this.$video.pause()},i.setVolume=function(e){this.$video.muted&&(this.$video.muted=!1),this._volume=+(e||0),0===this._volume&&(this.$video.muted=!0),this.$video.volume=this._volume},i.destroy=function(){this.$video&&this.$video.pause(),this._hls&&(this._hls.destroy(),this._hls=null),e.prototype.destroy.call(this)},i._onEvent=function(){var e;(e=this).$video&&(e.$video.addEventListener("canplay",(function(){e.event.emit("canplay")})),e.$video.addEventListener("loadeddata",(function(){e.event.emit("loadeddata")})),e.$video.addEventListener("volumechange",(function(){e.event.emit("volumechange",{data:e.$video.volume})})),e.$video.addEventListener("waiting",(function(){e.event.emit("waiting")})),e.$video.addEventListener("timeupdate",(function(){var t;null==(t=e.event)||t.emit("timeupdate")})),e.$video.addEventListener("seeking",(function(){e.event.emit("seeking",{data:e.$video.currentTime})})),e.$video.addEventListener("seeked",(function(){e.event.emit("seeked")})),e.$video.addEventListener("abort",(function(){e.event.emit("abort")})),e.$video.addEventListener("error",(function(){var t;null==(t=e.event)||t.emit("error",{data:e.$video.error})})),e.$video.addEventListener("ended",(function(){e.event.emit("ended")})))},Rc(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(Ri);var xc="wasm_loaded",Cc="wasm_failed",Ic="init";function Pc(e,t){return Pc=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Pc(e,t)}var Oc=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=function(e,t){void 0===t&&(t=["h264"]);var i=(t||["h264"]).reduce((function(e,t){return t=t.toLowerCase(),e+(Xt[t]||0)}),0),r=e.split("?")[0],s=e.split("?")[1];return s=(s||"").split("&").filter((function(e){return!/^vc=\d?/.test(e)})).join("&"),r+"?"+s+(s?"&":"")+"vc="+i}(null==t?void 0:t.url,["h264","h265"]),function(e,t){if(((null==t?void 0:t.volume)||0)>1?e._volume=1:((null==t?void 0:t.volume)||0)<=0?e._volume=0:e._volume=+((null==t?void 0:t.volume)||0),t.volume=e._volume,e.options=zt({},wi,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=z(e.options.loggerOptions),e.event=new ei,e.logger.log("HlsPlayer version: ",Uc.version),e.logger.log("HlsPlayer options: ",e.options),e.options.logger=e.logger}(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),t),i._containerClassName=Li+"-container",i._render(),i}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Pc(e,t)}(t,e);var i=t.prototype;return i._render=function(){this.$container.classList.add(this._containerClassName)},i.destroy=function(){this.$container&&(this.$container.classList.remove(this._containerClassName),this.$container.innerHTML="",this.$container=null)},t}(Si);function Mc(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e=!0),this.playParam={durationMs:0,fps:0,sampleRate:0,size:{width:0,height:0},audioNone:e,videoCodec:T},!A())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(Ui.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===T){var e={seekPos:0,isLive:this.options.isLive,accurateSeek:!0,seekEvent:!1,realPlay:!0};return this.player.play(e)}return this.player.play()},i.pause=function(){return Ui.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return Ui.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===T&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage(P(B)),this._decoderWorker.terminate(),this._decoderWorker=null),this.logger.log("destroy"),null==(i=this.event)||null==(t=i.emit)||t.call(i,"destroy"),this.player=null,e.prototype.destroy.call(this),!0)},i.isPlaying=function(){return null!==this.player&&this.player.isPlayingState()},i.setVolume=function(e){var t;(e=+e)>1||e<0?this.logger.warn("volume volume value 0.0 ~ 1.0!"):((t=this).player||(t.event.emit("playerIsNull"),t.logger.warn("Player instance does not exist!"),0))&&(this.player.setVolume(e),this.event.emit("volumeChange",{data:e}))},i.getVersion=function(){return Ui.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new Vi({logger:this.logger,decoderWorker:this._decoderWorker,event:this.event}),this._m3u8Obj.bindReady(this),this._m3u8Obj.onFinished=function(e,t){},this._m3u8Obj.onCacheProcess=function(t){e.options.isLive||null==e.onCacheProcess||e.onCacheProcess.call(e,t)},this._m3u8Obj.onDemuxed=this._checkPlayer.bind(this),this._m3u8Obj.onSamples=this._hlsOnSamples.bind(this),this._m3u8Obj.demux(this.url)},i._checkPlayer=function(e,t){var i=this;if(null==i.player){var r,s,n;if(!(null==i||null==(r=i._m3u8Obj)?void 0:r.isHevcParam)||t)return null==i||null==(n=i._m3u8Obj)||null==(s=n.destroy)||s.call(n),i._m3u8Obj=null,this._decoderWorker.terminate(),this._decoderWorker=null,void(i.player=new Dc(Fc({},this.options,{event:this.event,logger:this.logger})));var a=i._m3u8Obj.getACodec(),o=i._m3u8Obj.getFPS(),l=i._m3u8Obj.getSampleRate(),h=i._m3u8Obj.getSize(),c=!1;c=i._m3u8Obj.getSampleChannel()<=0||""===a,i._softPlayer(0,o,l,h,c)}},i._hlsOnSamples=function(e,t){var i,r,s,n=this;if(t.video)null==(s=n.player)||null==(r=s.appendHevcFrame)||r.call(s,t);else if(!(null==(i=n._m3u8Obj)?void 0:i.audioNone)){var a,o;null==(o=n.player)||null==(a=o.appendAACFrame)||a.call(o,t)}},i._onWorkerMessage=function(){var e=this,i=this;this._decoderWorker.onmessage=function(r){var s=r.data;switch(s.cmd){case O:t.__HLS_WASM_DecoderState__=0;break;case M:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(xc),i._decoderWorker.postMessage(P("registerWasmPlayer")),i._m3u8Entry();break;case F:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(Cc,s),Ui.send("wasm",{name:"wasm loading failed"}),i._checkPlayer(!0)}}},i._softPlayer=function(e,t,i,r,s,n){var a,o,l=this;void 0===s&&(s=!1),void 0===n&&(n=null);var c,d=this;(this.playParam.durationMs=e,this.playParam.fps=t,this.playParam.sampleRate=i,this.playParam.size=r,this.playParam.audioNone=s,this.playParam.videoCodec=n||T,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new xi(Fc({},d.options,{sampleRate:i,fps:t,appendHevcType:h,fixed:!1,id:this.options.id,audioNone:s,videoCodec:n,logger:this.logger,event:this.event,decoderWorker:this._decoderWorker})),this.player.onPlayingTime=function(e){var t;null==d||null==(t=d.onPlayTime)||t.call(d,e)},this.player.onPlayingFinish=function(){var e,t;(l.pause(),null!=l.onPlayFinish)&&(null==(t=l)||null==(e=t.onPlayFinish)||e.call(t))},this.player.onLoadCache=function(){var e,t;null==(t=l)||null==(e=t.onLoadCache)||e.call(t)},this.player.onLoadCacheFinished=function(){var e,t;null==(t=l)||null==(e=t.onLoadCacheFinished)||e.call(t)},null==(a=d.player)||a.setDurationMs(e),null==(o=d.player)||o.setFrameRate(t),null!=d.onReadyShowDone)&&(null==d||null==(c=d.onReadyShowDone)||c.call(d));this.event.emit("parsed"),this.player&&this.options.autoPlay&&this.play()},t.supportType=function(e){if(Ui.send(1,{name:"supportType",options:e}),"hls"===e.type)return!0;if(e.url){var t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.m3u8$/i.test(new URL(t).pathname)}catch(e){}}return!1},Mc(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(Oc);return Uc.__HLS_WASM_DecoderState__=0,Uc.version="0.1.0",Uc}));
diff --git a/dist/types/index.d.ts b/dist/types/index.d.ts
new file mode 100644
index 0000000..6011f73
--- /dev/null
+++ b/dist/types/index.d.ts
@@ -0,0 +1,509 @@
+import { LoggerCls } from '@ezuikit/utils-logger';
+export { LoggerOptions } from '@ezuikit/utils-logger';
+import BasePlayer, { BasePlayerOptions } from '@ezuikit/player-base';
+import Hls from 'hls.js';
+import EventEmitter from 'eventemitter3';
+
+type Fn$1 = () => any;
+declare class AudioCore {
+ options: {
+ sampleRate: any;
+ appendType: any;
+ playMode: any;
+ isLive: boolean;
+ };
+ logger: LoggerCls;
+ sourceChannel: number;
+ audioCtx: AudioContext;
+ gainNode: GainNode;
+ sourceList: AudioBufferSourceNode[];
+ startStatus: boolean;
+ sampleQueue: Array;
+ nextBuffer: {
+ data: any;
+ pts: number;
+ };
+ playTimestamp: number;
+ playStartTime: number;
+ durationMs: number;
+ volume: number;
+ onLoadCache: Fn$1;
+ seekPos: any;
+ constructor(options: any);
+ resetStartParam(): void;
+ setOnLoadCache(callback: any): void;
+ setDurationMs(durationMs?: number): void;
+ setVolume(volume?: number): void;
+ getAlignVPTS(): number;
+ /**
+ * @brief Swap SourceNode To Play When before node play end
+ */
+ swapSource(sourceIndex?: number, dstIndex?: number): null;
+ /**
+ * @param sampleObj : {data:Uint8Array, pts:xxx}
+ */
+ addSample(sampleObj?: null): boolean;
+ runNextBuffer(): void;
+ /**
+ * @return
+ * 1 queue length == 0, no frame
+ * 0 OK
+ * -1 sourceIndex out of bounds
+ * -2 decode Error
+ */
+ decodeSample(sourceIndex?: number, dstIndex?: number): 1 | -1 | -2 | 0 | -3;
+ /**
+ * @return
+ * 1 queue length == 0, no frame
+ * 0 OK
+ * -1 sourceIndex out of bounds
+ * -2 decode Error
+ */
+ decodeWholeSamples(sourceIndex?: number): 1 | -1 | -2 | 0 | -3;
+ play(): void;
+ pause(): void;
+ stop(): void;
+ cleanQueue(): void;
+}
+
+/**
+ * @description yuv 数据结构
+ */
+declare class YuvStruct {
+ pts: number;
+ width: number;
+ height: number;
+ imageBufferY: Uint8Array;
+ imageBufferB: Uint8Array;
+ imageBufferR: Uint8Array;
+ constructor(pts: number, width: number, height: number, imageBufferY: Uint8Array, imageBufferB: Uint8Array, imageBufferR: Uint8Array);
+ /**
+ *
+ * @param pts
+ * @param width
+ * @param height
+ * @param imageBufferY
+ * @param imageBufferB
+ * @param imageBufferR
+ */
+ setYuv(pts: number, width: number, height: number, imageBufferY: Uint8Array, imageBufferB: Uint8Array, imageBufferR: Uint8Array): void;
+}
+
+declare class Cache {
+ limit: number;
+ logger: LoggerCls;
+ yuvCache: YuvStruct[];
+ constructor(options: any);
+ appendCacheByCacheYuv(cacheYuvObj: YuvStruct): number;
+ getState(): number;
+ cleanPipeline(): void;
+ shiftYuv(): YuvStruct | null | undefined;
+}
+
+declare class WebGlRender {
+ gl: WebGLRenderingContext;
+ program: WebGLProgram;
+ verticesBuffer: WebGLBuffer | null;
+ texCoordBuffer: WebGLBuffer | null;
+ constructor(canvas: HTMLCanvasElement, options?: any);
+ /**
+ * @description 渲染视频帧
+ * @param {number} videoFrameY
+ * @param {number} videoFrameB
+ * @param {number} videoFrameR
+ * @param {number} width
+ * @param {number} height
+ */
+ renderFrame(videoFrameY: any, videoFrameB: any, videoFrameR: any, width: any, height: any): void;
+ /**
+ * @description 释放webgl 数据
+ */
+ destroyContext(): void;
+}
+
+interface IEnginePlayer {
+ volume: number;
+ play: () => Promise;
+ pause: () => void;
+ setVolume: (volume?: number) => void;
+}
+
+declare class BufferFrame {
+ pts: number;
+ dts: number;
+ isKey: boolean;
+ data: Uint8Array;
+ video: boolean;
+ constructor(pts: number, isKey: boolean, data: Uint8Array, isVideo: boolean);
+ setFrame(pts: number, isKey: boolean, data: Uint8Array, isVideo: boolean): void;
+}
+
+interface HlsOptions extends BasePlayerOptions {
+ /** 出错尝试连接次数 默认 20 */
+ retry: number;
+ /** 是否是直播 默认 true */
+ isLive: boolean;
+ decoder?: string;
+ [key: string]: any;
+}
+
+interface UIOptions extends HlsOptions {
+ /** 视窗的宽 */
+ nodeName: 'video' | 'canvas';
+ disableContextmenu: boolean;
+}
+/**
+ * @class UI
+ * @description UI
+ *
+ * @example
+ * ```ts
+ * const ui = new UIVideo({
+ * id: "id",
+ * width: 100,
+ * height: 100
+ * });
+ * ```
+ */
+declare class UIVideo {
+ private readonly _classVideo;
+ $video: T;
+ logger: any;
+ event: any;
+ options: any;
+ private readonly _$container;
+ /**
+ * @description 构造函数
+ * @param {UIOptions} options
+ */
+ constructor(options?: Partial);
+ /**
+ * @description 渲染 UI
+ */
+ private _render;
+ /**
+ * @description 是否是 video 标签
+ * @returns {boolean}
+ */
+ private _isVideo;
+ /**
+ * @description 销毁
+ */
+ destroy(): void;
+}
+
+interface SoftPlayerOptions extends UIOptions {
+ width: number;
+ height: number;
+ fps: number;
+ fixed: any;
+ sampleRate: number;
+ appendHevcType: number;
+ frameDurMs: number;
+ id: string;
+ audioNone: boolean;
+ videoCodec: any;
+ logger: LoggerCls;
+ decoderWorker: Worker;
+ type: 'hls';
+ volume: number;
+ isLive: boolean;
+}
+type Fn = (a?: any) => any;
+declare class SoftPlayer extends UIVideo implements IEnginePlayer {
+ options: SoftPlayerOptions;
+ logger: LoggerCls;
+ frameList: BufferFrame[];
+ cacheInterval: number;
+ nowPacket: null;
+ stream: Uint8Array;
+ vCodecID: number;
+ audio: AudioCore;
+ liveStartMs: number;
+ durationMs: number;
+ videoPTS: number;
+ loop: number;
+ cacheLoop: number;
+ playParams: {
+ seekPos: number;
+ isLive: boolean;
+ accurateSeek: boolean;
+ seekEvent: boolean;
+ realPlay: boolean;
+ };
+ calculateStartTime: number;
+ fix_poc_err_skip: number;
+ frameTime: number;
+ frameTimeSec: number;
+ preCostTime: number;
+ _volume: number;
+ isPlaying: boolean;
+ isCaching: any;
+ isNewSeek: boolean;
+ flushDecoder: number;
+ isCheckDisplay: boolean;
+ isPlayLoadingFinish: number;
+ vCachePTS: number;
+ aCachePTS: number;
+ noCacheFrame: number;
+ onPlayingTime: Fn;
+ onPlayingFinish: Fn;
+ onLoadCache: Fn;
+ onLoadCacheFinished: Fn;
+ gl: WebGlRender;
+ cacheYuvBuf: Cache;
+ decoderWorker: Worker;
+ constructor(options?: Partial);
+ setSize(width: any, height: any): void;
+ setFrameRate(fps?: number): void;
+ setDurationMs(durationMs?: number): void;
+ setPlayingCall(callback: any): void;
+ get volume(): number;
+ set volume(volume: number);
+ setVolume(volume?: number): void;
+ isPlayingState(): boolean;
+ appendAACFrame(streamBytes: any): void;
+ appendHevcFrame(streamBytes: BufferFrame): void;
+ getCachePTS(): number;
+ endAudio(): void;
+ cleanSample(): void;
+ cleanVideoQueue(): void;
+ cleanCacheYUV(): void;
+ /**
+ * @description pause
+ */
+ pause(): void;
+ checkFinished(mode: any): boolean;
+ clearAllCache(): void;
+ getNalu1Packet(alginPTS?: boolean): {
+ nalBuf: false | Uint8Array;
+ pts: number;
+ } | null;
+ /**
+ * @TODO
+ */
+ cacheThread(): void;
+ stopCacheThread(): void;
+ /**
+ * 缓存中
+ */
+ loadCache(): void;
+ _playFunc(): boolean | undefined;
+ /**
+ * seekPos=-1,
+ * accurateSeek=true,
+ * seekEvent=false,
+ * realPlay=true
+ */
+ play(playParams?: any): Promise;
+ stop(): void;
+ /**
+ * @description 释放
+ * @returns
+ */
+ destroy(): boolean;
+ /**
+ *
+ */
+ nextNalu(onceGetNalCount?: number): false | Uint8Array;
+ /**
+ * @brief play yuv cache
+ */
+ playFrameYUV(show?: boolean): boolean;
+ drawImage(width: any, height: any, imageBufferY: any, imageBufferB: any, imageBufferR: any): void;
+ checkDisplaySize(widthIn: number, heightIn: number): number[];
+ _onWorkerMessage(): void;
+ initVideoAndAudio(): void;
+}
+
+interface HardHlsPlayerOptions extends Omit {
+ logger: LoggerCls;
+ event: EventEmitter;
+ volume: number;
+}
+/**
+ * @classdesc hls 播放器 (h264)
+ */
+declare class HardHlsPlayer extends UIVideo implements IEnginePlayer {
+ hlsPlayer: Hls;
+ _options: HardHlsPlayerOptions;
+ event: EventEmitter;
+ _hls: Hls;
+ _volume: number;
+ logger: LoggerCls;
+ constructor(options: HardHlsPlayerOptions);
+ private _init;
+ isPlayingState(): boolean;
+ play(): Promise;
+ pause(): void;
+ /**
+ * @description 获取音量
+ * @example
+ * ```ts
+ * player.volume // return number
+ * ```
+ */
+ get volume(): number;
+ /**
+ * @description 设置音量 [0.0 ~ 1.0]
+ * @example
+ * ```ts
+ * player.volume = 0.8
+ * ```
+ */
+ set volume(volume: number);
+ /**
+ * @description 设置音量 [0.0 ~ 1.0]
+ * @param {number} volume
+ */
+ setVolume(volume?: number): void;
+ destroy(): void;
+ _onEvent(): void;
+}
+
+/**
+ * @class UI
+ * @description UI
+ *
+ * @example
+ * ```ts
+ * const ui = new UIContainer({
+ * id: "id",
+ * width: 100,
+ * height: 100
+ * });
+ * ```
+ */
+declare class UIContainer extends BasePlayer {
+ private readonly _containerClassName;
+ /**
+ * @description 构造函数
+ * @param {UIOptions} options
+ */
+ constructor(options?: Partial);
+ private _render;
+ /**
+ * @description 销毁
+ */
+ destroy(): void;
+}
+
+/**
+ * @description hls 播放器
+ */
+declare class HlsPlayer extends UIContainer {
+ /** WebAssembly completed loading identity */
+ static __HLS_WASM_DecoderState__: number;
+ private _decoderWorker;
+ private _m3u8Obj;
+ url: string;
+ playParam: any;
+ player: SoftPlayer | HardHlsPlayer;
+ onPlayTime: any;
+ onParsed: any;
+ onSeekStart: null;
+ onLoadCache?: any;
+ onLoadCacheFinished?: any;
+ onPlayFinish: any;
+ onCacheProcess: any;
+ onReadyShowDone: any;
+ onError: null;
+ _volume: number;
+ constructor(options: Partial);
+ _init(): void;
+ /**
+ *
+ * @description 播放
+ * @returns {Promise}
+ * @example
+ *
+ * ```ts
+ * player.play()
+ * ```
+ *
+ */
+ play(): Promise;
+ /**
+ * @description 暂停
+ * @returns {void}
+ *
+ * @example
+ * ```ts
+ * player.pause()
+ * ```
+ */
+ pause(): boolean;
+ /**
+ * @description 销毁实例和dom
+ * @returns {void}
+ * @example
+ * ```ts
+ * player.destroy()
+ * ```
+ */
+ destroy(): boolean;
+ /**
+ * @description 当前的播放状态
+ * @returns {boolean}
+ */
+ isPlaying(): boolean;
+ /**
+ * @description 获取音量
+ * @example
+ * ```ts
+ * player.volume // return number
+ * ```
+ */
+ get volume(): number;
+ /**
+ * @description 设置音量 [0.0 ~ 1.0]
+ * @example
+ * ```ts
+ * player.volume = 0.8
+ * ```
+ */
+ set volume(volume: number);
+ setVolume(volume: number): void;
+ /**
+ * @description 当前版本
+ * @static
+ *
+ * @example
+ * ```ts
+ * HlsPlayer.version
+ * ```
+ */
+ static version: string;
+ /**
+ * @description 获取版本号
+ * @returns {string}
+ */
+ getVersion(): string;
+ /**
+ * @description 静态方法 判断是否支持播放地址
+ * @param {Partial<{ url: string }>} options
+ * @returns {boolean}
+ * @static
+ *
+ * @example
+ * ```ts
+ * HlsPlayer.supportType({url: "https://open.ys7.com/v3/openlive/E71992743_1_1.m3u8"})
+ * ```
+ */
+ static supportType(options: Partial<{
+ url?: string;
+ type?: string;
+ }>): boolean;
+ /**
+ * @brief m3u8
+ */
+ _m3u8Entry(): void;
+ _checkPlayer(empty: any, isAVC?: boolean): void;
+ _hlsOnSamples(readyObj: any, frame: BufferFrame): void;
+ _onWorkerMessage(): void;
+ _softPlayer(durationMs: any, fps: any, sampleRate: any, size: any, audioNone?: boolean, videoCodec?: null): void;
+}
+
+export { type HlsOptions, HlsPlayer as default };
diff --git a/examples/base-app/README.md b/examples/base-app/README.md
index 2fbb336..3700a35 100644
--- a/examples/base-app/README.md
+++ b/examples/base-app/README.md
@@ -1,7 +1,5 @@
## 使用
-
-
```bash
# 安装 http-server
diff --git a/examples/base-app/decoder.wasm b/examples/base-app/decoder.wasm
new file mode 100644
index 0000000..5c0c2fa
Binary files /dev/null and b/examples/base-app/decoder.wasm differ
diff --git a/examples/base-app/decoder.worker.js b/examples/base-app/decoder.worker.js
new file mode 100644
index 0000000..4b8dbac
--- /dev/null
+++ b/examples/base-app/decoder.worker.js
@@ -0,0 +1,8 @@
+/*
+*
+* DecoderWorker.js v0.1.0
+* Copyright (c) 2024-8-1 Ezviz-OpenBiz
+* .
+*
+*/
+!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e={DEFAULT_SAMPLERATE:44100,DEFAULT_CHANNEL:1,H264AUD:[0,0,0,1,9,224],H265AUD:[0,0,0,1,70,1,80],DEF_AAC:"aac",DEF_MP3:"mp3",DEF_H265:"h265",DEF_HEVC:"hevc",DEF_H264:"h264",DEF_AVC:"avc",CODEC_OFFSET_TABLE:["hevc","h265","avc","h264","aac","mp3"]};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t={exports:{}};!function(e,r){function t(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t=e.length?{done:!0}:{done:!1,value:e[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.")}var d,f,p=(f="undefined"!=typeof document?null==(d=document.currentScript)?void 0:d.src:void 0,function(e){var r,t=function(){var r=dr.value;r in e||Object.defineProperty(e,r,{configurable:!0,get:function(){q("Access to module property ('"+r+"') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.")}})};void 0===e&&(e={});var n,i,d=Object.assign({},e),p=new Promise((function(e,r){n=e,i=r}));["_malloc","_free","_memory","_registerWasmPlayer","_setCodecType","_exitWasmPlayer","_initDecoder","_decodeCodecContext","_destroy","_demuxTsStream","_getPacket","_getVLCLen","_getVLC","_getVPSLen","_getVPS","_getSPSLen","_getSPS","_getPPSLen","_getPPS","_getSEILen","_getSEI","___indirect_function_table","_ff_h264_cabac_tables","onRuntimeInitialized"].forEach((function(e){Object.getOwnPropertyDescriptor(p,e)||Object.defineProperty(p,e,{get:function(){return q("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")},set:function(){return q("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")}})}));var m="object"==("undefined"==typeof window?"undefined":u(window)),h="function"==typeof importScripts,g="object"==("undefined"==typeof process?"undefined":u(process))&&"object"==u(process.versions)&&"string"==typeof process.versions.node,v=!m&&!g&&!h;if(d.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");var E,y,w,b=Object.assign({},d),_="./this.program",S="";if(v){if("object"==("undefined"==typeof process?"undefined":u(process))||"object"==("undefined"==typeof window?"undefined":u(window))||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else{if(!m&&!h)throw new Error("environment detection error");if(h?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),f&&(S=f),S=S.startsWith("blob:")?"":S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=("undefined"==typeof window?"undefined":u(window))&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");E=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText},h&&(w=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),y=function(e,r,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){200==n.status||0==n.status&&n.response?r(n.response):t()},n.onerror=t,n.send(null)}}var O,T,k,A=d.print||console.log.bind(console),M=d.printErr||console.error.bind(console);Object.assign(d,b),b=null,O="fetchSettings",Object.getOwnPropertyDescriptor(d,O)&&q("`Module."+O+"` was supplied but `"+O+"` not included in INCOMING_MODULE_JS_API"),d.arguments&&d.arguments,ie("arguments","arguments_"),d.thisProgram&&(_=d.thisProgram),ie("thisProgram","thisProgram"),d.quit&&d.quit,ie("quit","quit_"),L(void 0===d.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.read,"Module.read option was removed (modify read_ in JS)"),L(void 0===d.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),L(void 0===d.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),L(void 0===d.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),L(void 0===d.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),ie("asm","wasmExports"),ie("read","read_"),ie("readAsync","readAsync"),ie("readBinary","readBinary"),ie("setWindowTitle","setWindowTitle"),L(!g,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable."),L(!v,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable."),d.wasmBinary&&(T=d.wasmBinary),ie("wasmBinary","wasmBinary"),"object"!=("undefined"==typeof WebAssembly?"undefined":u(WebAssembly))&&M("no native wasm support detected");var P,F,C,D,x,I=!1;function L(e,r){e||q("Assertion failed"+(r?": "+r:""))}function N(){var e=k.buffer;d.HEAP8=P=new Int8Array(e),d.HEAP16=C=new Int16Array(e),d.HEAPU8=F=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAP32=D=new Int32Array(e),d.HEAPU32=x=new Uint32Array(e),d.HEAPF32=new Float32Array(e),d.HEAPF64=new Float64Array(e)}function R(){if(!I){var e=ir();0==e&&(e+=4);var r=x[e>>2],t=x[e+4>>2];34821223==r&&2310721022==t||q("Stack overflow! Stack cookie has been overwritten at "+le(e)+", expected hex dwords 0x89BACDFE and 0x2135467, but received "+le(t)+" "+le(r)),1668509029!=x[0]&&q("Runtime error: The application has corrupted its heap memory area (address zero)!")}}L(!d.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),L("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),L(!d.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),L(!d.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"),function(){var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,115!==r[0]||99!==r[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"}();var U=[],B=[],j=[],$=!1;L(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var W=0,H=null,z=null,V={};function G(e){for(var r=e;;){if(!V[e])return e;e=r+Math.random()}}function Y(e){var r;W++,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(!V[e]),V[e]=1,null===H&&"undefined"!=typeof setInterval&&(H=setInterval((function(){if(I)return clearInterval(H),void(H=null);var e=!1;for(var r in V)e||(e=!0,M("still waiting on run dependencies:")),M("dependency: "+r);e&&M("(end of list)")}),1e4))):M("warning: run dependency added without ID")}function Q(e){var r;if(W--,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(V[e]),delete V[e]):M("warning: run dependency removed without ID"),0==W&&(null!==H&&(clearInterval(H),H=null),z)){var t=z;z=null,t()}}function q(e){var r;null==(r=d.onAbort)||r.call(d,e),M(e="Aborted("+e+")"),I=!0;var t=new WebAssembly.RuntimeError(e);throw i(t),t}var K,X,J,Z=function(e){return e.startsWith("data:application/octet-stream;base64,")},ee=function(e){return e.startsWith("file://")};function re(e,r){return function(){for(var t=arguments.length,n=new Array(t),o=0;o0;)e.shift()(d)};d.noExitRuntime;var le=function(e){return L("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")},de=function(e){var r;(r=de).shown||(r.shown={}),de.shown[e]||(de.shown[e]=1,M(e))};function fe(){L(null!=xe.varargs);var e=D[+xe.varargs>>2];return xe.varargs+=4,e}var pe=fe,me={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,r){for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:function(e){var r=me.isAbs(e),t="/"===e.substr(-1);return(e=me.normalizeArray(e.split("/").filter((function(e){return!!e})),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:function(e){var r=me.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:function(e){if("/"===e)return"/";var r=(e=(e=me.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){for(var e=arguments.length,r=new Array(e),t=0;t { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")}())(e)},ge={resolve:function(){for(var e=arguments.length,r=new Array(e),t=0;t=-1&&!o;i--){var a=i>=0?r[i]:Ce.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");if(!a)return"";n=a+"/"+n,o=me.isAbs(a)}return(o?"/":"")+(n=me.normalizeArray(n.split("/").filter((function(e){return!!e})),!o).join("/"))||"."},relative:function(e,r){var t=function(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)};e=ge.resolve(e).substr(1),r=ge.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),i=Math.min(n.length,o.length),a=i,s=0;s=n);)++o;if(o-r>16&&e.buffer&&ve)return ve.decode(e.subarray(r,o));for(var i="";r>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},ye=[],we=function(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r},be=function(e,r,t,n){if(L("string"==typeof e,"stringToUTF8Array expects a string (got "+(void 0===e?"undefined":u(e))+")"),!(n>0))return 0;for(var o=t,i=t+n-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(t>=i)break;r[t++]=s}else if(s<=2047){if(t+1>=i)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=i)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=i)break;s>1114111&&de("Invalid Unicode code point "+le(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o};function _e(e,r,t){var n=we(e)+1,o=new Array(n),i=be(e,o,0,o.length);return o.length=i,o}var Se,Oe={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){Oe.ttys[e]={input:[],output:[],ops:r},Ce.registerDevice(e,Oe.stream_ops)},stream_ops:{open:function(e){var r=Oe.ttys[e.node.rdev];if(!r)throw new Ce.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new Ce.ErrnoError(60);for(var i=0,a=0;a0&&(A(Ee(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,r,t){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(M(Ee(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(M(Ee(e.output,0)),e.output=[])}}},Te=function(e){q("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},ke={ops_table:null,mount:function(e){return ke.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){var o;if(Ce.isBlkdev(t)||Ce.isFIFO(t))throw new Ce.ErrnoError(63);(o=ke).ops_table||(o.ops_table={dir:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,lookup:ke.node_ops.lookup,mknod:ke.node_ops.mknod,rename:ke.node_ops.rename,unlink:ke.node_ops.unlink,rmdir:ke.node_ops.rmdir,readdir:ke.node_ops.readdir,symlink:ke.node_ops.symlink},stream:{llseek:ke.stream_ops.llseek}},file:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:{llseek:ke.stream_ops.llseek,read:ke.stream_ops.read,write:ke.stream_ops.write,allocate:ke.stream_ops.allocate,mmap:ke.stream_ops.mmap,msync:ke.stream_ops.msync}},link:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,readlink:ke.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:Ce.chrdev_stream_ops}});var i=Ce.createNode(e,r,t,n);return Ce.isDir(i.mode)?(i.node_ops=ke.ops_table.dir.node,i.stream_ops=ke.ops_table.dir.stream,i.contents={}):Ce.isFile(i.mode)?(i.node_ops=ke.ops_table.file.node,i.stream_ops=ke.ops_table.file.stream,i.usedBytes=0,i.contents=null):Ce.isLink(i.mode)?(i.node_ops=ke.ops_table.link.node,i.stream_ops=ke.ops_table.link.stream):Ce.isChrdev(i.mode)&&(i.node_ops=ke.ops_table.chrdev.node,i.stream_ops=ke.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[r]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=Ce.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,Ce.isDir(e.mode)?r.size=4096:Ce.isFile(e.mode)?r.size=e.usedBytes:Ce.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&ke.resizeFileStorage(e,r.size)},lookup:function(e,r){throw Ce.genericErrors[44]},mknod:function(e,r,t,n){return ke.createNode(e,r,t,n)},rename:function(e,r,t){if(Ce.isDir(e.mode)){var n;try{n=Ce.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new Ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=Ce.lookupNode(e,r);for(var n in t.contents)throw new Ce.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){for(var r,t=[".",".."],n=l(Object.keys(e.contents));!(r=n()).done;){var o=r.value;t.push(o)}return t},symlink:function(e,r,t){var n=ke.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!Ce.isLink(e.mode))throw new Ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,n);if(L(a>=0),a>8&&i.subarray)r.set(i.subarray(o,o+a),t);else for(var s=0;s0||t+r8)throw new Ce.ErrnoError(32);for(var t=e.split("/").filter((function(e){return!!e})),n=Ce.root,o="/",i=0;i40)throw new Ce.ErrnoError(32)}}return{path:o,node:n}},getPath:function(e){for(var r;;){if(Ce.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:function(e,r){for(var t=0,n=0;n>>0)%Ce.nameTable.length},hashAddNode:function(e){var r=Ce.hashName(e.parent.id,e.name);e.name_next=Ce.nameTable[r],Ce.nameTable[r]=e},hashRemoveNode:function(e){var r=Ce.hashName(e.parent.id,e.name);if(Ce.nameTable[r]===e)Ce.nameTable[r]=e.name_next;else for(var t=Ce.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:function(e,r){var t=Ce.mayLookup(e);if(t)throw new Ce.ErrnoError(t);for(var n=Ce.hashName(e.id,r),o=Ce.nameTable[n];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===r)return o}return Ce.lookup(e,r)},createNode:function(e,r,t,n){L("object"==(void 0===e?"undefined":u(e)));var o=new Ce.FSNode(e,r,t,n);return Ce.hashAddNode(o),o},destroyNode:function(e){Ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return!(49152&~e)},flagsToPermissionString:function(e){var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:function(e,r){return Ce.ignorePermissions||(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2},mayLookup:function(e){if(!Ce.isDir(e.mode))return 54;var r=Ce.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:function(e,r){try{return Ce.lookupNode(e,r),20}catch(e){}return Ce.nodePermissions(e,"wx")},mayDelete:function(e,r,t){var n;try{n=Ce.lookupNode(e,r)}catch(e){return e.errno}var o=Ce.nodePermissions(e,"wx");if(o)return o;if(t){if(!Ce.isDir(n.mode))return 54;if(Ce.isRoot(n)||Ce.getPath(n)===Ce.cwd())return 10}else if(Ce.isDir(n.mode))return 31;return 0},mayOpen:function(e,r){return e?Ce.isLink(e.mode)?32:Ce.isDir(e.mode)&&("r"!==Ce.flagsToPermissionString(r)||512&r)?31:Ce.nodePermissions(e,Ce.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=Ce.MAX_OPEN_FDS;e++)if(!Ce.streams[e])return e;throw new Ce.ErrnoError(33)},getStreamChecked:function(e){var r=Ce.getStream(e);if(!r)throw new Ce.ErrnoError(8);return r},getStream:function(e){return Ce.streams[e]},createStream:function(e,r){return void 0===r&&(r=-1),e=Object.assign(new Ce.FSStream,e),-1==r&&(r=Ce.nextfd()),e.fd=r,Ce.streams[r]=e,e},closeStream:function(e){Ce.streams[e]=null},dupStream:function(e,r){var t,n;void 0===r&&(r=-1);var o=Ce.createStream(e,r);return null==(n=o.stream_ops)||null==(t=n.dup)||t.call(n,o),o},chrdev_stream_ops:{open:function(e){var r=Ce.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,null==e.stream_ops.open||e.stream_ops.open.call(e.stream_ops,e)},llseek:function(){throw new Ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,r){return e<<8|r},registerDevice:function(e,r){Ce.devices[e]={stream_ops:r}},getDevice:function(e){return Ce.devices[e]},getMounts:function(e){for(var r=[],t=[e];t.length;){var n,o=t.pop();r.push(o),(n=t).push.apply(n,[].concat(o.mounts))}return r},syncfs:function(e,r){"function"==typeof e&&(r=e,e=!1),Ce.syncFSRequests++,Ce.syncFSRequests>1&&M("warning: "+Ce.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=Ce.getMounts(Ce.root.mount),n=0;function o(e){return L(Ce.syncFSRequests>0),Ce.syncFSRequests--,r(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach((function(r){if(!r.type.syncfs)return i(null);r.type.syncfs(r,e,i)}))},mount:function(e,r,t){if("string"==typeof e)throw e;var n,o="/"===t,i=!t;if(o&&Ce.root)throw new Ce.ErrnoError(10);if(!o&&!i){var a=Ce.lookupPath(t,{follow_mount:!1});if(t=a.path,n=a.node,Ce.isMountpoint(n))throw new Ce.ErrnoError(10);if(!Ce.isDir(n.mode))throw new Ce.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Ce.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:function(e){var r=Ce.lookupPath(e,{follow_mount:!1});if(!Ce.isMountpoint(r.node))throw new Ce.ErrnoError(28);var t=r.node,n=t.mounted,o=Ce.getMounts(n);Object.keys(Ce.nameTable).forEach((function(e){for(var r=Ce.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&Ce.destroyNode(r),r=t}})),t.mounted=null;var i=t.mount.mounts.indexOf(n);L(-1!==i),t.mount.mounts.splice(i,1)},lookup:function(e,r){return e.node_ops.lookup(e,r)},mknod:function(e,r,t){var n=Ce.lookupPath(e,{parent:!0}).node,o=me.basename(e);if(!o||"."===o||".."===o)throw new Ce.ErrnoError(28);var i=Ce.mayCreate(n,o);if(i)throw new Ce.ErrnoError(i);if(!n.node_ops.mknod)throw new Ce.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:function(e,r){return r=void 0!==r?r:438,r&=4095,r|=32768,Ce.mknod(e,r,0)},mkdir:function(e,r){return r=void 0!==r?r:511,r&=1023,r|=16384,Ce.mknod(e,r,0)},mkdirTree:function(e,r){for(var t=e.split("/"),n="",o=0;o=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(1==(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.read)throw new Ce.ErrnoError(28);var i=void 0!==o;if(i){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,r,t,n,o);return i||(e.position+=a),a},write:function(e,r,t,n,o,i){if(L(t>=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.write)throw new Ce.ErrnoError(28);e.seekable&&1024&e.flags&&Ce.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,i);return a||(e.position+=s),s},allocate:function(e,r,t){if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(r<0||t<=0)throw new Ce.ErrnoError(28);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(!Ce.isFile(e.node.mode)&&!Ce.isDir(e.node.mode))throw new Ce.ErrnoError(43);if(!e.stream_ops.allocate)throw new Ce.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:function(e,r,t,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new Ce.ErrnoError(2);if(1==(2097155&e.flags))throw new Ce.ErrnoError(2);if(!e.stream_ops.mmap)throw new Ce.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:function(e,r,t,n,o){return L(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0},ioctl:function(e,r,t){if(!e.stream_ops.ioctl)throw new Ce.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:function(e,r){if(void 0===r&&(r={}),r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=Ce.open(e,r.flags),o=Ce.stat(e).size,i=new Uint8Array(o);return Ce.read(n,i,0,o,0),"utf8"===r.encoding?t=Ee(i,0):"binary"===r.encoding&&(t=i),Ce.close(n),t},writeFile:function(e,r,t){void 0===t&&(t={}),t.flags=t.flags||577;var n=Ce.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(we(r)+1),i=be(r,o,0,o.length);Ce.write(n,o,0,i,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");Ce.write(n,r,0,r.byteLength,void 0,t.canOwn)}Ce.close(n)},cwd:function(){return Ce.currentPath},chdir:function(e){var r=Ce.lookupPath(e,{follow:!0});if(null===r.node)throw new Ce.ErrnoError(44);if(!Ce.isDir(r.node.mode))throw new Ce.ErrnoError(54);var t=Ce.nodePermissions(r.node,"x");if(t)throw new Ce.ErrnoError(t);Ce.currentPath=r.path},createDefaultDirectories:function(){Ce.mkdir("/tmp"),Ce.mkdir("/home"),Ce.mkdir("/home/web_user")},createDefaultDevices:function(){Ce.mkdir("/dev"),Ce.registerDevice(Ce.makedev(1,3),{read:function(){return 0},write:function(e,r,t,n,o){return n}}),Ce.mkdev("/dev/null",Ce.makedev(1,3)),Oe.register(Ce.makedev(5,0),Oe.default_tty_ops),Oe.register(Ce.makedev(6,0),Oe.default_tty1_ops),Ce.mkdev("/dev/tty",Ce.makedev(5,0)),Ce.mkdev("/dev/tty1",Ce.makedev(6,0));var e=new Uint8Array(1024),r=0,t=function(){return 0===r&&(r=he(e).byteLength),e[--r]};Ce.createDevice("/dev","random",t),Ce.createDevice("/dev","urandom",t),Ce.mkdir("/dev/shm"),Ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){Ce.mkdir("/proc");var e=Ce.mkdir("/proc/self");Ce.mkdir("/proc/self/fd"),Ce.mount({mount:function(){var r=Ce.createNode(e,"fd",16895,73);return r.node_ops={lookup:function(e,r){var t=+r,n=Ce.getStreamChecked(t),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return n.path}}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:function(){d.stdin?Ce.createDevice("/dev","stdin",d.stdin):Ce.symlink("/dev/tty","/dev/stdin"),d.stdout?Ce.createDevice("/dev","stdout",null,d.stdout):Ce.symlink("/dev/tty","/dev/stdout"),d.stderr?Ce.createDevice("/dev","stderr",null,d.stderr):Ce.symlink("/dev/tty1","/dev/stderr");var e=Ce.open("/dev/stdin",0),r=Ce.open("/dev/stdout",1),t=Ce.open("/dev/stderr",1);L(0===e.fd,"invalid handle for stdin ("+e.fd+")"),L(1===r.fd,"invalid handle for stdout ("+r.fd+")"),L(2===t.fd,"invalid handle for stderr ("+t.fd+")")},staticInit:function(){[44].forEach((function(e){Ce.genericErrors[e]=new Ce.ErrnoError(e),Ce.genericErrors[e].stack=""})),Ce.nameTable=new Array(4096),Ce.mount(ke,{},"/"),Ce.createDefaultDirectories(),Ce.createDefaultDevices(),Ce.createSpecialDirectories(),Ce.filesystems={MEMFS:ke}},init:function(e,r,t){L(!Ce.init.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Ce.init.initialized=!0,d.stdin=e||d.stdin,d.stdout=r||d.stdout,d.stderr=t||d.stderr,Ce.createStandardStreams()},quit:function(){Ce.init.initialized=!1,tr(0);for(var e=0;ethis.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},r.setDataGetter=function(e){this.getter=e},r.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,i=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,a=1048576;o||(a=n);var s=this;s.setDataGetter((function(e){var r=e*a,o=(e+1)*a-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,r){if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==a&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):_e(o.responseText||"")}(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&n||(a=n=1,n=this.getter(0).length,a=n,A("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=a,this.lengthKnown=!0},o(e,[{key:"length",get:function(){return this.lengthKnown||this.cacheLength(),this._length}},{key:"chunkSize",get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}]),e}();if("undefined"!=typeof XMLHttpRequest){if(!h)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s={isDevice:!1,contents:new a}}else s={isDevice:!1,url:t};var u=Ce.createFile(e,r,s,n,i);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,n);if(L(a>=0),i.slice)for(var s=0;s>2]=n.dev,D[t+4>>2]=n.mode,x[t+8>>2]=n.nlink,D[t+12>>2]=n.uid,D[t+16>>2]=n.gid,D[t+20>>2]=n.rdev,J=[n.size>>>0,(X=n.size,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+24>>2]=J[0],D[t+28>>2]=J[1],D[t+32>>2]=4096,D[t+36>>2]=n.blocks;var o=n.atime.getTime(),i=n.mtime.getTime(),a=n.ctime.getTime();return J=[Math.floor(o/1e3)>>>0,(X=Math.floor(o/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+40>>2]=J[0],D[t+44>>2]=J[1],x[t+48>>2]=o%1e3*1e3,J=[Math.floor(i/1e3)>>>0,(X=Math.floor(i/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+56>>2]=J[0],D[t+60>>2]=J[1],x[t+64>>2]=i%1e3*1e3,J=[Math.floor(a/1e3)>>>0,(X=Math.floor(a/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+72>>2]=J[0],D[t+76>>2]=J[1],x[t+80>>2]=a%1e3*1e3,J=[n.ino>>>0,(X=n.ino,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+88>>2]=J[0],D[t+92>>2]=J[1],0},doMsync:function(e,r,t,n,o){if(!Ce.isFile(r.node.mode))throw new Ce.ErrnoError(43);if(2&n)return 0;var i=F.slice(e,e+t);Ce.msync(r,i,o,t,n)},getStreamFromFD:function(e){return Ce.getStreamChecked(e)},varargs:void 0,getStr:function(e){return De(e)}},Ie=function(e,r){return L(e==e>>>0||e==(0|e)),L(r===(0|r)),r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN},Le=[0,31,60,91,121,152,182,213,244,274,305,335],Ne=[0,31,59,90,120,151,181,212,243,273,304,334],Re=function(e){var r;return((r=e.getFullYear())%4!=0||r%100==0&&r%400!=0?Ne:Le)[e.getMonth()]+e.getDate()-1},Ue=function(e,r,t){return L("number"==typeof t,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),be(e,F,r,t)};Se=function(){return performance.now()};var Be,je,$e=function(e){var r=k.buffer,t=(e-r.byteLength+65535)/65536;try{return k.grow(t),N(),1}catch(t){M("growMemory: Attempted to grow heap from "+r.byteLength+" bytes to "+e+" bytes, but got error: "+t)}},We={},He=function(){if(!He.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==("undefined"==typeof navigator?"undefined":u(navigator))&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:_||"./this.program"};for(var r in We)void 0===We[r]?delete e[r]:e[r]=We[r];var t=[];for(var r in e)t.push(r+"="+e[r]);He.strings=t}return He.strings},ze=function(e){return sr(e)},Ve=function(e,r,t,n,o){var i={string:function(e){var r=0;return null!=e&&0!==e&&(r=function(e){var r=we(e)+1,t=ze(r);return Ue(e,t,r),t}(e)),r},array:function(e){var r,t,n=ze(e.length);return t=n,L((r=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),P.set(r,t),n}},a=function(e){var r=d["_"+e];return L(r,"Cannot call unknown function "+e+", make sure it is exported"),r}(e),s=[],u=0;if(L("array"!==r,'Return type should not be "array".'),n)for(var c=0;c>7)},Ye=function(e,r){var t;if(L(!r.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function(function(e){L(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var r={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:"v"==e[0]?[]:[r[e[0]]]},n=1;n=Qe.length&&(Qe.length=e+1),Qe[e]=r=Be.get(e)),L(Be.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},Ke=function(e){return je||(je=new WeakMap,function(e,r){if(je)for(var t=e;t>1]=2,0}return-28}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,r,t,n){xe.varargs=n;try{r=xe.getStr(r),r=xe.calculateAt(e,r);var o=n?fe():0;return Ce.open(r,t,o).fd}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:function(){q("native code called abort()")},_emscripten_get_now_is_monotonic:function(){return 1},_emscripten_memcpy_js:function(e,r,t){return F.copyWithin(e,r,r+t)},_gmtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getUTCSeconds(),D[t+4>>2]=o.getUTCMinutes(),D[t+8>>2]=o.getUTCHours(),D[t+12>>2]=o.getUTCDate(),D[t+16>>2]=o.getUTCMonth(),D[t+20>>2]=o.getUTCFullYear()-1900,D[t+24>>2]=o.getUTCDay();var i=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),a=(o.getTime()-i)/864e5|0;D[t+28>>2]=a},_localtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getSeconds(),D[t+4>>2]=o.getMinutes(),D[t+8>>2]=o.getHours(),D[t+12>>2]=o.getDate(),D[t+16>>2]=o.getMonth(),D[t+20>>2]=o.getFullYear()-1900,D[t+24>>2]=o.getDay();var i=0|Re(o);D[t+28>>2]=i,D[t+36>>2]=-60*o.getTimezoneOffset();var a=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=a.getTimezoneOffset(),c=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));D[t+32>>2]=c},_mktime_js:function(e){var r,t=function(){var r=new Date(D[e+20>>2]+1900,D[e+16>>2],D[e+12>>2],D[e+8>>2],D[e+4>>2],D[e>>2],0),t=D[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),i=new Date(r.getFullYear(),6,1).getTimezoneOffset(),a=o.getTimezoneOffset(),s=Math.min(a,i);if(t<0)D[e+32>>2]=Number(i!=a&&s==n);else if(t>0!=(s==n)){var u=Math.max(a,i),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}D[e+24>>2]=r.getDay();var l=0|Re(r);D[e+28>>2]=l,D[e>>2]=r.getSeconds(),D[e+4>>2]=r.getMinutes(),D[e+8>>2]=r.getHours(),D[e+12>>2]=r.getDate(),D[e+16>>2]=r.getMonth(),D[e+20>>2]=r.getYear();var d=r.getTime();return isNaN(d)?-1:d/1e3}();return X=t,r=+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0,nr(r),t>>>0},_tzset_js:function(e,r,t,n){var o=(new Date).getFullYear(),i=new Date(o,0,1),a=new Date(o,6,1),s=i.getTimezoneOffset(),u=a.getTimezoneOffset(),c=Math.max(s,u);x[e>>2]=60*c,D[r>>2]=Number(s!=u);var l=function(e){return e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1]},d=l(i),f=l(a);L(d),L(f),L(we(d)<=16,"timezone name truncated to fit in TZNAME_MAX ("+d+")"),L(we(f)<=16,"timezone name truncated to fit in TZNAME_MAX ("+f+")"),u>>=0)>r);var t=2147483648;if(e>t)return M("Cannot enlarge memory, requested "+e+" bytes, but the limit is "+t+" bytes!"),!1;for(var n,o,i=1;i<=4;i*=2){var a=r*(1+.2/i);a=Math.min(a,e+100663296);var s=Math.min(t,(n=Math.max(e,a))+((o=65536)-n%o)%o);if($e(s))return!0}return M("Failed to grow the heap from "+r+" bytes to "+s+" bytes, not enough memory!"),!1},environ_get:function(e,r){var t=0;return He().forEach((function(n,o){var i=r+t;x[e+4*o>>2]=i,function(e,r){for(var t=0;t