From 9857e164cdaf1ead0da3c4963b608590a0017f5b Mon Sep 17 00:00:00 2001 From: ShineShao Date: Thu, 1 Aug 2024 12:54:14 +0800 Subject: [PATCH] version: 0.1.0 --- dist/decoder.worker.js | 2 +- dist/index.esm.js | 4 ++-- dist/index.js | 4 ++-- dist/index.umd.js | 4 ++-- package.json | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dist/decoder.worker.js b/dist/decoder.worker.js index e544318..4b8dbac 100644 --- a/dist/decoder.worker.js +++ b/dist/decoder.worker.js @@ -1,6 +1,6 @@ /* * -* DecoderWorker.js v0.1.0-beta.2 +* DecoderWorker.js v0.1.0 * Copyright (c) 2024-8-1 Ezviz-OpenBiz * . * diff --git a/dist/index.esm.js b/dist/index.esm.js index 55da091..aa87c8a 100644 --- a/dist/index.esm.js +++ b/dist/index.esm.js @@ -1,8 +1,8 @@ /* * -* HlsPlayer.js v0.1.0-beta.2 +* HlsPlayer.js v0.1.0 * Copyright (c) 2024-8-1 Ezviz-OpenBiz * . * */ -import e,{Video as t}from"@ezuikit/player-base";import i from"@ezuikit/utils-collect";import n from"hls.js";import{addVc as s,getStaticPath as r}from"@ezuikit/utils-tools";import o from"@ezuikit/utils-logger";import{merge as a}from"lodash-es";import l from"eventemitter3";var u=1,h=2,c=3,d="aac",p="h265",f="hevc",m="m3u8",v="hls",g=0,y=1,_=600,T=400,w=30,P=40,C=!1,x=44100,S=20,L="ONCE",b="SWAP",R=0,D=265,E=1001,k=1002,M=1003;var A,I=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function B(){return(new Date).getTime()}var F=window.AudioContext||(null==(A=window)?void 0:A.webkitAudioContext),N=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||x,appendType:e.appendType||g,playMode:e.playMode||b,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new F({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+(B()-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==(n=this.sourceList[e])||null==(i=n.start)||i.call(n),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 r,o,a=this.sourceList[e];return a.connect(this.gainNode),(null==a?void 0:a.startState)||null==(o=this.sourceList[e])||null==(r=o.start)||r.call(o),a.startState=!0,a.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=B();try{this.audioCtx.decodeAudioData(l,(function(t){var i,n;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(n=s.sourceList[e])||null==(i=n.start)||i.call(n),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,n=null,s=0;s",e)}},e}(),O=function(){function e(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var t=e.prototype;return t.appendCacheByCacheYuv=function(e){return this.yuvCache.push(e),this.yuvCache.length>=this.limit?(this.shiftYuv(),h):u},t.getState=function(){return this.yuvCache.length<=0?c:this.yuvCache.length>=this.limit?h:u},t.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},t.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},e}(),U=function(){function e(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r}return e.prototype.setYuv=function(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r},e}(),$=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 n=this.gl;n.activeTexture([n.TEXTURE0,n.TEXTURE1,n.TEXTURE2][e]),n.bindTexture(n.TEXTURE_2D,this.texture),n.uniform1i(n.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var n=this.gl;n.bindTexture(n.TEXTURE_2D,this.texture),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,i)},e}(),W=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"),n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,i),this.gl.compileShader(n);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"),r=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(r,s),this.gl.compileShader(r),this.gl.attachShader(this.program,n),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var o=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(o);var a=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(a),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(o,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(a,2,this.gl.FLOAT,!1,0,0),this.gl.y=new $(this.gl),this.gl.u=new $(this.gl),this.gl.v=new $(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,n,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(n,s,e),this.gl.u.fill(n>>1,s>>1,t),this.gl.v.fill(n>>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}(),V=function(e,t){return{cmd:e,data:t}},j="wasmLoading",Y="wasmLoaded",H="wasmFailed",X="videoCallback",Q="decodeCodecContext",z="destroy",G="demuxTsStream",J="demuxCoreReceive",q="readPacket",K="readPacketEnd",Z="mediaInfo",ee="ezui-hls",te={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},ie={disableContextmenu:!0},ne=function(){function e(e){void 0===e&&(e={}),this.options=Object.assign({},ie,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=ee+"-video",this._$container=document.getElementById(this.options.id),this._render()}var i=e.prototype;return i._render=function(){var e,i;if("video"===this.options.nodeName)this.$video=new t(this._$container,this.options).$video;else{var n;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(n=this.$video)||n.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==(i=this.event)||null==(e=i.emit)||e.call(i,"rendered")},i._isVideo=function(){return"VIDEO"===this.$video.nodeName},i.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},e}();function se(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===k&&e.play(e.playParams),e.isCaching=E)}),40))}},i._playFunc=function(){var e=!1;if(B()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=B(),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 n=parseInt(i/this.frameTimeSec+""),s=0;s",e,n,i),n>=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=B();t._playFunc(),t.preCostTime=B()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},i.stop=function(){this.destroy(),this.stream=new Uint8Array},i.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(V(z)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},i.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 n=this.stream.subarray(t);return this.stream=new Uint8Array,n}var s="0 0 1"===this.stream.slice(0,3).join(" "),r="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||r){if(-1===t)t=i;else{if(e<=1){var o=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),o}e-=1}i+=3}}return!1},i.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},i.drawImage=function(e,t,i,n,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var r=e*t,o=e/2*(t/2),a=new Uint8Array(r+2*o);a.set(i,0),a.set(n,r),a.set(s,r+o),this.gl.renderFrame(i,n,s,e,t),a=null},i.checkDisplaySize=function(e,t){var i,n=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),r=+(this.options.height/t).toFixed(2),o=n?s:r,a=this.options.fixed,l=a?this.options.width:parseInt(e*o+""),u=a?this.options.height:parseInt(t*o+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/u>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,u]},i._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===X){var n=i.data,s=n.ptsSec,r=n.strideY,o=n.height;n.width;var a=n.bufY,l=n.bufU,u=n.bufV,h=new U(s,r,o,a,l,u);e.cacheYuvBuf.appendCacheByCacheYuv(h),h=null}}},i.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new W(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new N({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},se(t,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),t}(ne),le=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],ue={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(ue.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return ue.isBlank(e)||ue.isComment(e)},defaultMinDur:99999},he=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=v,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 n=function(t){return new Promise((function(i,n){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(){n(new Error("Network error."))},s.send()}))};n(e).then((function(s){if(t._retry=10,i._uriParse(e)){var r=i._m3u8Parse(s);if("number"==typeof r&&r>=0)var o=setTimeout((function(){i.fetchM3u8(e),clearTimeout(o)}),200*r)}return n=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),n=null,t._retry>=1)var r=setTimeout((function(){i.fetchM3u8(e),clearTimeout(r)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,n=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],n=t[1].split("/"),this._preURI=i+"://"):n=t[0].split("/");for(var s=0;sc&&(s=c);var d,p=n[o+=1],f=null;if(p.includes("http"))f=p;else{if("/"===p[0]){var v=this._preURI.split("//"),g=v[v.length-1].split("/");this._preURI=v[0]+"//"+g[0]}f=this._preURI+p}if(!this._slices.includes(f))this._slices.push(f),null==this||null==(d=this.onTransportStream)||d.call(this,f,c)}}}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=ue.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),ce=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=[],n=e,s=0;s>4==15){var r=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(r<=0)continue;var o=t.subarray(s,s+r),a=new Uint8Array(r);a.set(o,0),i.push({ptime:n,data:a}),n+=this.frameDurSec,s+=r}else s+=1;return i},e}(),de="M3U8",pe="TS",fe="FETCH",me=function(){function e(){}return e.init=function(t){e.collect=new i(t)},e.send=function(t,i){var n,s;null==(s=e.collect)||null==(n=s.send)||n.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function ve(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(n){var s,r,o,a;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",n),null==(r=t.event)||null==(s=r.emit)||s.call(r,pe,{data:n}),null==(a=t.event)||null==(o=a.emit)||o.call(a,fe,{data:n,type:pe}),null==i||i.onDemuxedFailed(n,e),me.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage(V(G,{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===f||this.mediaInfo.vCodec===p},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 Z:var n,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(n=s.emit)||n.call(s,"mediaInfo",e.mediaInfo);break;case J:var r;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new ce(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(r=e.onDemuxed)||r.call(e)}}))},ve(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),_e=function(){function e(e,t,i,n){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=n}return e.prototype.setFrame=function(e,t,i,n){this.pts=e,this.isKey=t,this.data=i,this.video=n},e}(),Te=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 he(e),this.mpegTsDemux=new ye(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===m?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,n){t.logger.error("[M3u8] onDemuxedFailed: ",e,n),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(V(q))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===Ae.__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 n=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(n)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var r,o,a,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(o=t.event)||null==(r=o.emit)||r.call(o,de,{data:e}),null==(l=t.event)||null==(a=l.emit)||a.call(l,fe,{data:e,type:de}),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 q:var n,s=i.data,r=s.type,o=s.pts,a=s.ptime,l=s.keyframe,u=s.data,h=s.layer;if(u=new Uint8Array(u),1===r&&e.mpegTsDemux.mediaInfo.aCodec===d&&(u=e.mpegTsDemux.aacDec.sliceAACFrames(a,u)),0===r){var c=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var n=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return n.set(t.vps,0),n.set(t.sps,t.vps.length),n.set(t.pps,t.vps.length+t.sps.length),n.set(t.sei,t.vps.length+t.sps.length+t.pps.length),n.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),n}(h),p=o,f=new _e(p,1===l,c,!0);e.vPreFramePTS=p,null==e||e.onSamples(e.onReadyOBJ,f)}else if(1===r){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var v=u,g=0;g0&&(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")})))},we(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(ne);var Se="wasm_loaded",Le="wasm_failed",be="init";function Re(e,t){return Re=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Re(e,t)}var De=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=s(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=a({},te,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=o(e.options.loggerOptions),e.event=new l,e.logger.log("HlsPlayer version: ",Ae.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=ee+"-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&&Re(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 Ee(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:R},!I())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(me.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===R){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 me.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return me.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===R&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage(V(z)),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 me.send(1,{name:"getVersion"}),"0.1.0-beta.2"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new Te({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 xe(ke({},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 j:t.__HLS_WASM_DecoderState__=0;break;case Y:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(Se),i._decoderWorker.postMessage(V("registerWasmPlayer")),i._m3u8Entry();break;case H:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(Le,s),me.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||R,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new ae(ke({},h.options,{sampleRate:i,fps:t,appendHevcType:y,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(me.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},Ee(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(De);Ae.__HLS_WASM_DecoderState__=0,Ae.version="0.1.0-beta.2";export{Ae as default}; +import e,{Video as t}from"@ezuikit/player-base";import i from"@ezuikit/utils-collect";import n from"hls.js";import{addVc as s,getStaticPath as r}from"@ezuikit/utils-tools";import o from"@ezuikit/utils-logger";import{merge as a}from"lodash-es";import l from"eventemitter3";var u=1,h=2,c=3,d="aac",p="h265",f="hevc",m="m3u8",v="hls",g=0,y=1,_=600,T=400,w=30,P=40,C=!1,x=44100,S=20,L="ONCE",b="SWAP",R=0,D=265,E=1001,k=1002,M=1003;var A,I=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function B(){return(new Date).getTime()}var F=window.AudioContext||(null==(A=window)?void 0:A.webkitAudioContext),N=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||x,appendType:e.appendType||g,playMode:e.playMode||b,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new F({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+(B()-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==(n=this.sourceList[e])||null==(i=n.start)||i.call(n),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 r,o,a=this.sourceList[e];return a.connect(this.gainNode),(null==a?void 0:a.startState)||null==(o=this.sourceList[e])||null==(r=o.start)||r.call(o),a.startState=!0,a.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=B();try{this.audioCtx.decodeAudioData(l,(function(t){var i,n;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(n=s.sourceList[e])||null==(i=n.start)||i.call(n),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,n=null,s=0;s",e)}},e}(),O=function(){function e(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var t=e.prototype;return t.appendCacheByCacheYuv=function(e){return this.yuvCache.push(e),this.yuvCache.length>=this.limit?(this.shiftYuv(),h):u},t.getState=function(){return this.yuvCache.length<=0?c:this.yuvCache.length>=this.limit?h:u},t.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},t.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},e}(),U=function(){function e(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r}return e.prototype.setYuv=function(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r},e}(),$=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 n=this.gl;n.activeTexture([n.TEXTURE0,n.TEXTURE1,n.TEXTURE2][e]),n.bindTexture(n.TEXTURE_2D,this.texture),n.uniform1i(n.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var n=this.gl;n.bindTexture(n.TEXTURE_2D,this.texture),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,i)},e}(),W=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"),n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,i),this.gl.compileShader(n);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"),r=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(r,s),this.gl.compileShader(r),this.gl.attachShader(this.program,n),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var o=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(o);var a=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(a),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(o,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(a,2,this.gl.FLOAT,!1,0,0),this.gl.y=new $(this.gl),this.gl.u=new $(this.gl),this.gl.v=new $(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,n,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(n,s,e),this.gl.u.fill(n>>1,s>>1,t),this.gl.v.fill(n>>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}(),V=function(e,t){return{cmd:e,data:t}},j="wasmLoading",Y="wasmLoaded",H="wasmFailed",X="videoCallback",Q="decodeCodecContext",z="destroy",G="demuxTsStream",J="demuxCoreReceive",q="readPacket",K="readPacketEnd",Z="mediaInfo",ee="ezui-hls",te={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},ie={disableContextmenu:!0},ne=function(){function e(e){void 0===e&&(e={}),this.options=Object.assign({},ie,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=ee+"-video",this._$container=document.getElementById(this.options.id),this._render()}var i=e.prototype;return i._render=function(){var e,i;if("video"===this.options.nodeName)this.$video=new t(this._$container,this.options).$video;else{var n;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(n=this.$video)||n.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==(i=this.event)||null==(e=i.emit)||e.call(i,"rendered")},i._isVideo=function(){return"VIDEO"===this.$video.nodeName},i.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},e}();function se(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===k&&e.play(e.playParams),e.isCaching=E)}),40))}},i._playFunc=function(){var e=!1;if(B()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=B(),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 n=parseInt(i/this.frameTimeSec+""),s=0;s",e,n,i),n>=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=B();t._playFunc(),t.preCostTime=B()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},i.stop=function(){this.destroy(),this.stream=new Uint8Array},i.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(V(z)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},i.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 n=this.stream.subarray(t);return this.stream=new Uint8Array,n}var s="0 0 1"===this.stream.slice(0,3).join(" "),r="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||r){if(-1===t)t=i;else{if(e<=1){var o=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),o}e-=1}i+=3}}return!1},i.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},i.drawImage=function(e,t,i,n,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var r=e*t,o=e/2*(t/2),a=new Uint8Array(r+2*o);a.set(i,0),a.set(n,r),a.set(s,r+o),this.gl.renderFrame(i,n,s,e,t),a=null},i.checkDisplaySize=function(e,t){var i,n=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),r=+(this.options.height/t).toFixed(2),o=n?s:r,a=this.options.fixed,l=a?this.options.width:parseInt(e*o+""),u=a?this.options.height:parseInt(t*o+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/u>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,u]},i._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===X){var n=i.data,s=n.ptsSec,r=n.strideY,o=n.height;n.width;var a=n.bufY,l=n.bufU,u=n.bufV,h=new U(s,r,o,a,l,u);e.cacheYuvBuf.appendCacheByCacheYuv(h),h=null}}},i.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new W(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new N({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},se(t,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),t}(ne),le=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],ue={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(ue.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return ue.isBlank(e)||ue.isComment(e)},defaultMinDur:99999},he=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=v,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 n=function(t){return new Promise((function(i,n){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(){n(new Error("Network error."))},s.send()}))};n(e).then((function(s){if(t._retry=10,i._uriParse(e)){var r=i._m3u8Parse(s);if("number"==typeof r&&r>=0)var o=setTimeout((function(){i.fetchM3u8(e),clearTimeout(o)}),200*r)}return n=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),n=null,t._retry>=1)var r=setTimeout((function(){i.fetchM3u8(e),clearTimeout(r)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,n=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],n=t[1].split("/"),this._preURI=i+"://"):n=t[0].split("/");for(var s=0;sc&&(s=c);var d,p=n[o+=1],f=null;if(p.includes("http"))f=p;else{if("/"===p[0]){var v=this._preURI.split("//"),g=v[v.length-1].split("/");this._preURI=v[0]+"//"+g[0]}f=this._preURI+p}if(!this._slices.includes(f))this._slices.push(f),null==this||null==(d=this.onTransportStream)||d.call(this,f,c)}}}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=ue.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),ce=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=[],n=e,s=0;s>4==15){var r=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(r<=0)continue;var o=t.subarray(s,s+r),a=new Uint8Array(r);a.set(o,0),i.push({ptime:n,data:a}),n+=this.frameDurSec,s+=r}else s+=1;return i},e}(),de="M3U8",pe="TS",fe="FETCH",me=function(){function e(){}return e.init=function(t){e.collect=new i(t)},e.send=function(t,i){var n,s;null==(s=e.collect)||null==(n=s.send)||n.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function ve(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(n){var s,r,o,a;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",n),null==(r=t.event)||null==(s=r.emit)||s.call(r,pe,{data:n}),null==(a=t.event)||null==(o=a.emit)||o.call(a,fe,{data:n,type:pe}),null==i||i.onDemuxedFailed(n,e),me.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage(V(G,{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===f||this.mediaInfo.vCodec===p},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 Z:var n,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(n=s.emit)||n.call(s,"mediaInfo",e.mediaInfo);break;case J:var r;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new ce(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(r=e.onDemuxed)||r.call(e)}}))},ve(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),_e=function(){function e(e,t,i,n){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=n}return e.prototype.setFrame=function(e,t,i,n){this.pts=e,this.isKey=t,this.data=i,this.video=n},e}(),Te=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 he(e),this.mpegTsDemux=new ye(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===m?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,n){t.logger.error("[M3u8] onDemuxedFailed: ",e,n),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(V(q))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===Ae.__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 n=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(n)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var r,o,a,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(o=t.event)||null==(r=o.emit)||r.call(o,de,{data:e}),null==(l=t.event)||null==(a=l.emit)||a.call(l,fe,{data:e,type:de}),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 q:var n,s=i.data,r=s.type,o=s.pts,a=s.ptime,l=s.keyframe,u=s.data,h=s.layer;if(u=new Uint8Array(u),1===r&&e.mpegTsDemux.mediaInfo.aCodec===d&&(u=e.mpegTsDemux.aacDec.sliceAACFrames(a,u)),0===r){var c=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var n=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return n.set(t.vps,0),n.set(t.sps,t.vps.length),n.set(t.pps,t.vps.length+t.sps.length),n.set(t.sei,t.vps.length+t.sps.length+t.pps.length),n.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),n}(h),p=o,f=new _e(p,1===l,c,!0);e.vPreFramePTS=p,null==e||e.onSamples(e.onReadyOBJ,f)}else if(1===r){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var v=u,g=0;g0&&(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")})))},we(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(ne);var Se="wasm_loaded",Le="wasm_failed",be="init";function Re(e,t){return Re=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Re(e,t)}var De=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=s(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=a({},te,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=o(e.options.loggerOptions),e.event=new l,e.logger.log("HlsPlayer version: ",Ae.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=ee+"-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&&Re(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 Ee(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:R},!I())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(me.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===R){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 me.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return me.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===R&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage(V(z)),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 me.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new Te({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 xe(ke({},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 j:t.__HLS_WASM_DecoderState__=0;break;case Y:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(Se),i._decoderWorker.postMessage(V("registerWasmPlayer")),i._m3u8Entry();break;case H:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(Le,s),me.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||R,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new ae(ke({},h.options,{sampleRate:i,fps:t,appendHevcType:y,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(me.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},Ee(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(De);Ae.__HLS_WASM_DecoderState__=0,Ae.version="0.1.0";export{Ae as default}; diff --git a/dist/index.js b/dist/index.js index 049f803..7cc4cad 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,8 +1,8 @@ /* * -* HlsPlayer.js v0.1.0-beta.2 +* HlsPlayer.js v0.1.0 * Copyright (c) 2024-8-1 Ezviz-OpenBiz * . * */ -"use strict";var e=require("@ezuikit/player-base"),t=require("@ezuikit/utils-collect"),i=require("hls.js"),n=require("@ezuikit/utils-tools"),s=require("@ezuikit/utils-logger"),r=require("lodash-es"),o=require("eventemitter3"),a=1,l=2,u=3,h="aac",c="h265",d="hevc",p="m3u8",f="hls",m=0,v=1,g=600,y=400,_=30,T=40,P=!1,w=44100,C=20,x="ONCE",S="SWAP",L=0,b=265,R=1001,D=1002,E=1003;var k,M=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function A(){return(new Date).getTime()}var I=window.AudioContext||(null==(k=window)?void 0:k.webkitAudioContext),B=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||w,appendType:e.appendType||m,playMode:e.playMode||S,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new I({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+(A()-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==(n=this.sourceList[e])||null==(i=n.start)||i.call(n),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 r,o,a=this.sourceList[e];return a.connect(this.gainNode),(null==a?void 0:a.startState)||null==(o=this.sourceList[e])||null==(r=o.start)||r.call(o),a.startState=!0,a.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=A();try{this.audioCtx.decodeAudioData(l,(function(t){var i,n;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(n=s.sourceList[e])||null==(i=n.start)||i.call(n),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,n=null,s=0;s",e)}},e}(),F=function(){function e(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var t=e.prototype;return t.appendCacheByCacheYuv=function(e){return this.yuvCache.push(e),this.yuvCache.length>=this.limit?(this.shiftYuv(),l):a},t.getState=function(){return this.yuvCache.length<=0?u:this.yuvCache.length>=this.limit?l:a},t.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},t.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},e}(),N=function(){function e(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r}return e.prototype.setYuv=function(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r},e}(),O=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 n=this.gl;n.activeTexture([n.TEXTURE0,n.TEXTURE1,n.TEXTURE2][e]),n.bindTexture(n.TEXTURE_2D,this.texture),n.uniform1i(n.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var n=this.gl;n.bindTexture(n.TEXTURE_2D,this.texture),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,i)},e}(),U=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"),n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,i),this.gl.compileShader(n);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"),r=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(r,s),this.gl.compileShader(r),this.gl.attachShader(this.program,n),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var o=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(o);var a=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(a),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(o,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(a,2,this.gl.FLOAT,!1,0,0),this.gl.y=new O(this.gl),this.gl.u=new O(this.gl),this.gl.v=new O(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,n,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(n,s,e),this.gl.u.fill(n>>1,s>>1,t),this.gl.v.fill(n>>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}(),$=function(e,t){return{cmd:e,data:t}},W="wasmLoading",V="wasmLoaded",j="wasmFailed",Y="videoCallback",H="decodeCodecContext",X="destroy",Q="demuxTsStream",z="demuxCoreReceive",q="readPacket",G="readPacketEnd",J="mediaInfo",K="ezui-hls",Z={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},ee={disableContextmenu:!0},te=function(){function t(e){void 0===e&&(e={}),this.options=Object.assign({},ee,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=K+"-video",this._$container=document.getElementById(this.options.id),this._render()}var i=t.prototype;return i._render=function(){var t,i;if("video"===this.options.nodeName)this.$video=new e.Video(this._$container,this.options).$video;else{var n;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(n=this.$video)||n.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==(i=this.event)||null==(t=i.emit)||t.call(i,"rendered")},i._isVideo=function(){return"VIDEO"===this.$video.nodeName},i.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},t}();function ie(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===D&&e.play(e.playParams),e.isCaching=R)}),40))}},i._playFunc=function(){var e=!1;if(A()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=A(),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 n=parseInt(i/this.frameTimeSec+""),s=0;s",e,n,i),n>=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=A();t._playFunc(),t.preCostTime=A()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},i.stop=function(){this.destroy(),this.stream=new Uint8Array},i.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($(X)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},i.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 n=this.stream.subarray(t);return this.stream=new Uint8Array,n}var s="0 0 1"===this.stream.slice(0,3).join(" "),r="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||r){if(-1===t)t=i;else{if(e<=1){var o=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),o}e-=1}i+=3}}return!1},i.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},i.drawImage=function(e,t,i,n,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var r=e*t,o=e/2*(t/2),a=new Uint8Array(r+2*o);a.set(i,0),a.set(n,r),a.set(s,r+o),this.gl.renderFrame(i,n,s,e,t),a=null},i.checkDisplaySize=function(e,t){var i,n=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),r=+(this.options.height/t).toFixed(2),o=n?s:r,a=this.options.fixed,l=a?this.options.width:parseInt(e*o+""),u=a?this.options.height:parseInt(t*o+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/u>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,u]},i._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===Y){var n=i.data,s=n.ptsSec,r=n.strideY,o=n.height;n.width;var a=n.bufY,l=n.bufU,u=n.bufV,h=new N(s,r,o,a,l,u);e.cacheYuvBuf.appendCacheByCacheYuv(h),h=null}}},i.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new U(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new B({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},ie(t,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),t}(te),oe=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],ae={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(ae.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return ae.isBlank(e)||ae.isComment(e)},defaultMinDur:99999},le=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=f,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 n=function(t){return new Promise((function(i,n){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(){n(new Error("Network error."))},s.send()}))};n(e).then((function(s){if(t._retry=10,i._uriParse(e)){var r=i._m3u8Parse(s);if("number"==typeof r&&r>=0)var o=setTimeout((function(){i.fetchM3u8(e),clearTimeout(o)}),200*r)}return n=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),n=null,t._retry>=1)var r=setTimeout((function(){i.fetchM3u8(e),clearTimeout(r)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,n=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],n=t[1].split("/"),this._preURI=i+"://"):n=t[0].split("/");for(var s=0;sc&&(s=c);var d,f=n[o+=1],m=null;if(f.includes("http"))m=f;else{if("/"===f[0]){var v=this._preURI.split("//"),g=v[v.length-1].split("/");this._preURI=v[0]+"//"+g[0]}m=this._preURI+f}if(!this._slices.includes(m))this._slices.push(m),null==this||null==(d=this.onTransportStream)||d.call(this,m,c)}}}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=ae.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),ue=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=[],n=e,s=0;s>4==15){var r=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(r<=0)continue;var o=t.subarray(s,s+r),a=new Uint8Array(r);a.set(o,0),i.push({ptime:n,data:a}),n+=this.frameDurSec,s+=r}else s+=1;return i},e}(),he="M3U8",ce="TS",de="FETCH",pe=function(){function e(){}return e.init=function(i){e.collect=new t(i)},e.send=function(t,i){var n,s;null==(s=e.collect)||null==(n=s.send)||n.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function fe(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(n){var s,r,o,a;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",n),null==(r=t.event)||null==(s=r.emit)||s.call(r,ce,{data:n}),null==(a=t.event)||null==(o=a.emit)||o.call(a,de,{data:n,type:ce}),null==i||i.onDemuxedFailed(n,e),pe.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage($(Q,{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===d||this.mediaInfo.vCodec===c},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 J:var n,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(n=s.emit)||n.call(s,"mediaInfo",e.mediaInfo);break;case z:var r;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new ue(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(r=e.onDemuxed)||r.call(e)}}))},fe(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),ge=function(){function e(e,t,i,n){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=n}return e.prototype.setFrame=function(e,t,i,n){this.pts=e,this.isKey=t,this.data=i,this.video=n},e}(),ye=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 le(e),this.mpegTsDemux=new ve(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===p?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,n){t.logger.error("[M3u8] onDemuxedFailed: ",e,n),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($(q))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===ke.__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 n=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(n)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var r,o,a,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(o=t.event)||null==(r=o.emit)||r.call(o,he,{data:e}),null==(l=t.event)||null==(a=l.emit)||a.call(l,de,{data:e,type:he}),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 q:var n,s=i.data,r=s.type,o=s.pts,a=s.ptime,l=s.keyframe,u=s.data,c=s.layer;if(u=new Uint8Array(u),1===r&&e.mpegTsDemux.mediaInfo.aCodec===h&&(u=e.mpegTsDemux.aacDec.sliceAACFrames(a,u)),0===r){var d=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var n=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return n.set(t.vps,0),n.set(t.sps,t.vps.length),n.set(t.pps,t.vps.length+t.sps.length),n.set(t.sei,t.vps.length+t.sps.length+t.pps.length),n.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),n}(c),p=o,f=new ge(p,1===l,d,!0);e.vPreFramePTS=p,null==e||e.onSamples(e.onReadyOBJ,f)}else if(1===r){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var v=u,g=0;g0&&(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-beta.2"},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-beta.2",module.exports=ke; +"use strict";var e=require("@ezuikit/player-base"),t=require("@ezuikit/utils-collect"),i=require("hls.js"),n=require("@ezuikit/utils-tools"),s=require("@ezuikit/utils-logger"),r=require("lodash-es"),o=require("eventemitter3"),a=1,l=2,u=3,h="aac",c="h265",d="hevc",p="m3u8",f="hls",m=0,v=1,g=600,y=400,_=30,T=40,P=!1,w=44100,C=20,x="ONCE",S="SWAP",L=0,b=265,R=1001,D=1002,E=1003;var k,M=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function A(){return(new Date).getTime()}var I=window.AudioContext||(null==(k=window)?void 0:k.webkitAudioContext),B=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||w,appendType:e.appendType||m,playMode:e.playMode||S,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new I({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+(A()-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==(n=this.sourceList[e])||null==(i=n.start)||i.call(n),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 r,o,a=this.sourceList[e];return a.connect(this.gainNode),(null==a?void 0:a.startState)||null==(o=this.sourceList[e])||null==(r=o.start)||r.call(o),a.startState=!0,a.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=A();try{this.audioCtx.decodeAudioData(l,(function(t){var i,n;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(n=s.sourceList[e])||null==(i=n.start)||i.call(n),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,n=null,s=0;s",e)}},e}(),F=function(){function e(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var t=e.prototype;return t.appendCacheByCacheYuv=function(e){return this.yuvCache.push(e),this.yuvCache.length>=this.limit?(this.shiftYuv(),l):a},t.getState=function(){return this.yuvCache.length<=0?u:this.yuvCache.length>=this.limit?l:a},t.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},t.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},e}(),N=function(){function e(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r}return e.prototype.setYuv=function(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r},e}(),O=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 n=this.gl;n.activeTexture([n.TEXTURE0,n.TEXTURE1,n.TEXTURE2][e]),n.bindTexture(n.TEXTURE_2D,this.texture),n.uniform1i(n.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var n=this.gl;n.bindTexture(n.TEXTURE_2D,this.texture),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,i)},e}(),U=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"),n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,i),this.gl.compileShader(n);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"),r=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(r,s),this.gl.compileShader(r),this.gl.attachShader(this.program,n),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var o=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(o);var a=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(a),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(o,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(a,2,this.gl.FLOAT,!1,0,0),this.gl.y=new O(this.gl),this.gl.u=new O(this.gl),this.gl.v=new O(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,n,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(n,s,e),this.gl.u.fill(n>>1,s>>1,t),this.gl.v.fill(n>>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}(),$=function(e,t){return{cmd:e,data:t}},W="wasmLoading",V="wasmLoaded",j="wasmFailed",Y="videoCallback",H="decodeCodecContext",X="destroy",Q="demuxTsStream",z="demuxCoreReceive",q="readPacket",G="readPacketEnd",J="mediaInfo",K="ezui-hls",Z={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},ee={disableContextmenu:!0},te=function(){function t(e){void 0===e&&(e={}),this.options=Object.assign({},ee,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=K+"-video",this._$container=document.getElementById(this.options.id),this._render()}var i=t.prototype;return i._render=function(){var t,i;if("video"===this.options.nodeName)this.$video=new e.Video(this._$container,this.options).$video;else{var n;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(n=this.$video)||n.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==(i=this.event)||null==(t=i.emit)||t.call(i,"rendered")},i._isVideo=function(){return"VIDEO"===this.$video.nodeName},i.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},t}();function ie(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===D&&e.play(e.playParams),e.isCaching=R)}),40))}},i._playFunc=function(){var e=!1;if(A()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=A(),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 n=parseInt(i/this.frameTimeSec+""),s=0;s",e,n,i),n>=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=A();t._playFunc(),t.preCostTime=A()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},i.stop=function(){this.destroy(),this.stream=new Uint8Array},i.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($(X)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},i.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 n=this.stream.subarray(t);return this.stream=new Uint8Array,n}var s="0 0 1"===this.stream.slice(0,3).join(" "),r="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||r){if(-1===t)t=i;else{if(e<=1){var o=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),o}e-=1}i+=3}}return!1},i.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},i.drawImage=function(e,t,i,n,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var r=e*t,o=e/2*(t/2),a=new Uint8Array(r+2*o);a.set(i,0),a.set(n,r),a.set(s,r+o),this.gl.renderFrame(i,n,s,e,t),a=null},i.checkDisplaySize=function(e,t){var i,n=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),r=+(this.options.height/t).toFixed(2),o=n?s:r,a=this.options.fixed,l=a?this.options.width:parseInt(e*o+""),u=a?this.options.height:parseInt(t*o+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/u>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,u]},i._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===Y){var n=i.data,s=n.ptsSec,r=n.strideY,o=n.height;n.width;var a=n.bufY,l=n.bufU,u=n.bufV,h=new N(s,r,o,a,l,u);e.cacheYuvBuf.appendCacheByCacheYuv(h),h=null}}},i.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new U(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new B({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},ie(t,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),t}(te),oe=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],ae={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(ae.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return ae.isBlank(e)||ae.isComment(e)},defaultMinDur:99999},le=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=f,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 n=function(t){return new Promise((function(i,n){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(){n(new Error("Network error."))},s.send()}))};n(e).then((function(s){if(t._retry=10,i._uriParse(e)){var r=i._m3u8Parse(s);if("number"==typeof r&&r>=0)var o=setTimeout((function(){i.fetchM3u8(e),clearTimeout(o)}),200*r)}return n=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),n=null,t._retry>=1)var r=setTimeout((function(){i.fetchM3u8(e),clearTimeout(r)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,n=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],n=t[1].split("/"),this._preURI=i+"://"):n=t[0].split("/");for(var s=0;sc&&(s=c);var d,f=n[o+=1],m=null;if(f.includes("http"))m=f;else{if("/"===f[0]){var v=this._preURI.split("//"),g=v[v.length-1].split("/");this._preURI=v[0]+"//"+g[0]}m=this._preURI+f}if(!this._slices.includes(m))this._slices.push(m),null==this||null==(d=this.onTransportStream)||d.call(this,m,c)}}}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=ae.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),ue=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=[],n=e,s=0;s>4==15){var r=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(r<=0)continue;var o=t.subarray(s,s+r),a=new Uint8Array(r);a.set(o,0),i.push({ptime:n,data:a}),n+=this.frameDurSec,s+=r}else s+=1;return i},e}(),he="M3U8",ce="TS",de="FETCH",pe=function(){function e(){}return e.init=function(i){e.collect=new t(i)},e.send=function(t,i){var n,s;null==(s=e.collect)||null==(n=s.send)||n.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function fe(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(n){var s,r,o,a;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",n),null==(r=t.event)||null==(s=r.emit)||s.call(r,ce,{data:n}),null==(a=t.event)||null==(o=a.emit)||o.call(a,de,{data:n,type:ce}),null==i||i.onDemuxedFailed(n,e),pe.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage($(Q,{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===d||this.mediaInfo.vCodec===c},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 J:var n,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(n=s.emit)||n.call(s,"mediaInfo",e.mediaInfo);break;case z:var r;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new ue(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(r=e.onDemuxed)||r.call(e)}}))},fe(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),ge=function(){function e(e,t,i,n){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=n}return e.prototype.setFrame=function(e,t,i,n){this.pts=e,this.isKey=t,this.data=i,this.video=n},e}(),ye=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 le(e),this.mpegTsDemux=new ve(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===p?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,n){t.logger.error("[M3u8] onDemuxedFailed: ",e,n),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($(q))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===ke.__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 n=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(n)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var r,o,a,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(o=t.event)||null==(r=o.emit)||r.call(o,he,{data:e}),null==(l=t.event)||null==(a=l.emit)||a.call(l,de,{data:e,type:he}),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 q:var n,s=i.data,r=s.type,o=s.pts,a=s.ptime,l=s.keyframe,u=s.data,c=s.layer;if(u=new Uint8Array(u),1===r&&e.mpegTsDemux.mediaInfo.aCodec===h&&(u=e.mpegTsDemux.aacDec.sliceAACFrames(a,u)),0===r){var d=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var n=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return n.set(t.vps,0),n.set(t.sps,t.vps.length),n.set(t.pps,t.vps.length+t.sps.length),n.set(t.sei,t.vps.length+t.sps.length+t.pps.length),n.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),n}(c),p=o,f=new ge(p,1===l,d,!0);e.vPreFramePTS=p,null==e||e.onSamples(e.onReadyOBJ,f)}else if(1===r){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var v=u,g=0;g0&&(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 index 97aedb7..b67e92b 100644 --- a/dist/index.umd.js +++ b/dist/index.umd.js @@ -1,6 +1,6 @@ /* * -* HlsPlayer.js v0.1.0-beta.2 +* HlsPlayer.js v0.1.0 * Copyright (c) 2024-8-1 Ezviz-OpenBiz * . * @@ -57,4 +57,4 @@ * 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-beta.2"},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-beta.2",Uc})); +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/package.json b/package.json index da66fca..d192257 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ezuikit/player-hls", - "version": "0.1.0-beta.2", + "version": "0.1.0", "description": "hls播放器", "main": "dist/index.js", "umd": "dist/index.umd.js",